aboutsummaryrefslogtreecommitdiffstats
path: root/adapters
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 /adapters
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>
Diffstat (limited to 'adapters')
-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
519 files changed, 34179 insertions, 37030 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);