From 7511bc24717091b316b70b95a827600567bc285e Mon Sep 17 00:00:00 2001 From: "waqas.ikram" Date: Fri, 1 May 2020 12:30:32 +0100 Subject: Refactor SOL003 Adapter to organize its modules Change-Id: I6025f6b1975ead19284edcea76607b62a3bcbc17 Issue-ID: SO-2771 Signed-off-by: waqas.ikram --- .../etsi-sol003-adapter-application/pom.xml | 2 +- .../sol003/adapter/VnfmAdapterApplication.java | 57 -- .../adapter/VnfmBasicHttpSecurityConfigurer.java | 63 -- .../so/adapters/etsisol003adapter/Application.java | 57 ++ ...siSol003AdapterBasicHttpSecurityConfigurer.java | 63 ++ .../adapter/lcm/LifeCycleManagementConstants.java | 33 - .../etsi/sol003/adapter/lcm/NvfmAdapterUtils.java | 64 -- .../AbstractServiceProviderConfiguration.java | 49 -- .../adapter/lcm/extclients/SdcPackageProvider.java | 195 ------ .../lcm/extclients/aai/AaiClientProvider.java | 34 -- .../adapter/lcm/extclients/aai/AaiHelper.java | 217 ------- .../lcm/extclients/aai/AaiPropertiesImpl.java | 68 --- .../lcm/extclients/aai/AaiServiceProvider.java | 148 ----- .../lcm/extclients/aai/AaiServiceProviderImpl.java | 158 ----- .../lcm/extclients/aai/OamIpAddressSource.java | 57 -- .../lcm/extclients/vim/model/AccessInfo.java | 107 ---- .../lcm/extclients/vim/model/InterfaceInfo.java | 74 --- .../lcm/extclients/vim/model/VimCredentials.java | 85 --- .../adapter/lcm/extclients/vnfm/VnfmHelper.java | 228 ------- .../lcm/extclients/vnfm/VnfmServiceProvider.java | 104 ---- .../vnfm/VnfmServiceProviderConfiguration.java | 154 ----- .../extclients/vnfm/VnfmServiceProviderImpl.java | 194 ------ .../lcm/extclients/vnfm/VnfmUrlProvider.java | 95 --- .../adapter/lcm/jobmanagement/JobManager.java | 174 ------ .../adapter/lcm/jobmanagement/VnfmOperation.java | 122 ---- .../adapter/lcm/lifecycle/LifecycleManager.java | 265 -------- .../notificationhandling/NotificationHandler.java | 276 --------- .../adapter/lcm/rest/Sol003GrantController.java | 114 ---- .../adapter/lcm/rest/Sol003LcnContoller.java | 131 ---- .../adapter/lcm/rest/VnfmAdapterController.java | 163 ----- .../lcm/rest/exceptions/JobNotFoundException.java | 38 -- .../rest/exceptions/TenantNotFoundException.java | 35 -- .../lcm/rest/exceptions/VnfNotFoundException.java | 38 -- .../lcm/rest/exceptions/VnfmNotFoundException.java | 38 -- .../exceptions/VnfmRequestFailureException.java | 38 -- .../lcm/LifeCycleManagementConstants.java | 33 + .../etsisol003adapter/lcm/NvfmAdapterUtils.java | 64 ++ .../AbstractServiceProviderConfiguration.java | 49 ++ .../lcm/extclients/SdcPackageProvider.java | 195 ++++++ .../lcm/extclients/aai/AaiClientProvider.java | 34 ++ .../lcm/extclients/aai/AaiHelper.java | 217 +++++++ .../lcm/extclients/aai/AaiPropertiesImpl.java | 68 +++ .../lcm/extclients/aai/AaiServiceProvider.java | 148 +++++ .../lcm/extclients/aai/AaiServiceProviderImpl.java | 158 +++++ .../lcm/extclients/aai/OamIpAddressSource.java | 57 ++ .../lcm/extclients/vim/model/AccessInfo.java | 107 ++++ .../lcm/extclients/vim/model/InterfaceInfo.java | 74 +++ .../lcm/extclients/vim/model/VimCredentials.java | 85 +++ .../lcm/extclients/vnfm/VnfmHelper.java | 228 +++++++ .../lcm/extclients/vnfm/VnfmServiceProvider.java | 104 ++++ .../vnfm/VnfmServiceProviderConfiguration.java | 154 +++++ .../extclients/vnfm/VnfmServiceProviderImpl.java | 194 ++++++ .../lcm/extclients/vnfm/VnfmUrlProvider.java | 95 +++ .../lcm/jobmanagement/JobManager.java | 174 ++++++ .../lcm/jobmanagement/VnfmOperation.java | 122 ++++ .../lcm/lifecycle/LifecycleManager.java | 265 ++++++++ .../notificationhandling/NotificationHandler.java | 276 +++++++++ .../lcm/rest/EtsiSol003AdapterController.java | 163 +++++ .../lcm/rest/Sol003GrantController.java | 114 ++++ .../lcm/rest/Sol003LcnContoller.java | 131 ++++ .../lcm/rest/exceptions/JobNotFoundException.java | 38 ++ .../rest/exceptions/TenantNotFoundException.java | 35 ++ .../lcm/rest/exceptions/VnfNotFoundException.java | 38 ++ .../lcm/rest/exceptions/VnfmNotFoundException.java | 38 ++ .../exceptions/VnfmRequestFailureException.java | 38 ++ .../services/org.onap.so.client.RestProperties | 2 +- .../sol003/adapter/lcm/rest/HealthCheckTest.java | 54 -- .../lcm/rest/Sol003GrantControllerTest.java | 252 -------- .../adapter/lcm/rest/Sol003LcnControllerTest.java | 413 ------------- .../sol003/adapter/lcm/rest/TestApplication.java | 38 -- .../lcm/rest/VnfmAdapterControllerTest.java | 561 ----------------- .../lcm/rest/EtsiSol003AdapterControllerTest.java | 561 +++++++++++++++++ .../lcm/rest/HealthCheckTest.java | 54 ++ .../lcm/rest/Sol003GrantControllerTest.java | 252 ++++++++ .../lcm/rest/Sol003LcnControllerTest.java | 413 +++++++++++++ .../lcm/rest/TestApplication.java | 38 ++ .../etsi-sol003-lcm/etsi-sol003-lcm-api/pom.xml | 16 +- .../src/main/resources/etsisol003adapter.yaml | 522 ++++++++++++++++ .../src/main/resources/vnfmadapter.yaml | 522 ---------------- .../etsi-sol003-lcm-ext-clients/pom.xml | 4 +- .../ConversionServiceConfiguration.java | 55 -- .../PackageManagementConstants.java | 39 -- .../sol003/AbstractPkgNotificationConverter.java | 63 -- .../sol003/PkgChangeNotificationConverter.java | 85 --- .../sol003/PkgOnboardingNotificationConverter.java | 76 --- .../etsicatalog/sol003/VnfPkgInfoConverter.java | 198 ------ .../PkgmSubscriptionRequestConverter.java | 198 ------ .../AbstractServiceProviderConfiguration.java | 56 -- ...tsiCatalogPackageManagementServiceProvider.java | 72 --- .../etsicatalog/EtsiCatalogServiceProvider.java | 32 - .../EtsiCatalogServiceProviderConfiguration.java | 187 ------ .../EtsiCatalogServiceProviderImpl.java | 281 --------- .../EtsiCatalogSubscriptionServiceProvider.java | 55 -- .../etsicatalog/EtsiCatalogUrlProvider.java | 113 ---- .../vnfm/VnfmHttpServiceProviderConfiguration.java | 49 -- .../EtsiSubscriptionNotificationController.java | 166 ----- .../rest/Sol003PackageManagementController.java | 176 ------ ...003PackageManagementSubscriptionController.java | 172 ------ .../AuthenticationTypeNotSupportedException.java | 44 -- .../rest/exceptions/ConversionFailedException.java | 44 -- .../EtsiCatalogManagerBadRequestException.java | 43 -- .../EtsiCatalogManagerRequestFailureException.java | 43 -- ...tionNotificationControllerExceptionHandler.java | 112 ---- .../exceptions/InternalServerErrorException.java | 43 -- .../NotificationTypeNotSupportedException.java | 44 -- ...ackageManagementControllerExceptionHandler.java | 94 --- .../exceptions/SubscriptionNotFoundException.java | 43 -- .../rest/exceptions/VnfPkgBadRequestException.java | 43 -- .../rest/exceptions/VnfPkgConflictException.java | 43 -- .../rest/exceptions/VnfPkgNotFoundException.java | 43 -- .../AbstractNotificationServiceProvider.java | 59 -- .../BasicAuthNotificationServiceProvider.java | 68 --- .../NotificationManager.java | 137 ----- .../NotificationServiceProvider.java | 51 -- .../NotificationServiceProviderFactory.java | 67 -- .../OAuthNotificationServiceProvider.java | 104 ---- .../subscriptionmanagement/OAuthTokenResponse.java | 56 -- .../SubscriptionManager.java | 209 ------- .../TlsNotificationServiceProvider.java | 57 -- .../cache/AbstractCacheServiceProvider.java | 47 -- .../cache/CacheManagerConfiguration.java | 50 -- .../cache/CacheNotFoundException.java | 37 -- .../PackageManagementCacheServiceProvider.java | 74 --- .../PackageManagementCacheServiceProviderImpl.java | 119 ---- .../pkgm/ConversionServiceConfiguration.java | 55 ++ .../pkgm/PackageManagementConstants.java | 39 ++ .../sol003/AbstractPkgNotificationConverter.java | 63 ++ .../sol003/PkgChangeNotificationConverter.java | 85 +++ .../sol003/PkgOnboardingNotificationConverter.java | 76 +++ .../etsicatalog/sol003/VnfPkgInfoConverter.java | 198 ++++++ .../PkgmSubscriptionRequestConverter.java | 198 ++++++ .../AbstractServiceProviderConfiguration.java | 56 ++ ...tsiCatalogPackageManagementServiceProvider.java | 72 +++ .../etsicatalog/EtsiCatalogServiceProvider.java | 32 + .../EtsiCatalogServiceProviderConfiguration.java | 187 ++++++ .../EtsiCatalogServiceProviderImpl.java | 281 +++++++++ .../EtsiCatalogSubscriptionServiceProvider.java | 55 ++ .../etsicatalog/EtsiCatalogUrlProvider.java | 113 ++++ .../vnfm/VnfmHttpServiceProviderConfiguration.java | 49 ++ .../EtsiSubscriptionNotificationController.java | 166 +++++ .../rest/Sol003PackageManagementController.java | 176 ++++++ ...003PackageManagementSubscriptionController.java | 172 ++++++ .../AuthenticationTypeNotSupportedException.java | 44 ++ .../rest/exceptions/ConversionFailedException.java | 44 ++ .../EtsiCatalogManagerBadRequestException.java | 43 ++ .../EtsiCatalogManagerRequestFailureException.java | 43 ++ ...tionNotificationControllerExceptionHandler.java | 112 ++++ .../exceptions/InternalServerErrorException.java | 43 ++ .../NotificationTypeNotSupportedException.java | 44 ++ ...ackageManagementControllerExceptionHandler.java | 94 +++ .../exceptions/SubscriptionNotFoundException.java | 43 ++ .../rest/exceptions/VnfPkgBadRequestException.java | 43 ++ .../rest/exceptions/VnfPkgConflictException.java | 43 ++ .../rest/exceptions/VnfPkgNotFoundException.java | 43 ++ .../AbstractNotificationServiceProvider.java | 59 ++ .../BasicAuthNotificationServiceProvider.java | 68 +++ .../NotificationManager.java | 137 +++++ .../NotificationServiceProvider.java | 51 ++ .../NotificationServiceProviderFactory.java | 67 ++ .../OAuthNotificationServiceProvider.java | 104 ++++ .../subscriptionmanagement/OAuthTokenResponse.java | 56 ++ .../SubscriptionManager.java | 209 +++++++ .../TlsNotificationServiceProvider.java | 57 ++ .../cache/AbstractCacheServiceProvider.java | 47 ++ .../cache/CacheManagerConfiguration.java | 50 ++ .../cache/CacheNotFoundException.java | 37 ++ .../PackageManagementCacheServiceProvider.java | 74 +++ .../PackageManagementCacheServiceProviderImpl.java | 119 ++++ ...EtsiSubscriptionNotificationControllerTest.java | 591 ------------------ .../Sol003PackageManagementControllerTest.java | 677 --------------------- ...ackageManagementSubscriptionControllerTest.java | 403 ------------ .../packagemanagement/rest/TestApplication.java | 38 -- ...EtsiSubscriptionNotificationControllerTest.java | 591 ++++++++++++++++++ .../Sol003PackageManagementControllerTest.java | 677 +++++++++++++++++++++ ...ackageManagementSubscriptionControllerTest.java | 403 ++++++++++++ .../pkgm/rest/TestApplication.java | 38 ++ .../etsi-sol003-package-management-api/pom.xml | 8 +- .../pom.xml | 8 +- 178 files changed, 11032 insertions(+), 11032 deletions(-) delete mode 100755 adapters/etsi-sol003-adapter/etsi-sol003-adapter-application/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/VnfmAdapterApplication.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-adapter-application/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/VnfmBasicHttpSecurityConfigurer.java create mode 100755 adapters/etsi-sol003-adapter/etsi-sol003-adapter-application/src/main/java/org/onap/so/adapters/etsisol003adapter/Application.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-adapter-application/src/main/java/org/onap/so/adapters/etsisol003adapter/EtsiSol003AdapterBasicHttpSecurityConfigurer.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/LifeCycleManagementConstants.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/NvfmAdapterUtils.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/AbstractServiceProviderConfiguration.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/SdcPackageProvider.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/aai/AaiClientProvider.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/aai/AaiHelper.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/aai/AaiPropertiesImpl.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/aai/AaiServiceProvider.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/aai/AaiServiceProviderImpl.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/aai/OamIpAddressSource.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/vim/model/AccessInfo.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/vim/model/InterfaceInfo.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/vim/model/VimCredentials.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/vnfm/VnfmHelper.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/vnfm/VnfmServiceProvider.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/vnfm/VnfmServiceProviderConfiguration.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/vnfm/VnfmServiceProviderImpl.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/vnfm/VnfmUrlProvider.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/jobmanagement/JobManager.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/jobmanagement/VnfmOperation.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/lifecycle/LifecycleManager.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/notificationhandling/NotificationHandler.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/rest/Sol003GrantController.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/rest/Sol003LcnContoller.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/rest/VnfmAdapterController.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/rest/exceptions/JobNotFoundException.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/rest/exceptions/TenantNotFoundException.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/rest/exceptions/VnfNotFoundException.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/rest/exceptions/VnfmNotFoundException.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/rest/exceptions/VnfmRequestFailureException.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/LifeCycleManagementConstants.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/NvfmAdapterUtils.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/AbstractServiceProviderConfiguration.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/SdcPackageProvider.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/aai/AaiClientProvider.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/aai/AaiHelper.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/aai/AaiPropertiesImpl.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/aai/AaiServiceProvider.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/aai/AaiServiceProviderImpl.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/aai/OamIpAddressSource.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/vim/model/AccessInfo.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/vim/model/InterfaceInfo.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/vim/model/VimCredentials.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/vnfm/VnfmHelper.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/vnfm/VnfmServiceProvider.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/vnfm/VnfmServiceProviderConfiguration.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/vnfm/VnfmServiceProviderImpl.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/vnfm/VnfmUrlProvider.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/jobmanagement/JobManager.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/jobmanagement/VnfmOperation.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/lifecycle/LifecycleManager.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/notificationhandling/NotificationHandler.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/EtsiSol003AdapterController.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/Sol003GrantController.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/Sol003LcnContoller.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/exceptions/JobNotFoundException.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/exceptions/TenantNotFoundException.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/exceptions/VnfNotFoundException.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/exceptions/VnfmNotFoundException.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/exceptions/VnfmRequestFailureException.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/test/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/rest/HealthCheckTest.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/test/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/rest/Sol003GrantControllerTest.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/test/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/rest/Sol003LcnControllerTest.java delete mode 100755 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/test/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/rest/TestApplication.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/test/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/rest/VnfmAdapterControllerTest.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/test/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/EtsiSol003AdapterControllerTest.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/test/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/HealthCheckTest.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/test/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/Sol003GrantControllerTest.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/test/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/Sol003LcnControllerTest.java create mode 100755 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/test/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/TestApplication.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-api/src/main/resources/etsisol003adapter.yaml delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-api/src/main/resources/vnfmadapter.yaml delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/ConversionServiceConfiguration.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/PackageManagementConstants.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/converters/etsicatalog/sol003/AbstractPkgNotificationConverter.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/converters/etsicatalog/sol003/PkgChangeNotificationConverter.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/converters/etsicatalog/sol003/PkgOnboardingNotificationConverter.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/converters/etsicatalog/sol003/VnfPkgInfoConverter.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/converters/sol003/etsicatalog/PkgmSubscriptionRequestConverter.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/extclients/AbstractServiceProviderConfiguration.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/extclients/etsicatalog/EtsiCatalogPackageManagementServiceProvider.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/extclients/etsicatalog/EtsiCatalogServiceProvider.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/extclients/etsicatalog/EtsiCatalogServiceProviderConfiguration.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/extclients/etsicatalog/EtsiCatalogServiceProviderImpl.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/extclients/etsicatalog/EtsiCatalogSubscriptionServiceProvider.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/extclients/etsicatalog/EtsiCatalogUrlProvider.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/extclients/vnfm/VnfmHttpServiceProviderConfiguration.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/EtsiSubscriptionNotificationController.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/Sol003PackageManagementController.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/Sol003PackageManagementSubscriptionController.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/exceptions/AuthenticationTypeNotSupportedException.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/exceptions/ConversionFailedException.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/exceptions/EtsiCatalogManagerBadRequestException.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/exceptions/EtsiCatalogManagerRequestFailureException.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/exceptions/EtsiSubscriptionNotificationControllerExceptionHandler.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/exceptions/InternalServerErrorException.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/exceptions/NotificationTypeNotSupportedException.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/exceptions/Sol003PackageManagementControllerExceptionHandler.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/exceptions/SubscriptionNotFoundException.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/exceptions/VnfPkgBadRequestException.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/exceptions/VnfPkgConflictException.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/exceptions/VnfPkgNotFoundException.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/subscriptionmanagement/AbstractNotificationServiceProvider.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/subscriptionmanagement/BasicAuthNotificationServiceProvider.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/subscriptionmanagement/NotificationManager.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/subscriptionmanagement/NotificationServiceProvider.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/subscriptionmanagement/NotificationServiceProviderFactory.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/subscriptionmanagement/OAuthNotificationServiceProvider.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/subscriptionmanagement/OAuthTokenResponse.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/subscriptionmanagement/SubscriptionManager.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/subscriptionmanagement/TlsNotificationServiceProvider.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/subscriptionmanagement/cache/AbstractCacheServiceProvider.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/subscriptionmanagement/cache/CacheManagerConfiguration.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/subscriptionmanagement/cache/CacheNotFoundException.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/subscriptionmanagement/cache/PackageManagementCacheServiceProvider.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/subscriptionmanagement/cache/PackageManagementCacheServiceProviderImpl.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/ConversionServiceConfiguration.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/PackageManagementConstants.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/converters/etsicatalog/sol003/AbstractPkgNotificationConverter.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/converters/etsicatalog/sol003/PkgChangeNotificationConverter.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/converters/etsicatalog/sol003/PkgOnboardingNotificationConverter.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/converters/etsicatalog/sol003/VnfPkgInfoConverter.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/converters/sol003/etsicatalog/PkgmSubscriptionRequestConverter.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/extclients/AbstractServiceProviderConfiguration.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/extclients/etsicatalog/EtsiCatalogPackageManagementServiceProvider.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/extclients/etsicatalog/EtsiCatalogServiceProvider.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/extclients/etsicatalog/EtsiCatalogServiceProviderConfiguration.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/extclients/etsicatalog/EtsiCatalogServiceProviderImpl.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/extclients/etsicatalog/EtsiCatalogSubscriptionServiceProvider.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/extclients/etsicatalog/EtsiCatalogUrlProvider.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/extclients/vnfm/VnfmHttpServiceProviderConfiguration.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/EtsiSubscriptionNotificationController.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/Sol003PackageManagementController.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/Sol003PackageManagementSubscriptionController.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/exceptions/AuthenticationTypeNotSupportedException.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/exceptions/ConversionFailedException.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/exceptions/EtsiCatalogManagerBadRequestException.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/exceptions/EtsiCatalogManagerRequestFailureException.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/exceptions/EtsiSubscriptionNotificationControllerExceptionHandler.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/exceptions/InternalServerErrorException.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/exceptions/NotificationTypeNotSupportedException.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/exceptions/Sol003PackageManagementControllerExceptionHandler.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/exceptions/SubscriptionNotFoundException.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/exceptions/VnfPkgBadRequestException.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/exceptions/VnfPkgConflictException.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/exceptions/VnfPkgNotFoundException.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/subscriptionmanagement/AbstractNotificationServiceProvider.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/subscriptionmanagement/BasicAuthNotificationServiceProvider.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/subscriptionmanagement/NotificationManager.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/subscriptionmanagement/NotificationServiceProvider.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/subscriptionmanagement/NotificationServiceProviderFactory.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/subscriptionmanagement/OAuthNotificationServiceProvider.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/subscriptionmanagement/OAuthTokenResponse.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/subscriptionmanagement/SubscriptionManager.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/subscriptionmanagement/TlsNotificationServiceProvider.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/subscriptionmanagement/cache/AbstractCacheServiceProvider.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/subscriptionmanagement/cache/CacheManagerConfiguration.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/subscriptionmanagement/cache/CacheNotFoundException.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/subscriptionmanagement/cache/PackageManagementCacheServiceProvider.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/subscriptionmanagement/cache/PackageManagementCacheServiceProviderImpl.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/test/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/EtsiSubscriptionNotificationControllerTest.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/test/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/Sol003PackageManagementControllerTest.java delete mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/test/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/Sol003PackageManagementSubscriptionControllerTest.java delete mode 100755 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/test/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/TestApplication.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/test/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/EtsiSubscriptionNotificationControllerTest.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/test/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/Sol003PackageManagementControllerTest.java create mode 100644 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/test/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/Sol003PackageManagementSubscriptionControllerTest.java create mode 100755 adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/test/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/TestApplication.java (limited to 'adapters/etsi-sol003-adapter') diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-adapter-application/pom.xml b/adapters/etsi-sol003-adapter/etsi-sol003-adapter-application/pom.xml index 85024edee0..df4e3086ea 100644 --- a/adapters/etsi-sol003-adapter/etsi-sol003-adapter-application/pom.xml +++ b/adapters/etsi-sol003-adapter/etsi-sol003-adapter-application/pom.xml @@ -15,7 +15,7 @@ org.springframework.boot spring-boot-maven-plugin - org.onap.so.adapters.etsi.sol003.adapter.VnfmAdapterApplication + org.onap.so.adapters.etsisol003adapter.Application diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-adapter-application/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/VnfmAdapterApplication.java b/adapters/etsi-sol003-adapter/etsi-sol003-adapter-application/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/VnfmAdapterApplication.java deleted file mode 100755 index 6fe76db5e4..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-adapter-application/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/VnfmAdapterApplication.java +++ /dev/null @@ -1,57 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter; - -import static org.slf4j.LoggerFactory.getLogger; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.rest.VnfmAdapterController; -import org.slf4j.Logger; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration; -import org.springframework.cache.annotation.EnableCaching; - -/** - * The spring boot application for the VNFM (Virtual Network Function Manager) Adapter. - *

- * 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 ETSI - * SOL003 v2.5.1 - */ -@EnableCaching -@SpringBootApplication(scanBasePackages = {"org.onap.so"}) -@EnableAutoConfiguration(exclude = {JacksonAutoConfiguration.class}) -public class VnfmAdapterApplication { - private static final Logger logger = getLogger(VnfmAdapterApplication.class); - - /** - * Entry point for the Spring boot application - * - * @param args arguments for the application - */ - public static void main(final String[] args) { - new SpringApplication(VnfmAdapterApplication.class).run(args); - logger.info("VnfmAdapterApplication started!"); - } - -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-adapter-application/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/VnfmBasicHttpSecurityConfigurer.java b/adapters/etsi-sol003-adapter/etsi-sol003-adapter-application/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/VnfmBasicHttpSecurityConfigurer.java deleted file mode 100644 index cfc4ef02d7..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-adapter-application/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/VnfmBasicHttpSecurityConfigurer.java +++ /dev/null @@ -1,63 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Modifications Copyright (c) 2019 Samsung - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF 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.etsi.sol003.adapter; - -import org.onap.so.adapters.etsi.sol003.adapter.common.CommonConstants; -import org.onap.so.security.HttpSecurityConfigurer; -import org.onap.so.security.SoUserCredentialConfiguration; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Primary; -import org.springframework.http.HttpMethod; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.stereotype.Component; -import org.springframework.util.StringUtils; - -/** - * @author Waqas Ikram (waqas.ikram@est.tech) - * @author Gareth Roper (gareth.roper@est.tech) - */ -@Primary -@Component -public class VnfmBasicHttpSecurityConfigurer implements HttpSecurityConfigurer { - - @Autowired - private SoUserCredentialConfiguration soUserCredentialConfiguration; - - @Value("${server.ssl.client-auth:none}") - private String clientAuth; - - @Override - public void configure(final HttpSecurity http) throws Exception { - if (("need").equalsIgnoreCase(clientAuth)) { - http.csrf().disable().authorizeRequests().anyRequest().permitAll(); - } else { - http.csrf().disable().authorizeRequests().antMatchers("/manage/health", "/manage/info").permitAll() - .antMatchers(HttpMethod.GET, CommonConstants.ETSI_SUBSCRIPTION_NOTIFICATION_BASE_URL).permitAll() - .antMatchers("/**") - .hasAnyRole(StringUtils.collectionToDelimitedString(soUserCredentialConfiguration.getRoles(), ",")) - .and().httpBasic(); - } - } -} - diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-adapter-application/src/main/java/org/onap/so/adapters/etsisol003adapter/Application.java b/adapters/etsi-sol003-adapter/etsi-sol003-adapter-application/src/main/java/org/onap/so/adapters/etsisol003adapter/Application.java new file mode 100755 index 0000000000..261d2244d7 --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-adapter-application/src/main/java/org/onap/so/adapters/etsisol003adapter/Application.java @@ -0,0 +1,57 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter; + +import static org.slf4j.LoggerFactory.getLogger; +import org.onap.so.adapters.etsisol003adapter.lcm.rest.EtsiSol003AdapterController; +import org.slf4j.Logger; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration; +import org.springframework.cache.annotation.EnableCaching; + +/** + * The spring boot application for the ETSI SOL003 Adapter. + *

+ * The ETSI SOL003 Adapter receives requests through its REST API {@link EtsiSol003AdapterController} which it adapts + * into ETSI SOL003 compliant LCM (Life Cycle Management) calls towards an ETSI compliant VNFM. + * + * @see ETSI + * SOL003 v2.5.1 + */ +@EnableCaching +@SpringBootApplication(scanBasePackages = {"org.onap.so"}) +@EnableAutoConfiguration(exclude = {JacksonAutoConfiguration.class}) +public class Application { + private static final Logger logger = getLogger(Application.class); + + /** + * Entry point for the Spring boot application + * + * @param args arguments for the application + */ + public static void main(final String[] args) { + new SpringApplication(Application.class).run(args); + logger.info("VnfmAdapterApplication started!"); + } + +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-adapter-application/src/main/java/org/onap/so/adapters/etsisol003adapter/EtsiSol003AdapterBasicHttpSecurityConfigurer.java b/adapters/etsi-sol003-adapter/etsi-sol003-adapter-application/src/main/java/org/onap/so/adapters/etsisol003adapter/EtsiSol003AdapterBasicHttpSecurityConfigurer.java new file mode 100644 index 0000000000..618b4f6116 --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-adapter-application/src/main/java/org/onap/so/adapters/etsisol003adapter/EtsiSol003AdapterBasicHttpSecurityConfigurer.java @@ -0,0 +1,63 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Modifications Copyright (c) 2019 Samsung + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF 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.etsisol003adapter; + +import org.onap.so.adapters.etsi.sol003.adapter.common.CommonConstants; +import org.onap.so.security.HttpSecurityConfigurer; +import org.onap.so.security.SoUserCredentialConfiguration; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Primary; +import org.springframework.http.HttpMethod; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; + +/** + * @author Waqas Ikram (waqas.ikram@est.tech) + * @author Gareth Roper (gareth.roper@est.tech) + */ +@Primary +@Component +public class EtsiSol003AdapterBasicHttpSecurityConfigurer implements HttpSecurityConfigurer { + + @Autowired + private SoUserCredentialConfiguration soUserCredentialConfiguration; + + @Value("${server.ssl.client-auth:none}") + private String clientAuth; + + @Override + public void configure(final HttpSecurity http) throws Exception { + if (("need").equalsIgnoreCase(clientAuth)) { + http.csrf().disable().authorizeRequests().anyRequest().permitAll(); + } else { + http.csrf().disable().authorizeRequests().antMatchers("/manage/health", "/manage/info").permitAll() + .antMatchers(HttpMethod.GET, CommonConstants.ETSI_SUBSCRIPTION_NOTIFICATION_BASE_URL).permitAll() + .antMatchers("/**") + .hasAnyRole(StringUtils.collectionToDelimitedString(soUserCredentialConfiguration.getRoles(), ",")) + .and().httpBasic(); + } + } +} + diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/LifeCycleManagementConstants.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/LifeCycleManagementConstants.java deleted file mode 100644 index ec82c17971..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/LifeCycleManagementConstants.java +++ /dev/null @@ -1,33 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.lcm; - -/** - * ETSI SOL003 Life Cycle Management Adapter constants - * - * @author Waqas Ikram (waqas.ikram@est.tech) - */ -public class LifeCycleManagementConstants { - - public static final String OPERATION_NOTIFICATION_ENDPOINT = "/lcn/VnfLcmOperationOccurrenceNotification"; - - private LifeCycleManagementConstants() {} -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/NvfmAdapterUtils.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/NvfmAdapterUtils.java deleted file mode 100644 index 2132108ca2..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/NvfmAdapterUtils.java +++ /dev/null @@ -1,64 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.lcm; - -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import org.slf4j.Logger; -import java.util.ArrayList; -import java.util.Collection; -import static org.slf4j.LoggerFactory.getLogger; - -public class NvfmAdapterUtils { - private static Logger logger = getLogger(NvfmAdapterUtils.class); - - public static JsonObject child(JsonObject parent, String name) { - return childElement(parent, name).getAsJsonObject(); - } - - public static JsonElement childElement(JsonObject parent, String name) { - JsonElement child = parent.get(name); - if (child == null) { - throw abortOperation("Missing child " + name); - } - return child; - } - - public static Collection children(JsonObject parent) { - ArrayList childElements = new ArrayList<>(); - for (String childKey : parent.keySet()) { - if (parent.get(childKey).isJsonObject()) { - childElements.add(parent.get(childKey).getAsJsonObject()); - } - } - return childElements; - } - - public static RuntimeException abortOperation(String msg, Exception e) { - logger.error(msg, e); - return new RuntimeException(msg, e); - } - - public static RuntimeException abortOperation(String msg) { - logger.error(msg); - return new RuntimeException(msg); - } -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/AbstractServiceProviderConfiguration.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/AbstractServiceProviderConfiguration.java deleted file mode 100644 index 84dd549d61..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/AbstractServiceProviderConfiguration.java +++ /dev/null @@ -1,49 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients; - -import java.util.Iterator; -import org.onap.etsi.sol003.adapter.lcm.v1.JSON; -import org.springframework.http.converter.HttpMessageConverter; -import org.springframework.http.converter.json.GsonHttpMessageConverter; -import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; -import org.springframework.web.client.RestTemplate; -import com.google.gson.Gson; - -/** - * A base class that can be extended by classes for configuring HttpRestServiceProvider classes. Provides common methods - * that will be useful to some such classes. - * - * @author gareth.roper@est.tech - */ -public abstract class AbstractServiceProviderConfiguration { - - public void setGsonMessageConverter(final RestTemplate restTemplate) { - final Iterator> iterator = restTemplate.getMessageConverters().iterator(); - while (iterator.hasNext()) { - if (iterator.next() instanceof MappingJackson2HttpMessageConverter) { - iterator.remove(); - } - } - final Gson gson = new JSON().getGson(); - restTemplate.getMessageConverters().add(new GsonHttpMessageConverter(gson)); - } -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/SdcPackageProvider.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/SdcPackageProvider.java deleted file mode 100644 index 907a15d3bc..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/SdcPackageProvider.java +++ /dev/null @@ -1,195 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * ================================================================================ - * Modifications Copyright (c) 2019 Samsung - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients; - -import static com.google.common.base.Splitter.on; -import static com.google.common.collect.Iterables.filter; -import static com.google.common.io.ByteStreams.toByteArray; -import static java.lang.String.format; -import static org.apache.http.HttpHeaders.ACCEPT; -import static org.apache.http.HttpHeaders.AUTHORIZATION; -import static org.onap.so.adapters.etsi.sol003.adapter.lcm.NvfmAdapterUtils.abortOperation; -import static org.onap.so.adapters.etsi.sol003.adapter.lcm.NvfmAdapterUtils.child; -import static org.onap.so.adapters.etsi.sol003.adapter.lcm.NvfmAdapterUtils.childElement; -import static org.onap.so.adapters.etsi.sol003.adapter.lcm.NvfmAdapterUtils.children; -import static org.slf4j.LoggerFactory.getLogger; -import static org.springframework.http.MediaType.APPLICATION_OCTET_STREAM_VALUE; -import com.google.common.io.ByteStreams; -import com.google.gson.Gson; -import com.google.gson.JsonObject; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.NoSuchElementException; -import java.util.Set; -import java.util.zip.ZipEntry; -import java.util.zip.ZipInputStream; -import javax.net.ssl.SSLContext; -import org.apache.commons.codec.binary.Base64; -import org.apache.http.HttpEntity; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.onap.so.utils.CryptoUtils; -import org.slf4j.Logger; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Component; -import org.yaml.snakeyaml.Yaml; - -@Component -public class SdcPackageProvider { - private static final String GET_PACKAGE_URL = "%s/sdc/v1/catalog/resources/%s/toscaModel"; - @Value("${sdc.toscametapath:TOSCA-Metadata/TOSCA.meta}") - private List toscaMetaPaths; - private static final String TOSCA_VNFD_KEY = "Entry-Definitions"; - private static Logger logger = getLogger(SdcPackageProvider.class); - - @Value("${sdc.username}") - private String sdcUsername; - @Value("${sdc.password}") - private String sdcPassword; - @Value("${sdc.key}") - private String sdcKey; - @Value("${sdc.endpoint}") - private String baseUrl; - - public String getVnfdId(final String csarId) { - return getVnfNodeProperty(csarId, "descriptor_id"); - } - - private String getVnfNodeProperty(final String csarId, final String propertyName) { - logger.debug("Getting " + propertyName + " from " + csarId); - final byte[] onapPackage = getPackage(csarId); - - try { - final String vnfdLocation = getVnfdLocation(new ByteArrayInputStream(onapPackage)); - final String onapVnfdContent = getFileInZip(new ByteArrayInputStream(onapPackage), vnfdLocation).toString(); - logger.debug("VNFD CONTENTS: " + onapVnfdContent); - final JsonObject root = new Gson().toJsonTree(new Yaml().load(onapVnfdContent)).getAsJsonObject(); - - final JsonObject topologyTemplates = child(root, "topology_template"); - final JsonObject nodeTemplates = child(topologyTemplates, "node_templates"); - for (final JsonObject child : children(nodeTemplates)) { - final String type = childElement(child, "type").getAsString(); - String propertyValue = null; - if ("tosca.nodes.nfv.VNF".equals(type)) { - final JsonObject properties = child(child, "properties"); - logger.debug("properties: " + properties.toString()); - - propertyValue = properties.get(propertyName).getAsJsonPrimitive().getAsString(); - } - if (propertyValue == null) { - propertyValue = getValueFromNodeTypeDefinition(root, type, propertyName); - } - return propertyValue; - } - - } catch (final Exception e) { - throw new IllegalArgumentException("Unable to extract " + propertyName + " from ONAP package", e); - } - throw new IllegalArgumentException("Unable to extract " + propertyName + " from ONAP package"); - } - - private String getValueFromNodeTypeDefinition(final JsonObject root, final String nodeTypeName, - final String propertyName) { - final JsonObject nodeTypes = child(root, "node_types"); - final JsonObject nodeType = child(nodeTypes, nodeTypeName); - - if ("tosca.nodes.nfv.VNF".equals(childElement(nodeType, "derived_from").getAsString())) { - final JsonObject properties = child(nodeType, "properties"); - logger.debug("properties: " + properties.toString()); - final JsonObject property = child(properties, propertyName); - logger.debug("property: " + property.toString()); - logger.debug("property default: " + childElement(property, "default").toString()); - return childElement(property, "default").getAsJsonPrimitive().getAsString(); - } - return null; - } - - private byte[] getPackage(final String csarId) { - final String SERVICE_NAME = "vnfm-adapter"; - try (CloseableHttpClient client = HttpClients.custom().setSSLContext(SSLContext.getDefault()).build()) { - final HttpGet httpget = new HttpGet(format(GET_PACKAGE_URL, baseUrl, csarId)); - httpget.setHeader(ACCEPT, APPLICATION_OCTET_STREAM_VALUE); - httpget.setHeader("X-ECOMP-InstanceID", SERVICE_NAME); - httpget.setHeader("X-FromAppId", SERVICE_NAME); - final String auth = sdcUsername + ":" + CryptoUtils.decrypt(sdcPassword, sdcKey); - final byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(StandardCharsets.ISO_8859_1)); - final String authHeader = "Basic " + new String(encodedAuth); - httpget.setHeader(AUTHORIZATION, authHeader); - logger.debug("Fetching from SDC: " + httpget); - final CloseableHttpResponse response = client.execute(httpget); - final HttpEntity entity = response.getEntity(); - final InputStream is = entity.getContent(); - return toByteArray(is); - } catch (final Exception e) { - throw abortOperation("Unable to download " + csarId + " package from SDC", e); - } - } - - private String getVnfdLocation(final InputStream stream) throws IOException { - final Iterator pathIterator = toscaMetaPaths.iterator(); - while (pathIterator.hasNext()) { - final String toscaMetadata = new String(getFileInZip(stream, pathIterator.next()).toByteArray()); - if (!toscaMetadata.isEmpty()) { - final String toscaVnfdLine = - filter(on("\n").split(toscaMetadata), line -> line.contains(TOSCA_VNFD_KEY)).iterator().next(); - return toscaVnfdLine.replace(TOSCA_VNFD_KEY + ":", "").trim(); - } - } - throw abortOperation("Unable to find valid Tosca Path"); - } - - private static ByteArrayOutputStream getFileInZip(final InputStream zip, final String path) throws IOException { - final ZipInputStream zipInputStream = new ZipInputStream(zip); - final ByteArrayOutputStream fileContent = getFileInZip(zipInputStream, path); - zipInputStream.close(); - return fileContent; - } - - private static ByteArrayOutputStream getFileInZip(final ZipInputStream zipInputStream, final String path) - throws IOException { - ZipEntry zipEntry; - final Set items = new HashSet<>(); - while ((zipEntry = zipInputStream.getNextEntry()) != null) { - items.add(zipEntry.getName()); - if (zipEntry.getName().matches(path)) { - final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - ByteStreams.copy(zipInputStream, byteArrayOutputStream); - return byteArrayOutputStream; - } - } - logger.error("Unable to find the {} in archive found: {}", path, items); - throw new NoSuchElementException("Unable to find the " + path + " in archive found: " + items); - } - - public String getFlavourId(final String csarId) { - return getVnfNodeProperty(csarId, "flavour_id"); - } -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/aai/AaiClientProvider.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/aai/AaiClientProvider.java deleted file mode 100644 index be1b68470a..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/aai/AaiClientProvider.java +++ /dev/null @@ -1,34 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.aai; - -import org.onap.aaiclient.client.aai.AAIResourcesClient; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -@Configuration -public class AaiClientProvider { - - @Bean - public AAIResourcesClient getAaiClient() { - return new AAIResourcesClient(); - } -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/aai/AaiHelper.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/aai/AaiHelper.java deleted file mode 100644 index 806193fc5f..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/aai/AaiHelper.java +++ /dev/null @@ -1,217 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.aai; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import org.onap.aai.domain.yang.EsrSystemInfo; -import org.onap.aai.domain.yang.EsrSystemInfoList; -import org.onap.aai.domain.yang.EsrVnfm; -import org.onap.aai.domain.yang.EsrVnfmList; -import org.onap.aai.domain.yang.GenericVnf; -import org.onap.aai.domain.yang.Relationship; -import org.onap.aai.domain.yang.RelationshipData; -import org.onap.aai.domain.yang.Vserver; -import org.onap.etsi.sol003.adapter.lcm.v1.model.Tenant; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.lcn.model.LcnVnfLcmOperationOccurrenceNotificationAffectedVnfcs; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.rest.exceptions.TenantNotFoundException; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.rest.exceptions.VnfmNotFoundException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -/** - * Provides helper methods for interactions with AAI. - */ -@Service -public class AaiHelper { - - private static final Logger logger = LoggerFactory.getLogger(AaiHelper.class); - private final AaiServiceProvider aaiServiceProvider; - private final Map mapOfVnfIdToOamIpAddressHolder = new HashMap<>(); - - @Autowired - public AaiHelper(final AaiServiceProvider aaiServiceProvider) { - this.aaiServiceProvider = aaiServiceProvider; - } - - /** - * Get the VNFM assigned for use for the given generic VNF. - * - * @param vnf the generic VNF - * @return the VNFM to use, or null if no VNFM has been assigned yet - */ - public EsrVnfm getAssignedVnfm(final GenericVnf vnf) { - final String vnfmId = getIdOfAssignedVnfm(vnf); - return vnfmId == null ? null : aaiServiceProvider.invokeGetVnfm(vnfmId); - } - - /** - * Get the ID of the VNFM assigned for use for the given generic VNF. - * - * @param vnf the generic VNF - * @return the ID of the VNFM to use, or null if no VNFM has been assigned yet - */ - public String getIdOfAssignedVnfm(final GenericVnf vnf) { - final Relationship relationship = getRelationship(vnf, "esr-vnfm"); - return getRelationshipData(relationship, "esr-vnfm.vnfm-id"); - } - - /** - * Get the tenant assigned for use for the given generic VNF. - * - * @param vnf the generic VNF - * @return the tenant to use, or null if no tenant has been assigned yet - */ - public Tenant getAssignedTenant(final GenericVnf vnf) { - final Relationship relationship = getRelationship(vnf, "tenant"); - final String cloudOwner = getRelationshipData(relationship, "cloud-region.cloud-owner"); - final String cloudRegion = getRelationshipData(relationship, "cloud-region.cloud-region-id"); - final String tenantId = getRelationshipData(relationship, "tenant.tenant-id"); - if (cloudOwner == null || cloudRegion == null || tenantId == null) { - throw new TenantNotFoundException("No matching Tenant found in AAI. VNFID: " + vnf.getVnfId()); - } else { - return new Tenant().cloudOwner(cloudOwner).regionName(cloudRegion).tenantId(tenantId); - } - } - - private Relationship getRelationship(final GenericVnf vnf, final String relationshipRelatedToValue) { - for (final Relationship relationship : vnf.getRelationshipList() == null ? Collections.emptyList() - : vnf.getRelationshipList().getRelationship()) { - if (relationship.getRelatedTo().equals(relationshipRelatedToValue)) { - return relationship; - } - } - return null; - } - - /** - * Get the value of the relationship data with the given key in the given relationship. - * - * @param relationship the relationship - * @param relationshipDataKey the key for the relationship data - * @return the value of the relationship data for the given key - */ - public String getRelationshipData(final Relationship relationship, final String relationshipDataKey) { - if (relationship != null) { - for (final RelationshipData relationshipData : relationship.getRelationshipData()) { - if (relationshipData.getRelationshipKey().equals(relationshipDataKey)) { - return relationshipData.getRelationshipValue(); - } - } - } - return null; - } - - /** - * Delete from the given VNF the relationship matching the given criteria. - * - * @param vnf the VNF - * @param relationshipRelatedToValue the related-to value for the relationship - * @param dataKey the relationship data key to match on - * @param dataValue the value the relationship data with the given key must match - * @return the deleted relationship or null if none found matching the given criteria - */ - public Relationship deleteRelationshipWithDataValue(final GenericVnf vnf, final String relationshipRelatedToValue, - final String dataKey, final String dataValue) { - final Iterator relationships = - vnf.getRelationshipList() == null ? Collections.emptyList().iterator() - : vnf.getRelationshipList().getRelationship().iterator(); - - while (relationships.hasNext()) { - final Relationship relationship = relationships.next(); - if (relationship.getRelatedTo().equals(relationshipRelatedToValue) - && dataValue.equals(getRelationshipData(relationship, dataKey))) { - relationships.remove(); - return relationship; - } - } - return null; - } - - /** - * 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 - */ - public EsrVnfm selectVnfm(final GenericVnf vnf) { - final EsrVnfmList vnfmsInEsr = aaiServiceProvider.invokeGetVnfms(); - - if (vnfmsInEsr == null) { - throw new VnfmNotFoundException("No VNFMs found in AAI ESR"); - } - logger.debug("VNFMs in ESR: " + vnfmsInEsr); - - for (final EsrVnfm vnfm : vnfmsInEsr.getEsrVnfm()) { - final EsrSystemInfoList systemInfolist = - aaiServiceProvider.invokeGetVnfmEsrSystemInfoList(vnfm.getVnfmId()); - vnfm.setEsrSystemInfoList(systemInfolist); - if (vnfmHasMatchingEsrSystemInfoType(vnfm, vnf.getNfType())) { - return vnfm; - } - } - throw new VnfmNotFoundException("No matching VNFM found in AAI ESR"); - } - - private boolean vnfmHasMatchingEsrSystemInfoType(final EsrVnfm vnfm, final String type) { - logger.debug("Checking VNFM ID: " + vnfm + ": " + vnfm.getVnfmId()); - - final EsrSystemInfoList systemInfolist = vnfm.getEsrSystemInfoList(); - if (systemInfolist != null) { - for (final EsrSystemInfo esrSystemInfo : systemInfolist.getEsrSystemInfo()) { - if (esrSystemInfo.getType().equals(type)) { - logger.debug("Matched VNFM ID: " + vnfm + ", based on type"); - return true; - } - } - } - return false; - } - - /** - * Create a vserver. - * - * @param vnfc the VNFC to base the vserver on - * @return the vserver - */ - public Vserver createVserver(final LcnVnfLcmOperationOccurrenceNotificationAffectedVnfcs vnfc) { - final Vserver vserver = new Vserver(); - vserver.setVserverId(vnfc.getComputeResource().getResourceId()); - vserver.setVserverName(vnfc.getId()); - vserver.setProvStatus("active"); - vserver.setVserverSelflink("Not available"); - return vserver; - } - - public void setOamIpAddressSource(final String vnfId, final OamIpAddressSource oamIpAddressSource) { - mapOfVnfIdToOamIpAddressHolder.put(vnfId, oamIpAddressSource); - } - - public OamIpAddressSource getOamIpAddressSource(final String vnfId) { - return mapOfVnfIdToOamIpAddressHolder.get(vnfId); - } - -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/aai/AaiPropertiesImpl.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/aai/AaiPropertiesImpl.java deleted file mode 100644 index 8a14e8f59e..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/aai/AaiPropertiesImpl.java +++ /dev/null @@ -1,68 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.aai; - -import org.onap.aaiclient.client.aai.AAIProperties; -import org.onap.aaiclient.client.aai.AAIVersion; -import org.onap.so.spring.SpringContextHelper; -import org.springframework.context.ApplicationContext; -import java.net.MalformedURLException; -import java.net.URL; - -public class AaiPropertiesImpl implements AAIProperties { - - private final String endpoint; - private final String encryptedBasicAuth; - private final String encrytptionKey; - - public AaiPropertiesImpl() { - - final ApplicationContext context = SpringContextHelper.getAppContext(); - this.endpoint = context.getEnvironment().getProperty("aai.endpoint"); - this.encryptedBasicAuth = context.getEnvironment().getProperty("aai.auth"); - this.encrytptionKey = context.getEnvironment().getProperty("mso.key"); - } - - @Override - public URL getEndpoint() throws MalformedURLException { - return new URL(endpoint); - } - - @Override - public String getSystemName() { - return "MSO"; - } - - @Override - public AAIVersion getDefaultVersion() { - return AAIVersion.LATEST; - } - - @Override - public String getAuth() { - return encryptedBasicAuth; - } - - @Override - public String getKey() { - return encrytptionKey; - } -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/aai/AaiServiceProvider.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/aai/AaiServiceProvider.java deleted file mode 100644 index 68a8405c0a..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/aai/AaiServiceProvider.java +++ /dev/null @@ -1,148 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.aai; - -import org.onap.aai.domain.yang.EsrSystemInfoList; -import org.onap.aai.domain.yang.EsrVnfm; -import org.onap.aai.domain.yang.EsrVnfmList; -import org.onap.aai.domain.yang.GenericVnf; -import org.onap.aai.domain.yang.GenericVnfs; -import org.onap.aai.domain.yang.Vserver; -import org.onap.etsi.sol003.adapter.lcm.v1.model.Tenant; - -/** - * Provides methods for invoking REST calls to AAI. - */ -public interface AaiServiceProvider { - - /** - * Invoke a get request for a generic VNF. - * - * @param vnfId the VNF id - * @return the generic VNF - */ - GenericVnf invokeGetGenericVnf(final String vnfId); - - /** - * Invoke a query for a generic VNF with the given selfLink - * - * @param selfLink the selfLink - * @return the matching generic vnfs - */ - GenericVnfs invokeQueryGenericVnf(final String selfLink); - - /** - * Invoke a GET request for the VNFMs. - * - * @return the VNFMs - */ - EsrVnfmList invokeGetVnfms(); - - /** - * Invoke a GET request for the esr system info list for a VNFM. - * - * @return the esr system info list for the VNFM - */ - EsrSystemInfoList invokeGetVnfmEsrSystemInfoList(final String vnfmId); - - /** - * Invoke a GET request for the a VNFM. - * - * @param vnfmId the ID of the VNFM - * @return the VNFM - */ - EsrVnfm invokeGetVnfm(final String vnfmId); - - /** - * Invoke a PATCH request for a generic vnf. - * - * @param vnf the generic vnf - * @return - */ - void invokePatchGenericVnf(GenericVnf vnf); - - /** - * Invoke a PUT request for a relationship from a generic vnf to a VNFM. - * - * @param vnf the generic vnf - * @param vnfmId the ID of the VNFM - * @return - */ - void invokePutGenericVnfToVnfmRelationship(GenericVnf vnf, final String vnfmId); - - - /** - * Invoke a PUT request for a vserver. - * - * @param cloudOwner the cloud owner - * @param cloudRegion the cloud region - * @param tenantId the ID of the tenant - * @param vserver the vserver - * @return - */ - void invokePutVserver(final String cloudOwner, final String cloudRegion, final String tenantId, - final Vserver vserver); - - /** - * Invoke a PUT request for a relationship from a vserver to a generic vnf. - * - * @param cloudOwner the cloud owner - * @param cloudRegion the cloud region the vserver is deployed on - * @param tenantId the ID of the tenant the vserver is deployed on - * @param vserver the vserver - * @param vnfId the ID of the generic vnf - * @return - */ - void invokePutVserverToVnfRelationship(final String cloudOwner, final String cloudRegion, final String tenantId, - final Vserver vserver, final String vnfId); - - /** - * Invoke a DELETE request for a vserver. - * - * @param cloudOwner the cloud owner - * @param cloudRegion the cloud region - * @param tenantId the ID of the tenant - * @param vserverId the ID of the vserver - * @return - */ - void invokeDeleteVserver(final String cloudOwner, final String cloudRegion, final String tenantId, - final String vserverId); - - /** - * Invoke a GET request for the a tenant. - * - * @param cloudOwner the cloud owner - * @param cloudRegion the cloud region - * @param tenantId the ID of the tenant - * @return the tenant - */ - Tenant invokeGetTenant(final String cloudOwner, final String cloudRegion, final String tenantId); - - /** - * Invoke a GET request for the esr system info list for a cloud region. - * - * @param cloudOwner the cloud owner - * @param cloudRegion the cloud region - * @return the esr system info list for the VNFM - */ - EsrSystemInfoList invokeGetCloudRegionEsrSystemInfoList(final String cloudOwner, final String cloudRegion); - -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/aai/AaiServiceProviderImpl.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/aai/AaiServiceProviderImpl.java deleted file mode 100644 index 5c7b0bec47..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/aai/AaiServiceProviderImpl.java +++ /dev/null @@ -1,158 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.aai; - -import org.onap.aai.domain.yang.EsrSystemInfoList; -import org.onap.aai.domain.yang.EsrVnfm; -import org.onap.aai.domain.yang.EsrVnfmList; -import org.onap.aai.domain.yang.GenericVnf; -import org.onap.aai.domain.yang.GenericVnfs; -import org.onap.aai.domain.yang.Vserver; -import org.onap.etsi.sol003.adapter.lcm.v1.model.Tenant; -import org.onap.aaiclient.client.aai.AAIObjectType; -import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory; -import org.onap.aaiclient.client.graphinventory.entities.uri.Depth; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -@Service -public class AaiServiceProviderImpl implements AaiServiceProvider { - - private static final Logger logger = LoggerFactory.getLogger(AaiServiceProviderImpl.class); - private final AaiClientProvider aaiClientProvider; - - @Autowired - public AaiServiceProviderImpl(final AaiClientProvider aaiClientProvider) { - this.aaiClientProvider = aaiClientProvider; - } - - @Override - public GenericVnf invokeGetGenericVnf(final String vnfId) { - return aaiClientProvider.getAaiClient() - .get(GenericVnf.class, AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId)) - .orElseGet(() -> { - logger.debug("No vnf found in AAI with ID: {}", vnfId); - return null; - }); - } - - @Override - public GenericVnfs invokeQueryGenericVnf(final String selfLink) { - return aaiClientProvider.getAaiClient() - .get(GenericVnfs.class, - AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNFS).queryParam("selflink", selfLink)) - .orElseGet(() -> { - logger.debug("No vnf found in AAI with selflink: {}", selfLink); - return null; - }); - } - - @Override - public EsrVnfmList invokeGetVnfms() { - return aaiClientProvider.getAaiClient() - .get(EsrVnfmList.class, AAIUriFactory.createResourceUri(AAIObjectType.VNFM_LIST)).orElseGet(() -> { - logger.debug("No VNFMs in AAI"); - return null; - }); - } - - @Override - public EsrVnfm invokeGetVnfm(final String vnfmId) { - return aaiClientProvider.getAaiClient() - .get(EsrVnfm.class, AAIUriFactory.createResourceUri(AAIObjectType.VNFM, vnfmId).depth(Depth.ONE)) - .orElseGet(() -> { - logger.debug("VNFM not found in AAI"); - return null; - }); - } - - @Override - public EsrSystemInfoList invokeGetVnfmEsrSystemInfoList(final String vnfmId) { - return aaiClientProvider.getAaiClient() - .get(EsrSystemInfoList.class, - AAIUriFactory.createResourceUri(AAIObjectType.VNFM_ESR_SYSTEM_INFO_LIST, vnfmId)) - .orElseGet(() -> { - logger.debug("VNFM ESR system info list not found in AAI"); - return null; - }); - } - - @Override - public void invokePatchGenericVnf(final GenericVnf vnf) { - aaiClientProvider.getAaiClient() - .update(AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnf.getVnfId()), vnf); - } - - @Override - public void invokePutGenericVnfToVnfmRelationship(final GenericVnf vnf, final String vnfmId) { - aaiClientProvider.getAaiClient().connect(AAIUriFactory.createResourceUri(AAIObjectType.VNFM, vnfmId), - AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnf.getVnfId())); - } - - @Override - public void invokePutVserver(final String cloudOwner, final String cloudRegion, final String tenant, - final Vserver vserver) { - aaiClientProvider.getAaiClient().create(AAIUriFactory.createResourceUri(AAIObjectType.VSERVER, cloudOwner, - cloudRegion, tenant, vserver.getVserverId()), vserver); - } - - @Override - public void invokePutVserverToVnfRelationship(final String cloudOwner, final String cloudRegion, - final String tenant, final Vserver vserver, final String vnfId) { - aaiClientProvider.getAaiClient() - .connect( - AAIUriFactory.createResourceUri(AAIObjectType.VSERVER, cloudOwner, cloudRegion, tenant, - vserver.getVserverId()), - AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId)); - } - - @Override - public void invokeDeleteVserver(final String cloudOwner, final String cloudRegion, final String tenant, - final String vserverId) { - aaiClientProvider.getAaiClient().delete( - AAIUriFactory.createResourceUri(AAIObjectType.VSERVER, cloudOwner, cloudRegion, tenant, vserverId)); - } - - @Override - public Tenant invokeGetTenant(final String cloudOwner, final String cloudRegion, final String tenantId) { - return aaiClientProvider.getAaiClient() - .get(Tenant.class, - AAIUriFactory.createResourceUri(AAIObjectType.TENANT, cloudOwner, cloudRegion, tenantId)) - .orElseGet(() -> { - logger.debug("Tenant not found in AAI"); - return null; - }); - } - - @Override - public EsrSystemInfoList invokeGetCloudRegionEsrSystemInfoList(final String cloudOwner, final String cloudRegion) { - return aaiClientProvider - .getAaiClient().get(EsrSystemInfoList.class, AAIUriFactory - .createResourceUri(AAIObjectType.CLOUD_ESR_SYSTEM_INFO_LIST, cloudOwner, cloudRegion)) - .orElseGet(() -> { - logger.debug("Cloud esr system info list not found in AAI"); - return null; - }); - } - -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/aai/OamIpAddressSource.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/aai/OamIpAddressSource.java deleted file mode 100644 index 25bacce705..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/aai/OamIpAddressSource.java +++ /dev/null @@ -1,57 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.aai; - -/** - * Represents the source of the value to use as the AAI OAM IP address of a VNF - */ -public class OamIpAddressSource { - - private final OamIpAddressType type; - private final String value; - - public OamIpAddressSource(final OamIpAddressType type, final String value) { - this.type = type; - this.value = value; - } - - public OamIpAddressType getType() { - return type; - } - - public String getValue() { - return value; - } - - public enum OamIpAddressType { - /** - * The value passed in {@link OamIpAddress#OamIpAddress(OamIpAddressType, String)} is to be used directly as the - * OAM IP address - */ - LITERAL, - /** - * The OAM IP address is to be retrieved from the vnfConfigurableProperties returned from the VNFM using the - * value passed in {@link OamIpAddress#OamIpAddress(OamIpAddressType, String)} as the name of a property - */ - CONFIGURABLE_PROPERTY - } - -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/vim/model/AccessInfo.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/vim/model/AccessInfo.java deleted file mode 100644 index b557acd892..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/vim/model/AccessInfo.java +++ /dev/null @@ -1,107 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vim.model; - -import java.util.Objects; - -public class AccessInfo { - - protected String projectId; - protected String projectName; - protected String domainName; - protected VimCredentials credentials; - - public String getProjectId() { - return projectId; - } - - public void setProjectId(final String value) { - projectId = value; - } - - public String getProjectName() { - return projectName; - } - - public void setProjectName(final String value) { - projectName = value; - } - - public String getDomainName() { - return domainName; - } - - public void setDomainName(final String value) { - domainName = value; - } - - public VimCredentials getCredentials() { - return credentials; - } - - public void setCredentials(final VimCredentials value) { - credentials = value; - } - - @Override - public boolean equals(final java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - final AccessInfo accessInfo = (AccessInfo) o; - return Objects.equals(this.projectId, accessInfo.projectId) - && Objects.equals(this.projectName, accessInfo.projectName) - && Objects.equals(this.domainName, accessInfo.domainName) - && Objects.equals(this.credentials, accessInfo.credentials); - } - - @Override - public int hashCode() { - return Objects.hash(projectId, projectName, domainName, credentials); - } - - @Override - public String toString() { - final StringBuilder sb = new StringBuilder(); - sb.append("class AccessInfo {\n"); - - sb.append(" projectId: ").append(toIndentedString(projectId)).append("\n"); - sb.append(" projectName: ").append(toIndentedString(projectName)).append("\n"); - sb.append(" domainName: ").append(toIndentedString(domainName)).append("\n"); - sb.append(" credentials: ").append(toIndentedString(credentials)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces (except the first line). - */ - private String toIndentedString(final java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/vim/model/InterfaceInfo.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/vim/model/InterfaceInfo.java deleted file mode 100644 index af11e35e80..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/vim/model/InterfaceInfo.java +++ /dev/null @@ -1,74 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vim.model; - -import java.util.Objects; - -public class InterfaceInfo { - - protected String identityEndPoint; - - public String getIdentityEndPoint() { - return identityEndPoint; - } - - public void setIdentityEndPoint(final String value) { - identityEndPoint = value; - } - - @Override - public boolean equals(final java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - final InterfaceInfo interfaceInfo = (InterfaceInfo) o; - return Objects.equals(this.identityEndPoint, interfaceInfo.identityEndPoint); - } - - @Override - public int hashCode() { - return Objects.hash(identityEndPoint); - } - - @Override - public String toString() { - final StringBuilder sb = new StringBuilder(); - sb.append("class InterfaceInfo {\n"); - - sb.append(" identityEndPoint: ").append(toIndentedString(identityEndPoint)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces (except the first line). - */ - private String toIndentedString(final java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/vim/model/VimCredentials.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/vim/model/VimCredentials.java deleted file mode 100644 index 6927d38757..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/vim/model/VimCredentials.java +++ /dev/null @@ -1,85 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vim.model; - -import java.util.Objects; - -public class VimCredentials { - - protected String username; - - protected String password; - - public String getUsername() { - return username; - } - - public void setUsername(final String value) { - username = value; - } - - public String getPassword() { - return password; - } - - public void setPassword(final String password) { - this.password = password; - } - - @Override - public boolean equals(final java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - final VimCredentials vimCredentials = (VimCredentials) o; - return Objects.equals(this.username, vimCredentials.username) - && Objects.equals(this.password, vimCredentials.password); - } - - @Override - public int hashCode() { - return Objects.hash(username, password); - } - - @Override - public String toString() { - final StringBuilder sb = new StringBuilder(); - sb.append("class AccessInfo {\n"); - - sb.append(" username: ").append(toIndentedString(username)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces (except the first line). - */ - private String toIndentedString(final java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/vnfm/VnfmHelper.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/vnfm/VnfmHelper.java deleted file mode 100644 index e2f673b6c4..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/vnfm/VnfmHelper.java +++ /dev/null @@ -1,228 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm; - -import java.security.GeneralSecurityException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.onap.aai.domain.yang.EsrSystemInfo; -import org.onap.etsi.sol003.adapter.lcm.v1.model.CreateVnfRequest; -import org.onap.etsi.sol003.adapter.lcm.v1.model.ExternalVirtualLink; -import org.onap.etsi.sol003.adapter.lcm.v1.model.Tenant; -import org.onap.so.adapters.etsi.sol003.adapter.common.VnfmAdapterUrlProvider; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.aai.AaiServiceProvider; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vim.model.AccessInfo; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vim.model.InterfaceInfo; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vim.model.VimCredentials; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.model.InstantiateVnfRequest; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.model.LccnSubscriptionRequest; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.model.SubscriptionsAuthentication; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.model.SubscriptionsAuthentication.AuthTypeEnum; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.model.SubscriptionsAuthenticationParamsBasic; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.model.SubscriptionsAuthenticationParamsOauth2ClientCredentials; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.model.SubscriptionsFilter; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.model.SubscriptionsFilter.NotificationTypesEnum; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.model.SubscriptionsFilterVnfInstanceSubscriptionFilter; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.model.VnfInstancesvnfInstanceIdinstantiateExtVirtualLinks; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.model.VnfInstancesvnfInstanceIdinstantiateVimConnectionInfo; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.grant.model.InlineResponse201VimConnections; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import com.google.common.reflect.TypeToken; -import com.google.gson.Gson; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; - -/** - * Provides helper methods for interactions with VNFM. - */ -@Service -public class VnfmHelper { - - private static final Logger logger = LoggerFactory.getLogger(VnfmHelper.class); - private static final String SEPARATOR = "_"; - private final AaiServiceProvider aaiServiceProvider; - private final VnfmAdapterUrlProvider vnfmAdapterUrlProvider; - - @Autowired - public VnfmHelper(final AaiServiceProvider aaiServiceProvider, - final VnfmAdapterUrlProvider vnfmAdapterUrlProvider) { - this.aaiServiceProvider = aaiServiceProvider; - this.vnfmAdapterUrlProvider = vnfmAdapterUrlProvider; - } - - /** - * Create an {@link InstantiateVnfRequest} to send in an instantiation request to a VNFM. - * - * @param tenant the tenant the request is to be fulfilled on - * @param createVnfRequest the request received by the VNFM adapter - */ - public InstantiateVnfRequest createInstantiateRequest(final Tenant tenant, final CreateVnfRequest createVnfRequest, - final String flavourId) { - final InstantiateVnfRequest instantiateVnfRequest = new InstantiateVnfRequest(); - instantiateVnfRequest.setFlavourId(flavourId); - instantiateVnfRequest.setVimConnectionInfo(getVimConnectionInfos(tenant)); - instantiateVnfRequest - .setAdditionalParams(getAdditionalParametersAsJsonObject(createVnfRequest.getAdditionalParams())); - instantiateVnfRequest.setExtVirtualLinks(getExternalVirtualLinks(createVnfRequest.getExternalVirtualLinks())); - createVnfRequest.getExternalVirtualLinks(); - return instantiateVnfRequest; - } - - private List getVimConnectionInfos(final Tenant tenant) { - final List connectionInfos = new ArrayList<>(); - connectionInfos.add(getVimConnectionInfo(tenant)); - return connectionInfos; - } - - private VnfInstancesvnfInstanceIdinstantiateVimConnectionInfo getVimConnectionInfo(final Tenant tenant) { - final EsrSystemInfo esrSystemInfo = - aaiServiceProvider.invokeGetCloudRegionEsrSystemInfoList(tenant.getCloudOwner(), tenant.getRegionName()) - .getEsrSystemInfo().iterator().next(); - - final VnfInstancesvnfInstanceIdinstantiateVimConnectionInfo vnfInstancesVimConnectionInfo = - new VnfInstancesvnfInstanceIdinstantiateVimConnectionInfo(); - final String vimId = createVimId(tenant.getCloudOwner(), tenant.getRegionName()); - vnfInstancesVimConnectionInfo.setId(vimId); - vnfInstancesVimConnectionInfo.setVimId(vimId); - vnfInstancesVimConnectionInfo.setVimType(esrSystemInfo.getType()); - vnfInstancesVimConnectionInfo.setInterfaceInfo(getInterfaceInfo(esrSystemInfo.getServiceUrl())); - vnfInstancesVimConnectionInfo.setAccessInfo(getAccessInfo(esrSystemInfo, tenant.getTenantId())); - return vnfInstancesVimConnectionInfo; - } - - private InterfaceInfo getInterfaceInfo(final String url) { - final InterfaceInfo interfaceInfo = new InterfaceInfo(); - interfaceInfo.setIdentityEndPoint(url); - return interfaceInfo; - } - - private AccessInfo getAccessInfo(final EsrSystemInfo esrSystemInfo, final String tenantId) { - final AccessInfo accessInfo = new AccessInfo(); - accessInfo.setProjectId(tenantId); - accessInfo.setDomainName(esrSystemInfo.getCloudDomain()); - - final VimCredentials vimCredentials = new VimCredentials(); - vimCredentials.setUsername(esrSystemInfo.getUserName()); - vimCredentials.setPassword(esrSystemInfo.getPassword()); - accessInfo.setCredentials(vimCredentials); - return accessInfo; - } - - private String createVimId(final String cloudOwner, final String cloudRegion) { - return cloudOwner + SEPARATOR + cloudRegion; - } - - private JsonObject getAdditionalParametersAsJsonObject(final Map additionalParameters) { - final JsonObject additionalParametersJsonObject = new JsonObject(); - if (additionalParameters != null) { - for (final Map.Entry item : new Gson().toJsonTree(additionalParameters) - .getAsJsonObject().entrySet()) { - additionalParametersJsonObject.add(item.getKey(), item.getValue()); - } - } else { - logger.warn("No additional parameters were specified for the operation"); - } - return additionalParametersJsonObject; - } - - private List getExternalVirtualLinks( - final List extVirtualLinks) { - if (extVirtualLinks != null) { - final String extVirtualLinksJsonObject = - new Gson().toJson(extVirtualLinks, new TypeToken>() {}.getType()); - return new Gson().fromJson(extVirtualLinksJsonObject, - new TypeToken>() {}.getType()); - } - return null; - } - - /** - * Create a {@link LccnSubscriptionRequest} to send in an notification subscription request to a VNFM. - * - * @param the ID of the VNF notifications are required for - * @return the request - * @throws GeneralSecurityException - */ - public LccnSubscriptionRequest createNotificationSubscriptionRequest(final String vnfId) - throws GeneralSecurityException { - final LccnSubscriptionRequest lccnSubscriptionRequest = new LccnSubscriptionRequest(); - lccnSubscriptionRequest.setAuthentication(getSubscriptionsAuthentication()); - lccnSubscriptionRequest.setCallbackUri(vnfmAdapterUrlProvider.getVnfLcmOperationOccurrenceNotificationUrl()); - final SubscriptionsFilter filter = new SubscriptionsFilter(); - filter.addNotificationTypesItem(NotificationTypesEnum.VNFLCMOPERATIONOCCURRENCENOTIFICATION); - final SubscriptionsFilterVnfInstanceSubscriptionFilter vnfInstanceSubscriptionFilter = - new SubscriptionsFilterVnfInstanceSubscriptionFilter(); - vnfInstanceSubscriptionFilter.addVnfInstanceIdsItem(vnfId); - filter.setVnfInstanceSubscriptionFilter(vnfInstanceSubscriptionFilter); - lccnSubscriptionRequest.setFilter(filter); - return lccnSubscriptionRequest; - } - - private SubscriptionsAuthentication getSubscriptionsAuthentication() throws GeneralSecurityException { - final SubscriptionsAuthentication authentication = new SubscriptionsAuthentication(); - - final ImmutablePair decrypedAuth = vnfmAdapterUrlProvider.getDecryptAuth(); - - final SubscriptionsAuthenticationParamsOauth2ClientCredentials oauthParams = - new SubscriptionsAuthenticationParamsOauth2ClientCredentials(); - oauthParams.setTokenEndpoint(vnfmAdapterUrlProvider.getOauthTokenUrl()); - oauthParams.clientId(decrypedAuth.getLeft()); - oauthParams.setClientPassword(decrypedAuth.getRight()); - authentication.addAuthTypeItem(AuthTypeEnum.OAUTH2_CLIENT_CREDENTIALS); - authentication.paramsOauth2ClientCredentials(oauthParams); - - final SubscriptionsAuthenticationParamsBasic basicAuthParams = new SubscriptionsAuthenticationParamsBasic(); - basicAuthParams.setUserName(decrypedAuth.getLeft()); - basicAuthParams.setPassword(decrypedAuth.getRight()); - authentication.addAuthTypeItem(AuthTypeEnum.BASIC); - authentication.paramsBasic(basicAuthParams); - - authentication.addAuthTypeItem(AuthTypeEnum.TLS_CERT); - return authentication; - } - - /** - * Get the VIM connections for a tenant - * - * @param tenant the tenant - * @return the VIM connections - */ - public InlineResponse201VimConnections getVimConnections(final Tenant tenant) { - final EsrSystemInfo esrSystemInfo = - aaiServiceProvider.invokeGetCloudRegionEsrSystemInfoList(tenant.getCloudOwner(), tenant.getRegionName()) - .getEsrSystemInfo().iterator().next(); - - final InlineResponse201VimConnections vimConnection = new InlineResponse201VimConnections(); - vimConnection.setId(createVimId(tenant.getCloudOwner(), tenant.getRegionName())); - vimConnection.setVimId(vimConnection.getId()); - vimConnection.setVimType(esrSystemInfo.getType()); - vimConnection.setInterfaceInfo(getInterfaceInfo(esrSystemInfo.getServiceUrl())); - vimConnection.setAccessInfo(getAccessInfo(esrSystemInfo, tenant.getTenantId())); - return vimConnection; - } - - -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/vnfm/VnfmServiceProvider.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/vnfm/VnfmServiceProvider.java deleted file mode 100644 index d4ce8c8484..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/vnfm/VnfmServiceProvider.java +++ /dev/null @@ -1,104 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm; - -import org.onap.aai.domain.yang.EsrVnfm; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.model.CreateVnfRequest; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.model.InlineResponse200; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.model.InlineResponse2001; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.model.InlineResponse201; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.model.InstantiateVnfRequest; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.model.LccnSubscriptionRequest; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.model.TerminateVnfRequest; -import com.google.common.base.Optional; - -/** - * Provides methods for invoking REST calls to a VNFM. - */ -public interface VnfmServiceProvider { - - /** - * Invoke a get request for a VNF. - * - * @param vnfm the VNFM in AAI - * @param vnfSelfLink the link to the VNF in the VNFM - * @return the VNF from the VNFM - */ - Optional getVnf(final EsrVnfm vnfm, final String vnfSelfLink); - - /** - * Invoke an instantiate request for a VNF. - * - * @param vnfm the VNFM in AAI - * @param vnfSelfLink the link to he VNF on the VNFM - * @param instantiateVnfRequest the instantiate request - * @return the operation ID of the instantiation operation - */ - String instantiateVnf(final EsrVnfm vnfm, final String vnfSelfLink, - final InstantiateVnfRequest instantiateVnfRequest); - - /** - * Invoke a notification subscription request to a VNFM. - * - * @param vnfm the VNFM in AAI - * @param subscriptionRequest - * @return the response to the subscription request - */ - InlineResponse2001 subscribeForNotifications(final EsrVnfm vnfm, final LccnSubscriptionRequest subscriptionRequest); - - /** - * Invoke a terminate request for a VNF. - * - * @param vnfm the VNFM in AAI - * @param vnfSelfLink the link to he VNF on the VNFM - * @param terminateVnfRequest the terminate request - * @return the operation ID of the termination operation - */ - String terminateVnf(final EsrVnfm vnfm, final String vnfSelfLink, final TerminateVnfRequest terminateVnfRequest); - - /** - * Invoke a delete request for a VNF. - * - * @param vnfm the VNFM in AAI - * @param vnfSelfLink the link to he VNF on the VNFM - * @return the operation ID of the instantiation operation - */ - void deleteVnf(final EsrVnfm vnfm, final String vnfSelfLink); - - /** - * Invoke a get request for a VNFM operation. - * - * @param vnfm the VNFM in AAI - * @param operationId the id of the operation on the VNFM - * @return the operation from the VNFM - */ - Optional getOperation(final EsrVnfm vnfm, final String operationId); - - /** - * Invoke a create request to a VNFM - * - * @param vnfm the VNFM in AAI - * @param createVnfRequest the parameters for creating a VNF - * @return the newly created VNF - */ - Optional createVnf(final EsrVnfm vnfm, final CreateVnfRequest createVnfRequest); - -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/vnfm/VnfmServiceProviderConfiguration.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/vnfm/VnfmServiceProviderConfiguration.java deleted file mode 100644 index 231d19a6aa..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/vnfm/VnfmServiceProviderConfiguration.java +++ /dev/null @@ -1,154 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm; - -import static org.onap.so.client.RestTemplateConfig.CONFIGURABLE_REST_TEMPLATE; -import java.io.IOException; -import java.security.KeyManagementException; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.UnrecoverableKeyException; -import java.security.cert.CertificateException; -import java.util.Map; -import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; -import javax.net.ssl.SSLContext; -import org.apache.commons.lang3.StringUtils; -import org.apache.http.client.HttpClient; -import org.apache.http.conn.ssl.SSLConnectionSocketFactory; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.ssl.SSLContextBuilder; -import org.onap.aai.domain.yang.EsrSystemInfo; -import org.onap.aai.domain.yang.EsrVnfm; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.AbstractServiceProviderConfiguration; -import org.onap.so.configuration.rest.BasicHttpHeadersProvider; -import org.onap.so.rest.service.HttpRestServiceProvider; -import org.onap.so.rest.service.HttpRestServiceProviderImpl; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.io.Resource; -import org.springframework.http.client.BufferingClientHttpRequestFactory; -import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; -import org.springframework.security.oauth2.client.OAuth2RestTemplate; -import org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsResourceDetails; -import org.springframework.web.client.RestTemplate; - -/** - * Configures the HttpRestServiceProvider for REST call to a VNFM. - */ -@Configuration -public class VnfmServiceProviderConfiguration extends AbstractServiceProviderConfiguration { - - private static final Logger logger = LoggerFactory.getLogger(VnfmServiceProviderConfiguration.class); - private Map mapOfVnfmIdToHttpRestServiceProvider = new ConcurrentHashMap<>(); - - @Value("${http.client.ssl.trust-store:#{null}}") - private Resource trustStore; - @Value("${http.client.ssl.trust-store-password:#{null}}") - private String trustStorePassword; - - @Value("${server.ssl.key-store:#{null}}") - private Resource keyStoreResource; - @Value("${server.ssl.key--store-password:#{null}}") - private String keyStorePassword; - - /** - * This property is only intended to be temporary until the AAI schema is updated to support setting the endpoint - */ - @Value("${vnfmadapter.temp.vnfm.oauth.endpoint:#{null}}") - private String oauthEndpoint; - - @Qualifier(CONFIGURABLE_REST_TEMPLATE) - @Autowired() - private RestTemplate defaultRestTemplate; - - public HttpRestServiceProvider getHttpRestServiceProvider(final EsrVnfm vnfm) { - if (!mapOfVnfmIdToHttpRestServiceProvider.containsKey(vnfm.getVnfmId())) { - mapOfVnfmIdToHttpRestServiceProvider.put(vnfm.getVnfmId(), createHttpRestServiceProvider(vnfm)); - } - return mapOfVnfmIdToHttpRestServiceProvider.get(vnfm.getVnfmId()); - } - - private HttpRestServiceProvider createHttpRestServiceProvider(final EsrVnfm vnfm) { - final RestTemplate restTemplate = createRestTemplate(vnfm); - setGsonMessageConverter(restTemplate); - if (trustStore != null) { - setTrustStore(restTemplate); - } - return new HttpRestServiceProviderImpl(restTemplate, new BasicHttpHeadersProvider().getHttpHeaders()); - } - - private RestTemplate createRestTemplate(final EsrVnfm vnfm) { - if (vnfm != null) { - for (final EsrSystemInfo esrSystemInfo : vnfm.getEsrSystemInfoList().getEsrSystemInfo()) { - if (!StringUtils.isEmpty(esrSystemInfo.getUserName()) - && !StringUtils.isEmpty(esrSystemInfo.getPassword())) { - return createOAuth2RestTemplate(esrSystemInfo); - } - } - } - return defaultRestTemplate; - } - - private OAuth2RestTemplate createOAuth2RestTemplate(final EsrSystemInfo esrSystemInfo) { - logger.debug("Getting OAuth2RestTemplate ..."); - final ClientCredentialsResourceDetails resourceDetails = new ClientCredentialsResourceDetails(); - resourceDetails.setId(UUID.randomUUID().toString()); - resourceDetails.setClientId(esrSystemInfo.getUserName()); - resourceDetails.setClientSecret(esrSystemInfo.getPassword()); - resourceDetails.setAccessTokenUri( - oauthEndpoint == null ? esrSystemInfo.getServiceUrl().replace("vnflcm/v1", "oauth/token") - : oauthEndpoint); - resourceDetails.setGrantType("client_credentials"); - return new OAuth2RestTemplate(resourceDetails); - } - - private void setTrustStore(final RestTemplate restTemplate) { - SSLContext sslContext; - try { - if (keyStoreResource != null) { - KeyStore keystore = KeyStore.getInstance("pkcs12"); - keystore.load(keyStoreResource.getInputStream(), keyStorePassword.toCharArray()); - sslContext = - new SSLContextBuilder().loadTrustMaterial(trustStore.getURL(), trustStorePassword.toCharArray()) - .loadKeyMaterial(keystore, keyStorePassword.toCharArray()).build(); - } else { - sslContext = new SSLContextBuilder() - .loadTrustMaterial(trustStore.getURL(), trustStorePassword.toCharArray()).build(); - } - logger.info("Setting truststore: {}", trustStore.getURL()); - final SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext); - final HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); - final HttpComponentsClientHttpRequestFactory factory = - new HttpComponentsClientHttpRequestFactory(httpClient); - restTemplate.setRequestFactory(new BufferingClientHttpRequestFactory(factory)); - } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException | CertificateException - | IOException | UnrecoverableKeyException exception) { - logger.error("Error reading truststore, TLS connection to VNFM will fail.", exception); - } - } - -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/vnfm/VnfmServiceProviderImpl.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/vnfm/VnfmServiceProviderImpl.java deleted file mode 100644 index 6adbde2eae..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/vnfm/VnfmServiceProviderImpl.java +++ /dev/null @@ -1,194 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm; - -import org.onap.aai.domain.yang.EsrVnfm; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.model.CreateVnfRequest; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.model.InlineResponse200; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.model.InlineResponse2001; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.model.InlineResponse201; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.model.InlineResponse201.InstantiationStateEnum; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.model.InstantiateVnfRequest; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.model.LccnSubscriptionRequest; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.model.TerminateVnfRequest; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.jobmanagement.JobManager; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.rest.exceptions.VnfmRequestFailureException; -import org.onap.so.rest.exceptions.RestProcessingException; -import org.onap.so.rest.service.HttpRestServiceProvider; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Service; -import com.google.common.base.Optional; - -@Service -public class VnfmServiceProviderImpl implements VnfmServiceProvider { - private static final Logger logger = LoggerFactory.getLogger(VnfmServiceProviderImpl.class); - - private final VnfmServiceProviderConfiguration vnfmServiceProviderConfiguration; - private final VnfmUrlProvider urlProvider; - - @Autowired - public VnfmServiceProviderImpl(final VnfmUrlProvider urlProvider, - VnfmServiceProviderConfiguration vnfmServiceProviderConfiguration) { - this.vnfmServiceProviderConfiguration = vnfmServiceProviderConfiguration; - this.urlProvider = urlProvider; - } - - @Override - public Optional getVnf(final EsrVnfm vnfm, final String vnfSelfLink) { - return getHttpServiceProvider(vnfm).get(vnfSelfLink, InlineResponse201.class); - } - - @Override - public String instantiateVnf(final EsrVnfm vnfm, final String vnfSelfLink, - final InstantiateVnfRequest instantiateVnfRequest) { - logger.debug("Sending instantiate request " + instantiateVnfRequest + " to : " + vnfSelfLink); - - ResponseEntity response = null; - try { - response = getHttpServiceProvider(vnfm).postHttpRequest(instantiateVnfRequest, vnfSelfLink + "/instantiate", - Void.class); - } catch (final Exception exception) { - final String errorMessage = - "Instantiate request to " + vnfSelfLink + " resulted in exception" + instantiateVnfRequest; - logger.error(errorMessage, exception); - throw new VnfmRequestFailureException(errorMessage, exception); - } - if (response.getStatusCode() != HttpStatus.ACCEPTED) { - final String errorMessage = "Instantiate request to " + vnfSelfLink + " returned status code: " - + response.getStatusCode() + ", request: " + instantiateVnfRequest; - logger.error(errorMessage); - throw new VnfmRequestFailureException(errorMessage); - } - final String locationHeader = response.getHeaders().get("Location").iterator().next(); - return locationHeader.substring(locationHeader.lastIndexOf("/") + 1); - } - - @Override - public InlineResponse2001 subscribeForNotifications(final EsrVnfm vnfm, - final LccnSubscriptionRequest subscriptionRequest) { - logger.info("Subscribing for notifications {}", subscriptionRequest); - final String url = urlProvider.getSubscriptionsUrl(vnfm.getVnfmId()); - ResponseEntity response = null; - try { - response = getHttpServiceProvider(vnfm).postHttpRequest(subscriptionRequest, url, InlineResponse2001.class); - logger.info("Subscribing for notifications response {}", response); - } catch (final Exception exception) { - final String errorMessage = - "Subscription to VNFM " + vnfm.getVnfmId() + " resulted in exception" + subscriptionRequest; - logger.error(errorMessage, exception); - throw new VnfmRequestFailureException(errorMessage, exception); - } - if (response.getStatusCode() != HttpStatus.CREATED) { - final String errorMessage = "Subscription to VNFM " + vnfm.getVnfmId() + " returned status code: " - + response.getStatusCode() + ", request: " + subscriptionRequest; - logger.error(errorMessage); - throw new VnfmRequestFailureException(errorMessage); - } - return response.getBody(); - } - - @Override - public String terminateVnf(final EsrVnfm vnfm, final String vnfSelfLink, - final TerminateVnfRequest terminateVnfRequest) { - logger.debug("Sending terminate request " + terminateVnfRequest + " to : " + vnfSelfLink); - - ResponseEntity response = null; - try { - response = getHttpServiceProvider(vnfm).postHttpRequest(terminateVnfRequest, vnfSelfLink + "/terminate", - Void.class); - } catch (final RestProcessingException restProcessingException) { - if (restProcessingException.getStatusCode() == HttpStatus.CONFLICT.value()) { - InlineResponse201 vnf = getVnf(vnfm, vnfSelfLink).get(); - if (vnf.getInstantiationState().equals(InstantiationStateEnum.NOT_INSTANTIATED)) { - return JobManager.ALREADY_COMPLETED_OPERATION_ID; - } else { - final String errorMessage = - "Terminate request to " + vnfSelfLink + " resulted in exception" + terminateVnfRequest; - logger.error(errorMessage, restProcessingException); - throw new VnfmRequestFailureException(errorMessage, restProcessingException); - } - } - } catch (final Exception exception) { - final String errorMessage = - "Terminate request to " + vnfSelfLink + " resulted in exception" + terminateVnfRequest; - logger.error(errorMessage, exception); - throw new VnfmRequestFailureException(errorMessage, exception); - } - checkIfResponseIsAcceptable(response, vnfSelfLink, terminateVnfRequest); - final String locationHeader = response.getHeaders().get("Location").iterator().next(); - return locationHeader.substring(locationHeader.lastIndexOf("/") + 1); - } - - @Override - public void deleteVnf(final EsrVnfm vnfm, final String vnfSelfLink) { - logger.debug("Sending delete request to : " + vnfSelfLink); - final ResponseEntity response = getHttpServiceProvider(vnfm).deleteHttpRequest(vnfSelfLink, Void.class); - if (response.getStatusCode() != HttpStatus.NO_CONTENT) { - throw new VnfmRequestFailureException( - "Delete request to " + vnfSelfLink + " return status code: " + response.getStatusCode()); - } - } - - @Override - public Optional getOperation(final EsrVnfm vnfm, final String operationId) { - final String url = urlProvider.getOperationUrl(vnfm.getVnfmId(), operationId); - return getHttpServiceProvider(vnfm).get(url, InlineResponse200.class); - } - - @Override - public Optional createVnf(final EsrVnfm vnfm, final CreateVnfRequest createVnfRequest) { - final String url = urlProvider.getCreationUrl(vnfm.getVnfmId()); - logger.debug("Sending create request {} to : {}", createVnfRequest, url); - try { - return getHttpServiceProvider(vnfm).post(createVnfRequest, url, InlineResponse201.class); - } catch (final Exception exception) { - final String errorMessage = - "Create request to vnfm:" + vnfm.getVnfmId() + " resulted in exception" + createVnfRequest; - logger.error(errorMessage, exception); - throw new VnfmRequestFailureException(errorMessage, exception); - } - } - - private void checkIfResponseIsAcceptable(ResponseEntity response, String vnfSelfLink, - TerminateVnfRequest terminateVnfRequest) { - if (response == null) { - final String errorMessage = - "Terminate request to " + vnfSelfLink + ", response is null, " + "request: " + terminateVnfRequest; - logger.error(errorMessage); - throw new VnfmRequestFailureException(errorMessage); - } - if (response.getStatusCode() != HttpStatus.ACCEPTED) { - final String errorMessage = "Terminate request to " + vnfSelfLink + ", returned status code: " - + response.getStatusCode() + ", request: " + terminateVnfRequest; - logger.error(errorMessage); - throw new VnfmRequestFailureException(errorMessage); - } - } - - private HttpRestServiceProvider getHttpServiceProvider(final EsrVnfm vnfm) { - return vnfmServiceProviderConfiguration.getHttpRestServiceProvider(vnfm); - } - -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/vnfm/VnfmUrlProvider.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/vnfm/VnfmUrlProvider.java deleted file mode 100644 index a88086ff00..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/extclients/vnfm/VnfmUrlProvider.java +++ /dev/null @@ -1,95 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm; - -import static org.slf4j.LoggerFactory.getLogger; -import java.net.URI; -import org.onap.aai.domain.yang.EsrSystemInfo; -import org.onap.aai.domain.yang.EsrSystemInfoList; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.aai.AaiServiceProvider; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.rest.exceptions.VnfmNotFoundException; -import org.slf4j.Logger; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.web.util.UriComponentsBuilder; - -/** - * Provides URLs for REST calls to a VNFM. - */ -@Service -public class VnfmUrlProvider { - - private static Logger logger = getLogger(VnfmUrlProvider.class); - private final AaiServiceProvider aaiServiceProvider; - - @Autowired - public VnfmUrlProvider(final AaiServiceProvider aaiServiceProvider) { - this.aaiServiceProvider = aaiServiceProvider; - } - - /** - * Get the URL for an operation on a VNFM. - * - * @param vnfmId The ID of the VNFM - * @return the URL of the operation - */ - public String getOperationUrl(final String vnfmId, final String operationId) { - final String url = UriComponentsBuilder.fromUri(getBaseUri(vnfmId)).pathSegment("vnf_lcm_op_occs") - .pathSegment(operationId).build().toString(); - logger.debug("getOperationUrl:" + url); - - return url; - } - - /** - * Get the URL for the subscriptions on a VNFM. - * - * @param vnfmId The ID of the VNFM - * @return the URL of the subscriptions - */ - public String getSubscriptionsUrl(final String vnfmId) { - final String url = - UriComponentsBuilder.fromUri(getBaseUri(vnfmId)).pathSegment("subscriptions").build().toString(); - logger.debug("getSubscriptionUrl:" + url); - - return url; - } - - public String getCreationUrl(final String vnfmId) { - final String url = - UriComponentsBuilder.fromUri(getBaseUri(vnfmId)).pathSegment("vnf_instances").build().toString(); - logger.debug("getCreationUrl:" + url); - - return url; - } - - private URI getBaseUri(final String vnfmId) { - final EsrSystemInfoList vnfmEsrSystemInfoList = aaiServiceProvider.invokeGetVnfmEsrSystemInfoList(vnfmId); - - if (vnfmEsrSystemInfoList != null) { - for (final EsrSystemInfo esrSystemInfo : vnfmEsrSystemInfoList.getEsrSystemInfo()) { - return UriComponentsBuilder.fromHttpUrl(esrSystemInfo.getServiceUrl()).build().toUri(); - } - } - - throw new VnfmNotFoundException("VNFM, or Service URL for VNFM, not found for VNFM " + vnfmId); - } -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/jobmanagement/JobManager.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/jobmanagement/JobManager.java deleted file mode 100644 index 84d1022424..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/jobmanagement/JobManager.java +++ /dev/null @@ -1,174 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.lcm.jobmanagement; - -import static org.slf4j.LoggerFactory.getLogger; -import java.util.Map; -import java.util.UUID; -import org.onap.etsi.sol003.adapter.lcm.v1.model.OperationEnum; -import org.onap.etsi.sol003.adapter.lcm.v1.model.OperationStateEnum; -import org.onap.etsi.sol003.adapter.lcm.v1.model.OperationStatusRetrievalStatusEnum; -import org.onap.etsi.sol003.adapter.lcm.v1.model.QueryJobResponse; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.aai.AaiServiceProvider; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.VnfmServiceProvider; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.model.InlineResponse200; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.rest.exceptions.JobNotFoundException; -import org.onap.so.rest.exceptions.HttpResouceNotFoundException; -import org.slf4j.Logger; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; -import com.google.common.base.Optional; -import com.google.common.collect.Maps; - -/** - * Manages jobs enabling the status of jobs to be queried. A job is associated with an operation on a VNFM. - */ -@Component -public class JobManager { - public static final String ALREADY_COMPLETED_OPERATION_ID = "alreadyCompleted"; - private static final String SEPARATOR = "_"; - private static Logger logger = getLogger(JobManager.class); - private final Map mapOfJobIdToVnfmOperation = Maps.newConcurrentMap(); - private final VnfmServiceProvider vnfmServiceProvider; - private final AaiServiceProvider aaiServiceProvider; - - @Autowired - JobManager(final VnfmServiceProvider vnfmServiceProvider, final AaiServiceProvider aaiServiceProvider) { - this.vnfmServiceProvider = vnfmServiceProvider; - this.aaiServiceProvider = aaiServiceProvider; - } - - /** - * Create a job associated with an operation on a VNFM. - * - * @param vnfmId the VNFM the operation relates to - * @param operationId the ID of the associated VNFM operation - * @param waitForNotificationForSuccess if set to true 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)} - */ - public String createJob(final String vnfmId, final String operationId, - final boolean waitForNotificationForSuccess) { - final String jobId = vnfmId + SEPARATOR + UUID.randomUUID().toString(); - final VnfmOperation vnfmOperation = new VnfmOperation(vnfmId, operationId, waitForNotificationForSuccess); - mapOfJobIdToVnfmOperation.put(jobId, vnfmOperation); - return jobId; - } - - /** - * 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 null of no operation is associated with the given - * job ID - */ - public QueryJobResponse getVnfmOperation(final String jobId) { - final VnfmOperation vnfmOperation = mapOfJobIdToVnfmOperation.get(jobId); - final QueryJobResponse response = new QueryJobResponse(); - - if (vnfmOperation == null) { - throw new JobNotFoundException("No job found with ID: " + jobId); - } - - if (vnfmOperation.getOperationId().equals(ALREADY_COMPLETED_OPERATION_ID)) { - response.setOperationStatusRetrievalStatus(OperationStatusRetrievalStatusEnum.STATUS_FOUND); - return response.operationState(OperationStateEnum.COMPLETED); - } - - if (vnfmOperation.isVnfDeleted()) { - response.setOperationStatusRetrievalStatus(OperationStatusRetrievalStatusEnum.STATUS_FOUND); - return response.operationState(getOperationState(vnfmOperation, null)); - } - - try { - final Optional operationOptional = vnfmServiceProvider.getOperation( - aaiServiceProvider.invokeGetVnfm(vnfmOperation.getVnfmId()), vnfmOperation.getOperationId()); - - if (!operationOptional.isPresent()) { - return response.operationStatusRetrievalStatus(OperationStatusRetrievalStatusEnum.OPERATION_NOT_FOUND); - } - final InlineResponse200 operation = operationOptional.get(); - - logger.debug("Job Id: {} operationId: {} operation details: {} ", jobId, operation.getId(), operation); - - if (operation.getOperationState() == null) { - return response.operationStatusRetrievalStatus(OperationStatusRetrievalStatusEnum.WAITING_FOR_STATUS); - } - - response.setOperationStatusRetrievalStatus(OperationStatusRetrievalStatusEnum.STATUS_FOUND); - response.setId(operation.getId()); - response.setOperation(OperationEnum.fromValue(operation.getOperation().getValue())); - response.setOperationState(getOperationState(vnfmOperation, operation)); - response.setStartTime(operation.getStartTime()); - response.setStateEnteredTime(operation.getStateEnteredTime()); - response.setVnfInstanceId(operation.getVnfInstanceId()); - - return response; - } catch (final HttpResouceNotFoundException exception) { - logger.error("Exception encountered trying to get operation status for operation id " - + vnfmOperation.getOperationId(), exception); - return response.operationStatusRetrievalStatus(OperationStatusRetrievalStatusEnum.WAITING_FOR_STATUS); - } - } - - private OperationStateEnum getOperationState(final VnfmOperation vnfmOperation, - final InlineResponse200 operationResponse) { - switch (vnfmOperation.getNotificationStatus()) { - case NOTIFICATION_PROCESSING_PENDING: - return org.onap.etsi.sol003.adapter.lcm.v1.model.OperationStateEnum.PROCESSING; - case NOTIFICATION_PROCEESING_SUCCESSFUL: - return org.onap.etsi.sol003.adapter.lcm.v1.model.OperationStateEnum.COMPLETED; - case NOTIFICATION_PROCESSING_FAILED: - return org.onap.etsi.sol003.adapter.lcm.v1.model.OperationStateEnum.FAILED; - default: - if (operationResponse == null || operationResponse.getOperationState() == null) - return null; - return OperationStateEnum.fromValue(operationResponse.getOperationState().getValue()); - } - } - - public void notificationProcessedForOperation(final String operationId, - final boolean notificationProcessingWasSuccessful) { - logger.debug("Notification processed for operation ID {} success?: {}", operationId, - notificationProcessingWasSuccessful); - final java.util.Optional relatedOperation = mapOfJobIdToVnfmOperation.values().stream() - .filter(operation -> operation.getOperationId().equals(operationId)).findFirst(); - if (relatedOperation.isPresent()) { - relatedOperation.get().setNotificationProcessed(notificationProcessingWasSuccessful); - } else { - logger.debug("No operation found for operation ID {} ", operationId); - - } - } - - public void vnfDeleted(final String operationId) { - logger.debug("VNF deleyed for operation ID {}", operationId); - final java.util.Optional relatedOperation = mapOfJobIdToVnfmOperation.values().stream() - .filter(operation -> operation.getOperationId().equals(operationId)).findFirst(); - if (relatedOperation.isPresent()) { - relatedOperation.get().setVnfDeleted(); - } else { - logger.debug("No operation found for operation ID {} ", operationId); - } - } - -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/jobmanagement/VnfmOperation.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/jobmanagement/VnfmOperation.java deleted file mode 100644 index f28eeb9ebc..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/jobmanagement/VnfmOperation.java +++ /dev/null @@ -1,122 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.lcm.jobmanagement; - -/** - * Represents an operation on a VNFM. - */ -public class VnfmOperation { - - private final String vnfmId; - private final String operationId; - private NotificationStatus notificationStatus; - private boolean vnfDeleted; - - public VnfmOperation(final String vnfmId, final String operationId, final boolean waitForNotificationForSuccess) { - this.vnfmId = vnfmId; - this.operationId = operationId; - this.notificationStatus = waitForNotificationForSuccess ? NotificationStatus.NOTIFICATION_PROCESSING_PENDING - : NotificationStatus.NOTIFICATION_PROCESSING_NOT_REQUIRED; - } - - /** - * Get the ID of the operation on the VNFM. - * - * @return the ID of the operation on the VNFM - */ - public String getOperationId() { - return operationId; - } - - /** - * Get the ID of the VNFM the operation is carried out by. - * - * @return the ID of the VNFM - */ - public String getVnfmId() { - return vnfmId; - } - - /** - * Set the required notification has been processed for the operation. - * - * @param notificationProcessingWasSuccessful true if the notification processing was successful, - * false otherwise - */ - public void setNotificationProcessed(final boolean notificationProcessingWasSuccessful) { - this.notificationStatus = - notificationProcessingWasSuccessful ? NotificationStatus.NOTIFICATION_PROCEESING_SUCCESSFUL - : NotificationStatus.NOTIFICATION_PROCESSING_FAILED; - } - - /** - * Get the notification status for the operation. - * - * @return the notification status - */ - public NotificationStatus getNotificationStatus() { - return notificationStatus; - } - - /** - * Set the VNF has been deleted from the VNFM. - */ - public void setVnfDeleted() { - this.vnfDeleted = true; - } - - /** - * Check if the VNF has been deleted from the VNFM - * - * @return true of the VNF has been deleted from the VNFM, false otherwise - */ - public boolean isVnfDeleted() { - return vnfDeleted; - } - - - public enum NotificationStatus { - /** - * No notification handling is required to determine the status of the operation - */ - NOTIFICATION_PROCESSING_NOT_REQUIRED, - /** - * A notification must be processed before the notification can be considered to be completed - */ - NOTIFICATION_PROCESSING_PENDING, - /** - * A notification has been successfully handled for the operation - */ - NOTIFICATION_PROCEESING_SUCCESSFUL, - /** - * An error occurred processing a notification for the operation - */ - NOTIFICATION_PROCESSING_FAILED; - } - - @Override - public String toString() { - return "VnfmOperation [vnfmId=" + vnfmId + ", operationId=" + operationId + ", notificationStatus=" - + notificationStatus + "]"; - } - - -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/lifecycle/LifecycleManager.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/lifecycle/LifecycleManager.java deleted file mode 100644 index 74c6571c3d..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/lifecycle/LifecycleManager.java +++ /dev/null @@ -1,265 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.lcm.lifecycle; - -import java.util.Map; -import org.onap.aai.domain.yang.EsrVnfm; -import org.onap.aai.domain.yang.GenericVnf; -import org.onap.aai.domain.yang.Relationship; -import org.onap.etsi.sol003.adapter.lcm.v1.model.CreateVnfRequest; -import org.onap.etsi.sol003.adapter.lcm.v1.model.CreateVnfResponse; -import org.onap.etsi.sol003.adapter.lcm.v1.model.DeleteVnfResponse; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.SdcPackageProvider; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.aai.AaiHelper; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.aai.AaiServiceProvider; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.aai.OamIpAddressSource; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.aai.OamIpAddressSource.OamIpAddressType; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.VnfmHelper; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.VnfmServiceProvider; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.model.InlineResponse201; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.model.InstantiateVnfRequest; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.model.LccnSubscriptionRequest; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.model.TerminateVnfRequest; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.model.TerminateVnfRequest.TerminationTypeEnum; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.jobmanagement.JobManager; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.rest.exceptions.VnfNotFoundException; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.rest.exceptions.VnfmNotFoundException; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.rest.exceptions.VnfmRequestFailureException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; -import com.google.common.base.Optional; - -/** - * Manages lifecycle operations towards the VNFMs. - */ -@Component -public class LifecycleManager { - private static final Logger logger = LoggerFactory.getLogger(LifecycleManager.class); - private final AaiServiceProvider aaiServiceProvider; - private final VnfmServiceProvider vnfmServiceProvider; - private final AaiHelper aaiHelper; - private final VnfmHelper vnfmHelper; - private final JobManager jobManager; - private final SdcPackageProvider packageProvider; - - @Autowired - LifecycleManager(final AaiServiceProvider aaiServiceProvider, final AaiHelper aaiHelper, - final VnfmHelper vnfmHelper, final VnfmServiceProvider vnfmServiceProvider, final JobManager jobManager, - final SdcPackageProvider packageProvider) { - this.aaiServiceProvider = aaiServiceProvider; - this.vnfmServiceProvider = vnfmServiceProvider; - this.aaiHelper = aaiHelper; - this.vnfmHelper = vnfmHelper; - this.jobManager = jobManager; - this.packageProvider = packageProvider; - } - - /** - * Create a VNF on a VNFM. - * - * @param vnfIdInAai the ID of the VNF in AAI - * @param request the create request - * @return the response to the request - */ - public CreateVnfResponse createVnf(final String vnfIdInAai, final CreateVnfRequest request) { - GenericVnf genericVnf = getGenericVnfFromAai(vnfIdInAai); - EsrVnfm vnfm = aaiHelper.getAssignedVnfm(genericVnf); - checkIfVnfAlreadyExistsInVnfm(vnfm, genericVnf); - - if (vnfm == null) { - vnfm = aaiHelper.selectVnfm(genericVnf); - aaiServiceProvider.invokePutGenericVnfToVnfmRelationship(genericVnf, vnfm.getVnfmId()); - } - final InlineResponse201 vnfmResponse = sendCreateRequestToVnfm(request, genericVnf, vnfIdInAai, vnfm); - - logger.info("Create response: {}", vnfmResponse); - - genericVnf.setSelflink(getSelfLink(vnfmResponse, vnfm)); - - GenericVnf genericVnfPatch = new GenericVnf(); - genericVnfPatch.setVnfId(genericVnf.getVnfId()); - genericVnfPatch.setSelflink(genericVnf.getSelflink()); - aaiServiceProvider.invokePatchGenericVnf(genericVnfPatch); - - final String vnfIdInVnfm = vnfmResponse.getId(); - - final OamIpAddressSource oamIpAddressSource = extractOamIpAddressSource(request); - aaiHelper.setOamIpAddressSource(vnfIdInVnfm, oamIpAddressSource); - - createNotificationSubscription(vnfm, vnfIdInVnfm); - final String operationId = sendInstantiateRequestToVnfm(vnfm, genericVnf, request); - - final String jobId = jobManager.createJob(vnfm.getVnfmId(), operationId, false); - final CreateVnfResponse response = new CreateVnfResponse(); - response.setJobId(jobId); - return response; - } - - private String getSelfLink(final InlineResponse201 vnfmResponse, final EsrVnfm vnfm) { - if (vnfmResponse.getLinks() != null && vnfmResponse.getLinks().getSelf() != null - && vnfmResponse.getLinks().getSelf().getHref() != null) { - return vnfmResponse.getLinks().getSelf().getHref(); - } - return vnfm.getEsrSystemInfoList().getEsrSystemInfo().iterator().next().getServiceUrl() + "/vnf_instances/" - + vnfmResponse.getId(); - } - - private OamIpAddressSource extractOamIpAddressSource(final CreateVnfRequest request) { - final Map additionalParams = request.getAdditionalParams(); - try { - final String sourceType = additionalParams.remove("oamIpAddressSourceType"); - final String sourceValue = additionalParams.remove("oamIpAddressSourceValue"); - final OamIpAddressType oamIpAddressType = OamIpAddressType.valueOf(sourceType.toUpperCase()); - return new OamIpAddressSource(oamIpAddressType, sourceValue); - } catch (final NullPointerException | IllegalArgumentException exception) { - logger.debug("Additional Params not set for OAM IP address source", exception); - return null; - } - } - - private void checkIfVnfAlreadyExistsInVnfm(final EsrVnfm vnfm, final GenericVnf genericVnf) { - if (genericVnf.getSelflink() != null && !genericVnf.getSelflink().isEmpty() && vnfm != null) { - Optional response = Optional.absent(); - try { - response = vnfmServiceProvider.getVnf(vnfm, genericVnf.getSelflink()); - } catch (final Exception exception) { - logger.debug("Ignoring invalid self link in generic vnf", exception); - } - if (response.isPresent()) { - throw new IllegalArgumentException("VNF " + genericVnf.getVnfId() - + " is already defined on the VNFM, self link: " + genericVnf.getSelflink()); - } - } - } - - private InlineResponse201 sendCreateRequestToVnfm(final CreateVnfRequest aaiRequest, final GenericVnf genericVnf, - final String vnfIdInAai, final EsrVnfm vnfm) { - logger.debug("Sending a create request to SVNFM " + aaiRequest); - final org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.model.CreateVnfRequest vnfmRequest = - new org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.model.CreateVnfRequest(); - - final String vnfdId = packageProvider.getVnfdId(genericVnf.getModelVersionId()); - vnfmRequest.setVnfdId(vnfdId); - vnfmRequest.setVnfInstanceName(aaiRequest.getName().replaceAll(" ", "_")); - vnfmRequest.setVnfInstanceDescription(vnfIdInAai); - - final Optional optionalResponse = vnfmServiceProvider.createVnf(vnfm, vnfmRequest); - - try { - return optionalResponse.get(); - } catch (final Exception exception) { - final String errorMessage = "Unable to return response from VNFM"; - logger.error(errorMessage, exception); - throw new VnfmRequestFailureException(errorMessage, exception); - } - } - - private void createNotificationSubscription(final EsrVnfm vnfm, final String vnfId) { - try { - final LccnSubscriptionRequest subscriptionRequest = vnfmHelper.createNotificationSubscriptionRequest(vnfId); - vnfmServiceProvider.subscribeForNotifications(vnfm, subscriptionRequest); - } catch (final Exception exception) { - logger.warn("Subscription for notifications to VNFM: " + vnfm.getVnfmId() + " for VNF " + vnfId - + " failed. AAI will not be updated unless the VNFM is configured by other means to send notifications relating to this VNF", - exception); - } - } - - private String sendInstantiateRequestToVnfm(final EsrVnfm vnfm, final GenericVnf genericVnf, - final CreateVnfRequest createVnfRequest) { - - final InstantiateVnfRequest instantiateVnfRequest = - vnfmHelper.createInstantiateRequest(createVnfRequest.getTenant(), createVnfRequest, - packageProvider.getFlavourId(genericVnf.getModelVersionId())); - final String jobId = vnfmServiceProvider.instantiateVnf(vnfm, genericVnf.getSelflink(), instantiateVnfRequest); - - logger.info("Instantiate VNF request successfully sent to " + genericVnf.getSelflink()); - return jobId; - } - - /** - * Delete a VNF on a VNFM. - * - * @param vnfIdInAai the ID of the VNF in AAI - * @return the response to the request - */ - public DeleteVnfResponse deleteVnf(final String vnfIdInAai) { - final GenericVnf genericVnf = getGenericVnfFromAai(vnfIdInAai); - final EsrVnfm vnfm = getAssignedVnfm(genericVnf); - - final String operationId = sendTerminateRequestToVnfm(vnfm, genericVnf); - - if (operationId.equals(JobManager.ALREADY_COMPLETED_OPERATION_ID)) { - sendDeleteRequestToVnfm(genericVnf); - } - final String jobId = jobManager.createJob(vnfm.getVnfmId(), operationId, true); - - return new DeleteVnfResponse().jobId(jobId); - } - - private String sendTerminateRequestToVnfm(final EsrVnfm vnfm, final GenericVnf genericVnf) { - final TerminateVnfRequest terminateVnfRequest = new TerminateVnfRequest(); - terminateVnfRequest.setTerminationType(TerminationTypeEnum.FORCEFUL); - return vnfmServiceProvider.terminateVnf(vnfm, genericVnf.getSelflink(), terminateVnfRequest); - } - - private GenericVnf getGenericVnfFromAai(final String vnfIdInAai) { - final GenericVnf genericVnf = aaiServiceProvider.invokeGetGenericVnf(vnfIdInAai); - if (genericVnf == null) { - throw new VnfNotFoundException("VNF not found in AAI: " + vnfIdInAai); - } - logger.debug("Retrieved generic VNF from AAI: " + genericVnf); - return genericVnf; - } - - private EsrVnfm getAssignedVnfm(final GenericVnf genericVnf) { - final EsrVnfm vnfm = aaiHelper.getAssignedVnfm(genericVnf); - if (vnfm == null) { - throw new VnfmNotFoundException("No VNFM found in AAI for VNF " + genericVnf.getVnfId()); - } - return vnfm; - } - - private void sendDeleteRequestToVnfm(final GenericVnf genericVnf) { - - vnfmServiceProvider.deleteVnf(aaiHelper.getAssignedVnfm(genericVnf), genericVnf.getSelflink()); - - final GenericVnf genericVnfPatch = new GenericVnf(); - genericVnfPatch.setVnfId(genericVnf.getVnfId()); - genericVnfPatch.setOrchestrationStatus("Assigned"); - genericVnfPatch.setSelflink(""); - aaiServiceProvider.invokePatchGenericVnf(genericVnfPatch); - - for (final Relationship relationship : genericVnf.getRelationshipList().getRelationship()) { - if (relationship.getRelatedTo().equals("vserver")) { - aaiServiceProvider.invokeDeleteVserver( - aaiHelper.getRelationshipData(relationship, "cloud-region.cloud-owner"), - aaiHelper.getRelationshipData(relationship, "cloud-region.cloud-region-id"), - aaiHelper.getRelationshipData(relationship, "tenant.tenant-id"), - aaiHelper.getRelationshipData(relationship, "vserver.vserver-id")); - } - } - - - } -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/notificationhandling/NotificationHandler.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/notificationhandling/NotificationHandler.java deleted file mode 100644 index 43a8c352ff..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/notificationhandling/NotificationHandler.java +++ /dev/null @@ -1,276 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.lcm.notificationhandling; - -import static org.slf4j.LoggerFactory.getLogger; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.json.JSONException; -import org.json.JSONObject; -import org.onap.aai.domain.yang.GenericVnf; -import org.onap.aai.domain.yang.Relationship; -import org.onap.aai.domain.yang.Vserver; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.aai.AaiHelper; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.aai.AaiServiceProvider; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.aai.OamIpAddressSource; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.aai.OamIpAddressSource.OamIpAddressType; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.VnfmServiceProvider; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.model.InlineResponse201; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.model.InlineResponse201VimConnectionInfo; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.jobmanagement.JobManager; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.lcn.model.LcnVnfLcmOperationOccurrenceNotificationAffectedVnfcs; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.lcn.model.LcnVnfLcmOperationOccurrenceNotificationAffectedVnfcs.ChangeTypeEnum; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.lcn.model.VnfLcmOperationOccurrenceNotification; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.lcn.model.VnfLcmOperationOccurrenceNotification.OperationStateEnum; -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. - */ -public class NotificationHandler implements Runnable { - private static Logger logger = getLogger(NotificationHandler.class); - private final VnfLcmOperationOccurrenceNotification vnfLcmOperationOccurrenceNotification; - private final AaiHelper aaiHelper; - private final AaiServiceProvider aaiServiceProvider; - private final VnfmServiceProvider vnfmServiceProvider; - private final JobManager jobManager; - private final InlineResponse201 vnfInstance; - - public NotificationHandler(final VnfLcmOperationOccurrenceNotification vnfLcmOperationOccurrenceNotification, - final AaiHelper aaiHelper, final AaiServiceProvider aaiServiceProvider, - final VnfmServiceProvider vnfmServiceProvider, final JobManager jobManager, - final InlineResponse201 vnfInstance) { - this.vnfLcmOperationOccurrenceNotification = vnfLcmOperationOccurrenceNotification; - this.aaiHelper = aaiHelper; - this.aaiServiceProvider = aaiServiceProvider; - this.vnfmServiceProvider = vnfmServiceProvider; - this.jobManager = jobManager; - this.vnfInstance = vnfInstance; - } - - @Override - public void run() { - try { - if (vnfLcmOperationOccurrenceNotification.getOperationState().equals(OperationStateEnum.COMPLETED)) { - switch (vnfLcmOperationOccurrenceNotification.getOperation()) { - case INSTANTIATE: - handleVnfInstantiate(); - break; - case TERMINATE: - handleVnfTerminate(); - break; - default: - } - } - } catch (final Exception exception) { - logger.error("Error encountered handling notification, AAI may not be updated correctly " - + vnfLcmOperationOccurrenceNotification, exception); - } - } - - private void handleVnfInstantiate() { - if (vnfLcmOperationOccurrenceNotification.getOperationState().equals(OperationStateEnum.COMPLETED)) { - handleVnfInstantiateCompleted(); - } - } - - private void handleVnfInstantiateCompleted() { - final GenericVnf genericVnf = aaiServiceProvider - .invokeQueryGenericVnf(vnfInstance.getLinks().getSelf().getHref()).getGenericVnf().get(0); - - final GenericVnf genericVnfPatch = new GenericVnf(); - genericVnfPatch.setVnfId(genericVnf.getVnfId()); - setOamIpAddress(genericVnfPatch, vnfInstance); - genericVnfPatch.setOrchestrationStatus("Created"); - aaiServiceProvider.invokePatchGenericVnf(genericVnfPatch); - - addVservers(vnfLcmOperationOccurrenceNotification, genericVnf.getVnfId(), vnfInstance.getVimConnectionInfo()); - - logger.debug("Finished handling notification for vnfm: " + vnfInstance.getId()); - } - - private void setOamIpAddress(final GenericVnf genericVnf, final InlineResponse201 vnfInstance) { - final OamIpAddressSource oamIpAddressSource = aaiHelper.getOamIpAddressSource(vnfInstance.getId()); - if (oamIpAddressSource == null) { - logger.warn("No source indicated for OAM IP address, no value will be set in AAI"); - return; - } - if (oamIpAddressSource.getType().equals(OamIpAddressType.LITERAL)) { - genericVnf.setIpv4OamAddress(oamIpAddressSource.getValue()); - } else { - try { - logger.debug("ConfigurableProperties: " + vnfInstance.getVnfConfigurableProperties()); - if (vnfInstance.getVnfConfigurableProperties() == null) { - logger.warn("No ConfigurableProperties, cannot set OAM IP Address"); - } - final JSONObject properties = new JSONObject((Map) vnfInstance.getVnfConfigurableProperties()); - genericVnf.setIpv4OamAddress(properties.get(oamIpAddressSource.getValue()).toString()); - } catch (final JSONException jsonException) { - logger.error("Error getting vnfIpAddress", jsonException); - } - } - } - - private void handleVnfTerminate() { - switch (vnfLcmOperationOccurrenceNotification.getOperationState()) { - case COMPLETED: - handleVnfTerminateCompleted(); - break; - case FAILED: - case ROLLING_BACK: - handleVnfTerminateFailed(); - break; - default: - } - } - - private void handleVnfTerminateFailed() { - try { - final GenericVnf genericVnf = aaiServiceProvider - .invokeQueryGenericVnf(vnfInstance.getLinks().getSelf().getHref()).getGenericVnf().get(0); - deleteVserversFromAai(vnfLcmOperationOccurrenceNotification, genericVnf); - } finally { - jobManager.notificationProcessedForOperation(vnfLcmOperationOccurrenceNotification.getVnfLcmOpOccId(), - false); - } - } - - private void handleVnfTerminateCompleted() { - GenericVnf genericVnf = null; - boolean vServersDeletedFromAai = false; - boolean identifierDeletedFromVnfm = false; - boolean genericVnfUpdated = false; - try { - genericVnf = aaiServiceProvider.invokeQueryGenericVnf(vnfInstance.getLinks().getSelf().getHref()) - .getGenericVnf().get(0); - vServersDeletedFromAai = deleteVserversFromAai(vnfLcmOperationOccurrenceNotification, genericVnf); - identifierDeletedFromVnfm = deleteVnfIdentifierOnVnfm(genericVnf); - genericVnfUpdated = patchVnfInAai(genericVnf.getVnfId(), "Assigned", identifierDeletedFromVnfm ? "" : null); - } finally { - jobManager.notificationProcessedForOperation(vnfLcmOperationOccurrenceNotification.getVnfLcmOpOccId(), - vServersDeletedFromAai && identifierDeletedFromVnfm && genericVnfUpdated); - jobManager.vnfDeleted(vnfLcmOperationOccurrenceNotification.getVnfLcmOpOccId()); - } - } - - private void addVservers(final VnfLcmOperationOccurrenceNotification notification, final String vnfId, - final List vnfInstancesVimConnectionInfo) { - final Map vimConnectionIdToVimConnectionInfo = new HashMap<>(); - for (final InlineResponse201VimConnectionInfo vimConnectionInfo : vnfInstancesVimConnectionInfo) { - vimConnectionIdToVimConnectionInfo.put(vimConnectionInfo.getId(), vimConnectionInfo); - } - - for (final LcnVnfLcmOperationOccurrenceNotificationAffectedVnfcs vnfc : notification.getAffectedVnfcs()) { - final InlineResponse201VimConnectionInfo vimConnectionInfo = - getVimConnectionInfo(vimConnectionIdToVimConnectionInfo, vnfc); - if (ChangeTypeEnum.ADDED.equals(vnfc.getChangeType())) { - final Vserver vserver = aaiHelper.createVserver(vnfc); - aaiServiceProvider.invokePutVserver(getCloudOwner(vimConnectionInfo), getCloudRegion(vimConnectionInfo), - getTenant(vimConnectionInfo), vserver); - - aaiServiceProvider.invokePutVserverToVnfRelationship(getCloudOwner(vimConnectionInfo), - getCloudRegion(vimConnectionInfo), getTenant(vimConnectionInfo), vserver, vnfId); - } - } - } - - private boolean deleteVserversFromAai(final VnfLcmOperationOccurrenceNotification notification, - final GenericVnf vnf) { - try { - for (final LcnVnfLcmOperationOccurrenceNotificationAffectedVnfcs vnfc : notification.getAffectedVnfcs()) { - if (ChangeTypeEnum.REMOVED.equals(vnfc.getChangeType())) { - - final Relationship relationshipToVserver = aaiHelper.deleteRelationshipWithDataValue(vnf, "vserver", - "vserver.vserver-id", vnfc.getComputeResource().getResourceId()); - - aaiServiceProvider.invokeDeleteVserver( - aaiHelper.getRelationshipData(relationshipToVserver, "cloud-region.cloud-owner"), - aaiHelper.getRelationshipData(relationshipToVserver, "cloud-region.cloud-region-id"), - aaiHelper.getRelationshipData(relationshipToVserver, "tenant.tenant-id"), - vnfc.getComputeResource().getResourceId()); - } - } - return true; - } catch (final Exception exception) { - logger.error( - "Error encountered deleting vservers based on received notification, AAI may not be updated correctly " - + vnfLcmOperationOccurrenceNotification, - exception); - return false; - } - } - - private boolean deleteVnfIdentifierOnVnfm(GenericVnf genericVnf) { - try { - vnfmServiceProvider.deleteVnf(aaiHelper.getAssignedVnfm(genericVnf), genericVnf.getSelflink()); - return true; - } catch (Exception exception) { - logger.error("Exception deleting the identifier " + genericVnf.getSelflink() - + " from the VNFM. The VNF has been terminated successfully but the identifier will remain on the VNFM.", - exception); - return false; - } - } - - private boolean patchVnfInAai(final String vnfId, final String orchestrationStatus, final String selfLink) { - try { - final GenericVnf genericVnfPatch = new GenericVnf(); - genericVnfPatch.setVnfId(vnfId); - genericVnfPatch.setOrchestrationStatus(orchestrationStatus); - if (selfLink != null) { - genericVnfPatch.setSelflink(selfLink); - } - aaiServiceProvider.invokePatchGenericVnf(genericVnfPatch); - return true; - } catch (final Exception exception) { - logger.error( - "Error encountered setting orchestration status and/or self link based on received notification, AAI may not be updated correctly " - + vnfLcmOperationOccurrenceNotification, - exception); - return false; - } - } - - private InlineResponse201VimConnectionInfo getVimConnectionInfo( - final Map vimConnectionIdToVimConnectionInfo, - final LcnVnfLcmOperationOccurrenceNotificationAffectedVnfcs vnfc) { - final String vimConnectionId = vnfc.getComputeResource().getVimConnectionId(); - return vimConnectionIdToVimConnectionInfo.get(vimConnectionId); - } - - private String getCloudOwner(final InlineResponse201VimConnectionInfo vimConnectionInfo) { - final String vimId = vimConnectionInfo.getVimId(); - return vimId.substring(0, vimId.indexOf("_")); - } - - private String getCloudRegion(final InlineResponse201VimConnectionInfo vimConnectionInfo) { - final String vimId = vimConnectionInfo.getVimId(); - return vimId.substring(vimId.indexOf("_") + 1); - } - - private String getTenant(final InlineResponse201VimConnectionInfo vimConnectionInfo) { - final JSONObject vimConnectionJsonObject = new JSONObject(vimConnectionInfo); - return vimConnectionJsonObject.getJSONObject("accessInfo").get("projectId").toString(); - } - -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/rest/Sol003GrantController.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/rest/Sol003GrantController.java deleted file mode 100644 index a9682964d8..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/rest/Sol003GrantController.java +++ /dev/null @@ -1,114 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.lcm.rest; - -import static org.onap.so.adapters.etsi.sol003.adapter.common.CommonConstants.BASE_URL; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; -import javax.ws.rs.core.MediaType; -import org.onap.etsi.sol003.adapter.lcm.v1.model.Tenant; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.aai.AaiHelper; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.aai.AaiServiceProvider; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.VnfmHelper; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.grant.model.GrantRequest; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.grant.model.GrantsAddResources; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.grant.model.InlineResponse201; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.grant.model.InlineResponse201AddResources; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.grant.model.InlineResponse201VimConnections; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; - -@Controller -@RequestMapping(value = BASE_URL, produces = MediaType.APPLICATION_JSON, consumes = MediaType.APPLICATION_JSON) -public class Sol003GrantController { - - private static final Logger logger = LoggerFactory.getLogger(Sol003GrantController.class); - public final AaiServiceProvider aaiServiceProvider; - public final AaiHelper aaiHelper; - public final VnfmHelper vnfmHelper; - - @Autowired - public Sol003GrantController(final AaiServiceProvider aaiServiceProvider, final AaiHelper aaiHelper, - final VnfmHelper vnfmHelper) { - this.aaiServiceProvider = aaiServiceProvider; - this.aaiHelper = aaiHelper; - this.vnfmHelper = vnfmHelper; - } - - @GetMapping(value = "/grants/{grantId}") - public ResponseEntity grantsGrantIdGet(@PathVariable("grantId") final String grantId) { - logger.info("Get grant received from VNFM, grant id: " + grantId); - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - } - - @PostMapping(value = "/grants") - public ResponseEntity grantsPost(@RequestBody final GrantRequest grantRequest) { - logger.info("Grant request received from VNFM: " + grantRequest); - - final InlineResponse201 grantResponse = createGrantResponse(grantRequest); - logger.info("Grant request returning to VNFM: " + grantResponse); - return new ResponseEntity<>(grantResponse, HttpStatus.CREATED); - } - - private InlineResponse201 createGrantResponse(final GrantRequest grantRequest) { - final InlineResponse201 grantResponse = new InlineResponse201(); - grantResponse.setId(UUID.randomUUID().toString()); - grantResponse.setVnfInstanceId(grantRequest.getVnfInstanceId()); - grantResponse.setVnfLcmOpOccId(grantRequest.getVnfLcmOpOccId()); - final String vnfSelfLink = grantRequest.getLinks().getVnfInstance().getHref(); - final Tenant tenant = aaiHelper - .getAssignedTenant(aaiServiceProvider.invokeQueryGenericVnf(vnfSelfLink).getGenericVnf().get(0)); - - String vimConnectionId = ""; - final InlineResponse201VimConnections vimConnection = vnfmHelper.getVimConnections(tenant); - grantResponse.addVimConnectionsItem(vimConnection); - vimConnectionId = vimConnection.getId(); - - if (grantRequest.getOperation().equals(GrantRequest.OperationEnum.INSTANTIATE)) { - grantResponse.addResources(getResources(grantRequest.getAddResources(), vimConnectionId)); - } else if (grantRequest.getOperation().equals(GrantRequest.OperationEnum.TERMINATE)) { - grantResponse.removeResources(getResources(grantRequest.getRemoveResources(), vimConnectionId)); - } - return grantResponse; - } - - private List getResources(final List requestResources, - final String vimId) { - final List resources = new ArrayList<>(); - for (final GrantsAddResources requestResource : requestResources) { - final InlineResponse201AddResources responseResource = new InlineResponse201AddResources(); - responseResource.setResourceDefinitionId(requestResource.getId()); - responseResource.setVimConnectionId(vimId); - resources.add(responseResource); - } - return resources; - } -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/rest/Sol003LcnContoller.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/rest/Sol003LcnContoller.java deleted file mode 100644 index 26ba1fffcf..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/rest/Sol003LcnContoller.java +++ /dev/null @@ -1,131 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.lcm.rest; - -import static org.onap.so.adapters.etsi.sol003.adapter.common.CommonConstants.BASE_URL; -import static org.onap.so.adapters.etsi.sol003.adapter.lcm.LifeCycleManagementConstants.OPERATION_NOTIFICATION_ENDPOINT; -import static org.slf4j.LoggerFactory.getLogger; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import javax.ws.rs.core.MediaType; -import org.onap.aai.domain.yang.EsrVnfm; -import org.onap.aai.domain.yang.GenericVnf; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.aai.AaiHelper; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.aai.AaiServiceProvider; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.VnfmServiceProvider; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.jobmanagement.JobManager; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.lcn.model.VnfIdentifierCreationNotification; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.lcn.model.VnfIdentifierDeletionNotification; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.lcn.model.VnfLcmOperationOccurrenceNotification; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.lcn.model.VnfLcmOperationOccurrenceNotification.OperationEnum; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.lcn.model.VnfLcmOperationOccurrenceNotification.OperationStateEnum; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.notificationhandling.NotificationHandler; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.model.InlineResponse201; -import org.slf4j.Logger; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; - -/** - * Controller for handling notifications from the VNFM (Virtual Network Function Manager). - */ -@Controller -@RequestMapping(value = BASE_URL, produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}, - consumes = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) -public class Sol003LcnContoller { - private static Logger logger = getLogger(Sol003LcnContoller.class); - private static final String LOG_LCN_RECEIVED = "LCN received from VNFM: "; - private final AaiServiceProvider aaiServiceProvider; - private final AaiHelper aaiHelper; - private final VnfmServiceProvider vnfmServiceProvider; - private final JobManager jobManager; - private final ExecutorService executor = Executors.newCachedThreadPool(); - - @Autowired - Sol003LcnContoller(final AaiServiceProvider aaiServiceProvider, final AaiHelper aaiHelper, - final VnfmServiceProvider vnfmServiceProvider, final JobManager jobManager) { - this.aaiServiceProvider = aaiServiceProvider; - this.aaiHelper = aaiHelper; - this.vnfmServiceProvider = vnfmServiceProvider; - this.jobManager = jobManager; - } - - @PostMapping(value = "/lcn/VnfIdentifierCreationNotification") - public ResponseEntity lcnVnfIdentifierCreationNotificationPost( - @RequestBody final VnfIdentifierCreationNotification vnfIdentifierCreationNotification) { - logger.info(LOG_LCN_RECEIVED + vnfIdentifierCreationNotification); - return new ResponseEntity<>(HttpStatus.NO_CONTENT); - } - - @PostMapping(value = "/lcn/VnfIdentifierDeletionNotification") - public ResponseEntity lcnVnfIdentifierDeletionNotificationPost( - @RequestBody final VnfIdentifierDeletionNotification vnfIdentifierDeletionNotification) { - logger.info(LOG_LCN_RECEIVED + vnfIdentifierDeletionNotification); - return new ResponseEntity<>(HttpStatus.NO_CONTENT); - } - - @PostMapping(value = OPERATION_NOTIFICATION_ENDPOINT) - public ResponseEntity lcnVnfLcmOperationOccurrenceNotificationPost( - @RequestBody final VnfLcmOperationOccurrenceNotification vnfLcmOperationOccurrenceNotification) { - logger.info(LOG_LCN_RECEIVED + vnfLcmOperationOccurrenceNotification); - - if (isANotificationOfInterest(vnfLcmOperationOccurrenceNotification)) { - final InlineResponse201 vnfInstance = getVnfInstance(vnfLcmOperationOccurrenceNotification); - final NotificationHandler handler = new NotificationHandler(vnfLcmOperationOccurrenceNotification, - aaiHelper, aaiServiceProvider, vnfmServiceProvider, jobManager, vnfInstance); - executor.execute(handler); - } - - logger.info("Sending notification response"); - return new ResponseEntity<>(HttpStatus.NO_CONTENT); - } - - private boolean isANotificationOfInterest(final VnfLcmOperationOccurrenceNotification notification) { - return isInstanitiateCompleted(notification) || isTerminateTerminalState(notification); - } - - private boolean isInstanitiateCompleted(final VnfLcmOperationOccurrenceNotification notification) { - return notification.getOperation().equals(OperationEnum.INSTANTIATE) - && notification.getOperationState().equals(OperationStateEnum.COMPLETED); - } - - private boolean isTerminateTerminalState(final VnfLcmOperationOccurrenceNotification notification) { - return notification.getOperation().equals(OperationEnum.TERMINATE) - && (notification.getOperationState().equals(OperationStateEnum.COMPLETED) - || notification.getOperationState().equals(OperationStateEnum.FAILED) - || notification.getOperationState().equals(OperationStateEnum.ROLLED_BACK)); - } - - private InlineResponse201 getVnfInstance( - final VnfLcmOperationOccurrenceNotification vnfLcmOperationOccurrenceNotification) { - GenericVnf vnfInAai = aaiServiceProvider - .invokeQueryGenericVnf(vnfLcmOperationOccurrenceNotification.getLinks().getVnfInstance().getHref()) - .getGenericVnf().get(0); - EsrVnfm vnfm = aaiHelper.getAssignedVnfm(vnfInAai); - return vnfmServiceProvider - .getVnf(vnfm, vnfLcmOperationOccurrenceNotification.getLinks().getVnfInstance().getHref()).get(); - } - -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/rest/VnfmAdapterController.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/rest/VnfmAdapterController.java deleted file mode 100644 index 9b571af81e..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/rest/VnfmAdapterController.java +++ /dev/null @@ -1,163 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.lcm.rest; - -import static org.onap.so.adapters.etsi.sol003.adapter.common.CommonConstants.BASE_URL; -import javax.validation.Valid; -import javax.ws.rs.core.MediaType; -import org.onap.etsi.sol003.adapter.lcm.v1.model.CreateVnfRequest; -import org.onap.etsi.sol003.adapter.lcm.v1.model.CreateVnfResponse; -import org.onap.etsi.sol003.adapter.lcm.v1.model.DeleteVnfResponse; -import org.onap.etsi.sol003.adapter.lcm.v1.model.QueryJobResponse; -import org.onap.logging.ref.slf4j.ONAPLogConstants; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.jobmanagement.JobManager; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.lifecycle.LifecycleManager; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.slf4j.MDC; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.DeleteMapping; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestHeader; -import org.springframework.web.bind.annotation.RequestMapping; -import io.swagger.annotations.ApiParam; - -/** - * Controller for handling requests to the VNFM (Virtual Network Function Manager) adapter REST API. - */ -@Controller -@RequestMapping(value = BASE_URL, produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}, - consumes = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) -public class VnfmAdapterController { - - private static final Logger logger = LoggerFactory.getLogger(VnfmAdapterController.class); - private final LifecycleManager lifecycleManager; - private final JobManager jobManager; - - @Autowired - VnfmAdapterController(final LifecycleManager lifecycleManager, final JobManager jobManager) { - this.lifecycleManager = lifecycleManager; - this.jobManager = jobManager; - } - - @PostMapping(value = "/vnfs/{vnfId}") - public ResponseEntity vnfCreate( - @ApiParam(value = "The identifier of the VNF. This must be the vnf-id of an existing generic-vnf in AAI.", - required = true) @PathVariable("vnfId") final String vnfId, - @ApiParam(value = "VNF creation parameters", - required = true) @Valid @RequestBody final CreateVnfRequest createVnfRequest, - @ApiParam( - value = "Used to track REST requests for logging purposes. Identifies a single top level invocation of ONAP", - required = false) @RequestHeader(value = ONAPLogConstants.Headers.REQUEST_ID, - required = false) final String requestId, - @ApiParam( - value = "Used to track REST requests for logging purposes. Identifies the client application user agent or user invoking the API", - required = false) @RequestHeader(value = ONAPLogConstants.Headers.PARTNER_NAME, - required = false) final String partnerName, - @ApiParam( - value = "Used to track REST requests for logging purposes. Identifies a single invocation of a single component", - required = false) @RequestHeader(value = ONAPLogConstants.Headers.INVOCATION_ID, - required = false) final String invocationId) { - - setLoggingMDCs(requestId, partnerName, invocationId); - - logger.info("REST request vnfCreate with body: {}", createVnfRequest); - - try { - final CreateVnfResponse createVnfResponse = lifecycleManager.createVnf(vnfId, createVnfRequest); - return new ResponseEntity<>(createVnfResponse, HttpStatus.ACCEPTED); - } finally { - clearLoggingMDCs(); - } - } - - @DeleteMapping(value = "/vnfs/{vnfId}") - public ResponseEntity vnfDelete( - @ApiParam(value = "The identifier of the VNF. This must be the vnf-id of an existing generic-vnf in AAI.", - required = true) @PathVariable("vnfId") final String vnfId, - @ApiParam( - value = "Used to track REST requests for logging purposes. Identifies a single top level invocation of ONAP", - required = false) @RequestHeader(value = ONAPLogConstants.Headers.REQUEST_ID, - required = false) final String requestId, - @ApiParam( - value = "Used to track REST requests for logging purposes. Identifies the client application user agent or user invoking the API", - required = false) @RequestHeader(value = ONAPLogConstants.Headers.PARTNER_NAME, - required = false) final String partnerName, - @ApiParam( - value = "Used to track REST requests for logging purposes. Identifies a single invocation of a single component", - required = false) @RequestHeader(value = ONAPLogConstants.Headers.INVOCATION_ID, - required = false) final String invocationId) { - - setLoggingMDCs(requestId, partnerName, invocationId); - - logger.info("REST request vnfDelete for VNF: {}", vnfId); - - try { - final DeleteVnfResponse response = lifecycleManager.deleteVnf(vnfId); - return new ResponseEntity<>(response, HttpStatus.ACCEPTED); - } finally { - clearLoggingMDCs(); - } - } - - @GetMapping(value = "/jobs/{jobId}") - public ResponseEntity jobQuery( - @ApiParam(value = "The identifier of the Job.", required = true) @PathVariable("jobId") final String jobId, - @ApiParam( - value = "Used to track REST requests for logging purposes. Identifies a single top level invocation of ONAP", - required = false) @RequestHeader(value = ONAPLogConstants.Headers.REQUEST_ID, - required = false) final String requestId, - @ApiParam( - value = "Used to track REST requests for logging purposes. Identifies the client application user agent or user invoking the API", - required = false) @RequestHeader(value = ONAPLogConstants.Headers.PARTNER_NAME, - required = false) final String partnerName, - @ApiParam( - value = "Used to track REST requests for logging purposes. Identifies a single invocation of a single component", - required = false) @RequestHeader(value = ONAPLogConstants.Headers.INVOCATION_ID, - required = false) final String invocationId) { - - setLoggingMDCs(requestId, partnerName, invocationId); - - try { - final QueryJobResponse response = jobManager.getVnfmOperation(jobId); - return new ResponseEntity<>(response, HttpStatus.OK); - } finally { - clearLoggingMDCs(); - } - } - - private void setLoggingMDCs(final String requestId, final String partnerName, final String invocationId) { - MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, requestId); - MDC.put(ONAPLogConstants.MDCs.PARTNER_NAME, partnerName); - MDC.put(ONAPLogConstants.MDCs.INVOCATION_ID, invocationId); - } - - private void clearLoggingMDCs() { - MDC.clear(); - } - -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/rest/exceptions/JobNotFoundException.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/rest/exceptions/JobNotFoundException.java deleted file mode 100644 index a5fac29ec7..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/rest/exceptions/JobNotFoundException.java +++ /dev/null @@ -1,38 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.lcm.rest.exceptions; - -import org.springframework.http.HttpStatus; -import org.springframework.web.bind.annotation.ResponseStatus; - -/** - * Exception for job not found. - */ -@ResponseStatus(HttpStatus.NOT_FOUND) -public class JobNotFoundException extends RuntimeException { - - private static final long serialVersionUID = 6398018034431666933L; - - public JobNotFoundException(final String message) { - super(message); - } - -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/rest/exceptions/TenantNotFoundException.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/rest/exceptions/TenantNotFoundException.java deleted file mode 100644 index d120f7e81a..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/rest/exceptions/TenantNotFoundException.java +++ /dev/null @@ -1,35 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.lcm.rest.exceptions; - -/** - * Exception for Tenant not found. - */ - -public class TenantNotFoundException extends RuntimeException { - - private static final long serialVersionUID = 6398018034431666933L; - - public TenantNotFoundException(final String message) { - super(message); - } - -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/rest/exceptions/VnfNotFoundException.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/rest/exceptions/VnfNotFoundException.java deleted file mode 100644 index 31ea91ae72..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/rest/exceptions/VnfNotFoundException.java +++ /dev/null @@ -1,38 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.lcm.rest.exceptions; - -import org.springframework.http.HttpStatus; -import org.springframework.web.bind.annotation.ResponseStatus; - -/** - * Exception for VNF not found. - */ -@ResponseStatus(HttpStatus.NOT_FOUND) -public class VnfNotFoundException extends RuntimeException { - - private static final long serialVersionUID = 6398018034431666933L; - - public VnfNotFoundException(final String message) { - super(message); - } - -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/rest/exceptions/VnfmNotFoundException.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/rest/exceptions/VnfmNotFoundException.java deleted file mode 100644 index d4107616c3..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/rest/exceptions/VnfmNotFoundException.java +++ /dev/null @@ -1,38 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.lcm.rest.exceptions; - -import org.springframework.http.HttpStatus; -import org.springframework.web.bind.annotation.ResponseStatus; - -/** - * Exception for VNFM not found. - */ -@ResponseStatus(HttpStatus.BAD_REQUEST) -public class VnfmNotFoundException extends RuntimeException { - - private static final long serialVersionUID = 6398018034431666933L; - - public VnfmNotFoundException(final String message) { - super(message); - } - -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/rest/exceptions/VnfmRequestFailureException.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/rest/exceptions/VnfmRequestFailureException.java deleted file mode 100644 index c2add907fe..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/rest/exceptions/VnfmRequestFailureException.java +++ /dev/null @@ -1,38 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.lcm.rest.exceptions; - -/** - * Exception indicating a request to a VNFM failed. - */ -public class VnfmRequestFailureException extends RuntimeException { - - private static final long serialVersionUID = 6398018034431666933L; - - public VnfmRequestFailureException(final String message) { - super(message); - } - - public VnfmRequestFailureException(final String message, final Throwable throwable) { - super(message, throwable); - } - -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/LifeCycleManagementConstants.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/LifeCycleManagementConstants.java new file mode 100644 index 0000000000..d9804072b7 --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/LifeCycleManagementConstants.java @@ -0,0 +1,33 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.lcm; + +/** + * ETSI SOL003 Life Cycle Management Adapter constants + * + * @author Waqas Ikram (waqas.ikram@est.tech) + */ +public class LifeCycleManagementConstants { + + public static final String OPERATION_NOTIFICATION_ENDPOINT = "/lcn/VnfLcmOperationOccurrenceNotification"; + + private LifeCycleManagementConstants() {} +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/NvfmAdapterUtils.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/NvfmAdapterUtils.java new file mode 100644 index 0000000000..a46ad8ffd4 --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/NvfmAdapterUtils.java @@ -0,0 +1,64 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.lcm; + +import static org.slf4j.LoggerFactory.getLogger; +import java.util.ArrayList; +import java.util.Collection; +import org.slf4j.Logger; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; + +public class NvfmAdapterUtils { + private static Logger logger = getLogger(NvfmAdapterUtils.class); + + public static JsonObject child(final JsonObject parent, final String name) { + return childElement(parent, name).getAsJsonObject(); + } + + public static JsonElement childElement(final JsonObject parent, final String name) { + final JsonElement child = parent.get(name); + if (child == null) { + throw abortOperation("Missing child " + name); + } + return child; + } + + public static Collection children(final JsonObject parent) { + final ArrayList childElements = new ArrayList<>(); + for (final String childKey : parent.keySet()) { + if (parent.get(childKey).isJsonObject()) { + childElements.add(parent.get(childKey).getAsJsonObject()); + } + } + return childElements; + } + + public static RuntimeException abortOperation(final String msg, final Exception e) { + logger.error(msg, e); + return new RuntimeException(msg, e); + } + + public static RuntimeException abortOperation(final String msg) { + logger.error(msg); + return new RuntimeException(msg); + } +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/AbstractServiceProviderConfiguration.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/AbstractServiceProviderConfiguration.java new file mode 100644 index 0000000000..b9ce641096 --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/AbstractServiceProviderConfiguration.java @@ -0,0 +1,49 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.lcm.extclients; + +import java.util.Iterator; +import org.onap.so.adapters.etsisol003adapter.lcm.v1.JSON; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.http.converter.json.GsonHttpMessageConverter; +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; +import org.springframework.web.client.RestTemplate; +import com.google.gson.Gson; + +/** + * A base class that can be extended by classes for configuring HttpRestServiceProvider classes. Provides common methods + * that will be useful to some such classes. + * + * @author gareth.roper@est.tech + */ +public abstract class AbstractServiceProviderConfiguration { + + public void setGsonMessageConverter(final RestTemplate restTemplate) { + final Iterator> iterator = restTemplate.getMessageConverters().iterator(); + while (iterator.hasNext()) { + if (iterator.next() instanceof MappingJackson2HttpMessageConverter) { + iterator.remove(); + } + } + final Gson gson = new JSON().getGson(); + restTemplate.getMessageConverters().add(new GsonHttpMessageConverter(gson)); + } +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/SdcPackageProvider.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/SdcPackageProvider.java new file mode 100644 index 0000000000..497de2874c --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/SdcPackageProvider.java @@ -0,0 +1,195 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Modifications Copyright (c) 2019 Samsung + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.lcm.extclients; + +import static com.google.common.base.Splitter.on; +import static com.google.common.collect.Iterables.filter; +import static com.google.common.io.ByteStreams.toByteArray; +import static java.lang.String.format; +import static org.apache.http.HttpHeaders.ACCEPT; +import static org.apache.http.HttpHeaders.AUTHORIZATION; +import static org.onap.so.adapters.etsisol003adapter.lcm.NvfmAdapterUtils.abortOperation; +import static org.onap.so.adapters.etsisol003adapter.lcm.NvfmAdapterUtils.child; +import static org.onap.so.adapters.etsisol003adapter.lcm.NvfmAdapterUtils.childElement; +import static org.onap.so.adapters.etsisol003adapter.lcm.NvfmAdapterUtils.children; +import static org.slf4j.LoggerFactory.getLogger; +import static org.springframework.http.MediaType.APPLICATION_OCTET_STREAM_VALUE; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.Set; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; +import javax.net.ssl.SSLContext; +import org.apache.commons.codec.binary.Base64; +import org.apache.http.HttpEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.onap.so.utils.CryptoUtils; +import org.slf4j.Logger; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; +import org.yaml.snakeyaml.Yaml; +import com.google.common.io.ByteStreams; +import com.google.gson.Gson; +import com.google.gson.JsonObject; + +@Component +public class SdcPackageProvider { + private static final String GET_PACKAGE_URL = "%s/sdc/v1/catalog/resources/%s/toscaModel"; + @Value("${sdc.toscametapath:TOSCA-Metadata/TOSCA.meta}") + private List toscaMetaPaths; + private static final String TOSCA_VNFD_KEY = "Entry-Definitions"; + private static Logger logger = getLogger(SdcPackageProvider.class); + + @Value("${sdc.username}") + private String sdcUsername; + @Value("${sdc.password}") + private String sdcPassword; + @Value("${sdc.key}") + private String sdcKey; + @Value("${sdc.endpoint}") + private String baseUrl; + + public String getVnfdId(final String csarId) { + return getVnfNodeProperty(csarId, "descriptor_id"); + } + + private String getVnfNodeProperty(final String csarId, final String propertyName) { + logger.debug("Getting " + propertyName + " from " + csarId); + final byte[] onapPackage = getPackage(csarId); + + try { + final String vnfdLocation = getVnfdLocation(new ByteArrayInputStream(onapPackage)); + final String onapVnfdContent = getFileInZip(new ByteArrayInputStream(onapPackage), vnfdLocation).toString(); + logger.debug("VNFD CONTENTS: " + onapVnfdContent); + final JsonObject root = new Gson().toJsonTree(new Yaml().load(onapVnfdContent)).getAsJsonObject(); + + final JsonObject topologyTemplates = child(root, "topology_template"); + final JsonObject nodeTemplates = child(topologyTemplates, "node_templates"); + for (final JsonObject child : children(nodeTemplates)) { + final String type = childElement(child, "type").getAsString(); + String propertyValue = null; + if ("tosca.nodes.nfv.VNF".equals(type)) { + final JsonObject properties = child(child, "properties"); + logger.debug("properties: " + properties.toString()); + + propertyValue = properties.get(propertyName).getAsJsonPrimitive().getAsString(); + } + if (propertyValue == null) { + propertyValue = getValueFromNodeTypeDefinition(root, type, propertyName); + } + return propertyValue; + } + + } catch (final Exception e) { + throw new IllegalArgumentException("Unable to extract " + propertyName + " from ONAP package", e); + } + throw new IllegalArgumentException("Unable to extract " + propertyName + " from ONAP package"); + } + + private String getValueFromNodeTypeDefinition(final JsonObject root, final String nodeTypeName, + final String propertyName) { + final JsonObject nodeTypes = child(root, "node_types"); + final JsonObject nodeType = child(nodeTypes, nodeTypeName); + + if ("tosca.nodes.nfv.VNF".equals(childElement(nodeType, "derived_from").getAsString())) { + final JsonObject properties = child(nodeType, "properties"); + logger.debug("properties: " + properties.toString()); + final JsonObject property = child(properties, propertyName); + logger.debug("property: " + property.toString()); + logger.debug("property default: " + childElement(property, "default").toString()); + return childElement(property, "default").getAsJsonPrimitive().getAsString(); + } + return null; + } + + private byte[] getPackage(final String csarId) { + final String SERVICE_NAME = "vnfm-adapter"; + try (CloseableHttpClient client = HttpClients.custom().setSSLContext(SSLContext.getDefault()).build()) { + final HttpGet httpget = new HttpGet(format(GET_PACKAGE_URL, baseUrl, csarId)); + httpget.setHeader(ACCEPT, APPLICATION_OCTET_STREAM_VALUE); + httpget.setHeader("X-ECOMP-InstanceID", SERVICE_NAME); + httpget.setHeader("X-FromAppId", SERVICE_NAME); + final String auth = sdcUsername + ":" + CryptoUtils.decrypt(sdcPassword, sdcKey); + final byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(StandardCharsets.ISO_8859_1)); + final String authHeader = "Basic " + new String(encodedAuth); + httpget.setHeader(AUTHORIZATION, authHeader); + logger.debug("Fetching from SDC: " + httpget); + final CloseableHttpResponse response = client.execute(httpget); + final HttpEntity entity = response.getEntity(); + final InputStream is = entity.getContent(); + return toByteArray(is); + } catch (final Exception e) { + throw abortOperation("Unable to download " + csarId + " package from SDC", e); + } + } + + private String getVnfdLocation(final InputStream stream) throws IOException { + final Iterator pathIterator = toscaMetaPaths.iterator(); + while (pathIterator.hasNext()) { + final String toscaMetadata = new String(getFileInZip(stream, pathIterator.next()).toByteArray()); + if (!toscaMetadata.isEmpty()) { + final String toscaVnfdLine = + filter(on("\n").split(toscaMetadata), line -> line.contains(TOSCA_VNFD_KEY)).iterator().next(); + return toscaVnfdLine.replace(TOSCA_VNFD_KEY + ":", "").trim(); + } + } + throw abortOperation("Unable to find valid Tosca Path"); + } + + private static ByteArrayOutputStream getFileInZip(final InputStream zip, final String path) throws IOException { + final ZipInputStream zipInputStream = new ZipInputStream(zip); + final ByteArrayOutputStream fileContent = getFileInZip(zipInputStream, path); + zipInputStream.close(); + return fileContent; + } + + private static ByteArrayOutputStream getFileInZip(final ZipInputStream zipInputStream, final String path) + throws IOException { + ZipEntry zipEntry; + final Set items = new HashSet<>(); + while ((zipEntry = zipInputStream.getNextEntry()) != null) { + items.add(zipEntry.getName()); + if (zipEntry.getName().matches(path)) { + final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + ByteStreams.copy(zipInputStream, byteArrayOutputStream); + return byteArrayOutputStream; + } + } + logger.error("Unable to find the {} in archive found: {}", path, items); + throw new NoSuchElementException("Unable to find the " + path + " in archive found: " + items); + } + + public String getFlavourId(final String csarId) { + return getVnfNodeProperty(csarId, "flavour_id"); + } +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/aai/AaiClientProvider.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/aai/AaiClientProvider.java new file mode 100644 index 0000000000..529be0eb2e --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/aai/AaiClientProvider.java @@ -0,0 +1,34 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.lcm.extclients.aai; + +import org.onap.aaiclient.client.aai.AAIResourcesClient; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class AaiClientProvider { + + @Bean + public AAIResourcesClient getAaiClient() { + return new AAIResourcesClient(); + } +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/aai/AaiHelper.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/aai/AaiHelper.java new file mode 100644 index 0000000000..958d2ebca8 --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/aai/AaiHelper.java @@ -0,0 +1,217 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.lcm.extclients.aai; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import org.onap.aai.domain.yang.EsrSystemInfo; +import org.onap.aai.domain.yang.EsrSystemInfoList; +import org.onap.aai.domain.yang.EsrVnfm; +import org.onap.aai.domain.yang.EsrVnfmList; +import org.onap.aai.domain.yang.GenericVnf; +import org.onap.aai.domain.yang.Relationship; +import org.onap.aai.domain.yang.RelationshipData; +import org.onap.aai.domain.yang.Vserver; +import org.onap.so.adapters.etsisol003adapter.lcm.lcn.model.LcnVnfLcmOperationOccurrenceNotificationAffectedVnfcs; +import org.onap.so.adapters.etsisol003adapter.lcm.rest.exceptions.TenantNotFoundException; +import org.onap.so.adapters.etsisol003adapter.lcm.rest.exceptions.VnfmNotFoundException; +import org.onap.so.adapters.etsisol003adapter.lcm.v1.model.Tenant; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +/** + * Provides helper methods for interactions with AAI. + */ +@Service +public class AaiHelper { + + private static final Logger logger = LoggerFactory.getLogger(AaiHelper.class); + private final AaiServiceProvider aaiServiceProvider; + private final Map mapOfVnfIdToOamIpAddressHolder = new HashMap<>(); + + @Autowired + public AaiHelper(final AaiServiceProvider aaiServiceProvider) { + this.aaiServiceProvider = aaiServiceProvider; + } + + /** + * Get the VNFM assigned for use for the given generic VNF. + * + * @param vnf the generic VNF + * @return the VNFM to use, or null if no VNFM has been assigned yet + */ + public EsrVnfm getAssignedVnfm(final GenericVnf vnf) { + final String vnfmId = getIdOfAssignedVnfm(vnf); + return vnfmId == null ? null : aaiServiceProvider.invokeGetVnfm(vnfmId); + } + + /** + * Get the ID of the VNFM assigned for use for the given generic VNF. + * + * @param vnf the generic VNF + * @return the ID of the VNFM to use, or null if no VNFM has been assigned yet + */ + public String getIdOfAssignedVnfm(final GenericVnf vnf) { + final Relationship relationship = getRelationship(vnf, "esr-vnfm"); + return getRelationshipData(relationship, "esr-vnfm.vnfm-id"); + } + + /** + * Get the tenant assigned for use for the given generic VNF. + * + * @param vnf the generic VNF + * @return the tenant to use, or null if no tenant has been assigned yet + */ + public Tenant getAssignedTenant(final GenericVnf vnf) { + final Relationship relationship = getRelationship(vnf, "tenant"); + final String cloudOwner = getRelationshipData(relationship, "cloud-region.cloud-owner"); + final String cloudRegion = getRelationshipData(relationship, "cloud-region.cloud-region-id"); + final String tenantId = getRelationshipData(relationship, "tenant.tenant-id"); + if (cloudOwner == null || cloudRegion == null || tenantId == null) { + throw new TenantNotFoundException("No matching Tenant found in AAI. VNFID: " + vnf.getVnfId()); + } else { + return new Tenant().cloudOwner(cloudOwner).regionName(cloudRegion).tenantId(tenantId); + } + } + + private Relationship getRelationship(final GenericVnf vnf, final String relationshipRelatedToValue) { + for (final Relationship relationship : vnf.getRelationshipList() == null ? Collections.emptyList() + : vnf.getRelationshipList().getRelationship()) { + if (relationship.getRelatedTo().equals(relationshipRelatedToValue)) { + return relationship; + } + } + return null; + } + + /** + * Get the value of the relationship data with the given key in the given relationship. + * + * @param relationship the relationship + * @param relationshipDataKey the key for the relationship data + * @return the value of the relationship data for the given key + */ + public String getRelationshipData(final Relationship relationship, final String relationshipDataKey) { + if (relationship != null) { + for (final RelationshipData relationshipData : relationship.getRelationshipData()) { + if (relationshipData.getRelationshipKey().equals(relationshipDataKey)) { + return relationshipData.getRelationshipValue(); + } + } + } + return null; + } + + /** + * Delete from the given VNF the relationship matching the given criteria. + * + * @param vnf the VNF + * @param relationshipRelatedToValue the related-to value for the relationship + * @param dataKey the relationship data key to match on + * @param dataValue the value the relationship data with the given key must match + * @return the deleted relationship or null if none found matching the given criteria + */ + public Relationship deleteRelationshipWithDataValue(final GenericVnf vnf, final String relationshipRelatedToValue, + final String dataKey, final String dataValue) { + final Iterator relationships = + vnf.getRelationshipList() == null ? Collections.emptyList().iterator() + : vnf.getRelationshipList().getRelationship().iterator(); + + while (relationships.hasNext()) { + final Relationship relationship = relationships.next(); + if (relationship.getRelatedTo().equals(relationshipRelatedToValue) + && dataValue.equals(getRelationshipData(relationship, dataKey))) { + relationships.remove(); + return relationship; + } + } + return null; + } + + /** + * 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 + */ + public EsrVnfm selectVnfm(final GenericVnf vnf) { + final EsrVnfmList vnfmsInEsr = aaiServiceProvider.invokeGetVnfms(); + + if (vnfmsInEsr == null) { + throw new VnfmNotFoundException("No VNFMs found in AAI ESR"); + } + logger.debug("VNFMs in ESR: " + vnfmsInEsr); + + for (final EsrVnfm vnfm : vnfmsInEsr.getEsrVnfm()) { + final EsrSystemInfoList systemInfolist = + aaiServiceProvider.invokeGetVnfmEsrSystemInfoList(vnfm.getVnfmId()); + vnfm.setEsrSystemInfoList(systemInfolist); + if (vnfmHasMatchingEsrSystemInfoType(vnfm, vnf.getNfType())) { + return vnfm; + } + } + throw new VnfmNotFoundException("No matching VNFM found in AAI ESR"); + } + + private boolean vnfmHasMatchingEsrSystemInfoType(final EsrVnfm vnfm, final String type) { + logger.debug("Checking VNFM ID: " + vnfm + ": " + vnfm.getVnfmId()); + + final EsrSystemInfoList systemInfolist = vnfm.getEsrSystemInfoList(); + if (systemInfolist != null) { + for (final EsrSystemInfo esrSystemInfo : systemInfolist.getEsrSystemInfo()) { + if (esrSystemInfo.getType().equals(type)) { + logger.debug("Matched VNFM ID: " + vnfm + ", based on type"); + return true; + } + } + } + return false; + } + + /** + * Create a vserver. + * + * @param vnfc the VNFC to base the vserver on + * @return the vserver + */ + public Vserver createVserver(final LcnVnfLcmOperationOccurrenceNotificationAffectedVnfcs vnfc) { + final Vserver vserver = new Vserver(); + vserver.setVserverId(vnfc.getComputeResource().getResourceId()); + vserver.setVserverName(vnfc.getId()); + vserver.setProvStatus("active"); + vserver.setVserverSelflink("Not available"); + return vserver; + } + + public void setOamIpAddressSource(final String vnfId, final OamIpAddressSource oamIpAddressSource) { + mapOfVnfIdToOamIpAddressHolder.put(vnfId, oamIpAddressSource); + } + + public OamIpAddressSource getOamIpAddressSource(final String vnfId) { + return mapOfVnfIdToOamIpAddressHolder.get(vnfId); + } + +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/aai/AaiPropertiesImpl.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/aai/AaiPropertiesImpl.java new file mode 100644 index 0000000000..b3b22e239d --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/aai/AaiPropertiesImpl.java @@ -0,0 +1,68 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.lcm.extclients.aai; + +import org.onap.aaiclient.client.aai.AAIProperties; +import org.onap.aaiclient.client.aai.AAIVersion; +import org.onap.so.spring.SpringContextHelper; +import org.springframework.context.ApplicationContext; +import java.net.MalformedURLException; +import java.net.URL; + +public class AaiPropertiesImpl implements AAIProperties { + + private final String endpoint; + private final String encryptedBasicAuth; + private final String encrytptionKey; + + public AaiPropertiesImpl() { + + final ApplicationContext context = SpringContextHelper.getAppContext(); + this.endpoint = context.getEnvironment().getProperty("aai.endpoint"); + this.encryptedBasicAuth = context.getEnvironment().getProperty("aai.auth"); + this.encrytptionKey = context.getEnvironment().getProperty("mso.key"); + } + + @Override + public URL getEndpoint() throws MalformedURLException { + return new URL(endpoint); + } + + @Override + public String getSystemName() { + return "MSO"; + } + + @Override + public AAIVersion getDefaultVersion() { + return AAIVersion.LATEST; + } + + @Override + public String getAuth() { + return encryptedBasicAuth; + } + + @Override + public String getKey() { + return encrytptionKey; + } +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/aai/AaiServiceProvider.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/aai/AaiServiceProvider.java new file mode 100644 index 0000000000..f527b6cd97 --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/aai/AaiServiceProvider.java @@ -0,0 +1,148 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.lcm.extclients.aai; + +import org.onap.aai.domain.yang.EsrSystemInfoList; +import org.onap.aai.domain.yang.EsrVnfm; +import org.onap.aai.domain.yang.EsrVnfmList; +import org.onap.aai.domain.yang.GenericVnf; +import org.onap.aai.domain.yang.GenericVnfs; +import org.onap.aai.domain.yang.Vserver; +import org.onap.so.adapters.etsisol003adapter.lcm.v1.model.Tenant; + +/** + * Provides methods for invoking REST calls to AAI. + */ +public interface AaiServiceProvider { + + /** + * Invoke a get request for a generic VNF. + * + * @param vnfId the VNF id + * @return the generic VNF + */ + GenericVnf invokeGetGenericVnf(final String vnfId); + + /** + * Invoke a query for a generic VNF with the given selfLink + * + * @param selfLink the selfLink + * @return the matching generic vnfs + */ + GenericVnfs invokeQueryGenericVnf(final String selfLink); + + /** + * Invoke a GET request for the VNFMs. + * + * @return the VNFMs + */ + EsrVnfmList invokeGetVnfms(); + + /** + * Invoke a GET request for the esr system info list for a VNFM. + * + * @return the esr system info list for the VNFM + */ + EsrSystemInfoList invokeGetVnfmEsrSystemInfoList(final String vnfmId); + + /** + * Invoke a GET request for the a VNFM. + * + * @param vnfmId the ID of the VNFM + * @return the VNFM + */ + EsrVnfm invokeGetVnfm(final String vnfmId); + + /** + * Invoke a PATCH request for a generic vnf. + * + * @param vnf the generic vnf + * @return + */ + void invokePatchGenericVnf(GenericVnf vnf); + + /** + * Invoke a PUT request for a relationship from a generic vnf to a VNFM. + * + * @param vnf the generic vnf + * @param vnfmId the ID of the VNFM + * @return + */ + void invokePutGenericVnfToVnfmRelationship(GenericVnf vnf, final String vnfmId); + + + /** + * Invoke a PUT request for a vserver. + * + * @param cloudOwner the cloud owner + * @param cloudRegion the cloud region + * @param tenantId the ID of the tenant + * @param vserver the vserver + * @return + */ + void invokePutVserver(final String cloudOwner, final String cloudRegion, final String tenantId, + final Vserver vserver); + + /** + * Invoke a PUT request for a relationship from a vserver to a generic vnf. + * + * @param cloudOwner the cloud owner + * @param cloudRegion the cloud region the vserver is deployed on + * @param tenantId the ID of the tenant the vserver is deployed on + * @param vserver the vserver + * @param vnfId the ID of the generic vnf + * @return + */ + void invokePutVserverToVnfRelationship(final String cloudOwner, final String cloudRegion, final String tenantId, + final Vserver vserver, final String vnfId); + + /** + * Invoke a DELETE request for a vserver. + * + * @param cloudOwner the cloud owner + * @param cloudRegion the cloud region + * @param tenantId the ID of the tenant + * @param vserverId the ID of the vserver + * @return + */ + void invokeDeleteVserver(final String cloudOwner, final String cloudRegion, final String tenantId, + final String vserverId); + + /** + * Invoke a GET request for the a tenant. + * + * @param cloudOwner the cloud owner + * @param cloudRegion the cloud region + * @param tenantId the ID of the tenant + * @return the tenant + */ + Tenant invokeGetTenant(final String cloudOwner, final String cloudRegion, final String tenantId); + + /** + * Invoke a GET request for the esr system info list for a cloud region. + * + * @param cloudOwner the cloud owner + * @param cloudRegion the cloud region + * @return the esr system info list for the VNFM + */ + EsrSystemInfoList invokeGetCloudRegionEsrSystemInfoList(final String cloudOwner, final String cloudRegion); + +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/aai/AaiServiceProviderImpl.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/aai/AaiServiceProviderImpl.java new file mode 100644 index 0000000000..d9450b3472 --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/aai/AaiServiceProviderImpl.java @@ -0,0 +1,158 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.lcm.extclients.aai; + +import org.onap.aai.domain.yang.EsrSystemInfoList; +import org.onap.aai.domain.yang.EsrVnfm; +import org.onap.aai.domain.yang.EsrVnfmList; +import org.onap.aai.domain.yang.GenericVnf; +import org.onap.aai.domain.yang.GenericVnfs; +import org.onap.aai.domain.yang.Vserver; +import org.onap.aaiclient.client.aai.AAIObjectType; +import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory; +import org.onap.aaiclient.client.graphinventory.entities.uri.Depth; +import org.onap.so.adapters.etsisol003adapter.lcm.v1.model.Tenant; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class AaiServiceProviderImpl implements AaiServiceProvider { + + private static final Logger logger = LoggerFactory.getLogger(AaiServiceProviderImpl.class); + private final AaiClientProvider aaiClientProvider; + + @Autowired + public AaiServiceProviderImpl(final AaiClientProvider aaiClientProvider) { + this.aaiClientProvider = aaiClientProvider; + } + + @Override + public GenericVnf invokeGetGenericVnf(final String vnfId) { + return aaiClientProvider.getAaiClient() + .get(GenericVnf.class, AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId)) + .orElseGet(() -> { + logger.debug("No vnf found in AAI with ID: {}", vnfId); + return null; + }); + } + + @Override + public GenericVnfs invokeQueryGenericVnf(final String selfLink) { + return aaiClientProvider.getAaiClient() + .get(GenericVnfs.class, + AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNFS).queryParam("selflink", selfLink)) + .orElseGet(() -> { + logger.debug("No vnf found in AAI with selflink: {}", selfLink); + return null; + }); + } + + @Override + public EsrVnfmList invokeGetVnfms() { + return aaiClientProvider.getAaiClient() + .get(EsrVnfmList.class, AAIUriFactory.createResourceUri(AAIObjectType.VNFM_LIST)).orElseGet(() -> { + logger.debug("No VNFMs in AAI"); + return null; + }); + } + + @Override + public EsrVnfm invokeGetVnfm(final String vnfmId) { + return aaiClientProvider.getAaiClient() + .get(EsrVnfm.class, AAIUriFactory.createResourceUri(AAIObjectType.VNFM, vnfmId).depth(Depth.ONE)) + .orElseGet(() -> { + logger.debug("VNFM not found in AAI"); + return null; + }); + } + + @Override + public EsrSystemInfoList invokeGetVnfmEsrSystemInfoList(final String vnfmId) { + return aaiClientProvider.getAaiClient() + .get(EsrSystemInfoList.class, + AAIUriFactory.createResourceUri(AAIObjectType.VNFM_ESR_SYSTEM_INFO_LIST, vnfmId)) + .orElseGet(() -> { + logger.debug("VNFM ESR system info list not found in AAI"); + return null; + }); + } + + @Override + public void invokePatchGenericVnf(final GenericVnf vnf) { + aaiClientProvider.getAaiClient() + .update(AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnf.getVnfId()), vnf); + } + + @Override + public void invokePutGenericVnfToVnfmRelationship(final GenericVnf vnf, final String vnfmId) { + aaiClientProvider.getAaiClient().connect(AAIUriFactory.createResourceUri(AAIObjectType.VNFM, vnfmId), + AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnf.getVnfId())); + } + + @Override + public void invokePutVserver(final String cloudOwner, final String cloudRegion, final String tenant, + final Vserver vserver) { + aaiClientProvider.getAaiClient().create(AAIUriFactory.createResourceUri(AAIObjectType.VSERVER, cloudOwner, + cloudRegion, tenant, vserver.getVserverId()), vserver); + } + + @Override + public void invokePutVserverToVnfRelationship(final String cloudOwner, final String cloudRegion, + final String tenant, final Vserver vserver, final String vnfId) { + aaiClientProvider.getAaiClient() + .connect( + AAIUriFactory.createResourceUri(AAIObjectType.VSERVER, cloudOwner, cloudRegion, tenant, + vserver.getVserverId()), + AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId)); + } + + @Override + public void invokeDeleteVserver(final String cloudOwner, final String cloudRegion, final String tenant, + final String vserverId) { + aaiClientProvider.getAaiClient().delete( + AAIUriFactory.createResourceUri(AAIObjectType.VSERVER, cloudOwner, cloudRegion, tenant, vserverId)); + } + + @Override + public Tenant invokeGetTenant(final String cloudOwner, final String cloudRegion, final String tenantId) { + return aaiClientProvider.getAaiClient() + .get(Tenant.class, + AAIUriFactory.createResourceUri(AAIObjectType.TENANT, cloudOwner, cloudRegion, tenantId)) + .orElseGet(() -> { + logger.debug("Tenant not found in AAI"); + return null; + }); + } + + @Override + public EsrSystemInfoList invokeGetCloudRegionEsrSystemInfoList(final String cloudOwner, final String cloudRegion) { + return aaiClientProvider + .getAaiClient().get(EsrSystemInfoList.class, AAIUriFactory + .createResourceUri(AAIObjectType.CLOUD_ESR_SYSTEM_INFO_LIST, cloudOwner, cloudRegion)) + .orElseGet(() -> { + logger.debug("Cloud esr system info list not found in AAI"); + return null; + }); + } + +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/aai/OamIpAddressSource.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/aai/OamIpAddressSource.java new file mode 100644 index 0000000000..b81925241c --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/aai/OamIpAddressSource.java @@ -0,0 +1,57 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.lcm.extclients.aai; + +/** + * Represents the source of the value to use as the AAI OAM IP address of a VNF + */ +public class OamIpAddressSource { + + private final OamIpAddressType type; + private final String value; + + public OamIpAddressSource(final OamIpAddressType type, final String value) { + this.type = type; + this.value = value; + } + + public OamIpAddressType getType() { + return type; + } + + public String getValue() { + return value; + } + + public enum OamIpAddressType { + /** + * The value passed in {@link OamIpAddress#OamIpAddress(OamIpAddressType, String)} is to be used directly as the + * OAM IP address + */ + LITERAL, + /** + * The OAM IP address is to be retrieved from the vnfConfigurableProperties returned from the VNFM using the + * value passed in {@link OamIpAddress#OamIpAddress(OamIpAddressType, String)} as the name of a property + */ + CONFIGURABLE_PROPERTY + } + +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/vim/model/AccessInfo.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/vim/model/AccessInfo.java new file mode 100644 index 0000000000..139df248d4 --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/vim/model/AccessInfo.java @@ -0,0 +1,107 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.lcm.extclients.vim.model; + +import java.util.Objects; + +public class AccessInfo { + + protected String projectId; + protected String projectName; + protected String domainName; + protected VimCredentials credentials; + + public String getProjectId() { + return projectId; + } + + public void setProjectId(final String value) { + projectId = value; + } + + public String getProjectName() { + return projectName; + } + + public void setProjectName(final String value) { + projectName = value; + } + + public String getDomainName() { + return domainName; + } + + public void setDomainName(final String value) { + domainName = value; + } + + public VimCredentials getCredentials() { + return credentials; + } + + public void setCredentials(final VimCredentials value) { + credentials = value; + } + + @Override + public boolean equals(final java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + final AccessInfo accessInfo = (AccessInfo) o; + return Objects.equals(this.projectId, accessInfo.projectId) + && Objects.equals(this.projectName, accessInfo.projectName) + && Objects.equals(this.domainName, accessInfo.domainName) + && Objects.equals(this.credentials, accessInfo.credentials); + } + + @Override + public int hashCode() { + return Objects.hash(projectId, projectName, domainName, credentials); + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder(); + sb.append("class AccessInfo {\n"); + + sb.append(" projectId: ").append(toIndentedString(projectId)).append("\n"); + sb.append(" projectName: ").append(toIndentedString(projectName)).append("\n"); + sb.append(" domainName: ").append(toIndentedString(domainName)).append("\n"); + sb.append(" credentials: ").append(toIndentedString(credentials)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces (except the first line). + */ + private String toIndentedString(final java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/vim/model/InterfaceInfo.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/vim/model/InterfaceInfo.java new file mode 100644 index 0000000000..9d4355a0c4 --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/vim/model/InterfaceInfo.java @@ -0,0 +1,74 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.lcm.extclients.vim.model; + +import java.util.Objects; + +public class InterfaceInfo { + + protected String identityEndPoint; + + public String getIdentityEndPoint() { + return identityEndPoint; + } + + public void setIdentityEndPoint(final String value) { + identityEndPoint = value; + } + + @Override + public boolean equals(final java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + final InterfaceInfo interfaceInfo = (InterfaceInfo) o; + return Objects.equals(this.identityEndPoint, interfaceInfo.identityEndPoint); + } + + @Override + public int hashCode() { + return Objects.hash(identityEndPoint); + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder(); + sb.append("class InterfaceInfo {\n"); + + sb.append(" identityEndPoint: ").append(toIndentedString(identityEndPoint)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces (except the first line). + */ + private String toIndentedString(final java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/vim/model/VimCredentials.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/vim/model/VimCredentials.java new file mode 100644 index 0000000000..fd1a9078bb --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/vim/model/VimCredentials.java @@ -0,0 +1,85 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.lcm.extclients.vim.model; + +import java.util.Objects; + +public class VimCredentials { + + protected String username; + + protected String password; + + public String getUsername() { + return username; + } + + public void setUsername(final String value) { + username = value; + } + + public String getPassword() { + return password; + } + + public void setPassword(final String password) { + this.password = password; + } + + @Override + public boolean equals(final java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + final VimCredentials vimCredentials = (VimCredentials) o; + return Objects.equals(this.username, vimCredentials.username) + && Objects.equals(this.password, vimCredentials.password); + } + + @Override + public int hashCode() { + return Objects.hash(username, password); + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder(); + sb.append("class AccessInfo {\n"); + + sb.append(" username: ").append(toIndentedString(username)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces (except the first line). + */ + private String toIndentedString(final java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/vnfm/VnfmHelper.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/vnfm/VnfmHelper.java new file mode 100644 index 0000000000..9155261bd2 --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/vnfm/VnfmHelper.java @@ -0,0 +1,228 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm; + +import java.security.GeneralSecurityException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.onap.aai.domain.yang.EsrSystemInfo; +import org.onap.so.adapters.etsi.sol003.adapter.common.VnfmAdapterUrlProvider; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.aai.AaiServiceProvider; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vim.model.AccessInfo; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vim.model.InterfaceInfo; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vim.model.VimCredentials; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.InstantiateVnfRequest; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.LccnSubscriptionRequest; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.SubscriptionsAuthentication; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.SubscriptionsAuthentication.AuthTypeEnum; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.SubscriptionsAuthenticationParamsBasic; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.SubscriptionsAuthenticationParamsOauth2ClientCredentials; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.SubscriptionsFilter; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.SubscriptionsFilter.NotificationTypesEnum; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.SubscriptionsFilterVnfInstanceSubscriptionFilter; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.VnfInstancesvnfInstanceIdinstantiateExtVirtualLinks; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.VnfInstancesvnfInstanceIdinstantiateVimConnectionInfo; +import org.onap.so.adapters.etsisol003adapter.lcm.grant.model.InlineResponse201VimConnections; +import org.onap.so.adapters.etsisol003adapter.lcm.v1.model.CreateVnfRequest; +import org.onap.so.adapters.etsisol003adapter.lcm.v1.model.ExternalVirtualLink; +import org.onap.so.adapters.etsisol003adapter.lcm.v1.model.Tenant; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import com.google.common.reflect.TypeToken; +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; + +/** + * Provides helper methods for interactions with VNFM. + */ +@Service +public class VnfmHelper { + + private static final Logger logger = LoggerFactory.getLogger(VnfmHelper.class); + private static final String SEPARATOR = "_"; + private final AaiServiceProvider aaiServiceProvider; + private final VnfmAdapterUrlProvider vnfmAdapterUrlProvider; + + @Autowired + public VnfmHelper(final AaiServiceProvider aaiServiceProvider, + final VnfmAdapterUrlProvider vnfmAdapterUrlProvider) { + this.aaiServiceProvider = aaiServiceProvider; + this.vnfmAdapterUrlProvider = vnfmAdapterUrlProvider; + } + + /** + * Create an {@link InstantiateVnfRequest} to send in an instantiation request to a VNFM. + * + * @param tenant the tenant the request is to be fulfilled on + * @param createVnfRequest the request received by the VNFM adapter + */ + public InstantiateVnfRequest createInstantiateRequest(final Tenant tenant, final CreateVnfRequest createVnfRequest, + final String flavourId) { + final InstantiateVnfRequest instantiateVnfRequest = new InstantiateVnfRequest(); + instantiateVnfRequest.setFlavourId(flavourId); + instantiateVnfRequest.setVimConnectionInfo(getVimConnectionInfos(tenant)); + instantiateVnfRequest + .setAdditionalParams(getAdditionalParametersAsJsonObject(createVnfRequest.getAdditionalParams())); + instantiateVnfRequest.setExtVirtualLinks(getExternalVirtualLinks(createVnfRequest.getExternalVirtualLinks())); + createVnfRequest.getExternalVirtualLinks(); + return instantiateVnfRequest; + } + + private List getVimConnectionInfos(final Tenant tenant) { + final List connectionInfos = new ArrayList<>(); + connectionInfos.add(getVimConnectionInfo(tenant)); + return connectionInfos; + } + + private VnfInstancesvnfInstanceIdinstantiateVimConnectionInfo getVimConnectionInfo(final Tenant tenant) { + final EsrSystemInfo esrSystemInfo = + aaiServiceProvider.invokeGetCloudRegionEsrSystemInfoList(tenant.getCloudOwner(), tenant.getRegionName()) + .getEsrSystemInfo().iterator().next(); + + final VnfInstancesvnfInstanceIdinstantiateVimConnectionInfo vnfInstancesVimConnectionInfo = + new VnfInstancesvnfInstanceIdinstantiateVimConnectionInfo(); + final String vimId = createVimId(tenant.getCloudOwner(), tenant.getRegionName()); + vnfInstancesVimConnectionInfo.setId(vimId); + vnfInstancesVimConnectionInfo.setVimId(vimId); + vnfInstancesVimConnectionInfo.setVimType(esrSystemInfo.getType()); + vnfInstancesVimConnectionInfo.setInterfaceInfo(getInterfaceInfo(esrSystemInfo.getServiceUrl())); + vnfInstancesVimConnectionInfo.setAccessInfo(getAccessInfo(esrSystemInfo, tenant.getTenantId())); + return vnfInstancesVimConnectionInfo; + } + + private InterfaceInfo getInterfaceInfo(final String url) { + final InterfaceInfo interfaceInfo = new InterfaceInfo(); + interfaceInfo.setIdentityEndPoint(url); + return interfaceInfo; + } + + private AccessInfo getAccessInfo(final EsrSystemInfo esrSystemInfo, final String tenantId) { + final AccessInfo accessInfo = new AccessInfo(); + accessInfo.setProjectId(tenantId); + accessInfo.setDomainName(esrSystemInfo.getCloudDomain()); + + final VimCredentials vimCredentials = new VimCredentials(); + vimCredentials.setUsername(esrSystemInfo.getUserName()); + vimCredentials.setPassword(esrSystemInfo.getPassword()); + accessInfo.setCredentials(vimCredentials); + return accessInfo; + } + + private String createVimId(final String cloudOwner, final String cloudRegion) { + return cloudOwner + SEPARATOR + cloudRegion; + } + + private JsonObject getAdditionalParametersAsJsonObject(final Map additionalParameters) { + final JsonObject additionalParametersJsonObject = new JsonObject(); + if (additionalParameters != null) { + for (final Map.Entry item : new Gson().toJsonTree(additionalParameters) + .getAsJsonObject().entrySet()) { + additionalParametersJsonObject.add(item.getKey(), item.getValue()); + } + } else { + logger.warn("No additional parameters were specified for the operation"); + } + return additionalParametersJsonObject; + } + + private List getExternalVirtualLinks( + final List extVirtualLinks) { + if (extVirtualLinks != null) { + final String extVirtualLinksJsonObject = + new Gson().toJson(extVirtualLinks, new TypeToken>() {}.getType()); + return new Gson().fromJson(extVirtualLinksJsonObject, + new TypeToken>() {}.getType()); + } + return null; + } + + /** + * Create a {@link LccnSubscriptionRequest} to send in an notification subscription request to a VNFM. + * + * @param the ID of the VNF notifications are required for + * @return the request + * @throws GeneralSecurityException + */ + public LccnSubscriptionRequest createNotificationSubscriptionRequest(final String vnfId) + throws GeneralSecurityException { + final LccnSubscriptionRequest lccnSubscriptionRequest = new LccnSubscriptionRequest(); + lccnSubscriptionRequest.setAuthentication(getSubscriptionsAuthentication()); + lccnSubscriptionRequest.setCallbackUri(vnfmAdapterUrlProvider.getVnfLcmOperationOccurrenceNotificationUrl()); + final SubscriptionsFilter filter = new SubscriptionsFilter(); + filter.addNotificationTypesItem(NotificationTypesEnum.VNFLCMOPERATIONOCCURRENCENOTIFICATION); + final SubscriptionsFilterVnfInstanceSubscriptionFilter vnfInstanceSubscriptionFilter = + new SubscriptionsFilterVnfInstanceSubscriptionFilter(); + vnfInstanceSubscriptionFilter.addVnfInstanceIdsItem(vnfId); + filter.setVnfInstanceSubscriptionFilter(vnfInstanceSubscriptionFilter); + lccnSubscriptionRequest.setFilter(filter); + return lccnSubscriptionRequest; + } + + private SubscriptionsAuthentication getSubscriptionsAuthentication() throws GeneralSecurityException { + final SubscriptionsAuthentication authentication = new SubscriptionsAuthentication(); + + final ImmutablePair decrypedAuth = vnfmAdapterUrlProvider.getDecryptAuth(); + + final SubscriptionsAuthenticationParamsOauth2ClientCredentials oauthParams = + new SubscriptionsAuthenticationParamsOauth2ClientCredentials(); + oauthParams.setTokenEndpoint(vnfmAdapterUrlProvider.getOauthTokenUrl()); + oauthParams.clientId(decrypedAuth.getLeft()); + oauthParams.setClientPassword(decrypedAuth.getRight()); + authentication.addAuthTypeItem(AuthTypeEnum.OAUTH2_CLIENT_CREDENTIALS); + authentication.paramsOauth2ClientCredentials(oauthParams); + + final SubscriptionsAuthenticationParamsBasic basicAuthParams = new SubscriptionsAuthenticationParamsBasic(); + basicAuthParams.setUserName(decrypedAuth.getLeft()); + basicAuthParams.setPassword(decrypedAuth.getRight()); + authentication.addAuthTypeItem(AuthTypeEnum.BASIC); + authentication.paramsBasic(basicAuthParams); + + authentication.addAuthTypeItem(AuthTypeEnum.TLS_CERT); + return authentication; + } + + /** + * Get the VIM connections for a tenant + * + * @param tenant the tenant + * @return the VIM connections + */ + public InlineResponse201VimConnections getVimConnections(final Tenant tenant) { + final EsrSystemInfo esrSystemInfo = + aaiServiceProvider.invokeGetCloudRegionEsrSystemInfoList(tenant.getCloudOwner(), tenant.getRegionName()) + .getEsrSystemInfo().iterator().next(); + + final InlineResponse201VimConnections vimConnection = new InlineResponse201VimConnections(); + vimConnection.setId(createVimId(tenant.getCloudOwner(), tenant.getRegionName())); + vimConnection.setVimId(vimConnection.getId()); + vimConnection.setVimType(esrSystemInfo.getType()); + vimConnection.setInterfaceInfo(getInterfaceInfo(esrSystemInfo.getServiceUrl())); + vimConnection.setAccessInfo(getAccessInfo(esrSystemInfo, tenant.getTenantId())); + return vimConnection; + } + + +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/vnfm/VnfmServiceProvider.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/vnfm/VnfmServiceProvider.java new file mode 100644 index 0000000000..a6c6740235 --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/vnfm/VnfmServiceProvider.java @@ -0,0 +1,104 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm; + +import org.onap.aai.domain.yang.EsrVnfm; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.CreateVnfRequest; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.InlineResponse200; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.InlineResponse2001; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.InlineResponse201; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.InstantiateVnfRequest; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.LccnSubscriptionRequest; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.TerminateVnfRequest; +import com.google.common.base.Optional; + +/** + * Provides methods for invoking REST calls to a VNFM. + */ +public interface VnfmServiceProvider { + + /** + * Invoke a get request for a VNF. + * + * @param vnfm the VNFM in AAI + * @param vnfSelfLink the link to the VNF in the VNFM + * @return the VNF from the VNFM + */ + Optional getVnf(final EsrVnfm vnfm, final String vnfSelfLink); + + /** + * Invoke an instantiate request for a VNF. + * + * @param vnfm the VNFM in AAI + * @param vnfSelfLink the link to he VNF on the VNFM + * @param instantiateVnfRequest the instantiate request + * @return the operation ID of the instantiation operation + */ + String instantiateVnf(final EsrVnfm vnfm, final String vnfSelfLink, + final InstantiateVnfRequest instantiateVnfRequest); + + /** + * Invoke a notification subscription request to a VNFM. + * + * @param vnfm the VNFM in AAI + * @param subscriptionRequest + * @return the response to the subscription request + */ + InlineResponse2001 subscribeForNotifications(final EsrVnfm vnfm, final LccnSubscriptionRequest subscriptionRequest); + + /** + * Invoke a terminate request for a VNF. + * + * @param vnfm the VNFM in AAI + * @param vnfSelfLink the link to he VNF on the VNFM + * @param terminateVnfRequest the terminate request + * @return the operation ID of the termination operation + */ + String terminateVnf(final EsrVnfm vnfm, final String vnfSelfLink, final TerminateVnfRequest terminateVnfRequest); + + /** + * Invoke a delete request for a VNF. + * + * @param vnfm the VNFM in AAI + * @param vnfSelfLink the link to he VNF on the VNFM + * @return the operation ID of the instantiation operation + */ + void deleteVnf(final EsrVnfm vnfm, final String vnfSelfLink); + + /** + * Invoke a get request for a VNFM operation. + * + * @param vnfm the VNFM in AAI + * @param operationId the id of the operation on the VNFM + * @return the operation from the VNFM + */ + Optional getOperation(final EsrVnfm vnfm, final String operationId); + + /** + * Invoke a create request to a VNFM + * + * @param vnfm the VNFM in AAI + * @param createVnfRequest the parameters for creating a VNF + * @return the newly created VNF + */ + Optional createVnf(final EsrVnfm vnfm, final CreateVnfRequest createVnfRequest); + +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/vnfm/VnfmServiceProviderConfiguration.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/vnfm/VnfmServiceProviderConfiguration.java new file mode 100644 index 0000000000..e35dafb4ea --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/vnfm/VnfmServiceProviderConfiguration.java @@ -0,0 +1,154 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm; + +import static org.onap.so.client.RestTemplateConfig.CONFIGURABLE_REST_TEMPLATE; +import java.io.IOException; +import java.security.KeyManagementException; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.UnrecoverableKeyException; +import java.security.cert.CertificateException; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import javax.net.ssl.SSLContext; +import org.apache.commons.lang3.StringUtils; +import org.apache.http.client.HttpClient; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.ssl.SSLContextBuilder; +import org.onap.aai.domain.yang.EsrSystemInfo; +import org.onap.aai.domain.yang.EsrVnfm; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.AbstractServiceProviderConfiguration; +import org.onap.so.configuration.rest.BasicHttpHeadersProvider; +import org.onap.so.rest.service.HttpRestServiceProvider; +import org.onap.so.rest.service.HttpRestServiceProviderImpl; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.io.Resource; +import org.springframework.http.client.BufferingClientHttpRequestFactory; +import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; +import org.springframework.security.oauth2.client.OAuth2RestTemplate; +import org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsResourceDetails; +import org.springframework.web.client.RestTemplate; + +/** + * Configures the HttpRestServiceProvider for REST call to a VNFM. + */ +@Configuration +public class VnfmServiceProviderConfiguration extends AbstractServiceProviderConfiguration { + + private static final Logger logger = LoggerFactory.getLogger(VnfmServiceProviderConfiguration.class); + private final Map mapOfVnfmIdToHttpRestServiceProvider = new ConcurrentHashMap<>(); + + @Value("${http.client.ssl.trust-store:#{null}}") + private Resource trustStore; + @Value("${http.client.ssl.trust-store-password:#{null}}") + private String trustStorePassword; + + @Value("${server.ssl.key-store:#{null}}") + private Resource keyStoreResource; + @Value("${server.ssl.key--store-password:#{null}}") + private String keyStorePassword; + + /** + * This property is only intended to be temporary until the AAI schema is updated to support setting the endpoint + */ + @Value("${vnfmadapter.temp.vnfm.oauth.endpoint:#{null}}") + private String oauthEndpoint; + + @Qualifier(CONFIGURABLE_REST_TEMPLATE) + @Autowired + private RestTemplate defaultRestTemplate; + + public HttpRestServiceProvider getHttpRestServiceProvider(final EsrVnfm vnfm) { + if (!mapOfVnfmIdToHttpRestServiceProvider.containsKey(vnfm.getVnfmId())) { + mapOfVnfmIdToHttpRestServiceProvider.put(vnfm.getVnfmId(), createHttpRestServiceProvider(vnfm)); + } + return mapOfVnfmIdToHttpRestServiceProvider.get(vnfm.getVnfmId()); + } + + private HttpRestServiceProvider createHttpRestServiceProvider(final EsrVnfm vnfm) { + final RestTemplate restTemplate = createRestTemplate(vnfm); + setGsonMessageConverter(restTemplate); + if (trustStore != null) { + setTrustStore(restTemplate); + } + return new HttpRestServiceProviderImpl(restTemplate, new BasicHttpHeadersProvider().getHttpHeaders()); + } + + private RestTemplate createRestTemplate(final EsrVnfm vnfm) { + if (vnfm != null) { + for (final EsrSystemInfo esrSystemInfo : vnfm.getEsrSystemInfoList().getEsrSystemInfo()) { + if (!StringUtils.isEmpty(esrSystemInfo.getUserName()) + && !StringUtils.isEmpty(esrSystemInfo.getPassword())) { + return createOAuth2RestTemplate(esrSystemInfo); + } + } + } + return defaultRestTemplate; + } + + private OAuth2RestTemplate createOAuth2RestTemplate(final EsrSystemInfo esrSystemInfo) { + logger.debug("Getting OAuth2RestTemplate ..."); + final ClientCredentialsResourceDetails resourceDetails = new ClientCredentialsResourceDetails(); + resourceDetails.setId(UUID.randomUUID().toString()); + resourceDetails.setClientId(esrSystemInfo.getUserName()); + resourceDetails.setClientSecret(esrSystemInfo.getPassword()); + resourceDetails.setAccessTokenUri( + oauthEndpoint == null ? esrSystemInfo.getServiceUrl().replace("vnflcm/v1", "oauth/token") + : oauthEndpoint); + resourceDetails.setGrantType("client_credentials"); + return new OAuth2RestTemplate(resourceDetails); + } + + private void setTrustStore(final RestTemplate restTemplate) { + SSLContext sslContext; + try { + if (keyStoreResource != null) { + final KeyStore keystore = KeyStore.getInstance("pkcs12"); + keystore.load(keyStoreResource.getInputStream(), keyStorePassword.toCharArray()); + sslContext = + new SSLContextBuilder().loadTrustMaterial(trustStore.getURL(), trustStorePassword.toCharArray()) + .loadKeyMaterial(keystore, keyStorePassword.toCharArray()).build(); + } else { + sslContext = new SSLContextBuilder() + .loadTrustMaterial(trustStore.getURL(), trustStorePassword.toCharArray()).build(); + } + logger.info("Setting truststore: {}", trustStore.getURL()); + final SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext); + final HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); + final HttpComponentsClientHttpRequestFactory factory = + new HttpComponentsClientHttpRequestFactory(httpClient); + restTemplate.setRequestFactory(new BufferingClientHttpRequestFactory(factory)); + } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException | CertificateException + | IOException | UnrecoverableKeyException exception) { + logger.error("Error reading truststore, TLS connection to VNFM will fail.", exception); + } + } + +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/vnfm/VnfmServiceProviderImpl.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/vnfm/VnfmServiceProviderImpl.java new file mode 100644 index 0000000000..6ad5c16e4c --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/vnfm/VnfmServiceProviderImpl.java @@ -0,0 +1,194 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm; + +import org.onap.aai.domain.yang.EsrVnfm; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.CreateVnfRequest; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.InlineResponse200; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.InlineResponse2001; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.InlineResponse201; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.InlineResponse201.InstantiationStateEnum; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.InstantiateVnfRequest; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.LccnSubscriptionRequest; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.TerminateVnfRequest; +import org.onap.so.adapters.etsisol003adapter.lcm.jobmanagement.JobManager; +import org.onap.so.adapters.etsisol003adapter.lcm.rest.exceptions.VnfmRequestFailureException; +import org.onap.so.rest.exceptions.RestProcessingException; +import org.onap.so.rest.service.HttpRestServiceProvider; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; +import com.google.common.base.Optional; + +@Service +public class VnfmServiceProviderImpl implements VnfmServiceProvider { + private static final Logger logger = LoggerFactory.getLogger(VnfmServiceProviderImpl.class); + + private final VnfmServiceProviderConfiguration vnfmServiceProviderConfiguration; + private final VnfmUrlProvider urlProvider; + + @Autowired + public VnfmServiceProviderImpl(final VnfmUrlProvider urlProvider, + final VnfmServiceProviderConfiguration vnfmServiceProviderConfiguration) { + this.vnfmServiceProviderConfiguration = vnfmServiceProviderConfiguration; + this.urlProvider = urlProvider; + } + + @Override + public Optional getVnf(final EsrVnfm vnfm, final String vnfSelfLink) { + return getHttpServiceProvider(vnfm).get(vnfSelfLink, InlineResponse201.class); + } + + @Override + public String instantiateVnf(final EsrVnfm vnfm, final String vnfSelfLink, + final InstantiateVnfRequest instantiateVnfRequest) { + logger.debug("Sending instantiate request " + instantiateVnfRequest + " to : " + vnfSelfLink); + + ResponseEntity response = null; + try { + response = getHttpServiceProvider(vnfm).postHttpRequest(instantiateVnfRequest, vnfSelfLink + "/instantiate", + Void.class); + } catch (final Exception exception) { + final String errorMessage = + "Instantiate request to " + vnfSelfLink + " resulted in exception" + instantiateVnfRequest; + logger.error(errorMessage, exception); + throw new VnfmRequestFailureException(errorMessage, exception); + } + if (response.getStatusCode() != HttpStatus.ACCEPTED) { + final String errorMessage = "Instantiate request to " + vnfSelfLink + " returned status code: " + + response.getStatusCode() + ", request: " + instantiateVnfRequest; + logger.error(errorMessage); + throw new VnfmRequestFailureException(errorMessage); + } + final String locationHeader = response.getHeaders().get("Location").iterator().next(); + return locationHeader.substring(locationHeader.lastIndexOf("/") + 1); + } + + @Override + public InlineResponse2001 subscribeForNotifications(final EsrVnfm vnfm, + final LccnSubscriptionRequest subscriptionRequest) { + logger.info("Subscribing for notifications {}", subscriptionRequest); + final String url = urlProvider.getSubscriptionsUrl(vnfm.getVnfmId()); + ResponseEntity response = null; + try { + response = getHttpServiceProvider(vnfm).postHttpRequest(subscriptionRequest, url, InlineResponse2001.class); + logger.info("Subscribing for notifications response {}", response); + } catch (final Exception exception) { + final String errorMessage = + "Subscription to VNFM " + vnfm.getVnfmId() + " resulted in exception" + subscriptionRequest; + logger.error(errorMessage, exception); + throw new VnfmRequestFailureException(errorMessage, exception); + } + if (response.getStatusCode() != HttpStatus.CREATED) { + final String errorMessage = "Subscription to VNFM " + vnfm.getVnfmId() + " returned status code: " + + response.getStatusCode() + ", request: " + subscriptionRequest; + logger.error(errorMessage); + throw new VnfmRequestFailureException(errorMessage); + } + return response.getBody(); + } + + @Override + public String terminateVnf(final EsrVnfm vnfm, final String vnfSelfLink, + final TerminateVnfRequest terminateVnfRequest) { + logger.debug("Sending terminate request " + terminateVnfRequest + " to : " + vnfSelfLink); + + ResponseEntity response = null; + try { + response = getHttpServiceProvider(vnfm).postHttpRequest(terminateVnfRequest, vnfSelfLink + "/terminate", + Void.class); + } catch (final RestProcessingException restProcessingException) { + if (restProcessingException.getStatusCode() == HttpStatus.CONFLICT.value()) { + final InlineResponse201 vnf = getVnf(vnfm, vnfSelfLink).get(); + if (vnf.getInstantiationState().equals(InstantiationStateEnum.NOT_INSTANTIATED)) { + return JobManager.ALREADY_COMPLETED_OPERATION_ID; + } else { + final String errorMessage = + "Terminate request to " + vnfSelfLink + " resulted in exception" + terminateVnfRequest; + logger.error(errorMessage, restProcessingException); + throw new VnfmRequestFailureException(errorMessage, restProcessingException); + } + } + } catch (final Exception exception) { + final String errorMessage = + "Terminate request to " + vnfSelfLink + " resulted in exception" + terminateVnfRequest; + logger.error(errorMessage, exception); + throw new VnfmRequestFailureException(errorMessage, exception); + } + checkIfResponseIsAcceptable(response, vnfSelfLink, terminateVnfRequest); + final String locationHeader = response.getHeaders().get("Location").iterator().next(); + return locationHeader.substring(locationHeader.lastIndexOf("/") + 1); + } + + @Override + public void deleteVnf(final EsrVnfm vnfm, final String vnfSelfLink) { + logger.debug("Sending delete request to : " + vnfSelfLink); + final ResponseEntity response = getHttpServiceProvider(vnfm).deleteHttpRequest(vnfSelfLink, Void.class); + if (response.getStatusCode() != HttpStatus.NO_CONTENT) { + throw new VnfmRequestFailureException( + "Delete request to " + vnfSelfLink + " return status code: " + response.getStatusCode()); + } + } + + @Override + public Optional getOperation(final EsrVnfm vnfm, final String operationId) { + final String url = urlProvider.getOperationUrl(vnfm.getVnfmId(), operationId); + return getHttpServiceProvider(vnfm).get(url, InlineResponse200.class); + } + + @Override + public Optional createVnf(final EsrVnfm vnfm, final CreateVnfRequest createVnfRequest) { + final String url = urlProvider.getCreationUrl(vnfm.getVnfmId()); + logger.debug("Sending create request {} to : {}", createVnfRequest, url); + try { + return getHttpServiceProvider(vnfm).post(createVnfRequest, url, InlineResponse201.class); + } catch (final Exception exception) { + final String errorMessage = + "Create request to vnfm:" + vnfm.getVnfmId() + " resulted in exception" + createVnfRequest; + logger.error(errorMessage, exception); + throw new VnfmRequestFailureException(errorMessage, exception); + } + } + + private void checkIfResponseIsAcceptable(final ResponseEntity response, final String vnfSelfLink, + final TerminateVnfRequest terminateVnfRequest) { + if (response == null) { + final String errorMessage = + "Terminate request to " + vnfSelfLink + ", response is null, " + "request: " + terminateVnfRequest; + logger.error(errorMessage); + throw new VnfmRequestFailureException(errorMessage); + } + if (response.getStatusCode() != HttpStatus.ACCEPTED) { + final String errorMessage = "Terminate request to " + vnfSelfLink + ", returned status code: " + + response.getStatusCode() + ", request: " + terminateVnfRequest; + logger.error(errorMessage); + throw new VnfmRequestFailureException(errorMessage); + } + } + + private HttpRestServiceProvider getHttpServiceProvider(final EsrVnfm vnfm) { + return vnfmServiceProviderConfiguration.getHttpRestServiceProvider(vnfm); + } + +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/vnfm/VnfmUrlProvider.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/vnfm/VnfmUrlProvider.java new file mode 100644 index 0000000000..a9319c07fe --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/vnfm/VnfmUrlProvider.java @@ -0,0 +1,95 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm; + +import static org.slf4j.LoggerFactory.getLogger; +import java.net.URI; +import org.onap.aai.domain.yang.EsrSystemInfo; +import org.onap.aai.domain.yang.EsrSystemInfoList; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.aai.AaiServiceProvider; +import org.onap.so.adapters.etsisol003adapter.lcm.rest.exceptions.VnfmNotFoundException; +import org.slf4j.Logger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.web.util.UriComponentsBuilder; + +/** + * Provides URLs for REST calls to a VNFM. + */ +@Service +public class VnfmUrlProvider { + + private static Logger logger = getLogger(VnfmUrlProvider.class); + private final AaiServiceProvider aaiServiceProvider; + + @Autowired + public VnfmUrlProvider(final AaiServiceProvider aaiServiceProvider) { + this.aaiServiceProvider = aaiServiceProvider; + } + + /** + * Get the URL for an operation on a VNFM. + * + * @param vnfmId The ID of the VNFM + * @return the URL of the operation + */ + public String getOperationUrl(final String vnfmId, final String operationId) { + final String url = UriComponentsBuilder.fromUri(getBaseUri(vnfmId)).pathSegment("vnf_lcm_op_occs") + .pathSegment(operationId).build().toString(); + logger.debug("getOperationUrl:" + url); + + return url; + } + + /** + * Get the URL for the subscriptions on a VNFM. + * + * @param vnfmId The ID of the VNFM + * @return the URL of the subscriptions + */ + public String getSubscriptionsUrl(final String vnfmId) { + final String url = + UriComponentsBuilder.fromUri(getBaseUri(vnfmId)).pathSegment("subscriptions").build().toString(); + logger.debug("getSubscriptionUrl:" + url); + + return url; + } + + public String getCreationUrl(final String vnfmId) { + final String url = + UriComponentsBuilder.fromUri(getBaseUri(vnfmId)).pathSegment("vnf_instances").build().toString(); + logger.debug("getCreationUrl:" + url); + + return url; + } + + private URI getBaseUri(final String vnfmId) { + final EsrSystemInfoList vnfmEsrSystemInfoList = aaiServiceProvider.invokeGetVnfmEsrSystemInfoList(vnfmId); + + if (vnfmEsrSystemInfoList != null) { + for (final EsrSystemInfo esrSystemInfo : vnfmEsrSystemInfoList.getEsrSystemInfo()) { + return UriComponentsBuilder.fromHttpUrl(esrSystemInfo.getServiceUrl()).build().toUri(); + } + } + + throw new VnfmNotFoundException("VNFM, or Service URL for VNFM, not found for VNFM " + vnfmId); + } +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/jobmanagement/JobManager.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/jobmanagement/JobManager.java new file mode 100644 index 0000000000..5ac0179176 --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/jobmanagement/JobManager.java @@ -0,0 +1,174 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.lcm.jobmanagement; + +import static org.slf4j.LoggerFactory.getLogger; +import java.util.Map; +import java.util.UUID; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.aai.AaiServiceProvider; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.VnfmServiceProvider; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.InlineResponse200; +import org.onap.so.adapters.etsisol003adapter.lcm.rest.exceptions.JobNotFoundException; +import org.onap.so.adapters.etsisol003adapter.lcm.v1.model.OperationEnum; +import org.onap.so.adapters.etsisol003adapter.lcm.v1.model.OperationStateEnum; +import org.onap.so.adapters.etsisol003adapter.lcm.v1.model.OperationStatusRetrievalStatusEnum; +import org.onap.so.adapters.etsisol003adapter.lcm.v1.model.QueryJobResponse; +import org.onap.so.rest.exceptions.HttpResouceNotFoundException; +import org.slf4j.Logger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import com.google.common.base.Optional; +import com.google.common.collect.Maps; + +/** + * Manages jobs enabling the status of jobs to be queried. A job is associated with an operation on a VNFM. + */ +@Component +public class JobManager { + public static final String ALREADY_COMPLETED_OPERATION_ID = "alreadyCompleted"; + private static final String SEPARATOR = "_"; + private static Logger logger = getLogger(JobManager.class); + private final Map mapOfJobIdToVnfmOperation = Maps.newConcurrentMap(); + private final VnfmServiceProvider vnfmServiceProvider; + private final AaiServiceProvider aaiServiceProvider; + + @Autowired + JobManager(final VnfmServiceProvider vnfmServiceProvider, final AaiServiceProvider aaiServiceProvider) { + this.vnfmServiceProvider = vnfmServiceProvider; + this.aaiServiceProvider = aaiServiceProvider; + } + + /** + * Create a job associated with an operation on a VNFM. + * + * @param vnfmId the VNFM the operation relates to + * @param operationId the ID of the associated VNFM operation + * @param waitForNotificationForSuccess if set to true 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)} + */ + public String createJob(final String vnfmId, final String operationId, + final boolean waitForNotificationForSuccess) { + final String jobId = vnfmId + SEPARATOR + UUID.randomUUID().toString(); + final VnfmOperation vnfmOperation = new VnfmOperation(vnfmId, operationId, waitForNotificationForSuccess); + mapOfJobIdToVnfmOperation.put(jobId, vnfmOperation); + return jobId; + } + + /** + * 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 null of no operation is associated with the given + * job ID + */ + public QueryJobResponse getVnfmOperation(final String jobId) { + final VnfmOperation vnfmOperation = mapOfJobIdToVnfmOperation.get(jobId); + final QueryJobResponse response = new QueryJobResponse(); + + if (vnfmOperation == null) { + throw new JobNotFoundException("No job found with ID: " + jobId); + } + + if (vnfmOperation.getOperationId().equals(ALREADY_COMPLETED_OPERATION_ID)) { + response.setOperationStatusRetrievalStatus(OperationStatusRetrievalStatusEnum.STATUS_FOUND); + return response.operationState(OperationStateEnum.COMPLETED); + } + + if (vnfmOperation.isVnfDeleted()) { + response.setOperationStatusRetrievalStatus(OperationStatusRetrievalStatusEnum.STATUS_FOUND); + return response.operationState(getOperationState(vnfmOperation, null)); + } + + try { + final Optional operationOptional = vnfmServiceProvider.getOperation( + aaiServiceProvider.invokeGetVnfm(vnfmOperation.getVnfmId()), vnfmOperation.getOperationId()); + + if (!operationOptional.isPresent()) { + return response.operationStatusRetrievalStatus(OperationStatusRetrievalStatusEnum.OPERATION_NOT_FOUND); + } + final InlineResponse200 operation = operationOptional.get(); + + logger.debug("Job Id: {} operationId: {} operation details: {} ", jobId, operation.getId(), operation); + + if (operation.getOperationState() == null) { + return response.operationStatusRetrievalStatus(OperationStatusRetrievalStatusEnum.WAITING_FOR_STATUS); + } + + response.setOperationStatusRetrievalStatus(OperationStatusRetrievalStatusEnum.STATUS_FOUND); + response.setId(operation.getId()); + response.setOperation(OperationEnum.fromValue(operation.getOperation().getValue())); + response.setOperationState(getOperationState(vnfmOperation, operation)); + response.setStartTime(operation.getStartTime()); + response.setStateEnteredTime(operation.getStateEnteredTime()); + response.setVnfInstanceId(operation.getVnfInstanceId()); + + return response; + } catch (final HttpResouceNotFoundException exception) { + logger.error("Exception encountered trying to get operation status for operation id " + + vnfmOperation.getOperationId(), exception); + return response.operationStatusRetrievalStatus(OperationStatusRetrievalStatusEnum.WAITING_FOR_STATUS); + } + } + + private OperationStateEnum getOperationState(final VnfmOperation vnfmOperation, + final InlineResponse200 operationResponse) { + switch (vnfmOperation.getNotificationStatus()) { + case NOTIFICATION_PROCESSING_PENDING: + return org.onap.so.adapters.etsisol003adapter.lcm.v1.model.OperationStateEnum.PROCESSING; + case NOTIFICATION_PROCEESING_SUCCESSFUL: + return org.onap.so.adapters.etsisol003adapter.lcm.v1.model.OperationStateEnum.COMPLETED; + case NOTIFICATION_PROCESSING_FAILED: + return org.onap.so.adapters.etsisol003adapter.lcm.v1.model.OperationStateEnum.FAILED; + default: + if (operationResponse == null || operationResponse.getOperationState() == null) + return null; + return OperationStateEnum.fromValue(operationResponse.getOperationState().getValue()); + } + } + + public void notificationProcessedForOperation(final String operationId, + final boolean notificationProcessingWasSuccessful) { + logger.debug("Notification processed for operation ID {} success?: {}", operationId, + notificationProcessingWasSuccessful); + final java.util.Optional relatedOperation = mapOfJobIdToVnfmOperation.values().stream() + .filter(operation -> operation.getOperationId().equals(operationId)).findFirst(); + if (relatedOperation.isPresent()) { + relatedOperation.get().setNotificationProcessed(notificationProcessingWasSuccessful); + } else { + logger.debug("No operation found for operation ID {} ", operationId); + + } + } + + public void vnfDeleted(final String operationId) { + logger.debug("VNF deleyed for operation ID {}", operationId); + final java.util.Optional relatedOperation = mapOfJobIdToVnfmOperation.values().stream() + .filter(operation -> operation.getOperationId().equals(operationId)).findFirst(); + if (relatedOperation.isPresent()) { + relatedOperation.get().setVnfDeleted(); + } else { + logger.debug("No operation found for operation ID {} ", operationId); + } + } + +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/jobmanagement/VnfmOperation.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/jobmanagement/VnfmOperation.java new file mode 100644 index 0000000000..8cb9197d44 --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/jobmanagement/VnfmOperation.java @@ -0,0 +1,122 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.lcm.jobmanagement; + +/** + * Represents an operation on a VNFM. + */ +public class VnfmOperation { + + private final String vnfmId; + private final String operationId; + private NotificationStatus notificationStatus; + private boolean vnfDeleted; + + public VnfmOperation(final String vnfmId, final String operationId, final boolean waitForNotificationForSuccess) { + this.vnfmId = vnfmId; + this.operationId = operationId; + this.notificationStatus = waitForNotificationForSuccess ? NotificationStatus.NOTIFICATION_PROCESSING_PENDING + : NotificationStatus.NOTIFICATION_PROCESSING_NOT_REQUIRED; + } + + /** + * Get the ID of the operation on the VNFM. + * + * @return the ID of the operation on the VNFM + */ + public String getOperationId() { + return operationId; + } + + /** + * Get the ID of the VNFM the operation is carried out by. + * + * @return the ID of the VNFM + */ + public String getVnfmId() { + return vnfmId; + } + + /** + * Set the required notification has been processed for the operation. + * + * @param notificationProcessingWasSuccessful true if the notification processing was successful, + * false otherwise + */ + public void setNotificationProcessed(final boolean notificationProcessingWasSuccessful) { + this.notificationStatus = + notificationProcessingWasSuccessful ? NotificationStatus.NOTIFICATION_PROCEESING_SUCCESSFUL + : NotificationStatus.NOTIFICATION_PROCESSING_FAILED; + } + + /** + * Get the notification status for the operation. + * + * @return the notification status + */ + public NotificationStatus getNotificationStatus() { + return notificationStatus; + } + + /** + * Set the VNF has been deleted from the VNFM. + */ + public void setVnfDeleted() { + this.vnfDeleted = true; + } + + /** + * Check if the VNF has been deleted from the VNFM + * + * @return true of the VNF has been deleted from the VNFM, false otherwise + */ + public boolean isVnfDeleted() { + return vnfDeleted; + } + + + public enum NotificationStatus { + /** + * No notification handling is required to determine the status of the operation + */ + NOTIFICATION_PROCESSING_NOT_REQUIRED, + /** + * A notification must be processed before the notification can be considered to be completed + */ + NOTIFICATION_PROCESSING_PENDING, + /** + * A notification has been successfully handled for the operation + */ + NOTIFICATION_PROCEESING_SUCCESSFUL, + /** + * An error occurred processing a notification for the operation + */ + NOTIFICATION_PROCESSING_FAILED; + } + + @Override + public String toString() { + return "VnfmOperation [vnfmId=" + vnfmId + ", operationId=" + operationId + ", notificationStatus=" + + notificationStatus + "]"; + } + + +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/lifecycle/LifecycleManager.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/lifecycle/LifecycleManager.java new file mode 100644 index 0000000000..8ba56c5051 --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/lifecycle/LifecycleManager.java @@ -0,0 +1,265 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.lcm.lifecycle; + +import java.util.Map; +import org.onap.aai.domain.yang.EsrVnfm; +import org.onap.aai.domain.yang.GenericVnf; +import org.onap.aai.domain.yang.Relationship; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.SdcPackageProvider; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.aai.AaiHelper; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.aai.AaiServiceProvider; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.aai.OamIpAddressSource; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.aai.OamIpAddressSource.OamIpAddressType; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.VnfmHelper; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.VnfmServiceProvider; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.InlineResponse201; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.InstantiateVnfRequest; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.LccnSubscriptionRequest; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.TerminateVnfRequest; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.TerminateVnfRequest.TerminationTypeEnum; +import org.onap.so.adapters.etsisol003adapter.lcm.jobmanagement.JobManager; +import org.onap.so.adapters.etsisol003adapter.lcm.rest.exceptions.VnfNotFoundException; +import org.onap.so.adapters.etsisol003adapter.lcm.rest.exceptions.VnfmNotFoundException; +import org.onap.so.adapters.etsisol003adapter.lcm.rest.exceptions.VnfmRequestFailureException; +import org.onap.so.adapters.etsisol003adapter.lcm.v1.model.CreateVnfRequest; +import org.onap.so.adapters.etsisol003adapter.lcm.v1.model.CreateVnfResponse; +import org.onap.so.adapters.etsisol003adapter.lcm.v1.model.DeleteVnfResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import com.google.common.base.Optional; + +/** + * Manages lifecycle operations towards the VNFMs. + */ +@Component +public class LifecycleManager { + private static final Logger logger = LoggerFactory.getLogger(LifecycleManager.class); + private final AaiServiceProvider aaiServiceProvider; + private final VnfmServiceProvider vnfmServiceProvider; + private final AaiHelper aaiHelper; + private final VnfmHelper vnfmHelper; + private final JobManager jobManager; + private final SdcPackageProvider packageProvider; + + @Autowired + LifecycleManager(final AaiServiceProvider aaiServiceProvider, final AaiHelper aaiHelper, + final VnfmHelper vnfmHelper, final VnfmServiceProvider vnfmServiceProvider, final JobManager jobManager, + final SdcPackageProvider packageProvider) { + this.aaiServiceProvider = aaiServiceProvider; + this.vnfmServiceProvider = vnfmServiceProvider; + this.aaiHelper = aaiHelper; + this.vnfmHelper = vnfmHelper; + this.jobManager = jobManager; + this.packageProvider = packageProvider; + } + + /** + * Create a VNF on a VNFM. + * + * @param vnfIdInAai the ID of the VNF in AAI + * @param request the create request + * @return the response to the request + */ + public CreateVnfResponse createVnf(final String vnfIdInAai, final CreateVnfRequest request) { + final GenericVnf genericVnf = getGenericVnfFromAai(vnfIdInAai); + EsrVnfm vnfm = aaiHelper.getAssignedVnfm(genericVnf); + checkIfVnfAlreadyExistsInVnfm(vnfm, genericVnf); + + if (vnfm == null) { + vnfm = aaiHelper.selectVnfm(genericVnf); + aaiServiceProvider.invokePutGenericVnfToVnfmRelationship(genericVnf, vnfm.getVnfmId()); + } + final InlineResponse201 vnfmResponse = sendCreateRequestToVnfm(request, genericVnf, vnfIdInAai, vnfm); + + logger.info("Create response: {}", vnfmResponse); + + genericVnf.setSelflink(getSelfLink(vnfmResponse, vnfm)); + + final GenericVnf genericVnfPatch = new GenericVnf(); + genericVnfPatch.setVnfId(genericVnf.getVnfId()); + genericVnfPatch.setSelflink(genericVnf.getSelflink()); + aaiServiceProvider.invokePatchGenericVnf(genericVnfPatch); + + final String vnfIdInVnfm = vnfmResponse.getId(); + + final OamIpAddressSource oamIpAddressSource = extractOamIpAddressSource(request); + aaiHelper.setOamIpAddressSource(vnfIdInVnfm, oamIpAddressSource); + + createNotificationSubscription(vnfm, vnfIdInVnfm); + final String operationId = sendInstantiateRequestToVnfm(vnfm, genericVnf, request); + + final String jobId = jobManager.createJob(vnfm.getVnfmId(), operationId, false); + final CreateVnfResponse response = new CreateVnfResponse(); + response.setJobId(jobId); + return response; + } + + private String getSelfLink(final InlineResponse201 vnfmResponse, final EsrVnfm vnfm) { + if (vnfmResponse.getLinks() != null && vnfmResponse.getLinks().getSelf() != null + && vnfmResponse.getLinks().getSelf().getHref() != null) { + return vnfmResponse.getLinks().getSelf().getHref(); + } + return vnfm.getEsrSystemInfoList().getEsrSystemInfo().iterator().next().getServiceUrl() + "/vnf_instances/" + + vnfmResponse.getId(); + } + + private OamIpAddressSource extractOamIpAddressSource(final CreateVnfRequest request) { + final Map additionalParams = request.getAdditionalParams(); + try { + final String sourceType = additionalParams.remove("oamIpAddressSourceType"); + final String sourceValue = additionalParams.remove("oamIpAddressSourceValue"); + final OamIpAddressType oamIpAddressType = OamIpAddressType.valueOf(sourceType.toUpperCase()); + return new OamIpAddressSource(oamIpAddressType, sourceValue); + } catch (final NullPointerException | IllegalArgumentException exception) { + logger.debug("Additional Params not set for OAM IP address source", exception); + return null; + } + } + + private void checkIfVnfAlreadyExistsInVnfm(final EsrVnfm vnfm, final GenericVnf genericVnf) { + if (genericVnf.getSelflink() != null && !genericVnf.getSelflink().isEmpty() && vnfm != null) { + Optional response = Optional.absent(); + try { + response = vnfmServiceProvider.getVnf(vnfm, genericVnf.getSelflink()); + } catch (final Exception exception) { + logger.debug("Ignoring invalid self link in generic vnf", exception); + } + if (response.isPresent()) { + throw new IllegalArgumentException("VNF " + genericVnf.getVnfId() + + " is already defined on the VNFM, self link: " + genericVnf.getSelflink()); + } + } + } + + private InlineResponse201 sendCreateRequestToVnfm(final CreateVnfRequest aaiRequest, final GenericVnf genericVnf, + final String vnfIdInAai, final EsrVnfm vnfm) { + logger.debug("Sending a create request to SVNFM " + aaiRequest); + final org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.CreateVnfRequest vnfmRequest = + new org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.CreateVnfRequest(); + + final String vnfdId = packageProvider.getVnfdId(genericVnf.getModelVersionId()); + vnfmRequest.setVnfdId(vnfdId); + vnfmRequest.setVnfInstanceName(aaiRequest.getName().replaceAll(" ", "_")); + vnfmRequest.setVnfInstanceDescription(vnfIdInAai); + + final Optional optionalResponse = vnfmServiceProvider.createVnf(vnfm, vnfmRequest); + + try { + return optionalResponse.get(); + } catch (final Exception exception) { + final String errorMessage = "Unable to return response from VNFM"; + logger.error(errorMessage, exception); + throw new VnfmRequestFailureException(errorMessage, exception); + } + } + + private void createNotificationSubscription(final EsrVnfm vnfm, final String vnfId) { + try { + final LccnSubscriptionRequest subscriptionRequest = vnfmHelper.createNotificationSubscriptionRequest(vnfId); + vnfmServiceProvider.subscribeForNotifications(vnfm, subscriptionRequest); + } catch (final Exception exception) { + logger.warn("Subscription for notifications to VNFM: " + vnfm.getVnfmId() + " for VNF " + vnfId + + " failed. AAI will not be updated unless the VNFM is configured by other means to send notifications relating to this VNF", + exception); + } + } + + private String sendInstantiateRequestToVnfm(final EsrVnfm vnfm, final GenericVnf genericVnf, + final CreateVnfRequest createVnfRequest) { + + final InstantiateVnfRequest instantiateVnfRequest = + vnfmHelper.createInstantiateRequest(createVnfRequest.getTenant(), createVnfRequest, + packageProvider.getFlavourId(genericVnf.getModelVersionId())); + final String jobId = vnfmServiceProvider.instantiateVnf(vnfm, genericVnf.getSelflink(), instantiateVnfRequest); + + logger.info("Instantiate VNF request successfully sent to " + genericVnf.getSelflink()); + return jobId; + } + + /** + * Delete a VNF on a VNFM. + * + * @param vnfIdInAai the ID of the VNF in AAI + * @return the response to the request + */ + public DeleteVnfResponse deleteVnf(final String vnfIdInAai) { + final GenericVnf genericVnf = getGenericVnfFromAai(vnfIdInAai); + final EsrVnfm vnfm = getAssignedVnfm(genericVnf); + + final String operationId = sendTerminateRequestToVnfm(vnfm, genericVnf); + + if (operationId.equals(JobManager.ALREADY_COMPLETED_OPERATION_ID)) { + sendDeleteRequestToVnfm(genericVnf); + } + final String jobId = jobManager.createJob(vnfm.getVnfmId(), operationId, true); + + return new DeleteVnfResponse().jobId(jobId); + } + + private String sendTerminateRequestToVnfm(final EsrVnfm vnfm, final GenericVnf genericVnf) { + final TerminateVnfRequest terminateVnfRequest = new TerminateVnfRequest(); + terminateVnfRequest.setTerminationType(TerminationTypeEnum.FORCEFUL); + return vnfmServiceProvider.terminateVnf(vnfm, genericVnf.getSelflink(), terminateVnfRequest); + } + + private GenericVnf getGenericVnfFromAai(final String vnfIdInAai) { + final GenericVnf genericVnf = aaiServiceProvider.invokeGetGenericVnf(vnfIdInAai); + if (genericVnf == null) { + throw new VnfNotFoundException("VNF not found in AAI: " + vnfIdInAai); + } + logger.debug("Retrieved generic VNF from AAI: " + genericVnf); + return genericVnf; + } + + private EsrVnfm getAssignedVnfm(final GenericVnf genericVnf) { + final EsrVnfm vnfm = aaiHelper.getAssignedVnfm(genericVnf); + if (vnfm == null) { + throw new VnfmNotFoundException("No VNFM found in AAI for VNF " + genericVnf.getVnfId()); + } + return vnfm; + } + + private void sendDeleteRequestToVnfm(final GenericVnf genericVnf) { + + vnfmServiceProvider.deleteVnf(aaiHelper.getAssignedVnfm(genericVnf), genericVnf.getSelflink()); + + final GenericVnf genericVnfPatch = new GenericVnf(); + genericVnfPatch.setVnfId(genericVnf.getVnfId()); + genericVnfPatch.setOrchestrationStatus("Assigned"); + genericVnfPatch.setSelflink(""); + aaiServiceProvider.invokePatchGenericVnf(genericVnfPatch); + + for (final Relationship relationship : genericVnf.getRelationshipList().getRelationship()) { + if (relationship.getRelatedTo().equals("vserver")) { + aaiServiceProvider.invokeDeleteVserver( + aaiHelper.getRelationshipData(relationship, "cloud-region.cloud-owner"), + aaiHelper.getRelationshipData(relationship, "cloud-region.cloud-region-id"), + aaiHelper.getRelationshipData(relationship, "tenant.tenant-id"), + aaiHelper.getRelationshipData(relationship, "vserver.vserver-id")); + } + } + + + } +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/notificationhandling/NotificationHandler.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/notificationhandling/NotificationHandler.java new file mode 100644 index 0000000000..f23fac8115 --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/notificationhandling/NotificationHandler.java @@ -0,0 +1,276 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.lcm.notificationhandling; + +import static org.slf4j.LoggerFactory.getLogger; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.json.JSONException; +import org.json.JSONObject; +import org.onap.aai.domain.yang.GenericVnf; +import org.onap.aai.domain.yang.Relationship; +import org.onap.aai.domain.yang.Vserver; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.aai.AaiHelper; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.aai.AaiServiceProvider; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.aai.OamIpAddressSource; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.aai.OamIpAddressSource.OamIpAddressType; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.VnfmServiceProvider; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.InlineResponse201; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.InlineResponse201VimConnectionInfo; +import org.onap.so.adapters.etsisol003adapter.lcm.jobmanagement.JobManager; +import org.onap.so.adapters.etsisol003adapter.lcm.lcn.model.LcnVnfLcmOperationOccurrenceNotificationAffectedVnfcs; +import org.onap.so.adapters.etsisol003adapter.lcm.lcn.model.LcnVnfLcmOperationOccurrenceNotificationAffectedVnfcs.ChangeTypeEnum; +import org.onap.so.adapters.etsisol003adapter.lcm.lcn.model.VnfLcmOperationOccurrenceNotification; +import org.onap.so.adapters.etsisol003adapter.lcm.lcn.model.VnfLcmOperationOccurrenceNotification.OperationStateEnum; +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. + */ +public class NotificationHandler implements Runnable { + private static Logger logger = getLogger(NotificationHandler.class); + private final VnfLcmOperationOccurrenceNotification vnfLcmOperationOccurrenceNotification; + private final AaiHelper aaiHelper; + private final AaiServiceProvider aaiServiceProvider; + private final VnfmServiceProvider vnfmServiceProvider; + private final JobManager jobManager; + private final InlineResponse201 vnfInstance; + + public NotificationHandler(final VnfLcmOperationOccurrenceNotification vnfLcmOperationOccurrenceNotification, + final AaiHelper aaiHelper, final AaiServiceProvider aaiServiceProvider, + final VnfmServiceProvider vnfmServiceProvider, final JobManager jobManager, + final InlineResponse201 vnfInstance) { + this.vnfLcmOperationOccurrenceNotification = vnfLcmOperationOccurrenceNotification; + this.aaiHelper = aaiHelper; + this.aaiServiceProvider = aaiServiceProvider; + this.vnfmServiceProvider = vnfmServiceProvider; + this.jobManager = jobManager; + this.vnfInstance = vnfInstance; + } + + @Override + public void run() { + try { + if (vnfLcmOperationOccurrenceNotification.getOperationState().equals(OperationStateEnum.COMPLETED)) { + switch (vnfLcmOperationOccurrenceNotification.getOperation()) { + case INSTANTIATE: + handleVnfInstantiate(); + break; + case TERMINATE: + handleVnfTerminate(); + break; + default: + } + } + } catch (final Exception exception) { + logger.error("Error encountered handling notification, AAI may not be updated correctly " + + vnfLcmOperationOccurrenceNotification, exception); + } + } + + private void handleVnfInstantiate() { + if (vnfLcmOperationOccurrenceNotification.getOperationState().equals(OperationStateEnum.COMPLETED)) { + handleVnfInstantiateCompleted(); + } + } + + private void handleVnfInstantiateCompleted() { + final GenericVnf genericVnf = aaiServiceProvider + .invokeQueryGenericVnf(vnfInstance.getLinks().getSelf().getHref()).getGenericVnf().get(0); + + final GenericVnf genericVnfPatch = new GenericVnf(); + genericVnfPatch.setVnfId(genericVnf.getVnfId()); + setOamIpAddress(genericVnfPatch, vnfInstance); + genericVnfPatch.setOrchestrationStatus("Created"); + aaiServiceProvider.invokePatchGenericVnf(genericVnfPatch); + + addVservers(vnfLcmOperationOccurrenceNotification, genericVnf.getVnfId(), vnfInstance.getVimConnectionInfo()); + + logger.debug("Finished handling notification for vnfm: " + vnfInstance.getId()); + } + + private void setOamIpAddress(final GenericVnf genericVnf, final InlineResponse201 vnfInstance) { + final OamIpAddressSource oamIpAddressSource = aaiHelper.getOamIpAddressSource(vnfInstance.getId()); + if (oamIpAddressSource == null) { + logger.warn("No source indicated for OAM IP address, no value will be set in AAI"); + return; + } + if (oamIpAddressSource.getType().equals(OamIpAddressType.LITERAL)) { + genericVnf.setIpv4OamAddress(oamIpAddressSource.getValue()); + } else { + try { + logger.debug("ConfigurableProperties: " + vnfInstance.getVnfConfigurableProperties()); + if (vnfInstance.getVnfConfigurableProperties() == null) { + logger.warn("No ConfigurableProperties, cannot set OAM IP Address"); + } + final JSONObject properties = new JSONObject((Map) vnfInstance.getVnfConfigurableProperties()); + genericVnf.setIpv4OamAddress(properties.get(oamIpAddressSource.getValue()).toString()); + } catch (final JSONException jsonException) { + logger.error("Error getting vnfIpAddress", jsonException); + } + } + } + + private void handleVnfTerminate() { + switch (vnfLcmOperationOccurrenceNotification.getOperationState()) { + case COMPLETED: + handleVnfTerminateCompleted(); + break; + case FAILED: + case ROLLING_BACK: + handleVnfTerminateFailed(); + break; + default: + } + } + + private void handleVnfTerminateFailed() { + try { + final GenericVnf genericVnf = aaiServiceProvider + .invokeQueryGenericVnf(vnfInstance.getLinks().getSelf().getHref()).getGenericVnf().get(0); + deleteVserversFromAai(vnfLcmOperationOccurrenceNotification, genericVnf); + } finally { + jobManager.notificationProcessedForOperation(vnfLcmOperationOccurrenceNotification.getVnfLcmOpOccId(), + false); + } + } + + private void handleVnfTerminateCompleted() { + GenericVnf genericVnf = null; + boolean vServersDeletedFromAai = false; + boolean identifierDeletedFromVnfm = false; + boolean genericVnfUpdated = false; + try { + genericVnf = aaiServiceProvider.invokeQueryGenericVnf(vnfInstance.getLinks().getSelf().getHref()) + .getGenericVnf().get(0); + vServersDeletedFromAai = deleteVserversFromAai(vnfLcmOperationOccurrenceNotification, genericVnf); + identifierDeletedFromVnfm = deleteVnfIdentifierOnVnfm(genericVnf); + genericVnfUpdated = patchVnfInAai(genericVnf.getVnfId(), "Assigned", identifierDeletedFromVnfm ? "" : null); + } finally { + jobManager.notificationProcessedForOperation(vnfLcmOperationOccurrenceNotification.getVnfLcmOpOccId(), + vServersDeletedFromAai && identifierDeletedFromVnfm && genericVnfUpdated); + jobManager.vnfDeleted(vnfLcmOperationOccurrenceNotification.getVnfLcmOpOccId()); + } + } + + private void addVservers(final VnfLcmOperationOccurrenceNotification notification, final String vnfId, + final List vnfInstancesVimConnectionInfo) { + final Map vimConnectionIdToVimConnectionInfo = new HashMap<>(); + for (final InlineResponse201VimConnectionInfo vimConnectionInfo : vnfInstancesVimConnectionInfo) { + vimConnectionIdToVimConnectionInfo.put(vimConnectionInfo.getId(), vimConnectionInfo); + } + + for (final LcnVnfLcmOperationOccurrenceNotificationAffectedVnfcs vnfc : notification.getAffectedVnfcs()) { + final InlineResponse201VimConnectionInfo vimConnectionInfo = + getVimConnectionInfo(vimConnectionIdToVimConnectionInfo, vnfc); + if (ChangeTypeEnum.ADDED.equals(vnfc.getChangeType())) { + final Vserver vserver = aaiHelper.createVserver(vnfc); + aaiServiceProvider.invokePutVserver(getCloudOwner(vimConnectionInfo), getCloudRegion(vimConnectionInfo), + getTenant(vimConnectionInfo), vserver); + + aaiServiceProvider.invokePutVserverToVnfRelationship(getCloudOwner(vimConnectionInfo), + getCloudRegion(vimConnectionInfo), getTenant(vimConnectionInfo), vserver, vnfId); + } + } + } + + private boolean deleteVserversFromAai(final VnfLcmOperationOccurrenceNotification notification, + final GenericVnf vnf) { + try { + for (final LcnVnfLcmOperationOccurrenceNotificationAffectedVnfcs vnfc : notification.getAffectedVnfcs()) { + if (ChangeTypeEnum.REMOVED.equals(vnfc.getChangeType())) { + + final Relationship relationshipToVserver = aaiHelper.deleteRelationshipWithDataValue(vnf, "vserver", + "vserver.vserver-id", vnfc.getComputeResource().getResourceId()); + + aaiServiceProvider.invokeDeleteVserver( + aaiHelper.getRelationshipData(relationshipToVserver, "cloud-region.cloud-owner"), + aaiHelper.getRelationshipData(relationshipToVserver, "cloud-region.cloud-region-id"), + aaiHelper.getRelationshipData(relationshipToVserver, "tenant.tenant-id"), + vnfc.getComputeResource().getResourceId()); + } + } + return true; + } catch (final Exception exception) { + logger.error( + "Error encountered deleting vservers based on received notification, AAI may not be updated correctly " + + vnfLcmOperationOccurrenceNotification, + exception); + return false; + } + } + + private boolean deleteVnfIdentifierOnVnfm(final GenericVnf genericVnf) { + try { + vnfmServiceProvider.deleteVnf(aaiHelper.getAssignedVnfm(genericVnf), genericVnf.getSelflink()); + return true; + } catch (final Exception exception) { + logger.error("Exception deleting the identifier " + genericVnf.getSelflink() + + " from the VNFM. The VNF has been terminated successfully but the identifier will remain on the VNFM.", + exception); + return false; + } + } + + private boolean patchVnfInAai(final String vnfId, final String orchestrationStatus, final String selfLink) { + try { + final GenericVnf genericVnfPatch = new GenericVnf(); + genericVnfPatch.setVnfId(vnfId); + genericVnfPatch.setOrchestrationStatus(orchestrationStatus); + if (selfLink != null) { + genericVnfPatch.setSelflink(selfLink); + } + aaiServiceProvider.invokePatchGenericVnf(genericVnfPatch); + return true; + } catch (final Exception exception) { + logger.error( + "Error encountered setting orchestration status and/or self link based on received notification, AAI may not be updated correctly " + + vnfLcmOperationOccurrenceNotification, + exception); + return false; + } + } + + private InlineResponse201VimConnectionInfo getVimConnectionInfo( + final Map vimConnectionIdToVimConnectionInfo, + final LcnVnfLcmOperationOccurrenceNotificationAffectedVnfcs vnfc) { + final String vimConnectionId = vnfc.getComputeResource().getVimConnectionId(); + return vimConnectionIdToVimConnectionInfo.get(vimConnectionId); + } + + private String getCloudOwner(final InlineResponse201VimConnectionInfo vimConnectionInfo) { + final String vimId = vimConnectionInfo.getVimId(); + return vimId.substring(0, vimId.indexOf("_")); + } + + private String getCloudRegion(final InlineResponse201VimConnectionInfo vimConnectionInfo) { + final String vimId = vimConnectionInfo.getVimId(); + return vimId.substring(vimId.indexOf("_") + 1); + } + + private String getTenant(final InlineResponse201VimConnectionInfo vimConnectionInfo) { + final JSONObject vimConnectionJsonObject = new JSONObject(vimConnectionInfo); + return vimConnectionJsonObject.getJSONObject("accessInfo").get("projectId").toString(); + } + +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/EtsiSol003AdapterController.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/EtsiSol003AdapterController.java new file mode 100644 index 0000000000..70131c89a5 --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/EtsiSol003AdapterController.java @@ -0,0 +1,163 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.lcm.rest; + +import static org.onap.so.adapters.etsi.sol003.adapter.common.CommonConstants.BASE_URL; +import javax.validation.Valid; +import javax.ws.rs.core.MediaType; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.onap.so.adapters.etsisol003adapter.lcm.jobmanagement.JobManager; +import org.onap.so.adapters.etsisol003adapter.lcm.lifecycle.LifecycleManager; +import org.onap.so.adapters.etsisol003adapter.lcm.v1.model.CreateVnfRequest; +import org.onap.so.adapters.etsisol003adapter.lcm.v1.model.CreateVnfResponse; +import org.onap.so.adapters.etsisol003adapter.lcm.v1.model.DeleteVnfResponse; +import org.onap.so.adapters.etsisol003adapter.lcm.v1.model.QueryJobResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import io.swagger.annotations.ApiParam; + +/** + * Controller for handling requests to the VNFM (Virtual Network Function Manager) adapter REST API. + */ +@Controller +@RequestMapping(value = BASE_URL, produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}, + consumes = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) +public class EtsiSol003AdapterController { + + private static final Logger logger = LoggerFactory.getLogger(EtsiSol003AdapterController.class); + private final LifecycleManager lifecycleManager; + private final JobManager jobManager; + + @Autowired + EtsiSol003AdapterController(final LifecycleManager lifecycleManager, final JobManager jobManager) { + this.lifecycleManager = lifecycleManager; + this.jobManager = jobManager; + } + + @PostMapping(value = "/vnfs/{vnfId}") + public ResponseEntity vnfCreate( + @ApiParam(value = "The identifier of the VNF. This must be the vnf-id of an existing generic-vnf in AAI.", + required = true) @PathVariable("vnfId") final String vnfId, + @ApiParam(value = "VNF creation parameters", + required = true) @Valid @RequestBody final CreateVnfRequest createVnfRequest, + @ApiParam( + value = "Used to track REST requests for logging purposes. Identifies a single top level invocation of ONAP", + required = false) @RequestHeader(value = ONAPLogConstants.Headers.REQUEST_ID, + required = false) final String requestId, + @ApiParam( + value = "Used to track REST requests for logging purposes. Identifies the client application user agent or user invoking the API", + required = false) @RequestHeader(value = ONAPLogConstants.Headers.PARTNER_NAME, + required = false) final String partnerName, + @ApiParam( + value = "Used to track REST requests for logging purposes. Identifies a single invocation of a single component", + required = false) @RequestHeader(value = ONAPLogConstants.Headers.INVOCATION_ID, + required = false) final String invocationId) { + + setLoggingMDCs(requestId, partnerName, invocationId); + + logger.info("REST request vnfCreate with body: {}", createVnfRequest); + + try { + final CreateVnfResponse createVnfResponse = lifecycleManager.createVnf(vnfId, createVnfRequest); + return new ResponseEntity<>(createVnfResponse, HttpStatus.ACCEPTED); + } finally { + clearLoggingMDCs(); + } + } + + @DeleteMapping(value = "/vnfs/{vnfId}") + public ResponseEntity vnfDelete( + @ApiParam(value = "The identifier of the VNF. This must be the vnf-id of an existing generic-vnf in AAI.", + required = true) @PathVariable("vnfId") final String vnfId, + @ApiParam( + value = "Used to track REST requests for logging purposes. Identifies a single top level invocation of ONAP", + required = false) @RequestHeader(value = ONAPLogConstants.Headers.REQUEST_ID, + required = false) final String requestId, + @ApiParam( + value = "Used to track REST requests for logging purposes. Identifies the client application user agent or user invoking the API", + required = false) @RequestHeader(value = ONAPLogConstants.Headers.PARTNER_NAME, + required = false) final String partnerName, + @ApiParam( + value = "Used to track REST requests for logging purposes. Identifies a single invocation of a single component", + required = false) @RequestHeader(value = ONAPLogConstants.Headers.INVOCATION_ID, + required = false) final String invocationId) { + + setLoggingMDCs(requestId, partnerName, invocationId); + + logger.info("REST request vnfDelete for VNF: {}", vnfId); + + try { + final DeleteVnfResponse response = lifecycleManager.deleteVnf(vnfId); + return new ResponseEntity<>(response, HttpStatus.ACCEPTED); + } finally { + clearLoggingMDCs(); + } + } + + @GetMapping(value = "/jobs/{jobId}") + public ResponseEntity jobQuery( + @ApiParam(value = "The identifier of the Job.", required = true) @PathVariable("jobId") final String jobId, + @ApiParam( + value = "Used to track REST requests for logging purposes. Identifies a single top level invocation of ONAP", + required = false) @RequestHeader(value = ONAPLogConstants.Headers.REQUEST_ID, + required = false) final String requestId, + @ApiParam( + value = "Used to track REST requests for logging purposes. Identifies the client application user agent or user invoking the API", + required = false) @RequestHeader(value = ONAPLogConstants.Headers.PARTNER_NAME, + required = false) final String partnerName, + @ApiParam( + value = "Used to track REST requests for logging purposes. Identifies a single invocation of a single component", + required = false) @RequestHeader(value = ONAPLogConstants.Headers.INVOCATION_ID, + required = false) final String invocationId) { + + setLoggingMDCs(requestId, partnerName, invocationId); + + try { + final QueryJobResponse response = jobManager.getVnfmOperation(jobId); + return new ResponseEntity<>(response, HttpStatus.OK); + } finally { + clearLoggingMDCs(); + } + } + + private void setLoggingMDCs(final String requestId, final String partnerName, final String invocationId) { + MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, requestId); + MDC.put(ONAPLogConstants.MDCs.PARTNER_NAME, partnerName); + MDC.put(ONAPLogConstants.MDCs.INVOCATION_ID, invocationId); + } + + private void clearLoggingMDCs() { + MDC.clear(); + } + +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/Sol003GrantController.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/Sol003GrantController.java new file mode 100644 index 0000000000..8a17b68fae --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/Sol003GrantController.java @@ -0,0 +1,114 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.lcm.rest; + +import static org.onap.so.adapters.etsi.sol003.adapter.common.CommonConstants.BASE_URL; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import javax.ws.rs.core.MediaType; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.aai.AaiHelper; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.aai.AaiServiceProvider; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.VnfmHelper; +import org.onap.so.adapters.etsisol003adapter.lcm.grant.model.GrantRequest; +import org.onap.so.adapters.etsisol003adapter.lcm.grant.model.GrantsAddResources; +import org.onap.so.adapters.etsisol003adapter.lcm.grant.model.InlineResponse201; +import org.onap.so.adapters.etsisol003adapter.lcm.grant.model.InlineResponse201AddResources; +import org.onap.so.adapters.etsisol003adapter.lcm.grant.model.InlineResponse201VimConnections; +import org.onap.so.adapters.etsisol003adapter.lcm.v1.model.Tenant; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; + +@Controller +@RequestMapping(value = BASE_URL, produces = MediaType.APPLICATION_JSON, consumes = MediaType.APPLICATION_JSON) +public class Sol003GrantController { + + private static final Logger logger = LoggerFactory.getLogger(Sol003GrantController.class); + public final AaiServiceProvider aaiServiceProvider; + public final AaiHelper aaiHelper; + public final VnfmHelper vnfmHelper; + + @Autowired + public Sol003GrantController(final AaiServiceProvider aaiServiceProvider, final AaiHelper aaiHelper, + final VnfmHelper vnfmHelper) { + this.aaiServiceProvider = aaiServiceProvider; + this.aaiHelper = aaiHelper; + this.vnfmHelper = vnfmHelper; + } + + @GetMapping(value = "/grants/{grantId}") + public ResponseEntity grantsGrantIdGet(@PathVariable("grantId") final String grantId) { + logger.info("Get grant received from VNFM, grant id: " + grantId); + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + } + + @PostMapping(value = "/grants") + public ResponseEntity grantsPost(@RequestBody final GrantRequest grantRequest) { + logger.info("Grant request received from VNFM: " + grantRequest); + + final InlineResponse201 grantResponse = createGrantResponse(grantRequest); + logger.info("Grant request returning to VNFM: " + grantResponse); + return new ResponseEntity<>(grantResponse, HttpStatus.CREATED); + } + + private InlineResponse201 createGrantResponse(final GrantRequest grantRequest) { + final InlineResponse201 grantResponse = new InlineResponse201(); + grantResponse.setId(UUID.randomUUID().toString()); + grantResponse.setVnfInstanceId(grantRequest.getVnfInstanceId()); + grantResponse.setVnfLcmOpOccId(grantRequest.getVnfLcmOpOccId()); + final String vnfSelfLink = grantRequest.getLinks().getVnfInstance().getHref(); + final Tenant tenant = aaiHelper + .getAssignedTenant(aaiServiceProvider.invokeQueryGenericVnf(vnfSelfLink).getGenericVnf().get(0)); + + String vimConnectionId = ""; + final InlineResponse201VimConnections vimConnection = vnfmHelper.getVimConnections(tenant); + grantResponse.addVimConnectionsItem(vimConnection); + vimConnectionId = vimConnection.getId(); + + if (grantRequest.getOperation().equals(GrantRequest.OperationEnum.INSTANTIATE)) { + grantResponse.addResources(getResources(grantRequest.getAddResources(), vimConnectionId)); + } else if (grantRequest.getOperation().equals(GrantRequest.OperationEnum.TERMINATE)) { + grantResponse.removeResources(getResources(grantRequest.getRemoveResources(), vimConnectionId)); + } + return grantResponse; + } + + private List getResources(final List requestResources, + final String vimId) { + final List resources = new ArrayList<>(); + for (final GrantsAddResources requestResource : requestResources) { + final InlineResponse201AddResources responseResource = new InlineResponse201AddResources(); + responseResource.setResourceDefinitionId(requestResource.getId()); + responseResource.setVimConnectionId(vimId); + resources.add(responseResource); + } + return resources; + } +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/Sol003LcnContoller.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/Sol003LcnContoller.java new file mode 100644 index 0000000000..784fb8efa6 --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/Sol003LcnContoller.java @@ -0,0 +1,131 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.lcm.rest; + +import static org.onap.so.adapters.etsi.sol003.adapter.common.CommonConstants.BASE_URL; +import static org.onap.so.adapters.etsisol003adapter.lcm.LifeCycleManagementConstants.OPERATION_NOTIFICATION_ENDPOINT; +import static org.slf4j.LoggerFactory.getLogger; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import javax.ws.rs.core.MediaType; +import org.onap.aai.domain.yang.EsrVnfm; +import org.onap.aai.domain.yang.GenericVnf; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.aai.AaiHelper; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.aai.AaiServiceProvider; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.VnfmServiceProvider; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.InlineResponse201; +import org.onap.so.adapters.etsisol003adapter.lcm.jobmanagement.JobManager; +import org.onap.so.adapters.etsisol003adapter.lcm.lcn.model.VnfIdentifierCreationNotification; +import org.onap.so.adapters.etsisol003adapter.lcm.lcn.model.VnfIdentifierDeletionNotification; +import org.onap.so.adapters.etsisol003adapter.lcm.lcn.model.VnfLcmOperationOccurrenceNotification; +import org.onap.so.adapters.etsisol003adapter.lcm.lcn.model.VnfLcmOperationOccurrenceNotification.OperationEnum; +import org.onap.so.adapters.etsisol003adapter.lcm.lcn.model.VnfLcmOperationOccurrenceNotification.OperationStateEnum; +import org.onap.so.adapters.etsisol003adapter.lcm.notificationhandling.NotificationHandler; +import org.slf4j.Logger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; + +/** + * Controller for handling notifications from the VNFM (Virtual Network Function Manager). + */ +@Controller +@RequestMapping(value = BASE_URL, produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}, + consumes = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) +public class Sol003LcnContoller { + private static Logger logger = getLogger(Sol003LcnContoller.class); + private static final String LOG_LCN_RECEIVED = "LCN received from VNFM: "; + private final AaiServiceProvider aaiServiceProvider; + private final AaiHelper aaiHelper; + private final VnfmServiceProvider vnfmServiceProvider; + private final JobManager jobManager; + private final ExecutorService executor = Executors.newCachedThreadPool(); + + @Autowired + Sol003LcnContoller(final AaiServiceProvider aaiServiceProvider, final AaiHelper aaiHelper, + final VnfmServiceProvider vnfmServiceProvider, final JobManager jobManager) { + this.aaiServiceProvider = aaiServiceProvider; + this.aaiHelper = aaiHelper; + this.vnfmServiceProvider = vnfmServiceProvider; + this.jobManager = jobManager; + } + + @PostMapping(value = "/lcn/VnfIdentifierCreationNotification") + public ResponseEntity lcnVnfIdentifierCreationNotificationPost( + @RequestBody final VnfIdentifierCreationNotification vnfIdentifierCreationNotification) { + logger.info(LOG_LCN_RECEIVED + vnfIdentifierCreationNotification); + return new ResponseEntity<>(HttpStatus.NO_CONTENT); + } + + @PostMapping(value = "/lcn/VnfIdentifierDeletionNotification") + public ResponseEntity lcnVnfIdentifierDeletionNotificationPost( + @RequestBody final VnfIdentifierDeletionNotification vnfIdentifierDeletionNotification) { + logger.info(LOG_LCN_RECEIVED + vnfIdentifierDeletionNotification); + return new ResponseEntity<>(HttpStatus.NO_CONTENT); + } + + @PostMapping(value = OPERATION_NOTIFICATION_ENDPOINT) + public ResponseEntity lcnVnfLcmOperationOccurrenceNotificationPost( + @RequestBody final VnfLcmOperationOccurrenceNotification vnfLcmOperationOccurrenceNotification) { + logger.info(LOG_LCN_RECEIVED + vnfLcmOperationOccurrenceNotification); + + if (isANotificationOfInterest(vnfLcmOperationOccurrenceNotification)) { + final InlineResponse201 vnfInstance = getVnfInstance(vnfLcmOperationOccurrenceNotification); + final NotificationHandler handler = new NotificationHandler(vnfLcmOperationOccurrenceNotification, + aaiHelper, aaiServiceProvider, vnfmServiceProvider, jobManager, vnfInstance); + executor.execute(handler); + } + + logger.info("Sending notification response"); + return new ResponseEntity<>(HttpStatus.NO_CONTENT); + } + + private boolean isANotificationOfInterest(final VnfLcmOperationOccurrenceNotification notification) { + return isInstanitiateCompleted(notification) || isTerminateTerminalState(notification); + } + + private boolean isInstanitiateCompleted(final VnfLcmOperationOccurrenceNotification notification) { + return notification.getOperation().equals(OperationEnum.INSTANTIATE) + && notification.getOperationState().equals(OperationStateEnum.COMPLETED); + } + + private boolean isTerminateTerminalState(final VnfLcmOperationOccurrenceNotification notification) { + return notification.getOperation().equals(OperationEnum.TERMINATE) + && (notification.getOperationState().equals(OperationStateEnum.COMPLETED) + || notification.getOperationState().equals(OperationStateEnum.FAILED) + || notification.getOperationState().equals(OperationStateEnum.ROLLED_BACK)); + } + + private InlineResponse201 getVnfInstance( + final VnfLcmOperationOccurrenceNotification vnfLcmOperationOccurrenceNotification) { + final GenericVnf vnfInAai = aaiServiceProvider + .invokeQueryGenericVnf(vnfLcmOperationOccurrenceNotification.getLinks().getVnfInstance().getHref()) + .getGenericVnf().get(0); + final EsrVnfm vnfm = aaiHelper.getAssignedVnfm(vnfInAai); + return vnfmServiceProvider + .getVnf(vnfm, vnfLcmOperationOccurrenceNotification.getLinks().getVnfInstance().getHref()).get(); + } + +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/exceptions/JobNotFoundException.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/exceptions/JobNotFoundException.java new file mode 100644 index 0000000000..2461631bc4 --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/exceptions/JobNotFoundException.java @@ -0,0 +1,38 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.lcm.rest.exceptions; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +/** + * Exception for job not found. + */ +@ResponseStatus(HttpStatus.NOT_FOUND) +public class JobNotFoundException extends RuntimeException { + + private static final long serialVersionUID = 6398018034431666933L; + + public JobNotFoundException(final String message) { + super(message); + } + +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/exceptions/TenantNotFoundException.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/exceptions/TenantNotFoundException.java new file mode 100644 index 0000000000..b7911c82e7 --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/exceptions/TenantNotFoundException.java @@ -0,0 +1,35 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.lcm.rest.exceptions; + +/** + * Exception for Tenant not found. + */ + +public class TenantNotFoundException extends RuntimeException { + + private static final long serialVersionUID = 6398018034431666933L; + + public TenantNotFoundException(final String message) { + super(message); + } + +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/exceptions/VnfNotFoundException.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/exceptions/VnfNotFoundException.java new file mode 100644 index 0000000000..78232e2622 --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/exceptions/VnfNotFoundException.java @@ -0,0 +1,38 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.lcm.rest.exceptions; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +/** + * Exception for VNF not found. + */ +@ResponseStatus(HttpStatus.NOT_FOUND) +public class VnfNotFoundException extends RuntimeException { + + private static final long serialVersionUID = 6398018034431666933L; + + public VnfNotFoundException(final String message) { + super(message); + } + +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/exceptions/VnfmNotFoundException.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/exceptions/VnfmNotFoundException.java new file mode 100644 index 0000000000..6720d0bd92 --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/exceptions/VnfmNotFoundException.java @@ -0,0 +1,38 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.lcm.rest.exceptions; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +/** + * Exception for VNFM not found. + */ +@ResponseStatus(HttpStatus.BAD_REQUEST) +public class VnfmNotFoundException extends RuntimeException { + + private static final long serialVersionUID = 6398018034431666933L; + + public VnfmNotFoundException(final String message) { + super(message); + } + +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/exceptions/VnfmRequestFailureException.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/exceptions/VnfmRequestFailureException.java new file mode 100644 index 0000000000..10ada7ce18 --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/exceptions/VnfmRequestFailureException.java @@ -0,0 +1,38 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.lcm.rest.exceptions; + +/** + * Exception indicating a request to a VNFM failed. + */ +public class VnfmRequestFailureException extends RuntimeException { + + private static final long serialVersionUID = 6398018034431666933L; + + public VnfmRequestFailureException(final String message) { + super(message); + } + + public VnfmRequestFailureException(final String message, final Throwable throwable) { + super(message, throwable); + } + +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/resources/META-INF/services/org.onap.so.client.RestProperties b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/resources/META-INF/services/org.onap.so.client.RestProperties index 1d13643147..bc6ef94f42 100644 --- a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/resources/META-INF/services/org.onap.so.client.RestProperties +++ b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/resources/META-INF/services/org.onap.so.client.RestProperties @@ -1 +1 @@ -org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.aai.AaiPropertiesImpl \ No newline at end of file +org.onap.so.adapters.etsisol003adapter.lcm.extclients.aai.AaiPropertiesImpl \ No newline at end of file diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/test/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/rest/HealthCheckTest.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/test/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/rest/HealthCheckTest.java deleted file mode 100644 index 8b3c7f3ce7..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/test/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/rest/HealthCheckTest.java +++ /dev/null @@ -1,54 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.lcm.rest; - -import static org.junit.Assert.assertEquals; -import java.net.URI; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.http.RequestEntity; -import org.springframework.http.ResponseEntity; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.junit4.SpringRunner; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = TestApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) -@ActiveProfiles("test") -public class HealthCheckTest { - - @LocalServerPort - private int port; - - private final TestRestTemplate restTemplate = new TestRestTemplate("test", "test"); - - @Test - public void testHealthcheck() throws Exception { - final RequestEntity request = - RequestEntity.get(new URI("http://localhost:" + port + "/manage/health")).build(); - final ResponseEntity response = restTemplate.exchange(request, Void.class); - assertEquals(200, response.getStatusCode().value()); - } - -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/test/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/rest/Sol003GrantControllerTest.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/test/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/rest/Sol003GrantControllerTest.java deleted file mode 100644 index f7b84a4ee0..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/test/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/rest/Sol003GrantControllerTest.java +++ /dev/null @@ -1,252 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.lcm.rest; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.doReturn; -import static org.onap.so.client.RestTemplateConfig.CONFIGURABLE_REST_TEMPLATE; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import org.hamcrest.BaseMatcher; -import org.hamcrest.Description; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.hamcrest.MockitoHamcrest; -import org.onap.aai.domain.yang.EsrSystemInfo; -import org.onap.aai.domain.yang.EsrSystemInfoList; -import org.onap.aai.domain.yang.GenericVnf; -import org.onap.aai.domain.yang.GenericVnfs; -import org.onap.aai.domain.yang.Relationship; -import org.onap.aai.domain.yang.RelationshipData; -import org.onap.aai.domain.yang.RelationshipList; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.grant.model.GrantRequest; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.grant.model.GrantRequest.OperationEnum; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.grant.model.GrantsAddResources; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.grant.model.GrantsAddResources.TypeEnum; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.grant.model.GrantsLinks; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.grant.model.GrantsLinksVnfLcmOpOcc; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.grant.model.InlineResponse201; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.grant.model.InlineResponse201VimConnections; -import org.onap.aaiclient.client.aai.AAIResourcesClient; -import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.web.client.RestTemplate; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = TestApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) -@ActiveProfiles("test") -public class Sol003GrantControllerTest { - - private static final String CLOUD_OWNER = "myTestCloudOwner"; - private static final String REGION = "myTestRegion"; - private static final String TENANT_ID = "myTestTenantId"; - private static final String SEPARATOR = "_"; - private static final String vimConnectionId = CLOUD_OWNER + SEPARATOR + REGION; - - @LocalServerPort - private int port; - @Autowired - @Qualifier(CONFIGURABLE_REST_TEMPLATE) - private RestTemplate testRestTemplate; - - @MockBean - private AAIResourcesClient aaiResourcesClient; - - @Autowired - private Sol003GrantController controller; - - @Before - public void setUp() throws Exception { - setUpVimInMockAai(); - } - - @Test - public void grantRequest_ValidRequestInstantiate_GrantApproved() { - final GrantRequest grantRequest = createGrantRequest("INSTANTIATE"); - setUpGenericVnfWithVnfmRelationshipInMockAai("vnfmType", "vnfm1"); - final ResponseEntity response = controller.grantsPost(grantRequest); - assertEquals(HttpStatus.CREATED, response.getStatusCode()); - assertEquals(1, response.getBody().getAddResources().size()); - assertNull(response.getBody().getRemoveResources()); - - assertEquals(vimConnectionId, response.getBody().getAddResources().get(0).getVimConnectionId()); - assertEquals("myTestVnfIdOnVnfm", response.getBody().getVnfInstanceId()); - assertEquals("123456", response.getBody().getVnfLcmOpOccId()); - - final InlineResponse201VimConnections vimConnections = response.getBody().getVimConnections().get(0); - assertEquals(vimConnectionId, vimConnections.getVimId()); - assertEquals("OPENSTACK", vimConnections.getVimType()); - assertNotNull(vimConnections.getAccessInfo()); - assertNotNull(vimConnections.getInterfaceInfo()); - assertEquals("INSTANTIATE", grantRequest.getOperation().toString()); - } - - @Test - public void getGrant_notSupported_returns501() { - final ResponseEntity response2 = controller.grantsGrantIdGet("myTestGrantId"); - assertEquals(HttpStatus.NOT_IMPLEMENTED, response2.getStatusCode()); - } - - @Test - public void grantRequest_ValidRequestTerminate_GrantApproved() { - final GrantRequest grantRequest = createGrantRequest("TERMINATE"); - setUpGenericVnfWithVnfmRelationshipInMockAai("vnfmType", "vnfm1"); - final ResponseEntity response = controller.grantsPost(grantRequest); - - assertEquals(HttpStatus.CREATED, response.getStatusCode()); - assertNull(response.getBody().getAddResources()); - assertEquals(1, response.getBody().getRemoveResources().size()); - assertEquals(vimConnectionId, response.getBody().getRemoveResources().get(0).getVimConnectionId()); - assertEquals("myTestVnfIdOnVnfm", response.getBody().getVnfInstanceId()); - assertEquals("123456", response.getBody().getVnfLcmOpOccId()); - - final InlineResponse201VimConnections vimConnections = response.getBody().getVimConnections().get(0); - assertEquals(vimConnectionId, vimConnections.getVimId()); - assertEquals("OPENSTACK", vimConnections.getVimType()); - assertNotNull(vimConnections.getAccessInfo()); - assertNotNull(vimConnections.getInterfaceInfo()); - assertEquals("TERMINATE", grantRequest.getOperation().toString()); - - } - - private GrantRequest createGrantRequest(final String operation) { - final GrantRequest grantRequest = new GrantRequest(); - grantRequest.setVnfInstanceId("myTestVnfIdOnVnfm"); - grantRequest.setVnfLcmOpOccId("123456"); - grantRequest.links(new GrantsLinks() - .vnfInstance(new GrantsLinksVnfLcmOpOcc().href("http://vnfm:8080/vnfs/myTestVnfIdOnVnfm"))); - if (operation == "INSTANTIATE") { - grantRequest.setOperation(OperationEnum.INSTANTIATE); - final GrantsAddResources resource = new GrantsAddResources(); - resource.setId("123"); - resource.setType(TypeEnum.COMPUTE); - grantRequest.addAddResourcesItem(resource); - } else if (operation == "TERMINATE") { - grantRequest.setOperation(OperationEnum.TERMINATE); - final GrantsAddResources resource = new GrantsAddResources(); - resource.setId("123"); - resource.setType(TypeEnum.COMPUTE); - grantRequest.addRemoveResourcesItem(resource); - } - - return grantRequest; - } - - private void setUpVimInMockAai() { - final EsrSystemInfo esrSystemInfo = new EsrSystemInfo(); - esrSystemInfo.setServiceUrl("http://myVim:8080"); - esrSystemInfo.setType("OPENSTACK"); - esrSystemInfo.setSystemType("VIM"); - esrSystemInfo.setCloudDomain("myDomain"); - esrSystemInfo.setUserName("myUser"); - esrSystemInfo.setPassword("myPassword"); - - final EsrSystemInfoList esrSystemInfoList = new EsrSystemInfoList(); - esrSystemInfoList.getEsrSystemInfo().add(esrSystemInfo); - - doReturn(Optional.of(esrSystemInfoList)).when(aaiResourcesClient).get(eq(EsrSystemInfoList.class), - MockitoHamcrest.argThat(new AaiResourceUriMatcher("/cloud-infrastructure/cloud-regions/cloud-region/" - + CLOUD_OWNER + "/" + REGION + "/esr-system-info-list"))); - } - - private GenericVnf createGenericVnf(final String type) { - final GenericVnf genericVnf = new GenericVnf(); - genericVnf.setVnfId("myTestVnfId"); - genericVnf.setNfType(type); - return genericVnf; - } - - private void setUpGenericVnfWithVnfmRelationshipInMockAai(final String type, final String vnfmId) { - final GenericVnf genericVnf = createGenericVnf(type); - - final Relationship relationshipToVnfm = new Relationship(); - relationshipToVnfm.setRelatedTo("tenant"); - final RelationshipData relationshipData1 = new RelationshipData(); - final RelationshipData relationshipData2 = new RelationshipData(); - final RelationshipData relationshipData3 = new RelationshipData(); - - relationshipData1.setRelationshipKey("cloud-region.cloud-owner"); - relationshipData1.setRelationshipValue(CLOUD_OWNER); - relationshipData2.setRelationshipKey("cloud-region.cloud-region-id"); - relationshipData2.setRelationshipValue(REGION); - relationshipData3.setRelationshipKey("tenant.tenant-id"); - relationshipData3.setRelationshipValue(TENANT_ID); - - relationshipToVnfm.getRelationshipData().add(relationshipData1); - relationshipToVnfm.getRelationshipData().add(relationshipData2); - relationshipToVnfm.getRelationshipData().add(relationshipData3); - - final RelationshipList relationshipList = new RelationshipList(); - relationshipList.getRelationship().add(relationshipToVnfm); - genericVnf.setRelationshipList(relationshipList); - - doReturn(Optional.of(genericVnf)).when(aaiResourcesClient).get(eq(GenericVnf.class), - MockitoHamcrest.argThat(new AaiResourceUriMatcher("/network/generic-vnfs/generic-vnf/myTestVnfId"))); - - final List listOfGenericVnfs = new ArrayList<>(); - listOfGenericVnfs.add(genericVnf); - final GenericVnfs genericVnfs = new GenericVnfs(); - genericVnfs.getGenericVnf().addAll(listOfGenericVnfs); - doReturn(Optional.of(genericVnfs)).when(aaiResourcesClient).get(eq(GenericVnfs.class), - MockitoHamcrest.argThat(new AaiResourceUriMatcher( - "/network/generic-vnfs?selflink=http%3A%2F%2Fvnfm%3A8080%2Fvnfs%2FmyTestVnfIdOnVnfm"))); - } - - private class AaiResourceUriMatcher extends BaseMatcher { - - final String uriAsString; - - public AaiResourceUriMatcher(final String uriAsString) { - this.uriAsString = uriAsString; - } - - @Override - public boolean matches(final Object item) { - if (item instanceof AAIResourceUri) { - if (uriAsString.endsWith("...")) { - return ((AAIResourceUri) item).build().toString() - .startsWith(uriAsString.substring(0, uriAsString.indexOf("..."))); - } - return ((AAIResourceUri) item).build().toString().equals(uriAsString); - } - return false; - } - - @Override - public void describeTo(final Description description) {} - - } - -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/test/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/rest/Sol003LcnControllerTest.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/test/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/rest/Sol003LcnControllerTest.java deleted file mode 100644 index e67e840e35..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/test/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/rest/Sol003LcnControllerTest.java +++ /dev/null @@ -1,413 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.lcm.rest; - -import static org.junit.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.timeout; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyZeroInteractions; -import static org.onap.so.client.RestTemplateConfig.CONFIGURABLE_REST_TEMPLATE; -import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; -import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus; -import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import javax.inject.Inject; -import org.hamcrest.BaseMatcher; -import org.hamcrest.Description; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.ArgumentCaptor; -import org.mockito.hamcrest.MockitoHamcrest; -import org.onap.aai.domain.yang.EsrSystemInfoList; -import org.onap.aai.domain.yang.EsrVnfm; -import org.onap.aai.domain.yang.GenericVnf; -import org.onap.aai.domain.yang.GenericVnfs; -import org.onap.aai.domain.yang.Relationship; -import org.onap.aai.domain.yang.RelationshipData; -import org.onap.aai.domain.yang.RelationshipList; -import org.onap.aai.domain.yang.Vserver; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.aai.AaiHelper; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.aai.OamIpAddressSource; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.aai.OamIpAddressSource.OamIpAddressType; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vim.model.AccessInfo; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.model.InlineResponse201; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.model.InlineResponse201Links; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.model.InlineResponse201LinksSelf; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.model.InlineResponse201VimConnectionInfo; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.lcn.model.LcnVnfLcmOperationOccurrenceNotificationAffectedVnfcs; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.lcn.model.LcnVnfLcmOperationOccurrenceNotificationAffectedVnfcs.ChangeTypeEnum; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.lcn.model.LcnVnfLcmOperationOccurrenceNotificationComputeResource; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.lcn.model.LcnVnfLcmOperationOccurrenceNotificationLinks; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.lcn.model.LcnVnfLcmOperationOccurrenceNotificationLinksVnfInstance; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.lcn.model.VnfIdentifierCreationNotification; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.lcn.model.VnfLcmOperationOccurrenceNotification; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.lcn.model.VnfLcmOperationOccurrenceNotification.OperationEnum; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.lcn.model.VnfLcmOperationOccurrenceNotification.OperationStateEnum; -import org.onap.aaiclient.client.aai.AAIResourcesClient; -import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.client.MockRestServiceServer; -import org.springframework.web.client.RestTemplate; -import com.google.gson.Gson; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = TestApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) -@ActiveProfiles("test") -public class Sol003LcnControllerTest { - - private static final String CLOUD_OWNER = "myTestCloudOwner"; - private static final String REGION = "myTestRegion"; - private static final String TENANT_ID = "myTestTenantId"; - - @LocalServerPort - private int port; - @Autowired - @Qualifier(CONFIGURABLE_REST_TEMPLATE) - private RestTemplate testRestTemplate; - private MockRestServiceServer mockRestServer; - - @MockBean - private AAIResourcesClient aaiResourcesClient; - - @Autowired - private Sol003LcnContoller controller; - private final Gson gson = new Gson(); - - @Inject - private AaiHelper aaiHelper; - - @Before - public void setUp() throws Exception { - mockRestServer = MockRestServiceServer.bindTo(testRestTemplate).build(); - } - - @Test - public void lcnNotification_IdentifierCreated_Returns204() throws URISyntaxException, InterruptedException { - final VnfIdentifierCreationNotification vnfIdentifierCreationNotification = - new VnfIdentifierCreationNotification(); - final ResponseEntity response = - controller.lcnVnfIdentifierCreationNotificationPost(vnfIdentifierCreationNotification); - assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode()); - } - - @Test - public void lcnNotification_IdentifierDeleted_Returns204() throws URISyntaxException, InterruptedException { - final VnfIdentifierCreationNotification vnfIdentifierCreationNotification = - new VnfIdentifierCreationNotification(); - final ResponseEntity response = - controller.lcnVnfIdentifierCreationNotificationPost(vnfIdentifierCreationNotification); - assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode()); - } - - @Test - public void lcnNotification_InstantiateStartingOrProcessing_NoAction() - throws URISyntaxException, InterruptedException { - final VnfLcmOperationOccurrenceNotification startingNotification = new VnfLcmOperationOccurrenceNotification(); - startingNotification.setOperation(OperationEnum.INSTANTIATE); - startingNotification.setOperationState(OperationStateEnum.STARTING); - - ResponseEntity response = controller.lcnVnfLcmOperationOccurrenceNotificationPost(startingNotification); - assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode()); - - verifyZeroInteractions(aaiResourcesClient); - - final VnfLcmOperationOccurrenceNotification processingNotification = - new VnfLcmOperationOccurrenceNotification(); - processingNotification.setOperation(OperationEnum.INSTANTIATE); - processingNotification.setOperationState(OperationStateEnum.STARTING); - - response = controller.lcnVnfLcmOperationOccurrenceNotificationPost(processingNotification); - assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode()); - - verifyZeroInteractions(aaiResourcesClient); - } - - @Test - public void lcnNotification_InstantiateCompleted_AaiUpdated() throws URISyntaxException, InterruptedException { - final VnfLcmOperationOccurrenceNotification vnfLcmOperationOccurrenceNotification = - createNotification(OperationEnum.INSTANTIATE); - addVnfcsToNotification(vnfLcmOperationOccurrenceNotification, ChangeTypeEnum.ADDED); - final InlineResponse201 vnfInstance = createVnfInstance(); - - mockRestServer.expect(requestTo(new URI("http://vnfm:8080/vnfs/myTestVnfIdOnVnfm"))) - .andRespond(withSuccess(gson.toJson(vnfInstance), MediaType.APPLICATION_JSON)); - - final GenericVnf genericVnf = createGenericVnf("vnfmType1"); - addRelationshipFromGenericVnfToVnfm(genericVnf, "vnfm1"); - final List listOfGenericVnfs = new ArrayList<>(); - listOfGenericVnfs.add(genericVnf); - final GenericVnfs genericVnfs = new GenericVnfs(); - genericVnfs.getGenericVnf().addAll(listOfGenericVnfs); - doReturn(Optional.of(genericVnfs)).when(aaiResourcesClient).get(eq(GenericVnfs.class), - MockitoHamcrest.argThat(new AaiResourceUriMatcher( - "/network/generic-vnfs?selflink=http%3A%2F%2Fvnfm%3A8080%2Fvnfs%2FmyTestVnfIdOnVnfm"))); - EsrVnfm vnfm = new EsrVnfm(); - vnfm.setVnfmId("vnfm1"); - final EsrSystemInfoList esrSystemInfoList = new EsrSystemInfoList(); - vnfm.setEsrSystemInfoList(esrSystemInfoList); - doReturn(Optional.of(vnfm)).when(aaiResourcesClient).get(eq(EsrVnfm.class), MockitoHamcrest - .argThat(new AaiResourceUriMatcher("/external-system/esr-vnfm-list/esr-vnfm/vnfm1?depth=1"))); - - final ResponseEntity response = - controller.lcnVnfLcmOperationOccurrenceNotificationPost(vnfLcmOperationOccurrenceNotification); - assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode()); - - final ArgumentCaptor bodyArgument1 = ArgumentCaptor.forClass(Object.class); - final ArgumentCaptor uriArgument1 = ArgumentCaptor.forClass(AAIResourceUri.class); - - verify(aaiResourcesClient, timeout(1000)).update(uriArgument1.capture(), bodyArgument1.capture()); - - assertEquals("/network/generic-vnfs/generic-vnf/myTestVnfId", - uriArgument1.getAllValues().get(0).build().toString()); - final GenericVnf updatedGenericVnf = (GenericVnf) bodyArgument1.getAllValues().get(0); - assertEquals("10.10.10.10", updatedGenericVnf.getIpv4OamAddress()); - assertEquals("Created", updatedGenericVnf.getOrchestrationStatus()); - - final ArgumentCaptor bodyArgument2 = ArgumentCaptor.forClass(Object.class); - final ArgumentCaptor uriArgument2 = ArgumentCaptor.forClass(AAIResourceUri.class); - verify(aaiResourcesClient, timeout(1000)).create(uriArgument2.capture(), bodyArgument2.capture()); - - assertEquals( - "/cloud-infrastructure/cloud-regions/cloud-region/" + CLOUD_OWNER + "/" + REGION + "/tenants/tenant/" - + TENANT_ID + "/vservers/vserver/myVnfc1", - uriArgument2.getAllValues().get(0).build().toString()); - - final Vserver vserver = (Vserver) bodyArgument2.getAllValues().get(0); - assertEquals("myVnfc1", vserver.getVserverId()); - - final ArgumentCaptor uriArgument1Connect = ArgumentCaptor.forClass(AAIResourceUri.class); - final ArgumentCaptor uriArgument2Connect = ArgumentCaptor.forClass(AAIResourceUri.class); - verify(aaiResourcesClient, timeout(1000)).connect(uriArgument1Connect.capture(), uriArgument2Connect.capture()); - assertEquals( - "/cloud-infrastructure/cloud-regions/cloud-region/" + CLOUD_OWNER + "/" + REGION + "/tenants/tenant/" - + TENANT_ID + "/vservers/vserver/myVnfc1", - uriArgument1Connect.getAllValues().get(0).build().toString()); - assertEquals("/network/generic-vnfs/generic-vnf/myTestVnfId", - uriArgument2Connect.getAllValues().get(0).build().toString()); - } - - @Test - public void lcnNotification_TerminateCompleted_AaiUpdated() throws URISyntaxException, InterruptedException { - final VnfLcmOperationOccurrenceNotification vnfLcmOperationOccurrenceNotification = - createNotification(OperationEnum.TERMINATE); - addVnfcsToNotification(vnfLcmOperationOccurrenceNotification, ChangeTypeEnum.REMOVED); - - final InlineResponse201 vnfInstance = createVnfInstance(); - - mockRestServer.expect(requestTo(new URI("http://vnfm:8080/vnfs/myTestVnfIdOnVnfm"))) - .andRespond(withSuccess(gson.toJson(vnfInstance), MediaType.APPLICATION_JSON)); - - mockRestServer.expect(requestTo(new URI("http://vnfm:8080/vnfs/myTestVnfIdOnVnfm"))) - .andRespond(withStatus(HttpStatus.NO_CONTENT).contentType(MediaType.APPLICATION_JSON)); - - final GenericVnf genericVnf = createGenericVnf("vnfmType1"); - addRelationshipFromGenericVnfToVnfm(genericVnf, "vnfm1"); - genericVnf.setSelflink("http://vnfm:8080/vnfs/myTestVnfIdOnVnfm"); - final List listOfGenericVnfs = new ArrayList<>(); - listOfGenericVnfs.add(genericVnf); - final GenericVnfs genericVnfs = new GenericVnfs(); - genericVnfs.getGenericVnf().addAll(listOfGenericVnfs); - addRelationshipFromGenericVnfToVserver(genericVnf, "myVnfc1"); - - doReturn(Optional.of(genericVnfs)).when(aaiResourcesClient).get(eq(GenericVnfs.class), - MockitoHamcrest.argThat(new AaiResourceUriMatcher( - "/network/generic-vnfs?selflink=http%3A%2F%2Fvnfm%3A8080%2Fvnfs%2FmyTestVnfIdOnVnfm"))); - EsrVnfm vnfm = new EsrVnfm(); - vnfm.setVnfmId("vnfm1"); - final EsrSystemInfoList esrSystemInfoList = new EsrSystemInfoList(); - vnfm.setEsrSystemInfoList(esrSystemInfoList); - doReturn(Optional.of(vnfm)).when(aaiResourcesClient).get(eq(EsrVnfm.class), MockitoHamcrest - .argThat(new AaiResourceUriMatcher("/external-system/esr-vnfm-list/esr-vnfm/vnfm1?depth=1"))); - - final ResponseEntity response = - controller.lcnVnfLcmOperationOccurrenceNotificationPost(vnfLcmOperationOccurrenceNotification); - assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode()); - - final ArgumentCaptor genericVnfArgument = ArgumentCaptor.forClass(GenericVnf.class); - final ArgumentCaptor updateUriArgument = ArgumentCaptor.forClass(AAIResourceUri.class); - verify(aaiResourcesClient, timeout(10000000)).update(updateUriArgument.capture(), genericVnfArgument.capture()); - assertEquals("/network/generic-vnfs/generic-vnf/myTestVnfId", updateUriArgument.getValue().build().toString()); - assertEquals("Assigned", genericVnfArgument.getValue().getOrchestrationStatus()); - - final ArgumentCaptor deleteUriArgument = ArgumentCaptor.forClass(AAIResourceUri.class); - - verify(aaiResourcesClient, timeout(10000000)).delete(deleteUriArgument.capture()); - - assertEquals( - "/cloud-infrastructure/cloud-regions/cloud-region/" + CLOUD_OWNER + "/" + REGION + "/tenants/tenant/" - + TENANT_ID + "/vservers/vserver/myVnfc1", - deleteUriArgument.getAllValues().get(0).build().toString()); - } - - private VnfLcmOperationOccurrenceNotification createNotification(final OperationEnum operation) { - final VnfLcmOperationOccurrenceNotification notification = new VnfLcmOperationOccurrenceNotification(); - notification.setOperation(operation); - notification.setOperationState(OperationStateEnum.COMPLETED); - - final LcnVnfLcmOperationOccurrenceNotificationLinksVnfInstance linkToVnfInstance = - new LcnVnfLcmOperationOccurrenceNotificationLinksVnfInstance() - .href("http://vnfm:8080/vnfs/myTestVnfIdOnVnfm"); - final LcnVnfLcmOperationOccurrenceNotificationLinks operationLinks = - new LcnVnfLcmOperationOccurrenceNotificationLinks().vnfInstance(linkToVnfInstance); - notification.setLinks(operationLinks); - - return notification; - } - - private void addVnfcsToNotification(final VnfLcmOperationOccurrenceNotification notification, - final ChangeTypeEnum changeType) { - final List affectedVnfcs = new ArrayList<>();; - final LcnVnfLcmOperationOccurrenceNotificationAffectedVnfcs vnfc = - new LcnVnfLcmOperationOccurrenceNotificationAffectedVnfcs(); - vnfc.changeType(changeType); - final LcnVnfLcmOperationOccurrenceNotificationComputeResource computeResource = - new LcnVnfLcmOperationOccurrenceNotificationComputeResource(); - computeResource.setResourceId("myVnfc1"); - computeResource.setVimConnectionId(CLOUD_OWNER + "_" + REGION); - vnfc.setComputeResource(computeResource); - affectedVnfcs.add(vnfc); - notification.setAffectedVnfcs(affectedVnfcs); - } - - private InlineResponse201 createVnfInstance() { - final InlineResponse201 vnfInstance = new InlineResponse201(); - vnfInstance.setId("myTestVnfIdOnVnfm"); - final InlineResponse201LinksSelf selfLink = new InlineResponse201LinksSelf(); - selfLink.setHref("http://vnfm:8080/vnfs/myTestVnfIdOnVnfm"); - final InlineResponse201Links VnfInstancelinks = new InlineResponse201Links(); - VnfInstancelinks.setSelf(selfLink); - vnfInstance.setLinks(VnfInstancelinks); - - final Map vnfConfigurableProperties = new HashMap<>(); - vnfConfigurableProperties.put("vnfIpAddress", "10.10.10.10"); - vnfInstance.setVnfConfigurableProperties(vnfConfigurableProperties); - - final List vimConnectionInfo = new ArrayList<>();; - final InlineResponse201VimConnectionInfo vimConnection = new InlineResponse201VimConnectionInfo(); - vimConnection.setVimId(CLOUD_OWNER + "_" + REGION); - vimConnection.setId(CLOUD_OWNER + "_" + REGION); - final AccessInfo accessInfo = new AccessInfo(); - accessInfo.setProjectId(TENANT_ID); - vimConnection.setAccessInfo(accessInfo); - vimConnectionInfo.add(vimConnection); - vnfInstance.setVimConnectionInfo(vimConnectionInfo); - - final OamIpAddressSource oamIpAddressSource = - new OamIpAddressSource(OamIpAddressType.CONFIGURABLE_PROPERTY, "vnfIpAddress"); - aaiHelper.setOamIpAddressSource("myTestVnfIdOnVnfm", oamIpAddressSource); - return vnfInstance; - } - - private GenericVnf createGenericVnf(final String type) { - final GenericVnf genericVnf = new GenericVnf(); - genericVnf.setVnfId("myTestVnfId"); - genericVnf.setNfType(type); - return genericVnf; - } - - private void addRelationshipFromGenericVnfToVnfm(final GenericVnf genericVnf, final String vnfmId) { - final Relationship relationshipToVnfm = new Relationship(); - relationshipToVnfm.setRelatedLink("/aai/v15/external-system/esr-vnfm-list/esr-vnfm/" + vnfmId); - relationshipToVnfm.setRelatedTo("esr-vnfm"); - final RelationshipData relationshipData = new RelationshipData(); - relationshipData.setRelationshipKey("esr-vnfm.vnfm-id"); - relationshipData.setRelationshipValue(vnfmId); - relationshipToVnfm.getRelationshipData().add(relationshipData); - - if (genericVnf.getRelationshipList() == null) { - final RelationshipList relationshipList = new RelationshipList(); - genericVnf.setRelationshipList(relationshipList); - } - genericVnf.getRelationshipList().getRelationship().add(relationshipToVnfm); - } - - private void addRelationshipFromGenericVnfToVserver(final GenericVnf genericVnf, final String vserverId) { - final Relationship relationshipToVserver = new Relationship(); - relationshipToVserver.setRelatedTo("vserver"); - final RelationshipData relationshipData1 = new RelationshipData(); - relationshipData1.setRelationshipKey("vserver.vserver-id"); - relationshipData1.setRelationshipValue(vserverId); - relationshipToVserver.getRelationshipData().add(relationshipData1); - final RelationshipData relationshipData2 = new RelationshipData(); - relationshipData2.setRelationshipKey("cloud-region.cloud-owner"); - relationshipData2.setRelationshipValue(CLOUD_OWNER); - relationshipToVserver.getRelationshipData().add(relationshipData2); - final RelationshipData relationshipData3 = new RelationshipData(); - relationshipData3.setRelationshipKey("cloud-region.cloud-region-id"); - relationshipData3.setRelationshipValue(REGION); - relationshipToVserver.getRelationshipData().add(relationshipData3); - final RelationshipData relationshipData4 = new RelationshipData(); - relationshipData4.setRelationshipKey("tenant.tenant-id"); - relationshipData4.setRelationshipValue(TENANT_ID); - relationshipToVserver.getRelationshipData().add(relationshipData4); - - if (genericVnf.getRelationshipList() == null) { - final RelationshipList relationshipList = new RelationshipList(); - genericVnf.setRelationshipList(relationshipList); - } - genericVnf.getRelationshipList().getRelationship().add(relationshipToVserver); - } - - private class AaiResourceUriMatcher extends BaseMatcher { - - final String uriAsString; - - public AaiResourceUriMatcher(final String uriAsString) { - this.uriAsString = uriAsString; - } - - @Override - public boolean matches(final Object item) { - if (item instanceof AAIResourceUri) { - if (uriAsString.endsWith("...")) { - return ((AAIResourceUri) item).build().toString() - .startsWith(uriAsString.substring(0, uriAsString.indexOf("..."))); - } - return ((AAIResourceUri) item).build().toString().equals(uriAsString); - } - return false; - } - - @Override - public void describeTo(final Description description) {} - - } - -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/test/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/rest/TestApplication.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/test/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/rest/TestApplication.java deleted file mode 100755 index 9c2453db85..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/test/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/rest/TestApplication.java +++ /dev/null @@ -1,38 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.lcm.rest; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration; -import org.springframework.cache.annotation.EnableCaching; - -@EnableCaching -@SpringBootApplication(scanBasePackages = {"org.onap.so"}) -@EnableAutoConfiguration(exclude = {JacksonAutoConfiguration.class}) -public class TestApplication { - - public static void main(final String[] args) { - new SpringApplication(TestApplication.class).run(args); - } - -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/test/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/rest/VnfmAdapterControllerTest.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/test/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/rest/VnfmAdapterControllerTest.java deleted file mode 100644 index 2901af7673..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/test/java/org/onap/so/adapters/etsi/sol003/adapter/lcm/rest/VnfmAdapterControllerTest.java +++ /dev/null @@ -1,561 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.lcm.rest; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.timeout; -import static org.mockito.Mockito.verify; -import static org.onap.so.client.RestTemplateConfig.CONFIGURABLE_REST_TEMPLATE; -import static org.springframework.test.web.client.match.MockRestRequestMatchers.content; -import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; -import static org.springframework.test.web.client.response.MockRestResponseCreators.withBadRequest; -import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus; -import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; -import java.net.URI; -import java.util.Optional; -import org.hamcrest.BaseMatcher; -import org.hamcrest.Description; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.ArgumentCaptor; -import org.mockito.hamcrest.MockitoHamcrest; -import org.onap.aai.domain.yang.EsrSystemInfo; -import org.onap.aai.domain.yang.EsrSystemInfoList; -import org.onap.aai.domain.yang.EsrVnfm; -import org.onap.aai.domain.yang.EsrVnfmList; -import org.onap.aai.domain.yang.GenericVnf; -import org.onap.aai.domain.yang.Relationship; -import org.onap.aai.domain.yang.RelationshipData; -import org.onap.aai.domain.yang.RelationshipList; -import org.onap.etsi.sol003.adapter.lcm.v1.model.CreateVnfRequest; -import org.onap.etsi.sol003.adapter.lcm.v1.model.CreateVnfResponse; -import org.onap.etsi.sol003.adapter.lcm.v1.model.DeleteVnfResponse; -import org.onap.etsi.sol003.adapter.lcm.v1.model.OperationEnum; -import org.onap.etsi.sol003.adapter.lcm.v1.model.OperationStateEnum; -import org.onap.etsi.sol003.adapter.lcm.v1.model.QueryJobResponse; -import org.onap.etsi.sol003.adapter.lcm.v1.model.Tenant; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.SdcPackageProvider; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.model.InlineResponse200; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.model.InlineResponse2001; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.model.InlineResponse201; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.model.InlineResponse201.InstantiationStateEnum; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.model.InlineResponse201Links; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.model.InlineResponse201LinksSelf; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.lcn.JSON; -import org.onap.so.adapters.etsi.sol003.adapter.lcm.rest.exceptions.VnfmNotFoundException; -import org.onap.aaiclient.client.aai.AAIResourcesClient; -import org.onap.aaiclient.client.aai.AAIVersion; -import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.RequestEntity; -import org.springframework.http.ResponseEntity; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.client.MockRestServiceServer; -import org.springframework.web.client.RestTemplate; -import org.threeten.bp.LocalDateTime; -import org.threeten.bp.OffsetDateTime; -import org.threeten.bp.ZoneOffset; -import com.google.gson.Gson; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = TestApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) -@ActiveProfiles("test") -public class VnfmAdapterControllerTest { - - private static final OffsetDateTime JAN_1_2019_12_00 = - OffsetDateTime.of(LocalDateTime.of(2019, 1, 1, 12, 0), ZoneOffset.UTC); - private static final OffsetDateTime JAN_1_2019_1_00 = - OffsetDateTime.of(LocalDateTime.of(2019, 1, 1, 1, 0), ZoneOffset.UTC); - private static final String CLOUD_OWNER = "myTestCloudOwner"; - private static final String REGION = "myTestRegion"; - private static final String TENANT_ID = "myTestTenantId"; - - @LocalServerPort - private int port; - @Autowired - @Qualifier(CONFIGURABLE_REST_TEMPLATE) - private RestTemplate testRestTemplate; - private MockRestServiceServer mockRestServer; - - @MockBean - AAIResourcesClient aaiResourcesClient; - - @MockBean - SdcPackageProvider sdcPackageProvider; - - @Autowired - VnfmAdapterController controller; - Gson gson = new JSON().getGson(); - - @Before - public void setUp() throws Exception { - mockRestServer = MockRestServiceServer.bindTo(testRestTemplate).build(); - } - - @Test - public void createVnf_ValidRequest_Returns202AndJobId() throws Exception { - final Tenant tenant = new Tenant().cloudOwner(CLOUD_OWNER).regionName(REGION).tenantId(TENANT_ID); - final CreateVnfRequest createVnfRequest = new CreateVnfRequest().name("myTestName").tenant(tenant); - - setUpGenericVnfInMockAai("vnfmType2"); - setUpVnfmsInMockAai(); - setUpVimInMockAai(); - - final String expectedsubscriptionRequest = - "{\"filter\":{\"vnfInstanceSubscriptionFilter\":{\"vnfInstanceIds\":[\"vnfId\"]},\"notificationTypes\":[\"VnfLcmOperationOccurrenceNotification\"]},\"callbackUri\":\"https://so-vnfm-adapter.onap:30406/so/vnfm-adapter/v1/lcn/VnfLcmOperationOccurrenceNotification\",\"authentication\":{\"authType\":[\"OAUTH2_CLIENT_CREDENTIALS\", \"BASIC\", \"TLS_CERT\"],\"paramsOauth2ClientCredentials\":{\"clientId\":\"vnfm\",\"clientPassword\":\"password1$\",\"tokenEndpoint\":\"https://so-vnfm-adapter.onap:30406/oauth/token\"},\"paramsBasic\":{\"userName\":\"vnfm\",\"password\":\"password1$\"}}}"; - final InlineResponse2001 subscriptionResponse = new InlineResponse2001(); - - final InlineResponse201 createResponse = createCreateResponse(); - mockRestServer.expect(requestTo("http://vnfm2:8080/vnf_instances")) - .andRespond(withSuccess(gson.toJson(createResponse), MediaType.APPLICATION_JSON)); - - mockRestServer.expect(requestTo("http://vnfm2:8080/subscriptions")) - .andExpect(content().json(expectedsubscriptionRequest)) - .andRespond(withSuccess(gson.toJson(subscriptionResponse), MediaType.APPLICATION_JSON)); - - mockRestServer.expect(requestTo("http://vnfm2:8080/vnf_instances/vnfId/instantiate")) - .andRespond(withStatus(HttpStatus.ACCEPTED).contentType(MediaType.APPLICATION_JSON) - .location(new URI("http://vnfm2:8080/vnf_lcm_op_occs/123456"))); - - final InlineResponse200 firstOperationQueryResponse = createOperationQueryResponse( - org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.model.InlineResponse200.OperationEnum.INSTANTIATE, - org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.model.InlineResponse200.OperationStateEnum.PROCESSING); - mockRestServer.expect(requestTo("http://vnfm2:8080/vnf_lcm_op_occs/123456")) - .andRespond(withSuccess(gson.toJson(firstOperationQueryResponse), MediaType.APPLICATION_JSON)); - - final InlineResponse200 secondOperationQueryReponse = createOperationQueryResponse( - org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.model.InlineResponse200.OperationEnum.INSTANTIATE, - org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.model.InlineResponse200.OperationStateEnum.COMPLETED); - mockRestServer.expect(requestTo("http://vnfm2:8080/vnf_lcm_op_occs/123456")) - .andRespond(withSuccess(gson.toJson(secondOperationQueryReponse), MediaType.APPLICATION_JSON)); - - // Invoke the create request - - final ResponseEntity createVnfResponse = - controller.vnfCreate("myTestVnfId", createVnfRequest, "asadas", "so", "1213"); - assertEquals(HttpStatus.ACCEPTED, createVnfResponse.getStatusCode()); - assertNotNull(createVnfResponse.getBody().getJobId()); - - final ArgumentCaptor genericVnfArgument = ArgumentCaptor.forClass(GenericVnf.class); - final ArgumentCaptor uriArgument = ArgumentCaptor.forClass(AAIResourceUri.class); - - verify(aaiResourcesClient).update(uriArgument.capture(), genericVnfArgument.capture()); - - assertEquals("/network/generic-vnfs/generic-vnf/myTestVnfId", uriArgument.getValue().build().toString()); - - assertEquals("myTestVnfId", genericVnfArgument.getValue().getVnfId()); - - final ArgumentCaptor uriArgument1Connect = ArgumentCaptor.forClass(AAIResourceUri.class); - final ArgumentCaptor uriArgument2Connect = ArgumentCaptor.forClass(AAIResourceUri.class); - verify(aaiResourcesClient, timeout(1000)).connect(uriArgument1Connect.capture(), uriArgument2Connect.capture()); - assertEquals("/external-system/esr-vnfm-list/esr-vnfm/vnfm2", - uriArgument1Connect.getAllValues().get(0).build().toString()); - assertEquals("/network/generic-vnfs/generic-vnf/myTestVnfId", - uriArgument2Connect.getAllValues().get(0).build().toString()); - - // check the job status - - final ResponseEntity firstJobQueryResponse = - controller.jobQuery(createVnfResponse.getBody().getJobId(), "", "so", "1213"); - assertEquals(OperationEnum.INSTANTIATE, firstJobQueryResponse.getBody().getOperation()); - assertEquals(OperationStateEnum.PROCESSING, firstJobQueryResponse.getBody().getOperationState()); - assertEquals(JAN_1_2019_12_00, firstJobQueryResponse.getBody().getStartTime()); - assertEquals(JAN_1_2019_1_00, firstJobQueryResponse.getBody().getStateEnteredTime()); - - final ResponseEntity secondJobQueryResponse = - controller.jobQuery(createVnfResponse.getBody().getJobId(), "", "so", "1213"); - assertEquals(OperationEnum.INSTANTIATE, secondJobQueryResponse.getBody().getOperation()); - assertEquals(OperationStateEnum.COMPLETED, secondJobQueryResponse.getBody().getOperationState()); - assertEquals(JAN_1_2019_12_00, secondJobQueryResponse.getBody().getStartTime()); - assertEquals(JAN_1_2019_1_00, secondJobQueryResponse.getBody().getStateEnteredTime()); - } - - @Test(expected = IllegalArgumentException.class) - public void createVnf_VnfAlreadyExistsOnVnfm_ThrowsIllegalArgumentException() throws Exception { - final Tenant tenant = new Tenant().cloudOwner(CLOUD_OWNER).regionName(REGION).tenantId(TENANT_ID); - final CreateVnfRequest createVnfRequest = new CreateVnfRequest().name("myTestName").tenant(tenant); - - final GenericVnf genericVnf = setUpGenericVnfInMockAai("vnfmType1"); - addSelfLinkToGenericVnf(genericVnf); - addRelationshipFromGenericVnfToVnfm(genericVnf, "vnfm1"); - setUpVnfmsInMockAai(); - - final InlineResponse201 reponse = new InlineResponse201(); - mockRestServer.expect(requestTo(new URI("http://vnfm:8080/vnfs/myTestVnfIdOnVnfm"))) - .andRespond(withSuccess(gson.toJson(reponse), MediaType.APPLICATION_JSON)); - - controller.vnfCreate("myTestVnfId", createVnfRequest, "asadas", "so", "1213"); - } - - @Test(expected = VnfmNotFoundException.class) - public void createVnf_NoMatchingVnfmFound_ThrowsException() throws Exception { - final Tenant tenant = new Tenant().cloudOwner(CLOUD_OWNER).regionName(REGION).tenantId(TENANT_ID); - final CreateVnfRequest createVnfRequest = new CreateVnfRequest().name("myTestName").tenant(tenant); - - setUpGenericVnfInMockAai("anotherType"); - setUpVnfmsInMockAai(); - - controller.vnfCreate("myTestVnfId", createVnfRequest, "asadas", "so", "1213"); - } - - @Test - public void createVnf_VnfmAlreadyAssociatedWithVnf_Returns202AndJobId() throws Exception { - final Tenant tenant = new Tenant().cloudOwner(CLOUD_OWNER).regionName(REGION).tenantId(TENANT_ID); - final CreateVnfRequest createVnfRequest = new CreateVnfRequest().name("myTestName").tenant(tenant); - - final GenericVnf genericVnf = setUpGenericVnfInMockAai("vnfmType2"); - addRelationshipFromGenericVnfToVnfm(genericVnf, "vnfm2"); - setUpVnfmsInMockAai(); - setUpVimInMockAai(); - - final InlineResponse201 createResponse = createCreateResponse(); - mockRestServer.expect(requestTo("http://vnfm2:8080/vnf_instances")) - .andRespond(withSuccess(gson.toJson(createResponse), MediaType.APPLICATION_JSON)); - - mockRestServer.expect(requestTo("http://vnfm2:8080/subscriptions")).andRespond(withBadRequest()); - - mockRestServer.expect(requestTo("http://vnfm2:8080/vnf_instances/vnfId/instantiate")) - .andRespond(withStatus(HttpStatus.ACCEPTED).contentType(MediaType.APPLICATION_JSON) - .location(new URI("http://vnfm2:8080/vnf_lcm_op_occs/123456"))); - - final ResponseEntity response = - controller.vnfCreate("myTestVnfId", createVnfRequest, "asadas", "so", "1213"); - assertEquals(HttpStatus.ACCEPTED, response.getStatusCode()); - assertNotNull(response.getBody().getJobId()); - } - - @Test - @Ignore - public void createVnf_UnauthorizedUser_Returns401() throws Exception { - final TestRestTemplate restTemplateWrongPassword = new TestRestTemplate("test", "wrongPassword"); - final Tenant tenant = new Tenant().cloudOwner(CLOUD_OWNER).regionName(REGION).tenantId(TENANT_ID); - final CreateVnfRequest createVnfRequest = new CreateVnfRequest().name("myTestName").tenant(tenant); - - final RequestEntity request = - RequestEntity.post(new URI("http://localhost:" + port + "/so/vnfm-adapter/v1/vnfs/myVnfId")) - .accept(MediaType.APPLICATION_JSON).contentType(MediaType.APPLICATION_JSON) - .header("X-ONAP-RequestId", "myRequestId").header("X-ONAP-InvocationID", "myInvocationId") - .body(createVnfRequest); - final ResponseEntity response = - restTemplateWrongPassword.exchange(request, CreateVnfResponse.class); - assertEquals(401, response.getStatusCode().value()); - } - - @Test - public void deleteVnf_ValidRequest_Returns202AndJobId() throws Exception { - final TestRestTemplate restTemplate = new TestRestTemplate("test", "test"); - - final GenericVnf genericVnf = setUpGenericVnfInMockAai("vnfmType1"); - addSelfLinkToGenericVnf(genericVnf); - addRelationshipFromGenericVnfToVnfm(genericVnf, "vnfm1"); - setUpVnfmsInMockAai(); - - mockRestServer.expect(requestTo("http://vnfm:8080/vnfs/myTestVnfIdOnVnfm/terminate")) - .andRespond(withStatus(HttpStatus.ACCEPTED).contentType(MediaType.APPLICATION_JSON) - .location(new URI("http://vnfm1:8080/vnf_lcm_op_occs/1234567"))); - - final InlineResponse200 firstOperationQueryResponse = createOperationQueryResponse( - org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.model.InlineResponse200.OperationEnum.TERMINATE, - org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.model.InlineResponse200.OperationStateEnum.PROCESSING); - mockRestServer.expect(requestTo("http://vnfm1:8080/vnf_lcm_op_occs/1234567")) - .andRespond(withSuccess(gson.toJson(firstOperationQueryResponse), MediaType.APPLICATION_JSON)); - - final InlineResponse200 secondOperationQueryReponse = createOperationQueryResponse( - org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.model.InlineResponse200.OperationEnum.TERMINATE, - org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.model.InlineResponse200.OperationStateEnum.COMPLETED); - mockRestServer.expect(requestTo("http://vnfm1:8080/vnf_lcm_op_occs/1234567")) - .andRespond(withSuccess(gson.toJson(secondOperationQueryReponse), MediaType.APPLICATION_JSON)); - - final RequestEntity request = RequestEntity - .delete(new URI("http://localhost:" + port + "/so/vnfm-adapter/v1/vnfs/myTestVnfId")) - .accept(MediaType.APPLICATION_JSON).header("X-ONAP-RequestId", "myRequestId") - .header("X-ONAP-InvocationID", "myInvocationId").header("Content-Type", "application/json").build(); - final ResponseEntity deleteVnfResponse = - restTemplate.exchange(request, DeleteVnfResponse.class); - assertEquals(202, deleteVnfResponse.getStatusCode().value()); - assertNotNull(deleteVnfResponse.getBody().getJobId()); - - final ResponseEntity firstJobQueryResponse = - controller.jobQuery(deleteVnfResponse.getBody().getJobId(), "", "so", "1213"); - assertEquals(OperationEnum.TERMINATE, firstJobQueryResponse.getBody().getOperation()); - assertEquals(OperationStateEnum.PROCESSING, firstJobQueryResponse.getBody().getOperationState()); - assertEquals(JAN_1_2019_12_00, firstJobQueryResponse.getBody().getStartTime()); - assertEquals(JAN_1_2019_1_00, firstJobQueryResponse.getBody().getStateEnteredTime()); - - final ResponseEntity secondJobQueryResponse = - controller.jobQuery(deleteVnfResponse.getBody().getJobId(), "", "so", "1213"); - assertEquals(OperationEnum.TERMINATE, secondJobQueryResponse.getBody().getOperation()); - assertEquals(OperationStateEnum.PROCESSING, secondJobQueryResponse.getBody().getOperationState()); - assertEquals(JAN_1_2019_12_00, secondJobQueryResponse.getBody().getStartTime()); - assertEquals(JAN_1_2019_1_00, secondJobQueryResponse.getBody().getStateEnteredTime()); - } - - @Test - public void deleteVnf_VnfAlreadyTerminated_Returns202AndJobId() throws Exception { - final TestRestTemplate restTemplate = new TestRestTemplate("test", "test"); - - final GenericVnf genericVnf = setUpGenericVnfInMockAai("vnfmType1"); - addSelfLinkToGenericVnf(genericVnf); - addRelationshipFromGenericVnfToVnfm(genericVnf, "vnfm1"); - setUpVnfmsInMockAai(); - - mockRestServer.expect(requestTo("http://vnfm:8080/vnfs/myTestVnfIdOnVnfm/terminate")) - .andRespond(withStatus(HttpStatus.CONFLICT).contentType(MediaType.APPLICATION_JSON)); - - final InlineResponse201 reponse = new InlineResponse201(); - reponse.setInstantiationState(InstantiationStateEnum.NOT_INSTANTIATED); - mockRestServer.expect(requestTo(new URI("http://vnfm:8080/vnfs/myTestVnfIdOnVnfm"))) - .andRespond(withSuccess(gson.toJson(reponse), MediaType.APPLICATION_JSON)); - - mockRestServer.expect(requestTo("http://vnfm:8080/vnfs/myTestVnfIdOnVnfm")) - .andRespond(withStatus(HttpStatus.NO_CONTENT).contentType(MediaType.APPLICATION_JSON)); - - final RequestEntity request = RequestEntity - .delete(new URI("http://localhost:" + port + "/so/vnfm-adapter/v1/vnfs/myTestVnfId")) - .accept(MediaType.APPLICATION_JSON).header("X-ONAP-RequestId", "myRequestId") - .header("X-ONAP-InvocationID", "myInvocationId").header("Content-Type", "application/json").build(); - final ResponseEntity deleteVnfResponse = - restTemplate.exchange(request, DeleteVnfResponse.class); - assertEquals(202, deleteVnfResponse.getStatusCode().value()); - assertNotNull(deleteVnfResponse.getBody().getJobId()); - - final ResponseEntity jobQueryResponse = - controller.jobQuery(deleteVnfResponse.getBody().getJobId(), "", "so", "1213"); - assertEquals(OperationStateEnum.COMPLETED, jobQueryResponse.getBody().getOperationState()); - } - - @Test - public void deleteVnf_GenericVnfNotFound_Returns404() throws Exception { - final TestRestTemplate restTemplate = new TestRestTemplate("test", "test"); - - final RequestEntity request = RequestEntity - .delete(new URI("http://localhost:" + port + "/so/vnfm-adapter/v1/vnfs/myNonExistingVnfId")) - .accept(MediaType.APPLICATION_JSON).header("X-ONAP-RequestId", "myRequestId") - .header("X-ONAP-InvocationID", "myInvocationId").header("Content-Type", "application/json").build(); - final ResponseEntity deleteVnfResponse = - restTemplate.exchange(request, DeleteVnfResponse.class); - assertEquals(404, deleteVnfResponse.getStatusCode().value()); - assertNull(deleteVnfResponse.getBody().getJobId()); - } - - @Test - public void deleteVnf_NoAssignedVnfm_Returns400() throws Exception { - final TestRestTemplate restTemplate = new TestRestTemplate("test", "test"); - - setUpGenericVnfInMockAai("vnfmType"); - - final RequestEntity request = RequestEntity - .delete(new URI("http://localhost:" + port + "/so/vnfm-adapter/v1/vnfs/myTestVnfId")) - .accept(MediaType.APPLICATION_JSON).header("X-ONAP-RequestId", "myRequestId") - .header("X-ONAP-InvocationID", "myInvocationId").header("Content-Type", "application/json").build(); - final ResponseEntity deleteVnfResponse = - restTemplate.exchange(request, DeleteVnfResponse.class); - assertEquals(400, deleteVnfResponse.getStatusCode().value()); - assertNull(deleteVnfResponse.getBody().getJobId()); - } - - @Test - public void deleteVnf_ErrorStatusCodeFromVnfm_Returns500() throws Exception { - final TestRestTemplate restTemplate = new TestRestTemplate("test", "test"); - - final GenericVnf genericVnf = setUpGenericVnfInMockAai("vnfmType1"); - addSelfLinkToGenericVnf(genericVnf); - addRelationshipFromGenericVnfToVnfm(genericVnf, "vnfm1"); - setUpVnfmsInMockAai(); - - mockRestServer.expect(requestTo("http://vnfm:8080/vnfs/myTestVnfIdOnVnfm/terminate")) - .andRespond(withStatus(HttpStatus.BAD_REQUEST).contentType(MediaType.APPLICATION_JSON)); - - final RequestEntity request = RequestEntity - .delete(new URI("http://localhost:" + port + "/so/vnfm-adapter/v1/vnfs/myTestVnfId")) - .accept(MediaType.APPLICATION_JSON).header("X-ONAP-RequestId", "myRequestId") - .header("X-ONAP-InvocationID", "myInvocationId").header("Content-Type", "application/json").build(); - final ResponseEntity deleteVnfResponse = - restTemplate.exchange(request, DeleteVnfResponse.class); - assertEquals(500, deleteVnfResponse.getStatusCode().value()); - assertNull(deleteVnfResponse.getBody().getJobId()); - - } - - private InlineResponse200 createOperationQueryResponse( - final org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.model.InlineResponse200.OperationEnum operation, - final org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.model.InlineResponse200.OperationStateEnum operationState) { - final InlineResponse200 response = new InlineResponse200(); - response.setId("9876"); - response.setOperation(operation); - response.setOperationState(operationState); - response.setStartTime(JAN_1_2019_12_00); - response.setStateEnteredTime(JAN_1_2019_1_00); - response.setVnfInstanceId("myVnfInstanceId"); - return response; - } - - private GenericVnf createGenericVnf(final String type) { - final GenericVnf genericVnf = new GenericVnf(); - genericVnf.setVnfId("myTestVnfId"); - genericVnf.setNfType(type); - return genericVnf; - } - - private GenericVnf setUpGenericVnfInMockAai(final String type) { - final GenericVnf genericVnf = createGenericVnf(type); - - doReturn(Optional.of(genericVnf)).when(aaiResourcesClient).get(eq(GenericVnf.class), - MockitoHamcrest.argThat(new AaiResourceUriMatcher("/network/generic-vnfs/generic-vnf/myTestVnfId"))); - return genericVnf; - } - - private void addSelfLinkToGenericVnf(final GenericVnf vnf) { - vnf.setSelflink("http://vnfm:8080/vnfs/myTestVnfIdOnVnfm"); - } - - private void addRelationshipFromGenericVnfToVnfm(final GenericVnf genericVnf, final String vnfmId) { - final Relationship relationshipToVnfm = new Relationship(); - relationshipToVnfm - .setRelatedLink("/aai/" + AAIVersion.LATEST + "/external-system/esr-vnfm-list/esr-vnfm/" + vnfmId); - relationshipToVnfm.setRelatedTo("esr-vnfm"); - final RelationshipData relationshipData = new RelationshipData(); - relationshipData.setRelationshipKey("esr-vnfm.vnfm-id"); - relationshipData.setRelationshipValue(vnfmId); - relationshipToVnfm.getRelationshipData().add(relationshipData); - - final RelationshipList relationshipList = new RelationshipList(); - relationshipList.getRelationship().add(relationshipToVnfm); - genericVnf.setRelationshipList(relationshipList); - } - - private void setUpVnfmsInMockAai() { - final EsrSystemInfo esrSystemInfo1 = new EsrSystemInfo(); - esrSystemInfo1.setServiceUrl("http://vnfm1:8080"); - esrSystemInfo1.setType("vnfmType1"); - esrSystemInfo1.setSystemType("VNFM"); - final EsrSystemInfoList esrSystemInfoList1 = new EsrSystemInfoList(); - esrSystemInfoList1.getEsrSystemInfo().add(esrSystemInfo1); - - final EsrVnfm esrVnfm1 = new EsrVnfm(); - esrVnfm1.setVnfmId("vnfm1"); - esrVnfm1.setEsrSystemInfoList(esrSystemInfoList1); - esrVnfm1.setResourceVersion("1234"); - - final EsrSystemInfo esrSystemInfo2 = new EsrSystemInfo(); - esrSystemInfo2.setServiceUrl("http://vnfm2:8080"); - esrSystemInfo2.setType("vnfmType2"); - esrSystemInfo2.setSystemType("VNFM"); - final EsrSystemInfoList esrSystemInfoList2 = new EsrSystemInfoList(); - esrSystemInfoList2.getEsrSystemInfo().add(esrSystemInfo2); - - final EsrVnfm esrVnfm2 = new EsrVnfm(); - esrVnfm2.setVnfmId("vnfm2"); - esrVnfm2.setEsrSystemInfoList(esrSystemInfoList2); - esrVnfm2.setResourceVersion("1234"); - - final EsrVnfmList esrVnfmList = new EsrVnfmList(); - esrVnfmList.getEsrVnfm().add(esrVnfm1); - esrVnfmList.getEsrVnfm().add(esrVnfm2); - - doReturn(Optional.of(esrVnfm1)).when(aaiResourcesClient).get(eq(EsrVnfm.class), MockitoHamcrest - .argThat(new AaiResourceUriMatcher("/external-system/esr-vnfm-list/esr-vnfm/vnfm1?depth=1"))); - - doReturn(Optional.of(esrVnfm2)).when(aaiResourcesClient).get(eq(EsrVnfm.class), MockitoHamcrest - .argThat(new AaiResourceUriMatcher("/external-system/esr-vnfm-list/esr-vnfm/vnfm2?depth=1"))); - - doReturn(Optional.of(esrVnfmList)).when(aaiResourcesClient).get(eq(EsrVnfmList.class), - MockitoHamcrest.argThat(new AaiResourceUriMatcher("/external-system/esr-vnfm-list"))); - - doReturn(Optional.of(esrSystemInfoList1)).when(aaiResourcesClient).get(eq(EsrSystemInfoList.class), - MockitoHamcrest.argThat(new AaiResourceUriMatcher( - "/external-system/esr-vnfm-list/esr-vnfm/vnfm1/esr-system-info-list"))); - doReturn(Optional.of(esrSystemInfoList2)).when(aaiResourcesClient).get(eq(EsrSystemInfoList.class), - MockitoHamcrest.argThat(new AaiResourceUriMatcher( - "/external-system/esr-vnfm-list/esr-vnfm/vnfm2/esr-system-info-list"))); - } - - private void setUpVimInMockAai() { - final EsrSystemInfo esrSystemInfo = new EsrSystemInfo(); - esrSystemInfo.setServiceUrl("http://myVim:8080"); - esrSystemInfo.setType("openstack"); - esrSystemInfo.setSystemType("VIM"); - esrSystemInfo.setCloudDomain("myDomain"); - esrSystemInfo.setUserName("myUser"); - esrSystemInfo.setPassword("myPassword"); - - final EsrSystemInfoList esrSystemInfoList = new EsrSystemInfoList(); - esrSystemInfoList.getEsrSystemInfo().add(esrSystemInfo); - - doReturn(Optional.of(esrSystemInfoList)).when(aaiResourcesClient).get(eq(EsrSystemInfoList.class), - MockitoHamcrest.argThat(new AaiResourceUriMatcher("/cloud-infrastructure/cloud-regions/cloud-region/" - + CLOUD_OWNER + "/" + REGION + "/esr-system-info-list"))); - } - - private InlineResponse201 createCreateResponse() { - final InlineResponse201 createResponse = new InlineResponse201(); - createResponse.setVnfdId("myTestVnfd"); - final InlineResponse201Links links = new InlineResponse201Links(); - final InlineResponse201LinksSelf self = new InlineResponse201LinksSelf(); - self.setHref("http://vnfm2:8080/vnf_instances/vnfId"); - links.setSelf(self); - createResponse.setLinks(links); - createResponse.setId("vnfId"); - return createResponse; - } - - - private class AaiResourceUriMatcher extends BaseMatcher { - - final String uriAsString; - - public AaiResourceUriMatcher(final String uriAsString) { - this.uriAsString = uriAsString; - } - - @Override - public boolean matches(final Object item) { - if (item instanceof AAIResourceUri) { - if (uriAsString.endsWith("...")) { - return ((AAIResourceUri) item).build().toString() - .startsWith(uriAsString.substring(0, uriAsString.indexOf("..."))); - } - return ((AAIResourceUri) item).build().toString().equals(uriAsString); - } - return false; - } - - @Override - public void describeTo(final Description description) {} - - } - -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/test/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/EtsiSol003AdapterControllerTest.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/test/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/EtsiSol003AdapterControllerTest.java new file mode 100644 index 0000000000..eaf40b546f --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/test/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/EtsiSol003AdapterControllerTest.java @@ -0,0 +1,561 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.lcm.rest; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.timeout; +import static org.mockito.Mockito.verify; +import static org.onap.so.client.RestTemplateConfig.CONFIGURABLE_REST_TEMPLATE; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.content; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; +import static org.springframework.test.web.client.response.MockRestResponseCreators.withBadRequest; +import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus; +import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; +import java.net.URI; +import java.util.Optional; +import org.hamcrest.BaseMatcher; +import org.hamcrest.Description; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.hamcrest.MockitoHamcrest; +import org.onap.aai.domain.yang.EsrSystemInfo; +import org.onap.aai.domain.yang.EsrSystemInfoList; +import org.onap.aai.domain.yang.EsrVnfm; +import org.onap.aai.domain.yang.EsrVnfmList; +import org.onap.aai.domain.yang.GenericVnf; +import org.onap.aai.domain.yang.Relationship; +import org.onap.aai.domain.yang.RelationshipData; +import org.onap.aai.domain.yang.RelationshipList; +import org.onap.aaiclient.client.aai.AAIResourcesClient; +import org.onap.aaiclient.client.aai.AAIVersion; +import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.SdcPackageProvider; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.InlineResponse200; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.InlineResponse2001; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.InlineResponse201; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.InlineResponse201.InstantiationStateEnum; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.InlineResponse201Links; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.InlineResponse201LinksSelf; +import org.onap.so.adapters.etsisol003adapter.lcm.lcn.JSON; +import org.onap.so.adapters.etsisol003adapter.lcm.rest.exceptions.VnfmNotFoundException; +import org.onap.so.adapters.etsisol003adapter.lcm.v1.model.CreateVnfRequest; +import org.onap.so.adapters.etsisol003adapter.lcm.v1.model.CreateVnfResponse; +import org.onap.so.adapters.etsisol003adapter.lcm.v1.model.DeleteVnfResponse; +import org.onap.so.adapters.etsisol003adapter.lcm.v1.model.OperationEnum; +import org.onap.so.adapters.etsisol003adapter.lcm.v1.model.OperationStateEnum; +import org.onap.so.adapters.etsisol003adapter.lcm.v1.model.QueryJobResponse; +import org.onap.so.adapters.etsisol003adapter.lcm.v1.model.Tenant; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.RequestEntity; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.client.MockRestServiceServer; +import org.springframework.web.client.RestTemplate; +import org.threeten.bp.LocalDateTime; +import org.threeten.bp.OffsetDateTime; +import org.threeten.bp.ZoneOffset; +import com.google.gson.Gson; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = TestApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) +@ActiveProfiles("test") +public class EtsiSol003AdapterControllerTest { + + private static final OffsetDateTime JAN_1_2019_12_00 = + OffsetDateTime.of(LocalDateTime.of(2019, 1, 1, 12, 0), ZoneOffset.UTC); + private static final OffsetDateTime JAN_1_2019_1_00 = + OffsetDateTime.of(LocalDateTime.of(2019, 1, 1, 1, 0), ZoneOffset.UTC); + private static final String CLOUD_OWNER = "myTestCloudOwner"; + private static final String REGION = "myTestRegion"; + private static final String TENANT_ID = "myTestTenantId"; + + @LocalServerPort + private int port; + @Autowired + @Qualifier(CONFIGURABLE_REST_TEMPLATE) + private RestTemplate testRestTemplate; + private MockRestServiceServer mockRestServer; + + @MockBean + AAIResourcesClient aaiResourcesClient; + + @MockBean + SdcPackageProvider sdcPackageProvider; + + @Autowired + EtsiSol003AdapterController controller; + Gson gson = new JSON().getGson(); + + @Before + public void setUp() throws Exception { + mockRestServer = MockRestServiceServer.bindTo(testRestTemplate).build(); + } + + @Test + public void createVnf_ValidRequest_Returns202AndJobId() throws Exception { + final Tenant tenant = new Tenant().cloudOwner(CLOUD_OWNER).regionName(REGION).tenantId(TENANT_ID); + final CreateVnfRequest createVnfRequest = new CreateVnfRequest().name("myTestName").tenant(tenant); + + setUpGenericVnfInMockAai("vnfmType2"); + setUpVnfmsInMockAai(); + setUpVimInMockAai(); + + final String expectedsubscriptionRequest = + "{\"filter\":{\"vnfInstanceSubscriptionFilter\":{\"vnfInstanceIds\":[\"vnfId\"]},\"notificationTypes\":[\"VnfLcmOperationOccurrenceNotification\"]},\"callbackUri\":\"https://so-vnfm-adapter.onap:30406/so/vnfm-adapter/v1/lcn/VnfLcmOperationOccurrenceNotification\",\"authentication\":{\"authType\":[\"OAUTH2_CLIENT_CREDENTIALS\", \"BASIC\", \"TLS_CERT\"],\"paramsOauth2ClientCredentials\":{\"clientId\":\"vnfm\",\"clientPassword\":\"password1$\",\"tokenEndpoint\":\"https://so-vnfm-adapter.onap:30406/oauth/token\"},\"paramsBasic\":{\"userName\":\"vnfm\",\"password\":\"password1$\"}}}"; + final InlineResponse2001 subscriptionResponse = new InlineResponse2001(); + + final InlineResponse201 createResponse = createCreateResponse(); + mockRestServer.expect(requestTo("http://vnfm2:8080/vnf_instances")) + .andRespond(withSuccess(gson.toJson(createResponse), MediaType.APPLICATION_JSON)); + + mockRestServer.expect(requestTo("http://vnfm2:8080/subscriptions")) + .andExpect(content().json(expectedsubscriptionRequest)) + .andRespond(withSuccess(gson.toJson(subscriptionResponse), MediaType.APPLICATION_JSON)); + + mockRestServer.expect(requestTo("http://vnfm2:8080/vnf_instances/vnfId/instantiate")) + .andRespond(withStatus(HttpStatus.ACCEPTED).contentType(MediaType.APPLICATION_JSON) + .location(new URI("http://vnfm2:8080/vnf_lcm_op_occs/123456"))); + + final InlineResponse200 firstOperationQueryResponse = createOperationQueryResponse( + org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.InlineResponse200.OperationEnum.INSTANTIATE, + org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.InlineResponse200.OperationStateEnum.PROCESSING); + mockRestServer.expect(requestTo("http://vnfm2:8080/vnf_lcm_op_occs/123456")) + .andRespond(withSuccess(gson.toJson(firstOperationQueryResponse), MediaType.APPLICATION_JSON)); + + final InlineResponse200 secondOperationQueryReponse = createOperationQueryResponse( + org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.InlineResponse200.OperationEnum.INSTANTIATE, + org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.InlineResponse200.OperationStateEnum.COMPLETED); + mockRestServer.expect(requestTo("http://vnfm2:8080/vnf_lcm_op_occs/123456")) + .andRespond(withSuccess(gson.toJson(secondOperationQueryReponse), MediaType.APPLICATION_JSON)); + + // Invoke the create request + + final ResponseEntity createVnfResponse = + controller.vnfCreate("myTestVnfId", createVnfRequest, "asadas", "so", "1213"); + assertEquals(HttpStatus.ACCEPTED, createVnfResponse.getStatusCode()); + assertNotNull(createVnfResponse.getBody().getJobId()); + + final ArgumentCaptor genericVnfArgument = ArgumentCaptor.forClass(GenericVnf.class); + final ArgumentCaptor uriArgument = ArgumentCaptor.forClass(AAIResourceUri.class); + + verify(aaiResourcesClient).update(uriArgument.capture(), genericVnfArgument.capture()); + + assertEquals("/network/generic-vnfs/generic-vnf/myTestVnfId", uriArgument.getValue().build().toString()); + + assertEquals("myTestVnfId", genericVnfArgument.getValue().getVnfId()); + + final ArgumentCaptor uriArgument1Connect = ArgumentCaptor.forClass(AAIResourceUri.class); + final ArgumentCaptor uriArgument2Connect = ArgumentCaptor.forClass(AAIResourceUri.class); + verify(aaiResourcesClient, timeout(1000)).connect(uriArgument1Connect.capture(), uriArgument2Connect.capture()); + assertEquals("/external-system/esr-vnfm-list/esr-vnfm/vnfm2", + uriArgument1Connect.getAllValues().get(0).build().toString()); + assertEquals("/network/generic-vnfs/generic-vnf/myTestVnfId", + uriArgument2Connect.getAllValues().get(0).build().toString()); + + // check the job status + + final ResponseEntity firstJobQueryResponse = + controller.jobQuery(createVnfResponse.getBody().getJobId(), "", "so", "1213"); + assertEquals(OperationEnum.INSTANTIATE, firstJobQueryResponse.getBody().getOperation()); + assertEquals(OperationStateEnum.PROCESSING, firstJobQueryResponse.getBody().getOperationState()); + assertEquals(JAN_1_2019_12_00, firstJobQueryResponse.getBody().getStartTime()); + assertEquals(JAN_1_2019_1_00, firstJobQueryResponse.getBody().getStateEnteredTime()); + + final ResponseEntity secondJobQueryResponse = + controller.jobQuery(createVnfResponse.getBody().getJobId(), "", "so", "1213"); + assertEquals(OperationEnum.INSTANTIATE, secondJobQueryResponse.getBody().getOperation()); + assertEquals(OperationStateEnum.COMPLETED, secondJobQueryResponse.getBody().getOperationState()); + assertEquals(JAN_1_2019_12_00, secondJobQueryResponse.getBody().getStartTime()); + assertEquals(JAN_1_2019_1_00, secondJobQueryResponse.getBody().getStateEnteredTime()); + } + + @Test(expected = IllegalArgumentException.class) + public void createVnf_VnfAlreadyExistsOnVnfm_ThrowsIllegalArgumentException() throws Exception { + final Tenant tenant = new Tenant().cloudOwner(CLOUD_OWNER).regionName(REGION).tenantId(TENANT_ID); + final CreateVnfRequest createVnfRequest = new CreateVnfRequest().name("myTestName").tenant(tenant); + + final GenericVnf genericVnf = setUpGenericVnfInMockAai("vnfmType1"); + addSelfLinkToGenericVnf(genericVnf); + addRelationshipFromGenericVnfToVnfm(genericVnf, "vnfm1"); + setUpVnfmsInMockAai(); + + final InlineResponse201 reponse = new InlineResponse201(); + mockRestServer.expect(requestTo(new URI("http://vnfm:8080/vnfs/myTestVnfIdOnVnfm"))) + .andRespond(withSuccess(gson.toJson(reponse), MediaType.APPLICATION_JSON)); + + controller.vnfCreate("myTestVnfId", createVnfRequest, "asadas", "so", "1213"); + } + + @Test(expected = VnfmNotFoundException.class) + public void createVnf_NoMatchingVnfmFound_ThrowsException() throws Exception { + final Tenant tenant = new Tenant().cloudOwner(CLOUD_OWNER).regionName(REGION).tenantId(TENANT_ID); + final CreateVnfRequest createVnfRequest = new CreateVnfRequest().name("myTestName").tenant(tenant); + + setUpGenericVnfInMockAai("anotherType"); + setUpVnfmsInMockAai(); + + controller.vnfCreate("myTestVnfId", createVnfRequest, "asadas", "so", "1213"); + } + + @Test + public void createVnf_VnfmAlreadyAssociatedWithVnf_Returns202AndJobId() throws Exception { + final Tenant tenant = new Tenant().cloudOwner(CLOUD_OWNER).regionName(REGION).tenantId(TENANT_ID); + final CreateVnfRequest createVnfRequest = new CreateVnfRequest().name("myTestName").tenant(tenant); + + final GenericVnf genericVnf = setUpGenericVnfInMockAai("vnfmType2"); + addRelationshipFromGenericVnfToVnfm(genericVnf, "vnfm2"); + setUpVnfmsInMockAai(); + setUpVimInMockAai(); + + final InlineResponse201 createResponse = createCreateResponse(); + mockRestServer.expect(requestTo("http://vnfm2:8080/vnf_instances")) + .andRespond(withSuccess(gson.toJson(createResponse), MediaType.APPLICATION_JSON)); + + mockRestServer.expect(requestTo("http://vnfm2:8080/subscriptions")).andRespond(withBadRequest()); + + mockRestServer.expect(requestTo("http://vnfm2:8080/vnf_instances/vnfId/instantiate")) + .andRespond(withStatus(HttpStatus.ACCEPTED).contentType(MediaType.APPLICATION_JSON) + .location(new URI("http://vnfm2:8080/vnf_lcm_op_occs/123456"))); + + final ResponseEntity response = + controller.vnfCreate("myTestVnfId", createVnfRequest, "asadas", "so", "1213"); + assertEquals(HttpStatus.ACCEPTED, response.getStatusCode()); + assertNotNull(response.getBody().getJobId()); + } + + @Test + @Ignore + public void createVnf_UnauthorizedUser_Returns401() throws Exception { + final TestRestTemplate restTemplateWrongPassword = new TestRestTemplate("test", "wrongPassword"); + final Tenant tenant = new Tenant().cloudOwner(CLOUD_OWNER).regionName(REGION).tenantId(TENANT_ID); + final CreateVnfRequest createVnfRequest = new CreateVnfRequest().name("myTestName").tenant(tenant); + + final RequestEntity request = + RequestEntity.post(new URI("http://localhost:" + port + "/so/vnfm-adapter/v1/vnfs/myVnfId")) + .accept(MediaType.APPLICATION_JSON).contentType(MediaType.APPLICATION_JSON) + .header("X-ONAP-RequestId", "myRequestId").header("X-ONAP-InvocationID", "myInvocationId") + .body(createVnfRequest); + final ResponseEntity response = + restTemplateWrongPassword.exchange(request, CreateVnfResponse.class); + assertEquals(401, response.getStatusCode().value()); + } + + @Test + public void deleteVnf_ValidRequest_Returns202AndJobId() throws Exception { + final TestRestTemplate restTemplate = new TestRestTemplate("test", "test"); + + final GenericVnf genericVnf = setUpGenericVnfInMockAai("vnfmType1"); + addSelfLinkToGenericVnf(genericVnf); + addRelationshipFromGenericVnfToVnfm(genericVnf, "vnfm1"); + setUpVnfmsInMockAai(); + + mockRestServer.expect(requestTo("http://vnfm:8080/vnfs/myTestVnfIdOnVnfm/terminate")) + .andRespond(withStatus(HttpStatus.ACCEPTED).contentType(MediaType.APPLICATION_JSON) + .location(new URI("http://vnfm1:8080/vnf_lcm_op_occs/1234567"))); + + final InlineResponse200 firstOperationQueryResponse = createOperationQueryResponse( + org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.InlineResponse200.OperationEnum.TERMINATE, + org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.InlineResponse200.OperationStateEnum.PROCESSING); + mockRestServer.expect(requestTo("http://vnfm1:8080/vnf_lcm_op_occs/1234567")) + .andRespond(withSuccess(gson.toJson(firstOperationQueryResponse), MediaType.APPLICATION_JSON)); + + final InlineResponse200 secondOperationQueryReponse = createOperationQueryResponse( + org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.InlineResponse200.OperationEnum.TERMINATE, + org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.InlineResponse200.OperationStateEnum.COMPLETED); + mockRestServer.expect(requestTo("http://vnfm1:8080/vnf_lcm_op_occs/1234567")) + .andRespond(withSuccess(gson.toJson(secondOperationQueryReponse), MediaType.APPLICATION_JSON)); + + final RequestEntity request = RequestEntity + .delete(new URI("http://localhost:" + port + "/so/vnfm-adapter/v1/vnfs/myTestVnfId")) + .accept(MediaType.APPLICATION_JSON).header("X-ONAP-RequestId", "myRequestId") + .header("X-ONAP-InvocationID", "myInvocationId").header("Content-Type", "application/json").build(); + final ResponseEntity deleteVnfResponse = + restTemplate.exchange(request, DeleteVnfResponse.class); + assertEquals(202, deleteVnfResponse.getStatusCode().value()); + assertNotNull(deleteVnfResponse.getBody().getJobId()); + + final ResponseEntity firstJobQueryResponse = + controller.jobQuery(deleteVnfResponse.getBody().getJobId(), "", "so", "1213"); + assertEquals(OperationEnum.TERMINATE, firstJobQueryResponse.getBody().getOperation()); + assertEquals(OperationStateEnum.PROCESSING, firstJobQueryResponse.getBody().getOperationState()); + assertEquals(JAN_1_2019_12_00, firstJobQueryResponse.getBody().getStartTime()); + assertEquals(JAN_1_2019_1_00, firstJobQueryResponse.getBody().getStateEnteredTime()); + + final ResponseEntity secondJobQueryResponse = + controller.jobQuery(deleteVnfResponse.getBody().getJobId(), "", "so", "1213"); + assertEquals(OperationEnum.TERMINATE, secondJobQueryResponse.getBody().getOperation()); + assertEquals(OperationStateEnum.PROCESSING, secondJobQueryResponse.getBody().getOperationState()); + assertEquals(JAN_1_2019_12_00, secondJobQueryResponse.getBody().getStartTime()); + assertEquals(JAN_1_2019_1_00, secondJobQueryResponse.getBody().getStateEnteredTime()); + } + + @Test + public void deleteVnf_VnfAlreadyTerminated_Returns202AndJobId() throws Exception { + final TestRestTemplate restTemplate = new TestRestTemplate("test", "test"); + + final GenericVnf genericVnf = setUpGenericVnfInMockAai("vnfmType1"); + addSelfLinkToGenericVnf(genericVnf); + addRelationshipFromGenericVnfToVnfm(genericVnf, "vnfm1"); + setUpVnfmsInMockAai(); + + mockRestServer.expect(requestTo("http://vnfm:8080/vnfs/myTestVnfIdOnVnfm/terminate")) + .andRespond(withStatus(HttpStatus.CONFLICT).contentType(MediaType.APPLICATION_JSON)); + + final InlineResponse201 reponse = new InlineResponse201(); + reponse.setInstantiationState(InstantiationStateEnum.NOT_INSTANTIATED); + mockRestServer.expect(requestTo(new URI("http://vnfm:8080/vnfs/myTestVnfIdOnVnfm"))) + .andRespond(withSuccess(gson.toJson(reponse), MediaType.APPLICATION_JSON)); + + mockRestServer.expect(requestTo("http://vnfm:8080/vnfs/myTestVnfIdOnVnfm")) + .andRespond(withStatus(HttpStatus.NO_CONTENT).contentType(MediaType.APPLICATION_JSON)); + + final RequestEntity request = RequestEntity + .delete(new URI("http://localhost:" + port + "/so/vnfm-adapter/v1/vnfs/myTestVnfId")) + .accept(MediaType.APPLICATION_JSON).header("X-ONAP-RequestId", "myRequestId") + .header("X-ONAP-InvocationID", "myInvocationId").header("Content-Type", "application/json").build(); + final ResponseEntity deleteVnfResponse = + restTemplate.exchange(request, DeleteVnfResponse.class); + assertEquals(202, deleteVnfResponse.getStatusCode().value()); + assertNotNull(deleteVnfResponse.getBody().getJobId()); + + final ResponseEntity jobQueryResponse = + controller.jobQuery(deleteVnfResponse.getBody().getJobId(), "", "so", "1213"); + assertEquals(OperationStateEnum.COMPLETED, jobQueryResponse.getBody().getOperationState()); + } + + @Test + public void deleteVnf_GenericVnfNotFound_Returns404() throws Exception { + final TestRestTemplate restTemplate = new TestRestTemplate("test", "test"); + + final RequestEntity request = RequestEntity + .delete(new URI("http://localhost:" + port + "/so/vnfm-adapter/v1/vnfs/myNonExistingVnfId")) + .accept(MediaType.APPLICATION_JSON).header("X-ONAP-RequestId", "myRequestId") + .header("X-ONAP-InvocationID", "myInvocationId").header("Content-Type", "application/json").build(); + final ResponseEntity deleteVnfResponse = + restTemplate.exchange(request, DeleteVnfResponse.class); + assertEquals(404, deleteVnfResponse.getStatusCode().value()); + assertNull(deleteVnfResponse.getBody().getJobId()); + } + + @Test + public void deleteVnf_NoAssignedVnfm_Returns400() throws Exception { + final TestRestTemplate restTemplate = new TestRestTemplate("test", "test"); + + setUpGenericVnfInMockAai("vnfmType"); + + final RequestEntity request = RequestEntity + .delete(new URI("http://localhost:" + port + "/so/vnfm-adapter/v1/vnfs/myTestVnfId")) + .accept(MediaType.APPLICATION_JSON).header("X-ONAP-RequestId", "myRequestId") + .header("X-ONAP-InvocationID", "myInvocationId").header("Content-Type", "application/json").build(); + final ResponseEntity deleteVnfResponse = + restTemplate.exchange(request, DeleteVnfResponse.class); + assertEquals(400, deleteVnfResponse.getStatusCode().value()); + assertNull(deleteVnfResponse.getBody().getJobId()); + } + + @Test + public void deleteVnf_ErrorStatusCodeFromVnfm_Returns500() throws Exception { + final TestRestTemplate restTemplate = new TestRestTemplate("test", "test"); + + final GenericVnf genericVnf = setUpGenericVnfInMockAai("vnfmType1"); + addSelfLinkToGenericVnf(genericVnf); + addRelationshipFromGenericVnfToVnfm(genericVnf, "vnfm1"); + setUpVnfmsInMockAai(); + + mockRestServer.expect(requestTo("http://vnfm:8080/vnfs/myTestVnfIdOnVnfm/terminate")) + .andRespond(withStatus(HttpStatus.BAD_REQUEST).contentType(MediaType.APPLICATION_JSON)); + + final RequestEntity request = RequestEntity + .delete(new URI("http://localhost:" + port + "/so/vnfm-adapter/v1/vnfs/myTestVnfId")) + .accept(MediaType.APPLICATION_JSON).header("X-ONAP-RequestId", "myRequestId") + .header("X-ONAP-InvocationID", "myInvocationId").header("Content-Type", "application/json").build(); + final ResponseEntity deleteVnfResponse = + restTemplate.exchange(request, DeleteVnfResponse.class); + assertEquals(500, deleteVnfResponse.getStatusCode().value()); + assertNull(deleteVnfResponse.getBody().getJobId()); + + } + + private InlineResponse200 createOperationQueryResponse( + final org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.InlineResponse200.OperationEnum operation, + final org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.InlineResponse200.OperationStateEnum operationState) { + final InlineResponse200 response = new InlineResponse200(); + response.setId("9876"); + response.setOperation(operation); + response.setOperationState(operationState); + response.setStartTime(JAN_1_2019_12_00); + response.setStateEnteredTime(JAN_1_2019_1_00); + response.setVnfInstanceId("myVnfInstanceId"); + return response; + } + + private GenericVnf createGenericVnf(final String type) { + final GenericVnf genericVnf = new GenericVnf(); + genericVnf.setVnfId("myTestVnfId"); + genericVnf.setNfType(type); + return genericVnf; + } + + private GenericVnf setUpGenericVnfInMockAai(final String type) { + final GenericVnf genericVnf = createGenericVnf(type); + + doReturn(Optional.of(genericVnf)).when(aaiResourcesClient).get(eq(GenericVnf.class), + MockitoHamcrest.argThat(new AaiResourceUriMatcher("/network/generic-vnfs/generic-vnf/myTestVnfId"))); + return genericVnf; + } + + private void addSelfLinkToGenericVnf(final GenericVnf vnf) { + vnf.setSelflink("http://vnfm:8080/vnfs/myTestVnfIdOnVnfm"); + } + + private void addRelationshipFromGenericVnfToVnfm(final GenericVnf genericVnf, final String vnfmId) { + final Relationship relationshipToVnfm = new Relationship(); + relationshipToVnfm + .setRelatedLink("/aai/" + AAIVersion.LATEST + "/external-system/esr-vnfm-list/esr-vnfm/" + vnfmId); + relationshipToVnfm.setRelatedTo("esr-vnfm"); + final RelationshipData relationshipData = new RelationshipData(); + relationshipData.setRelationshipKey("esr-vnfm.vnfm-id"); + relationshipData.setRelationshipValue(vnfmId); + relationshipToVnfm.getRelationshipData().add(relationshipData); + + final RelationshipList relationshipList = new RelationshipList(); + relationshipList.getRelationship().add(relationshipToVnfm); + genericVnf.setRelationshipList(relationshipList); + } + + private void setUpVnfmsInMockAai() { + final EsrSystemInfo esrSystemInfo1 = new EsrSystemInfo(); + esrSystemInfo1.setServiceUrl("http://vnfm1:8080"); + esrSystemInfo1.setType("vnfmType1"); + esrSystemInfo1.setSystemType("VNFM"); + final EsrSystemInfoList esrSystemInfoList1 = new EsrSystemInfoList(); + esrSystemInfoList1.getEsrSystemInfo().add(esrSystemInfo1); + + final EsrVnfm esrVnfm1 = new EsrVnfm(); + esrVnfm1.setVnfmId("vnfm1"); + esrVnfm1.setEsrSystemInfoList(esrSystemInfoList1); + esrVnfm1.setResourceVersion("1234"); + + final EsrSystemInfo esrSystemInfo2 = new EsrSystemInfo(); + esrSystemInfo2.setServiceUrl("http://vnfm2:8080"); + esrSystemInfo2.setType("vnfmType2"); + esrSystemInfo2.setSystemType("VNFM"); + final EsrSystemInfoList esrSystemInfoList2 = new EsrSystemInfoList(); + esrSystemInfoList2.getEsrSystemInfo().add(esrSystemInfo2); + + final EsrVnfm esrVnfm2 = new EsrVnfm(); + esrVnfm2.setVnfmId("vnfm2"); + esrVnfm2.setEsrSystemInfoList(esrSystemInfoList2); + esrVnfm2.setResourceVersion("1234"); + + final EsrVnfmList esrVnfmList = new EsrVnfmList(); + esrVnfmList.getEsrVnfm().add(esrVnfm1); + esrVnfmList.getEsrVnfm().add(esrVnfm2); + + doReturn(Optional.of(esrVnfm1)).when(aaiResourcesClient).get(eq(EsrVnfm.class), MockitoHamcrest + .argThat(new AaiResourceUriMatcher("/external-system/esr-vnfm-list/esr-vnfm/vnfm1?depth=1"))); + + doReturn(Optional.of(esrVnfm2)).when(aaiResourcesClient).get(eq(EsrVnfm.class), MockitoHamcrest + .argThat(new AaiResourceUriMatcher("/external-system/esr-vnfm-list/esr-vnfm/vnfm2?depth=1"))); + + doReturn(Optional.of(esrVnfmList)).when(aaiResourcesClient).get(eq(EsrVnfmList.class), + MockitoHamcrest.argThat(new AaiResourceUriMatcher("/external-system/esr-vnfm-list"))); + + doReturn(Optional.of(esrSystemInfoList1)).when(aaiResourcesClient).get(eq(EsrSystemInfoList.class), + MockitoHamcrest.argThat(new AaiResourceUriMatcher( + "/external-system/esr-vnfm-list/esr-vnfm/vnfm1/esr-system-info-list"))); + doReturn(Optional.of(esrSystemInfoList2)).when(aaiResourcesClient).get(eq(EsrSystemInfoList.class), + MockitoHamcrest.argThat(new AaiResourceUriMatcher( + "/external-system/esr-vnfm-list/esr-vnfm/vnfm2/esr-system-info-list"))); + } + + private void setUpVimInMockAai() { + final EsrSystemInfo esrSystemInfo = new EsrSystemInfo(); + esrSystemInfo.setServiceUrl("http://myVim:8080"); + esrSystemInfo.setType("openstack"); + esrSystemInfo.setSystemType("VIM"); + esrSystemInfo.setCloudDomain("myDomain"); + esrSystemInfo.setUserName("myUser"); + esrSystemInfo.setPassword("myPassword"); + + final EsrSystemInfoList esrSystemInfoList = new EsrSystemInfoList(); + esrSystemInfoList.getEsrSystemInfo().add(esrSystemInfo); + + doReturn(Optional.of(esrSystemInfoList)).when(aaiResourcesClient).get(eq(EsrSystemInfoList.class), + MockitoHamcrest.argThat(new AaiResourceUriMatcher("/cloud-infrastructure/cloud-regions/cloud-region/" + + CLOUD_OWNER + "/" + REGION + "/esr-system-info-list"))); + } + + private InlineResponse201 createCreateResponse() { + final InlineResponse201 createResponse = new InlineResponse201(); + createResponse.setVnfdId("myTestVnfd"); + final InlineResponse201Links links = new InlineResponse201Links(); + final InlineResponse201LinksSelf self = new InlineResponse201LinksSelf(); + self.setHref("http://vnfm2:8080/vnf_instances/vnfId"); + links.setSelf(self); + createResponse.setLinks(links); + createResponse.setId("vnfId"); + return createResponse; + } + + + private class AaiResourceUriMatcher extends BaseMatcher { + + final String uriAsString; + + public AaiResourceUriMatcher(final String uriAsString) { + this.uriAsString = uriAsString; + } + + @Override + public boolean matches(final Object item) { + if (item instanceof AAIResourceUri) { + if (uriAsString.endsWith("...")) { + return ((AAIResourceUri) item).build().toString() + .startsWith(uriAsString.substring(0, uriAsString.indexOf("..."))); + } + return ((AAIResourceUri) item).build().toString().equals(uriAsString); + } + return false; + } + + @Override + public void describeTo(final Description description) {} + + } + +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/test/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/HealthCheckTest.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/test/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/HealthCheckTest.java new file mode 100644 index 0000000000..9fa16b5551 --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/test/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/HealthCheckTest.java @@ -0,0 +1,54 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.lcm.rest; + +import static org.junit.Assert.assertEquals; +import java.net.URI; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.http.RequestEntity; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = TestApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) +@ActiveProfiles("test") +public class HealthCheckTest { + + @LocalServerPort + private int port; + + private final TestRestTemplate restTemplate = new TestRestTemplate("test", "test"); + + @Test + public void testHealthcheck() throws Exception { + final RequestEntity request = + RequestEntity.get(new URI("http://localhost:" + port + "/manage/health")).build(); + final ResponseEntity response = restTemplate.exchange(request, Void.class); + assertEquals(200, response.getStatusCode().value()); + } + +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/test/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/Sol003GrantControllerTest.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/test/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/Sol003GrantControllerTest.java new file mode 100644 index 0000000000..21e56617cd --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/test/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/Sol003GrantControllerTest.java @@ -0,0 +1,252 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.lcm.rest; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doReturn; +import static org.onap.so.client.RestTemplateConfig.CONFIGURABLE_REST_TEMPLATE; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import org.hamcrest.BaseMatcher; +import org.hamcrest.Description; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.hamcrest.MockitoHamcrest; +import org.onap.aai.domain.yang.EsrSystemInfo; +import org.onap.aai.domain.yang.EsrSystemInfoList; +import org.onap.aai.domain.yang.GenericVnf; +import org.onap.aai.domain.yang.GenericVnfs; +import org.onap.aai.domain.yang.Relationship; +import org.onap.aai.domain.yang.RelationshipData; +import org.onap.aai.domain.yang.RelationshipList; +import org.onap.aaiclient.client.aai.AAIResourcesClient; +import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri; +import org.onap.so.adapters.etsisol003adapter.lcm.grant.model.GrantRequest; +import org.onap.so.adapters.etsisol003adapter.lcm.grant.model.GrantRequest.OperationEnum; +import org.onap.so.adapters.etsisol003adapter.lcm.grant.model.GrantsAddResources; +import org.onap.so.adapters.etsisol003adapter.lcm.grant.model.GrantsAddResources.TypeEnum; +import org.onap.so.adapters.etsisol003adapter.lcm.grant.model.GrantsLinks; +import org.onap.so.adapters.etsisol003adapter.lcm.grant.model.GrantsLinksVnfLcmOpOcc; +import org.onap.so.adapters.etsisol003adapter.lcm.grant.model.InlineResponse201; +import org.onap.so.adapters.etsisol003adapter.lcm.grant.model.InlineResponse201VimConnections; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.web.client.RestTemplate; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = TestApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) +@ActiveProfiles("test") +public class Sol003GrantControllerTest { + + private static final String CLOUD_OWNER = "myTestCloudOwner"; + private static final String REGION = "myTestRegion"; + private static final String TENANT_ID = "myTestTenantId"; + private static final String SEPARATOR = "_"; + private static final String vimConnectionId = CLOUD_OWNER + SEPARATOR + REGION; + + @LocalServerPort + private int port; + @Autowired + @Qualifier(CONFIGURABLE_REST_TEMPLATE) + private RestTemplate testRestTemplate; + + @MockBean + private AAIResourcesClient aaiResourcesClient; + + @Autowired + private Sol003GrantController controller; + + @Before + public void setUp() throws Exception { + setUpVimInMockAai(); + } + + @Test + public void grantRequest_ValidRequestInstantiate_GrantApproved() { + final GrantRequest grantRequest = createGrantRequest("INSTANTIATE"); + setUpGenericVnfWithVnfmRelationshipInMockAai("vnfmType", "vnfm1"); + final ResponseEntity response = controller.grantsPost(grantRequest); + assertEquals(HttpStatus.CREATED, response.getStatusCode()); + assertEquals(1, response.getBody().getAddResources().size()); + assertNull(response.getBody().getRemoveResources()); + + assertEquals(vimConnectionId, response.getBody().getAddResources().get(0).getVimConnectionId()); + assertEquals("myTestVnfIdOnVnfm", response.getBody().getVnfInstanceId()); + assertEquals("123456", response.getBody().getVnfLcmOpOccId()); + + final InlineResponse201VimConnections vimConnections = response.getBody().getVimConnections().get(0); + assertEquals(vimConnectionId, vimConnections.getVimId()); + assertEquals("OPENSTACK", vimConnections.getVimType()); + assertNotNull(vimConnections.getAccessInfo()); + assertNotNull(vimConnections.getInterfaceInfo()); + assertEquals("INSTANTIATE", grantRequest.getOperation().toString()); + } + + @Test + public void getGrant_notSupported_returns501() { + final ResponseEntity response2 = controller.grantsGrantIdGet("myTestGrantId"); + assertEquals(HttpStatus.NOT_IMPLEMENTED, response2.getStatusCode()); + } + + @Test + public void grantRequest_ValidRequestTerminate_GrantApproved() { + final GrantRequest grantRequest = createGrantRequest("TERMINATE"); + setUpGenericVnfWithVnfmRelationshipInMockAai("vnfmType", "vnfm1"); + final ResponseEntity response = controller.grantsPost(grantRequest); + + assertEquals(HttpStatus.CREATED, response.getStatusCode()); + assertNull(response.getBody().getAddResources()); + assertEquals(1, response.getBody().getRemoveResources().size()); + assertEquals(vimConnectionId, response.getBody().getRemoveResources().get(0).getVimConnectionId()); + assertEquals("myTestVnfIdOnVnfm", response.getBody().getVnfInstanceId()); + assertEquals("123456", response.getBody().getVnfLcmOpOccId()); + + final InlineResponse201VimConnections vimConnections = response.getBody().getVimConnections().get(0); + assertEquals(vimConnectionId, vimConnections.getVimId()); + assertEquals("OPENSTACK", vimConnections.getVimType()); + assertNotNull(vimConnections.getAccessInfo()); + assertNotNull(vimConnections.getInterfaceInfo()); + assertEquals("TERMINATE", grantRequest.getOperation().toString()); + + } + + private GrantRequest createGrantRequest(final String operation) { + final GrantRequest grantRequest = new GrantRequest(); + grantRequest.setVnfInstanceId("myTestVnfIdOnVnfm"); + grantRequest.setVnfLcmOpOccId("123456"); + grantRequest.links(new GrantsLinks() + .vnfInstance(new GrantsLinksVnfLcmOpOcc().href("http://vnfm:8080/vnfs/myTestVnfIdOnVnfm"))); + if (operation == "INSTANTIATE") { + grantRequest.setOperation(OperationEnum.INSTANTIATE); + final GrantsAddResources resource = new GrantsAddResources(); + resource.setId("123"); + resource.setType(TypeEnum.COMPUTE); + grantRequest.addAddResourcesItem(resource); + } else if (operation == "TERMINATE") { + grantRequest.setOperation(OperationEnum.TERMINATE); + final GrantsAddResources resource = new GrantsAddResources(); + resource.setId("123"); + resource.setType(TypeEnum.COMPUTE); + grantRequest.addRemoveResourcesItem(resource); + } + + return grantRequest; + } + + private void setUpVimInMockAai() { + final EsrSystemInfo esrSystemInfo = new EsrSystemInfo(); + esrSystemInfo.setServiceUrl("http://myVim:8080"); + esrSystemInfo.setType("OPENSTACK"); + esrSystemInfo.setSystemType("VIM"); + esrSystemInfo.setCloudDomain("myDomain"); + esrSystemInfo.setUserName("myUser"); + esrSystemInfo.setPassword("myPassword"); + + final EsrSystemInfoList esrSystemInfoList = new EsrSystemInfoList(); + esrSystemInfoList.getEsrSystemInfo().add(esrSystemInfo); + + doReturn(Optional.of(esrSystemInfoList)).when(aaiResourcesClient).get(eq(EsrSystemInfoList.class), + MockitoHamcrest.argThat(new AaiResourceUriMatcher("/cloud-infrastructure/cloud-regions/cloud-region/" + + CLOUD_OWNER + "/" + REGION + "/esr-system-info-list"))); + } + + private GenericVnf createGenericVnf(final String type) { + final GenericVnf genericVnf = new GenericVnf(); + genericVnf.setVnfId("myTestVnfId"); + genericVnf.setNfType(type); + return genericVnf; + } + + private void setUpGenericVnfWithVnfmRelationshipInMockAai(final String type, final String vnfmId) { + final GenericVnf genericVnf = createGenericVnf(type); + + final Relationship relationshipToVnfm = new Relationship(); + relationshipToVnfm.setRelatedTo("tenant"); + final RelationshipData relationshipData1 = new RelationshipData(); + final RelationshipData relationshipData2 = new RelationshipData(); + final RelationshipData relationshipData3 = new RelationshipData(); + + relationshipData1.setRelationshipKey("cloud-region.cloud-owner"); + relationshipData1.setRelationshipValue(CLOUD_OWNER); + relationshipData2.setRelationshipKey("cloud-region.cloud-region-id"); + relationshipData2.setRelationshipValue(REGION); + relationshipData3.setRelationshipKey("tenant.tenant-id"); + relationshipData3.setRelationshipValue(TENANT_ID); + + relationshipToVnfm.getRelationshipData().add(relationshipData1); + relationshipToVnfm.getRelationshipData().add(relationshipData2); + relationshipToVnfm.getRelationshipData().add(relationshipData3); + + final RelationshipList relationshipList = new RelationshipList(); + relationshipList.getRelationship().add(relationshipToVnfm); + genericVnf.setRelationshipList(relationshipList); + + doReturn(Optional.of(genericVnf)).when(aaiResourcesClient).get(eq(GenericVnf.class), + MockitoHamcrest.argThat(new AaiResourceUriMatcher("/network/generic-vnfs/generic-vnf/myTestVnfId"))); + + final List listOfGenericVnfs = new ArrayList<>(); + listOfGenericVnfs.add(genericVnf); + final GenericVnfs genericVnfs = new GenericVnfs(); + genericVnfs.getGenericVnf().addAll(listOfGenericVnfs); + doReturn(Optional.of(genericVnfs)).when(aaiResourcesClient).get(eq(GenericVnfs.class), + MockitoHamcrest.argThat(new AaiResourceUriMatcher( + "/network/generic-vnfs?selflink=http%3A%2F%2Fvnfm%3A8080%2Fvnfs%2FmyTestVnfIdOnVnfm"))); + } + + private class AaiResourceUriMatcher extends BaseMatcher { + + final String uriAsString; + + public AaiResourceUriMatcher(final String uriAsString) { + this.uriAsString = uriAsString; + } + + @Override + public boolean matches(final Object item) { + if (item instanceof AAIResourceUri) { + if (uriAsString.endsWith("...")) { + return ((AAIResourceUri) item).build().toString() + .startsWith(uriAsString.substring(0, uriAsString.indexOf("..."))); + } + return ((AAIResourceUri) item).build().toString().equals(uriAsString); + } + return false; + } + + @Override + public void describeTo(final Description description) {} + + } + +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/test/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/Sol003LcnControllerTest.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/test/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/Sol003LcnControllerTest.java new file mode 100644 index 0000000000..ab6ae83896 --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/test/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/Sol003LcnControllerTest.java @@ -0,0 +1,413 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.lcm.rest; + +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.timeout; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.onap.so.client.RestTemplateConfig.CONFIGURABLE_REST_TEMPLATE; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; +import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus; +import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import javax.inject.Inject; +import org.hamcrest.BaseMatcher; +import org.hamcrest.Description; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.hamcrest.MockitoHamcrest; +import org.onap.aai.domain.yang.EsrSystemInfoList; +import org.onap.aai.domain.yang.EsrVnfm; +import org.onap.aai.domain.yang.GenericVnf; +import org.onap.aai.domain.yang.GenericVnfs; +import org.onap.aai.domain.yang.Relationship; +import org.onap.aai.domain.yang.RelationshipData; +import org.onap.aai.domain.yang.RelationshipList; +import org.onap.aai.domain.yang.Vserver; +import org.onap.aaiclient.client.aai.AAIResourcesClient; +import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.aai.AaiHelper; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.aai.OamIpAddressSource; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.aai.OamIpAddressSource.OamIpAddressType; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vim.model.AccessInfo; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.InlineResponse201; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.InlineResponse201Links; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.InlineResponse201LinksSelf; +import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.InlineResponse201VimConnectionInfo; +import org.onap.so.adapters.etsisol003adapter.lcm.lcn.model.LcnVnfLcmOperationOccurrenceNotificationAffectedVnfcs; +import org.onap.so.adapters.etsisol003adapter.lcm.lcn.model.LcnVnfLcmOperationOccurrenceNotificationAffectedVnfcs.ChangeTypeEnum; +import org.onap.so.adapters.etsisol003adapter.lcm.lcn.model.LcnVnfLcmOperationOccurrenceNotificationComputeResource; +import org.onap.so.adapters.etsisol003adapter.lcm.lcn.model.LcnVnfLcmOperationOccurrenceNotificationLinks; +import org.onap.so.adapters.etsisol003adapter.lcm.lcn.model.LcnVnfLcmOperationOccurrenceNotificationLinksVnfInstance; +import org.onap.so.adapters.etsisol003adapter.lcm.lcn.model.VnfIdentifierCreationNotification; +import org.onap.so.adapters.etsisol003adapter.lcm.lcn.model.VnfLcmOperationOccurrenceNotification; +import org.onap.so.adapters.etsisol003adapter.lcm.lcn.model.VnfLcmOperationOccurrenceNotification.OperationEnum; +import org.onap.so.adapters.etsisol003adapter.lcm.lcn.model.VnfLcmOperationOccurrenceNotification.OperationStateEnum; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.client.MockRestServiceServer; +import org.springframework.web.client.RestTemplate; +import com.google.gson.Gson; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = TestApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) +@ActiveProfiles("test") +public class Sol003LcnControllerTest { + + private static final String CLOUD_OWNER = "myTestCloudOwner"; + private static final String REGION = "myTestRegion"; + private static final String TENANT_ID = "myTestTenantId"; + + @LocalServerPort + private int port; + @Autowired + @Qualifier(CONFIGURABLE_REST_TEMPLATE) + private RestTemplate testRestTemplate; + private MockRestServiceServer mockRestServer; + + @MockBean + private AAIResourcesClient aaiResourcesClient; + + @Autowired + private Sol003LcnContoller controller; + private final Gson gson = new Gson(); + + @Inject + private AaiHelper aaiHelper; + + @Before + public void setUp() throws Exception { + mockRestServer = MockRestServiceServer.bindTo(testRestTemplate).build(); + } + + @Test + public void lcnNotification_IdentifierCreated_Returns204() throws URISyntaxException, InterruptedException { + final VnfIdentifierCreationNotification vnfIdentifierCreationNotification = + new VnfIdentifierCreationNotification(); + final ResponseEntity response = + controller.lcnVnfIdentifierCreationNotificationPost(vnfIdentifierCreationNotification); + assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode()); + } + + @Test + public void lcnNotification_IdentifierDeleted_Returns204() throws URISyntaxException, InterruptedException { + final VnfIdentifierCreationNotification vnfIdentifierCreationNotification = + new VnfIdentifierCreationNotification(); + final ResponseEntity response = + controller.lcnVnfIdentifierCreationNotificationPost(vnfIdentifierCreationNotification); + assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode()); + } + + @Test + public void lcnNotification_InstantiateStartingOrProcessing_NoAction() + throws URISyntaxException, InterruptedException { + final VnfLcmOperationOccurrenceNotification startingNotification = new VnfLcmOperationOccurrenceNotification(); + startingNotification.setOperation(OperationEnum.INSTANTIATE); + startingNotification.setOperationState(OperationStateEnum.STARTING); + + ResponseEntity response = controller.lcnVnfLcmOperationOccurrenceNotificationPost(startingNotification); + assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode()); + + verifyZeroInteractions(aaiResourcesClient); + + final VnfLcmOperationOccurrenceNotification processingNotification = + new VnfLcmOperationOccurrenceNotification(); + processingNotification.setOperation(OperationEnum.INSTANTIATE); + processingNotification.setOperationState(OperationStateEnum.STARTING); + + response = controller.lcnVnfLcmOperationOccurrenceNotificationPost(processingNotification); + assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode()); + + verifyZeroInteractions(aaiResourcesClient); + } + + @Test + public void lcnNotification_InstantiateCompleted_AaiUpdated() throws URISyntaxException, InterruptedException { + final VnfLcmOperationOccurrenceNotification vnfLcmOperationOccurrenceNotification = + createNotification(OperationEnum.INSTANTIATE); + addVnfcsToNotification(vnfLcmOperationOccurrenceNotification, ChangeTypeEnum.ADDED); + final InlineResponse201 vnfInstance = createVnfInstance(); + + mockRestServer.expect(requestTo(new URI("http://vnfm:8080/vnfs/myTestVnfIdOnVnfm"))) + .andRespond(withSuccess(gson.toJson(vnfInstance), MediaType.APPLICATION_JSON)); + + final GenericVnf genericVnf = createGenericVnf("vnfmType1"); + addRelationshipFromGenericVnfToVnfm(genericVnf, "vnfm1"); + final List listOfGenericVnfs = new ArrayList<>(); + listOfGenericVnfs.add(genericVnf); + final GenericVnfs genericVnfs = new GenericVnfs(); + genericVnfs.getGenericVnf().addAll(listOfGenericVnfs); + doReturn(Optional.of(genericVnfs)).when(aaiResourcesClient).get(eq(GenericVnfs.class), + MockitoHamcrest.argThat(new AaiResourceUriMatcher( + "/network/generic-vnfs?selflink=http%3A%2F%2Fvnfm%3A8080%2Fvnfs%2FmyTestVnfIdOnVnfm"))); + final EsrVnfm vnfm = new EsrVnfm(); + vnfm.setVnfmId("vnfm1"); + final EsrSystemInfoList esrSystemInfoList = new EsrSystemInfoList(); + vnfm.setEsrSystemInfoList(esrSystemInfoList); + doReturn(Optional.of(vnfm)).when(aaiResourcesClient).get(eq(EsrVnfm.class), MockitoHamcrest + .argThat(new AaiResourceUriMatcher("/external-system/esr-vnfm-list/esr-vnfm/vnfm1?depth=1"))); + + final ResponseEntity response = + controller.lcnVnfLcmOperationOccurrenceNotificationPost(vnfLcmOperationOccurrenceNotification); + assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode()); + + final ArgumentCaptor bodyArgument1 = ArgumentCaptor.forClass(Object.class); + final ArgumentCaptor uriArgument1 = ArgumentCaptor.forClass(AAIResourceUri.class); + + verify(aaiResourcesClient, timeout(1000)).update(uriArgument1.capture(), bodyArgument1.capture()); + + assertEquals("/network/generic-vnfs/generic-vnf/myTestVnfId", + uriArgument1.getAllValues().get(0).build().toString()); + final GenericVnf updatedGenericVnf = (GenericVnf) bodyArgument1.getAllValues().get(0); + assertEquals("10.10.10.10", updatedGenericVnf.getIpv4OamAddress()); + assertEquals("Created", updatedGenericVnf.getOrchestrationStatus()); + + final ArgumentCaptor bodyArgument2 = ArgumentCaptor.forClass(Object.class); + final ArgumentCaptor uriArgument2 = ArgumentCaptor.forClass(AAIResourceUri.class); + verify(aaiResourcesClient, timeout(1000)).create(uriArgument2.capture(), bodyArgument2.capture()); + + assertEquals( + "/cloud-infrastructure/cloud-regions/cloud-region/" + CLOUD_OWNER + "/" + REGION + "/tenants/tenant/" + + TENANT_ID + "/vservers/vserver/myVnfc1", + uriArgument2.getAllValues().get(0).build().toString()); + + final Vserver vserver = (Vserver) bodyArgument2.getAllValues().get(0); + assertEquals("myVnfc1", vserver.getVserverId()); + + final ArgumentCaptor uriArgument1Connect = ArgumentCaptor.forClass(AAIResourceUri.class); + final ArgumentCaptor uriArgument2Connect = ArgumentCaptor.forClass(AAIResourceUri.class); + verify(aaiResourcesClient, timeout(1000)).connect(uriArgument1Connect.capture(), uriArgument2Connect.capture()); + assertEquals( + "/cloud-infrastructure/cloud-regions/cloud-region/" + CLOUD_OWNER + "/" + REGION + "/tenants/tenant/" + + TENANT_ID + "/vservers/vserver/myVnfc1", + uriArgument1Connect.getAllValues().get(0).build().toString()); + assertEquals("/network/generic-vnfs/generic-vnf/myTestVnfId", + uriArgument2Connect.getAllValues().get(0).build().toString()); + } + + @Test + public void lcnNotification_TerminateCompleted_AaiUpdated() throws URISyntaxException, InterruptedException { + final VnfLcmOperationOccurrenceNotification vnfLcmOperationOccurrenceNotification = + createNotification(OperationEnum.TERMINATE); + addVnfcsToNotification(vnfLcmOperationOccurrenceNotification, ChangeTypeEnum.REMOVED); + + final InlineResponse201 vnfInstance = createVnfInstance(); + + mockRestServer.expect(requestTo(new URI("http://vnfm:8080/vnfs/myTestVnfIdOnVnfm"))) + .andRespond(withSuccess(gson.toJson(vnfInstance), MediaType.APPLICATION_JSON)); + + mockRestServer.expect(requestTo(new URI("http://vnfm:8080/vnfs/myTestVnfIdOnVnfm"))) + .andRespond(withStatus(HttpStatus.NO_CONTENT).contentType(MediaType.APPLICATION_JSON)); + + final GenericVnf genericVnf = createGenericVnf("vnfmType1"); + addRelationshipFromGenericVnfToVnfm(genericVnf, "vnfm1"); + genericVnf.setSelflink("http://vnfm:8080/vnfs/myTestVnfIdOnVnfm"); + final List listOfGenericVnfs = new ArrayList<>(); + listOfGenericVnfs.add(genericVnf); + final GenericVnfs genericVnfs = new GenericVnfs(); + genericVnfs.getGenericVnf().addAll(listOfGenericVnfs); + addRelationshipFromGenericVnfToVserver(genericVnf, "myVnfc1"); + + doReturn(Optional.of(genericVnfs)).when(aaiResourcesClient).get(eq(GenericVnfs.class), + MockitoHamcrest.argThat(new AaiResourceUriMatcher( + "/network/generic-vnfs?selflink=http%3A%2F%2Fvnfm%3A8080%2Fvnfs%2FmyTestVnfIdOnVnfm"))); + final EsrVnfm vnfm = new EsrVnfm(); + vnfm.setVnfmId("vnfm1"); + final EsrSystemInfoList esrSystemInfoList = new EsrSystemInfoList(); + vnfm.setEsrSystemInfoList(esrSystemInfoList); + doReturn(Optional.of(vnfm)).when(aaiResourcesClient).get(eq(EsrVnfm.class), MockitoHamcrest + .argThat(new AaiResourceUriMatcher("/external-system/esr-vnfm-list/esr-vnfm/vnfm1?depth=1"))); + + final ResponseEntity response = + controller.lcnVnfLcmOperationOccurrenceNotificationPost(vnfLcmOperationOccurrenceNotification); + assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode()); + + final ArgumentCaptor genericVnfArgument = ArgumentCaptor.forClass(GenericVnf.class); + final ArgumentCaptor updateUriArgument = ArgumentCaptor.forClass(AAIResourceUri.class); + verify(aaiResourcesClient, timeout(10000000)).update(updateUriArgument.capture(), genericVnfArgument.capture()); + assertEquals("/network/generic-vnfs/generic-vnf/myTestVnfId", updateUriArgument.getValue().build().toString()); + assertEquals("Assigned", genericVnfArgument.getValue().getOrchestrationStatus()); + + final ArgumentCaptor deleteUriArgument = ArgumentCaptor.forClass(AAIResourceUri.class); + + verify(aaiResourcesClient, timeout(10000000)).delete(deleteUriArgument.capture()); + + assertEquals( + "/cloud-infrastructure/cloud-regions/cloud-region/" + CLOUD_OWNER + "/" + REGION + "/tenants/tenant/" + + TENANT_ID + "/vservers/vserver/myVnfc1", + deleteUriArgument.getAllValues().get(0).build().toString()); + } + + private VnfLcmOperationOccurrenceNotification createNotification(final OperationEnum operation) { + final VnfLcmOperationOccurrenceNotification notification = new VnfLcmOperationOccurrenceNotification(); + notification.setOperation(operation); + notification.setOperationState(OperationStateEnum.COMPLETED); + + final LcnVnfLcmOperationOccurrenceNotificationLinksVnfInstance linkToVnfInstance = + new LcnVnfLcmOperationOccurrenceNotificationLinksVnfInstance() + .href("http://vnfm:8080/vnfs/myTestVnfIdOnVnfm"); + final LcnVnfLcmOperationOccurrenceNotificationLinks operationLinks = + new LcnVnfLcmOperationOccurrenceNotificationLinks().vnfInstance(linkToVnfInstance); + notification.setLinks(operationLinks); + + return notification; + } + + private void addVnfcsToNotification(final VnfLcmOperationOccurrenceNotification notification, + final ChangeTypeEnum changeType) { + final List affectedVnfcs = new ArrayList<>();; + final LcnVnfLcmOperationOccurrenceNotificationAffectedVnfcs vnfc = + new LcnVnfLcmOperationOccurrenceNotificationAffectedVnfcs(); + vnfc.changeType(changeType); + final LcnVnfLcmOperationOccurrenceNotificationComputeResource computeResource = + new LcnVnfLcmOperationOccurrenceNotificationComputeResource(); + computeResource.setResourceId("myVnfc1"); + computeResource.setVimConnectionId(CLOUD_OWNER + "_" + REGION); + vnfc.setComputeResource(computeResource); + affectedVnfcs.add(vnfc); + notification.setAffectedVnfcs(affectedVnfcs); + } + + private InlineResponse201 createVnfInstance() { + final InlineResponse201 vnfInstance = new InlineResponse201(); + vnfInstance.setId("myTestVnfIdOnVnfm"); + final InlineResponse201LinksSelf selfLink = new InlineResponse201LinksSelf(); + selfLink.setHref("http://vnfm:8080/vnfs/myTestVnfIdOnVnfm"); + final InlineResponse201Links VnfInstancelinks = new InlineResponse201Links(); + VnfInstancelinks.setSelf(selfLink); + vnfInstance.setLinks(VnfInstancelinks); + + final Map vnfConfigurableProperties = new HashMap<>(); + vnfConfigurableProperties.put("vnfIpAddress", "10.10.10.10"); + vnfInstance.setVnfConfigurableProperties(vnfConfigurableProperties); + + final List vimConnectionInfo = new ArrayList<>();; + final InlineResponse201VimConnectionInfo vimConnection = new InlineResponse201VimConnectionInfo(); + vimConnection.setVimId(CLOUD_OWNER + "_" + REGION); + vimConnection.setId(CLOUD_OWNER + "_" + REGION); + final AccessInfo accessInfo = new AccessInfo(); + accessInfo.setProjectId(TENANT_ID); + vimConnection.setAccessInfo(accessInfo); + vimConnectionInfo.add(vimConnection); + vnfInstance.setVimConnectionInfo(vimConnectionInfo); + + final OamIpAddressSource oamIpAddressSource = + new OamIpAddressSource(OamIpAddressType.CONFIGURABLE_PROPERTY, "vnfIpAddress"); + aaiHelper.setOamIpAddressSource("myTestVnfIdOnVnfm", oamIpAddressSource); + return vnfInstance; + } + + private GenericVnf createGenericVnf(final String type) { + final GenericVnf genericVnf = new GenericVnf(); + genericVnf.setVnfId("myTestVnfId"); + genericVnf.setNfType(type); + return genericVnf; + } + + private void addRelationshipFromGenericVnfToVnfm(final GenericVnf genericVnf, final String vnfmId) { + final Relationship relationshipToVnfm = new Relationship(); + relationshipToVnfm.setRelatedLink("/aai/v15/external-system/esr-vnfm-list/esr-vnfm/" + vnfmId); + relationshipToVnfm.setRelatedTo("esr-vnfm"); + final RelationshipData relationshipData = new RelationshipData(); + relationshipData.setRelationshipKey("esr-vnfm.vnfm-id"); + relationshipData.setRelationshipValue(vnfmId); + relationshipToVnfm.getRelationshipData().add(relationshipData); + + if (genericVnf.getRelationshipList() == null) { + final RelationshipList relationshipList = new RelationshipList(); + genericVnf.setRelationshipList(relationshipList); + } + genericVnf.getRelationshipList().getRelationship().add(relationshipToVnfm); + } + + private void addRelationshipFromGenericVnfToVserver(final GenericVnf genericVnf, final String vserverId) { + final Relationship relationshipToVserver = new Relationship(); + relationshipToVserver.setRelatedTo("vserver"); + final RelationshipData relationshipData1 = new RelationshipData(); + relationshipData1.setRelationshipKey("vserver.vserver-id"); + relationshipData1.setRelationshipValue(vserverId); + relationshipToVserver.getRelationshipData().add(relationshipData1); + final RelationshipData relationshipData2 = new RelationshipData(); + relationshipData2.setRelationshipKey("cloud-region.cloud-owner"); + relationshipData2.setRelationshipValue(CLOUD_OWNER); + relationshipToVserver.getRelationshipData().add(relationshipData2); + final RelationshipData relationshipData3 = new RelationshipData(); + relationshipData3.setRelationshipKey("cloud-region.cloud-region-id"); + relationshipData3.setRelationshipValue(REGION); + relationshipToVserver.getRelationshipData().add(relationshipData3); + final RelationshipData relationshipData4 = new RelationshipData(); + relationshipData4.setRelationshipKey("tenant.tenant-id"); + relationshipData4.setRelationshipValue(TENANT_ID); + relationshipToVserver.getRelationshipData().add(relationshipData4); + + if (genericVnf.getRelationshipList() == null) { + final RelationshipList relationshipList = new RelationshipList(); + genericVnf.setRelationshipList(relationshipList); + } + genericVnf.getRelationshipList().getRelationship().add(relationshipToVserver); + } + + private class AaiResourceUriMatcher extends BaseMatcher { + + final String uriAsString; + + public AaiResourceUriMatcher(final String uriAsString) { + this.uriAsString = uriAsString; + } + + @Override + public boolean matches(final Object item) { + if (item instanceof AAIResourceUri) { + if (uriAsString.endsWith("...")) { + return ((AAIResourceUri) item).build().toString() + .startsWith(uriAsString.substring(0, uriAsString.indexOf("..."))); + } + return ((AAIResourceUri) item).build().toString().equals(uriAsString); + } + return false; + } + + @Override + public void describeTo(final Description description) {} + + } + +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/test/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/TestApplication.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/test/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/TestApplication.java new file mode 100755 index 0000000000..b59bc025e8 --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/test/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/TestApplication.java @@ -0,0 +1,38 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.lcm.rest; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration; +import org.springframework.cache.annotation.EnableCaching; + +@EnableCaching +@SpringBootApplication(scanBasePackages = {"org.onap.so"}) +@EnableAutoConfiguration(exclude = {JacksonAutoConfiguration.class}) +public class TestApplication { + + public static void main(final String[] args) { + new SpringApplication(TestApplication.class).run(args); + } + +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-api/pom.xml b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-api/pom.xml index 06251a2593..f6789575c6 100644 --- a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-api/pom.xml +++ b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-api/pom.xml @@ -21,12 +21,12 @@ generate - ${basedir}/src/main/resources/vnfmadapter.yaml + ${basedir}/src/main/resources/etsisol003adapter.yaml java retrofit2 - ${project.build.directory}/generated-sources/vnfmadapter - org.onap.etsi.sol003.adapter.lcm.v1.api - org.onap.etsi.sol003.adapter.lcm.v1.model + ${project.build.directory}/generated-sources/etsisol003adapter + org.onap.so.adapters.etsisol003adapter.lcm.v1.api + org.onap.so.adapters.etsisol003adapter.lcm.v1.model false false @@ -48,8 +48,8 @@ java okhttp-gson ${project.build.directory}/generated-sources/sol003-vnf-lcn - org.onap.so.adapters.etsi.sol003.adapter.lcm.lcn.api - org.onap.so.adapters.etsi.sol003.adapter.lcm.lcn.model + org.onap.so.adapters.etsisol003adapter.lcm.lcn.api + org.onap.so.adapters.etsisol003adapter.lcm.lcn.model false false @@ -70,8 +70,8 @@ java okhttp-gson ${project.build.directory}/generated-sources/sol003-vnf-grant - org.onap.so.adapters.etsi.sol003.adapter.lcm.grant.api - org.onap.so.adapters.etsi.sol003.adapter.lcm.grant.model + org.onap.so.adapters.etsisol003adapter.lcm.grant.api + org.onap.so.adapters.etsisol003adapter.lcm.grant.model false false diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-api/src/main/resources/etsisol003adapter.yaml b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-api/src/main/resources/etsisol003adapter.yaml new file mode 100644 index 0000000000..9d0a5283af --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-api/src/main/resources/etsisol003adapter.yaml @@ -0,0 +1,522 @@ +swagger: '2.0' +info: + version: 1.0.0 + title: ONAP SO VNFM Adapter API + description: >- + Describes the API between SO (Service Orchestrator) and the adapter for VNFM + (Virtual Network Function Manager) +basePath: /so/vnfm-adapter/v1 +schemes: + - http + - https +consumes: + - application/json +produces: + - application/json +paths: + '/vnfs/{vnfId}': + post: + tags: + - SO VNFM Adapter + summary: VNF create + description: Create a VNF instance using a VNFM. + operationId: vnf_create + consumes: + - application/json + parameters: + - required: true + type: string + description: >- + The identifier of the VNF. This must be the vnf-id of an existing + generic-vnf in AAI. + name: vnfId + in: path + - in: body + name: body + description: VNF creation parameters + required: true + schema: + $ref: '#/definitions/CreateVnfRequest' + - name: X-ONAP-RequestID + description: >- + Used to track REST requests for logging purposes. Identifies a + single top level invocation of ONAP + in: header + required: true + type: string + - name: X-InvocationID + description: >- + Used to track REST requests for logging purposes. Identifies a + single invocation of a single component + in: header + required: true + type: string + responses: + '202': + description: >- + The request was accepted for processing, but the processing has not + been completed. + schema: + $ref: '#/definitions/CreateVnfResponse' + '400': + description: >- + An error occurred in the VNFM adapter relating to the given input, + for example, if the definition of the given VNF in AAI does not + included required information. + '404': + description: A VNF with the specified ID was not found in AAI. + '500': + description: >- + An error occurred in the VNFM adapter not relating to the given + input, or an error is received from the VNFM. + delete: + tags: + - SO VNFM Adapter + summary: VNF delete + description: Delete an instance of a VNF using a VNFM. + operationId: vnf_delete + consumes: + - application/json + parameters: + - required: true + type: string + description: >- + The identifier of the VNF. This must be the vnf-id of an existing + generic-vnf in AAI + name: vnfId + in: path + - name: X-ONAP-RequestID + description: >- + Used to track REST requests for logging purposes. Identifies a + single top level invocation of ONAP + in: header + required: true + type: string + - name: X-InvocationID + description: >- + Used to track REST requests for logging purposes. Identifies a + single invocation of a single component + in: header + required: true + type: string + responses: + '202': + description: >- + The request was accepted for processing, but the processing has not + been completed. + schema: + $ref: '#/definitions/DeleteVnfResponse' + '400': + description: >- + An error occurred in the VNFM adapter relating to the given input, + for example, if the definition of the given VNF in AAI does not + included required information. + '404': + description: A VNF with the specified ID was not found in AAI. + '500': + description: >- + An error occurred in the VNFM adapter not relating to the given + input, or an error is received from the VNFM. + '/jobs/{jobId}': + get: + tags: + - SO VNFM Adapter + summary: Job query + description: Query the status of a job. + operationId: job_query + consumes: + - application/json + produces: + - application/json + parameters: + - required: true + type: string + description: The identifier of the Job. + name: jobId + in: path + - name: X-ONAP-RequestID + description: >- + Used to track REST requests for logging purposes. Identifies a + single top level invocation of ONAP + in: header + required: true + type: string + - name: X-InvocationID + description: >- + Used to track REST requests for logging purposes. Identifies a + single invocation of a single component + in: header + required: true + type: string + responses: + '200': + description: '' + schema: + $ref: '#/definitions/QueryJobResponse' + '404': + description: A job with the specified ID was not found. + '500': + description: >- + An error occurred in the VNFM adapter not relating to the given + input, or an error is received from the VNFM. +definitions: + CreateVnfRequest: + type: object + properties: + name: + type: string + description: The name to be applied to the VNF. + tenant: + $ref: '#/definitions/Tenant' + additionalParams: + type: object + description: >- + Additional input parameters for the instantiation process, specific to + the VNF being instantiated, as declared in the VNFD as part of + "InstantiateVnfOpConfig". + additionalProperties: + type: string + externalVirtualLinks: + type: array + description: Information about external VLs to connect the VNF to. + items: + $ref: '#/definitions/ExternalVirtualLink' + required: + - name + - tenant + Tenant: + type: object + description: Details of the tenant that VNFs can be deployed into + properties: + cloudOwner: + type: string + description: The owner in AAI of the cloud to which the tenant belongs. + regionName: + type: string + description: The regionName in AAI of the cloud to which the tenant belongs. + tenantId: + type: string + description: The identifier of the tenant in the VIM. + required: + - cloudOwner + - regionName + - tenantId + CreateVnfResponse: + type: object + properties: + jobId: + description: The ID of the job which can be used to query the status of the job + type: string + required: + - jobId + DeleteVnfResponse: + type: object + properties: + jobId: + description: >- + The ID of the job which can be used to query the status of the delete + job + type: string + required: + - jobId + QueryJobResponse: + type: object + properties: + operationStatusRetrievalStatus: + $ref: '#/definitions/OperationStatusRetrievalStatusEnum' + id: + type: string + operation: + $ref: '#/definitions/OperationEnum' + operationState: + $ref: '#/definitions/OperationStateEnum' + startTime: + type: string + format: date-time + stateEnteredTime: + type: string + format: date-time + vnfInstanceId: + type: string + required: + - operationStatusRetrievalStatus + OperationStatusRetrievalStatusEnum: + description: The status of the attempt to retrieve the operation from the VNFM + type: string + enum: + - STATUS_FOUND + - WAITING_FOR_STATUS + - OPERATION_NOT_FOUND + - CANNOT_RETRIEVE_STATUS + OperationEnum: + description: The operation + type: string + enum: + - INSTANTIATE + - SCALE + - SCALE_TO_LEVEL + - CHANGE_FLAVOUR + - TERMINATE + - HEAL + - OPERATE + - CHANGE_EXT_CONN + - MODIFY_INFO + OperationStateEnum: + description: The status of the operation + type: string + enum: + - STARTING + - PROCESSING + - COMPLETED + - FAILED_TEMP + - FAILED + - ROLLING_BACK + - ROLLED_BACK + ExternalVirtualLink: + description: | + This type represents an external VL. + type: object + required: + - id + - resourceId + - extCps + properties: + id: + description: | + An identifier with the intention of being globally unique. + type: string + tenant: + $ref: '#/definitions/Tenant' + resourceId: + description: | + An identifier maintained by the VIM. + type: string + extCps: + description: | + External CPs of the VNF to be connected to this external VL. + type: array + items: + description: > + This type represents configuration information for external CPs + created from a CPD. + type: object + required: + - cpdId + properties: + cpdId: + description: | + An identifier that is unique within a VNF descriptor. + type: string + cpConfig: + description: > + List of instance data that need to be configured on the CP + instances created from the respective CPD. + type: array + items: + description: > + This type represents an externally provided link port or + network address information per instance of an external + connection point. In case a link port is provided, the VNFM + shall use that link port when connecting the external CP to + the external VL. In a link port is not provided, the VNFM + shall create a link port on the external VL, and use that link + port to connect the external CP to the external VL. + type: object + properties: + cpInstanceId: + description: > + An identifier that is unique for the respective type + within a VNF instance, but may not be globally unique. + type: string + linkPortId: + description: | + An identifier with the intention of being globally unique. + type: string + cpProtocolData: + description: > + Parameters for configuring the network protocols on the + link port that connects the CP to a VL. The following + conditions apply to the attributes "linkPortId" and + "cpProtocolData": * The "linkPortId" and "cpProtocolData" + attributes shall both be absent for the deletion of an + existing external CP instance + addressed by cpInstanceId. + * At least one of these attributes shall be present for a + to-be-created external CP instance or an existing external + CP instance. + * If the "linkPortId" attribute is absent, the VNFM shall + create a link port. + + * If the "cpProtocolData" attribute is absent, the + "linkPortId" attribute shall be provided referencing a + pre-created link port, + and the VNFM can use means outside the scope of the present + document to obtain the pre-configured address information for the + connection point from the resource representing the link port. + * If both "cpProtocolData" and "linkportId" are provided, + the API consumer shall ensure that the cpProtocolData can + be used with the + pre-created link port referenced by "linkPortId". + type: array + items: + description: | + This type represents network protocol data. + type: object + required: + - layerProtocol + properties: + layerProtocol: + description: > + Identifier of layer(s) and protocol(s). This + attribute allows to signal the addition of further + types of layer and protocol in future versions of + the present document in a backwards-compatible way. + In the current version of the present document, only + IP over Ethernet is supported. + type: string + enum: + - IP_OVER_ETHERNET + ipOverEthernet: + description: > + This type represents network address data for IP + over Ethernet. + type: object + properties: + macAddress: + description: > + A MAC address. Representation: string that + consists of groups of two hexadecimal digits, + separated by hyphens or colons. + type: string + format: MAC + ipAddresses: + description: > + List of IP addresses to assign to the CP + instance. Each entry represents IP address data + for fixed or dynamic IP address assignment per + subnet. If this attribute is not present, no IP + address shall be assigned. + type: array + items: + type: object + required: + - type + properties: + type: + description: > + The type of the IP addresses. Permitted + values: IPV4, IPV6. + type: string + enum: + - IPV4 + - IPV6 + fixedAddresses: + description: > + Fixed addresses to assign (from the subnet + defined by "subnetId" if provided). + Exactly one of "fixedAddresses", + "numDynamicAddresses" or "ipAddressRange" + shall be present. + type: array + items: + description: > + An IPV4 or IPV6 address. Representation: + In case of an IPV4 address, string that + consists of four decimal integers + separated by dots, each integer ranging + from 0 to 255. In case of an IPV6 + address, string that consists of groups + of zero to four hexadecimal digits, + separated by colons. + type: string + format: IP + numDynamicAddresses: + description: > + Number of dynamic addresses to assign + (from the subnet defined by "subnetId" if + provided). Exactly one of + "fixedAddresses", "numDynamicAddresses" or + "ipAddressRange" shall be present. + type: integer + addressRange: + description: > + An IP address range to be used, e.g. in + case of egress connections. In case this + attribute is present, IP addresses from + the range will be used. + type: object + required: + - minAddress + - maxAddress + properties: + minAddress: + description: > + An IPV4 or IPV6 address. Representation: + In case of an IPV4 address, string that + consists of four decimal integers + separated by dots, each integer ranging + from 0 to 255. In case of an IPV6 + address, string that consists of groups + of zero to four hexadecimal digits, + separated by colons. + type: string + format: IP + maxAddress: + description: > + An IPV4 or IPV6 address. Representation: + In case of an IPV4 address, string that + consists of four decimal integers + separated by dots, each integer ranging + from 0 to 255. In case of an IPV6 + address, string that consists of groups + of zero to four hexadecimal digits, + separated by colons. + type: string + format: IP + subnetId: + description: > + An identifier maintained by the VIM or + other resource provider. It is expected to + be unique within the VIM instance. + type: string + extLinkPorts: + description: > + Externally provided link ports to be used to connect external + connection points to this external VL. If this attribute is not + present, the VNFM shall create the link ports on the external VL. + type: array + items: + description: > + This type represents an externally provided link port to be used to + connect an external connection point to an external VL. + type: object + required: + - id + - resourceHandle + properties: + id: + description: | + An identifier with the intention of being globally unique. + type: string + resourceHandle: + required: + - tenant + - resourceId + type: object + description: > + This type represents the information that allows addressing a + virtualised resource that is used by a VNF instance. + properties: + tenant: + $ref: '#/definitions/Tenant' + resourceId: + description: > + An identifier maintained by the VIM or other resource + provider. It is expected to be unique within the VIM + instance. + type: string + vimLevelResourceType: + description: > + Type of the resource in the scope of the VIM or the resource + provider. + type: string \ No newline at end of file diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-api/src/main/resources/vnfmadapter.yaml b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-api/src/main/resources/vnfmadapter.yaml deleted file mode 100644 index 9d0a5283af..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-api/src/main/resources/vnfmadapter.yaml +++ /dev/null @@ -1,522 +0,0 @@ -swagger: '2.0' -info: - version: 1.0.0 - title: ONAP SO VNFM Adapter API - description: >- - Describes the API between SO (Service Orchestrator) and the adapter for VNFM - (Virtual Network Function Manager) -basePath: /so/vnfm-adapter/v1 -schemes: - - http - - https -consumes: - - application/json -produces: - - application/json -paths: - '/vnfs/{vnfId}': - post: - tags: - - SO VNFM Adapter - summary: VNF create - description: Create a VNF instance using a VNFM. - operationId: vnf_create - consumes: - - application/json - parameters: - - required: true - type: string - description: >- - The identifier of the VNF. This must be the vnf-id of an existing - generic-vnf in AAI. - name: vnfId - in: path - - in: body - name: body - description: VNF creation parameters - required: true - schema: - $ref: '#/definitions/CreateVnfRequest' - - name: X-ONAP-RequestID - description: >- - Used to track REST requests for logging purposes. Identifies a - single top level invocation of ONAP - in: header - required: true - type: string - - name: X-InvocationID - description: >- - Used to track REST requests for logging purposes. Identifies a - single invocation of a single component - in: header - required: true - type: string - responses: - '202': - description: >- - The request was accepted for processing, but the processing has not - been completed. - schema: - $ref: '#/definitions/CreateVnfResponse' - '400': - description: >- - An error occurred in the VNFM adapter relating to the given input, - for example, if the definition of the given VNF in AAI does not - included required information. - '404': - description: A VNF with the specified ID was not found in AAI. - '500': - description: >- - An error occurred in the VNFM adapter not relating to the given - input, or an error is received from the VNFM. - delete: - tags: - - SO VNFM Adapter - summary: VNF delete - description: Delete an instance of a VNF using a VNFM. - operationId: vnf_delete - consumes: - - application/json - parameters: - - required: true - type: string - description: >- - The identifier of the VNF. This must be the vnf-id of an existing - generic-vnf in AAI - name: vnfId - in: path - - name: X-ONAP-RequestID - description: >- - Used to track REST requests for logging purposes. Identifies a - single top level invocation of ONAP - in: header - required: true - type: string - - name: X-InvocationID - description: >- - Used to track REST requests for logging purposes. Identifies a - single invocation of a single component - in: header - required: true - type: string - responses: - '202': - description: >- - The request was accepted for processing, but the processing has not - been completed. - schema: - $ref: '#/definitions/DeleteVnfResponse' - '400': - description: >- - An error occurred in the VNFM adapter relating to the given input, - for example, if the definition of the given VNF in AAI does not - included required information. - '404': - description: A VNF with the specified ID was not found in AAI. - '500': - description: >- - An error occurred in the VNFM adapter not relating to the given - input, or an error is received from the VNFM. - '/jobs/{jobId}': - get: - tags: - - SO VNFM Adapter - summary: Job query - description: Query the status of a job. - operationId: job_query - consumes: - - application/json - produces: - - application/json - parameters: - - required: true - type: string - description: The identifier of the Job. - name: jobId - in: path - - name: X-ONAP-RequestID - description: >- - Used to track REST requests for logging purposes. Identifies a - single top level invocation of ONAP - in: header - required: true - type: string - - name: X-InvocationID - description: >- - Used to track REST requests for logging purposes. Identifies a - single invocation of a single component - in: header - required: true - type: string - responses: - '200': - description: '' - schema: - $ref: '#/definitions/QueryJobResponse' - '404': - description: A job with the specified ID was not found. - '500': - description: >- - An error occurred in the VNFM adapter not relating to the given - input, or an error is received from the VNFM. -definitions: - CreateVnfRequest: - type: object - properties: - name: - type: string - description: The name to be applied to the VNF. - tenant: - $ref: '#/definitions/Tenant' - additionalParams: - type: object - description: >- - Additional input parameters for the instantiation process, specific to - the VNF being instantiated, as declared in the VNFD as part of - "InstantiateVnfOpConfig". - additionalProperties: - type: string - externalVirtualLinks: - type: array - description: Information about external VLs to connect the VNF to. - items: - $ref: '#/definitions/ExternalVirtualLink' - required: - - name - - tenant - Tenant: - type: object - description: Details of the tenant that VNFs can be deployed into - properties: - cloudOwner: - type: string - description: The owner in AAI of the cloud to which the tenant belongs. - regionName: - type: string - description: The regionName in AAI of the cloud to which the tenant belongs. - tenantId: - type: string - description: The identifier of the tenant in the VIM. - required: - - cloudOwner - - regionName - - tenantId - CreateVnfResponse: - type: object - properties: - jobId: - description: The ID of the job which can be used to query the status of the job - type: string - required: - - jobId - DeleteVnfResponse: - type: object - properties: - jobId: - description: >- - The ID of the job which can be used to query the status of the delete - job - type: string - required: - - jobId - QueryJobResponse: - type: object - properties: - operationStatusRetrievalStatus: - $ref: '#/definitions/OperationStatusRetrievalStatusEnum' - id: - type: string - operation: - $ref: '#/definitions/OperationEnum' - operationState: - $ref: '#/definitions/OperationStateEnum' - startTime: - type: string - format: date-time - stateEnteredTime: - type: string - format: date-time - vnfInstanceId: - type: string - required: - - operationStatusRetrievalStatus - OperationStatusRetrievalStatusEnum: - description: The status of the attempt to retrieve the operation from the VNFM - type: string - enum: - - STATUS_FOUND - - WAITING_FOR_STATUS - - OPERATION_NOT_FOUND - - CANNOT_RETRIEVE_STATUS - OperationEnum: - description: The operation - type: string - enum: - - INSTANTIATE - - SCALE - - SCALE_TO_LEVEL - - CHANGE_FLAVOUR - - TERMINATE - - HEAL - - OPERATE - - CHANGE_EXT_CONN - - MODIFY_INFO - OperationStateEnum: - description: The status of the operation - type: string - enum: - - STARTING - - PROCESSING - - COMPLETED - - FAILED_TEMP - - FAILED - - ROLLING_BACK - - ROLLED_BACK - ExternalVirtualLink: - description: | - This type represents an external VL. - type: object - required: - - id - - resourceId - - extCps - properties: - id: - description: | - An identifier with the intention of being globally unique. - type: string - tenant: - $ref: '#/definitions/Tenant' - resourceId: - description: | - An identifier maintained by the VIM. - type: string - extCps: - description: | - External CPs of the VNF to be connected to this external VL. - type: array - items: - description: > - This type represents configuration information for external CPs - created from a CPD. - type: object - required: - - cpdId - properties: - cpdId: - description: | - An identifier that is unique within a VNF descriptor. - type: string - cpConfig: - description: > - List of instance data that need to be configured on the CP - instances created from the respective CPD. - type: array - items: - description: > - This type represents an externally provided link port or - network address information per instance of an external - connection point. In case a link port is provided, the VNFM - shall use that link port when connecting the external CP to - the external VL. In a link port is not provided, the VNFM - shall create a link port on the external VL, and use that link - port to connect the external CP to the external VL. - type: object - properties: - cpInstanceId: - description: > - An identifier that is unique for the respective type - within a VNF instance, but may not be globally unique. - type: string - linkPortId: - description: | - An identifier with the intention of being globally unique. - type: string - cpProtocolData: - description: > - Parameters for configuring the network protocols on the - link port that connects the CP to a VL. The following - conditions apply to the attributes "linkPortId" and - "cpProtocolData": * The "linkPortId" and "cpProtocolData" - attributes shall both be absent for the deletion of an - existing external CP instance - addressed by cpInstanceId. - * At least one of these attributes shall be present for a - to-be-created external CP instance or an existing external - CP instance. - * If the "linkPortId" attribute is absent, the VNFM shall - create a link port. - - * If the "cpProtocolData" attribute is absent, the - "linkPortId" attribute shall be provided referencing a - pre-created link port, - and the VNFM can use means outside the scope of the present - document to obtain the pre-configured address information for the - connection point from the resource representing the link port. - * If both "cpProtocolData" and "linkportId" are provided, - the API consumer shall ensure that the cpProtocolData can - be used with the - pre-created link port referenced by "linkPortId". - type: array - items: - description: | - This type represents network protocol data. - type: object - required: - - layerProtocol - properties: - layerProtocol: - description: > - Identifier of layer(s) and protocol(s). This - attribute allows to signal the addition of further - types of layer and protocol in future versions of - the present document in a backwards-compatible way. - In the current version of the present document, only - IP over Ethernet is supported. - type: string - enum: - - IP_OVER_ETHERNET - ipOverEthernet: - description: > - This type represents network address data for IP - over Ethernet. - type: object - properties: - macAddress: - description: > - A MAC address. Representation: string that - consists of groups of two hexadecimal digits, - separated by hyphens or colons. - type: string - format: MAC - ipAddresses: - description: > - List of IP addresses to assign to the CP - instance. Each entry represents IP address data - for fixed or dynamic IP address assignment per - subnet. If this attribute is not present, no IP - address shall be assigned. - type: array - items: - type: object - required: - - type - properties: - type: - description: > - The type of the IP addresses. Permitted - values: IPV4, IPV6. - type: string - enum: - - IPV4 - - IPV6 - fixedAddresses: - description: > - Fixed addresses to assign (from the subnet - defined by "subnetId" if provided). - Exactly one of "fixedAddresses", - "numDynamicAddresses" or "ipAddressRange" - shall be present. - type: array - items: - description: > - An IPV4 or IPV6 address. Representation: - In case of an IPV4 address, string that - consists of four decimal integers - separated by dots, each integer ranging - from 0 to 255. In case of an IPV6 - address, string that consists of groups - of zero to four hexadecimal digits, - separated by colons. - type: string - format: IP - numDynamicAddresses: - description: > - Number of dynamic addresses to assign - (from the subnet defined by "subnetId" if - provided). Exactly one of - "fixedAddresses", "numDynamicAddresses" or - "ipAddressRange" shall be present. - type: integer - addressRange: - description: > - An IP address range to be used, e.g. in - case of egress connections. In case this - attribute is present, IP addresses from - the range will be used. - type: object - required: - - minAddress - - maxAddress - properties: - minAddress: - description: > - An IPV4 or IPV6 address. Representation: - In case of an IPV4 address, string that - consists of four decimal integers - separated by dots, each integer ranging - from 0 to 255. In case of an IPV6 - address, string that consists of groups - of zero to four hexadecimal digits, - separated by colons. - type: string - format: IP - maxAddress: - description: > - An IPV4 or IPV6 address. Representation: - In case of an IPV4 address, string that - consists of four decimal integers - separated by dots, each integer ranging - from 0 to 255. In case of an IPV6 - address, string that consists of groups - of zero to four hexadecimal digits, - separated by colons. - type: string - format: IP - subnetId: - description: > - An identifier maintained by the VIM or - other resource provider. It is expected to - be unique within the VIM instance. - type: string - extLinkPorts: - description: > - Externally provided link ports to be used to connect external - connection points to this external VL. If this attribute is not - present, the VNFM shall create the link ports on the external VL. - type: array - items: - description: > - This type represents an externally provided link port to be used to - connect an external connection point to an external VL. - type: object - required: - - id - - resourceHandle - properties: - id: - description: | - An identifier with the intention of being globally unique. - type: string - resourceHandle: - required: - - tenant - - resourceId - type: object - description: > - This type represents the information that allows addressing a - virtualised resource that is used by a VNF instance. - properties: - tenant: - $ref: '#/definitions/Tenant' - resourceId: - description: > - An identifier maintained by the VIM or other resource - provider. It is expected to be unique within the VIM - instance. - type: string - vimLevelResourceType: - description: > - Type of the resource in the scope of the VIM or the resource - provider. - type: string \ No newline at end of file diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-ext-clients/pom.xml b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-ext-clients/pom.xml index 97c261971f..5452b578a7 100644 --- a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-ext-clients/pom.xml +++ b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-ext-clients/pom.xml @@ -25,8 +25,8 @@ java okhttp-gson ${project.build.directory}/generated-sources/sol003-vnf-lcm - org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.api - org.onap.so.adapters.etsi.sol003.adapter.lcm.extclients.vnfm.model + org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.api + org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model false false diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/ConversionServiceConfiguration.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/ConversionServiceConfiguration.java deleted file mode 100644 index 15601f7c0e..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/ConversionServiceConfiguration.java +++ /dev/null @@ -1,55 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2020 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ -package org.onap.so.adapters.etsi.sol003.adapter.packagemanagement; - -import org.onap.so.adapters.etsi.sol003.adapter.common.VnfmAdapterUrlProvider; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.converters.etsicatalog.sol003.PkgChangeNotificationConverter; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.converters.etsicatalog.sol003.PkgOnboardingNotificationConverter; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.converters.etsicatalog.sol003.VnfPkgInfoConverter; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.converters.sol003.etsicatalog.PkgmSubscriptionRequestConverter; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.core.convert.ConversionService; -import org.springframework.core.convert.support.DefaultConversionService; - -/** - * @author Waqas Ikram (waqas.ikram@est.tech) - * - */ -public class ConversionServiceConfiguration { - - private final VnfmAdapterUrlProvider vnfmAdapterUrlProvider; - - @Autowired - public ConversionServiceConfiguration(final VnfmAdapterUrlProvider vnfmAdapterUrlProvider) { - this.vnfmAdapterUrlProvider = vnfmAdapterUrlProvider; - } - - @Bean - public ConversionService conversionService() { - final DefaultConversionService service = new DefaultConversionService(); - service.addConverter(new VnfPkgInfoConverter(vnfmAdapterUrlProvider)); - service.addConverter(new PkgmSubscriptionRequestConverter()); - service.addConverter(new PkgChangeNotificationConverter(vnfmAdapterUrlProvider)); - service.addConverter(new PkgOnboardingNotificationConverter(vnfmAdapterUrlProvider)); - return service; - } - -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/PackageManagementConstants.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/PackageManagementConstants.java deleted file mode 100644 index 9f39b092eb..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/PackageManagementConstants.java +++ /dev/null @@ -1,39 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.packagemanagement; - -/** - * ETSI SOL003 VNF Package Management Adapter constants - * - * @author Ronan Kenny (ronan.kenny@est.tech) - * @author Gareth Roper (gareth.roper@est.tech) - */ -public class PackageManagementConstants { - - public static final String APPLICATION_ZIP = "application/zip"; - - /** - * Name of the subscription cache - */ - public static final String PACKAGE_MANAGEMENT_SUBSCRIPTION_CACHE = "PackageManagementSubscriptionCache"; - - private PackageManagementConstants() {} -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/converters/etsicatalog/sol003/AbstractPkgNotificationConverter.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/converters/etsicatalog/sol003/AbstractPkgNotificationConverter.java deleted file mode 100644 index fda2d54869..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/converters/etsicatalog/sol003/AbstractPkgNotificationConverter.java +++ /dev/null @@ -1,63 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2020 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.converters.etsicatalog.sol003; - -import org.onap.so.adapters.etsi.sol003.adapter.common.VnfmAdapterUrlProvider; -import org.onap.so.adapters.etsi.sol003.adapter.etsicatalog.notification.model.PkgmLinks; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.vnfm.notification.model.URIisprovidedbytheclientwhencreatingthesubscriptionVnfPackageOnboardingNotificationLinks; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.vnfm.notification.model.URIisprovidedbytheclientwhencreatingthesubscriptionVnfPackageOnboardingNotificationLinksVnfPackage; - -/** - * A base class that can be extended by classes for converting Etsi Catalog Manager Pkg Notification classes. Provides - * common methods that will be useful to those classes. - * - * @author andrew.a.lamb@est.tech - */ -abstract public class AbstractPkgNotificationConverter { - - private final VnfmAdapterUrlProvider vnfmAdapterUrlProvider; - - public AbstractPkgNotificationConverter(final VnfmAdapterUrlProvider vnfmAdapterUrlProvider) { - this.vnfmAdapterUrlProvider = vnfmAdapterUrlProvider; - } - - protected URIisprovidedbytheclientwhencreatingthesubscriptionVnfPackageOnboardingNotificationLinks convert( - final PkgmLinks pkgmLinks, final String vnfPkgId, final String subscriptionId) { - final URIisprovidedbytheclientwhencreatingthesubscriptionVnfPackageOnboardingNotificationLinksVnfPackage linksVnfPackage = - new URIisprovidedbytheclientwhencreatingthesubscriptionVnfPackageOnboardingNotificationLinksVnfPackage(); - if (pkgmLinks.getVnfPackage() != null) { - linksVnfPackage.setHref(vnfmAdapterUrlProvider.getVnfPackageUrl(vnfPkgId)); - } - - final URIisprovidedbytheclientwhencreatingthesubscriptionVnfPackageOnboardingNotificationLinksVnfPackage linksSubscription = - new URIisprovidedbytheclientwhencreatingthesubscriptionVnfPackageOnboardingNotificationLinksVnfPackage(); - if (pkgmLinks.getSubscription() != null) { - linksSubscription.setHref(vnfmAdapterUrlProvider.getSubscriptionUriString(subscriptionId)); - } - - final URIisprovidedbytheclientwhencreatingthesubscriptionVnfPackageOnboardingNotificationLinks links = - new URIisprovidedbytheclientwhencreatingthesubscriptionVnfPackageOnboardingNotificationLinks(); - links.setVnfPackage(linksVnfPackage); - links.setSubscription(linksSubscription); - return links; - } - -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/converters/etsicatalog/sol003/PkgChangeNotificationConverter.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/converters/etsicatalog/sol003/PkgChangeNotificationConverter.java deleted file mode 100644 index 157f98787e..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/converters/etsicatalog/sol003/PkgChangeNotificationConverter.java +++ /dev/null @@ -1,85 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2020 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.converters.etsicatalog.sol003; - -import static org.slf4j.LoggerFactory.getLogger; -import org.onap.so.adapters.etsi.sol003.adapter.common.VnfmAdapterUrlProvider; -import org.onap.so.adapters.etsi.sol003.adapter.etsicatalog.notification.model.PkgChangeNotification; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.vnfm.notification.model.VnfPackageChangeNotification; -import org.slf4j.Logger; -import org.springframework.core.convert.converter.Converter; -import org.springframework.stereotype.Service; - -/** - * Converter to convert from an Etsi Catalog Manager {@link PkgChangeNotification} Object to its equivalent SOL003 - * {@link VnfPackageChangeNotification} Object - * - * @author andrew.a.lamb@est.tech - */ -@Service -public class PkgChangeNotificationConverter extends AbstractPkgNotificationConverter - implements Converter { - private static final Logger logger = getLogger(PkgChangeNotificationConverter.class); - - public PkgChangeNotificationConverter(final VnfmAdapterUrlProvider vnfmAdapterUrlProvider) { - super(vnfmAdapterUrlProvider); - } - - /** - * Convert a {@link PkgChangeNotification} Object to an {@link VnfPackageChangeNotification} Object - * - * @param pkgChangeNotification The PkgChangeNotification Object to Convert - * @return The Converted VnfPackageChangeNotification Object - */ - @Override - public VnfPackageChangeNotification convert(final PkgChangeNotification pkgChangeNotification) { - logger.info("Converting PkgChangeNotification\n{}", pkgChangeNotification.toString()); - final VnfPackageChangeNotification vnfPackageChangeNotification = new VnfPackageChangeNotification(); - vnfPackageChangeNotification.setId(pkgChangeNotification.getId()); - - if (pkgChangeNotification.getNotificationType() != null) { - vnfPackageChangeNotification.setNotificationType(VnfPackageChangeNotification.NotificationTypeEnum - .fromValue(pkgChangeNotification.getNotificationType().getValue())); - } - - vnfPackageChangeNotification.setSubscriptionId(pkgChangeNotification.getSubscriptionId()); - vnfPackageChangeNotification.setTimeStamp(pkgChangeNotification.getTimeStamp()); - vnfPackageChangeNotification.setVnfPkgId(pkgChangeNotification.getVnfPkgId()); - - vnfPackageChangeNotification.setVnfdId(pkgChangeNotification.getVnfdId()); - - if (pkgChangeNotification.getChangeType() != null) { - vnfPackageChangeNotification.setChangeType(VnfPackageChangeNotification.ChangeTypeEnum - .fromValue(pkgChangeNotification.getChangeType().getValue())); - } - - if (pkgChangeNotification.getOperationalState() != null) { - vnfPackageChangeNotification.setOperationalState(VnfPackageChangeNotification.OperationalStateEnum - .fromValue(pkgChangeNotification.getOperationalState().getValue())); - } - - vnfPackageChangeNotification.setLinks(convert(pkgChangeNotification.getLinks(), - pkgChangeNotification.getVnfPkgId(), pkgChangeNotification.getSubscriptionId())); - - return vnfPackageChangeNotification; - } - -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/converters/etsicatalog/sol003/PkgOnboardingNotificationConverter.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/converters/etsicatalog/sol003/PkgOnboardingNotificationConverter.java deleted file mode 100644 index 6fdce75754..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/converters/etsicatalog/sol003/PkgOnboardingNotificationConverter.java +++ /dev/null @@ -1,76 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2020 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.converters.etsicatalog.sol003; - -import static org.slf4j.LoggerFactory.getLogger; -import org.onap.so.adapters.etsi.sol003.adapter.common.VnfmAdapterUrlProvider; -import org.onap.so.adapters.etsi.sol003.adapter.etsicatalog.notification.model.PkgOnboardingNotification; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.vnfm.notification.model.VnfPackageOnboardingNotification; -import org.slf4j.Logger; -import org.springframework.core.convert.converter.Converter; -import org.springframework.stereotype.Service; - -/** - * Converter to convert from an Etsi Catalog Manager {@link PkgOnboardingNotification} Object to its equivalent SOL003 - * {@link VnfPackageOnboardingNotification} Object - * - * @author andrew.a.lamb@est.tech - */ -@Service -public class PkgOnboardingNotificationConverter extends AbstractPkgNotificationConverter - implements Converter { - private static final Logger logger = getLogger(PkgOnboardingNotificationConverter.class); - - public PkgOnboardingNotificationConverter(final VnfmAdapterUrlProvider vnfmAdapterUrlProvider) { - super(vnfmAdapterUrlProvider); - } - - - /** - * Convert a {@link PkgOnboardingNotification} Object to an {@link VnfPackageOnboardingNotification} Object - * - * @param pkgOnboardingNotification The PkgOnboardingNotification Object to Convert - * @return The Converted VnfPackageOnboardingNotification Object - */ - @Override - public VnfPackageOnboardingNotification convert(final PkgOnboardingNotification pkgOnboardingNotification) { - logger.info("Converting PkgChangeNotification\n{}", pkgOnboardingNotification.toString()); - final VnfPackageOnboardingNotification vnfPackageOnboardingNotification = - new VnfPackageOnboardingNotification(); - vnfPackageOnboardingNotification.setId(pkgOnboardingNotification.getId()); - - if (pkgOnboardingNotification.getNotificationType() != null) { - vnfPackageOnboardingNotification.setNotificationType(VnfPackageOnboardingNotification.NotificationTypeEnum - .fromValue(pkgOnboardingNotification.getNotificationType().getValue())); - } - - vnfPackageOnboardingNotification.setSubscriptionId(pkgOnboardingNotification.getSubscriptionId()); - vnfPackageOnboardingNotification.setTimeStamp(pkgOnboardingNotification.getTimeStamp()); - vnfPackageOnboardingNotification.setVnfPkgId(pkgOnboardingNotification.getVnfPkgId()); - vnfPackageOnboardingNotification.setVnfdId(pkgOnboardingNotification.getVnfdId()); - - vnfPackageOnboardingNotification.setLinks(convert(pkgOnboardingNotification.getLinks(), - pkgOnboardingNotification.getVnfPkgId(), pkgOnboardingNotification.getSubscriptionId())); - - return vnfPackageOnboardingNotification; - } - -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/converters/etsicatalog/sol003/VnfPkgInfoConverter.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/converters/etsicatalog/sol003/VnfPkgInfoConverter.java deleted file mode 100644 index b6a955bc23..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/converters/etsicatalog/sol003/VnfPkgInfoConverter.java +++ /dev/null @@ -1,198 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.converters.etsicatalog.sol003; - -import java.util.ArrayList; -import java.util.List; -import org.onap.so.adapters.etsi.sol003.adapter.common.VnfmAdapterUrlProvider; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.model.Checksum; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.model.VNFPKGMLinkSerializer; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.model.VnfPackageArtifactInfo; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.model.VnfPackageSoftwareImageInfo; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.model.VnfPkgInfo; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.model.InlineResponse2001; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.model.VnfPackagesAdditionalArtifacts; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.model.VnfPackagesChecksum; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.model.VnfPackagesLinks; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.model.VnfPackagesLinksSelf; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.model.VnfPackagesSoftwareImages; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.core.convert.converter.Converter; -import org.springframework.stereotype.Service; - -/** - * Converter to convert from an Etsi Catalog Manager {@link VnfPkgInfo} Object to its equivalent SOL003 Object - * {@link InlineResponse2001} Object - * - * @author andrew.a.lamb@est.tech - */ -@Service -public class VnfPkgInfoConverter implements Converter { - private static final Logger logger = LoggerFactory.getLogger(VnfPkgInfoConverter.class); - private final VnfmAdapterUrlProvider vnfmAdapterUrlProvider; - - public VnfPkgInfoConverter(final VnfmAdapterUrlProvider vnfmAdapterUrlProvider) { - this.vnfmAdapterUrlProvider = vnfmAdapterUrlProvider; - } - - /** - * Convert a {@link VnfPkgInfo} Object to an {@link InlineResponse2001} Object - * - * @param vnfPkgInfo The VnfPkgInfo Object to Convert - * @return The Converted InlineResponse2001 Object - */ - @Override - public InlineResponse2001 convert(final VnfPkgInfo vnfPkgInfo) { - if (vnfPkgInfo == null) { - logger.error("No VnfPkgInfo Object Provided for Conversion. (Null object received, returning Null)"); - return null; - } - final InlineResponse2001 response = new InlineResponse2001(); - response.setId(vnfPkgInfo.getId()); - response.setVnfdId(vnfPkgInfo.getVnfdId()); - response.setVnfProvider(vnfPkgInfo.getVnfProvider()); - response.setVnfProductName(vnfPkgInfo.getVnfProductName()); - response.setVnfSoftwareVersion(vnfPkgInfo.getVnfSoftwareVersion()); - response.setVnfdVersion(vnfPkgInfo.getVnfdVersion()); - response.setChecksum(convertChecksumToVnfPackagesChecksum(vnfPkgInfo.getChecksum())); - response.setSoftwareImages( - convertVnfPackageSoftwareImageInfoListToVnfPackagesSoftwareImagesList(vnfPkgInfo.getSoftwareImages())); - response.setAdditionalArtifacts(convertVnfPackageArtifactInfoListToVnfPackagesAdditionalArtifactsList( - vnfPkgInfo.getAdditionalArtifacts())); - - if (vnfPkgInfo.getOnboardingState() != null) { - response.setOnboardingState( - InlineResponse2001.OnboardingStateEnum.fromValue(vnfPkgInfo.getOnboardingState().getValue())); - } - - if (vnfPkgInfo.getOperationalState() != null) { - response.setOperationalState( - InlineResponse2001.OperationalStateEnum.fromValue(vnfPkgInfo.getOperationalState().getValue())); - } - - response.setUserDefinedData((vnfPkgInfo.getUserDefinedData())); - - if (vnfPkgInfo.getLinks() != null) { - response.setLinks(getVnfPackagesLinks(vnfPkgInfo.getLinks(), vnfPkgInfo.getId())); - } - - return response; - } - - private VnfPackagesChecksum convertChecksumToVnfPackagesChecksum(final Checksum checksum) { - final VnfPackagesChecksum vnfPackagesChecksum = new VnfPackagesChecksum(); - if (checksum != null) { - vnfPackagesChecksum.setAlgorithm(checksum.getAlgorithm()); - vnfPackagesChecksum.setHash(checksum.getHash()); - } - return vnfPackagesChecksum; - } - - private List convertVnfPackageSoftwareImageInfoListToVnfPackagesSoftwareImagesList( - final List vnfPackageSoftwareImageInfoList) { - final List vnfPackagesSoftwareImages = new ArrayList<>(); - if (vnfPackageSoftwareImageInfoList != null) { - for (final VnfPackageSoftwareImageInfo vnfPackageSoftwareImageInfo : vnfPackageSoftwareImageInfoList) { - final VnfPackagesSoftwareImages softwareImage = - convertVnfPackageSoftwareImageInfoToVnfPackagesSoftwareImages(vnfPackageSoftwareImageInfo); - vnfPackagesSoftwareImages.add(softwareImage); - } - } - return vnfPackagesSoftwareImages; - } - - private VnfPackagesSoftwareImages convertVnfPackageSoftwareImageInfoToVnfPackagesSoftwareImages( - final VnfPackageSoftwareImageInfo vnfPackageSoftwareImageInfo) { - final VnfPackagesSoftwareImages vnfPackagesSoftwareImages = new VnfPackagesSoftwareImages(); - vnfPackagesSoftwareImages.setId(vnfPackageSoftwareImageInfo.getId()); - vnfPackagesSoftwareImages.setName(vnfPackageSoftwareImageInfo.getName()); - vnfPackagesSoftwareImages.setProvider(vnfPackageSoftwareImageInfo.getProvider()); - vnfPackagesSoftwareImages.setVersion(vnfPackageSoftwareImageInfo.getVersion()); - vnfPackagesSoftwareImages - .setChecksum(convertChecksumToVnfPackagesChecksum(vnfPackageSoftwareImageInfo.getChecksum())); - if (vnfPackageSoftwareImageInfo.getContainerFormat() != null) { - vnfPackagesSoftwareImages.setContainerFormat(VnfPackagesSoftwareImages.ContainerFormatEnum - .fromValue(vnfPackageSoftwareImageInfo.getContainerFormat().getValue())); - } - - if (vnfPackageSoftwareImageInfo.getDiskFormat() != null) { - vnfPackagesSoftwareImages.setDiskFormat(VnfPackagesSoftwareImages.DiskFormatEnum - .fromValue(vnfPackageSoftwareImageInfo.getDiskFormat().getValue())); - } - - vnfPackagesSoftwareImages.setCreatedAt(vnfPackageSoftwareImageInfo.getCreatedAt()); - vnfPackagesSoftwareImages.setMinDisk(vnfPackageSoftwareImageInfo.getMinDisk()); - vnfPackagesSoftwareImages.setMinRam(vnfPackageSoftwareImageInfo.getMinRam()); - vnfPackagesSoftwareImages.setSize(vnfPackageSoftwareImageInfo.getSize()); - vnfPackagesSoftwareImages.setUserMetadata(vnfPackageSoftwareImageInfo.getUserMetadata()); - vnfPackagesSoftwareImages.setImagePath(vnfPackageSoftwareImageInfo.getImagePath()); - return vnfPackagesSoftwareImages; - } - - private List convertVnfPackageArtifactInfoListToVnfPackagesAdditionalArtifactsList( - final List vnfPackageArtifactInfoList) { - if (vnfPackageArtifactInfoList != null) { - final List additionalArtifacts = new ArrayList<>(); - for (final VnfPackageArtifactInfo artifactInfo : vnfPackageArtifactInfoList) { - final VnfPackagesAdditionalArtifacts artifact = - convertVnfPackageArtifactInfoToVnfPackagesAdditionalArtifacts(artifactInfo); - additionalArtifacts.add(artifact); - } - return additionalArtifacts; - } - return null; - } - - private VnfPackagesAdditionalArtifacts convertVnfPackageArtifactInfoToVnfPackagesAdditionalArtifacts( - final VnfPackageArtifactInfo vnfPackageArtifactInfo) { - final VnfPackagesAdditionalArtifacts vnfPackagesAdditionalArtifacts = new VnfPackagesAdditionalArtifacts(); - vnfPackagesAdditionalArtifacts.setArtifactPath(vnfPackageArtifactInfo.getArtifactPath()); - vnfPackagesAdditionalArtifacts - .setChecksum(convertChecksumToVnfPackagesChecksum(vnfPackageArtifactInfo.getChecksum())); - vnfPackagesAdditionalArtifacts.setMetadata(vnfPackageArtifactInfo.getMetadata()); - return vnfPackagesAdditionalArtifacts; - } - - private VnfPackagesLinks getVnfPackagesLinks(final VNFPKGMLinkSerializer links, final String vnfPkgId) { - final VnfPackagesLinks vnfPackagesLinks = new VnfPackagesLinks(); - - if (links.getSelf() != null) { - vnfPackagesLinks.setSelf(getVnfPackagesLinksSelf(vnfmAdapterUrlProvider.getVnfPackageUrl(vnfPkgId))); - } - - if (links.getVnfd() != null) { - vnfPackagesLinks.setVnfd(getVnfPackagesLinksSelf(vnfmAdapterUrlProvider.getVnfPackageVnfdUrl(vnfPkgId))); - } - - if (links.getPackageContent() != null) { - vnfPackagesLinks.setPackageContent( - getVnfPackagesLinksSelf(vnfmAdapterUrlProvider.getVnfPackageContentUrl(vnfPkgId))); - } - - return vnfPackagesLinks; - } - - private VnfPackagesLinksSelf getVnfPackagesLinksSelf(final String href) { - return new VnfPackagesLinksSelf().href(href); - } - -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/converters/sol003/etsicatalog/PkgmSubscriptionRequestConverter.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/converters/sol003/etsicatalog/PkgmSubscriptionRequestConverter.java deleted file mode 100644 index 1fb5d8ad5c..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/converters/sol003/etsicatalog/PkgmSubscriptionRequestConverter.java +++ /dev/null @@ -1,198 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.converters.sol003.etsicatalog; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.model.Version; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.model.VnfProducts; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.model.VnfProductsProviders; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.model.PkgmSubscriptionRequest; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.model.SubscriptionsFilter1; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.model.SubscriptionsFilter1.NotificationTypesEnum; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.model.SubscriptionsFilter1.OperationalStateEnum; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.model.SubscriptionsFilter1.UsageStateEnum; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.model.SubscriptionsFilterVersions; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.model.SubscriptionsFilterVnfProducts; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.model.SubscriptionsFilterVnfProductsFromProviders; -import org.springframework.core.convert.converter.Converter; -import org.springframework.stereotype.Service; - -/** - * Converter to convert from an Etsi Catalog Manager {@link PkgmSubscriptionRequest} Object to its equivalent ETSI - * Catalog Manager Object - * - * @author Ronan Kenny (ronan.kenny@est.tech) - * @author Gareth Roper (gareth.roper@est.tech) - */ -@Service -public class PkgmSubscriptionRequestConverter implements - Converter { - - @Override - public org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.model.PkgmSubscriptionRequest convert( - final PkgmSubscriptionRequest pkgmSubscriptionRequest) { - final org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.model.PkgmSubscriptionRequest etsiCatalogManagerSubscriptionRequest = - new org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.model.PkgmSubscriptionRequest(); - - etsiCatalogManagerSubscriptionRequest - .setFilter(getPkgmNotificationsFilter(pkgmSubscriptionRequest.getFilter())); - - return etsiCatalogManagerSubscriptionRequest; - } - - - private org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.model.PkgmNotificationsFilter getPkgmNotificationsFilter( - final SubscriptionsFilter1 sol003SubscriptionsFilter) { - final org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.model.PkgmNotificationsFilter etsiCatalogManagerFilters = - new org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.model.PkgmNotificationsFilter(); - - if (sol003SubscriptionsFilter.getNotificationTypes() != null) { - etsiCatalogManagerFilters.setNotificationTypes( - getPkgmNotificationsFilterNotificationTypes(sol003SubscriptionsFilter.getNotificationTypes())); - } - - etsiCatalogManagerFilters.setVnfProductsFromProviders( - getVnfProductsProviders(sol003SubscriptionsFilter.getVnfProductsFromProviders())); - - etsiCatalogManagerFilters.setVnfdId(getVnfdIds(sol003SubscriptionsFilter.getVnfdId())); - - etsiCatalogManagerFilters.setVnfPkgId(getVnfPkgIds(sol003SubscriptionsFilter.getVnfPkgId())); - - etsiCatalogManagerFilters - .setOperationalState(getOperationalState(sol003SubscriptionsFilter.getOperationalState())); - - etsiCatalogManagerFilters.setUsageState(getUsageState(sol003SubscriptionsFilter.getUsageState())); - - return etsiCatalogManagerFilters; - } - - - private List getUsageState( - final List usageStates) { - if (usageStates != null) { - final List etsiCatalogUsageStates = - new ArrayList<>(); - usageStates.stream().forEach(state -> { - etsiCatalogUsageStates.add( - org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.model.PkgmNotificationsFilter.UsageStateEnum - .fromValue(state.getValue())); - }); - return etsiCatalogUsageStates; - } - return Collections.emptyList(); - } - - - private List getOperationalState( - final List operationalStates) { - if (operationalStates != null) { - final List etsiCatalogOperationalStates = - new ArrayList<>(); - operationalStates.forEach(state -> { - etsiCatalogOperationalStates.add( - org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.model.PkgmNotificationsFilter.OperationalStateEnum - .fromValue(state.getValue())); - }); - - return etsiCatalogOperationalStates; - } - return Collections.emptyList(); - } - - private List getVnfPkgIds(final List vnfPkgId) { - if (vnfPkgId != null) { - final List etsiCatalogManagerVnfPkgId = new ArrayList<>(); - vnfPkgId.forEach(type -> { - etsiCatalogManagerVnfPkgId.add(type); - }); - return etsiCatalogManagerVnfPkgId; - } - return Collections.emptyList(); - } - - private List getVnfdIds(final List vnfdId) { - if (vnfdId != null) { - final List etsiCatalogManagerVnfdId = new ArrayList<>(); - vnfdId.forEach(type -> { - etsiCatalogManagerVnfdId.add(type); - }); - return etsiCatalogManagerVnfdId; - } - return Collections.emptyList(); - } - - private List getVnfProductsProviders( - final List filterProductsFromProvider) { - - if (filterProductsFromProvider != null && !filterProductsFromProvider.isEmpty()) { - final List etsiCatalogManagerVnfProductsProviders = new ArrayList<>(); - filterProductsFromProvider.forEach(vnfProduct -> { - etsiCatalogManagerVnfProductsProviders - .add(new VnfProductsProviders().vnfProvider(vnfProduct.getVnfProvider()) - .vnfProducts(getVnfProducts(vnfProduct.getVnfProducts()))); - }); - return etsiCatalogManagerVnfProductsProviders; - } - return Collections.emptyList(); - } - - private List getVnfProducts(final List sol003VnfProducts) { - if (sol003VnfProducts != null) { - final List etsiCatalogManagerVnfProductsList = new ArrayList<>(); - sol003VnfProducts.forEach(vnfProduct -> { - etsiCatalogManagerVnfProductsList.add(new VnfProducts().vnfProductName(vnfProduct.getVnfProductName()) - .versions(getVersion(vnfProduct.getVersions()))); - }); - return etsiCatalogManagerVnfProductsList; - } - return Collections.emptyList(); - } - - private List getVersion(final List sol003FilterVersions) { - if (sol003FilterVersions != null && !sol003FilterVersions.isEmpty()) { - final List etsiCatalogVersionList = new ArrayList<>(); - sol003FilterVersions.forEach(vnfFilterVersion -> { - etsiCatalogVersionList.add(new Version().vnfSoftwareVersion(vnfFilterVersion.getVnfSoftwareVersion()) - .vnfdVersions(vnfFilterVersion.getVnfdVersions())); - }); - return etsiCatalogVersionList; - } - return Collections.emptyList(); - } - - private List getPkgmNotificationsFilterNotificationTypes( - final List notificationTypes) { - - if (notificationTypes != null && !notificationTypes.isEmpty()) { - final List etsiCatalogNotificationTypes = - new ArrayList<>(); - notificationTypes.forEach(type -> etsiCatalogNotificationTypes.add( - org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.model.PkgmNotificationsFilter.NotificationTypesEnum - .fromValue(type.getValue()))); - return etsiCatalogNotificationTypes; - } - return Collections.emptyList(); - } - - -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/extclients/AbstractServiceProviderConfiguration.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/extclients/AbstractServiceProviderConfiguration.java deleted file mode 100644 index 1129c40154..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/extclients/AbstractServiceProviderConfiguration.java +++ /dev/null @@ -1,56 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients; - -import java.time.LocalDateTime; -import java.util.Iterator; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.JSON; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.rest.EtsiSubscriptionNotificationController; -import org.springframework.http.converter.HttpMessageConverter; -import org.springframework.http.converter.json.GsonHttpMessageConverter; -import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; -import org.springframework.web.client.RestTemplate; -import com.google.gson.Gson; -import org.threeten.bp.OffsetDateTime; - -/** - * A base class that can be extended by classes for configuring HttpRestServiceProvider classes. Provides common methods - * that will be useful to some such classes. - * - * @author gareth.roper@est.tech - */ -public abstract class AbstractServiceProviderConfiguration { - private final JSON.OffsetDateTimeTypeAdapter offsetDateTimeTypeAdapter = new JSON.OffsetDateTimeTypeAdapter(); - - public void setGsonMessageConverter(final RestTemplate restTemplate) { - final Iterator> iterator = restTemplate.getMessageConverters().iterator(); - while (iterator.hasNext()) { - if (iterator.next() instanceof MappingJackson2HttpMessageConverter) { - iterator.remove(); - } - } - final Gson gson = JSON.createGson().registerTypeAdapter(OffsetDateTime.class, offsetDateTimeTypeAdapter) - .registerTypeAdapter(LocalDateTime.class, - new EtsiSubscriptionNotificationController.LocalDateTimeTypeAdapter()) - .create(); - restTemplate.getMessageConverters().add(new GsonHttpMessageConverter(gson)); - } -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/extclients/etsicatalog/EtsiCatalogPackageManagementServiceProvider.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/extclients/etsicatalog/EtsiCatalogPackageManagementServiceProvider.java deleted file mode 100644 index dfa0ab73bd..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/extclients/etsicatalog/EtsiCatalogPackageManagementServiceProvider.java +++ /dev/null @@ -1,72 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2020 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ -package org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog; - -import java.util.Optional; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.model.InlineResponse2001; - -/** - * @author Waqas Ikram (waqas.ikram@est.tech) - * - */ -public interface EtsiCatalogPackageManagementServiceProvider { - - /** - * GET Package Content, from VNF Package. - * - * @param vnfPkgId The ID of the VNF Package from which the "package_content" will be retrieved. - * @return The Package Content of a VNF Package ("vnfPkgId"). - */ - Optional getVnfPackageContent(final String vnfPkgId); - - /** - * GET VNF packages information from ETSI Catalog. Will return zero or more VNF package representations. - * - * @return An Array of all VNF packages retrieved from the ETSI Catalog. - */ - Optional getVnfPackages(); - - /** - * GET specific VNF package information from ETSI Catalog. - * - * @param vnfPkgId The ID of the VNF Package that you want to query. - * @return The VNF package retrieved from the ETSI Catalog - */ - Optional getVnfPackage(final String vnfPkgId); - - /** - * GET specific VNF package VNFD from ETSI Catalog. - * - * @param vnfPkgId The ID of the VNF Package that you want to query. - * @return The VNF package retrieved from the ETSI Catalog - */ - Optional getVnfPackageVnfd(final String vnfPkgId); - - /** - * GET Package Artifact, from VNF Package. - * - * @param vnfPkgId The ID of the VNF Package from which the artifact will be retrieved. - * @param artifactPath Sequence of one or more path segments representing the path of the artifact within the VNF - * Package, e.g., foo/bar/run.sh - * @return The Package Artifact of a VNF Package ("vnfPkgId", "artifactPath"). - */ - Optional getVnfPackageArtifact(final String vnfPkgId, final String artifactPath); - -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/extclients/etsicatalog/EtsiCatalogServiceProvider.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/extclients/etsicatalog/EtsiCatalogServiceProvider.java deleted file mode 100644 index 7a99c344ef..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/extclients/etsicatalog/EtsiCatalogServiceProvider.java +++ /dev/null @@ -1,32 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog; - -/** - * Provides methods for invoking REST calls to the ETSI Catalog Manager. - * - * @author gareth.roper@est.tech - */ -public interface EtsiCatalogServiceProvider - extends EtsiCatalogSubscriptionServiceProvider, EtsiCatalogPackageManagementServiceProvider { - - -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/extclients/etsicatalog/EtsiCatalogServiceProviderConfiguration.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/extclients/etsicatalog/EtsiCatalogServiceProviderConfiguration.java deleted file mode 100644 index f99bdfe3b7..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/extclients/etsicatalog/EtsiCatalogServiceProviderConfiguration.java +++ /dev/null @@ -1,187 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog; - -import java.io.IOException; -import java.security.KeyManagementException; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.cert.CertificateException; -import java.util.Iterator; -import java.util.concurrent.TimeUnit; -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLSession; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.config.Registry; -import org.apache.http.config.RegistryBuilder; -import org.apache.http.conn.socket.ConnectionSocketFactory; -import org.apache.http.conn.socket.PlainConnectionSocketFactory; -import org.apache.http.conn.ssl.SSLConnectionSocketFactory; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.apache.http.ssl.SSLContextBuilder; -import org.onap.logging.filter.spring.SpringClientPayloadFilter; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.AbstractServiceProviderConfiguration; -import org.onap.so.configuration.rest.BasicHttpHeadersProvider; -import org.onap.so.configuration.rest.HttpClientConnectionConfiguration; -import org.onap.so.logging.jaxrs.filter.SOSpringClientFilter; -import org.onap.so.rest.service.HttpRestServiceProvider; -import org.onap.so.rest.service.HttpRestServiceProviderImpl; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.io.Resource; -import org.springframework.http.client.BufferingClientHttpRequestFactory; -import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; -import org.springframework.http.converter.HttpMessageConverter; -import org.springframework.http.converter.json.GsonHttpMessageConverter; -import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; -import org.springframework.web.client.RestTemplate; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -/** - * Configures the HttpRestServiceProvider to make REST calls to the ETSI Catalog Manager - * - * @author gareth.roper@est.tech - */ - -@Configuration -public class EtsiCatalogServiceProviderConfiguration extends AbstractServiceProviderConfiguration { - - public static final String ETSI_CATALOG_REST_TEMPLATE_BEAN = "etsiCatalogRestTemplate"; - - public static final String ETSI_CATALOG_SERVICE_PROVIDER_BEAN = "etsiCatalogServiceProvider"; - - private final static Logger LOGGER = LoggerFactory.getLogger(EtsiCatalogServiceProviderConfiguration.class); - - private final HttpClientConnectionConfiguration clientConnectionConfiguration; - - @Value("${etsi-catalog-manager.http.client.ssl.trust-store:#{null}}") - private Resource trustStore; - @Value("${etsi-catalog-manager.http.client.ssl.trust-store-password:#{null}}") - private String trustStorePassword; - - @Autowired - public EtsiCatalogServiceProviderConfiguration( - final HttpClientConnectionConfiguration clientConnectionConfiguration) { - this.clientConnectionConfiguration = clientConnectionConfiguration; - } - - @Bean - @Qualifier(ETSI_CATALOG_REST_TEMPLATE_BEAN) - public RestTemplate etsiCatalogRestTemplate() { - final RestTemplate restTemplate = new RestTemplate(); - restTemplate.getInterceptors().add(new SOSpringClientFilter()); - restTemplate.getInterceptors().add((new SpringClientPayloadFilter())); - return restTemplate; - } - - @Bean - @Qualifier(ETSI_CATALOG_SERVICE_PROVIDER_BEAN) - public HttpRestServiceProvider etsiCatalogHttpRestServiceProvider( - @Qualifier(ETSI_CATALOG_REST_TEMPLATE_BEAN) final RestTemplate restTemplate) { - setGsonMessageConverter(restTemplate); - - final HttpClientBuilder httpClientBuilder = getHttpClientBuilder(); - if (trustStore != null) { - try { - LOGGER.debug("Setting up HttpComponentsClientHttpRequestFactory with SSL Context"); - LOGGER.debug("Setting client trust-store: {}", trustStore.getURL()); - LOGGER.debug("Creating SSLConnectionSocketFactory with AllowAllHostsVerifier ... "); - final SSLContext sslContext = new SSLContextBuilder() - .loadTrustMaterial(trustStore.getURL(), trustStorePassword.toCharArray()).build(); - final SSLConnectionSocketFactory sslConnectionSocketFactory = - new SSLConnectionSocketFactory(sslContext, AllowAllHostsVerifier.INSTANCE); - httpClientBuilder.setSSLSocketFactory(sslConnectionSocketFactory); - final Registry socketFactoryRegistry = RegistryBuilder - .create().register("http", PlainConnectionSocketFactory.INSTANCE) - .register("https", sslConnectionSocketFactory).build(); - - httpClientBuilder.setConnectionManager(getConnectionManager(socketFactoryRegistry)); - } catch (final KeyManagementException | NoSuchAlgorithmException | KeyStoreException | CertificateException - | IOException exception) { - LOGGER.error("Error reading truststore, TLS connection will fail.", exception); - } - - } else { - LOGGER.debug("Setting connection manager without SSL ConnectionSocketFactory ..."); - httpClientBuilder.setConnectionManager(getConnectionManager()); - } - - final HttpComponentsClientHttpRequestFactory factory = - new HttpComponentsClientHttpRequestFactory(httpClientBuilder.build()); - restTemplate.setRequestFactory(new BufferingClientHttpRequestFactory(factory)); - - return new HttpRestServiceProviderImpl(restTemplate, new BasicHttpHeadersProvider().getHttpHeaders()); - } - - private PoolingHttpClientConnectionManager getConnectionManager( - final Registry socketFactoryRegistry) { - return new PoolingHttpClientConnectionManager(socketFactoryRegistry, null, null, null, - clientConnectionConfiguration.getTimeToLiveInMins(), TimeUnit.MINUTES); - } - - private PoolingHttpClientConnectionManager getConnectionManager() { - return new PoolingHttpClientConnectionManager(clientConnectionConfiguration.getTimeToLiveInMins(), - TimeUnit.MINUTES); - } - - private HttpClientBuilder getHttpClientBuilder() { - return HttpClientBuilder.create().setMaxConnPerRoute(clientConnectionConfiguration.getMaxConnectionsPerRoute()) - .setMaxConnTotal(clientConnectionConfiguration.getMaxConnections()) - .setDefaultRequestConfig(getRequestConfig()); - } - - private RequestConfig getRequestConfig() { - return RequestConfig.custom().setSocketTimeout(clientConnectionConfiguration.getSocketTimeOutInMiliSeconds()) - .setConnectTimeout(clientConnectionConfiguration.getConnectionTimeOutInMilliSeconds()).build(); - } - - private static final class AllowAllHostsVerifier implements HostnameVerifier { - - private static final AllowAllHostsVerifier INSTANCE = new AllowAllHostsVerifier(); - - @Override - public boolean verify(final String hostname, final SSLSession session) { - LOGGER.debug("Skipping hostname verification ..."); - return true; - } - - } - - public void setGsonMessageConverter(final RestTemplate restTemplate) { - final Iterator> iterator = restTemplate.getMessageConverters().iterator(); - while (iterator.hasNext()) { - if (iterator.next() instanceof MappingJackson2HttpMessageConverter) { - iterator.remove(); - } - } - final Gson gson = new GsonBuilder().create(); - restTemplate.getMessageConverters().add(new GsonHttpMessageConverter(gson)); - } - -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/extclients/etsicatalog/EtsiCatalogServiceProviderImpl.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/extclients/etsicatalog/EtsiCatalogServiceProviderImpl.java deleted file mode 100644 index a27a22d674..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/extclients/etsicatalog/EtsiCatalogServiceProviderImpl.java +++ /dev/null @@ -1,281 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog; - -import static org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.EtsiCatalogServiceProviderConfiguration.ETSI_CATALOG_SERVICE_PROVIDER_BEAN; -import java.util.Optional; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.model.NsdmSubscription; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.model.PkgmSubscription; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.model.VnfPkgInfo; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.model.InlineResponse2001; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.rest.exceptions.EtsiCatalogManagerBadRequestException; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.rest.exceptions.EtsiCatalogManagerRequestFailureException; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.rest.exceptions.SubscriptionNotFoundException; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.rest.exceptions.VnfPkgBadRequestException; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.rest.exceptions.VnfPkgConflictException; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.rest.exceptions.VnfPkgNotFoundException; -import org.onap.so.rest.exceptions.HttpResouceNotFoundException; -import org.onap.so.rest.exceptions.InvalidRestRequestException; -import org.onap.so.rest.exceptions.RestProcessingException; -import org.onap.so.rest.service.HttpRestServiceProvider; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.core.convert.ConversionService; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Service; - -/** - * Provides the implementations of the REST Requests to the ETSI Catalog Manager. - * - * @author gareth.roper@est.tech - */ -@Service -public class EtsiCatalogServiceProviderImpl implements EtsiCatalogServiceProvider { - private static final Logger logger = LoggerFactory.getLogger(EtsiCatalogServiceProviderImpl.class); - - private final HttpRestServiceProvider httpServiceProvider; - private final EtsiCatalogUrlProvider etsiCatalogUrlProvider; - private final ConversionService conversionService; - - @Autowired - public EtsiCatalogServiceProviderImpl(final EtsiCatalogUrlProvider etsiCatalogUrlProvider, - @Qualifier(ETSI_CATALOG_SERVICE_PROVIDER_BEAN) final HttpRestServiceProvider httpServiceProvider, - final ConversionService conversionService) { - this.etsiCatalogUrlProvider = etsiCatalogUrlProvider; - this.httpServiceProvider = httpServiceProvider; - this.conversionService = conversionService; - } - - @Override - public Optional getVnfPackageContent(final String vnfPkgId) - throws EtsiCatalogManagerRequestFailureException { - final String vnfRequestUrl = etsiCatalogUrlProvider.getVnfPackageContentUrl(vnfPkgId); - final String vnfRequestName = "getVnfPackageContent"; - return requestVnfElement(vnfPkgId, vnfRequestUrl, vnfRequestName); - } - - @Override - public Optional getVnfPackageArtifact(final String vnfPkgId, final String artifactPath) { - try { - final ResponseEntity response = httpServiceProvider.getHttpResponse( - etsiCatalogUrlProvider.getVnfPackageArtifactUrl(vnfPkgId, artifactPath), byte[].class); - logger.info("getVnfPackageArtifact Request to ETSI Catalog Manager Status Code: {}", - response.getStatusCodeValue()); - if (response.getStatusCode().is2xxSuccessful()) { - return Optional.ofNullable(response.getBody()); - } - } catch (final HttpResouceNotFoundException httpResouceNotFoundException) { - logger.error("Caught HttpResouceNotFoundException", httpResouceNotFoundException); - throw new VnfPkgNotFoundException("No Vnf Package Artifact found with vnfPkgId: \"" + vnfPkgId - + "\" and artifactPath: \"" + artifactPath + "\"."); - } catch (final RestProcessingException restProcessingException) { - logger.error("Caught RestProcessingException with Status Code: {}", restProcessingException.getStatusCode(), - restProcessingException); - if (restProcessingException.getStatusCode() == HttpStatus.CONFLICT.value()) { - throw new VnfPkgConflictException("A conflict occurred with the state of the resource,\n" - + "due to the attribute: onboardingState not being set to ONBOARDED."); - } - } - throw new EtsiCatalogManagerRequestFailureException("Internal Server Error Occurred."); - } - - @Override - public Optional getVnfPackages() { - try { - final ResponseEntity response = - httpServiceProvider.getHttpResponse(etsiCatalogUrlProvider.getVnfPackagesUrl(), VnfPkgInfo[].class); - logger.info("getVnfPackages Request to ETSI Catalog Manager Status Code: {}", - response.getStatusCodeValue()); - if (response.getStatusCode().is2xxSuccessful()) { - if (response.hasBody()) { - final VnfPkgInfo[] vnfPackages = response.getBody(); - assert (vnfPackages != null); - final InlineResponse2001[] responses = new InlineResponse2001[vnfPackages.length]; - for (int index = 0; index < vnfPackages.length; index++) { - if (conversionService.canConvert(vnfPackages[index].getClass(), InlineResponse2001.class)) { - final InlineResponse2001 inlineResponse2001 = - conversionService.convert(vnfPackages[index], InlineResponse2001.class); - if (inlineResponse2001 != null) { - responses[index] = inlineResponse2001; - } - } else { - logger.error("Unable to find Converter for response class: {}", - vnfPackages[index].getClass()); - } - } - return Optional.of(responses); - } - logger.error("Received response without body ..."); - } - logger.error("Unexpected status code received {}", response.getStatusCode()); - return Optional.empty(); - } catch (final InvalidRestRequestException invalidRestRequestException) { - logger.error("Caught InvalidRestRequestException", invalidRestRequestException); - throw new VnfPkgBadRequestException("Error: Bad Request Received"); - } catch (final HttpResouceNotFoundException httpResouceNotFoundException) { - logger.error("Caught HttpResouceNotFoundException", httpResouceNotFoundException); - throw new VnfPkgNotFoundException("No Vnf Packages found"); - } catch (final RestProcessingException restProcessingException) { - logger.error("Caught RestProcessingException with Status Code: {}", restProcessingException.getStatusCode(), - restProcessingException); - throw new EtsiCatalogManagerRequestFailureException("Internal Server Error Occurred."); - } - } - - @Override - public Optional getVnfPackage(final String vnfPkgId) { - try { - final ResponseEntity response = httpServiceProvider - .getHttpResponse(etsiCatalogUrlProvider.getVnfPackageUrl(vnfPkgId), VnfPkgInfo.class); - logger.info("getVnfPackage Request for vnfPkgId {} to ETSI Catalog Manager Status Code: {}", vnfPkgId, - response.getStatusCodeValue()); - if (response.getStatusCode().is2xxSuccessful()) { - if (response.hasBody()) { - final VnfPkgInfo vnfPkgInfo = response.getBody(); - if (conversionService.canConvert(vnfPkgInfo.getClass(), InlineResponse2001.class)) { - return Optional.ofNullable(conversionService.convert(vnfPkgInfo, InlineResponse2001.class)); - } - logger.error("Unable to find Converter for response class: {}", vnfPkgInfo.getClass()); - } - logger.error("Received response without body ...."); - } - return Optional.empty(); - } catch (final InvalidRestRequestException invalidRestRequestException) { - logger.error("Caught InvalidRestRequestException", invalidRestRequestException); - throw new VnfPkgBadRequestException("Error: Bad Request Received"); - } catch (final HttpResouceNotFoundException httpResouceNotFoundException) { - logger.error("Caught HttpResouceNotFoundException", httpResouceNotFoundException); - throw new VnfPkgNotFoundException("No Vnf Package found with vnfPkgId: " + vnfPkgId); - } catch (final RestProcessingException restProcessingException) { - logger.error("Caught RestProcessingException with Status Code: {}", restProcessingException.getStatusCode(), - restProcessingException); - throw new EtsiCatalogManagerRequestFailureException("Internal Server Error Occurred."); - } - } - - @Override - public Optional getVnfPackageVnfd(final String vnfPkgId) { - final String vnfRequestUrl = etsiCatalogUrlProvider.getVnfPackageVnfdUrl(vnfPkgId); - final String vnfRequestName = "getVnfPackageVnfd"; - return requestVnfElement(vnfPkgId, vnfRequestUrl, vnfRequestName); - } - - @Override - public Optional postSubscription( - final org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.model.PkgmSubscriptionRequest etsiCatalogManagerSubscriptionRequest) { - try { - final ResponseEntity responseEntity = - httpServiceProvider.postHttpRequest(etsiCatalogManagerSubscriptionRequest, - etsiCatalogUrlProvider.getSubscriptionUrl(), PkgmSubscription.class); - if (responseEntity.getStatusCode().is2xxSuccessful()) { - if (responseEntity.hasBody()) { - return Optional.of(responseEntity.getBody()); - } - logger.error("Received response without body on postSubscription"); - } - logger.error("Unexpected Status Code Received on postSubscription: {}", responseEntity.getStatusCode()); - return Optional.empty(); - } catch (final InvalidRestRequestException invalidRestRequestException) { - logger.error("Caught InvalidRestRequestException", invalidRestRequestException); - throw new EtsiCatalogManagerBadRequestException( - "Bad Request Received on postSubscription call to ETSI Catalog Manager."); - } catch (final RestProcessingException restProcessingException) { - logger.error("Caught RestProcessingException with Status Code: {}", restProcessingException.getStatusCode(), - restProcessingException); - throw new EtsiCatalogManagerRequestFailureException( - "Internal Server Error Occurred. On postSubscription with StatusCode: " - + restProcessingException.getStatusCode()); - } - } - - @Override - public boolean deleteSubscription(final String subscriptionId) { - try { - final ResponseEntity responseEntity = httpServiceProvider - .deleteHttpRequest(etsiCatalogUrlProvider.getSubscriptionUrl() + "/" + subscriptionId, Void.class); - - if (responseEntity.getStatusCode().is2xxSuccessful()) { - logger.info("Subscription with ID: {} has been successfully deleted from the ETSI Catalog Manager", - subscriptionId); - return true; - } - logger.error("Unexpected Status Code Received on deleteSubscription: {}", responseEntity.getStatusCode()); - return false; - } catch (final HttpResouceNotFoundException resouceNotFoundException) { - final String message = "Unable to find subscription in ETSI Catalog Manager using id: " + subscriptionId; - logger.error(message); - throw new SubscriptionNotFoundException(message); - } catch (final InvalidRestRequestException invalidRestRequestException) { - logger.error("Caught InvalidRestRequestException on deleteSubscription call to ETSI Catalog Manager.", - invalidRestRequestException); - throw new EtsiCatalogManagerBadRequestException( - "Bad Request Received on deleteSubscription call to ETSI Catalog Manager."); - } - } - - @Override - public Optional getSubscription(final String subscriptionId) { - try { - final ResponseEntity responseEntity = httpServiceProvider.getHttpResponse( - etsiCatalogUrlProvider.getSubscriptionUrl() + "/" + subscriptionId, NsdmSubscription.class); - - if (responseEntity.getStatusCode().is2xxSuccessful()) { - logger.debug("Found subscription with ID: {} in ETSI Catalog Manager", subscriptionId); - return Optional.ofNullable(responseEntity.getBody()); - } - logger.error("Unexpected Status Code Received on getting subscription from ETSI Catalog Manager: {}", - responseEntity.getStatusCode()); - } catch (final HttpResouceNotFoundException resouceNotFoundException) { - logger.error("Unable to find subscription in ETSI Catalog Manager using id: {}", subscriptionId); - return Optional.empty(); - } catch (final RestProcessingException | InvalidRestRequestException exception) { - logger.error("Unable to query ETSI Catalog Manager for subscription using id: {}", subscriptionId, - exception); - } - throw new EtsiCatalogManagerRequestFailureException("Internal Server Error Occurred."); - } - - private Optional requestVnfElement(final String vnfPkgId, final String vnfRequestUrl, - final String vnfRequestName) { - try { - final ResponseEntity response = httpServiceProvider.getHttpResponse(vnfRequestUrl, byte[].class); - logger.info("{} Request to ETSI Catalog Manager Status Code: {}", vnfRequestName, - response.getStatusCodeValue()); - if (response.getStatusCode() == HttpStatus.OK) { - return Optional.ofNullable(response.getBody()); - } - } catch (final HttpResouceNotFoundException httpResouceNotFoundException) { - logger.error("Caught HttpResouceNotFoundException", httpResouceNotFoundException); - throw new VnfPkgNotFoundException("No Vnf Package found with vnfPkgId: " + vnfPkgId); - } catch (final RestProcessingException restProcessingException) { - logger.error("Caught RestProcessingException with Status Code: {}", restProcessingException.getStatusCode(), - restProcessingException); - if (restProcessingException.getStatusCode() == HttpStatus.CONFLICT.value()) { - throw new VnfPkgConflictException("A conflict occurred with the state of the resource,\n" - + "due to the attribute: onboardingState not being set to ONBOARDED."); - } - } - throw new EtsiCatalogManagerRequestFailureException("Internal Server Error Occurred."); - } -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/extclients/etsicatalog/EtsiCatalogSubscriptionServiceProvider.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/extclients/etsicatalog/EtsiCatalogSubscriptionServiceProvider.java deleted file mode 100644 index 74e9915819..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/extclients/etsicatalog/EtsiCatalogSubscriptionServiceProvider.java +++ /dev/null @@ -1,55 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2020 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ -package org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog; - -import java.util.Optional; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.model.NsdmSubscription; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.model.PkgmSubscription; - -/** - * @author Waqas Ikram (waqas.ikram@est.tech) - * - */ -public interface EtsiCatalogSubscriptionServiceProvider { - - /** - * POST the SubscriptionRequest Object. - * - * @return The ETSI Catalog Manager's PkgmSubscription object. - */ - Optional postSubscription( - final org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.model.PkgmSubscriptionRequest etsiCatalogManagerSubscriptionRequest); - - /** - * Get the Subscription from ETSI Catalog. - * - * @param subscriptionId Subscription ID - * @return The Subscription {@link NsdmSubscription} from ETSI Catalog - */ - Optional getSubscription(final String subscriptionId); - - /** - * DELETE the SubscriptionRequest Object. - * - * @return A Boolean representing if the delete was successful or not. - */ - boolean deleteSubscription(final String subscriptionId); - -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/extclients/etsicatalog/EtsiCatalogUrlProvider.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/extclients/etsicatalog/EtsiCatalogUrlProvider.java deleted file mode 100644 index 63564600ca..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/extclients/etsicatalog/EtsiCatalogUrlProvider.java +++ /dev/null @@ -1,113 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog; - -import static org.slf4j.LoggerFactory.getLogger; -import org.slf4j.Logger; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Service; - -/** - * Provides the URLs for the REST Requests to the ETSI Catalog Manager. - * - * @author gareth.roper@est.tech - */ -@Service -public class EtsiCatalogUrlProvider { - - private static final Logger logger = getLogger(EtsiCatalogUrlProvider.class); - - @Value("${etsi-catalog-manager.vnfpkgm.endpoint}") - private String etsiCatalogManagerEndpoint; - - public EtsiCatalogUrlProvider() {} - - /** - * Get the URL for retrieving the Package Content from the ETSI Catalog.". - * - * @param vnfPkgId The ID of the VNF Package - * @return the URL for the GET operation - */ - public String getVnfPackageContentUrl(final String vnfPkgId) { - final String url = etsiCatalogManagerEndpoint + "/vnf_packages/" + vnfPkgId + "/package_content"; - logger.info("getEtsiCatalogVnfPackageContentUrl: {}", url); - return url; - } - - /** - * Get the URL for retrieving VNF packages information from ETSI Catalog.". - * - * @return the URL for the GET operation - */ - public String getVnfPackagesUrl() { - final String url = etsiCatalogManagerEndpoint + "/vnf_packages"; - logger.info("getEtsiCatalogVnfPackagesEndpoint: {}", url); - return url; - } - - /** - * Get the URL for retrieving specific VNF package information from the ETSI Catalog.". - * - * @param vnfPkgId The ID of the VNF Package - * @return the URL for the GET operation - */ - public String getVnfPackageUrl(final String vnfPkgId) { - final String url = etsiCatalogManagerEndpoint + "/vnf_packages/" + vnfPkgId; - logger.info("getEtsiCatalogVnfPackageEndpoint: {}", url); - return url; - } - - /** - * Get the URL for retrieving VNF Package Artifacts - * - * @param vnfPkgId The ID of the VNF Package - * @param artifactPath The path to the Artifact - * @return the URL for the GET operation - */ - public String getVnfPackageArtifactUrl(final String vnfPkgId, final String artifactPath) { - final String url = etsiCatalogManagerEndpoint + "/vnf_packages/" + vnfPkgId + "/artifacts/" + artifactPath; - logger.info("getVnfPackageArtifactUrl: {}", url); - return url; - } - - /** - * Get the URL for retrieving VNF packages vnfd from ETSI Catalog. - * - * @param vnfPkgId The ID of the VNF Package - * @return the URL for the GET operation - */ - public String getVnfPackageVnfdUrl(final String vnfPkgId) { - final String url = etsiCatalogManagerEndpoint + "/vnf_packages/" + vnfPkgId + "/vnfd"; - logger.info("getEtsiCatalogVnfPackageVnfd: {}", url); - return url; - } - - /** - * Get the URL for posting/retrieving a Subscription - * - * @return the URL for the operation - */ - public String getSubscriptionUrl() { - final String url = etsiCatalogManagerEndpoint + "/subscriptions"; - logger.info("getSubscriptionNotificationUrl: {}", url); - return url; - } -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/extclients/vnfm/VnfmHttpServiceProviderConfiguration.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/extclients/vnfm/VnfmHttpServiceProviderConfiguration.java deleted file mode 100644 index 57ed2c381a..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/extclients/vnfm/VnfmHttpServiceProviderConfiguration.java +++ /dev/null @@ -1,49 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2020 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ -package org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.vnfm; - -import static org.onap.so.client.RestTemplateConfig.CONFIGURABLE_REST_TEMPLATE; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.AbstractServiceProviderConfiguration; -import org.onap.so.configuration.rest.BasicHttpHeadersProvider; -import org.onap.so.rest.service.HttpRestServiceProvider; -import org.onap.so.rest.service.HttpRestServiceProviderImpl; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.client.RestTemplate; - -/** - * @author Waqas Ikram (waqas.ikram@est.tech) - * - */ -@Configuration -public class VnfmHttpServiceProviderConfiguration extends AbstractServiceProviderConfiguration { - public static final String VNFM_ADAPTER_HTTP_SERVICE_PROVIDER_BEAN = "vnfmAdapterHttpServiceProvider"; - - @Bean - @Qualifier(VNFM_ADAPTER_HTTP_SERVICE_PROVIDER_BEAN) - public HttpRestServiceProvider vnfmAdapterHttpRestServiceProvider( - @Autowired @Qualifier(CONFIGURABLE_REST_TEMPLATE) RestTemplate restTemplate) { - setGsonMessageConverter(restTemplate); - return new HttpRestServiceProviderImpl(restTemplate, new BasicHttpHeadersProvider().getHttpHeaders()); - } - -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/EtsiSubscriptionNotificationController.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/EtsiSubscriptionNotificationController.java deleted file mode 100644 index 71ff4a907b..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/EtsiSubscriptionNotificationController.java +++ /dev/null @@ -1,166 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2020 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.rest; - -import static org.onap.so.adapters.etsi.sol003.adapter.common.CommonConstants.ETSI_SUBSCRIPTION_NOTIFICATION_CONTROLLER_BASE_URL; -import static org.slf4j.LoggerFactory.getLogger; -import java.util.AbstractMap; -import java.util.Map.Entry; -import javax.ws.rs.core.MediaType; -import org.onap.so.adapters.etsi.sol003.adapter.etsicatalog.notification.model.PkgChangeNotification; -import org.onap.so.adapters.etsi.sol003.adapter.etsicatalog.notification.model.PkgOnboardingNotification; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.rest.exceptions.InternalServerErrorException; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.rest.exceptions.NotificationTypeNotSupportedException; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.subscriptionmanagement.NotificationManager; -import org.slf4j.Logger; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.time.LocalDateTime; -import java.io.IOException; -import java.time.format.DateTimeFormatter; - -/** - * This controller handles the ETSI Subscription Notification Endpoints. - * - * @author Ronan Kenny (ronan.kenny@est.tech) - * @author Gareth Roper (gareth.roper@est.tech) - * @author Andrew Lamb (andrew.a.lamb@est.tech) - */ -@Controller -@RequestMapping(value = ETSI_SUBSCRIPTION_NOTIFICATION_CONTROLLER_BASE_URL) -public class EtsiSubscriptionNotificationController { - - private static final Logger logger = getLogger(EtsiSubscriptionNotificationController.class); - private final NotificationManager notificationManager; - private final Gson gson; - - @Autowired - public EtsiSubscriptionNotificationController(final NotificationManager notificationManager) { - this.notificationManager = notificationManager; - this.gson = new GsonBuilder().registerTypeAdapter(LocalDateTime.class, new LocalDateTimeTypeAdapter()).create(); - } - - @GetMapping(value = "/notification") - public ResponseEntity testSubscriptionNotificationEndPoint() { - logger.debug("Testing Notification Endpoint"); - return ResponseEntity.noContent().build(); - } - - /** - * POST notification on to subscriber. - * - * @param notification The notification to send. - * @return Response Code: 204 No Content if Successful, ProblemDetails Object if not. - */ - @PostMapping(value = "/notification", consumes = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON) - public ResponseEntity postSubscriptionNotification(@RequestBody final Object notification) { - logger.info("Posting subscription notification class: {} \n{}", notification.getClass(), notification); - final String notificationString = gson.toJson(notification); - - final Entry notificationObject = getNotificationObject(notificationString); - if (notificationManager.processSubscriptionNotification(notificationObject.getValue(), - notificationObject.getKey())) { - logger.info("Notification Delivered Successfully"); - return ResponseEntity.noContent().build(); - } - final String errorMessage = "An error occurred. Sending of notification to VNFM failed."; - logger.error(errorMessage); - throw new InternalServerErrorException(errorMessage); - } - - private Entry getNotificationObject(final String notification) { - logger.info("getNotificationObject() notification: {}", notification); - final String notificationType = getNotificationType(notification); - if (PkgOnboardingNotification.NotificationTypeEnum.VNFPACKAGEONBOARDINGNOTIFICATION.getValue() - .equals(notificationType)) { - final PkgOnboardingNotification pkgOnboardingNotification = - gson.fromJson(notification, PkgOnboardingNotification.class); - logger.info("Onboarding notification received:\n{}", pkgOnboardingNotification); - return new AbstractMap.SimpleEntry<>(pkgOnboardingNotification.getSubscriptionId(), - pkgOnboardingNotification); - } - if (PkgChangeNotification.NotificationTypeEnum.VNFPACKAGECHANGENOTIFICATION.getValue() - .equals(notificationType)) { - final PkgChangeNotification pkgChangeNotification = - gson.fromJson(notification, PkgChangeNotification.class); - logger.info("Change notification received:\n{}", pkgChangeNotification); - return new AbstractMap.SimpleEntry<>(pkgChangeNotification.getSubscriptionId(), pkgChangeNotification); - - } - - final String errorMessage = "An error occurred. Notification type not supported for: " + notificationType; - logger.error(errorMessage); - throw new NotificationTypeNotSupportedException(errorMessage); - - } - - private String getNotificationType(final String notification) { - try { - logger.info("getNotificationType() notification: {}", notification); - final JsonParser parser = new JsonParser(); - final JsonObject element = (JsonObject) parser.parse(notification); - return element.get("notificationType").getAsString(); - } catch (final Exception e) { - logger.error("An error occurred processing notificiation: {}", e.getMessage()); - } - throw new NotificationTypeNotSupportedException( - "Unable to parse notification type in object \n" + notification); - } - - public static class LocalDateTimeTypeAdapter extends TypeAdapter { - - private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); - - @Override - public void write(final JsonWriter out, final LocalDateTime localDateTime) throws IOException { - if (localDateTime == null) { - out.nullValue(); - } else { - out.value(FORMATTER.format(localDateTime)); - } - } - - @Override - public LocalDateTime read(final JsonReader in) throws IOException { - switch (in.peek()) { - case NULL: - in.nextNull(); - return null; - default: - final String dateTime = in.nextString(); - return LocalDateTime.parse(dateTime, FORMATTER); - } - } - } - -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/Sol003PackageManagementController.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/Sol003PackageManagementController.java deleted file mode 100644 index 275ffa21e5..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/Sol003PackageManagementController.java +++ /dev/null @@ -1,176 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.rest; - -import static org.onap.so.adapters.etsi.sol003.adapter.common.CommonConstants.PACKAGE_MANAGEMENT_BASE_URL; -import static org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.PackageManagementConstants.APPLICATION_ZIP; -import static org.slf4j.LoggerFactory.getLogger; -import java.util.Optional; -import javax.ws.rs.core.MediaType; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.model.ProblemDetails; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.EtsiCatalogServiceProvider; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.model.InlineResponse2001; -import org.slf4j.Logger; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; - -/** - * Controller for handling the VNF Package Management. For further information please read: - * https://www.etsi.org/deliver/etsi_gs/NFV-SOL/001_099/003/02.05.01_60/gs_nfv-sol003v020501p.pdf Use the section number - * above each endpoint to find the corresponding section in the above document. - * - * @author gareth.roper@est.tech - */ -@Controller -@RequestMapping(value = PACKAGE_MANAGEMENT_BASE_URL, consumes = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) -public class Sol003PackageManagementController { - - private final EtsiCatalogServiceProvider etsiCatalogServiceProvider; - private static final String LOG_REQUEST_RECEIVED = "VNF PackageManagement Controller: {} {} {} {}"; - private static final Logger logger = getLogger(Sol003PackageManagementController.class); - - @Autowired - Sol003PackageManagementController(final EtsiCatalogServiceProvider etsiCatalogServiceProvider) { - this.etsiCatalogServiceProvider = etsiCatalogServiceProvider; - } - - /** - * GET VNF packages information. Will return zero or more VNF package representations that match the attribute - * filter. These representations will be in a list. Section Number: 10.4.2 - * - * @return An Array of all VNF packages. Object: InlineResponse2001[] Response Code: 200 OK - */ - @GetMapping(value = "/vnf_packages", produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) - public ResponseEntity getVnfPackages() { - logger.info(LOG_REQUEST_RECEIVED, "getVnfPackages."); - final Optional response = etsiCatalogServiceProvider.getVnfPackages(); - if (response.isPresent()) { - logger.info(LOG_REQUEST_RECEIVED, "getVnfPackages Response: ", HttpStatus.OK); - return ResponseEntity.ok().body(response.get()); - } - final String errorMessage = "An error occurred, a null response was received by the\n" - + " Sol003PackageManagementController from the EtsiCatalogManager using the GET \"vnf_packages\" \n" - + "endpoint."; - logger.error(errorMessage); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new ProblemDetails().detail(errorMessage)); - } - - /** - * GET VNF package information. Will return a specific VNF package representation that match the attribute filter. - * Section Number: 10.4.3 - * - * @param vnfPkgId The ID of the VNF Package that you want to query. - * @return A VNF package based on vnfPkgId. Object: VnfPkgInfo Response Code: 200 OK - */ - @GetMapping(value = "/vnf_packages/{vnfPkgId}", produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) - public ResponseEntity getVnfPackage(@PathVariable("vnfPkgId") final String vnfPkgId) { - logger.info(LOG_REQUEST_RECEIVED, "getVnfPackage: ", vnfPkgId); - final Optional response = etsiCatalogServiceProvider.getVnfPackage(vnfPkgId); - if (response.isPresent()) { - logger.info(LOG_REQUEST_RECEIVED, "getVnfPackage Response: ", HttpStatus.OK); - return ResponseEntity.ok().body(response.get()); - } - final String errorMessage = "An error occurred, a null response was received by the\n" - + " Sol003PackageManagementController from the EtsiCatalogManager using the GET \"vnf_packages\" by vnfPkgId: \"" - + vnfPkgId + "\" \n" + "endpoint."; - logger.error(errorMessage); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new ProblemDetails().detail(errorMessage)); - } - - /** - * GET VNFD, from VNF package. Will return a copy of the file representing the VNFD or a ZIP file that contains the - * file/multiple files representing the VNFD specified. Section Number: 10.4.4 - * - * @param vnfPkgId The ID of the VNF Package that you want to retrieve the VNFD from. - * @return The VNFD of a VNF Package as a single file or within a ZIP file. Object: byte[] Response Code: 200 OK - */ - @GetMapping(value = "/vnf_packages/{vnfPkgId}/vnfd", - produces = {MediaType.TEXT_PLAIN, APPLICATION_ZIP, MediaType.APPLICATION_JSON}) - public ResponseEntity getVnfPackageVnfd(@PathVariable("vnfPkgId") final String vnfPkgId) { - logger.info(LOG_REQUEST_RECEIVED, "getVnfPackageVnfd Endpoint Invoked with VNF Package ID: ", vnfPkgId); - final Optional response = etsiCatalogServiceProvider.getVnfPackageVnfd(vnfPkgId); - if (response.isPresent()) { - logger.info(LOG_REQUEST_RECEIVED, "getVnfPackageVnfd Response: ", HttpStatus.OK); - return new ResponseEntity<>(response.get(), HttpStatus.OK); - } - final String errorMessage = "An error occurred, a null response was received by the\n" - + " Sol003PackageManagementController from the EtsiCatalogManager using the GET \"vnfd\" \n" - + "endpoint."; - - logger.error(errorMessage); - return new ResponseEntity<>(new ProblemDetails().detail(errorMessage), HttpStatus.INTERNAL_SERVER_ERROR); - } - - /** - * GET Package Content, from VNF Package. Will return a copy of the VNF package file that you specified. Section - * Number: 10.4.5 - * - * @param vnfPkgId The ID of the VNF Package that you want to retrieve the "package_content" from. - * @return The Package Content of a VNF Package. Object: byte[] Response Code: 200 OK - */ - @GetMapping(value = "/vnf_packages/{vnfPkgId}/package_content", - produces = {MediaType.APPLICATION_JSON, APPLICATION_ZIP, MediaType.APPLICATION_OCTET_STREAM}) - public ResponseEntity getVnfPackageContent(@PathVariable("vnfPkgId") final String vnfPkgId) { - logger.info(LOG_REQUEST_RECEIVED, "getVnfPackageContent Endpoint Invoked with VNF Package ID: ", vnfPkgId); - final Optional response = etsiCatalogServiceProvider.getVnfPackageContent(vnfPkgId); - if (response.isPresent()) { - logger.info(LOG_REQUEST_RECEIVED, "getVnfPackageContent Response: ", HttpStatus.OK); - return ResponseEntity.ok().body(response.get()); - } - final String errorMessage = "An error occurred, a null response was received by the\n" - + " Sol003PackageManagementController from the EtsiCatalogManager using the GET \"package_content\" \n" - + "endpoint."; - logger.error(errorMessage); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new ProblemDetails().detail(errorMessage)); - } - - /** - * GET Artifact, from VNF Package Will return a the content of the artifact that you specified. Section Number: - * 10.4.6 - * - * @param vnfPkgId The ID of the VNF Package that you want to retrieve an artifact from. - * @param artifactPath The path of the artifact that you want to retrieve. - * @return An Artifact from a VNF Package. Object: byte[] Response Code: 200 OK - */ - @GetMapping(value = "/vnf_packages/{vnfPkgId}/artifacts/{artifactPath}", - produces = {MediaType.APPLICATION_OCTET_STREAM, MediaType.APPLICATION_JSON}) - public ResponseEntity getVnfPackageArtifact(@PathVariable("vnfPkgId") final String vnfPkgId, - @PathVariable("artifactPath") final String artifactPath) { - logger.info(LOG_REQUEST_RECEIVED, "getVnfPackageArtifact: vnfPkgId= ", vnfPkgId, " artifactPath=", - artifactPath); - final Optional response = etsiCatalogServiceProvider.getVnfPackageArtifact(vnfPkgId, artifactPath); - if (response.isPresent()) { - logger.info(LOG_REQUEST_RECEIVED, "getVnfPackageArtifact Response: ", HttpStatus.OK); - return ResponseEntity.ok().body(response.get()); - } - final String errorMessage = "An error occurred, a null response was received by the\n" - + " Sol003PackageManagementController from the EtsiCatalogManager using the\n GET \"vnf_packages\" by vnfPkgId: \"" - + vnfPkgId + "\" for artifactPath: \"" + artifactPath + "\"\n" + "endpoint."; - logger.error(errorMessage); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new ProblemDetails().detail(errorMessage)); - } - -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/Sol003PackageManagementSubscriptionController.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/Sol003PackageManagementSubscriptionController.java deleted file mode 100644 index 73c62afac5..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/Sol003PackageManagementSubscriptionController.java +++ /dev/null @@ -1,172 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2020 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.rest; - -import static org.onap.so.adapters.etsi.sol003.adapter.common.CommonConstants.PACKAGE_MANAGEMENT_BASE_URL; -import static org.slf4j.LoggerFactory.getLogger; -import java.net.URI; -import java.security.GeneralSecurityException; -import java.util.List; -import java.util.Optional; -import javax.ws.rs.core.MediaType; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.model.ProblemDetails; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.model.InlineResponse201; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.model.PkgmSubscriptionRequest; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.subscriptionmanagement.SubscriptionManager; -import org.slf4j.Logger; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.DeleteMapping; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; - -/** - * Controller for handling the Subscription Management. The client can use this resource to subscribe to notifications - * related to the VNF package management, and to query its subscriptions. For further information please read: - * https://www.etsi.org/deliver/etsi_gs/NFV-SOL/001_099/003/02.05.01_60/gs_nfv-sol003v020501p.pdf Use the section number - * above each endpoint to find the corresponding section in the above document. - * - * @author Ronan Kenny (ronan.kenny@est.tech) - * @author Gareth Roper (gareth.roper@est.tech) - */ -@Controller -@RequestMapping(value = PACKAGE_MANAGEMENT_BASE_URL, produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}, - consumes = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) -public class Sol003PackageManagementSubscriptionController { - - private static final String LOG_REQUEST_RECEIVED = "Subscription Management Controller: {} {}"; - private static final Logger logger = getLogger(Sol003PackageManagementSubscriptionController.class); - private final SubscriptionManager subscriptionManager; - - @Autowired - public Sol003PackageManagementSubscriptionController(final SubscriptionManager subscriptionManager) { - this.subscriptionManager = subscriptionManager; - } - - /** - * POST Subscribe request. Will send request and respond with the subscription that you subscribed to, if - * successful. Section Number: 10.4.7 - * - * @param pkgmSubscriptionRequest This includes the details of the subscription to be created. - * @return The subscription requested, if successful. Object: InlineRespone2002 Response Code: 201 Created Response - * Code: 303 Duplicate Subscription - * @throws GeneralSecurityException - */ - @PostMapping(value = "/subscriptions") - public ResponseEntity postSubscriptionRequest(@RequestBody final PkgmSubscriptionRequest pkgmSubscriptionRequest) - throws GeneralSecurityException { - logger.info(LOG_REQUEST_RECEIVED, " postSubscriptionRequest Endpoint Called", pkgmSubscriptionRequest); - - // Check if subscription exists already. - final Optional exists = subscriptionManager.getSubscriptionId(pkgmSubscriptionRequest); - - if (exists.isPresent()) { - final URI subscriptionUri = subscriptionManager.getSubscriptionUri(exists.get()); - final HttpHeaders headers = createLocationHeader(subscriptionUri); - logger.info("PkgmSubscriptionRequest already exists with uri {} ", subscriptionUri); - return new ResponseEntity<>(headers, HttpStatus.SEE_OTHER); - } - - logger.debug("No duplicate Subscription exists, continuing with POST."); - final Optional optionalInlineResponse = - subscriptionManager.createSubscription(pkgmSubscriptionRequest); - - if (optionalInlineResponse.isPresent()) { - InlineResponse201 inlineResponse = optionalInlineResponse.get(); - final URI subscriptionUri = subscriptionManager.getSubscriptionUri(inlineResponse.getId()); - final HttpHeaders headers = createLocationHeader(subscriptionUri); - logger.debug("Sending response with uri {} ", subscriptionUri); - return new ResponseEntity<>(inlineResponse, headers, HttpStatus.CREATED); - } - final String errorMessage = "A null response was received during the postSubscriptionRequest call."; - logger.error(errorMessage); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new ProblemDetails().detail(errorMessage)); - } - - /** - * GET all subscriptions. Will return a list of all subscriptions currently active. Section Number: 10.4.7 - * - * @return All of the current active subscriptions. Object: List Response Code: 200 OK - */ - @GetMapping(value = "/subscriptions") - public ResponseEntity> getSubscriptions() { - logger.info(LOG_REQUEST_RECEIVED, " getSubscriptions."); - List subscriptionsList = subscriptionManager.getSubscriptions(); - return new ResponseEntity<>(subscriptionsList, HttpStatus.OK); - } - - /** - * GET a specific subscription, by subscriptionId. Section Number: 10.4.8 - * - * @param subscriptionId The ID of the subscription that you wish to retrieve. - * @return A subscription based on subscriptionId. Object: InlineResponse2002 Response Code: 200 OK - */ - @GetMapping(value = "/subscriptions/{subscriptionId}") - public ResponseEntity getSubscription(@PathVariable("subscriptionId") final String subscriptionId) { - logger.info(LOG_REQUEST_RECEIVED, " Getting Subscription: ", subscriptionId); - final Optional optional = subscriptionManager.getSubscription(subscriptionId); - if (optional.isPresent()) { - logger.debug("Return subscription with id {} and body {}", subscriptionId, optional); - return new ResponseEntity<>(optional.get(), HttpStatus.OK); - } - final String errorMessage = - "The requested subscription: " + subscriptionId + " was not found on call getSubscription"; - logger.error(errorMessage); - return ResponseEntity.status(HttpStatus.NOT_FOUND).body(new ProblemDetails().detail(errorMessage)); - } - - /** - * DELETE a specific subscription, by subscriptionId. Section Number: 10.4.8.3.5 - * - * @param subscriptionId The ID of the subscription that you wish to delete. - * @return Empty response if successful. Object: Void Response Code: 204 No Content - */ - @DeleteMapping(value = "/subscriptions/{subscriptionId}") - public ResponseEntity deleteSubscription(@PathVariable("subscriptionId") final String subscriptionId) { - if (subscriptionManager.deleteSubscription(subscriptionId)) { - logger.debug("Successfully deleted subscription with id {}", subscriptionId); - return ResponseEntity.noContent().build(); - } - final String errorMessage = - "The requested subscription: " + subscriptionId + " was not found on call deleteSubscription"; - logger.error(errorMessage); - return ResponseEntity.status(HttpStatus.NOT_FOUND).body(new ProblemDetails().detail(errorMessage)); - } - - /** - * Method to set the Location in the header with the URI parameter - * - * @param subscriptionUri - * @return header with callbackUri in Location - */ - private HttpHeaders createLocationHeader(final URI subscriptionUri) { - final HttpHeaders headers = new HttpHeaders(); - headers.setLocation(subscriptionUri); - return headers; - } - -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/exceptions/AuthenticationTypeNotSupportedException.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/exceptions/AuthenticationTypeNotSupportedException.java deleted file mode 100644 index b886f348fe..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/exceptions/AuthenticationTypeNotSupportedException.java +++ /dev/null @@ -1,44 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2020 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ -package org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.rest.exceptions; - -import org.springframework.http.HttpStatus; -import org.springframework.web.bind.annotation.ResponseStatus; - -/** - * Exception for an unsupported authentication type - * - * @author Andrew Lamb (andrew.a.lamb@est.tech) - */ -@ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR) -public class AuthenticationTypeNotSupportedException extends RuntimeException { - - private static final long serialVersionUID = 2939423208362066902L; - - public AuthenticationTypeNotSupportedException(final String message) { - super(message); - } - - @Override - public synchronized Throwable fillInStackTrace() { - return this; - } - -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/exceptions/ConversionFailedException.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/exceptions/ConversionFailedException.java deleted file mode 100644 index ebb2aeb2c3..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/exceptions/ConversionFailedException.java +++ /dev/null @@ -1,44 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2020 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ -package org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.rest.exceptions; - -import org.springframework.http.HttpStatus; -import org.springframework.web.bind.annotation.ResponseStatus; - -/** - * Exception for Conversion Failures - * - * @author Gareth Roper (gareth.roper@est.tech) - * @author Andrew Lamb (andrew.a.lamb@est.tech) - */ -@ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR) -public class ConversionFailedException extends RuntimeException { - - private static final long serialVersionUID = 45898561453196895L; - - public ConversionFailedException(final String message) { - super(message); - } - - @Override - public synchronized Throwable fillInStackTrace() { - return this; - } -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/exceptions/EtsiCatalogManagerBadRequestException.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/exceptions/EtsiCatalogManagerBadRequestException.java deleted file mode 100644 index fec2045253..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/exceptions/EtsiCatalogManagerBadRequestException.java +++ /dev/null @@ -1,43 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ -package org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.rest.exceptions; - -import org.springframework.http.HttpStatus; -import org.springframework.web.bind.annotation.ResponseStatus; - -/** - * Exception for an ETSI Catalog Manager Bad Request Exception. - * - * @author Gareth Roper (gareth.roper@est.tech - */ -@ResponseStatus(code = HttpStatus.BAD_REQUEST) -public class EtsiCatalogManagerBadRequestException extends RuntimeException { - - private static final long serialVersionUID = 6571317418914258768L; - - public EtsiCatalogManagerBadRequestException(final String message) { - super(message); - } - - @Override - public synchronized Throwable fillInStackTrace() { - return this; - } -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/exceptions/EtsiCatalogManagerRequestFailureException.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/exceptions/EtsiCatalogManagerRequestFailureException.java deleted file mode 100644 index 8c20ec1565..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/exceptions/EtsiCatalogManagerRequestFailureException.java +++ /dev/null @@ -1,43 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ -package org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.rest.exceptions; - -import org.springframework.http.HttpStatus; -import org.springframework.web.bind.annotation.ResponseStatus; - -/** - * Exception for an ETSI Catalog Manager Request Failure - * - * @author gareth.roper@est.tech - */ -@ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR) -public class EtsiCatalogManagerRequestFailureException extends RuntimeException { - - private static final long serialVersionUID = 66862444537194516L; - - public EtsiCatalogManagerRequestFailureException(final String message) { - super(message); - } - - @Override - public synchronized Throwable fillInStackTrace() { - return this; - } -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/exceptions/EtsiSubscriptionNotificationControllerExceptionHandler.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/exceptions/EtsiSubscriptionNotificationControllerExceptionHandler.java deleted file mode 100644 index 434560aa57..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/exceptions/EtsiSubscriptionNotificationControllerExceptionHandler.java +++ /dev/null @@ -1,112 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2020 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.rest.exceptions; - -import static org.slf4j.LoggerFactory.getLogger; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.model.ProblemDetails; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.rest.EtsiSubscriptionNotificationController; -import org.onap.so.rest.exceptions.HttpResouceNotFoundException; -import org.onap.so.rest.exceptions.InvalidRestRequestException; -import org.onap.so.rest.exceptions.RestProcessingException; -import org.slf4j.Logger; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.ControllerAdvice; -import org.springframework.web.bind.annotation.ExceptionHandler; - -/** - * Exception Handler for the Etsi Subscription Notification Controller {@link EtsiSubscriptionNotificationController - * EtsiSubscriptionNotificationController} - * - * @author Andrew Lamb (andrew.a.lamb@est.tech) - */ -@ControllerAdvice(assignableTypes = EtsiSubscriptionNotificationController.class) -public class EtsiSubscriptionNotificationControllerExceptionHandler { - - private static final Logger logger = getLogger(EtsiSubscriptionNotificationControllerExceptionHandler.class); - - @ExceptionHandler(InvalidRestRequestException.class) - public ResponseEntity handleInvalidRestRequestException( - final InvalidRestRequestException invalidRestRequestException) { - final String errorMessage = "An error occurred. Sending of notification to VNFM failed with response: " - + HttpStatus.BAD_REQUEST + ".\n" + invalidRestRequestException.getMessage(); - logger.error(errorMessage); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new ProblemDetails().detail(errorMessage)); - } - - @ExceptionHandler(HttpResouceNotFoundException.class) - public ResponseEntity handleHttpResourceNotFoundException( - final HttpResouceNotFoundException httpResourceNotFoundException) { - final String errorMessage = "An error occurred. Sending of notification to VNFM failed with response: " - + HttpStatus.NOT_FOUND + ".\n" + httpResourceNotFoundException.getMessage(); - logger.error(errorMessage); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new ProblemDetails().detail(errorMessage)); - } - - @ExceptionHandler(RestProcessingException.class) - public ResponseEntity handleRestProcessingException( - final RestProcessingException restProcessingException) { - final String errorMessage = "An error occurred. Sending of notification to VNFM failed with response: " - + restProcessingException.getStatusCode() + ".\n" + restProcessingException.getMessage(); - logger.error(errorMessage); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new ProblemDetails().detail(errorMessage)); - } - - @ExceptionHandler(InternalServerErrorException.class) - public ResponseEntity handleInternalServerErrorException( - final InternalServerErrorException internalServerErrorException) { - logger.error(internalServerErrorException.getMessage()); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(new ProblemDetails().detail(internalServerErrorException.getMessage())); - } - - @ExceptionHandler(AuthenticationTypeNotSupportedException.class) - public ResponseEntity handleAuthenticationTypeNotSupportedException( - final AuthenticationTypeNotSupportedException authenticationTypeNotSupportedException) { - logger.error(authenticationTypeNotSupportedException.getMessage()); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(new ProblemDetails().detail(authenticationTypeNotSupportedException.getMessage())); - } - - @ExceptionHandler(ConversionFailedException.class) - public ResponseEntity handleConversionFailedException( - final ConversionFailedException conversionFailedException) { - logger.error(conversionFailedException.getMessage()); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(new ProblemDetails().detail(conversionFailedException.getMessage())); - } - - @ExceptionHandler(NotificationTypeNotSupportedException.class) - public ResponseEntity handleNotificationTypeNotSupportedException( - final NotificationTypeNotSupportedException notificationTypeNotSupportedException) { - logger.error(notificationTypeNotSupportedException.getMessage()); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(new ProblemDetails().detail(notificationTypeNotSupportedException.getMessage())); - } - - @ExceptionHandler(SubscriptionNotFoundException.class) - public ResponseEntity handleSubscriptionNotFoundException( - final SubscriptionNotFoundException subscriptionNotFoundException) { - logger.error(subscriptionNotFoundException.getMessage()); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(new ProblemDetails().detail(subscriptionNotFoundException.getMessage())); - } -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/exceptions/InternalServerErrorException.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/exceptions/InternalServerErrorException.java deleted file mode 100644 index e3a7207dcb..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/exceptions/InternalServerErrorException.java +++ /dev/null @@ -1,43 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2020 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ -package org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.rest.exceptions; - -import org.springframework.http.HttpStatus; -import org.springframework.web.bind.annotation.ResponseStatus; - -/** - * Exception for an ETSI Catalog Manager Request Failure - * - * @author gareth.roper@est.tech - */ -@ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR) -public class InternalServerErrorException extends RuntimeException { - - private static final long serialVersionUID = 66864561537194516L; - - public InternalServerErrorException(final String message) { - super(message); - } - - @Override - public synchronized Throwable fillInStackTrace() { - return this; - } -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/exceptions/NotificationTypeNotSupportedException.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/exceptions/NotificationTypeNotSupportedException.java deleted file mode 100644 index 42b75d51b2..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/exceptions/NotificationTypeNotSupportedException.java +++ /dev/null @@ -1,44 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2020 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ -package org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.rest.exceptions; - -import org.springframework.http.HttpStatus; -import org.springframework.web.bind.annotation.ResponseStatus; - -/** - * Exception for an unsupported notification type - * - * @author Andrew Lamb (andrew.a.lamb@est.tech) - */ -@ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR) -public class NotificationTypeNotSupportedException extends RuntimeException { - - private static final long serialVersionUID = 2939423208362066902L; - - public NotificationTypeNotSupportedException(final String message) { - super(message); - } - - @Override - public synchronized Throwable fillInStackTrace() { - return this; - } - -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/exceptions/Sol003PackageManagementControllerExceptionHandler.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/exceptions/Sol003PackageManagementControllerExceptionHandler.java deleted file mode 100644 index bfcf451f13..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/exceptions/Sol003PackageManagementControllerExceptionHandler.java +++ /dev/null @@ -1,94 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.rest.exceptions; - -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.model.ProblemDetails; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.rest.Sol003PackageManagementController; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.ControllerAdvice; -import org.springframework.web.bind.annotation.ExceptionHandler; - -/** - * Exception Handler for the Package Management Controller {@link Sol003PackageManagementController Sol003Controller} - * - * @author gareth.roper@est.tech - */ -@ControllerAdvice(assignableTypes = Sol003PackageManagementController.class) - -public class Sol003PackageManagementControllerExceptionHandler { - - @ExceptionHandler(EtsiCatalogManagerRequestFailureException.class) - public ResponseEntity handleEtsiCatalogManagerRequestFailureException( - final EtsiCatalogManagerRequestFailureException etsiCatalogManagerRequestFailureException) { - final ProblemDetails problemDetails = new ProblemDetails(); - problemDetails.setDetail(etsiCatalogManagerRequestFailureException.getMessage()); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(problemDetails); - } - - @ExceptionHandler(EtsiCatalogManagerBadRequestException.class) - public ResponseEntity handleEtsiCatalogManagerBadRequestFailureException( - final EtsiCatalogManagerBadRequestException etsiCatalogManagerBadRequestException) { - final ProblemDetails problemDetails = new ProblemDetails(); - problemDetails.setDetail(etsiCatalogManagerBadRequestException.getMessage()); - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(problemDetails); - } - - @ExceptionHandler(SubscriptionNotFoundException.class) - public ResponseEntity handleSubscriptionNotFoundException( - final SubscriptionNotFoundException subscriptionNotFoundException) { - final ProblemDetails problemDetails = new ProblemDetails(); - problemDetails.setDetail(subscriptionNotFoundException.getMessage()); - return ResponseEntity.status(HttpStatus.NOT_FOUND).body(problemDetails); - } - - @ExceptionHandler(ConversionFailedException.class) - public ResponseEntity handleConversionFailedException( - final ConversionFailedException conversionFailedException) { - final ProblemDetails problemDetails = new ProblemDetails(); - problemDetails.setDetail(conversionFailedException.getMessage()); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(problemDetails); - } - - @ExceptionHandler(VnfPkgConflictException.class) - public ResponseEntity handleVnfPkgConflictException( - final VnfPkgConflictException vnfPkgConflictException) { - final ProblemDetails problemDetails = new ProblemDetails(); - problemDetails.setDetail(vnfPkgConflictException.getMessage()); - return ResponseEntity.status(HttpStatus.CONFLICT).body(problemDetails); - } - - @ExceptionHandler(VnfPkgNotFoundException.class) - public ResponseEntity handleVnfPkgNotFoundException( - final VnfPkgNotFoundException vnfPkgNotFoundException) { - final ProblemDetails problemDetails = new ProblemDetails(); - problemDetails.setDetail(vnfPkgNotFoundException.getMessage()); - return ResponseEntity.status(HttpStatus.NOT_FOUND).body(problemDetails); - } - - @ExceptionHandler(VnfPkgBadRequestException.class) - public ResponseEntity handleVnfPkgBadRequestException( - final VnfPkgBadRequestException vnfPkgBadRequestException) { - final ProblemDetails problemDetails = new ProblemDetails(); - problemDetails.setDetail(vnfPkgBadRequestException.getMessage()); - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(problemDetails); - } -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/exceptions/SubscriptionNotFoundException.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/exceptions/SubscriptionNotFoundException.java deleted file mode 100644 index 65f7245b09..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/exceptions/SubscriptionNotFoundException.java +++ /dev/null @@ -1,43 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2020 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ -package org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.rest.exceptions; - -import org.springframework.http.HttpStatus; -import org.springframework.web.bind.annotation.ResponseStatus; - -/** - * Exception for an ETSI Catalog Manager Request Failure - * - * @author gareth.roper@est.tech - */ -@ResponseStatus(code = HttpStatus.NOT_FOUND) -public class SubscriptionNotFoundException extends RuntimeException { - - private static final long serialVersionUID = 85268561453194516L; - - public SubscriptionNotFoundException(final String message) { - super(message); - } - - @Override - public synchronized Throwable fillInStackTrace() { - return this; - } -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/exceptions/VnfPkgBadRequestException.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/exceptions/VnfPkgBadRequestException.java deleted file mode 100644 index bbf80928cb..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/exceptions/VnfPkgBadRequestException.java +++ /dev/null @@ -1,43 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ -package org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.rest.exceptions; - -import org.springframework.http.HttpStatus; -import org.springframework.web.bind.annotation.ResponseStatus; - -/** - * Exception for a Vnfpkg Bad Request failure, due to state of resource. - * - * @author andrew.a.lamb@est.tech - */ -@ResponseStatus(code = HttpStatus.BAD_REQUEST) -public class VnfPkgBadRequestException extends RuntimeException { - - private static final long serialVersionUID = 3301317418914258411L; - - public VnfPkgBadRequestException(final String message) { - super(message); - } - - @Override - public synchronized Throwable fillInStackTrace() { - return this; - } -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/exceptions/VnfPkgConflictException.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/exceptions/VnfPkgConflictException.java deleted file mode 100644 index a5ec31318e..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/exceptions/VnfPkgConflictException.java +++ /dev/null @@ -1,43 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ -package org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.rest.exceptions; - -import org.springframework.http.HttpStatus; -import org.springframework.web.bind.annotation.ResponseStatus; - -/** - * Exception for a VnfPkg Conflict failures, due to state of resource. - * - * @author gareth.roper@est.tech - */ -@ResponseStatus(code = HttpStatus.CONFLICT) -public class VnfPkgConflictException extends RuntimeException { - - private static final long serialVersionUID = 26862444537198441L; - - public VnfPkgConflictException(final String message) { - super(message); - } - - @Override - public synchronized Throwable fillInStackTrace() { - return this; - } -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/exceptions/VnfPkgNotFoundException.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/exceptions/VnfPkgNotFoundException.java deleted file mode 100644 index 0d3cdd27a8..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/exceptions/VnfPkgNotFoundException.java +++ /dev/null @@ -1,43 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ -package org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.rest.exceptions; - -import org.springframework.http.HttpStatus; -import org.springframework.web.bind.annotation.ResponseStatus; - -/** - * Exception for VnfPkg Not Found Failures - * - * @author gareth.roper@est.tech - */ -@ResponseStatus(code = HttpStatus.NOT_FOUND) -public class VnfPkgNotFoundException extends RuntimeException { - - private static final long serialVersionUID = 26862444537198441L; - - public VnfPkgNotFoundException(final String message) { - super(message); - } - - @Override - public synchronized Throwable fillInStackTrace() { - return this; - } -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/subscriptionmanagement/AbstractNotificationServiceProvider.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/subscriptionmanagement/AbstractNotificationServiceProvider.java deleted file mode 100644 index 666067b714..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/subscriptionmanagement/AbstractNotificationServiceProvider.java +++ /dev/null @@ -1,59 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2020 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ -package org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.subscriptionmanagement; - -import static org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.vnfm.VnfmHttpServiceProviderConfiguration.VNFM_ADAPTER_HTTP_SERVICE_PROVIDER_BEAN; -import java.nio.charset.StandardCharsets; -import org.apache.commons.codec.binary.Base64; -import org.onap.so.configuration.rest.BasicHttpHeadersProvider; -import org.onap.so.rest.service.HttpRestServiceProvider; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; - -/** - * A base class that can be extended by classes for providing notification services. Provides common methods that will - * be useful to those classes. - * - * @author Waqas Ikram (waqas.ikram@est.tech) - * @author Andrew Lamb (andrew.a.lamb@est.tech) - */ -public abstract class AbstractNotificationServiceProvider { - - @Autowired - @Qualifier(VNFM_ADAPTER_HTTP_SERVICE_PROVIDER_BEAN) - private HttpRestServiceProvider httpRestServiceProvider; - - protected HttpRestServiceProvider getHttpRestServiceProvider() { - return httpRestServiceProvider; - } - - protected BasicHttpHeadersProvider getBasicHttpHeadersProviderWithBasicAuth(final String username, - final String password) { - final byte[] encodedAuth = getBasicAuth(username, password); - final String authHeader = "Basic " + new String(encodedAuth); - return new BasicHttpHeadersProvider(authHeader); - } - - protected byte[] getBasicAuth(final String username, final String password) { - final String auth = username + ":" + password; - return Base64.encodeBase64(auth.getBytes(StandardCharsets.ISO_8859_1)); - } - -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/subscriptionmanagement/BasicAuthNotificationServiceProvider.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/subscriptionmanagement/BasicAuthNotificationServiceProvider.java deleted file mode 100644 index 616493ccf3..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/subscriptionmanagement/BasicAuthNotificationServiceProvider.java +++ /dev/null @@ -1,68 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2020 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ -package org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.subscriptionmanagement; - -import static org.slf4j.LoggerFactory.getLogger; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.model.SubscriptionsAuthentication; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.model.SubscriptionsAuthentication.AuthTypeEnum; -import org.onap.so.configuration.rest.HttpHeadersProvider; -import org.onap.so.rest.service.HttpRestServiceProvider; -import org.slf4j.Logger; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Service; - -/** - * Implementation of a NotificationServiceProvider which supports Basic Authentication - * - * @author Waqas Ikram (waqas.ikram@est.tech) - * @author Andrew Lamb (andrew.a.lamb@est.tech) - */ -@Service -public class BasicAuthNotificationServiceProvider extends AbstractNotificationServiceProvider - implements NotificationServiceProvider { - - private static final Logger logger = getLogger(BasicAuthNotificationServiceProvider.class); - - @Override - public boolean send(final Object notification, final SubscriptionsAuthentication subscriptionsAuthentication, - final String callbackUri) { - logger.info("Sending notification to uri: {}", callbackUri); - final HttpHeadersProvider httpHeadersProvider = - getBasicHttpHeadersProviderWithBasicAuth(subscriptionsAuthentication.getParamsBasic().getUserName(), - subscriptionsAuthentication.getParamsBasic().getPassword()); - final HttpRestServiceProvider httpRestServiceProvider = getHttpRestServiceProvider(); - - final ResponseEntity responseEntity = httpRestServiceProvider.postHttpRequest(notification, callbackUri, - httpHeadersProvider.getHttpHeaders(), Void.class); - if (responseEntity.getStatusCode().is2xxSuccessful()) { - logger.info("Notification sent successfully."); - return true; - } - - logger.error("Failed to send notification."); - return false; - } - - @Override - public AuthTypeEnum getAuthType() { - return AuthTypeEnum.BASIC; - } - -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/subscriptionmanagement/NotificationManager.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/subscriptionmanagement/NotificationManager.java deleted file mode 100644 index aaf824630d..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/subscriptionmanagement/NotificationManager.java +++ /dev/null @@ -1,137 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2020 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.subscriptionmanagement; - -import static org.slf4j.LoggerFactory.getLogger; -import java.util.List; -import java.util.Optional; -import org.onap.so.adapters.etsi.sol003.adapter.etsicatalog.notification.model.PkgChangeNotification; -import org.onap.so.adapters.etsi.sol003.adapter.etsicatalog.notification.model.PkgOnboardingNotification; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.vnfm.notification.model.VnfPackageChangeNotification; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.vnfm.notification.model.VnfPackageOnboardingNotification; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.model.PkgmSubscriptionRequest; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.model.SubscriptionsAuthentication; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.model.SubscriptionsAuthentication.AuthTypeEnum; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.rest.exceptions.AuthenticationTypeNotSupportedException; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.rest.exceptions.ConversionFailedException; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.rest.exceptions.NotificationTypeNotSupportedException; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.rest.exceptions.SubscriptionNotFoundException; -import org.slf4j.Logger; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.convert.ConversionService; -import org.springframework.stereotype.Service; - -/** - * Manages package management subscription notifications to the VNFMs - * - * @author Andrew Lamb (andrew.a.lamb@est.tech) - * - */ -@Service -public class NotificationManager { - - private static final Logger logger = getLogger(NotificationManager.class); - private final ConversionService conversionService; - private final SubscriptionManager subscriptionManager; - private final NotificationServiceProviderFactory notificationServiceProviderFactory; - - @Autowired - public NotificationManager(final SubscriptionManager subscriptionManager, final ConversionService conversionService, - final NotificationServiceProviderFactory notificationServiceProviderFactory) { - this.subscriptionManager = subscriptionManager; - this.conversionService = conversionService; - this.notificationServiceProviderFactory = notificationServiceProviderFactory; - } - - /** - * Process a subscription notification. Checks for a subscription request stored in the adapter and if there is, it - * sends the notification to the subscribed vnfm. - * - * @param notification the notification to send to the vnfm - * @param subscriptionId the id of the subscription request - * @return true if the notification is successfully sent - */ - public boolean processSubscriptionNotification(final Object notification, final String subscriptionId) { - final Optional optionalSubscription = - subscriptionManager.getSubscriptionRequest(subscriptionId); - if (optionalSubscription.isPresent()) { - final PkgmSubscriptionRequest subscriptionRequest = optionalSubscription.get(); - return notifyVnfm(subscriptionRequest, notification); - } - final String errorMessage = "No subscription found with subscriptionId " + subscriptionId - + ". Unable to forward notification to subscriber."; - logger.error(errorMessage); - throw new SubscriptionNotFoundException(errorMessage); - } - - private boolean notifyVnfm(final PkgmSubscriptionRequest subscriptionRequest, final Object notification) { - if (!(notification instanceof PkgOnboardingNotification) && !(notification instanceof PkgChangeNotification)) { - final String errorMessage = - "An error occurred. Notification type not supported for: " + notification.getClass(); - logger.error(errorMessage); - throw new NotificationTypeNotSupportedException(errorMessage); - } - - final SubscriptionsAuthentication subscriptionsAuthentication = subscriptionRequest.getAuthentication(); - final AuthTypeEnum authType = getAuthType(subscriptionsAuthentication.getAuthType()); - final NotificationServiceProvider sender = notificationServiceProviderFactory.getNotificationSender(authType); - - final Object vnfmNotificationObject = convertEtsiCatalogNotification(notification); - - if (sender.send(vnfmNotificationObject, subscriptionsAuthentication, subscriptionRequest.getCallbackUri())) { - logger.info("Notification delivered successfully {}", notification); - return true; - } - - logger.error("Failed to deliver notification."); - return false; - } - - private SubscriptionsAuthentication.AuthTypeEnum getAuthType(final List authTypes) { - if (authTypes.contains(SubscriptionsAuthentication.AuthTypeEnum.TLS_CERT)) { - return SubscriptionsAuthentication.AuthTypeEnum.TLS_CERT; - } - if (authTypes.contains(SubscriptionsAuthentication.AuthTypeEnum.OAUTH2_CLIENT_CREDENTIALS)) { - return SubscriptionsAuthentication.AuthTypeEnum.OAUTH2_CLIENT_CREDENTIALS; - } - if (authTypes.contains(SubscriptionsAuthentication.AuthTypeEnum.BASIC)) { - return SubscriptionsAuthentication.AuthTypeEnum.BASIC; - } - final String errorMessage = - "An error occurred. No supported authentication type provided in subscription request."; - logger.error(errorMessage); - throw new AuthenticationTypeNotSupportedException(errorMessage); - } - - private Object convertEtsiCatalogNotification(final Object etsiCatalogNotification) { - logger.info("Converting notification:\n {}", etsiCatalogNotification); - if (conversionService.canConvert(etsiCatalogNotification.getClass(), VnfPackageOnboardingNotification.class)) { - return conversionService.convert(etsiCatalogNotification, VnfPackageOnboardingNotification.class); - } else if (conversionService.canConvert(etsiCatalogNotification.getClass(), - VnfPackageChangeNotification.class)) { - return conversionService.convert(etsiCatalogNotification, VnfPackageChangeNotification.class); - } - final String errorMessage = "An error occurred. Unable to convert provided notification object."; - logger.error(errorMessage + "\n" + etsiCatalogNotification); - throw new ConversionFailedException(errorMessage); - } - -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/subscriptionmanagement/NotificationServiceProvider.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/subscriptionmanagement/NotificationServiceProvider.java deleted file mode 100644 index bdba77efcb..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/subscriptionmanagement/NotificationServiceProvider.java +++ /dev/null @@ -1,51 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2020 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ -package org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.subscriptionmanagement; - -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.model.SubscriptionsAuthentication; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.model.SubscriptionsAuthentication.AuthTypeEnum; - -/** - * Interface which lays out requirements for a Notification Service Provider - * - * @author Waqas Ikram (waqas.ikram@est.tech) - * @author Andrew Lamb (andrew.a.lamb@est.tech) - */ -public interface NotificationServiceProvider { - - /** - * Method to send a notification to a uri, given the subscription authentication - * - * @param notification The notification to send - * @param subscriptionsAuthentication Object containing the authentication details - * @param callbackUri The uri to send the notification to - * @return true if notification is delivered successfully, otherwise false - */ - boolean send(final Object notification, final SubscriptionsAuthentication subscriptionsAuthentication, - final String callbackUri); - - /** - * Method to get the supported authorization type of the service provider - * - * @return the supported AuthTypeEnum - */ - AuthTypeEnum getAuthType(); - -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/subscriptionmanagement/NotificationServiceProviderFactory.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/subscriptionmanagement/NotificationServiceProviderFactory.java deleted file mode 100644 index 05795750c3..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/subscriptionmanagement/NotificationServiceProviderFactory.java +++ /dev/null @@ -1,67 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2020 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ -package org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.subscriptionmanagement; - -import static org.slf4j.LoggerFactory.getLogger; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.model.SubscriptionsAuthentication.AuthTypeEnum; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.rest.exceptions.AuthenticationTypeNotSupportedException; -import org.slf4j.Logger; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -/** - * Factory to provide a notification services - * - * @author Waqas Ikram (waqas.ikram@est.tech) - * @author Andrew Lamb (andrew.a.lamb@est.tech) - */ -@Component -public class NotificationServiceProviderFactory { - - private static final Logger logger = getLogger(NotificationServiceProviderFactory.class); - private static final Map CACHE = new HashMap<>(); - - @Autowired - public NotificationServiceProviderFactory(final List services) { - for (final NotificationServiceProvider notificationServiceProvider : services) { - logger.debug("Adding {} of type {} to cache", notificationServiceProvider.getClass().getCanonicalName(), - notificationServiceProvider.getAuthType()); - CACHE.put(notificationServiceProvider.getAuthType(), notificationServiceProvider); - } - } - - /** - * Get a notification service for a given authorization type - * - * @param type the type of authentication required - * @return the notification service - */ - public NotificationServiceProvider getNotificationSender(final AuthTypeEnum type) { - final NotificationServiceProvider service = CACHE.get(type); - if (service == null) { - throw new AuthenticationTypeNotSupportedException("Unknown type: " + type); - } - return service; - } - -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/subscriptionmanagement/OAuthNotificationServiceProvider.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/subscriptionmanagement/OAuthNotificationServiceProvider.java deleted file mode 100644 index 213eb11a0d..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/subscriptionmanagement/OAuthNotificationServiceProvider.java +++ /dev/null @@ -1,104 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2020 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ -package org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.subscriptionmanagement; - -import static org.slf4j.LoggerFactory.getLogger; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.model.SubscriptionsAuthentication; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.model.SubscriptionsAuthentication.AuthTypeEnum; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.rest.exceptions.InternalServerErrorException; -import org.onap.so.configuration.rest.BasicHttpHeadersProvider; -import org.onap.so.configuration.rest.HttpHeadersProvider; -import org.onap.so.rest.service.HttpRestServiceProvider; -import org.slf4j.Logger; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Service; - -/** - * @author Waqas Ikram (waqas.ikram@est.tech) - * @author Andrew Lamb (andrew.a.lamb@est.tech) - * - */ -@Service -public class OAuthNotificationServiceProvider extends AbstractNotificationServiceProvider - implements NotificationServiceProvider { - - private static final Logger logger = getLogger(OAuthNotificationServiceProvider.class); - - @Override - public boolean send(final Object notification, final SubscriptionsAuthentication subscriptionsAuthentication, - final String callbackUri) { - logger.info("Sending notification to uri: {}", callbackUri); - logger.info("Object: {}", notification); - final String token = getAccessToken(subscriptionsAuthentication); - - if (token == null) { - logger.error("Failed to get access token"); - return false; - } - - final HttpHeadersProvider httpHeadersProvider = getHttpHeadersProvider(token); - final HttpRestServiceProvider httpRestServiceProvider = getHttpRestServiceProvider(); - final ResponseEntity responseEntity = httpRestServiceProvider.postHttpRequest(notification, callbackUri, - httpHeadersProvider.getHttpHeaders(), Void.class); - if (responseEntity.getStatusCode().is2xxSuccessful()) { - logger.info("Notification sent successfully."); - return true; - } - - logger.error("Failed to send notification."); - return false; - } - - @Override - public AuthTypeEnum getAuthType() { - return AuthTypeEnum.OAUTH2_CLIENT_CREDENTIALS; - } - - private BasicHttpHeadersProvider getHttpHeadersProvider(final String token) { - final String authHeader = "Bearer " + token; - return new BasicHttpHeadersProvider(authHeader); - } - - private String getAccessToken(final SubscriptionsAuthentication subscriptionsAuthentication) { - logger.info("Requesting Access Token."); - - final String tokenEndpoint = subscriptionsAuthentication.getParamsOauth2ClientCredentials().getTokenEndpoint(); - - final HttpHeadersProvider httpHeadersProvider = getBasicHttpHeadersProviderWithBasicAuth( - subscriptionsAuthentication.getParamsOauth2ClientCredentials().getClientId(), - subscriptionsAuthentication.getParamsOauth2ClientCredentials().getClientPassword()); - - final HttpRestServiceProvider httpRestServiceProvider = getHttpRestServiceProvider(); - final ResponseEntity responseEntity = httpRestServiceProvider.postHttpRequest(null, - tokenEndpoint, httpHeadersProvider.getHttpHeaders(), OAuthTokenResponse.class); - if (responseEntity.getStatusCode().is2xxSuccessful()) { - if (responseEntity.getBody() != null) { - logger.info("Returning Access Token."); - return responseEntity.getBody().getAccessToken(); - } - } - - final String errorMessage = "An error occurred. Unable to retrieve OAuth Token from VNFM for notification."; - logger.error(errorMessage); - throw new InternalServerErrorException(errorMessage); - } - - -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/subscriptionmanagement/OAuthTokenResponse.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/subscriptionmanagement/OAuthTokenResponse.java deleted file mode 100644 index b7e288a4be..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/subscriptionmanagement/OAuthTokenResponse.java +++ /dev/null @@ -1,56 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2020 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ -package org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.subscriptionmanagement; - -import java.io.Serializable; -import javax.xml.bind.annotation.XmlElement; -import com.google.gson.annotations.SerializedName; - -/** - * @author Waqas Ikram (waqas.ikram@est.tech) - * @author Andrew Lamb (andrew.a.lamb@est.tech) - */ -public class OAuthTokenResponse implements Serializable { - - private static final long serialVersionUID = -6455742984985959926L; - - @XmlElement(name = "access_token") - @SerializedName("access_token") - private String accessToken; - - /** - * Get the Accees Token - * - * @return the Access Token - */ - public String getAccessToken() { - return accessToken; - } - - /** - * Set the Access Token - * - * @param accessToken - */ - public void setAccessToken(final String accessToken) { - this.accessToken = accessToken; - } - -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/subscriptionmanagement/SubscriptionManager.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/subscriptionmanagement/SubscriptionManager.java deleted file mode 100644 index adf0fda1ab..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/subscriptionmanagement/SubscriptionManager.java +++ /dev/null @@ -1,209 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2020 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.subscriptionmanagement; - -import static org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.model.SubscriptionAuthentication.AuthTypeEnum.BASIC; -import static org.slf4j.LoggerFactory.getLogger; -import java.net.URI; -import java.security.GeneralSecurityException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.onap.so.adapters.etsi.sol003.adapter.common.VnfmAdapterUrlProvider; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.EtsiCatalogServiceProvider; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.model.BasicAuth; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.model.NsdmSubscription; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.model.PkgmSubscription; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.model.InlineResponse201; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.model.PkgmSubscriptionRequest; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.model.SubscriptionsLinks; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.model.VnfPackagesLinksSelf; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.rest.exceptions.ConversionFailedException; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.rest.exceptions.InternalServerErrorException; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.rest.exceptions.SubscriptionNotFoundException; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.subscriptionmanagement.cache.PackageManagementCacheServiceProvider; -import org.slf4j.Logger; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.convert.ConversionService; -import org.springframework.stereotype.Service; - -/** - * Manages package management subscriptions from the VNFMs - * - * @author Ronan Kenny (ronan.kenny@est.tech) - * @author Gareth Roper (gareth.roper@est.tech) - */ -@Service -public class SubscriptionManager { - - private static final Logger logger = getLogger(SubscriptionManager.class); - private final PackageManagementCacheServiceProvider packageManagementCacheServiceProvider; - private final ConversionService conversionService; - private final EtsiCatalogServiceProvider etsiCatalogServiceProvider; - private final VnfmAdapterUrlProvider vnfmAdapterUrlProvider; - - @Autowired - public SubscriptionManager(final PackageManagementCacheServiceProvider packageManagementCacheServiceProvider, - final ConversionService conversionService, final EtsiCatalogServiceProvider etsiCatalogServiceProvider, - final VnfmAdapterUrlProvider vnfmAdapterUrlProvider) { - this.packageManagementCacheServiceProvider = packageManagementCacheServiceProvider; - this.conversionService = conversionService; - this.etsiCatalogServiceProvider = etsiCatalogServiceProvider; - this.vnfmAdapterUrlProvider = vnfmAdapterUrlProvider; - } - - public Optional createSubscription(final PkgmSubscriptionRequest pkgmSubscriptionRequest) - throws GeneralSecurityException { - - final org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.model.PkgmSubscriptionRequest etsiCatalogManagerSubscriptionRequest = - buildEtsiCatalogManagerPkgmSubscriptionRequest(pkgmSubscriptionRequest); - - final Optional optionalEtsiCatalogManagerSubscription = - etsiCatalogServiceProvider.postSubscription(etsiCatalogManagerSubscriptionRequest); - - if (optionalEtsiCatalogManagerSubscription.isPresent()) { - final PkgmSubscription etsiCatalogManagerSubscription = optionalEtsiCatalogManagerSubscription.get(); - logger.debug("postPkgmSubscriptionRequest Response SubscriptionId: {}", - Objects.requireNonNull(etsiCatalogManagerSubscription.getId())); - final String subscriptionId = etsiCatalogManagerSubscription.getId(); - - packageManagementCacheServiceProvider.addSubscription(subscriptionId, pkgmSubscriptionRequest); - - final InlineResponse201 response = new InlineResponse201(); - response.setId(subscriptionId); - response.setFilter(pkgmSubscriptionRequest.getFilter()); - response.setCallbackUri(vnfmAdapterUrlProvider.getSubscriptionUriString(subscriptionId)); - response.setLinks(new SubscriptionsLinks() - .self(new VnfPackagesLinksSelf().href(getSubscriptionUri(subscriptionId).toString()))); - - return Optional.of(response); - } - throw new InternalServerErrorException( - "Received empty response from POST to ETSI Catalog Manager Subscription Endpoint."); - } - - public Optional getSubscriptionId(final PkgmSubscriptionRequest pkgmSubscriptionRequest) { - return packageManagementCacheServiceProvider.getSubscriptionId(pkgmSubscriptionRequest); - } - - public Optional getSubscription(final String subscriptionId) { - - logger.debug("Checking if subscrition with id: {} exists in ETSI Catalog Manager", subscriptionId); - final Optional etsiCatalogSubscriptionOption = - etsiCatalogServiceProvider.getSubscription(subscriptionId); - - if (!etsiCatalogSubscriptionOption.isPresent()) { - logger.debug("Unable to find subscription in ETSI Catalog Manager using id: {}", subscriptionId); - if (packageManagementCacheServiceProvider.getSubscription(subscriptionId).isPresent()) { - logger.debug("will remove subcription with id: {} from local cache", subscriptionId); - packageManagementCacheServiceProvider.deleteSubscription(subscriptionId); - } - } - - final Optional optional = - packageManagementCacheServiceProvider.getSubscription(subscriptionId); - if (optional.isPresent()) { - final PkgmSubscriptionRequest subscription = optional.get(); - return Optional.of(getInlineResponse2002(subscriptionId, subscription)); - } - return Optional.empty(); - } - - public List getSubscriptions() { - final Map subscriptions = - packageManagementCacheServiceProvider.getSubscriptions(); - final List response = new ArrayList<>(); - subscriptions.forEach((key, value) -> { - final Optional optional = getSubscription(key); - if (optional.isPresent()) { - response.add(optional.get()); - } - }); - return response; - } - - public boolean deleteSubscription(final String subscriptionId) { - if (packageManagementCacheServiceProvider.getSubscription(subscriptionId).isPresent()) { - try { - if (etsiCatalogServiceProvider.deleteSubscription(subscriptionId)) { - return packageManagementCacheServiceProvider.deleteSubscription(subscriptionId); - } - } catch (final SubscriptionNotFoundException subscriptionNotFoundException) { - logger.error( - "Unable to find subscription in ETSI Catalog Manager using id: {} will delete it from local cache", - subscriptionId); - return packageManagementCacheServiceProvider.deleteSubscription(subscriptionId); - } - } - return false; - } - - public URI getSubscriptionUri(final String subscriptionId) { - return vnfmAdapterUrlProvider.getSubscriptionUri(subscriptionId); - } - - public Optional getSubscriptionRequest(final String subscriptionId) { - return packageManagementCacheServiceProvider.getSubscription(subscriptionId); - } - - private InlineResponse201 getInlineResponse2002(final String id, final PkgmSubscriptionRequest subscription) { - return new InlineResponse201().id(id).filter(subscription.getFilter()) - .callbackUri(subscription.getCallbackUri()); - } - - private org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.model.PkgmSubscriptionRequest buildEtsiCatalogManagerPkgmSubscriptionRequest( - final PkgmSubscriptionRequest pkgmSubscriptionRequest) throws GeneralSecurityException { - - final org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.model.PkgmSubscriptionRequest etsiCatalogManagerSubscriptionRequest; - try { - etsiCatalogManagerSubscriptionRequest = conversionService.convert(pkgmSubscriptionRequest, - org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.model.PkgmSubscriptionRequest.class); - } catch (final org.springframework.core.convert.ConversionException conversionException) { - logger.error(conversionException.getMessage()); - throw new ConversionFailedException( - "Could not convert Sol003 PkgmSubscriptionRequest to ETSI-Catalog Manager PkgmSubscriptionRequest"); - } catch (final Exception exception) { - logger.error(exception.getMessage()); - throw new InternalServerErrorException( - "Could not convert Sol003 PkgmSubscriptionRequest to ETSI-Catalog Manager PkgmSubscriptionRequest"); - } - - if (etsiCatalogManagerSubscriptionRequest != null) { - etsiCatalogManagerSubscriptionRequest - .setCallbackUri(vnfmAdapterUrlProvider.getEtsiSubscriptionNotificationBaseUrl()); - - final ImmutablePair immutablePair = vnfmAdapterUrlProvider.getDecryptAuth(); - if (!immutablePair.equals(ImmutablePair.nullPair())) { - etsiCatalogManagerSubscriptionRequest.setAuthentication( - new org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.model.SubscriptionAuthentication() - .addAuthTypeItem(BASIC).paramsBasic(new BasicAuth().userName(immutablePair.getLeft()) - .password(immutablePair.getRight()))); - } - return etsiCatalogManagerSubscriptionRequest; - } - throw new ConversionFailedException( - "Failed to convert Sol003 PkgmSubscriptionRequest to ETSI-Catalog Manager PkgmSubscriptionRequest"); - } - -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/subscriptionmanagement/TlsNotificationServiceProvider.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/subscriptionmanagement/TlsNotificationServiceProvider.java deleted file mode 100644 index 3db2cca75a..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/subscriptionmanagement/TlsNotificationServiceProvider.java +++ /dev/null @@ -1,57 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2020 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ -package org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.subscriptionmanagement; - -import static org.slf4j.LoggerFactory.getLogger; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.model.SubscriptionsAuthentication; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.model.SubscriptionsAuthentication.AuthTypeEnum; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.rest.exceptions.AuthenticationTypeNotSupportedException; -import org.slf4j.Logger; -import org.springframework.stereotype.Service; - -/** - * - * @author Waqas Ikram (waqas.ikram@est.tech) - * @author Andrew Lamb (andrew.a.lamb@est.tech) - */ -@Service -public class TlsNotificationServiceProvider extends AbstractNotificationServiceProvider - implements NotificationServiceProvider { - - private static final Logger logger = getLogger(TlsNotificationServiceProvider.class); - - @Override - public boolean send(final Object notification, final SubscriptionsAuthentication subscriptionsAuthentication, - final String callbackUri) { - final String errorMessage = "An error occurred. Authentication type " - + subscriptionsAuthentication.getAuthType().toString() + " not currently supported."; - logger.error(errorMessage); - throw new AuthenticationTypeNotSupportedException(errorMessage); - } - - - @Override - public AuthTypeEnum getAuthType() { - return AuthTypeEnum.TLS_CERT; - } - - - -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/subscriptionmanagement/cache/AbstractCacheServiceProvider.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/subscriptionmanagement/cache/AbstractCacheServiceProvider.java deleted file mode 100644 index 6d92a9f688..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/subscriptionmanagement/cache/AbstractCacheServiceProvider.java +++ /dev/null @@ -1,47 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.subscriptionmanagement.cache; - -import org.springframework.cache.Cache; -import org.springframework.cache.CacheManager; - -/** - * @author Ronan Kenny (ronan.kenny@est.tech) - * @author Gareth Roper (gareth.roper@est.tech) - */ -public abstract class AbstractCacheServiceProvider { - - private final CacheManager cacheManager; - private final String cacheName; - - public AbstractCacheServiceProvider(final String cacheName, final CacheManager cacheManager) { - this.cacheName = cacheName; - this.cacheManager = cacheManager; - } - - public Cache getCache() { - final Cache cache = cacheManager.getCache(cacheName); - if (cache == null) { - throw new CacheNotFoundException("Unable to find " + cacheName + " cache"); - } - return cache; - } -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/subscriptionmanagement/cache/CacheManagerConfiguration.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/subscriptionmanagement/cache/CacheManagerConfiguration.java deleted file mode 100644 index 89b1164c1e..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/subscriptionmanagement/cache/CacheManagerConfiguration.java +++ /dev/null @@ -1,50 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2020 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.subscriptionmanagement.cache; - -import java.util.Arrays; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.PackageManagementConstants; -import org.springframework.cache.Cache; -import org.springframework.cache.CacheManager; -import org.springframework.cache.concurrent.ConcurrentMapCache; -import org.springframework.cache.support.SimpleCacheManager; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -/** - * @author Ronan Kenny (ronan.kenny@est.tech) - * @author Gareth Roper (gareth.roper@est.tech) - */ -@Configuration -public class CacheManagerConfiguration { - - @Bean - public CacheManager cacheManager() { - final SimpleCacheManager manager = new SimpleCacheManager(); - manager.setCaches(Arrays.asList(getCache(PackageManagementConstants.PACKAGE_MANAGEMENT_SUBSCRIPTION_CACHE))); - - return manager; - } - - private Cache getCache(final String name) { - return new ConcurrentMapCache(name); - } -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/subscriptionmanagement/cache/CacheNotFoundException.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/subscriptionmanagement/cache/CacheNotFoundException.java deleted file mode 100644 index 1c9448b50c..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/subscriptionmanagement/cache/CacheNotFoundException.java +++ /dev/null @@ -1,37 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2020 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.subscriptionmanagement.cache; - -/** - * Exception for failure to find the cache. - * - * @author Ronan Kenny (ronan.kenny@est.tech) - * @author Gareth Roper (gareth.roper@est.tech) - * - */ -public class CacheNotFoundException extends RuntimeException { - - private static final long serialVersionUID = -372361485260755367L; - - public CacheNotFoundException(final String message) { - super(message); - } -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/subscriptionmanagement/cache/PackageManagementCacheServiceProvider.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/subscriptionmanagement/cache/PackageManagementCacheServiceProvider.java deleted file mode 100644 index 531beec83a..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/subscriptionmanagement/cache/PackageManagementCacheServiceProvider.java +++ /dev/null @@ -1,74 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2020 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.subscriptionmanagement.cache; - -import java.util.Map; -import java.util.Optional; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.model.PkgmSubscriptionRequest; - -/** - * Interface which provides methods for communicating with the cache - * - * @author Ronan Kenny (ronan.kenny@est.tech) - * @author Gareth Roper (gareth.roper@est.tech) - * - */ -public interface PackageManagementCacheServiceProvider { - - /** - * Checks cache if subscription request Id is already present. If not, it adds the subscription to the cache. - * - * @param subscriptionId - * @param pkgmSubscriptionRequest - */ - void addSubscription(final String subscriptionId, final PkgmSubscriptionRequest pkgmSubscriptionRequest); - - /** - * Gets individual subscription from cache - * - * @param subscriptionId - * @return > - */ - Optional getSubscription(final String subscriptionId); - - /** - * Gets Map of subscriptions from cache - * - * @return Map> - */ - Map getSubscriptions(); - - /** - * Delete subscription from cache - * - * @param subscriptionId - * @return Boolean - */ - boolean deleteSubscription(final String subscriptionId); - - /** - * Checks if subscription exists in cache and return its subscriptionId - * - * @param pkgmSubscriptionRequest - * @return Subscription Id - */ - Optional getSubscriptionId(final PkgmSubscriptionRequest pkgmSubscriptionRequest); -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/subscriptionmanagement/cache/PackageManagementCacheServiceProviderImpl.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/subscriptionmanagement/cache/PackageManagementCacheServiceProviderImpl.java deleted file mode 100644 index 8280a4614b..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/subscriptionmanagement/cache/PackageManagementCacheServiceProviderImpl.java +++ /dev/null @@ -1,119 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2020 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.subscriptionmanagement.cache; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Optional; -import java.util.concurrent.ConcurrentHashMap; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.PackageManagementConstants; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.model.PkgmSubscriptionRequest; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.cache.Cache; -import org.springframework.cache.CacheManager; -import org.springframework.stereotype.Service; - -/** - * Implementation which provides methods for communicating with the cache - * - * @author Ronan Kenny (ronan.kenny@est.tech) - * @author Gareth Roper (gareth.roper@est.tech) - */ -@Service -public class PackageManagementCacheServiceProviderImpl extends AbstractCacheServiceProvider - implements PackageManagementCacheServiceProvider { - - private static final Logger LOGGER = LoggerFactory.getLogger(PackageManagementCacheServiceProviderImpl.class); - - @Autowired - public PackageManagementCacheServiceProviderImpl(final CacheManager cacheManager) { - super(PackageManagementConstants.PACKAGE_MANAGEMENT_SUBSCRIPTION_CACHE, cacheManager); - } - - @Override - public void addSubscription(final String subscriptionId, final PkgmSubscriptionRequest pkgmSubscriptionRequest) { - LOGGER.debug("Adding {} to cache with subscription id: {}", pkgmSubscriptionRequest, subscriptionId); - getCache().put(subscriptionId, pkgmSubscriptionRequest); - } - - @Override - public Optional getSubscription(final String subscriptionId) { - LOGGER.debug("Getting subscription from cache using Id: {}", subscriptionId); - final Cache cache = getCache(); - final PkgmSubscriptionRequest cacheValue = cache.get(subscriptionId, PkgmSubscriptionRequest.class); - if (cacheValue != null) { - return Optional.of(cacheValue); - } - LOGGER.error("Unable to find Subscription in cache using Id: {}", subscriptionId); - return Optional.empty(); - } - - @Override - public Map getSubscriptions() { - LOGGER.info("Getting all subscriptions from cache"); - final Cache cache = getCache(); - - final Object nativeCache = cache.getNativeCache(); - if (nativeCache instanceof ConcurrentHashMap) { - @SuppressWarnings("unchecked") - final ConcurrentHashMap concurrentHashMap = (ConcurrentHashMap) nativeCache; - final Map result = new HashMap<>(); - concurrentHashMap.keySet().forEach(key -> { - final Optional optional = getSubscription(key.toString()); - optional.ifPresent(pkgmSubscriptionRequest -> result.put(key.toString(), pkgmSubscriptionRequest)); - }); - return result; - } - LOGGER.error("Unable to find Subscriptions in cache"); - return Collections.emptyMap(); - } - - @Override - public boolean deleteSubscription(final String subscriptionId) { - final Cache cache = getCache(); - final Optional optional = getSubscription(subscriptionId); - if (optional.isPresent()) { - cache.evict(subscriptionId); - return true; - } - return false; - } - - @Override - public Optional getSubscriptionId(final PkgmSubscriptionRequest pkgmSubscriptionRequest) { - final Cache cache = getCache(); - final Object nativeCache = cache.getNativeCache(); - if (nativeCache instanceof ConcurrentHashMap) { - @SuppressWarnings("unchecked") - final ConcurrentHashMap concurrentHashMap = (ConcurrentHashMap) nativeCache; - final Optional> optional = concurrentHashMap.entrySet().stream() - .filter(entry -> entry.getValue().equals(pkgmSubscriptionRequest)).findAny(); - if (optional.isPresent()) { - return Optional.of(optional.get().getKey().toString()); - } - } - return Optional.empty(); - } -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/ConversionServiceConfiguration.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/ConversionServiceConfiguration.java new file mode 100644 index 0000000000..fd19d0e0a1 --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/ConversionServiceConfiguration.java @@ -0,0 +1,55 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.so.adapters.etsisol003adapter.pkgm; + +import org.onap.so.adapters.etsi.sol003.adapter.common.VnfmAdapterUrlProvider; +import org.onap.so.adapters.etsisol003adapter.pkgm.converters.etsicatalog.sol003.PkgChangeNotificationConverter; +import org.onap.so.adapters.etsisol003adapter.pkgm.converters.etsicatalog.sol003.PkgOnboardingNotificationConverter; +import org.onap.so.adapters.etsisol003adapter.pkgm.converters.etsicatalog.sol003.VnfPkgInfoConverter; +import org.onap.so.adapters.etsisol003adapter.pkgm.converters.sol003.etsicatalog.PkgmSubscriptionRequestConverter; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.core.convert.ConversionService; +import org.springframework.core.convert.support.DefaultConversionService; + +/** + * @author Waqas Ikram (waqas.ikram@est.tech) + * + */ +public class ConversionServiceConfiguration { + + private final VnfmAdapterUrlProvider vnfmAdapterUrlProvider; + + @Autowired + public ConversionServiceConfiguration(final VnfmAdapterUrlProvider vnfmAdapterUrlProvider) { + this.vnfmAdapterUrlProvider = vnfmAdapterUrlProvider; + } + + @Bean + public ConversionService conversionService() { + final DefaultConversionService service = new DefaultConversionService(); + service.addConverter(new VnfPkgInfoConverter(vnfmAdapterUrlProvider)); + service.addConverter(new PkgmSubscriptionRequestConverter()); + service.addConverter(new PkgChangeNotificationConverter(vnfmAdapterUrlProvider)); + service.addConverter(new PkgOnboardingNotificationConverter(vnfmAdapterUrlProvider)); + return service; + } + +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/PackageManagementConstants.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/PackageManagementConstants.java new file mode 100644 index 0000000000..5922aab9ca --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/PackageManagementConstants.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.pkgm; + +/** + * ETSI SOL003 VNF Package Management Adapter constants + * + * @author Ronan Kenny (ronan.kenny@est.tech) + * @author Gareth Roper (gareth.roper@est.tech) + */ +public class PackageManagementConstants { + + public static final String APPLICATION_ZIP = "application/zip"; + + /** + * Name of the subscription cache + */ + public static final String PACKAGE_MANAGEMENT_SUBSCRIPTION_CACHE = "PackageManagementSubscriptionCache"; + + private PackageManagementConstants() {} +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/converters/etsicatalog/sol003/AbstractPkgNotificationConverter.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/converters/etsicatalog/sol003/AbstractPkgNotificationConverter.java new file mode 100644 index 0000000000..5f2ee1d5ab --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/converters/etsicatalog/sol003/AbstractPkgNotificationConverter.java @@ -0,0 +1,63 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.pkgm.converters.etsicatalog.sol003; + +import org.onap.so.adapters.etsi.sol003.adapter.common.VnfmAdapterUrlProvider; +import org.onap.so.adapters.etsisol003adapter.etsicatalog.notification.model.PkgmLinks; +import org.onap.so.adapters.etsisol003adapter.pkgm.extclients.vnfm.notification.model.URIisprovidedbytheclientwhencreatingthesubscriptionVnfPackageOnboardingNotificationLinks; +import org.onap.so.adapters.etsisol003adapter.pkgm.extclients.vnfm.notification.model.URIisprovidedbytheclientwhencreatingthesubscriptionVnfPackageOnboardingNotificationLinksVnfPackage; + +/** + * A base class that can be extended by classes for converting Etsi Catalog Manager Pkg Notification classes. Provides + * common methods that will be useful to those classes. + * + * @author andrew.a.lamb@est.tech + */ +abstract public class AbstractPkgNotificationConverter { + + private final VnfmAdapterUrlProvider vnfmAdapterUrlProvider; + + public AbstractPkgNotificationConverter(final VnfmAdapterUrlProvider vnfmAdapterUrlProvider) { + this.vnfmAdapterUrlProvider = vnfmAdapterUrlProvider; + } + + protected URIisprovidedbytheclientwhencreatingthesubscriptionVnfPackageOnboardingNotificationLinks convert( + final PkgmLinks pkgmLinks, final String vnfPkgId, final String subscriptionId) { + final URIisprovidedbytheclientwhencreatingthesubscriptionVnfPackageOnboardingNotificationLinksVnfPackage linksVnfPackage = + new URIisprovidedbytheclientwhencreatingthesubscriptionVnfPackageOnboardingNotificationLinksVnfPackage(); + if (pkgmLinks.getVnfPackage() != null) { + linksVnfPackage.setHref(vnfmAdapterUrlProvider.getVnfPackageUrl(vnfPkgId)); + } + + final URIisprovidedbytheclientwhencreatingthesubscriptionVnfPackageOnboardingNotificationLinksVnfPackage linksSubscription = + new URIisprovidedbytheclientwhencreatingthesubscriptionVnfPackageOnboardingNotificationLinksVnfPackage(); + if (pkgmLinks.getSubscription() != null) { + linksSubscription.setHref(vnfmAdapterUrlProvider.getSubscriptionUriString(subscriptionId)); + } + + final URIisprovidedbytheclientwhencreatingthesubscriptionVnfPackageOnboardingNotificationLinks links = + new URIisprovidedbytheclientwhencreatingthesubscriptionVnfPackageOnboardingNotificationLinks(); + links.setVnfPackage(linksVnfPackage); + links.setSubscription(linksSubscription); + return links; + } + +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/converters/etsicatalog/sol003/PkgChangeNotificationConverter.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/converters/etsicatalog/sol003/PkgChangeNotificationConverter.java new file mode 100644 index 0000000000..5787d35b9a --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/converters/etsicatalog/sol003/PkgChangeNotificationConverter.java @@ -0,0 +1,85 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.pkgm.converters.etsicatalog.sol003; + +import static org.slf4j.LoggerFactory.getLogger; +import org.onap.so.adapters.etsi.sol003.adapter.common.VnfmAdapterUrlProvider; +import org.onap.so.adapters.etsisol003adapter.etsicatalog.notification.model.PkgChangeNotification; +import org.onap.so.adapters.etsisol003adapter.pkgm.extclients.vnfm.notification.model.VnfPackageChangeNotification; +import org.slf4j.Logger; +import org.springframework.core.convert.converter.Converter; +import org.springframework.stereotype.Service; + +/** + * Converter to convert from an Etsi Catalog Manager {@link PkgChangeNotification} Object to its equivalent SOL003 + * {@link VnfPackageChangeNotification} Object + * + * @author andrew.a.lamb@est.tech + */ +@Service +public class PkgChangeNotificationConverter extends AbstractPkgNotificationConverter + implements Converter { + private static final Logger logger = getLogger(PkgChangeNotificationConverter.class); + + public PkgChangeNotificationConverter(final VnfmAdapterUrlProvider vnfmAdapterUrlProvider) { + super(vnfmAdapterUrlProvider); + } + + /** + * Convert a {@link PkgChangeNotification} Object to an {@link VnfPackageChangeNotification} Object + * + * @param pkgChangeNotification The PkgChangeNotification Object to Convert + * @return The Converted VnfPackageChangeNotification Object + */ + @Override + public VnfPackageChangeNotification convert(final PkgChangeNotification pkgChangeNotification) { + logger.info("Converting PkgChangeNotification\n{}", pkgChangeNotification.toString()); + final VnfPackageChangeNotification vnfPackageChangeNotification = new VnfPackageChangeNotification(); + vnfPackageChangeNotification.setId(pkgChangeNotification.getId()); + + if (pkgChangeNotification.getNotificationType() != null) { + vnfPackageChangeNotification.setNotificationType(VnfPackageChangeNotification.NotificationTypeEnum + .fromValue(pkgChangeNotification.getNotificationType().getValue())); + } + + vnfPackageChangeNotification.setSubscriptionId(pkgChangeNotification.getSubscriptionId()); + vnfPackageChangeNotification.setTimeStamp(pkgChangeNotification.getTimeStamp()); + vnfPackageChangeNotification.setVnfPkgId(pkgChangeNotification.getVnfPkgId()); + + vnfPackageChangeNotification.setVnfdId(pkgChangeNotification.getVnfdId()); + + if (pkgChangeNotification.getChangeType() != null) { + vnfPackageChangeNotification.setChangeType(VnfPackageChangeNotification.ChangeTypeEnum + .fromValue(pkgChangeNotification.getChangeType().getValue())); + } + + if (pkgChangeNotification.getOperationalState() != null) { + vnfPackageChangeNotification.setOperationalState(VnfPackageChangeNotification.OperationalStateEnum + .fromValue(pkgChangeNotification.getOperationalState().getValue())); + } + + vnfPackageChangeNotification.setLinks(convert(pkgChangeNotification.getLinks(), + pkgChangeNotification.getVnfPkgId(), pkgChangeNotification.getSubscriptionId())); + + return vnfPackageChangeNotification; + } + +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/converters/etsicatalog/sol003/PkgOnboardingNotificationConverter.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/converters/etsicatalog/sol003/PkgOnboardingNotificationConverter.java new file mode 100644 index 0000000000..96a5d827e6 --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/converters/etsicatalog/sol003/PkgOnboardingNotificationConverter.java @@ -0,0 +1,76 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.pkgm.converters.etsicatalog.sol003; + +import static org.slf4j.LoggerFactory.getLogger; +import org.onap.so.adapters.etsi.sol003.adapter.common.VnfmAdapterUrlProvider; +import org.onap.so.adapters.etsisol003adapter.etsicatalog.notification.model.PkgOnboardingNotification; +import org.onap.so.adapters.etsisol003adapter.pkgm.extclients.vnfm.notification.model.VnfPackageOnboardingNotification; +import org.slf4j.Logger; +import org.springframework.core.convert.converter.Converter; +import org.springframework.stereotype.Service; + +/** + * Converter to convert from an Etsi Catalog Manager {@link PkgOnboardingNotification} Object to its equivalent SOL003 + * {@link VnfPackageOnboardingNotification} Object + * + * @author andrew.a.lamb@est.tech + */ +@Service +public class PkgOnboardingNotificationConverter extends AbstractPkgNotificationConverter + implements Converter { + private static final Logger logger = getLogger(PkgOnboardingNotificationConverter.class); + + public PkgOnboardingNotificationConverter(final VnfmAdapterUrlProvider vnfmAdapterUrlProvider) { + super(vnfmAdapterUrlProvider); + } + + + /** + * Convert a {@link PkgOnboardingNotification} Object to an {@link VnfPackageOnboardingNotification} Object + * + * @param pkgOnboardingNotification The PkgOnboardingNotification Object to Convert + * @return The Converted VnfPackageOnboardingNotification Object + */ + @Override + public VnfPackageOnboardingNotification convert(final PkgOnboardingNotification pkgOnboardingNotification) { + logger.info("Converting PkgChangeNotification\n{}", pkgOnboardingNotification.toString()); + final VnfPackageOnboardingNotification vnfPackageOnboardingNotification = + new VnfPackageOnboardingNotification(); + vnfPackageOnboardingNotification.setId(pkgOnboardingNotification.getId()); + + if (pkgOnboardingNotification.getNotificationType() != null) { + vnfPackageOnboardingNotification.setNotificationType(VnfPackageOnboardingNotification.NotificationTypeEnum + .fromValue(pkgOnboardingNotification.getNotificationType().getValue())); + } + + vnfPackageOnboardingNotification.setSubscriptionId(pkgOnboardingNotification.getSubscriptionId()); + vnfPackageOnboardingNotification.setTimeStamp(pkgOnboardingNotification.getTimeStamp()); + vnfPackageOnboardingNotification.setVnfPkgId(pkgOnboardingNotification.getVnfPkgId()); + vnfPackageOnboardingNotification.setVnfdId(pkgOnboardingNotification.getVnfdId()); + + vnfPackageOnboardingNotification.setLinks(convert(pkgOnboardingNotification.getLinks(), + pkgOnboardingNotification.getVnfPkgId(), pkgOnboardingNotification.getSubscriptionId())); + + return vnfPackageOnboardingNotification; + } + +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/converters/etsicatalog/sol003/VnfPkgInfoConverter.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/converters/etsicatalog/sol003/VnfPkgInfoConverter.java new file mode 100644 index 0000000000..0121cc5885 --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/converters/etsicatalog/sol003/VnfPkgInfoConverter.java @@ -0,0 +1,198 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.pkgm.converters.etsicatalog.sol003; + +import java.util.ArrayList; +import java.util.List; +import org.onap.so.adapters.etsi.sol003.adapter.common.VnfmAdapterUrlProvider; +import org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.model.Checksum; +import org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.model.VNFPKGMLinkSerializer; +import org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.model.VnfPackageArtifactInfo; +import org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.model.VnfPackageSoftwareImageInfo; +import org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.model.VnfPkgInfo; +import org.onap.so.adapters.etsisol003adapter.pkgm.model.InlineResponse2001; +import org.onap.so.adapters.etsisol003adapter.pkgm.model.VnfPackagesAdditionalArtifacts; +import org.onap.so.adapters.etsisol003adapter.pkgm.model.VnfPackagesChecksum; +import org.onap.so.adapters.etsisol003adapter.pkgm.model.VnfPackagesLinks; +import org.onap.so.adapters.etsisol003adapter.pkgm.model.VnfPackagesLinksSelf; +import org.onap.so.adapters.etsisol003adapter.pkgm.model.VnfPackagesSoftwareImages; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.core.convert.converter.Converter; +import org.springframework.stereotype.Service; + +/** + * Converter to convert from an Etsi Catalog Manager {@link VnfPkgInfo} Object to its equivalent SOL003 Object + * {@link InlineResponse2001} Object + * + * @author andrew.a.lamb@est.tech + */ +@Service +public class VnfPkgInfoConverter implements Converter { + private static final Logger logger = LoggerFactory.getLogger(VnfPkgInfoConverter.class); + private final VnfmAdapterUrlProvider vnfmAdapterUrlProvider; + + public VnfPkgInfoConverter(final VnfmAdapterUrlProvider vnfmAdapterUrlProvider) { + this.vnfmAdapterUrlProvider = vnfmAdapterUrlProvider; + } + + /** + * Convert a {@link VnfPkgInfo} Object to an {@link InlineResponse2001} Object + * + * @param vnfPkgInfo The VnfPkgInfo Object to Convert + * @return The Converted InlineResponse2001 Object + */ + @Override + public InlineResponse2001 convert(final VnfPkgInfo vnfPkgInfo) { + if (vnfPkgInfo == null) { + logger.error("No VnfPkgInfo Object Provided for Conversion. (Null object received, returning Null)"); + return null; + } + final InlineResponse2001 response = new InlineResponse2001(); + response.setId(vnfPkgInfo.getId()); + response.setVnfdId(vnfPkgInfo.getVnfdId()); + response.setVnfProvider(vnfPkgInfo.getVnfProvider()); + response.setVnfProductName(vnfPkgInfo.getVnfProductName()); + response.setVnfSoftwareVersion(vnfPkgInfo.getVnfSoftwareVersion()); + response.setVnfdVersion(vnfPkgInfo.getVnfdVersion()); + response.setChecksum(convertChecksumToVnfPackagesChecksum(vnfPkgInfo.getChecksum())); + response.setSoftwareImages( + convertVnfPackageSoftwareImageInfoListToVnfPackagesSoftwareImagesList(vnfPkgInfo.getSoftwareImages())); + response.setAdditionalArtifacts(convertVnfPackageArtifactInfoListToVnfPackagesAdditionalArtifactsList( + vnfPkgInfo.getAdditionalArtifacts())); + + if (vnfPkgInfo.getOnboardingState() != null) { + response.setOnboardingState( + InlineResponse2001.OnboardingStateEnum.fromValue(vnfPkgInfo.getOnboardingState().getValue())); + } + + if (vnfPkgInfo.getOperationalState() != null) { + response.setOperationalState( + InlineResponse2001.OperationalStateEnum.fromValue(vnfPkgInfo.getOperationalState().getValue())); + } + + response.setUserDefinedData((vnfPkgInfo.getUserDefinedData())); + + if (vnfPkgInfo.getLinks() != null) { + response.setLinks(getVnfPackagesLinks(vnfPkgInfo.getLinks(), vnfPkgInfo.getId())); + } + + return response; + } + + private VnfPackagesChecksum convertChecksumToVnfPackagesChecksum(final Checksum checksum) { + final VnfPackagesChecksum vnfPackagesChecksum = new VnfPackagesChecksum(); + if (checksum != null) { + vnfPackagesChecksum.setAlgorithm(checksum.getAlgorithm()); + vnfPackagesChecksum.setHash(checksum.getHash()); + } + return vnfPackagesChecksum; + } + + private List convertVnfPackageSoftwareImageInfoListToVnfPackagesSoftwareImagesList( + final List vnfPackageSoftwareImageInfoList) { + final List vnfPackagesSoftwareImages = new ArrayList<>(); + if (vnfPackageSoftwareImageInfoList != null) { + for (final VnfPackageSoftwareImageInfo vnfPackageSoftwareImageInfo : vnfPackageSoftwareImageInfoList) { + final VnfPackagesSoftwareImages softwareImage = + convertVnfPackageSoftwareImageInfoToVnfPackagesSoftwareImages(vnfPackageSoftwareImageInfo); + vnfPackagesSoftwareImages.add(softwareImage); + } + } + return vnfPackagesSoftwareImages; + } + + private VnfPackagesSoftwareImages convertVnfPackageSoftwareImageInfoToVnfPackagesSoftwareImages( + final VnfPackageSoftwareImageInfo vnfPackageSoftwareImageInfo) { + final VnfPackagesSoftwareImages vnfPackagesSoftwareImages = new VnfPackagesSoftwareImages(); + vnfPackagesSoftwareImages.setId(vnfPackageSoftwareImageInfo.getId()); + vnfPackagesSoftwareImages.setName(vnfPackageSoftwareImageInfo.getName()); + vnfPackagesSoftwareImages.setProvider(vnfPackageSoftwareImageInfo.getProvider()); + vnfPackagesSoftwareImages.setVersion(vnfPackageSoftwareImageInfo.getVersion()); + vnfPackagesSoftwareImages + .setChecksum(convertChecksumToVnfPackagesChecksum(vnfPackageSoftwareImageInfo.getChecksum())); + if (vnfPackageSoftwareImageInfo.getContainerFormat() != null) { + vnfPackagesSoftwareImages.setContainerFormat(VnfPackagesSoftwareImages.ContainerFormatEnum + .fromValue(vnfPackageSoftwareImageInfo.getContainerFormat().getValue())); + } + + if (vnfPackageSoftwareImageInfo.getDiskFormat() != null) { + vnfPackagesSoftwareImages.setDiskFormat(VnfPackagesSoftwareImages.DiskFormatEnum + .fromValue(vnfPackageSoftwareImageInfo.getDiskFormat().getValue())); + } + + vnfPackagesSoftwareImages.setCreatedAt(vnfPackageSoftwareImageInfo.getCreatedAt()); + vnfPackagesSoftwareImages.setMinDisk(vnfPackageSoftwareImageInfo.getMinDisk()); + vnfPackagesSoftwareImages.setMinRam(vnfPackageSoftwareImageInfo.getMinRam()); + vnfPackagesSoftwareImages.setSize(vnfPackageSoftwareImageInfo.getSize()); + vnfPackagesSoftwareImages.setUserMetadata(vnfPackageSoftwareImageInfo.getUserMetadata()); + vnfPackagesSoftwareImages.setImagePath(vnfPackageSoftwareImageInfo.getImagePath()); + return vnfPackagesSoftwareImages; + } + + private List convertVnfPackageArtifactInfoListToVnfPackagesAdditionalArtifactsList( + final List vnfPackageArtifactInfoList) { + if (vnfPackageArtifactInfoList != null) { + final List additionalArtifacts = new ArrayList<>(); + for (final VnfPackageArtifactInfo artifactInfo : vnfPackageArtifactInfoList) { + final VnfPackagesAdditionalArtifacts artifact = + convertVnfPackageArtifactInfoToVnfPackagesAdditionalArtifacts(artifactInfo); + additionalArtifacts.add(artifact); + } + return additionalArtifacts; + } + return null; + } + + private VnfPackagesAdditionalArtifacts convertVnfPackageArtifactInfoToVnfPackagesAdditionalArtifacts( + final VnfPackageArtifactInfo vnfPackageArtifactInfo) { + final VnfPackagesAdditionalArtifacts vnfPackagesAdditionalArtifacts = new VnfPackagesAdditionalArtifacts(); + vnfPackagesAdditionalArtifacts.setArtifactPath(vnfPackageArtifactInfo.getArtifactPath()); + vnfPackagesAdditionalArtifacts + .setChecksum(convertChecksumToVnfPackagesChecksum(vnfPackageArtifactInfo.getChecksum())); + vnfPackagesAdditionalArtifacts.setMetadata(vnfPackageArtifactInfo.getMetadata()); + return vnfPackagesAdditionalArtifacts; + } + + private VnfPackagesLinks getVnfPackagesLinks(final VNFPKGMLinkSerializer links, final String vnfPkgId) { + final VnfPackagesLinks vnfPackagesLinks = new VnfPackagesLinks(); + + if (links.getSelf() != null) { + vnfPackagesLinks.setSelf(getVnfPackagesLinksSelf(vnfmAdapterUrlProvider.getVnfPackageUrl(vnfPkgId))); + } + + if (links.getVnfd() != null) { + vnfPackagesLinks.setVnfd(getVnfPackagesLinksSelf(vnfmAdapterUrlProvider.getVnfPackageVnfdUrl(vnfPkgId))); + } + + if (links.getPackageContent() != null) { + vnfPackagesLinks.setPackageContent( + getVnfPackagesLinksSelf(vnfmAdapterUrlProvider.getVnfPackageContentUrl(vnfPkgId))); + } + + return vnfPackagesLinks; + } + + private VnfPackagesLinksSelf getVnfPackagesLinksSelf(final String href) { + return new VnfPackagesLinksSelf().href(href); + } + +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/converters/sol003/etsicatalog/PkgmSubscriptionRequestConverter.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/converters/sol003/etsicatalog/PkgmSubscriptionRequestConverter.java new file mode 100644 index 0000000000..f63ada9c75 --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/converters/sol003/etsicatalog/PkgmSubscriptionRequestConverter.java @@ -0,0 +1,198 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.pkgm.converters.sol003.etsicatalog; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.model.Version; +import org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.model.VnfProducts; +import org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.model.VnfProductsProviders; +import org.onap.so.adapters.etsisol003adapter.pkgm.model.PkgmSubscriptionRequest; +import org.onap.so.adapters.etsisol003adapter.pkgm.model.SubscriptionsFilter1; +import org.onap.so.adapters.etsisol003adapter.pkgm.model.SubscriptionsFilter1.NotificationTypesEnum; +import org.onap.so.adapters.etsisol003adapter.pkgm.model.SubscriptionsFilter1.OperationalStateEnum; +import org.onap.so.adapters.etsisol003adapter.pkgm.model.SubscriptionsFilter1.UsageStateEnum; +import org.onap.so.adapters.etsisol003adapter.pkgm.model.SubscriptionsFilterVersions; +import org.onap.so.adapters.etsisol003adapter.pkgm.model.SubscriptionsFilterVnfProducts; +import org.onap.so.adapters.etsisol003adapter.pkgm.model.SubscriptionsFilterVnfProductsFromProviders; +import org.springframework.core.convert.converter.Converter; +import org.springframework.stereotype.Service; + +/** + * Converter to convert from an Etsi Catalog Manager {@link PkgmSubscriptionRequest} Object to its equivalent ETSI + * Catalog Manager Object + * + * @author Ronan Kenny (ronan.kenny@est.tech) + * @author Gareth Roper (gareth.roper@est.tech) + */ +@Service +public class PkgmSubscriptionRequestConverter implements + Converter { + + @Override + public org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.model.PkgmSubscriptionRequest convert( + final PkgmSubscriptionRequest pkgmSubscriptionRequest) { + final org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.model.PkgmSubscriptionRequest etsiCatalogManagerSubscriptionRequest = + new org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.model.PkgmSubscriptionRequest(); + + etsiCatalogManagerSubscriptionRequest + .setFilter(getPkgmNotificationsFilter(pkgmSubscriptionRequest.getFilter())); + + return etsiCatalogManagerSubscriptionRequest; + } + + + private org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.model.PkgmNotificationsFilter getPkgmNotificationsFilter( + final SubscriptionsFilter1 sol003SubscriptionsFilter) { + final org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.model.PkgmNotificationsFilter etsiCatalogManagerFilters = + new org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.model.PkgmNotificationsFilter(); + + if (sol003SubscriptionsFilter.getNotificationTypes() != null) { + etsiCatalogManagerFilters.setNotificationTypes( + getPkgmNotificationsFilterNotificationTypes(sol003SubscriptionsFilter.getNotificationTypes())); + } + + etsiCatalogManagerFilters.setVnfProductsFromProviders( + getVnfProductsProviders(sol003SubscriptionsFilter.getVnfProductsFromProviders())); + + etsiCatalogManagerFilters.setVnfdId(getVnfdIds(sol003SubscriptionsFilter.getVnfdId())); + + etsiCatalogManagerFilters.setVnfPkgId(getVnfPkgIds(sol003SubscriptionsFilter.getVnfPkgId())); + + etsiCatalogManagerFilters + .setOperationalState(getOperationalState(sol003SubscriptionsFilter.getOperationalState())); + + etsiCatalogManagerFilters.setUsageState(getUsageState(sol003SubscriptionsFilter.getUsageState())); + + return etsiCatalogManagerFilters; + } + + + private List getUsageState( + final List usageStates) { + if (usageStates != null) { + final List etsiCatalogUsageStates = + new ArrayList<>(); + usageStates.stream().forEach(state -> { + etsiCatalogUsageStates.add( + org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.model.PkgmNotificationsFilter.UsageStateEnum + .fromValue(state.getValue())); + }); + return etsiCatalogUsageStates; + } + return Collections.emptyList(); + } + + + private List getOperationalState( + final List operationalStates) { + if (operationalStates != null) { + final List etsiCatalogOperationalStates = + new ArrayList<>(); + operationalStates.forEach(state -> { + etsiCatalogOperationalStates.add( + org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.model.PkgmNotificationsFilter.OperationalStateEnum + .fromValue(state.getValue())); + }); + + return etsiCatalogOperationalStates; + } + return Collections.emptyList(); + } + + private List getVnfPkgIds(final List vnfPkgId) { + if (vnfPkgId != null) { + final List etsiCatalogManagerVnfPkgId = new ArrayList<>(); + vnfPkgId.forEach(type -> { + etsiCatalogManagerVnfPkgId.add(type); + }); + return etsiCatalogManagerVnfPkgId; + } + return Collections.emptyList(); + } + + private List getVnfdIds(final List vnfdId) { + if (vnfdId != null) { + final List etsiCatalogManagerVnfdId = new ArrayList<>(); + vnfdId.forEach(type -> { + etsiCatalogManagerVnfdId.add(type); + }); + return etsiCatalogManagerVnfdId; + } + return Collections.emptyList(); + } + + private List getVnfProductsProviders( + final List filterProductsFromProvider) { + + if (filterProductsFromProvider != null && !filterProductsFromProvider.isEmpty()) { + final List etsiCatalogManagerVnfProductsProviders = new ArrayList<>(); + filterProductsFromProvider.forEach(vnfProduct -> { + etsiCatalogManagerVnfProductsProviders + .add(new VnfProductsProviders().vnfProvider(vnfProduct.getVnfProvider()) + .vnfProducts(getVnfProducts(vnfProduct.getVnfProducts()))); + }); + return etsiCatalogManagerVnfProductsProviders; + } + return Collections.emptyList(); + } + + private List getVnfProducts(final List sol003VnfProducts) { + if (sol003VnfProducts != null) { + final List etsiCatalogManagerVnfProductsList = new ArrayList<>(); + sol003VnfProducts.forEach(vnfProduct -> { + etsiCatalogManagerVnfProductsList.add(new VnfProducts().vnfProductName(vnfProduct.getVnfProductName()) + .versions(getVersion(vnfProduct.getVersions()))); + }); + return etsiCatalogManagerVnfProductsList; + } + return Collections.emptyList(); + } + + private List getVersion(final List sol003FilterVersions) { + if (sol003FilterVersions != null && !sol003FilterVersions.isEmpty()) { + final List etsiCatalogVersionList = new ArrayList<>(); + sol003FilterVersions.forEach(vnfFilterVersion -> { + etsiCatalogVersionList.add(new Version().vnfSoftwareVersion(vnfFilterVersion.getVnfSoftwareVersion()) + .vnfdVersions(vnfFilterVersion.getVnfdVersions())); + }); + return etsiCatalogVersionList; + } + return Collections.emptyList(); + } + + private List getPkgmNotificationsFilterNotificationTypes( + final List notificationTypes) { + + if (notificationTypes != null && !notificationTypes.isEmpty()) { + final List etsiCatalogNotificationTypes = + new ArrayList<>(); + notificationTypes.forEach(type -> etsiCatalogNotificationTypes.add( + org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.model.PkgmNotificationsFilter.NotificationTypesEnum + .fromValue(type.getValue()))); + return etsiCatalogNotificationTypes; + } + return Collections.emptyList(); + } + + +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/extclients/AbstractServiceProviderConfiguration.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/extclients/AbstractServiceProviderConfiguration.java new file mode 100644 index 0000000000..f9da6981c8 --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/extclients/AbstractServiceProviderConfiguration.java @@ -0,0 +1,56 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.pkgm.extclients; + +import java.time.LocalDateTime; +import java.util.Iterator; +import org.onap.so.adapters.etsisol003adapter.pkgm.JSON; +import org.onap.so.adapters.etsisol003adapter.pkgm.rest.EtsiSubscriptionNotificationController; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.http.converter.json.GsonHttpMessageConverter; +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; +import org.springframework.web.client.RestTemplate; +import org.threeten.bp.OffsetDateTime; +import com.google.gson.Gson; + +/** + * A base class that can be extended by classes for configuring HttpRestServiceProvider classes. Provides common methods + * that will be useful to some such classes. + * + * @author gareth.roper@est.tech + */ +public abstract class AbstractServiceProviderConfiguration { + private final JSON.OffsetDateTimeTypeAdapter offsetDateTimeTypeAdapter = new JSON.OffsetDateTimeTypeAdapter(); + + public void setGsonMessageConverter(final RestTemplate restTemplate) { + final Iterator> iterator = restTemplate.getMessageConverters().iterator(); + while (iterator.hasNext()) { + if (iterator.next() instanceof MappingJackson2HttpMessageConverter) { + iterator.remove(); + } + } + final Gson gson = JSON.createGson().registerTypeAdapter(OffsetDateTime.class, offsetDateTimeTypeAdapter) + .registerTypeAdapter(LocalDateTime.class, + new EtsiSubscriptionNotificationController.LocalDateTimeTypeAdapter()) + .create(); + restTemplate.getMessageConverters().add(new GsonHttpMessageConverter(gson)); + } +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/extclients/etsicatalog/EtsiCatalogPackageManagementServiceProvider.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/extclients/etsicatalog/EtsiCatalogPackageManagementServiceProvider.java new file mode 100644 index 0000000000..db3c24bd1c --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/extclients/etsicatalog/EtsiCatalogPackageManagementServiceProvider.java @@ -0,0 +1,72 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog; + +import java.util.Optional; +import org.onap.so.adapters.etsisol003adapter.pkgm.model.InlineResponse2001; + +/** + * @author Waqas Ikram (waqas.ikram@est.tech) + * + */ +public interface EtsiCatalogPackageManagementServiceProvider { + + /** + * GET Package Content, from VNF Package. + * + * @param vnfPkgId The ID of the VNF Package from which the "package_content" will be retrieved. + * @return The Package Content of a VNF Package ("vnfPkgId"). + */ + Optional getVnfPackageContent(final String vnfPkgId); + + /** + * GET VNF packages information from ETSI Catalog. Will return zero or more VNF package representations. + * + * @return An Array of all VNF packages retrieved from the ETSI Catalog. + */ + Optional getVnfPackages(); + + /** + * GET specific VNF package information from ETSI Catalog. + * + * @param vnfPkgId The ID of the VNF Package that you want to query. + * @return The VNF package retrieved from the ETSI Catalog + */ + Optional getVnfPackage(final String vnfPkgId); + + /** + * GET specific VNF package VNFD from ETSI Catalog. + * + * @param vnfPkgId The ID of the VNF Package that you want to query. + * @return The VNF package retrieved from the ETSI Catalog + */ + Optional getVnfPackageVnfd(final String vnfPkgId); + + /** + * GET Package Artifact, from VNF Package. + * + * @param vnfPkgId The ID of the VNF Package from which the artifact will be retrieved. + * @param artifactPath Sequence of one or more path segments representing the path of the artifact within the VNF + * Package, e.g., foo/bar/run.sh + * @return The Package Artifact of a VNF Package ("vnfPkgId", "artifactPath"). + */ + Optional getVnfPackageArtifact(final String vnfPkgId, final String artifactPath); + +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/extclients/etsicatalog/EtsiCatalogServiceProvider.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/extclients/etsicatalog/EtsiCatalogServiceProvider.java new file mode 100644 index 0000000000..f11fc5c39a --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/extclients/etsicatalog/EtsiCatalogServiceProvider.java @@ -0,0 +1,32 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog; + +/** + * Provides methods for invoking REST calls to the ETSI Catalog Manager. + * + * @author gareth.roper@est.tech + */ +public interface EtsiCatalogServiceProvider + extends EtsiCatalogSubscriptionServiceProvider, EtsiCatalogPackageManagementServiceProvider { + + +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/extclients/etsicatalog/EtsiCatalogServiceProviderConfiguration.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/extclients/etsicatalog/EtsiCatalogServiceProviderConfiguration.java new file mode 100644 index 0000000000..5caeebe53d --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/extclients/etsicatalog/EtsiCatalogServiceProviderConfiguration.java @@ -0,0 +1,187 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog; + +import java.io.IOException; +import java.security.KeyManagementException; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.cert.CertificateException; +import java.util.Iterator; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSession; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.config.Registry; +import org.apache.http.config.RegistryBuilder; +import org.apache.http.conn.socket.ConnectionSocketFactory; +import org.apache.http.conn.socket.PlainConnectionSocketFactory; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; +import org.apache.http.ssl.SSLContextBuilder; +import org.onap.logging.filter.spring.SpringClientPayloadFilter; +import org.onap.so.adapters.etsisol003adapter.pkgm.extclients.AbstractServiceProviderConfiguration; +import org.onap.so.configuration.rest.BasicHttpHeadersProvider; +import org.onap.so.configuration.rest.HttpClientConnectionConfiguration; +import org.onap.so.logging.jaxrs.filter.SOSpringClientFilter; +import org.onap.so.rest.service.HttpRestServiceProvider; +import org.onap.so.rest.service.HttpRestServiceProviderImpl; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.io.Resource; +import org.springframework.http.client.BufferingClientHttpRequestFactory; +import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.http.converter.json.GsonHttpMessageConverter; +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; +import org.springframework.web.client.RestTemplate; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +/** + * Configures the HttpRestServiceProvider to make REST calls to the ETSI Catalog Manager + * + * @author gareth.roper@est.tech + */ + +@Configuration +public class EtsiCatalogServiceProviderConfiguration extends AbstractServiceProviderConfiguration { + + public static final String ETSI_CATALOG_REST_TEMPLATE_BEAN = "etsiCatalogRestTemplate"; + + public static final String ETSI_CATALOG_SERVICE_PROVIDER_BEAN = "etsiCatalogServiceProvider"; + + private final static Logger LOGGER = LoggerFactory.getLogger(EtsiCatalogServiceProviderConfiguration.class); + + private final HttpClientConnectionConfiguration clientConnectionConfiguration; + + @Value("${etsi-catalog-manager.http.client.ssl.trust-store:#{null}}") + private Resource trustStore; + @Value("${etsi-catalog-manager.http.client.ssl.trust-store-password:#{null}}") + private String trustStorePassword; + + @Autowired + public EtsiCatalogServiceProviderConfiguration( + final HttpClientConnectionConfiguration clientConnectionConfiguration) { + this.clientConnectionConfiguration = clientConnectionConfiguration; + } + + @Bean + @Qualifier(ETSI_CATALOG_REST_TEMPLATE_BEAN) + public RestTemplate etsiCatalogRestTemplate() { + final RestTemplate restTemplate = new RestTemplate(); + restTemplate.getInterceptors().add(new SOSpringClientFilter()); + restTemplate.getInterceptors().add((new SpringClientPayloadFilter())); + return restTemplate; + } + + @Bean + @Qualifier(ETSI_CATALOG_SERVICE_PROVIDER_BEAN) + public HttpRestServiceProvider etsiCatalogHttpRestServiceProvider( + @Qualifier(ETSI_CATALOG_REST_TEMPLATE_BEAN) final RestTemplate restTemplate) { + setGsonMessageConverter(restTemplate); + + final HttpClientBuilder httpClientBuilder = getHttpClientBuilder(); + if (trustStore != null) { + try { + LOGGER.debug("Setting up HttpComponentsClientHttpRequestFactory with SSL Context"); + LOGGER.debug("Setting client trust-store: {}", trustStore.getURL()); + LOGGER.debug("Creating SSLConnectionSocketFactory with AllowAllHostsVerifier ... "); + final SSLContext sslContext = new SSLContextBuilder() + .loadTrustMaterial(trustStore.getURL(), trustStorePassword.toCharArray()).build(); + final SSLConnectionSocketFactory sslConnectionSocketFactory = + new SSLConnectionSocketFactory(sslContext, AllowAllHostsVerifier.INSTANCE); + httpClientBuilder.setSSLSocketFactory(sslConnectionSocketFactory); + final Registry socketFactoryRegistry = RegistryBuilder + .create().register("http", PlainConnectionSocketFactory.INSTANCE) + .register("https", sslConnectionSocketFactory).build(); + + httpClientBuilder.setConnectionManager(getConnectionManager(socketFactoryRegistry)); + } catch (final KeyManagementException | NoSuchAlgorithmException | KeyStoreException | CertificateException + | IOException exception) { + LOGGER.error("Error reading truststore, TLS connection will fail.", exception); + } + + } else { + LOGGER.debug("Setting connection manager without SSL ConnectionSocketFactory ..."); + httpClientBuilder.setConnectionManager(getConnectionManager()); + } + + final HttpComponentsClientHttpRequestFactory factory = + new HttpComponentsClientHttpRequestFactory(httpClientBuilder.build()); + restTemplate.setRequestFactory(new BufferingClientHttpRequestFactory(factory)); + + return new HttpRestServiceProviderImpl(restTemplate, new BasicHttpHeadersProvider().getHttpHeaders()); + } + + private PoolingHttpClientConnectionManager getConnectionManager( + final Registry socketFactoryRegistry) { + return new PoolingHttpClientConnectionManager(socketFactoryRegistry, null, null, null, + clientConnectionConfiguration.getTimeToLiveInMins(), TimeUnit.MINUTES); + } + + private PoolingHttpClientConnectionManager getConnectionManager() { + return new PoolingHttpClientConnectionManager(clientConnectionConfiguration.getTimeToLiveInMins(), + TimeUnit.MINUTES); + } + + private HttpClientBuilder getHttpClientBuilder() { + return HttpClientBuilder.create().setMaxConnPerRoute(clientConnectionConfiguration.getMaxConnectionsPerRoute()) + .setMaxConnTotal(clientConnectionConfiguration.getMaxConnections()) + .setDefaultRequestConfig(getRequestConfig()); + } + + private RequestConfig getRequestConfig() { + return RequestConfig.custom().setSocketTimeout(clientConnectionConfiguration.getSocketTimeOutInMiliSeconds()) + .setConnectTimeout(clientConnectionConfiguration.getConnectionTimeOutInMilliSeconds()).build(); + } + + private static final class AllowAllHostsVerifier implements HostnameVerifier { + + private static final AllowAllHostsVerifier INSTANCE = new AllowAllHostsVerifier(); + + @Override + public boolean verify(final String hostname, final SSLSession session) { + LOGGER.debug("Skipping hostname verification ..."); + return true; + } + + } + + public void setGsonMessageConverter(final RestTemplate restTemplate) { + final Iterator> iterator = restTemplate.getMessageConverters().iterator(); + while (iterator.hasNext()) { + if (iterator.next() instanceof MappingJackson2HttpMessageConverter) { + iterator.remove(); + } + } + final Gson gson = new GsonBuilder().create(); + restTemplate.getMessageConverters().add(new GsonHttpMessageConverter(gson)); + } + +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/extclients/etsicatalog/EtsiCatalogServiceProviderImpl.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/extclients/etsicatalog/EtsiCatalogServiceProviderImpl.java new file mode 100644 index 0000000000..a4e5550061 --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/extclients/etsicatalog/EtsiCatalogServiceProviderImpl.java @@ -0,0 +1,281 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog; + +import static org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.EtsiCatalogServiceProviderConfiguration.ETSI_CATALOG_SERVICE_PROVIDER_BEAN; +import java.util.Optional; +import org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.model.NsdmSubscription; +import org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.model.PkgmSubscription; +import org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.model.VnfPkgInfo; +import org.onap.so.adapters.etsisol003adapter.pkgm.model.InlineResponse2001; +import org.onap.so.adapters.etsisol003adapter.pkgm.rest.exceptions.EtsiCatalogManagerBadRequestException; +import org.onap.so.adapters.etsisol003adapter.pkgm.rest.exceptions.EtsiCatalogManagerRequestFailureException; +import org.onap.so.adapters.etsisol003adapter.pkgm.rest.exceptions.SubscriptionNotFoundException; +import org.onap.so.adapters.etsisol003adapter.pkgm.rest.exceptions.VnfPkgBadRequestException; +import org.onap.so.adapters.etsisol003adapter.pkgm.rest.exceptions.VnfPkgConflictException; +import org.onap.so.adapters.etsisol003adapter.pkgm.rest.exceptions.VnfPkgNotFoundException; +import org.onap.so.rest.exceptions.HttpResouceNotFoundException; +import org.onap.so.rest.exceptions.InvalidRestRequestException; +import org.onap.so.rest.exceptions.RestProcessingException; +import org.onap.so.rest.service.HttpRestServiceProvider; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.core.convert.ConversionService; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; + +/** + * Provides the implementations of the REST Requests to the ETSI Catalog Manager. + * + * @author gareth.roper@est.tech + */ +@Service +public class EtsiCatalogServiceProviderImpl implements EtsiCatalogServiceProvider { + private static final Logger logger = LoggerFactory.getLogger(EtsiCatalogServiceProviderImpl.class); + + private final HttpRestServiceProvider httpServiceProvider; + private final EtsiCatalogUrlProvider etsiCatalogUrlProvider; + private final ConversionService conversionService; + + @Autowired + public EtsiCatalogServiceProviderImpl(final EtsiCatalogUrlProvider etsiCatalogUrlProvider, + @Qualifier(ETSI_CATALOG_SERVICE_PROVIDER_BEAN) final HttpRestServiceProvider httpServiceProvider, + final ConversionService conversionService) { + this.etsiCatalogUrlProvider = etsiCatalogUrlProvider; + this.httpServiceProvider = httpServiceProvider; + this.conversionService = conversionService; + } + + @Override + public Optional getVnfPackageContent(final String vnfPkgId) + throws EtsiCatalogManagerRequestFailureException { + final String vnfRequestUrl = etsiCatalogUrlProvider.getVnfPackageContentUrl(vnfPkgId); + final String vnfRequestName = "getVnfPackageContent"; + return requestVnfElement(vnfPkgId, vnfRequestUrl, vnfRequestName); + } + + @Override + public Optional getVnfPackageArtifact(final String vnfPkgId, final String artifactPath) { + try { + final ResponseEntity response = httpServiceProvider.getHttpResponse( + etsiCatalogUrlProvider.getVnfPackageArtifactUrl(vnfPkgId, artifactPath), byte[].class); + logger.info("getVnfPackageArtifact Request to ETSI Catalog Manager Status Code: {}", + response.getStatusCodeValue()); + if (response.getStatusCode().is2xxSuccessful()) { + return Optional.ofNullable(response.getBody()); + } + } catch (final HttpResouceNotFoundException httpResouceNotFoundException) { + logger.error("Caught HttpResouceNotFoundException", httpResouceNotFoundException); + throw new VnfPkgNotFoundException("No Vnf Package Artifact found with vnfPkgId: \"" + vnfPkgId + + "\" and artifactPath: \"" + artifactPath + "\"."); + } catch (final RestProcessingException restProcessingException) { + logger.error("Caught RestProcessingException with Status Code: {}", restProcessingException.getStatusCode(), + restProcessingException); + if (restProcessingException.getStatusCode() == HttpStatus.CONFLICT.value()) { + throw new VnfPkgConflictException("A conflict occurred with the state of the resource,\n" + + "due to the attribute: onboardingState not being set to ONBOARDED."); + } + } + throw new EtsiCatalogManagerRequestFailureException("Internal Server Error Occurred."); + } + + @Override + public Optional getVnfPackages() { + try { + final ResponseEntity response = + httpServiceProvider.getHttpResponse(etsiCatalogUrlProvider.getVnfPackagesUrl(), VnfPkgInfo[].class); + logger.info("getVnfPackages Request to ETSI Catalog Manager Status Code: {}", + response.getStatusCodeValue()); + if (response.getStatusCode().is2xxSuccessful()) { + if (response.hasBody()) { + final VnfPkgInfo[] vnfPackages = response.getBody(); + assert (vnfPackages != null); + final InlineResponse2001[] responses = new InlineResponse2001[vnfPackages.length]; + for (int index = 0; index < vnfPackages.length; index++) { + if (conversionService.canConvert(vnfPackages[index].getClass(), InlineResponse2001.class)) { + final InlineResponse2001 inlineResponse2001 = + conversionService.convert(vnfPackages[index], InlineResponse2001.class); + if (inlineResponse2001 != null) { + responses[index] = inlineResponse2001; + } + } else { + logger.error("Unable to find Converter for response class: {}", + vnfPackages[index].getClass()); + } + } + return Optional.of(responses); + } + logger.error("Received response without body ..."); + } + logger.error("Unexpected status code received {}", response.getStatusCode()); + return Optional.empty(); + } catch (final InvalidRestRequestException invalidRestRequestException) { + logger.error("Caught InvalidRestRequestException", invalidRestRequestException); + throw new VnfPkgBadRequestException("Error: Bad Request Received"); + } catch (final HttpResouceNotFoundException httpResouceNotFoundException) { + logger.error("Caught HttpResouceNotFoundException", httpResouceNotFoundException); + throw new VnfPkgNotFoundException("No Vnf Packages found"); + } catch (final RestProcessingException restProcessingException) { + logger.error("Caught RestProcessingException with Status Code: {}", restProcessingException.getStatusCode(), + restProcessingException); + throw new EtsiCatalogManagerRequestFailureException("Internal Server Error Occurred."); + } + } + + @Override + public Optional getVnfPackage(final String vnfPkgId) { + try { + final ResponseEntity response = httpServiceProvider + .getHttpResponse(etsiCatalogUrlProvider.getVnfPackageUrl(vnfPkgId), VnfPkgInfo.class); + logger.info("getVnfPackage Request for vnfPkgId {} to ETSI Catalog Manager Status Code: {}", vnfPkgId, + response.getStatusCodeValue()); + if (response.getStatusCode().is2xxSuccessful()) { + if (response.hasBody()) { + final VnfPkgInfo vnfPkgInfo = response.getBody(); + if (conversionService.canConvert(vnfPkgInfo.getClass(), InlineResponse2001.class)) { + return Optional.ofNullable(conversionService.convert(vnfPkgInfo, InlineResponse2001.class)); + } + logger.error("Unable to find Converter for response class: {}", vnfPkgInfo.getClass()); + } + logger.error("Received response without body ...."); + } + return Optional.empty(); + } catch (final InvalidRestRequestException invalidRestRequestException) { + logger.error("Caught InvalidRestRequestException", invalidRestRequestException); + throw new VnfPkgBadRequestException("Error: Bad Request Received"); + } catch (final HttpResouceNotFoundException httpResouceNotFoundException) { + logger.error("Caught HttpResouceNotFoundException", httpResouceNotFoundException); + throw new VnfPkgNotFoundException("No Vnf Package found with vnfPkgId: " + vnfPkgId); + } catch (final RestProcessingException restProcessingException) { + logger.error("Caught RestProcessingException with Status Code: {}", restProcessingException.getStatusCode(), + restProcessingException); + throw new EtsiCatalogManagerRequestFailureException("Internal Server Error Occurred."); + } + } + + @Override + public Optional getVnfPackageVnfd(final String vnfPkgId) { + final String vnfRequestUrl = etsiCatalogUrlProvider.getVnfPackageVnfdUrl(vnfPkgId); + final String vnfRequestName = "getVnfPackageVnfd"; + return requestVnfElement(vnfPkgId, vnfRequestUrl, vnfRequestName); + } + + @Override + public Optional postSubscription( + final org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.model.PkgmSubscriptionRequest etsiCatalogManagerSubscriptionRequest) { + try { + final ResponseEntity responseEntity = + httpServiceProvider.postHttpRequest(etsiCatalogManagerSubscriptionRequest, + etsiCatalogUrlProvider.getSubscriptionUrl(), PkgmSubscription.class); + if (responseEntity.getStatusCode().is2xxSuccessful()) { + if (responseEntity.hasBody()) { + return Optional.of(responseEntity.getBody()); + } + logger.error("Received response without body on postSubscription"); + } + logger.error("Unexpected Status Code Received on postSubscription: {}", responseEntity.getStatusCode()); + return Optional.empty(); + } catch (final InvalidRestRequestException invalidRestRequestException) { + logger.error("Caught InvalidRestRequestException", invalidRestRequestException); + throw new EtsiCatalogManagerBadRequestException( + "Bad Request Received on postSubscription call to ETSI Catalog Manager."); + } catch (final RestProcessingException restProcessingException) { + logger.error("Caught RestProcessingException with Status Code: {}", restProcessingException.getStatusCode(), + restProcessingException); + throw new EtsiCatalogManagerRequestFailureException( + "Internal Server Error Occurred. On postSubscription with StatusCode: " + + restProcessingException.getStatusCode()); + } + } + + @Override + public boolean deleteSubscription(final String subscriptionId) { + try { + final ResponseEntity responseEntity = httpServiceProvider + .deleteHttpRequest(etsiCatalogUrlProvider.getSubscriptionUrl() + "/" + subscriptionId, Void.class); + + if (responseEntity.getStatusCode().is2xxSuccessful()) { + logger.info("Subscription with ID: {} has been successfully deleted from the ETSI Catalog Manager", + subscriptionId); + return true; + } + logger.error("Unexpected Status Code Received on deleteSubscription: {}", responseEntity.getStatusCode()); + return false; + } catch (final HttpResouceNotFoundException resouceNotFoundException) { + final String message = "Unable to find subscription in ETSI Catalog Manager using id: " + subscriptionId; + logger.error(message); + throw new SubscriptionNotFoundException(message); + } catch (final InvalidRestRequestException invalidRestRequestException) { + logger.error("Caught InvalidRestRequestException on deleteSubscription call to ETSI Catalog Manager.", + invalidRestRequestException); + throw new EtsiCatalogManagerBadRequestException( + "Bad Request Received on deleteSubscription call to ETSI Catalog Manager."); + } + } + + @Override + public Optional getSubscription(final String subscriptionId) { + try { + final ResponseEntity responseEntity = httpServiceProvider.getHttpResponse( + etsiCatalogUrlProvider.getSubscriptionUrl() + "/" + subscriptionId, NsdmSubscription.class); + + if (responseEntity.getStatusCode().is2xxSuccessful()) { + logger.debug("Found subscription with ID: {} in ETSI Catalog Manager", subscriptionId); + return Optional.ofNullable(responseEntity.getBody()); + } + logger.error("Unexpected Status Code Received on getting subscription from ETSI Catalog Manager: {}", + responseEntity.getStatusCode()); + } catch (final HttpResouceNotFoundException resouceNotFoundException) { + logger.error("Unable to find subscription in ETSI Catalog Manager using id: {}", subscriptionId); + return Optional.empty(); + } catch (final RestProcessingException | InvalidRestRequestException exception) { + logger.error("Unable to query ETSI Catalog Manager for subscription using id: {}", subscriptionId, + exception); + } + throw new EtsiCatalogManagerRequestFailureException("Internal Server Error Occurred."); + } + + private Optional requestVnfElement(final String vnfPkgId, final String vnfRequestUrl, + final String vnfRequestName) { + try { + final ResponseEntity response = httpServiceProvider.getHttpResponse(vnfRequestUrl, byte[].class); + logger.info("{} Request to ETSI Catalog Manager Status Code: {}", vnfRequestName, + response.getStatusCodeValue()); + if (response.getStatusCode() == HttpStatus.OK) { + return Optional.ofNullable(response.getBody()); + } + } catch (final HttpResouceNotFoundException httpResouceNotFoundException) { + logger.error("Caught HttpResouceNotFoundException", httpResouceNotFoundException); + throw new VnfPkgNotFoundException("No Vnf Package found with vnfPkgId: " + vnfPkgId); + } catch (final RestProcessingException restProcessingException) { + logger.error("Caught RestProcessingException with Status Code: {}", restProcessingException.getStatusCode(), + restProcessingException); + if (restProcessingException.getStatusCode() == HttpStatus.CONFLICT.value()) { + throw new VnfPkgConflictException("A conflict occurred with the state of the resource,\n" + + "due to the attribute: onboardingState not being set to ONBOARDED."); + } + } + throw new EtsiCatalogManagerRequestFailureException("Internal Server Error Occurred."); + } +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/extclients/etsicatalog/EtsiCatalogSubscriptionServiceProvider.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/extclients/etsicatalog/EtsiCatalogSubscriptionServiceProvider.java new file mode 100644 index 0000000000..d561f8734b --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/extclients/etsicatalog/EtsiCatalogSubscriptionServiceProvider.java @@ -0,0 +1,55 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog; + +import java.util.Optional; +import org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.model.NsdmSubscription; +import org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.model.PkgmSubscription; + +/** + * @author Waqas Ikram (waqas.ikram@est.tech) + * + */ +public interface EtsiCatalogSubscriptionServiceProvider { + + /** + * POST the SubscriptionRequest Object. + * + * @return The ETSI Catalog Manager's PkgmSubscription object. + */ + Optional postSubscription( + final org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.model.PkgmSubscriptionRequest etsiCatalogManagerSubscriptionRequest); + + /** + * Get the Subscription from ETSI Catalog. + * + * @param subscriptionId Subscription ID + * @return The Subscription {@link NsdmSubscription} from ETSI Catalog + */ + Optional getSubscription(final String subscriptionId); + + /** + * DELETE the SubscriptionRequest Object. + * + * @return A Boolean representing if the delete was successful or not. + */ + boolean deleteSubscription(final String subscriptionId); + +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/extclients/etsicatalog/EtsiCatalogUrlProvider.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/extclients/etsicatalog/EtsiCatalogUrlProvider.java new file mode 100644 index 0000000000..1725bf9fba --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/extclients/etsicatalog/EtsiCatalogUrlProvider.java @@ -0,0 +1,113 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog; + +import static org.slf4j.LoggerFactory.getLogger; +import org.slf4j.Logger; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; + +/** + * Provides the URLs for the REST Requests to the ETSI Catalog Manager. + * + * @author gareth.roper@est.tech + */ +@Service +public class EtsiCatalogUrlProvider { + + private static final Logger logger = getLogger(EtsiCatalogUrlProvider.class); + + @Value("${etsi-catalog-manager.vnfpkgm.endpoint}") + private String etsiCatalogManagerEndpoint; + + public EtsiCatalogUrlProvider() {} + + /** + * Get the URL for retrieving the Package Content from the ETSI Catalog.". + * + * @param vnfPkgId The ID of the VNF Package + * @return the URL for the GET operation + */ + public String getVnfPackageContentUrl(final String vnfPkgId) { + final String url = etsiCatalogManagerEndpoint + "/vnf_packages/" + vnfPkgId + "/package_content"; + logger.info("getEtsiCatalogVnfPackageContentUrl: {}", url); + return url; + } + + /** + * Get the URL for retrieving VNF packages information from ETSI Catalog.". + * + * @return the URL for the GET operation + */ + public String getVnfPackagesUrl() { + final String url = etsiCatalogManagerEndpoint + "/vnf_packages"; + logger.info("getEtsiCatalogVnfPackagesEndpoint: {}", url); + return url; + } + + /** + * Get the URL for retrieving specific VNF package information from the ETSI Catalog.". + * + * @param vnfPkgId The ID of the VNF Package + * @return the URL for the GET operation + */ + public String getVnfPackageUrl(final String vnfPkgId) { + final String url = etsiCatalogManagerEndpoint + "/vnf_packages/" + vnfPkgId; + logger.info("getEtsiCatalogVnfPackageEndpoint: {}", url); + return url; + } + + /** + * Get the URL for retrieving VNF Package Artifacts + * + * @param vnfPkgId The ID of the VNF Package + * @param artifactPath The path to the Artifact + * @return the URL for the GET operation + */ + public String getVnfPackageArtifactUrl(final String vnfPkgId, final String artifactPath) { + final String url = etsiCatalogManagerEndpoint + "/vnf_packages/" + vnfPkgId + "/artifacts/" + artifactPath; + logger.info("getVnfPackageArtifactUrl: {}", url); + return url; + } + + /** + * Get the URL for retrieving VNF packages vnfd from ETSI Catalog. + * + * @param vnfPkgId The ID of the VNF Package + * @return the URL for the GET operation + */ + public String getVnfPackageVnfdUrl(final String vnfPkgId) { + final String url = etsiCatalogManagerEndpoint + "/vnf_packages/" + vnfPkgId + "/vnfd"; + logger.info("getEtsiCatalogVnfPackageVnfd: {}", url); + return url; + } + + /** + * Get the URL for posting/retrieving a Subscription + * + * @return the URL for the operation + */ + public String getSubscriptionUrl() { + final String url = etsiCatalogManagerEndpoint + "/subscriptions"; + logger.info("getSubscriptionNotificationUrl: {}", url); + return url; + } +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/extclients/vnfm/VnfmHttpServiceProviderConfiguration.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/extclients/vnfm/VnfmHttpServiceProviderConfiguration.java new file mode 100644 index 0000000000..568c3df48b --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/extclients/vnfm/VnfmHttpServiceProviderConfiguration.java @@ -0,0 +1,49 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.so.adapters.etsisol003adapter.pkgm.extclients.vnfm; + +import static org.onap.so.client.RestTemplateConfig.CONFIGURABLE_REST_TEMPLATE; +import org.onap.so.adapters.etsisol003adapter.pkgm.extclients.AbstractServiceProviderConfiguration; +import org.onap.so.configuration.rest.BasicHttpHeadersProvider; +import org.onap.so.rest.service.HttpRestServiceProvider; +import org.onap.so.rest.service.HttpRestServiceProviderImpl; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.client.RestTemplate; + +/** + * @author Waqas Ikram (waqas.ikram@est.tech) + * + */ +@Configuration +public class VnfmHttpServiceProviderConfiguration extends AbstractServiceProviderConfiguration { + public static final String VNFM_ADAPTER_HTTP_SERVICE_PROVIDER_BEAN = "vnfmAdapterHttpServiceProvider"; + + @Bean + @Qualifier(VNFM_ADAPTER_HTTP_SERVICE_PROVIDER_BEAN) + public HttpRestServiceProvider vnfmAdapterHttpRestServiceProvider( + @Autowired @Qualifier(CONFIGURABLE_REST_TEMPLATE) RestTemplate restTemplate) { + setGsonMessageConverter(restTemplate); + return new HttpRestServiceProviderImpl(restTemplate, new BasicHttpHeadersProvider().getHttpHeaders()); + } + +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/EtsiSubscriptionNotificationController.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/EtsiSubscriptionNotificationController.java new file mode 100644 index 0000000000..de5314e6de --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/EtsiSubscriptionNotificationController.java @@ -0,0 +1,166 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.pkgm.rest; + +import static org.onap.so.adapters.etsi.sol003.adapter.common.CommonConstants.ETSI_SUBSCRIPTION_NOTIFICATION_CONTROLLER_BASE_URL; +import static org.slf4j.LoggerFactory.getLogger; +import java.io.IOException; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.AbstractMap; +import java.util.Map.Entry; +import javax.ws.rs.core.MediaType; +import org.onap.so.adapters.etsisol003adapter.etsicatalog.notification.model.PkgChangeNotification; +import org.onap.so.adapters.etsisol003adapter.etsicatalog.notification.model.PkgOnboardingNotification; +import org.onap.so.adapters.etsisol003adapter.pkgm.rest.exceptions.InternalServerErrorException; +import org.onap.so.adapters.etsisol003adapter.pkgm.rest.exceptions.NotificationTypeNotSupportedException; +import org.onap.so.adapters.etsisol003adapter.pkgm.subscriptionmanagement.NotificationManager; +import org.slf4j.Logger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; + +/** + * This controller handles the ETSI Subscription Notification Endpoints. + * + * @author Ronan Kenny (ronan.kenny@est.tech) + * @author Gareth Roper (gareth.roper@est.tech) + * @author Andrew Lamb (andrew.a.lamb@est.tech) + */ +@Controller +@RequestMapping(value = ETSI_SUBSCRIPTION_NOTIFICATION_CONTROLLER_BASE_URL) +public class EtsiSubscriptionNotificationController { + + private static final Logger logger = getLogger(EtsiSubscriptionNotificationController.class); + private final NotificationManager notificationManager; + private final Gson gson; + + @Autowired + public EtsiSubscriptionNotificationController(final NotificationManager notificationManager) { + this.notificationManager = notificationManager; + this.gson = new GsonBuilder().registerTypeAdapter(LocalDateTime.class, new LocalDateTimeTypeAdapter()).create(); + } + + @GetMapping(value = "/notification") + public ResponseEntity testSubscriptionNotificationEndPoint() { + logger.debug("Testing Notification Endpoint"); + return ResponseEntity.noContent().build(); + } + + /** + * POST notification on to subscriber. + * + * @param notification The notification to send. + * @return Response Code: 204 No Content if Successful, ProblemDetails Object if not. + */ + @PostMapping(value = "/notification", consumes = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON) + public ResponseEntity postSubscriptionNotification(@RequestBody final Object notification) { + logger.info("Posting subscription notification class: {} \n{}", notification.getClass(), notification); + final String notificationString = gson.toJson(notification); + + final Entry notificationObject = getNotificationObject(notificationString); + if (notificationManager.processSubscriptionNotification(notificationObject.getValue(), + notificationObject.getKey())) { + logger.info("Notification Delivered Successfully"); + return ResponseEntity.noContent().build(); + } + final String errorMessage = "An error occurred. Sending of notification to VNFM failed."; + logger.error(errorMessage); + throw new InternalServerErrorException(errorMessage); + } + + private Entry getNotificationObject(final String notification) { + logger.info("getNotificationObject() notification: {}", notification); + final String notificationType = getNotificationType(notification); + if (PkgOnboardingNotification.NotificationTypeEnum.VNFPACKAGEONBOARDINGNOTIFICATION.getValue() + .equals(notificationType)) { + final PkgOnboardingNotification pkgOnboardingNotification = + gson.fromJson(notification, PkgOnboardingNotification.class); + logger.info("Onboarding notification received:\n{}", pkgOnboardingNotification); + return new AbstractMap.SimpleEntry<>(pkgOnboardingNotification.getSubscriptionId(), + pkgOnboardingNotification); + } + if (PkgChangeNotification.NotificationTypeEnum.VNFPACKAGECHANGENOTIFICATION.getValue() + .equals(notificationType)) { + final PkgChangeNotification pkgChangeNotification = + gson.fromJson(notification, PkgChangeNotification.class); + logger.info("Change notification received:\n{}", pkgChangeNotification); + return new AbstractMap.SimpleEntry<>(pkgChangeNotification.getSubscriptionId(), pkgChangeNotification); + + } + + final String errorMessage = "An error occurred. Notification type not supported for: " + notificationType; + logger.error(errorMessage); + throw new NotificationTypeNotSupportedException(errorMessage); + + } + + private String getNotificationType(final String notification) { + try { + logger.info("getNotificationType() notification: {}", notification); + final JsonParser parser = new JsonParser(); + final JsonObject element = (JsonObject) parser.parse(notification); + return element.get("notificationType").getAsString(); + } catch (final Exception e) { + logger.error("An error occurred processing notificiation: {}", e.getMessage()); + } + throw new NotificationTypeNotSupportedException( + "Unable to parse notification type in object \n" + notification); + } + + public static class LocalDateTimeTypeAdapter extends TypeAdapter { + + private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + + @Override + public void write(final JsonWriter out, final LocalDateTime localDateTime) throws IOException { + if (localDateTime == null) { + out.nullValue(); + } else { + out.value(FORMATTER.format(localDateTime)); + } + } + + @Override + public LocalDateTime read(final JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + final String dateTime = in.nextString(); + return LocalDateTime.parse(dateTime, FORMATTER); + } + } + } + +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/Sol003PackageManagementController.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/Sol003PackageManagementController.java new file mode 100644 index 0000000000..6c1e5e5506 --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/Sol003PackageManagementController.java @@ -0,0 +1,176 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.pkgm.rest; + +import static org.onap.so.adapters.etsi.sol003.adapter.common.CommonConstants.PACKAGE_MANAGEMENT_BASE_URL; +import static org.onap.so.adapters.etsisol003adapter.pkgm.PackageManagementConstants.APPLICATION_ZIP; +import static org.slf4j.LoggerFactory.getLogger; +import java.util.Optional; +import javax.ws.rs.core.MediaType; +import org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.EtsiCatalogServiceProvider; +import org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.model.ProblemDetails; +import org.onap.so.adapters.etsisol003adapter.pkgm.model.InlineResponse2001; +import org.slf4j.Logger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; + +/** + * Controller for handling the VNF Package Management. For further information please read: + * https://www.etsi.org/deliver/etsi_gs/NFV-SOL/001_099/003/02.05.01_60/gs_nfv-sol003v020501p.pdf Use the section number + * above each endpoint to find the corresponding section in the above document. + * + * @author gareth.roper@est.tech + */ +@Controller +@RequestMapping(value = PACKAGE_MANAGEMENT_BASE_URL, consumes = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) +public class Sol003PackageManagementController { + + private final EtsiCatalogServiceProvider etsiCatalogServiceProvider; + private static final String LOG_REQUEST_RECEIVED = "VNF PackageManagement Controller: {} {} {} {}"; + private static final Logger logger = getLogger(Sol003PackageManagementController.class); + + @Autowired + Sol003PackageManagementController(final EtsiCatalogServiceProvider etsiCatalogServiceProvider) { + this.etsiCatalogServiceProvider = etsiCatalogServiceProvider; + } + + /** + * GET VNF packages information. Will return zero or more VNF package representations that match the attribute + * filter. These representations will be in a list. Section Number: 10.4.2 + * + * @return An Array of all VNF packages. Object: InlineResponse2001[] Response Code: 200 OK + */ + @GetMapping(value = "/vnf_packages", produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public ResponseEntity getVnfPackages() { + logger.info(LOG_REQUEST_RECEIVED, "getVnfPackages."); + final Optional response = etsiCatalogServiceProvider.getVnfPackages(); + if (response.isPresent()) { + logger.info(LOG_REQUEST_RECEIVED, "getVnfPackages Response: ", HttpStatus.OK); + return ResponseEntity.ok().body(response.get()); + } + final String errorMessage = "An error occurred, a null response was received by the\n" + + " Sol003PackageManagementController from the EtsiCatalogManager using the GET \"vnf_packages\" \n" + + "endpoint."; + logger.error(errorMessage); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new ProblemDetails().detail(errorMessage)); + } + + /** + * GET VNF package information. Will return a specific VNF package representation that match the attribute filter. + * Section Number: 10.4.3 + * + * @param vnfPkgId The ID of the VNF Package that you want to query. + * @return A VNF package based on vnfPkgId. Object: VnfPkgInfo Response Code: 200 OK + */ + @GetMapping(value = "/vnf_packages/{vnfPkgId}", produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + public ResponseEntity getVnfPackage(@PathVariable("vnfPkgId") final String vnfPkgId) { + logger.info(LOG_REQUEST_RECEIVED, "getVnfPackage: ", vnfPkgId); + final Optional response = etsiCatalogServiceProvider.getVnfPackage(vnfPkgId); + if (response.isPresent()) { + logger.info(LOG_REQUEST_RECEIVED, "getVnfPackage Response: ", HttpStatus.OK); + return ResponseEntity.ok().body(response.get()); + } + final String errorMessage = "An error occurred, a null response was received by the\n" + + " Sol003PackageManagementController from the EtsiCatalogManager using the GET \"vnf_packages\" by vnfPkgId: \"" + + vnfPkgId + "\" \n" + "endpoint."; + logger.error(errorMessage); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new ProblemDetails().detail(errorMessage)); + } + + /** + * GET VNFD, from VNF package. Will return a copy of the file representing the VNFD or a ZIP file that contains the + * file/multiple files representing the VNFD specified. Section Number: 10.4.4 + * + * @param vnfPkgId The ID of the VNF Package that you want to retrieve the VNFD from. + * @return The VNFD of a VNF Package as a single file or within a ZIP file. Object: byte[] Response Code: 200 OK + */ + @GetMapping(value = "/vnf_packages/{vnfPkgId}/vnfd", + produces = {MediaType.TEXT_PLAIN, APPLICATION_ZIP, MediaType.APPLICATION_JSON}) + public ResponseEntity getVnfPackageVnfd(@PathVariable("vnfPkgId") final String vnfPkgId) { + logger.info(LOG_REQUEST_RECEIVED, "getVnfPackageVnfd Endpoint Invoked with VNF Package ID: ", vnfPkgId); + final Optional response = etsiCatalogServiceProvider.getVnfPackageVnfd(vnfPkgId); + if (response.isPresent()) { + logger.info(LOG_REQUEST_RECEIVED, "getVnfPackageVnfd Response: ", HttpStatus.OK); + return new ResponseEntity<>(response.get(), HttpStatus.OK); + } + final String errorMessage = "An error occurred, a null response was received by the\n" + + " Sol003PackageManagementController from the EtsiCatalogManager using the GET \"vnfd\" \n" + + "endpoint."; + + logger.error(errorMessage); + return new ResponseEntity<>(new ProblemDetails().detail(errorMessage), HttpStatus.INTERNAL_SERVER_ERROR); + } + + /** + * GET Package Content, from VNF Package. Will return a copy of the VNF package file that you specified. Section + * Number: 10.4.5 + * + * @param vnfPkgId The ID of the VNF Package that you want to retrieve the "package_content" from. + * @return The Package Content of a VNF Package. Object: byte[] Response Code: 200 OK + */ + @GetMapping(value = "/vnf_packages/{vnfPkgId}/package_content", + produces = {MediaType.APPLICATION_JSON, APPLICATION_ZIP, MediaType.APPLICATION_OCTET_STREAM}) + public ResponseEntity getVnfPackageContent(@PathVariable("vnfPkgId") final String vnfPkgId) { + logger.info(LOG_REQUEST_RECEIVED, "getVnfPackageContent Endpoint Invoked with VNF Package ID: ", vnfPkgId); + final Optional response = etsiCatalogServiceProvider.getVnfPackageContent(vnfPkgId); + if (response.isPresent()) { + logger.info(LOG_REQUEST_RECEIVED, "getVnfPackageContent Response: ", HttpStatus.OK); + return ResponseEntity.ok().body(response.get()); + } + final String errorMessage = "An error occurred, a null response was received by the\n" + + " Sol003PackageManagementController from the EtsiCatalogManager using the GET \"package_content\" \n" + + "endpoint."; + logger.error(errorMessage); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new ProblemDetails().detail(errorMessage)); + } + + /** + * GET Artifact, from VNF Package Will return a the content of the artifact that you specified. Section Number: + * 10.4.6 + * + * @param vnfPkgId The ID of the VNF Package that you want to retrieve an artifact from. + * @param artifactPath The path of the artifact that you want to retrieve. + * @return An Artifact from a VNF Package. Object: byte[] Response Code: 200 OK + */ + @GetMapping(value = "/vnf_packages/{vnfPkgId}/artifacts/{artifactPath}", + produces = {MediaType.APPLICATION_OCTET_STREAM, MediaType.APPLICATION_JSON}) + public ResponseEntity getVnfPackageArtifact(@PathVariable("vnfPkgId") final String vnfPkgId, + @PathVariable("artifactPath") final String artifactPath) { + logger.info(LOG_REQUEST_RECEIVED, "getVnfPackageArtifact: vnfPkgId= ", vnfPkgId, " artifactPath=", + artifactPath); + final Optional response = etsiCatalogServiceProvider.getVnfPackageArtifact(vnfPkgId, artifactPath); + if (response.isPresent()) { + logger.info(LOG_REQUEST_RECEIVED, "getVnfPackageArtifact Response: ", HttpStatus.OK); + return ResponseEntity.ok().body(response.get()); + } + final String errorMessage = "An error occurred, a null response was received by the\n" + + " Sol003PackageManagementController from the EtsiCatalogManager using the\n GET \"vnf_packages\" by vnfPkgId: \"" + + vnfPkgId + "\" for artifactPath: \"" + artifactPath + "\"\n" + "endpoint."; + logger.error(errorMessage); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new ProblemDetails().detail(errorMessage)); + } + +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/Sol003PackageManagementSubscriptionController.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/Sol003PackageManagementSubscriptionController.java new file mode 100644 index 0000000000..905b4f6588 --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/Sol003PackageManagementSubscriptionController.java @@ -0,0 +1,172 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.pkgm.rest; + +import static org.onap.so.adapters.etsi.sol003.adapter.common.CommonConstants.PACKAGE_MANAGEMENT_BASE_URL; +import static org.slf4j.LoggerFactory.getLogger; +import java.net.URI; +import java.security.GeneralSecurityException; +import java.util.List; +import java.util.Optional; +import javax.ws.rs.core.MediaType; +import org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.model.ProblemDetails; +import org.onap.so.adapters.etsisol003adapter.pkgm.model.InlineResponse201; +import org.onap.so.adapters.etsisol003adapter.pkgm.model.PkgmSubscriptionRequest; +import org.onap.so.adapters.etsisol003adapter.pkgm.subscriptionmanagement.SubscriptionManager; +import org.slf4j.Logger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; + +/** + * Controller for handling the Subscription Management. The client can use this resource to subscribe to notifications + * related to the VNF package management, and to query its subscriptions. For further information please read: + * https://www.etsi.org/deliver/etsi_gs/NFV-SOL/001_099/003/02.05.01_60/gs_nfv-sol003v020501p.pdf Use the section number + * above each endpoint to find the corresponding section in the above document. + * + * @author Ronan Kenny (ronan.kenny@est.tech) + * @author Gareth Roper (gareth.roper@est.tech) + */ +@Controller +@RequestMapping(value = PACKAGE_MANAGEMENT_BASE_URL, produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}, + consumes = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) +public class Sol003PackageManagementSubscriptionController { + + private static final String LOG_REQUEST_RECEIVED = "Subscription Management Controller: {} {}"; + private static final Logger logger = getLogger(Sol003PackageManagementSubscriptionController.class); + private final SubscriptionManager subscriptionManager; + + @Autowired + public Sol003PackageManagementSubscriptionController(final SubscriptionManager subscriptionManager) { + this.subscriptionManager = subscriptionManager; + } + + /** + * POST Subscribe request. Will send request and respond with the subscription that you subscribed to, if + * successful. Section Number: 10.4.7 + * + * @param pkgmSubscriptionRequest This includes the details of the subscription to be created. + * @return The subscription requested, if successful. Object: InlineRespone2002 Response Code: 201 Created Response + * Code: 303 Duplicate Subscription + * @throws GeneralSecurityException + */ + @PostMapping(value = "/subscriptions") + public ResponseEntity postSubscriptionRequest(@RequestBody final PkgmSubscriptionRequest pkgmSubscriptionRequest) + throws GeneralSecurityException { + logger.info(LOG_REQUEST_RECEIVED, " postSubscriptionRequest Endpoint Called", pkgmSubscriptionRequest); + + // Check if subscription exists already. + final Optional exists = subscriptionManager.getSubscriptionId(pkgmSubscriptionRequest); + + if (exists.isPresent()) { + final URI subscriptionUri = subscriptionManager.getSubscriptionUri(exists.get()); + final HttpHeaders headers = createLocationHeader(subscriptionUri); + logger.info("PkgmSubscriptionRequest already exists with uri {} ", subscriptionUri); + return new ResponseEntity<>(headers, HttpStatus.SEE_OTHER); + } + + logger.debug("No duplicate Subscription exists, continuing with POST."); + final Optional optionalInlineResponse = + subscriptionManager.createSubscription(pkgmSubscriptionRequest); + + if (optionalInlineResponse.isPresent()) { + InlineResponse201 inlineResponse = optionalInlineResponse.get(); + final URI subscriptionUri = subscriptionManager.getSubscriptionUri(inlineResponse.getId()); + final HttpHeaders headers = createLocationHeader(subscriptionUri); + logger.debug("Sending response with uri {} ", subscriptionUri); + return new ResponseEntity<>(inlineResponse, headers, HttpStatus.CREATED); + } + final String errorMessage = "A null response was received during the postSubscriptionRequest call."; + logger.error(errorMessage); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new ProblemDetails().detail(errorMessage)); + } + + /** + * GET all subscriptions. Will return a list of all subscriptions currently active. Section Number: 10.4.7 + * + * @return All of the current active subscriptions. Object: List Response Code: 200 OK + */ + @GetMapping(value = "/subscriptions") + public ResponseEntity> getSubscriptions() { + logger.info(LOG_REQUEST_RECEIVED, " getSubscriptions."); + List subscriptionsList = subscriptionManager.getSubscriptions(); + return new ResponseEntity<>(subscriptionsList, HttpStatus.OK); + } + + /** + * GET a specific subscription, by subscriptionId. Section Number: 10.4.8 + * + * @param subscriptionId The ID of the subscription that you wish to retrieve. + * @return A subscription based on subscriptionId. Object: InlineResponse2002 Response Code: 200 OK + */ + @GetMapping(value = "/subscriptions/{subscriptionId}") + public ResponseEntity getSubscription(@PathVariable("subscriptionId") final String subscriptionId) { + logger.info(LOG_REQUEST_RECEIVED, " Getting Subscription: ", subscriptionId); + final Optional optional = subscriptionManager.getSubscription(subscriptionId); + if (optional.isPresent()) { + logger.debug("Return subscription with id {} and body {}", subscriptionId, optional); + return new ResponseEntity<>(optional.get(), HttpStatus.OK); + } + final String errorMessage = + "The requested subscription: " + subscriptionId + " was not found on call getSubscription"; + logger.error(errorMessage); + return ResponseEntity.status(HttpStatus.NOT_FOUND).body(new ProblemDetails().detail(errorMessage)); + } + + /** + * DELETE a specific subscription, by subscriptionId. Section Number: 10.4.8.3.5 + * + * @param subscriptionId The ID of the subscription that you wish to delete. + * @return Empty response if successful. Object: Void Response Code: 204 No Content + */ + @DeleteMapping(value = "/subscriptions/{subscriptionId}") + public ResponseEntity deleteSubscription(@PathVariable("subscriptionId") final String subscriptionId) { + if (subscriptionManager.deleteSubscription(subscriptionId)) { + logger.debug("Successfully deleted subscription with id {}", subscriptionId); + return ResponseEntity.noContent().build(); + } + final String errorMessage = + "The requested subscription: " + subscriptionId + " was not found on call deleteSubscription"; + logger.error(errorMessage); + return ResponseEntity.status(HttpStatus.NOT_FOUND).body(new ProblemDetails().detail(errorMessage)); + } + + /** + * Method to set the Location in the header with the URI parameter + * + * @param subscriptionUri + * @return header with callbackUri in Location + */ + private HttpHeaders createLocationHeader(final URI subscriptionUri) { + final HttpHeaders headers = new HttpHeaders(); + headers.setLocation(subscriptionUri); + return headers; + } + +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/exceptions/AuthenticationTypeNotSupportedException.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/exceptions/AuthenticationTypeNotSupportedException.java new file mode 100644 index 0000000000..6e1330140f --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/exceptions/AuthenticationTypeNotSupportedException.java @@ -0,0 +1,44 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.so.adapters.etsisol003adapter.pkgm.rest.exceptions; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +/** + * Exception for an unsupported authentication type + * + * @author Andrew Lamb (andrew.a.lamb@est.tech) + */ +@ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR) +public class AuthenticationTypeNotSupportedException extends RuntimeException { + + private static final long serialVersionUID = 2939423208362066902L; + + public AuthenticationTypeNotSupportedException(final String message) { + super(message); + } + + @Override + public synchronized Throwable fillInStackTrace() { + return this; + } + +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/exceptions/ConversionFailedException.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/exceptions/ConversionFailedException.java new file mode 100644 index 0000000000..9e9cb8e352 --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/exceptions/ConversionFailedException.java @@ -0,0 +1,44 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.so.adapters.etsisol003adapter.pkgm.rest.exceptions; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +/** + * Exception for Conversion Failures + * + * @author Gareth Roper (gareth.roper@est.tech) + * @author Andrew Lamb (andrew.a.lamb@est.tech) + */ +@ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR) +public class ConversionFailedException extends RuntimeException { + + private static final long serialVersionUID = 45898561453196895L; + + public ConversionFailedException(final String message) { + super(message); + } + + @Override + public synchronized Throwable fillInStackTrace() { + return this; + } +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/exceptions/EtsiCatalogManagerBadRequestException.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/exceptions/EtsiCatalogManagerBadRequestException.java new file mode 100644 index 0000000000..7d9d5fc17a --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/exceptions/EtsiCatalogManagerBadRequestException.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.so.adapters.etsisol003adapter.pkgm.rest.exceptions; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +/** + * Exception for an ETSI Catalog Manager Bad Request Exception. + * + * @author Gareth Roper (gareth.roper@est.tech + */ +@ResponseStatus(code = HttpStatus.BAD_REQUEST) +public class EtsiCatalogManagerBadRequestException extends RuntimeException { + + private static final long serialVersionUID = 6571317418914258768L; + + public EtsiCatalogManagerBadRequestException(final String message) { + super(message); + } + + @Override + public synchronized Throwable fillInStackTrace() { + return this; + } +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/exceptions/EtsiCatalogManagerRequestFailureException.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/exceptions/EtsiCatalogManagerRequestFailureException.java new file mode 100644 index 0000000000..a07732f3fa --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/exceptions/EtsiCatalogManagerRequestFailureException.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.so.adapters.etsisol003adapter.pkgm.rest.exceptions; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +/** + * Exception for an ETSI Catalog Manager Request Failure + * + * @author gareth.roper@est.tech + */ +@ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR) +public class EtsiCatalogManagerRequestFailureException extends RuntimeException { + + private static final long serialVersionUID = 66862444537194516L; + + public EtsiCatalogManagerRequestFailureException(final String message) { + super(message); + } + + @Override + public synchronized Throwable fillInStackTrace() { + return this; + } +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/exceptions/EtsiSubscriptionNotificationControllerExceptionHandler.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/exceptions/EtsiSubscriptionNotificationControllerExceptionHandler.java new file mode 100644 index 0000000000..645ef96326 --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/exceptions/EtsiSubscriptionNotificationControllerExceptionHandler.java @@ -0,0 +1,112 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.pkgm.rest.exceptions; + +import static org.slf4j.LoggerFactory.getLogger; +import org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.model.ProblemDetails; +import org.onap.so.adapters.etsisol003adapter.pkgm.rest.EtsiSubscriptionNotificationController; +import org.onap.so.rest.exceptions.HttpResouceNotFoundException; +import org.onap.so.rest.exceptions.InvalidRestRequestException; +import org.onap.so.rest.exceptions.RestProcessingException; +import org.slf4j.Logger; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; + +/** + * Exception Handler for the Etsi Subscription Notification Controller {@link EtsiSubscriptionNotificationController + * EtsiSubscriptionNotificationController} + * + * @author Andrew Lamb (andrew.a.lamb@est.tech) + */ +@ControllerAdvice(assignableTypes = EtsiSubscriptionNotificationController.class) +public class EtsiSubscriptionNotificationControllerExceptionHandler { + + private static final Logger logger = getLogger(EtsiSubscriptionNotificationControllerExceptionHandler.class); + + @ExceptionHandler(InvalidRestRequestException.class) + public ResponseEntity handleInvalidRestRequestException( + final InvalidRestRequestException invalidRestRequestException) { + final String errorMessage = "An error occurred. Sending of notification to VNFM failed with response: " + + HttpStatus.BAD_REQUEST + ".\n" + invalidRestRequestException.getMessage(); + logger.error(errorMessage); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new ProblemDetails().detail(errorMessage)); + } + + @ExceptionHandler(HttpResouceNotFoundException.class) + public ResponseEntity handleHttpResourceNotFoundException( + final HttpResouceNotFoundException httpResourceNotFoundException) { + final String errorMessage = "An error occurred. Sending of notification to VNFM failed with response: " + + HttpStatus.NOT_FOUND + ".\n" + httpResourceNotFoundException.getMessage(); + logger.error(errorMessage); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new ProblemDetails().detail(errorMessage)); + } + + @ExceptionHandler(RestProcessingException.class) + public ResponseEntity handleRestProcessingException( + final RestProcessingException restProcessingException) { + final String errorMessage = "An error occurred. Sending of notification to VNFM failed with response: " + + restProcessingException.getStatusCode() + ".\n" + restProcessingException.getMessage(); + logger.error(errorMessage); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new ProblemDetails().detail(errorMessage)); + } + + @ExceptionHandler(InternalServerErrorException.class) + public ResponseEntity handleInternalServerErrorException( + final InternalServerErrorException internalServerErrorException) { + logger.error(internalServerErrorException.getMessage()); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) + .body(new ProblemDetails().detail(internalServerErrorException.getMessage())); + } + + @ExceptionHandler(AuthenticationTypeNotSupportedException.class) + public ResponseEntity handleAuthenticationTypeNotSupportedException( + final AuthenticationTypeNotSupportedException authenticationTypeNotSupportedException) { + logger.error(authenticationTypeNotSupportedException.getMessage()); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) + .body(new ProblemDetails().detail(authenticationTypeNotSupportedException.getMessage())); + } + + @ExceptionHandler(ConversionFailedException.class) + public ResponseEntity handleConversionFailedException( + final ConversionFailedException conversionFailedException) { + logger.error(conversionFailedException.getMessage()); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) + .body(new ProblemDetails().detail(conversionFailedException.getMessage())); + } + + @ExceptionHandler(NotificationTypeNotSupportedException.class) + public ResponseEntity handleNotificationTypeNotSupportedException( + final NotificationTypeNotSupportedException notificationTypeNotSupportedException) { + logger.error(notificationTypeNotSupportedException.getMessage()); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) + .body(new ProblemDetails().detail(notificationTypeNotSupportedException.getMessage())); + } + + @ExceptionHandler(SubscriptionNotFoundException.class) + public ResponseEntity handleSubscriptionNotFoundException( + final SubscriptionNotFoundException subscriptionNotFoundException) { + logger.error(subscriptionNotFoundException.getMessage()); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) + .body(new ProblemDetails().detail(subscriptionNotFoundException.getMessage())); + } +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/exceptions/InternalServerErrorException.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/exceptions/InternalServerErrorException.java new file mode 100644 index 0000000000..9dd7f1b7b2 --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/exceptions/InternalServerErrorException.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.so.adapters.etsisol003adapter.pkgm.rest.exceptions; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +/** + * Exception for an ETSI Catalog Manager Request Failure + * + * @author gareth.roper@est.tech + */ +@ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR) +public class InternalServerErrorException extends RuntimeException { + + private static final long serialVersionUID = 66864561537194516L; + + public InternalServerErrorException(final String message) { + super(message); + } + + @Override + public synchronized Throwable fillInStackTrace() { + return this; + } +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/exceptions/NotificationTypeNotSupportedException.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/exceptions/NotificationTypeNotSupportedException.java new file mode 100644 index 0000000000..7716037342 --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/exceptions/NotificationTypeNotSupportedException.java @@ -0,0 +1,44 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.so.adapters.etsisol003adapter.pkgm.rest.exceptions; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +/** + * Exception for an unsupported notification type + * + * @author Andrew Lamb (andrew.a.lamb@est.tech) + */ +@ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR) +public class NotificationTypeNotSupportedException extends RuntimeException { + + private static final long serialVersionUID = 2939423208362066902L; + + public NotificationTypeNotSupportedException(final String message) { + super(message); + } + + @Override + public synchronized Throwable fillInStackTrace() { + return this; + } + +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/exceptions/Sol003PackageManagementControllerExceptionHandler.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/exceptions/Sol003PackageManagementControllerExceptionHandler.java new file mode 100644 index 0000000000..9f97b4ae02 --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/exceptions/Sol003PackageManagementControllerExceptionHandler.java @@ -0,0 +1,94 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.pkgm.rest.exceptions; + +import org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.model.ProblemDetails; +import org.onap.so.adapters.etsisol003adapter.pkgm.rest.Sol003PackageManagementController; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; + +/** + * Exception Handler for the Package Management Controller {@link Sol003PackageManagementController Sol003Controller} + * + * @author gareth.roper@est.tech + */ +@ControllerAdvice(assignableTypes = Sol003PackageManagementController.class) + +public class Sol003PackageManagementControllerExceptionHandler { + + @ExceptionHandler(EtsiCatalogManagerRequestFailureException.class) + public ResponseEntity handleEtsiCatalogManagerRequestFailureException( + final EtsiCatalogManagerRequestFailureException etsiCatalogManagerRequestFailureException) { + final ProblemDetails problemDetails = new ProblemDetails(); + problemDetails.setDetail(etsiCatalogManagerRequestFailureException.getMessage()); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(problemDetails); + } + + @ExceptionHandler(EtsiCatalogManagerBadRequestException.class) + public ResponseEntity handleEtsiCatalogManagerBadRequestFailureException( + final EtsiCatalogManagerBadRequestException etsiCatalogManagerBadRequestException) { + final ProblemDetails problemDetails = new ProblemDetails(); + problemDetails.setDetail(etsiCatalogManagerBadRequestException.getMessage()); + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(problemDetails); + } + + @ExceptionHandler(SubscriptionNotFoundException.class) + public ResponseEntity handleSubscriptionNotFoundException( + final SubscriptionNotFoundException subscriptionNotFoundException) { + final ProblemDetails problemDetails = new ProblemDetails(); + problemDetails.setDetail(subscriptionNotFoundException.getMessage()); + return ResponseEntity.status(HttpStatus.NOT_FOUND).body(problemDetails); + } + + @ExceptionHandler(ConversionFailedException.class) + public ResponseEntity handleConversionFailedException( + final ConversionFailedException conversionFailedException) { + final ProblemDetails problemDetails = new ProblemDetails(); + problemDetails.setDetail(conversionFailedException.getMessage()); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(problemDetails); + } + + @ExceptionHandler(VnfPkgConflictException.class) + public ResponseEntity handleVnfPkgConflictException( + final VnfPkgConflictException vnfPkgConflictException) { + final ProblemDetails problemDetails = new ProblemDetails(); + problemDetails.setDetail(vnfPkgConflictException.getMessage()); + return ResponseEntity.status(HttpStatus.CONFLICT).body(problemDetails); + } + + @ExceptionHandler(VnfPkgNotFoundException.class) + public ResponseEntity handleVnfPkgNotFoundException( + final VnfPkgNotFoundException vnfPkgNotFoundException) { + final ProblemDetails problemDetails = new ProblemDetails(); + problemDetails.setDetail(vnfPkgNotFoundException.getMessage()); + return ResponseEntity.status(HttpStatus.NOT_FOUND).body(problemDetails); + } + + @ExceptionHandler(VnfPkgBadRequestException.class) + public ResponseEntity handleVnfPkgBadRequestException( + final VnfPkgBadRequestException vnfPkgBadRequestException) { + final ProblemDetails problemDetails = new ProblemDetails(); + problemDetails.setDetail(vnfPkgBadRequestException.getMessage()); + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(problemDetails); + } +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/exceptions/SubscriptionNotFoundException.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/exceptions/SubscriptionNotFoundException.java new file mode 100644 index 0000000000..af409e7399 --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/exceptions/SubscriptionNotFoundException.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.so.adapters.etsisol003adapter.pkgm.rest.exceptions; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +/** + * Exception for an ETSI Catalog Manager Request Failure + * + * @author gareth.roper@est.tech + */ +@ResponseStatus(code = HttpStatus.NOT_FOUND) +public class SubscriptionNotFoundException extends RuntimeException { + + private static final long serialVersionUID = 85268561453194516L; + + public SubscriptionNotFoundException(final String message) { + super(message); + } + + @Override + public synchronized Throwable fillInStackTrace() { + return this; + } +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/exceptions/VnfPkgBadRequestException.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/exceptions/VnfPkgBadRequestException.java new file mode 100644 index 0000000000..5c318da89f --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/exceptions/VnfPkgBadRequestException.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.so.adapters.etsisol003adapter.pkgm.rest.exceptions; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +/** + * Exception for a Vnfpkg Bad Request failure, due to state of resource. + * + * @author andrew.a.lamb@est.tech + */ +@ResponseStatus(code = HttpStatus.BAD_REQUEST) +public class VnfPkgBadRequestException extends RuntimeException { + + private static final long serialVersionUID = 3301317418914258411L; + + public VnfPkgBadRequestException(final String message) { + super(message); + } + + @Override + public synchronized Throwable fillInStackTrace() { + return this; + } +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/exceptions/VnfPkgConflictException.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/exceptions/VnfPkgConflictException.java new file mode 100644 index 0000000000..7cb7a0c860 --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/exceptions/VnfPkgConflictException.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.so.adapters.etsisol003adapter.pkgm.rest.exceptions; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +/** + * Exception for a VnfPkg Conflict failures, due to state of resource. + * + * @author gareth.roper@est.tech + */ +@ResponseStatus(code = HttpStatus.CONFLICT) +public class VnfPkgConflictException extends RuntimeException { + + private static final long serialVersionUID = 26862444537198441L; + + public VnfPkgConflictException(final String message) { + super(message); + } + + @Override + public synchronized Throwable fillInStackTrace() { + return this; + } +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/exceptions/VnfPkgNotFoundException.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/exceptions/VnfPkgNotFoundException.java new file mode 100644 index 0000000000..5ed4847173 --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/exceptions/VnfPkgNotFoundException.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.so.adapters.etsisol003adapter.pkgm.rest.exceptions; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +/** + * Exception for VnfPkg Not Found Failures + * + * @author gareth.roper@est.tech + */ +@ResponseStatus(code = HttpStatus.NOT_FOUND) +public class VnfPkgNotFoundException extends RuntimeException { + + private static final long serialVersionUID = 26862444537198441L; + + public VnfPkgNotFoundException(final String message) { + super(message); + } + + @Override + public synchronized Throwable fillInStackTrace() { + return this; + } +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/subscriptionmanagement/AbstractNotificationServiceProvider.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/subscriptionmanagement/AbstractNotificationServiceProvider.java new file mode 100644 index 0000000000..8cd65e00f8 --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/subscriptionmanagement/AbstractNotificationServiceProvider.java @@ -0,0 +1,59 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.so.adapters.etsisol003adapter.pkgm.subscriptionmanagement; + +import static org.onap.so.adapters.etsisol003adapter.pkgm.extclients.vnfm.VnfmHttpServiceProviderConfiguration.VNFM_ADAPTER_HTTP_SERVICE_PROVIDER_BEAN; +import java.nio.charset.StandardCharsets; +import org.apache.commons.codec.binary.Base64; +import org.onap.so.configuration.rest.BasicHttpHeadersProvider; +import org.onap.so.rest.service.HttpRestServiceProvider; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; + +/** + * A base class that can be extended by classes for providing notification services. Provides common methods that will + * be useful to those classes. + * + * @author Waqas Ikram (waqas.ikram@est.tech) + * @author Andrew Lamb (andrew.a.lamb@est.tech) + */ +public abstract class AbstractNotificationServiceProvider { + + @Autowired + @Qualifier(VNFM_ADAPTER_HTTP_SERVICE_PROVIDER_BEAN) + private HttpRestServiceProvider httpRestServiceProvider; + + protected HttpRestServiceProvider getHttpRestServiceProvider() { + return httpRestServiceProvider; + } + + protected BasicHttpHeadersProvider getBasicHttpHeadersProviderWithBasicAuth(final String username, + final String password) { + final byte[] encodedAuth = getBasicAuth(username, password); + final String authHeader = "Basic " + new String(encodedAuth); + return new BasicHttpHeadersProvider(authHeader); + } + + protected byte[] getBasicAuth(final String username, final String password) { + final String auth = username + ":" + password; + return Base64.encodeBase64(auth.getBytes(StandardCharsets.ISO_8859_1)); + } + +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/subscriptionmanagement/BasicAuthNotificationServiceProvider.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/subscriptionmanagement/BasicAuthNotificationServiceProvider.java new file mode 100644 index 0000000000..fcba0f866d --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/subscriptionmanagement/BasicAuthNotificationServiceProvider.java @@ -0,0 +1,68 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.so.adapters.etsisol003adapter.pkgm.subscriptionmanagement; + +import static org.slf4j.LoggerFactory.getLogger; +import org.onap.so.adapters.etsisol003adapter.pkgm.model.SubscriptionsAuthentication; +import org.onap.so.adapters.etsisol003adapter.pkgm.model.SubscriptionsAuthentication.AuthTypeEnum; +import org.onap.so.configuration.rest.HttpHeadersProvider; +import org.onap.so.rest.service.HttpRestServiceProvider; +import org.slf4j.Logger; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; + +/** + * Implementation of a NotificationServiceProvider which supports Basic Authentication + * + * @author Waqas Ikram (waqas.ikram@est.tech) + * @author Andrew Lamb (andrew.a.lamb@est.tech) + */ +@Service +public class BasicAuthNotificationServiceProvider extends AbstractNotificationServiceProvider + implements NotificationServiceProvider { + + private static final Logger logger = getLogger(BasicAuthNotificationServiceProvider.class); + + @Override + public boolean send(final Object notification, final SubscriptionsAuthentication subscriptionsAuthentication, + final String callbackUri) { + logger.info("Sending notification to uri: {}", callbackUri); + final HttpHeadersProvider httpHeadersProvider = + getBasicHttpHeadersProviderWithBasicAuth(subscriptionsAuthentication.getParamsBasic().getUserName(), + subscriptionsAuthentication.getParamsBasic().getPassword()); + final HttpRestServiceProvider httpRestServiceProvider = getHttpRestServiceProvider(); + + final ResponseEntity responseEntity = httpRestServiceProvider.postHttpRequest(notification, callbackUri, + httpHeadersProvider.getHttpHeaders(), Void.class); + if (responseEntity.getStatusCode().is2xxSuccessful()) { + logger.info("Notification sent successfully."); + return true; + } + + logger.error("Failed to send notification."); + return false; + } + + @Override + public AuthTypeEnum getAuthType() { + return AuthTypeEnum.BASIC; + } + +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/subscriptionmanagement/NotificationManager.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/subscriptionmanagement/NotificationManager.java new file mode 100644 index 0000000000..a5f4aefc05 --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/subscriptionmanagement/NotificationManager.java @@ -0,0 +1,137 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.pkgm.subscriptionmanagement; + +import static org.slf4j.LoggerFactory.getLogger; +import java.util.List; +import java.util.Optional; +import org.onap.so.adapters.etsisol003adapter.etsicatalog.notification.model.PkgChangeNotification; +import org.onap.so.adapters.etsisol003adapter.etsicatalog.notification.model.PkgOnboardingNotification; +import org.onap.so.adapters.etsisol003adapter.pkgm.extclients.vnfm.notification.model.VnfPackageChangeNotification; +import org.onap.so.adapters.etsisol003adapter.pkgm.extclients.vnfm.notification.model.VnfPackageOnboardingNotification; +import org.onap.so.adapters.etsisol003adapter.pkgm.model.PkgmSubscriptionRequest; +import org.onap.so.adapters.etsisol003adapter.pkgm.model.SubscriptionsAuthentication; +import org.onap.so.adapters.etsisol003adapter.pkgm.model.SubscriptionsAuthentication.AuthTypeEnum; +import org.onap.so.adapters.etsisol003adapter.pkgm.rest.exceptions.AuthenticationTypeNotSupportedException; +import org.onap.so.adapters.etsisol003adapter.pkgm.rest.exceptions.ConversionFailedException; +import org.onap.so.adapters.etsisol003adapter.pkgm.rest.exceptions.NotificationTypeNotSupportedException; +import org.onap.so.adapters.etsisol003adapter.pkgm.rest.exceptions.SubscriptionNotFoundException; +import org.slf4j.Logger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.convert.ConversionService; +import org.springframework.stereotype.Service; + +/** + * Manages package management subscription notifications to the VNFMs + * + * @author Andrew Lamb (andrew.a.lamb@est.tech) + * + */ +@Service +public class NotificationManager { + + private static final Logger logger = getLogger(NotificationManager.class); + private final ConversionService conversionService; + private final SubscriptionManager subscriptionManager; + private final NotificationServiceProviderFactory notificationServiceProviderFactory; + + @Autowired + public NotificationManager(final SubscriptionManager subscriptionManager, final ConversionService conversionService, + final NotificationServiceProviderFactory notificationServiceProviderFactory) { + this.subscriptionManager = subscriptionManager; + this.conversionService = conversionService; + this.notificationServiceProviderFactory = notificationServiceProviderFactory; + } + + /** + * Process a subscription notification. Checks for a subscription request stored in the adapter and if there is, it + * sends the notification to the subscribed vnfm. + * + * @param notification the notification to send to the vnfm + * @param subscriptionId the id of the subscription request + * @return true if the notification is successfully sent + */ + public boolean processSubscriptionNotification(final Object notification, final String subscriptionId) { + final Optional optionalSubscription = + subscriptionManager.getSubscriptionRequest(subscriptionId); + if (optionalSubscription.isPresent()) { + final PkgmSubscriptionRequest subscriptionRequest = optionalSubscription.get(); + return notifyVnfm(subscriptionRequest, notification); + } + final String errorMessage = "No subscription found with subscriptionId " + subscriptionId + + ". Unable to forward notification to subscriber."; + logger.error(errorMessage); + throw new SubscriptionNotFoundException(errorMessage); + } + + private boolean notifyVnfm(final PkgmSubscriptionRequest subscriptionRequest, final Object notification) { + if (!(notification instanceof PkgOnboardingNotification) && !(notification instanceof PkgChangeNotification)) { + final String errorMessage = + "An error occurred. Notification type not supported for: " + notification.getClass(); + logger.error(errorMessage); + throw new NotificationTypeNotSupportedException(errorMessage); + } + + final SubscriptionsAuthentication subscriptionsAuthentication = subscriptionRequest.getAuthentication(); + final AuthTypeEnum authType = getAuthType(subscriptionsAuthentication.getAuthType()); + final NotificationServiceProvider sender = notificationServiceProviderFactory.getNotificationSender(authType); + + final Object vnfmNotificationObject = convertEtsiCatalogNotification(notification); + + if (sender.send(vnfmNotificationObject, subscriptionsAuthentication, subscriptionRequest.getCallbackUri())) { + logger.info("Notification delivered successfully {}", notification); + return true; + } + + logger.error("Failed to deliver notification."); + return false; + } + + private SubscriptionsAuthentication.AuthTypeEnum getAuthType(final List authTypes) { + if (authTypes.contains(SubscriptionsAuthentication.AuthTypeEnum.TLS_CERT)) { + return SubscriptionsAuthentication.AuthTypeEnum.TLS_CERT; + } + if (authTypes.contains(SubscriptionsAuthentication.AuthTypeEnum.OAUTH2_CLIENT_CREDENTIALS)) { + return SubscriptionsAuthentication.AuthTypeEnum.OAUTH2_CLIENT_CREDENTIALS; + } + if (authTypes.contains(SubscriptionsAuthentication.AuthTypeEnum.BASIC)) { + return SubscriptionsAuthentication.AuthTypeEnum.BASIC; + } + final String errorMessage = + "An error occurred. No supported authentication type provided in subscription request."; + logger.error(errorMessage); + throw new AuthenticationTypeNotSupportedException(errorMessage); + } + + private Object convertEtsiCatalogNotification(final Object etsiCatalogNotification) { + logger.info("Converting notification:\n {}", etsiCatalogNotification); + if (conversionService.canConvert(etsiCatalogNotification.getClass(), VnfPackageOnboardingNotification.class)) { + return conversionService.convert(etsiCatalogNotification, VnfPackageOnboardingNotification.class); + } else if (conversionService.canConvert(etsiCatalogNotification.getClass(), + VnfPackageChangeNotification.class)) { + return conversionService.convert(etsiCatalogNotification, VnfPackageChangeNotification.class); + } + final String errorMessage = "An error occurred. Unable to convert provided notification object."; + logger.error(errorMessage + "\n" + etsiCatalogNotification); + throw new ConversionFailedException(errorMessage); + } + +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/subscriptionmanagement/NotificationServiceProvider.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/subscriptionmanagement/NotificationServiceProvider.java new file mode 100644 index 0000000000..b2879ca84e --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/subscriptionmanagement/NotificationServiceProvider.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.so.adapters.etsisol003adapter.pkgm.subscriptionmanagement; + +import org.onap.so.adapters.etsisol003adapter.pkgm.model.SubscriptionsAuthentication; +import org.onap.so.adapters.etsisol003adapter.pkgm.model.SubscriptionsAuthentication.AuthTypeEnum; + +/** + * Interface which lays out requirements for a Notification Service Provider + * + * @author Waqas Ikram (waqas.ikram@est.tech) + * @author Andrew Lamb (andrew.a.lamb@est.tech) + */ +public interface NotificationServiceProvider { + + /** + * Method to send a notification to a uri, given the subscription authentication + * + * @param notification The notification to send + * @param subscriptionsAuthentication Object containing the authentication details + * @param callbackUri The uri to send the notification to + * @return true if notification is delivered successfully, otherwise false + */ + boolean send(final Object notification, final SubscriptionsAuthentication subscriptionsAuthentication, + final String callbackUri); + + /** + * Method to get the supported authorization type of the service provider + * + * @return the supported AuthTypeEnum + */ + AuthTypeEnum getAuthType(); + +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/subscriptionmanagement/NotificationServiceProviderFactory.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/subscriptionmanagement/NotificationServiceProviderFactory.java new file mode 100644 index 0000000000..3ff112fa5c --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/subscriptionmanagement/NotificationServiceProviderFactory.java @@ -0,0 +1,67 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.so.adapters.etsisol003adapter.pkgm.subscriptionmanagement; + +import static org.slf4j.LoggerFactory.getLogger; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.onap.so.adapters.etsisol003adapter.pkgm.model.SubscriptionsAuthentication.AuthTypeEnum; +import org.onap.so.adapters.etsisol003adapter.pkgm.rest.exceptions.AuthenticationTypeNotSupportedException; +import org.slf4j.Logger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +/** + * Factory to provide a notification services + * + * @author Waqas Ikram (waqas.ikram@est.tech) + * @author Andrew Lamb (andrew.a.lamb@est.tech) + */ +@Component +public class NotificationServiceProviderFactory { + + private static final Logger logger = getLogger(NotificationServiceProviderFactory.class); + private static final Map CACHE = new HashMap<>(); + + @Autowired + public NotificationServiceProviderFactory(final List services) { + for (final NotificationServiceProvider notificationServiceProvider : services) { + logger.debug("Adding {} of type {} to cache", notificationServiceProvider.getClass().getCanonicalName(), + notificationServiceProvider.getAuthType()); + CACHE.put(notificationServiceProvider.getAuthType(), notificationServiceProvider); + } + } + + /** + * Get a notification service for a given authorization type + * + * @param type the type of authentication required + * @return the notification service + */ + public NotificationServiceProvider getNotificationSender(final AuthTypeEnum type) { + final NotificationServiceProvider service = CACHE.get(type); + if (service == null) { + throw new AuthenticationTypeNotSupportedException("Unknown type: " + type); + } + return service; + } + +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/subscriptionmanagement/OAuthNotificationServiceProvider.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/subscriptionmanagement/OAuthNotificationServiceProvider.java new file mode 100644 index 0000000000..9b74d25a80 --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/subscriptionmanagement/OAuthNotificationServiceProvider.java @@ -0,0 +1,104 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.so.adapters.etsisol003adapter.pkgm.subscriptionmanagement; + +import static org.slf4j.LoggerFactory.getLogger; +import org.onap.so.adapters.etsisol003adapter.pkgm.model.SubscriptionsAuthentication; +import org.onap.so.adapters.etsisol003adapter.pkgm.model.SubscriptionsAuthentication.AuthTypeEnum; +import org.onap.so.adapters.etsisol003adapter.pkgm.rest.exceptions.InternalServerErrorException; +import org.onap.so.configuration.rest.BasicHttpHeadersProvider; +import org.onap.so.configuration.rest.HttpHeadersProvider; +import org.onap.so.rest.service.HttpRestServiceProvider; +import org.slf4j.Logger; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; + +/** + * @author Waqas Ikram (waqas.ikram@est.tech) + * @author Andrew Lamb (andrew.a.lamb@est.tech) + * + */ +@Service +public class OAuthNotificationServiceProvider extends AbstractNotificationServiceProvider + implements NotificationServiceProvider { + + private static final Logger logger = getLogger(OAuthNotificationServiceProvider.class); + + @Override + public boolean send(final Object notification, final SubscriptionsAuthentication subscriptionsAuthentication, + final String callbackUri) { + logger.info("Sending notification to uri: {}", callbackUri); + logger.info("Object: {}", notification); + final String token = getAccessToken(subscriptionsAuthentication); + + if (token == null) { + logger.error("Failed to get access token"); + return false; + } + + final HttpHeadersProvider httpHeadersProvider = getHttpHeadersProvider(token); + final HttpRestServiceProvider httpRestServiceProvider = getHttpRestServiceProvider(); + final ResponseEntity responseEntity = httpRestServiceProvider.postHttpRequest(notification, callbackUri, + httpHeadersProvider.getHttpHeaders(), Void.class); + if (responseEntity.getStatusCode().is2xxSuccessful()) { + logger.info("Notification sent successfully."); + return true; + } + + logger.error("Failed to send notification."); + return false; + } + + @Override + public AuthTypeEnum getAuthType() { + return AuthTypeEnum.OAUTH2_CLIENT_CREDENTIALS; + } + + private BasicHttpHeadersProvider getHttpHeadersProvider(final String token) { + final String authHeader = "Bearer " + token; + return new BasicHttpHeadersProvider(authHeader); + } + + private String getAccessToken(final SubscriptionsAuthentication subscriptionsAuthentication) { + logger.info("Requesting Access Token."); + + final String tokenEndpoint = subscriptionsAuthentication.getParamsOauth2ClientCredentials().getTokenEndpoint(); + + final HttpHeadersProvider httpHeadersProvider = getBasicHttpHeadersProviderWithBasicAuth( + subscriptionsAuthentication.getParamsOauth2ClientCredentials().getClientId(), + subscriptionsAuthentication.getParamsOauth2ClientCredentials().getClientPassword()); + + final HttpRestServiceProvider httpRestServiceProvider = getHttpRestServiceProvider(); + final ResponseEntity responseEntity = httpRestServiceProvider.postHttpRequest(null, + tokenEndpoint, httpHeadersProvider.getHttpHeaders(), OAuthTokenResponse.class); + if (responseEntity.getStatusCode().is2xxSuccessful()) { + if (responseEntity.getBody() != null) { + logger.info("Returning Access Token."); + return responseEntity.getBody().getAccessToken(); + } + } + + final String errorMessage = "An error occurred. Unable to retrieve OAuth Token from VNFM for notification."; + logger.error(errorMessage); + throw new InternalServerErrorException(errorMessage); + } + + +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/subscriptionmanagement/OAuthTokenResponse.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/subscriptionmanagement/OAuthTokenResponse.java new file mode 100644 index 0000000000..1adb42e479 --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/subscriptionmanagement/OAuthTokenResponse.java @@ -0,0 +1,56 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.so.adapters.etsisol003adapter.pkgm.subscriptionmanagement; + +import java.io.Serializable; +import javax.xml.bind.annotation.XmlElement; +import com.google.gson.annotations.SerializedName; + +/** + * @author Waqas Ikram (waqas.ikram@est.tech) + * @author Andrew Lamb (andrew.a.lamb@est.tech) + */ +public class OAuthTokenResponse implements Serializable { + + private static final long serialVersionUID = -6455742984985959926L; + + @XmlElement(name = "access_token") + @SerializedName("access_token") + private String accessToken; + + /** + * Get the Accees Token + * + * @return the Access Token + */ + public String getAccessToken() { + return accessToken; + } + + /** + * Set the Access Token + * + * @param accessToken + */ + public void setAccessToken(final String accessToken) { + this.accessToken = accessToken; + } + +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/subscriptionmanagement/SubscriptionManager.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/subscriptionmanagement/SubscriptionManager.java new file mode 100644 index 0000000000..d1ecc79373 --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/subscriptionmanagement/SubscriptionManager.java @@ -0,0 +1,209 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.pkgm.subscriptionmanagement; + +import static org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.model.SubscriptionAuthentication.AuthTypeEnum.BASIC; +import static org.slf4j.LoggerFactory.getLogger; +import java.net.URI; +import java.security.GeneralSecurityException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.onap.so.adapters.etsi.sol003.adapter.common.VnfmAdapterUrlProvider; +import org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.EtsiCatalogServiceProvider; +import org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.model.BasicAuth; +import org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.model.NsdmSubscription; +import org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.model.PkgmSubscription; +import org.onap.so.adapters.etsisol003adapter.pkgm.model.InlineResponse201; +import org.onap.so.adapters.etsisol003adapter.pkgm.model.PkgmSubscriptionRequest; +import org.onap.so.adapters.etsisol003adapter.pkgm.model.SubscriptionsLinks; +import org.onap.so.adapters.etsisol003adapter.pkgm.model.VnfPackagesLinksSelf; +import org.onap.so.adapters.etsisol003adapter.pkgm.rest.exceptions.ConversionFailedException; +import org.onap.so.adapters.etsisol003adapter.pkgm.rest.exceptions.InternalServerErrorException; +import org.onap.so.adapters.etsisol003adapter.pkgm.rest.exceptions.SubscriptionNotFoundException; +import org.onap.so.adapters.etsisol003adapter.pkgm.subscriptionmanagement.cache.PackageManagementCacheServiceProvider; +import org.slf4j.Logger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.convert.ConversionService; +import org.springframework.stereotype.Service; + +/** + * Manages package management subscriptions from the VNFMs + * + * @author Ronan Kenny (ronan.kenny@est.tech) + * @author Gareth Roper (gareth.roper@est.tech) + */ +@Service +public class SubscriptionManager { + + private static final Logger logger = getLogger(SubscriptionManager.class); + private final PackageManagementCacheServiceProvider packageManagementCacheServiceProvider; + private final ConversionService conversionService; + private final EtsiCatalogServiceProvider etsiCatalogServiceProvider; + private final VnfmAdapterUrlProvider vnfmAdapterUrlProvider; + + @Autowired + public SubscriptionManager(final PackageManagementCacheServiceProvider packageManagementCacheServiceProvider, + final ConversionService conversionService, final EtsiCatalogServiceProvider etsiCatalogServiceProvider, + final VnfmAdapterUrlProvider vnfmAdapterUrlProvider) { + this.packageManagementCacheServiceProvider = packageManagementCacheServiceProvider; + this.conversionService = conversionService; + this.etsiCatalogServiceProvider = etsiCatalogServiceProvider; + this.vnfmAdapterUrlProvider = vnfmAdapterUrlProvider; + } + + public Optional createSubscription(final PkgmSubscriptionRequest pkgmSubscriptionRequest) + throws GeneralSecurityException { + + final org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.model.PkgmSubscriptionRequest etsiCatalogManagerSubscriptionRequest = + buildEtsiCatalogManagerPkgmSubscriptionRequest(pkgmSubscriptionRequest); + + final Optional optionalEtsiCatalogManagerSubscription = + etsiCatalogServiceProvider.postSubscription(etsiCatalogManagerSubscriptionRequest); + + if (optionalEtsiCatalogManagerSubscription.isPresent()) { + final PkgmSubscription etsiCatalogManagerSubscription = optionalEtsiCatalogManagerSubscription.get(); + logger.debug("postPkgmSubscriptionRequest Response SubscriptionId: {}", + Objects.requireNonNull(etsiCatalogManagerSubscription.getId())); + final String subscriptionId = etsiCatalogManagerSubscription.getId(); + + packageManagementCacheServiceProvider.addSubscription(subscriptionId, pkgmSubscriptionRequest); + + final InlineResponse201 response = new InlineResponse201(); + response.setId(subscriptionId); + response.setFilter(pkgmSubscriptionRequest.getFilter()); + response.setCallbackUri(vnfmAdapterUrlProvider.getSubscriptionUriString(subscriptionId)); + response.setLinks(new SubscriptionsLinks() + .self(new VnfPackagesLinksSelf().href(getSubscriptionUri(subscriptionId).toString()))); + + return Optional.of(response); + } + throw new InternalServerErrorException( + "Received empty response from POST to ETSI Catalog Manager Subscription Endpoint."); + } + + public Optional getSubscriptionId(final PkgmSubscriptionRequest pkgmSubscriptionRequest) { + return packageManagementCacheServiceProvider.getSubscriptionId(pkgmSubscriptionRequest); + } + + public Optional getSubscription(final String subscriptionId) { + + logger.debug("Checking if subscrition with id: {} exists in ETSI Catalog Manager", subscriptionId); + final Optional etsiCatalogSubscriptionOption = + etsiCatalogServiceProvider.getSubscription(subscriptionId); + + if (!etsiCatalogSubscriptionOption.isPresent()) { + logger.debug("Unable to find subscription in ETSI Catalog Manager using id: {}", subscriptionId); + if (packageManagementCacheServiceProvider.getSubscription(subscriptionId).isPresent()) { + logger.debug("will remove subcription with id: {} from local cache", subscriptionId); + packageManagementCacheServiceProvider.deleteSubscription(subscriptionId); + } + } + + final Optional optional = + packageManagementCacheServiceProvider.getSubscription(subscriptionId); + if (optional.isPresent()) { + final PkgmSubscriptionRequest subscription = optional.get(); + return Optional.of(getInlineResponse2002(subscriptionId, subscription)); + } + return Optional.empty(); + } + + public List getSubscriptions() { + final Map subscriptions = + packageManagementCacheServiceProvider.getSubscriptions(); + final List response = new ArrayList<>(); + subscriptions.forEach((key, value) -> { + final Optional optional = getSubscription(key); + if (optional.isPresent()) { + response.add(optional.get()); + } + }); + return response; + } + + public boolean deleteSubscription(final String subscriptionId) { + if (packageManagementCacheServiceProvider.getSubscription(subscriptionId).isPresent()) { + try { + if (etsiCatalogServiceProvider.deleteSubscription(subscriptionId)) { + return packageManagementCacheServiceProvider.deleteSubscription(subscriptionId); + } + } catch (final SubscriptionNotFoundException subscriptionNotFoundException) { + logger.error( + "Unable to find subscription in ETSI Catalog Manager using id: {} will delete it from local cache", + subscriptionId); + return packageManagementCacheServiceProvider.deleteSubscription(subscriptionId); + } + } + return false; + } + + public URI getSubscriptionUri(final String subscriptionId) { + return vnfmAdapterUrlProvider.getSubscriptionUri(subscriptionId); + } + + public Optional getSubscriptionRequest(final String subscriptionId) { + return packageManagementCacheServiceProvider.getSubscription(subscriptionId); + } + + private InlineResponse201 getInlineResponse2002(final String id, final PkgmSubscriptionRequest subscription) { + return new InlineResponse201().id(id).filter(subscription.getFilter()) + .callbackUri(subscription.getCallbackUri()); + } + + private org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.model.PkgmSubscriptionRequest buildEtsiCatalogManagerPkgmSubscriptionRequest( + final PkgmSubscriptionRequest pkgmSubscriptionRequest) throws GeneralSecurityException { + + final org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.model.PkgmSubscriptionRequest etsiCatalogManagerSubscriptionRequest; + try { + etsiCatalogManagerSubscriptionRequest = conversionService.convert(pkgmSubscriptionRequest, + org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.model.PkgmSubscriptionRequest.class); + } catch (final org.springframework.core.convert.ConversionException conversionException) { + logger.error(conversionException.getMessage()); + throw new ConversionFailedException( + "Could not convert Sol003 PkgmSubscriptionRequest to ETSI-Catalog Manager PkgmSubscriptionRequest"); + } catch (final Exception exception) { + logger.error(exception.getMessage()); + throw new InternalServerErrorException( + "Could not convert Sol003 PkgmSubscriptionRequest to ETSI-Catalog Manager PkgmSubscriptionRequest"); + } + + if (etsiCatalogManagerSubscriptionRequest != null) { + etsiCatalogManagerSubscriptionRequest + .setCallbackUri(vnfmAdapterUrlProvider.getEtsiSubscriptionNotificationBaseUrl()); + + final ImmutablePair immutablePair = vnfmAdapterUrlProvider.getDecryptAuth(); + if (!immutablePair.equals(ImmutablePair.nullPair())) { + etsiCatalogManagerSubscriptionRequest.setAuthentication( + new org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.model.SubscriptionAuthentication() + .addAuthTypeItem(BASIC).paramsBasic(new BasicAuth().userName(immutablePair.getLeft()) + .password(immutablePair.getRight()))); + } + return etsiCatalogManagerSubscriptionRequest; + } + throw new ConversionFailedException( + "Failed to convert Sol003 PkgmSubscriptionRequest to ETSI-Catalog Manager PkgmSubscriptionRequest"); + } + +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/subscriptionmanagement/TlsNotificationServiceProvider.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/subscriptionmanagement/TlsNotificationServiceProvider.java new file mode 100644 index 0000000000..b27345d35c --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/subscriptionmanagement/TlsNotificationServiceProvider.java @@ -0,0 +1,57 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.so.adapters.etsisol003adapter.pkgm.subscriptionmanagement; + +import static org.slf4j.LoggerFactory.getLogger; +import org.onap.so.adapters.etsisol003adapter.pkgm.model.SubscriptionsAuthentication; +import org.onap.so.adapters.etsisol003adapter.pkgm.model.SubscriptionsAuthentication.AuthTypeEnum; +import org.onap.so.adapters.etsisol003adapter.pkgm.rest.exceptions.AuthenticationTypeNotSupportedException; +import org.slf4j.Logger; +import org.springframework.stereotype.Service; + +/** + * + * @author Waqas Ikram (waqas.ikram@est.tech) + * @author Andrew Lamb (andrew.a.lamb@est.tech) + */ +@Service +public class TlsNotificationServiceProvider extends AbstractNotificationServiceProvider + implements NotificationServiceProvider { + + private static final Logger logger = getLogger(TlsNotificationServiceProvider.class); + + @Override + public boolean send(final Object notification, final SubscriptionsAuthentication subscriptionsAuthentication, + final String callbackUri) { + final String errorMessage = "An error occurred. Authentication type " + + subscriptionsAuthentication.getAuthType().toString() + " not currently supported."; + logger.error(errorMessage); + throw new AuthenticationTypeNotSupportedException(errorMessage); + } + + + @Override + public AuthTypeEnum getAuthType() { + return AuthTypeEnum.TLS_CERT; + } + + + +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/subscriptionmanagement/cache/AbstractCacheServiceProvider.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/subscriptionmanagement/cache/AbstractCacheServiceProvider.java new file mode 100644 index 0000000000..ea780f0520 --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/subscriptionmanagement/cache/AbstractCacheServiceProvider.java @@ -0,0 +1,47 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.pkgm.subscriptionmanagement.cache; + +import org.springframework.cache.Cache; +import org.springframework.cache.CacheManager; + +/** + * @author Ronan Kenny (ronan.kenny@est.tech) + * @author Gareth Roper (gareth.roper@est.tech) + */ +public abstract class AbstractCacheServiceProvider { + + private final CacheManager cacheManager; + private final String cacheName; + + public AbstractCacheServiceProvider(final String cacheName, final CacheManager cacheManager) { + this.cacheName = cacheName; + this.cacheManager = cacheManager; + } + + public Cache getCache() { + final Cache cache = cacheManager.getCache(cacheName); + if (cache == null) { + throw new CacheNotFoundException("Unable to find " + cacheName + " cache"); + } + return cache; + } +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/subscriptionmanagement/cache/CacheManagerConfiguration.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/subscriptionmanagement/cache/CacheManagerConfiguration.java new file mode 100644 index 0000000000..1e07332fc5 --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/subscriptionmanagement/cache/CacheManagerConfiguration.java @@ -0,0 +1,50 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.pkgm.subscriptionmanagement.cache; + +import java.util.Arrays; +import org.onap.so.adapters.etsisol003adapter.pkgm.PackageManagementConstants; +import org.springframework.cache.Cache; +import org.springframework.cache.CacheManager; +import org.springframework.cache.concurrent.ConcurrentMapCache; +import org.springframework.cache.support.SimpleCacheManager; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * @author Ronan Kenny (ronan.kenny@est.tech) + * @author Gareth Roper (gareth.roper@est.tech) + */ +@Configuration +public class CacheManagerConfiguration { + + @Bean + public CacheManager cacheManager() { + final SimpleCacheManager manager = new SimpleCacheManager(); + manager.setCaches(Arrays.asList(getCache(PackageManagementConstants.PACKAGE_MANAGEMENT_SUBSCRIPTION_CACHE))); + + return manager; + } + + private Cache getCache(final String name) { + return new ConcurrentMapCache(name); + } +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/subscriptionmanagement/cache/CacheNotFoundException.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/subscriptionmanagement/cache/CacheNotFoundException.java new file mode 100644 index 0000000000..ae209ea31f --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/subscriptionmanagement/cache/CacheNotFoundException.java @@ -0,0 +1,37 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.pkgm.subscriptionmanagement.cache; + +/** + * Exception for failure to find the cache. + * + * @author Ronan Kenny (ronan.kenny@est.tech) + * @author Gareth Roper (gareth.roper@est.tech) + * + */ +public class CacheNotFoundException extends RuntimeException { + + private static final long serialVersionUID = -372361485260755367L; + + public CacheNotFoundException(final String message) { + super(message); + } +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/subscriptionmanagement/cache/PackageManagementCacheServiceProvider.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/subscriptionmanagement/cache/PackageManagementCacheServiceProvider.java new file mode 100644 index 0000000000..553e156b18 --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/subscriptionmanagement/cache/PackageManagementCacheServiceProvider.java @@ -0,0 +1,74 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.pkgm.subscriptionmanagement.cache; + +import java.util.Map; +import java.util.Optional; +import org.onap.so.adapters.etsisol003adapter.pkgm.model.PkgmSubscriptionRequest; + +/** + * Interface which provides methods for communicating with the cache + * + * @author Ronan Kenny (ronan.kenny@est.tech) + * @author Gareth Roper (gareth.roper@est.tech) + * + */ +public interface PackageManagementCacheServiceProvider { + + /** + * Checks cache if subscription request Id is already present. If not, it adds the subscription to the cache. + * + * @param subscriptionId + * @param pkgmSubscriptionRequest + */ + void addSubscription(final String subscriptionId, final PkgmSubscriptionRequest pkgmSubscriptionRequest); + + /** + * Gets individual subscription from cache + * + * @param subscriptionId + * @return > + */ + Optional getSubscription(final String subscriptionId); + + /** + * Gets Map of subscriptions from cache + * + * @return Map> + */ + Map getSubscriptions(); + + /** + * Delete subscription from cache + * + * @param subscriptionId + * @return Boolean + */ + boolean deleteSubscription(final String subscriptionId); + + /** + * Checks if subscription exists in cache and return its subscriptionId + * + * @param pkgmSubscriptionRequest + * @return Subscription Id + */ + Optional getSubscriptionId(final PkgmSubscriptionRequest pkgmSubscriptionRequest); +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/subscriptionmanagement/cache/PackageManagementCacheServiceProviderImpl.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/subscriptionmanagement/cache/PackageManagementCacheServiceProviderImpl.java new file mode 100644 index 0000000000..3a25570637 --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/pkgm/subscriptionmanagement/cache/PackageManagementCacheServiceProviderImpl.java @@ -0,0 +1,119 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.pkgm.subscriptionmanagement.cache; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; +import org.onap.so.adapters.etsisol003adapter.pkgm.PackageManagementConstants; +import org.onap.so.adapters.etsisol003adapter.pkgm.model.PkgmSubscriptionRequest; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cache.Cache; +import org.springframework.cache.CacheManager; +import org.springframework.stereotype.Service; + +/** + * Implementation which provides methods for communicating with the cache + * + * @author Ronan Kenny (ronan.kenny@est.tech) + * @author Gareth Roper (gareth.roper@est.tech) + */ +@Service +public class PackageManagementCacheServiceProviderImpl extends AbstractCacheServiceProvider + implements PackageManagementCacheServiceProvider { + + private static final Logger LOGGER = LoggerFactory.getLogger(PackageManagementCacheServiceProviderImpl.class); + + @Autowired + public PackageManagementCacheServiceProviderImpl(final CacheManager cacheManager) { + super(PackageManagementConstants.PACKAGE_MANAGEMENT_SUBSCRIPTION_CACHE, cacheManager); + } + + @Override + public void addSubscription(final String subscriptionId, final PkgmSubscriptionRequest pkgmSubscriptionRequest) { + LOGGER.debug("Adding {} to cache with subscription id: {}", pkgmSubscriptionRequest, subscriptionId); + getCache().put(subscriptionId, pkgmSubscriptionRequest); + } + + @Override + public Optional getSubscription(final String subscriptionId) { + LOGGER.debug("Getting subscription from cache using Id: {}", subscriptionId); + final Cache cache = getCache(); + final PkgmSubscriptionRequest cacheValue = cache.get(subscriptionId, PkgmSubscriptionRequest.class); + if (cacheValue != null) { + return Optional.of(cacheValue); + } + LOGGER.error("Unable to find Subscription in cache using Id: {}", subscriptionId); + return Optional.empty(); + } + + @Override + public Map getSubscriptions() { + LOGGER.info("Getting all subscriptions from cache"); + final Cache cache = getCache(); + + final Object nativeCache = cache.getNativeCache(); + if (nativeCache instanceof ConcurrentHashMap) { + @SuppressWarnings("unchecked") + final ConcurrentHashMap concurrentHashMap = (ConcurrentHashMap) nativeCache; + final Map result = new HashMap<>(); + concurrentHashMap.keySet().forEach(key -> { + final Optional optional = getSubscription(key.toString()); + optional.ifPresent(pkgmSubscriptionRequest -> result.put(key.toString(), pkgmSubscriptionRequest)); + }); + return result; + } + LOGGER.error("Unable to find Subscriptions in cache"); + return Collections.emptyMap(); + } + + @Override + public boolean deleteSubscription(final String subscriptionId) { + final Cache cache = getCache(); + final Optional optional = getSubscription(subscriptionId); + if (optional.isPresent()) { + cache.evict(subscriptionId); + return true; + } + return false; + } + + @Override + public Optional getSubscriptionId(final PkgmSubscriptionRequest pkgmSubscriptionRequest) { + final Cache cache = getCache(); + final Object nativeCache = cache.getNativeCache(); + if (nativeCache instanceof ConcurrentHashMap) { + @SuppressWarnings("unchecked") + final ConcurrentHashMap concurrentHashMap = (ConcurrentHashMap) nativeCache; + final Optional> optional = concurrentHashMap.entrySet().stream() + .filter(entry -> entry.getValue().equals(pkgmSubscriptionRequest)).findAny(); + if (optional.isPresent()) { + return Optional.of(optional.get().getKey().toString()); + } + } + return Optional.empty(); + } +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/test/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/EtsiSubscriptionNotificationControllerTest.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/test/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/EtsiSubscriptionNotificationControllerTest.java deleted file mode 100644 index f158a9e1de..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/test/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/EtsiSubscriptionNotificationControllerTest.java +++ /dev/null @@ -1,591 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2020 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.rest; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.onap.so.adapters.etsi.sol003.adapter.common.CommonConstants.ETSI_SUBSCRIPTION_NOTIFICATION_CONTROLLER_BASE_URL; -import static org.onap.so.client.RestTemplateConfig.CONFIGURABLE_REST_TEMPLATE; -import static org.springframework.test.annotation.DirtiesContext.ClassMode.BEFORE_CLASS; -import static org.springframework.test.web.client.match.MockRestRequestMatchers.header; -import static org.springframework.test.web.client.match.MockRestRequestMatchers.jsonPath; -import static org.springframework.test.web.client.match.MockRestRequestMatchers.method; -import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; -import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus; -import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; -import java.net.URI; -import java.time.LocalDateTime; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.onap.so.adapters.etsi.sol003.adapter.etsicatalog.notification.model.NOTIFICATIONLINKSERIALIZER; -import org.onap.so.adapters.etsi.sol003.adapter.etsicatalog.notification.model.PkgChangeNotification; -import org.onap.so.adapters.etsi.sol003.adapter.etsicatalog.notification.model.PkgOnboardingNotification; -import org.onap.so.adapters.etsi.sol003.adapter.etsicatalog.notification.model.PkgmLinks; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.JSON; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.PackageManagementConstants; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.model.ProblemDetails; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.vnfm.notification.model.VnfPackageChangeNotification; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.vnfm.notification.model.VnfPackageOnboardingNotification; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.model.PkgmSubscriptionRequest; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.model.SubscriptionsAuthentication; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.model.SubscriptionsAuthenticationParamsBasic; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.model.SubscriptionsAuthenticationParamsOauth2ClientCredentials; -import org.onap.so.configuration.rest.BasicHttpHeadersProvider; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.boot.web.client.RestTemplateBuilder; -import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.cache.Cache; -import org.springframework.cache.CacheManager; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpMethod; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.http.converter.json.GsonHttpMessageConverter; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.client.MockRestServiceServer; -import org.springframework.web.client.RestTemplate; -import com.google.gson.Gson; - -/** - * @author Andrew Lamb (andrew.a.lamb@est.tech) - * - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = TestApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) -@ActiveProfiles("test") -@DirtiesContext(classMode = BEFORE_CLASS) -public class EtsiSubscriptionNotificationControllerTest { - - @LocalServerPort - private int port; - - private static final URI CALLBACK_URI = URI.create("http://test_callback_uri/notification"); - private static final String TOKEN_ENDPOINT = "http://test_token_endpoint_uri/"; - private static final String TOKEN = "dXNlcm5hbWU6cGFzc3dvcmQ=......"; - private static final String JSON_TOKEN = "{\"access_token\":\"" + TOKEN + "\"}"; - private static final String LOCALHOST_URL = "http://localhost:"; - private static final String NOTIFICATION_BASE_URL = - ETSI_SUBSCRIPTION_NOTIFICATION_CONTROLLER_BASE_URL + "/notification"; - private static final String USERNAME = "username"; - private static final String PASSWORD = "password"; - private static final String EXPECTED_BASIC_AUTHORIZATION = "Basic dXNlcm5hbWU6cGFzc3dvcmQ="; - private static final String EXPECTED_OAUTH_AUTHORIZATION = "Bearer " + TOKEN; - private static final String NOTIFICATION_ID = "NOTIFICATION_ID"; - private static final String SUBSCRIPTION_ID = "SUBSCRIPTION_ID"; - private static final String TIME_STAMP_STRING_EXPECTED_FROM_ETSI_CATALOG = "2020-01-01 01:01:01"; - private static final java.time.LocalDateTime TIMESTAMP = java.time.LocalDateTime.of(2020, 1, 1, 1, 1, 1, 1); - private static final String VNFPKG_ID = UUID.randomUUID().toString(); - private static final String VNFD_ID = UUID.randomUUID().toString(); - private static final String EXPECTED_VNF_PACKAGE_HREF = - "https://so-vnfm-adapter.onap:30406/so/vnfm-adapter/v1/vnfpkgm/v1/vnf_packages/" + VNFPKG_ID; - private static final String EXPECTED_SUBSCRIPTION_HREF = - "https://so-vnfm-adapter.onap:30406/so/vnfm-adapter/v1/vnfpkgm/v1/subscriptions/" + SUBSCRIPTION_ID; - - - private BasicHttpHeadersProvider basicHttpHeadersProvider; - - @Autowired - @Qualifier(CONFIGURABLE_REST_TEMPLATE) - private RestTemplate restTemplate; - private MockRestServiceServer mockRestServiceServer; - - private TestRestTemplate testRestTemplate; - - @Autowired - private CacheManager cacheServiceProvider; - private Cache cache; - - @Before - public void setUp() { - mockRestServiceServer = MockRestServiceServer.bindTo(restTemplate).build(); - basicHttpHeadersProvider = new BasicHttpHeadersProvider(); - cache = cacheServiceProvider.getCache(PackageManagementConstants.PACKAGE_MANAGEMENT_SUBSCRIPTION_CACHE); - cache.clear(); - - final Gson gson = JSON.createGson().registerTypeAdapter(LocalDateTime.class, - new EtsiSubscriptionNotificationController.LocalDateTimeTypeAdapter()).create(); - testRestTemplate = new TestRestTemplate( - new RestTemplateBuilder().additionalMessageConverters(new GsonHttpMessageConverter(gson))); - } - - - @After - public void tearDown() { - mockRestServiceServer.reset(); - cache.clear(); - } - - @Test - public void testSubscriptionNotificationEndPoint_ReturnsNoContent() { - final ResponseEntity response = sendHttpGet(NOTIFICATION_BASE_URL); - assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode()); - } - - @Test - public void testOnboardingNotificationSentOnToVnfmCallbackUri_SubscriptionRequestInCache_Success() { - final PkgmSubscriptionRequest subscriptionRequest = - buildPkgmSubscriptionRequest(SubscriptionsAuthentication.AuthTypeEnum.BASIC); - cache.put(SUBSCRIPTION_ID, subscriptionRequest); - final PkgOnboardingNotification notification = buildPkgOnboardingNotification(); - - mockRestServiceServer.expect(requestTo(CALLBACK_URI)).andExpect(method(HttpMethod.POST)) - .andExpect(jsonPath("$.id").value(NOTIFICATION_ID)) - .andExpect(jsonPath("$.notificationType") - .value(VnfPackageOnboardingNotification.NotificationTypeEnum.VNFPACKAGEONBOARDINGNOTIFICATION - .toString())) - .andExpect(jsonPath("$.subscriptionId").value(SUBSCRIPTION_ID)) - .andExpect(jsonPath("$.timeStamp").value(TIME_STAMP_STRING_EXPECTED_FROM_ETSI_CATALOG)) - .andExpect(jsonPath("$.vnfPkgId").value(VNFPKG_ID)).andExpect(jsonPath("$.vnfdId").value(VNFD_ID)) - .andExpect(jsonPath("$._links") - .value(buildPkgmLinks(EXPECTED_VNF_PACKAGE_HREF, EXPECTED_SUBSCRIPTION_HREF))) - .andExpect(header("Authorization", EXPECTED_BASIC_AUTHORIZATION)).andRespond(withSuccess()); - - final ResponseEntity response = sendHttpPost(notification); - - assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode()); - } - - @Test - public void testOnboardingNotificationNotSentOnToVnfmCallbackUri_SubscriptionRequestNotInCache_Fail() { - final PkgOnboardingNotification notification = buildPkgOnboardingNotification(); - final ResponseEntity response = sendHttpPost(notification); - - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); - assertTrue(response.getBody() instanceof ProblemDetails); - - final ProblemDetails problemDetails = (ProblemDetails) response.getBody(); - final String errorMessage = "No subscription found with subscriptionId " + SUBSCRIPTION_ID - + ". Unable to forward notification to subscriber."; - - assertEquals(errorMessage, problemDetails.getDetail()); - } - - @Test - public void testOnboardingNotificationSentOnToVnfmCallbackUri_BadRequestResponseFromCallbackUri_Fail() { - final PkgmSubscriptionRequest subscriptionRequest = - buildPkgmSubscriptionRequest(SubscriptionsAuthentication.AuthTypeEnum.BASIC); - cache.put(SUBSCRIPTION_ID, subscriptionRequest); - final PkgOnboardingNotification notification = buildPkgOnboardingNotification(); - - mockRestServiceServer.expect(requestTo(CALLBACK_URI)).andExpect(method(HttpMethod.POST)) - .andRespond(withStatus(HttpStatus.BAD_REQUEST)); - - final ResponseEntity response = sendHttpPost(notification); - - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); - assertTrue(response.getBody() instanceof ProblemDetails); - - final ProblemDetails problemDetails = (ProblemDetails) response.getBody(); - final String errorMessage = "An error occurred. Sending of notification to VNFM failed with response: " - + HttpStatus.BAD_REQUEST + ".\n" + "No result found for given url: " + CALLBACK_URI; - - assertEquals(errorMessage, problemDetails.getDetail()); - } - - @Test - public void testOnboardingNotificationSentOnToVnfmCallbackUri_301MovedPermanentlyResponseFromCallbackUri_Fail() { - final PkgmSubscriptionRequest subscriptionRequest = - buildPkgmSubscriptionRequest(SubscriptionsAuthentication.AuthTypeEnum.BASIC); - cache.put(SUBSCRIPTION_ID, subscriptionRequest); - final PkgOnboardingNotification notification = buildPkgOnboardingNotification(); - - mockRestServiceServer.expect(requestTo(CALLBACK_URI)).andExpect(method(HttpMethod.POST)) - .andRespond(withStatus(HttpStatus.MOVED_PERMANENTLY)); - - final ResponseEntity response = sendHttpPost(notification); - - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); - assertTrue(response.getBody() instanceof ProblemDetails); - - final ProblemDetails problemDetails = (ProblemDetails) response.getBody(); - final String errorMessage = "An error occurred. Sending of notification to VNFM failed."; - - assertEquals(errorMessage, problemDetails.getDetail()); - } - - @Test - public void testOnboardingNotificationSentOnToVnfmCallbackUri_NotFoundResponseFromCallbackUri_Fail() { - final PkgmSubscriptionRequest subscriptionRequest = - buildPkgmSubscriptionRequest(SubscriptionsAuthentication.AuthTypeEnum.BASIC); - cache.put(SUBSCRIPTION_ID, subscriptionRequest); - final PkgOnboardingNotification notification = buildPkgOnboardingNotification(); - - mockRestServiceServer.expect(requestTo(CALLBACK_URI)).andExpect(method(HttpMethod.POST)) - .andRespond(withStatus(HttpStatus.NOT_FOUND)); - - final ResponseEntity response = sendHttpPost(notification); - - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); - assertTrue(response.getBody() instanceof ProblemDetails); - - final ProblemDetails problemDetails = (ProblemDetails) response.getBody(); - final String errorMessage = "An error occurred. Sending of notification to VNFM failed with response: " - + HttpStatus.NOT_FOUND + ".\n" + "No result found for given url: " + CALLBACK_URI; - - assertEquals(errorMessage, problemDetails.getDetail()); - } - - @Test - public void testOnboardingNotificationSentOnToVnfmCallbackUri_InternalServerErrorResponseFromCallbackUri_Fail() { - final PkgmSubscriptionRequest subscriptionRequest = - buildPkgmSubscriptionRequest(SubscriptionsAuthentication.AuthTypeEnum.BASIC); - cache.put(SUBSCRIPTION_ID, subscriptionRequest); - final PkgOnboardingNotification notification = buildPkgOnboardingNotification(); - - mockRestServiceServer.expect(requestTo(CALLBACK_URI)).andExpect(method(HttpMethod.POST)) - .andRespond(withStatus(HttpStatus.INTERNAL_SERVER_ERROR)); - - final ResponseEntity response = sendHttpPost(notification); - - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); - assertTrue(response.getBody() instanceof ProblemDetails); - - final ProblemDetails problemDetails = (ProblemDetails) response.getBody(); - final String errorMessage = "An error occurred. Sending of notification to VNFM failed with response: " - + HttpStatus.INTERNAL_SERVER_ERROR.value() + ".\n" + "Unable to invoke HTTP POST using URL: " - + CALLBACK_URI; - - assertEquals(errorMessage, problemDetails.getDetail()); - } - - @Test - public void testChangeNotificationSentOnToVnfmCallbackUri_SubscriptionRequestInCache_Success() { - final PkgmSubscriptionRequest subscriptionRequest = - buildPkgmSubscriptionRequest(SubscriptionsAuthentication.AuthTypeEnum.BASIC); - cache.put(SUBSCRIPTION_ID, subscriptionRequest); - final PkgChangeNotification notification = buildPkgChangeNotification(); - - mockRestServiceServer.expect(requestTo(CALLBACK_URI)).andExpect(method(HttpMethod.POST)) - .andExpect(jsonPath("$.id").value(NOTIFICATION_ID)) - .andExpect(jsonPath("$.notificationType").value( - VnfPackageChangeNotification.NotificationTypeEnum.VNFPACKAGECHANGENOTIFICATION.getValue())) - .andExpect(jsonPath("$.subscriptionId").value(SUBSCRIPTION_ID)) - .andExpect(jsonPath("$.timeStamp").value(TIME_STAMP_STRING_EXPECTED_FROM_ETSI_CATALOG)) - .andExpect(jsonPath("$.vnfPkgId").value(VNFPKG_ID)).andExpect(jsonPath("$.vnfdId").value(VNFD_ID)) - .andExpect( - jsonPath("$.changeType").value(PkgChangeNotification.ChangeTypeEnum.OP_STATE_CHANGE.toString())) - .andExpect(jsonPath("$.operationalState") - .value(PkgChangeNotification.OperationalStateEnum.ENABLED.toString())) - .andExpect(jsonPath("$._links") - .value(buildPkgmLinks(EXPECTED_VNF_PACKAGE_HREF, EXPECTED_SUBSCRIPTION_HREF))) - .andExpect(header("Authorization", EXPECTED_BASIC_AUTHORIZATION)).andRespond(withSuccess()); - - final ResponseEntity response = sendHttpPost(notification); - - assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode()); - } - - @Test - public void testChangeNotificationNotSentOnToVnfmCallbackUri_SubscriptionRequestNotInCache_Fail() { - final PkgChangeNotification notification = buildPkgChangeNotification(); - final ResponseEntity response = sendHttpPost(notification); - - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); - assertTrue(response.getBody() instanceof ProblemDetails); - - final ProblemDetails problemDetails = (ProblemDetails) response.getBody(); - final String errorMessage = "No subscription found with subscriptionId " + SUBSCRIPTION_ID - + ". Unable to forward notification to subscriber."; - - assertEquals(errorMessage, problemDetails.getDetail()); - } - - @Test - public void testChangeNotificationSentOnToVnfmCallbackUri_BadRequestResponseFromCallbackUri_Fail() { - final PkgmSubscriptionRequest subscriptionRequest = - buildPkgmSubscriptionRequest(SubscriptionsAuthentication.AuthTypeEnum.BASIC); - cache.put(SUBSCRIPTION_ID, subscriptionRequest); - final PkgChangeNotification notification = buildPkgChangeNotification(); - - mockRestServiceServer.expect(requestTo(CALLBACK_URI)).andExpect(method(HttpMethod.POST)) - .andRespond(withStatus(HttpStatus.BAD_REQUEST)); - - final ResponseEntity response = sendHttpPost(notification); - - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); - assertTrue(response.getBody() instanceof ProblemDetails); - - final ProblemDetails problemDetails = (ProblemDetails) response.getBody(); - final String errorMessage = "An error occurred. Sending of notification to VNFM failed with response: " - + HttpStatus.BAD_REQUEST + ".\n" + "No result found for given url: " + CALLBACK_URI; - - assertEquals(errorMessage, problemDetails.getDetail()); - } - - @Test - public void testChangeNotificationSentOnToVnfmCallbackUri_NotFoundResponseFromCallbackUri_Fail() { - final PkgmSubscriptionRequest subscriptionRequest = - buildPkgmSubscriptionRequest(SubscriptionsAuthentication.AuthTypeEnum.BASIC); - cache.put(SUBSCRIPTION_ID, subscriptionRequest); - final PkgChangeNotification notification = buildPkgChangeNotification(); - - mockRestServiceServer.expect(requestTo(CALLBACK_URI)).andExpect(method(HttpMethod.POST)) - .andRespond(withStatus(HttpStatus.NOT_FOUND)); - - final ResponseEntity response = sendHttpPost(notification); - - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); - assertTrue(response.getBody() instanceof ProblemDetails); - - final ProblemDetails problemDetails = (ProblemDetails) response.getBody(); - final String errorMessage = "An error occurred. Sending of notification to VNFM failed with response: " - + HttpStatus.NOT_FOUND + ".\n" + "No result found for given url: " + CALLBACK_URI; - - assertEquals(errorMessage, problemDetails.getDetail()); - } - - @Test - public void testChangeNotificationSentOnToVnfmCallbackUri_InternalServerErrorResponseFromCallbackUri_Fail() { - final PkgmSubscriptionRequest subscriptionRequest = - buildPkgmSubscriptionRequest(SubscriptionsAuthentication.AuthTypeEnum.BASIC); - cache.put(SUBSCRIPTION_ID, subscriptionRequest); - final PkgChangeNotification notification = buildPkgChangeNotification(); - - mockRestServiceServer.expect(requestTo(CALLBACK_URI)).andExpect(method(HttpMethod.POST)) - .andRespond(withStatus(HttpStatus.INTERNAL_SERVER_ERROR)); - - final ResponseEntity response = sendHttpPost(notification); - - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); - assertTrue(response.getBody() instanceof ProblemDetails); - - final ProblemDetails problemDetails = (ProblemDetails) response.getBody(); - final String errorMessage = "An error occurred. Sending of notification to VNFM failed with response: " - + HttpStatus.INTERNAL_SERVER_ERROR.value() + ".\n" + "Unable to invoke HTTP POST using URL: " - + CALLBACK_URI; - - assertEquals(errorMessage, problemDetails.getDetail()); - } - - @Test - public void testNotificationSentOnToVnfm_BasicAuthUserPasswordAuthorized_Success() { - final PkgmSubscriptionRequest subscriptionRequest = - buildPkgmSubscriptionRequest(SubscriptionsAuthentication.AuthTypeEnum.BASIC); - cache.put(SUBSCRIPTION_ID, subscriptionRequest); - final PkgOnboardingNotification notification = buildPkgOnboardingNotification(); - - mockRestServiceServer.expect(requestTo(CALLBACK_URI)).andExpect(method(HttpMethod.POST)) - .andExpect(jsonPath("$.id").value(NOTIFICATION_ID)) - .andExpect(jsonPath("$.notificationType") - .value(VnfPackageOnboardingNotification.NotificationTypeEnum.VNFPACKAGEONBOARDINGNOTIFICATION - .toString())) - .andExpect(jsonPath("$.subscriptionId").value(SUBSCRIPTION_ID)) - .andExpect(jsonPath("$.timeStamp").value(TIME_STAMP_STRING_EXPECTED_FROM_ETSI_CATALOG)) - .andExpect(jsonPath("$.vnfPkgId").value(VNFPKG_ID)).andExpect(jsonPath("$.vnfdId").value(VNFD_ID)) - .andExpect(jsonPath("$._links") - .value(buildPkgmLinks(EXPECTED_VNF_PACKAGE_HREF, EXPECTED_SUBSCRIPTION_HREF))) - .andExpect(header("Authorization", EXPECTED_BASIC_AUTHORIZATION)).andRespond(withSuccess()); - - final ResponseEntity response = sendHttpPost(notification); - - assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode()); - } - - @Test - public void testNotificationSentOnToVnfm_BasicAuthUserPasswordNotAuthorized_Fail() { - final PkgmSubscriptionRequest subscriptionRequest = - buildPkgmSubscriptionRequest(SubscriptionsAuthentication.AuthTypeEnum.BASIC); - cache.put(SUBSCRIPTION_ID, subscriptionRequest); - final PkgChangeNotification notification = buildPkgChangeNotification(); - - mockRestServiceServer.expect(requestTo(CALLBACK_URI)).andExpect(method(HttpMethod.POST)) - .andExpect(header("Authorization", EXPECTED_BASIC_AUTHORIZATION)) - .andRespond(withStatus(HttpStatus.UNAUTHORIZED)); - - final ResponseEntity response = sendHttpPost(notification); - - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); - assertTrue(response.getBody() instanceof ProblemDetails); - - final ProblemDetails problemDetails = (ProblemDetails) response.getBody(); - final String errorMessage = "An error occurred. Sending of notification to VNFM failed with response: " - + HttpStatus.UNAUTHORIZED.value() + ".\n" + "Unable to invoke HTTP POST using URL: " + CALLBACK_URI; - - assertEquals(errorMessage, problemDetails.getDetail()); - } - - @Test - public void testNotificationSentOnToVnfm_OAuthAuthorized_Success() { - final PkgmSubscriptionRequest subscriptionRequest = - buildPkgmSubscriptionRequest(SubscriptionsAuthentication.AuthTypeEnum.OAUTH2_CLIENT_CREDENTIALS); - cache.put(SUBSCRIPTION_ID, subscriptionRequest); - final PkgChangeNotification notification = buildPkgChangeNotification(); - - mockRestServiceServer.expect(requestTo(TOKEN_ENDPOINT)).andExpect(method(HttpMethod.POST)) - .andExpect(header("Authorization", EXPECTED_BASIC_AUTHORIZATION)) - .andRespond(withSuccess(JSON_TOKEN, MediaType.APPLICATION_JSON)); - - mockRestServiceServer.expect(requestTo(CALLBACK_URI)).andExpect(method(HttpMethod.POST)) - .andExpect(header("Authorization", EXPECTED_OAUTH_AUTHORIZATION)) - .andExpect(jsonPath("$.id").value(NOTIFICATION_ID)) - .andExpect(jsonPath("$.notificationType").value( - VnfPackageChangeNotification.NotificationTypeEnum.VNFPACKAGECHANGENOTIFICATION.toString())) - .andExpect(jsonPath("$.subscriptionId").value(SUBSCRIPTION_ID)) - .andExpect(jsonPath("$.timeStamp").value(TIME_STAMP_STRING_EXPECTED_FROM_ETSI_CATALOG)) - .andExpect(jsonPath("$.vnfPkgId").value(VNFPKG_ID)).andExpect(jsonPath("$.vnfdId").value(VNFD_ID)) - .andExpect( - jsonPath("$.changeType").value(PkgChangeNotification.ChangeTypeEnum.OP_STATE_CHANGE.toString())) - .andExpect(jsonPath("$.operationalState") - .value(PkgChangeNotification.OperationalStateEnum.ENABLED.toString())) - .andExpect(jsonPath("$._links") - .value(buildPkgmLinks(EXPECTED_VNF_PACKAGE_HREF, EXPECTED_SUBSCRIPTION_HREF))) - .andRespond(withSuccess()); - - final ResponseEntity response = sendHttpPost(notification); - - assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode()); - } - - @Test - public void testNotificationSentOnToVnfm_OAuthTokenNotReceived_Fail() { - final PkgmSubscriptionRequest subscriptionRequest = - buildPkgmSubscriptionRequest(SubscriptionsAuthentication.AuthTypeEnum.OAUTH2_CLIENT_CREDENTIALS); - cache.put(SUBSCRIPTION_ID, subscriptionRequest); - final PkgChangeNotification notification = buildPkgChangeNotification(); - - mockRestServiceServer.expect(requestTo(TOKEN_ENDPOINT)).andExpect(method(HttpMethod.POST)) - .andExpect(header("Authorization", EXPECTED_BASIC_AUTHORIZATION)).andRespond(withSuccess()); - - final ResponseEntity response = sendHttpPost(notification); - - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); - assertTrue(response.getBody() instanceof ProblemDetails); - - final ProblemDetails problemDetails = (ProblemDetails) response.getBody(); - final String errorMessage = "An error occurred. Unable to retrieve OAuth Token from VNFM for notification."; - - assertEquals(errorMessage, problemDetails.getDetail()); - } - - @Test - public void testNotificationSentOnToVnfm_TLSCertNotYetSupported_Fail() { - final PkgmSubscriptionRequest subscriptionRequest = - buildPkgmSubscriptionRequest(SubscriptionsAuthentication.AuthTypeEnum.TLS_CERT); - cache.put(SUBSCRIPTION_ID, subscriptionRequest); - final PkgChangeNotification notification = buildPkgChangeNotification(); - - final ResponseEntity response = sendHttpPost(notification); - - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); - assertTrue(response.getBody() instanceof ProblemDetails); - - final ProblemDetails problemDetails = (ProblemDetails) response.getBody(); - final String errorMessage = "An error occurred. Authentication type " - + subscriptionRequest.getAuthentication().getAuthType().toString() + " not currently supported."; - - assertEquals(errorMessage, problemDetails.getDetail()); - } - - private PkgOnboardingNotification buildPkgOnboardingNotification() { - final PkgOnboardingNotification notification = new PkgOnboardingNotification(); - notification.setId(NOTIFICATION_ID); - notification - .setNotificationType(PkgOnboardingNotification.NotificationTypeEnum.VNFPACKAGEONBOARDINGNOTIFICATION); - notification.setSubscriptionId(SUBSCRIPTION_ID); - notification.setTimeStamp(TIMESTAMP); - notification.setVnfPkgId(VNFPKG_ID); - notification.setVnfdId(VNFD_ID); - notification.setLinks(buildPkgmLinks()); - return notification; - } - - private PkgChangeNotification buildPkgChangeNotification() { - final PkgChangeNotification notification = new PkgChangeNotification(); - notification.setId(NOTIFICATION_ID); - notification.setNotificationType(PkgChangeNotification.NotificationTypeEnum.VNFPACKAGECHANGENOTIFICATION); - notification.setSubscriptionId(SUBSCRIPTION_ID); - notification.setTimeStamp(TIMESTAMP); - notification.setVnfPkgId(VNFPKG_ID); - notification.setVnfdId(VNFD_ID); - notification.setChangeType(PkgChangeNotification.ChangeTypeEnum.OP_STATE_CHANGE); - notification.setOperationalState(PkgChangeNotification.OperationalStateEnum.ENABLED); - notification.setLinks(buildPkgmLinks()); - return notification; - } - - private PkgmLinks buildPkgmLinks() { - return buildPkgmLinks("vnf_package_href", "subscription_href"); - } - - private PkgmLinks buildPkgmLinks(final String vnfPkgHref, final String subscriptionHref) { - return new PkgmLinks().vnfPackage(new NOTIFICATIONLINKSERIALIZER().href(vnfPkgHref)) - .subscription(new NOTIFICATIONLINKSERIALIZER().href(subscriptionHref)); - } - - private PkgmSubscriptionRequest buildPkgmSubscriptionRequest( - final SubscriptionsAuthentication.AuthTypeEnum authTypeEnum) { - final PkgmSubscriptionRequest subscriptionRequest = new PkgmSubscriptionRequest(); - subscriptionRequest.setCallbackUri(CALLBACK_URI.toString()); - subscriptionRequest.setAuthentication(buildSubscriptionsAuthentication(authTypeEnum)); - return subscriptionRequest; - } - - // TODO update for auth types other than basicAuth - private SubscriptionsAuthentication buildSubscriptionsAuthentication( - final SubscriptionsAuthentication.AuthTypeEnum authTypeEnum) { - final SubscriptionsAuthentication subscriptionsAuthentication = new SubscriptionsAuthentication(); - final List authTypes = new ArrayList<>(); - authTypes.add(authTypeEnum); - subscriptionsAuthentication.setAuthType(authTypes); - if (authTypeEnum == SubscriptionsAuthentication.AuthTypeEnum.TLS_CERT) { - // TODO: remove basic params and code for TLS - final SubscriptionsAuthenticationParamsBasic basicParams = - new SubscriptionsAuthenticationParamsBasic().userName(USERNAME).password(PASSWORD); - subscriptionsAuthentication.setParamsBasic(basicParams); - } else if (authTypeEnum == SubscriptionsAuthentication.AuthTypeEnum.OAUTH2_CLIENT_CREDENTIALS) { - final SubscriptionsAuthenticationParamsOauth2ClientCredentials oathParams = - new SubscriptionsAuthenticationParamsOauth2ClientCredentials().clientId(USERNAME) - .clientPassword(PASSWORD).tokenEndpoint(TOKEN_ENDPOINT); - subscriptionsAuthentication.setParamsOauth2ClientCredentials(oathParams); - } else { - final SubscriptionsAuthenticationParamsBasic basicParams = - new SubscriptionsAuthenticationParamsBasic().userName(USERNAME).password(PASSWORD); - subscriptionsAuthentication.setParamsBasic(basicParams); - } - - return subscriptionsAuthentication; - } - - private ResponseEntity sendHttpPost(final T notification) { - final String testURL = LOCALHOST_URL + port + NOTIFICATION_BASE_URL; - final HttpEntity request = new HttpEntity<>(notification, basicHttpHeadersProvider.getHttpHeaders()); - return testRestTemplate.withBasicAuth("test", "test").exchange(testURL, HttpMethod.POST, request, - ProblemDetails.class); - } - - private ResponseEntity sendHttpGet(final String url) { - final String testURL = LOCALHOST_URL + port + url; - final HttpEntity request = new HttpEntity<>(basicHttpHeadersProvider.getHttpHeaders()); - return testRestTemplate.withBasicAuth("test", "test").exchange(testURL, HttpMethod.GET, request, Void.class); - } - -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/test/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/Sol003PackageManagementControllerTest.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/test/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/Sol003PackageManagementControllerTest.java deleted file mode 100644 index b473248da1..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/test/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/Sol003PackageManagementControllerTest.java +++ /dev/null @@ -1,677 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.rest; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.onap.so.adapters.etsi.sol003.adapter.common.CommonConstants.PACKAGE_MANAGEMENT_BASE_URL; -import static org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.EtsiCatalogServiceProviderConfiguration.ETSI_CATALOG_REST_TEMPLATE_BEAN; -import static org.springframework.test.web.client.match.MockRestRequestMatchers.method; -import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; -import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus; -import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; -import java.util.ArrayList; -import java.util.List; -import java.util.Random; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.model.Checksum; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.model.ProblemDetails; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.model.UriLink; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.model.VNFPKGMLinkSerializer; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.model.VnfPackageArtifactInfo; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.model.VnfPackageSoftwareImageInfo; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.model.VnfPkgInfo; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.model.InlineResponse2001; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.model.VnfPackagesLinks; -import org.onap.so.configuration.rest.BasicHttpHeadersProvider; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpMethod; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.client.MockRestServiceServer; -import org.springframework.web.client.RestTemplate; -import com.google.gson.Gson; - -/** - * @author gareth.roper@est.tech - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = TestApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) -@ActiveProfiles("test") -public class Sol003PackageManagementControllerTest { - - @LocalServerPort - private int port; - - @Autowired - @Qualifier(ETSI_CATALOG_REST_TEMPLATE_BEAN) - private RestTemplate restTemplate; - - @Autowired - private TestRestTemplate testRestTemplate; - - private static final String VNF_PACKAGE_ID = "myVnfPackageId"; - private static final String ARTIFACT_PATH = "myArtifactPath"; - private static final String MSB_BASE_URL = "http://msb-iag.onap:80/api/vnfpkgm/v1/vnf_packages"; - private static final String VNFPKGM_BASE_URL = PACKAGE_MANAGEMENT_BASE_URL + "/vnf_packages"; - private static final String localhostUrl = "http://localhost:"; - private static final String GET_VNF_PACKAGES_URL = ""; - private static final String GET_VNF_PACKAGE_BY_ID_URL = "/" + VNF_PACKAGE_ID; - private static final String VNFD_ID = "vnfdId"; - private static final String VNF_PROVIDER = "vnfProvider"; - private static final String VNF_PRODUCT_NAME = "vnfProductName"; - private static final String VNF_SOFTWARE_VERSION = "vnfSoftwareVersion"; - private static final String VNFD_VERSION = "vnfdVersion"; - private static final String ALGORITHM = "algorithm"; - private static final String HASH = "hash"; - private static final String EXPECTED_BASE_URL = - "https://so-vnfm-adapter.onap:30406/so/vnfm-adapter/v1/vnfpkgm/v1/vnf_packages/"; - private static final String EXPECTED_SELF_HREF = EXPECTED_BASE_URL + VNF_PACKAGE_ID; - private static final String EXPECTED_VNFD_HREF = EXPECTED_BASE_URL + VNF_PACKAGE_ID + "/vnfd"; - private static final String EXPECTED_PACKAGE_CONTENT_HREF = EXPECTED_BASE_URL + VNF_PACKAGE_ID + "/package_content"; - - private MockRestServiceServer mockRestServiceServer; - private BasicHttpHeadersProvider basicHttpHeadersProvider; - private final Gson gson = new Gson(); - - public Sol003PackageManagementControllerTest() {} - - @Before - public void setUp() { - final MockRestServiceServer.MockRestServiceServerBuilder builder = MockRestServiceServer.bindTo(restTemplate); - builder.ignoreExpectOrder(true); - mockRestServiceServer = builder.build(); - basicHttpHeadersProvider = new BasicHttpHeadersProvider(); - } - - @After - public void after() { - mockRestServiceServer.reset(); - } - - @Test - public void testGetPackageContent_ValidArray_Success() { - final byte[] responseArray = buildByteArrayWithRandomData(10); - - mockRestServiceServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/package_content")) - .andExpect(method(HttpMethod.GET)) - .andRespond(withSuccess(responseArray, MediaType.APPLICATION_OCTET_STREAM)); - - final String testURL = "http://localhost:" + port + PACKAGE_MANAGEMENT_BASE_URL + "/vnf_packages/" - + VNF_PACKAGE_ID + "/package_content"; - final HttpEntity request = new HttpEntity<>(basicHttpHeadersProvider.getHttpHeaders()); - final ResponseEntity responseEntity = - testRestTemplate.withBasicAuth("test", "test").exchange(testURL, HttpMethod.GET, request, byte[].class); - - assertEquals(byte[].class, responseEntity.getBody().getClass()); - assertArrayEquals(responseEntity.getBody(), responseArray); - assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); - } - - @Test - public void testOnGetPackageContent_Conflict_Fail() { - mockRestServiceServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/package_content")) - .andExpect(method(HttpMethod.GET)).andRespond(withStatus(HttpStatus.CONFLICT)); - - final ResponseEntity responseEntity = sendHttpRequest(VNF_PACKAGE_ID + "/package_content"); - - assertTrue(responseEntity.getBody() instanceof ProblemDetails); - assertEquals(HttpStatus.CONFLICT, responseEntity.getStatusCode()); - } - - @Test - public void testOnGetPackageContent_NotFound_Fail() { - mockRestServiceServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/package_content")) - .andExpect(method(HttpMethod.GET)).andRespond(withStatus(HttpStatus.NOT_FOUND)); - - final ResponseEntity responseEntity = sendHttpRequest(VNF_PACKAGE_ID + "/package_content"); - - assertTrue(responseEntity.getBody() instanceof ProblemDetails); - assertEquals(HttpStatus.NOT_FOUND, responseEntity.getStatusCode()); - } - - @Test - public void testOnGetPackageContent_UnauthorizedClient_Fail() { - final String testURL = "http://localhost:" + port + PACKAGE_MANAGEMENT_BASE_URL + "/vnf_packages/" - + VNF_PACKAGE_ID + "/package_content"; - - mockRestServiceServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/package_content")) - .andExpect(method(HttpMethod.GET)).andRespond(withStatus(HttpStatus.UNAUTHORIZED)); - - final HttpEntity request = new HttpEntity<>(basicHttpHeadersProvider.getHttpHeaders()); - - - final ResponseEntity responseEntity = - testRestTemplate.exchange(testURL, HttpMethod.GET, request, ProblemDetails.class); - - assertTrue(responseEntity.getBody() instanceof ProblemDetails); - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); - } - - @Test - public void testOnGetPackageContent_InternalServerError_Fail() { - mockRestServiceServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/package_content")) - .andExpect(method(HttpMethod.GET)).andRespond(withStatus(HttpStatus.INTERNAL_SERVER_ERROR)); - - final ResponseEntity responseEntity = sendHttpRequest(VNF_PACKAGE_ID + "/package_content"); - - assertTrue(responseEntity.getBody() instanceof ProblemDetails); - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); - } - - @Test - public void testOnGetPackageContent_BadRequest_Fail() { - mockRestServiceServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/package_content")) - .andExpect(method(HttpMethod.GET)).andRespond(withStatus(HttpStatus.BAD_REQUEST)); - - final ResponseEntity responseEntity = sendHttpRequest(VNF_PACKAGE_ID + "/package_content"); - - assertTrue(responseEntity.getBody() instanceof ProblemDetails); - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); - } - - @Test - public void testOnGetPackageContent_UnauthorizedServer_InternalError_Fail() { - mockRestServiceServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/package_content")) - .andExpect(method(HttpMethod.GET)).andRespond(withStatus(HttpStatus.UNAUTHORIZED)); - - final ResponseEntity responseEntity = sendHttpRequest(VNF_PACKAGE_ID + "/package_content"); - - assertTrue(responseEntity.getBody() instanceof ProblemDetails); - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); - } - - @Test - public void testGetPackageContent_SuccessResponseFromServerWithNullPackage_Fail() { - mockRestServiceServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/package_content")) - .andExpect(method(HttpMethod.GET)).andRespond(withSuccess()); - - final ResponseEntity responseEntity = sendHttpRequest(VNF_PACKAGE_ID + "/package_content"); - - assertEquals(ProblemDetails.class, responseEntity.getBody().getClass()); - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); - } - - @Test - public void testGetPackageArtifact_ValidArray_Success() { - final byte[] responseArray = buildByteArrayWithRandomData(10); - - mockRestServiceServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/artifacts/" + ARTIFACT_PATH)) - .andExpect(method(HttpMethod.GET)) - .andRespond(withSuccess(responseArray, MediaType.APPLICATION_OCTET_STREAM)); - - final String testURL = "http://localhost:" + port + PACKAGE_MANAGEMENT_BASE_URL + "/vnf_packages/" - + VNF_PACKAGE_ID + "/artifacts/" + ARTIFACT_PATH; - final HttpEntity request = new HttpEntity<>(basicHttpHeadersProvider.getHttpHeaders()); - final ResponseEntity responseEntity = - testRestTemplate.withBasicAuth("test", "test").exchange(testURL, HttpMethod.GET, request, byte[].class); - - assertEquals(byte[].class, responseEntity.getBody().getClass()); - assertArrayEquals(responseEntity.getBody(), responseArray); - assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); - } - - @Test - public void testOnGetPackageArtifact_Conflict_Fail() { - mockRestServiceServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/artifacts/" + ARTIFACT_PATH)) - .andExpect(method(HttpMethod.GET)).andRespond(withStatus(HttpStatus.CONFLICT)); - - final ResponseEntity responseEntity = - sendHttpRequest(VNF_PACKAGE_ID + "/artifacts/" + ARTIFACT_PATH); - - assertNotNull(responseEntity.getBody()); - assertEquals(HttpStatus.CONFLICT, responseEntity.getStatusCode()); - } - - @Test - public void testOnGetPackageArtifact_NotFound_Fail() { - mockRestServiceServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/artifacts/" + ARTIFACT_PATH)) - .andExpect(method(HttpMethod.GET)).andRespond(withStatus(HttpStatus.NOT_FOUND)); - - final ResponseEntity responseEntity = - sendHttpRequest(VNF_PACKAGE_ID + "/artifacts/" + ARTIFACT_PATH); - - assertNotNull(responseEntity.getBody()); - assertEquals(HttpStatus.NOT_FOUND, responseEntity.getStatusCode()); - } - - @Test - public void testOnGetPackageArtifact_UnauthorizedClient_Fail() { - final String testURL = "http://localhost:" + port + PACKAGE_MANAGEMENT_BASE_URL + "/vnf_packages/" - + VNF_PACKAGE_ID + "/artifacts/" + ARTIFACT_PATH; - - mockRestServiceServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/artifacts/" + ARTIFACT_PATH)) - .andExpect(method(HttpMethod.GET)).andRespond(withStatus(HttpStatus.UNAUTHORIZED)); - - final HttpEntity request = new HttpEntity<>(basicHttpHeadersProvider.getHttpHeaders()); - final ResponseEntity responseEntity = - testRestTemplate.exchange(testURL, HttpMethod.GET, request, ProblemDetails.class); - - assertNotNull(responseEntity.getBody()); - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); - } - - @Test - public void testOnGetPackageArtifact_InternalServerError_Fail() { - mockRestServiceServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/artifacts/" + ARTIFACT_PATH)) - .andExpect(method(HttpMethod.GET)).andRespond(withStatus(HttpStatus.INTERNAL_SERVER_ERROR)); - - final ResponseEntity responseEntity = - sendHttpRequest(VNF_PACKAGE_ID + "/artifacts/" + ARTIFACT_PATH); - - assertNotNull(responseEntity.getBody()); - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); - } - - @Test - public void testOnGetPackageArtifact_BadRequest_Fail() { - mockRestServiceServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/artifacts/" + ARTIFACT_PATH)) - .andExpect(method(HttpMethod.GET)).andRespond(withStatus(HttpStatus.BAD_REQUEST)); - - final ResponseEntity responseEntity = - sendHttpRequest(VNF_PACKAGE_ID + "/artifacts/" + ARTIFACT_PATH); - - assertNotNull(responseEntity.getBody()); - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); - } - - @Test - public void testOnGetPackageArtifact_UnauthorizedServer_InternalError_Fail() { - mockRestServiceServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/artifacts/" + ARTIFACT_PATH)) - .andExpect(method(HttpMethod.GET)).andRespond(withStatus(HttpStatus.UNAUTHORIZED)); - - final ResponseEntity responseEntity = - sendHttpRequest(VNF_PACKAGE_ID + "/artifacts/" + ARTIFACT_PATH); - - assertNotNull(responseEntity.getBody()); - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); - } - - @Test - public void testGetPackageArtifact_SuccessResponseFromServerWithNullPackage_Fail() { - mockRestServiceServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/artifacts/" + ARTIFACT_PATH)) - .andExpect(method(HttpMethod.GET)).andRespond(withSuccess()); - - final ResponseEntity responseEntity = - sendHttpRequest(VNF_PACKAGE_ID + "/artifacts/" + ARTIFACT_PATH); - - assertNotNull(responseEntity.getBody()); - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); - } - - @Test - public void testVnfPackagesReceivedAsInlineResponse2001ListIfGetVnfPackagesSuccessful() { - final VnfPkgInfo[] responses = createVnfPkgArray(); - - mockRestServiceServer.expect(requestTo(MSB_BASE_URL)).andExpect(method(HttpMethod.GET)) - .andRespond(withSuccess(gson.toJson(responses), MediaType.APPLICATION_JSON)); - - final String testURL = localhostUrl + port + VNFPKGM_BASE_URL; - final HttpEntity request = new HttpEntity<>(basicHttpHeadersProvider.getHttpHeaders()); - - final ResponseEntity responseEntity = testRestTemplate.withBasicAuth("test", "test") - .exchange(testURL, HttpMethod.GET, request, InlineResponse2001[].class); - - assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); - assertNotNull(responseEntity.getBody()); - final InlineResponse2001[] inlineResponse2001array = responseEntity.getBody(); - final InlineResponse2001 inlineResponse2001 = inlineResponse2001array[0]; - assertEquals(VNF_PACKAGE_ID, inlineResponse2001.getId()); - assertEquals(VNFD_ID, inlineResponse2001.getVnfdId()); - assertEquals(VNFD_ID, inlineResponse2001.getSoftwareImages().get(0).getId()); - assertEquals(VNF_PRODUCT_NAME, inlineResponse2001.getSoftwareImages().get(0).getName()); - assertEquals(ALGORITHM, inlineResponse2001.getChecksum().getAlgorithm()); - assertEquals(HASH, inlineResponse2001.getChecksum().getHash()); - assertEquals(ARTIFACT_PATH, inlineResponse2001.getAdditionalArtifacts().get(0).getArtifactPath()); - assertEquals(ALGORITHM, inlineResponse2001.getAdditionalArtifacts().get(0).getChecksum().getAlgorithm()); - assertEquals(HASH, inlineResponse2001.getAdditionalArtifacts().get(0).getChecksum().getHash()); - final VnfPackagesLinks links = inlineResponse2001.getLinks(); - assertNotNull(links); - assertEquals(EXPECTED_SELF_HREF, links.getSelf().getHref()); - assertEquals(EXPECTED_VNFD_HREF, links.getVnfd().getHref()); - assertEquals(EXPECTED_PACKAGE_CONTENT_HREF, links.getPackageContent().getHref()); - } - - @Test - public void test400BadRequestInfoReceivedAsProblemDetailsIfGetVnfPackagesIs400BadRequest() { - mockRestServiceServer.expect(requestTo(MSB_BASE_URL)).andExpect(method(HttpMethod.GET)) - .andRespond(withStatus(HttpStatus.BAD_REQUEST)); - - final ResponseEntity responseEntity = sendHttpRequest(GET_VNF_PACKAGES_URL); - assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode()); - - assertNotNull(responseEntity.getBody()); - final ProblemDetails problemDetails = responseEntity.getBody(); - assertEquals("Error: Bad Request Received", problemDetails.getDetail()); - } - - @Test - public void test404NotFoundInfoReceivedAsProblemDetailsIfGetVnfPackagesIs404NotFound() { - mockRestServiceServer.expect(requestTo(MSB_BASE_URL)).andExpect(method(HttpMethod.GET)) - .andRespond(withStatus(HttpStatus.NOT_FOUND)); - - final ResponseEntity responseEntity = sendHttpRequest(GET_VNF_PACKAGES_URL); - assertEquals(HttpStatus.NOT_FOUND, responseEntity.getStatusCode()); - - assertNotNull(responseEntity.getBody()); - final ProblemDetails problemDetails = responseEntity.getBody(); - assertEquals("No Vnf Packages found", problemDetails.getDetail()); - } - - @Test - public void test500InternalServerErrorProblemDetailsReceivedIfGetVnfPackagesReturns500InternalServerError() { - mockRestServiceServer.expect(requestTo(MSB_BASE_URL)).andExpect(method(HttpMethod.GET)) - .andRespond(withStatus(HttpStatus.INTERNAL_SERVER_ERROR)); - - final ResponseEntity responseEntity = sendHttpRequest(GET_VNF_PACKAGES_URL); - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); - - assertNotNull(responseEntity.getBody()); - final ProblemDetails problemDetails = responseEntity.getBody(); - assertEquals("Internal Server Error Occurred.", problemDetails.getDetail()); - } - - @Test - public void test500InternalServerErrorProblemDetailsReceivedIfGetVnfPackagesReturnsANullPackage() { - mockRestServiceServer.expect(requestTo(MSB_BASE_URL)).andExpect(method(HttpMethod.GET)) - .andRespond(withSuccess()); - - final ResponseEntity responseEntity = sendHttpRequest(GET_VNF_PACKAGES_URL); - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); - - assertNotNull(responseEntity.getBody()); - final ProblemDetails problemDetails = responseEntity.getBody(); - assertEquals("An error occurred, a null response was received by the\n" - + " Sol003PackageManagementController from the EtsiCatalogManager using the GET \"vnf_packages\" \n" - + "endpoint.", problemDetails.getDetail()); - } - - @Test - public void testVnfPackageReceivedAsInlineResponse2001IfGetVnfPackageByIdSuccessful() { - final VnfPkgInfo response = createVnfPkgInfo(VNF_PACKAGE_ID); - - mockRestServiceServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID)).andExpect(method(HttpMethod.GET)) - .andRespond(withSuccess(gson.toJson(response), MediaType.APPLICATION_JSON)); - - final String testURL = localhostUrl + port + VNFPKGM_BASE_URL + "/" + VNF_PACKAGE_ID; - final HttpEntity request = new HttpEntity<>(basicHttpHeadersProvider.getHttpHeaders()); - final ResponseEntity responseEntity = testRestTemplate.withBasicAuth("test", "test") - .exchange(testURL, HttpMethod.GET, request, InlineResponse2001.class); - - assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); - assertNotNull(responseEntity.getBody()); - final InlineResponse2001 inlineResponse2001 = responseEntity.getBody(); - assertEquals(VNF_PACKAGE_ID, inlineResponse2001.getId()); - assertEquals(VNFD_ID, inlineResponse2001.getVnfdId()); - assertEquals(VNFD_ID, inlineResponse2001.getSoftwareImages().get(0).getId()); - assertEquals(VNF_PRODUCT_NAME, inlineResponse2001.getSoftwareImages().get(0).getName()); - assertEquals(ALGORITHM, inlineResponse2001.getChecksum().getAlgorithm()); - assertEquals(HASH, inlineResponse2001.getChecksum().getHash()); - assertEquals(ARTIFACT_PATH, inlineResponse2001.getAdditionalArtifacts().get(0).getArtifactPath()); - assertEquals(ALGORITHM, inlineResponse2001.getAdditionalArtifacts().get(0).getChecksum().getAlgorithm()); - assertEquals(HASH, inlineResponse2001.getAdditionalArtifacts().get(0).getChecksum().getHash()); - final VnfPackagesLinks links = inlineResponse2001.getLinks(); - assertNotNull(links); - assertEquals(EXPECTED_SELF_HREF, links.getSelf().getHref()); - assertEquals(EXPECTED_VNFD_HREF, links.getVnfd().getHref()); - assertEquals(EXPECTED_PACKAGE_CONTENT_HREF, links.getPackageContent().getHref()); - - } - - @Test - public void test400BadRequestInfoReceivedAsProblemDetailsIfGetVnfPackageByIdIs400BadRequest() { - mockRestServiceServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID)).andExpect(method(HttpMethod.GET)) - .andRespond(withStatus(HttpStatus.BAD_REQUEST)); - - final ResponseEntity responseEntity = sendHttpRequest(GET_VNF_PACKAGE_BY_ID_URL); - - assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode()); - assertNotNull(responseEntity.getBody()); - final ProblemDetails problemDetails = responseEntity.getBody(); - assertEquals("Error: Bad Request Received", problemDetails.getDetail()); - } - - @Test - public void test404NotFoundInfoReceivedAsProblemDetailsIfGetVnfPackageByIdIs404NotFound() { - mockRestServiceServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID)).andExpect(method(HttpMethod.GET)) - .andRespond(withStatus(HttpStatus.NOT_FOUND)); - - final ResponseEntity responseEntity = sendHttpRequest(GET_VNF_PACKAGE_BY_ID_URL); - - assertEquals(HttpStatus.NOT_FOUND, responseEntity.getStatusCode()); - assertNotNull(responseEntity.getBody()); - final ProblemDetails problemDetails = responseEntity.getBody(); - assertEquals("No Vnf Package found with vnfPkgId: " + VNF_PACKAGE_ID, problemDetails.getDetail()); - } - - @Test - public void test500InternalServerErrorProblemDetailsReceivedIfGetVnfPackageByIdReturns500InternalServerError() { - mockRestServiceServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID)).andExpect(method(HttpMethod.GET)) - .andRespond(withStatus(HttpStatus.INTERNAL_SERVER_ERROR)); - - final ResponseEntity responseEntity = sendHttpRequest(GET_VNF_PACKAGE_BY_ID_URL); - - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); - assertNotNull(responseEntity.getBody()); - final ProblemDetails problemDetails = responseEntity.getBody(); - assertEquals("Internal Server Error Occurred.", problemDetails.getDetail()); - } - - @Test - public void test500InternalServerErrorProblemDetailsReceivedIfGetVnfPackageByIdReturnsANullPackage() { - mockRestServiceServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID)).andExpect(method(HttpMethod.GET)) - .andRespond(withSuccess()); - - final ResponseEntity responseEntity = sendHttpRequest(GET_VNF_PACKAGE_BY_ID_URL); - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); - - assertNotNull(responseEntity.getBody()); - final ProblemDetails problemDetails = responseEntity.getBody(); - assertEquals("An error occurred, a null response was received by the\n" - + " Sol003PackageManagementController from the EtsiCatalogManager using the GET \"vnf_packages\" by vnfPkgId: \"" - + VNF_PACKAGE_ID + "\" \n" + "endpoint.", problemDetails.getDetail()); - } - - // The below test method is here to improve code coverage and provide a foundation for writing - // future tests - @Test - public void testGetPackageVnfd_ValidArray_Success() { - final byte[] responseArray = buildByteArrayWithRandomData(10); - - mockRestServiceServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/vnfd")) - .andExpect(method(HttpMethod.GET)) - .andRespond(withSuccess(responseArray, MediaType.APPLICATION_OCTET_STREAM)); - - final String testURL = - "http://localhost:" + port + PACKAGE_MANAGEMENT_BASE_URL + "/vnf_packages/" + VNF_PACKAGE_ID + "/vnfd"; - final HttpEntity request = new HttpEntity<>(basicHttpHeadersProvider.getHttpHeaders()); - final ResponseEntity responseEntity = - testRestTemplate.withBasicAuth("test", "test").exchange(testURL, HttpMethod.GET, request, byte[].class); - - assertEquals(byte[].class, responseEntity.getBody().getClass()); - assertArrayEquals(responseEntity.getBody(), responseArray); - assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); - } - - @Test - public void testOnGetPackageVnfd_Conflict_Fail() { - mockRestServiceServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/vnfd")) - .andExpect(method(HttpMethod.GET)).andRespond(withStatus(HttpStatus.CONFLICT)); - - final ResponseEntity responseEntity = sendHttpRequest(VNF_PACKAGE_ID + "/vnfd"); - - assertTrue(responseEntity.getBody() instanceof ProblemDetails); - assertEquals(HttpStatus.CONFLICT, responseEntity.getStatusCode()); - } - - @Test - public void testOnGetPackageVnfd_NotFound_Fail() { - mockRestServiceServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/vnfd")) - .andExpect(method(HttpMethod.GET)).andRespond(withStatus(HttpStatus.NOT_FOUND)); - - final ResponseEntity responseEntity = sendHttpRequest(VNF_PACKAGE_ID + "/vnfd"); - - assertTrue(responseEntity.getBody() instanceof ProblemDetails); - assertEquals(HttpStatus.NOT_FOUND, responseEntity.getStatusCode()); - } - - @Test - public void testOnGetPackageVnfd_UnauthorizedClient_Fail() { - mockRestServiceServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/vnfd")) - .andExpect(method(HttpMethod.GET)).andRespond(withStatus(HttpStatus.UNAUTHORIZED)); - - final ResponseEntity responseEntity = sendHttpRequest(VNF_PACKAGE_ID + "/vnfd"); - - assertTrue(responseEntity.getBody() instanceof ProblemDetails); - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); - } - - @Test - public void testOnGetPackageVnfd_InternalServerError_Fail() { - mockRestServiceServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/vnfd")) - .andExpect(method(HttpMethod.GET)).andRespond(withStatus(HttpStatus.INTERNAL_SERVER_ERROR)); - - final ResponseEntity responseEntity = sendHttpRequest(VNF_PACKAGE_ID + "/vnfd"); - - assertTrue(responseEntity.getBody() instanceof ProblemDetails); - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); - } - - @Test - public void testOnGetPackageVnfd_BadRequest_Fail() { - mockRestServiceServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/vnfd")) - .andExpect(method(HttpMethod.GET)).andRespond(withStatus(HttpStatus.BAD_REQUEST)); - - final ResponseEntity responseEntity = sendHttpRequest(VNF_PACKAGE_ID + "/vnfd"); - - assertTrue(responseEntity.getBody() instanceof ProblemDetails); - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); - } - - @Test - public void testOnGetPackageVnfd_UnauthorizedServer_InternalError_Fail() { - mockRestServiceServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/vnfd")) - .andExpect(method(HttpMethod.GET)).andRespond(withStatus(HttpStatus.UNAUTHORIZED)); - - final ResponseEntity responseEntity = sendHttpRequest(VNF_PACKAGE_ID + "/vnfd"); - - assertTrue(responseEntity.getBody() instanceof ProblemDetails); - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); - } - - @Test - public void testGetPackageVnfd_SuccessResponseFromServerWithNullPackage_Fail() { - mockRestServiceServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/vnfd")) - .andExpect(method(HttpMethod.GET)).andRespond(withSuccess()); - - final ResponseEntity responseEntity = sendHttpRequest(VNF_PACKAGE_ID + "/vnfd"); - - assertEquals(ProblemDetails.class, responseEntity.getBody().getClass()); - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); - } - - // Simply returns a byte array filled with random data, for use in the tests. - private byte[] buildByteArrayWithRandomData(final int sizeInKb) { - final Random rnd = new Random(); - final byte[] b = new byte[sizeInKb * 1024]; // converting kb to byte - rnd.nextBytes(b); - return b; - } - - private ResponseEntity sendHttpRequest(final String url) { - final String testURL = localhostUrl + port + VNFPKGM_BASE_URL + "/" + url; - final HttpEntity request = new HttpEntity<>(basicHttpHeadersProvider.getHttpHeaders()); - return testRestTemplate.withBasicAuth("test", "test").exchange(testURL, HttpMethod.GET, request, - ProblemDetails.class); - } - - private VnfPkgInfo[] createVnfPkgArray() { - final VnfPkgInfo[] vnfPkgInfoArray = new VnfPkgInfo[1]; - final VnfPkgInfo vnfPkgInfo = createVnfPkgInfo(VNF_PACKAGE_ID); - vnfPkgInfoArray[0] = vnfPkgInfo; - return vnfPkgInfoArray; - } - - private VnfPkgInfo createVnfPkgInfo(final String vnfPackageId) { - final VnfPkgInfo vnfPkgInfo = new VnfPkgInfo(); - vnfPkgInfo.setId(vnfPackageId); - vnfPkgInfo.setVnfdId(VNFD_ID); - vnfPkgInfo.setVnfProvider(VNF_PROVIDER); - vnfPkgInfo.setVnfProductName(VNF_PRODUCT_NAME); - vnfPkgInfo.setVnfSoftwareVersion(VNF_SOFTWARE_VERSION); - vnfPkgInfo.setVnfdVersion(VNFD_VERSION); - vnfPkgInfo.setChecksum(createVnfPkgChecksum()); - vnfPkgInfo.setSoftwareImages(createSoftwareImages()); - vnfPkgInfo.setAdditionalArtifacts(createAdditionalArtifacts()); - vnfPkgInfo.setLinks(createVNFPKGMLinkSerializerLinks()); - return vnfPkgInfo; - } - - private Checksum createVnfPkgChecksum() { - final Checksum checksum = new Checksum(); - checksum.setAlgorithm(ALGORITHM); - checksum.setHash(HASH); - return checksum; - } - - private List createSoftwareImages() { - final List softwareImages = new ArrayList<>(); - final VnfPackageSoftwareImageInfo vnfPackageSoftwareImageInfo = new VnfPackageSoftwareImageInfo(); - vnfPackageSoftwareImageInfo.setId(VNFD_ID); - vnfPackageSoftwareImageInfo.setName(VNF_PRODUCT_NAME); - vnfPackageSoftwareImageInfo.setProvider(""); - vnfPackageSoftwareImageInfo.setVersion(""); - vnfPackageSoftwareImageInfo.setChecksum(createVnfPkgChecksum()); - vnfPackageSoftwareImageInfo - .setContainerFormat(VnfPackageSoftwareImageInfo.ContainerFormatEnum.fromValue("AKI")); - softwareImages.add(vnfPackageSoftwareImageInfo); - return softwareImages; - } - - private List createAdditionalArtifacts() { - final List vnfPackageArtifactInfos = new ArrayList<>(); - final VnfPackageArtifactInfo vnfPackageArtifactInfo = - new VnfPackageArtifactInfo().artifactPath(ARTIFACT_PATH).checksum(createVnfPkgChecksum()); - vnfPackageArtifactInfos.add(vnfPackageArtifactInfo); - return vnfPackageArtifactInfos; - } - - private VNFPKGMLinkSerializer createVNFPKGMLinkSerializerLinks() { - final String baseUrl = "http://msb-iag:443/api/vnfpkgm/v1/vnf_packages"; - return new VNFPKGMLinkSerializer().self(new UriLink().href(baseUrl + "/myVnfPackageId")) - .vnfd(new UriLink().href(baseUrl + "/myVnfPackageId/vnfd")) - .packageContent(new UriLink().href(baseUrl + "/myVnfPackageId/package_content")); - } - -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/test/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/Sol003PackageManagementSubscriptionControllerTest.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/test/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/Sol003PackageManagementSubscriptionControllerTest.java deleted file mode 100644 index a2a7c4510e..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/test/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/Sol003PackageManagementSubscriptionControllerTest.java +++ /dev/null @@ -1,403 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2020 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.rest; - -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.onap.so.adapters.etsi.sol003.adapter.common.CommonConstants.ETSI_SUBSCRIPTION_NOTIFICATION_BASE_URL; -import static org.onap.so.adapters.etsi.sol003.adapter.common.CommonConstants.PACKAGE_MANAGEMENT_BASE_URL; -import static org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.EtsiCatalogServiceProviderConfiguration.ETSI_CATALOG_REST_TEMPLATE_BEAN; -import static org.springframework.test.web.client.match.MockRestRequestMatchers.method; -import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; -import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus; -import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; -import java.io.File; -import java.net.URI; -import java.net.URISyntaxException; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.security.GeneralSecurityException; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; -import java.util.UUID; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.PackageManagementConstants; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.model.BasicAuth; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.model.LinkSelf; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.model.NsdmSubscription; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.model.PkgmNotificationsFilter; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.model.PkgmSubscription; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.model.ProblemDetails; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.model.SubscriptionAuthentication; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.model.Version; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.model.VnfProducts; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.model.VnfProductsProviders; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.model.InlineResponse2002; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.model.InlineResponse201; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.model.PkgmSubscriptionRequest; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.model.SubscriptionsAuthentication; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.model.SubscriptionsFilter1; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.model.SubscriptionsFilterVnfProductsFromProviders; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.model.SubscriptionsLinks; -import org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.model.VnfPackagesLinksSelf; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.cache.Cache; -import org.springframework.cache.CacheManager; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.client.MockRestServiceServer; -import org.springframework.test.web.client.match.MockRestRequestMatchers; -import org.springframework.web.client.RestTemplate; -import com.google.gson.Gson; - -/** - * @author Ronan Kenny (ronan.kenny@est.tech) - * @author Gareth Roper (gareth.roper@est.tech) - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = TestApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) -@ActiveProfiles("test") -public class Sol003PackageManagementSubscriptionControllerTest { - - private final Gson gson = new Gson(); - private final URI msbEndpoint = URI.create("http://msb-iag.onap:80/api/vnfpkgm/v1/subscriptions"); - private static final String _NOTIFICATION_CALLBACK_URI = - "https://so-vnfm-adapter.onap:30406" + ETSI_SUBSCRIPTION_NOTIFICATION_BASE_URL; - private static final String LOCALHOST_URL = "http://localhost:"; - - @Autowired - @Qualifier(ETSI_CATALOG_REST_TEMPLATE_BEAN) - private RestTemplate restTemplate; - private MockRestServiceServer mockRestServiceServer; - @Autowired - private CacheManager cacheServiceProvider; - @Autowired - private Sol003PackageManagementSubscriptionController sol003PackageManagementSubscriptionController; - - @Autowired - private TestRestTemplate testRestTemplate; - - @LocalServerPort - private int port; - - private static final String ID = UUID.randomUUID().toString(); - - @Before - public void setUp() { - mockRestServiceServer = MockRestServiceServer.bindTo(restTemplate).build(); - final Cache cache = - cacheServiceProvider.getCache(PackageManagementConstants.PACKAGE_MANAGEMENT_SUBSCRIPTION_CACHE); - cache.clear(); - } - - @After - public void after() { - mockRestServiceServer.reset(); - } - - @Test - public void testSuccessPostSubscription() throws GeneralSecurityException, URISyntaxException { - final PkgmSubscriptionRequest pkgmSubscriptionRequest = postSubscriptionForTest(); - final ResponseEntity response = - (ResponseEntity) sol003PackageManagementSubscriptionController - .postSubscriptionRequest(pkgmSubscriptionRequest); - - final HttpHeaders headers = buildHttpHeaders(Objects.requireNonNull(response.getBody()).getCallbackUri()); - - final SubscriptionsLinks subscriptionsLinks = new SubscriptionsLinks(); - final VnfPackagesLinksSelf vnfPackagesLinksSelf = new VnfPackagesLinksSelf(); - vnfPackagesLinksSelf.setHref("https://so-vnfm-adapter.onap:30406" + PACKAGE_MANAGEMENT_BASE_URL - + "/subscriptions/" + response.getBody().getId()); - subscriptionsLinks.setSelf(vnfPackagesLinksSelf); - - assertEquals(pkgmSubscriptionRequest.getFilter(), response.getBody().getFilter()); - assertEquals(subscriptionsLinks, response.getBody().getLinks()); - assertEquals(response.getBody().getFilter(), pkgmSubscriptionRequest.getFilter()); - assert (response.getHeaders().equals(headers)); - assertThat(response.getStatusCode(), is(HttpStatus.CREATED)); - assertNotNull(response.getBody().getCallbackUri()); - } - - @Test - public void testFailPostSubscriptionAlreadyExists() throws GeneralSecurityException { - final PkgmSubscriptionRequest pkgmSubscriptionRequest = postSubscriptionForTest(); - - final ResponseEntity response = - (ResponseEntity) sol003PackageManagementSubscriptionController - .postSubscriptionRequest(pkgmSubscriptionRequest); - - // Create duplicate entry - final PkgmSubscriptionRequest pkgmSubscriptionRequest2 = buildPkgmSubscriptionRequest(); - - final ResponseEntity response2002 = - (ResponseEntity) sol003PackageManagementSubscriptionController - .postSubscriptionRequest(pkgmSubscriptionRequest2); - - assertEquals(HttpStatus.SEE_OTHER, response2002.getStatusCode()); - } - - @Test - public void testSuccessGetSubscriptionWithSubscriptionId() throws GeneralSecurityException, URISyntaxException { - - final PkgmSubscriptionRequest pkgmSubscriptionRequest = postSubscriptionForTest(); - - mockRestServiceServer.expect(requestTo(msbEndpoint + "/" + ID)).andExpect(method(HttpMethod.GET)) - .andRespond(withSuccess(gson.toJson(new NsdmSubscription().id(ID)), MediaType.APPLICATION_JSON)); - - final ResponseEntity response = - (ResponseEntity) sol003PackageManagementSubscriptionController - .postSubscriptionRequest(pkgmSubscriptionRequest); - final String subscriptionId = response.getBody().getId(); - - - - final ResponseEntity responseEntity = - (ResponseEntity) sol003PackageManagementSubscriptionController - .getSubscription(subscriptionId); - - final HttpHeaders headers = buildHttpHeaders(response.getBody().getCallbackUri()); - - assertEquals(response.getBody().getFilter(), pkgmSubscriptionRequest.getFilter()); - assertEquals(response.getHeaders(), headers); - assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); - assertEquals(pkgmSubscriptionRequest.getFilter(), response.getBody().getFilter()); - // Ensure CallBackUri is set to new URI - assertNotEquals(pkgmSubscriptionRequest.getCallbackUri(), response.getBody().getCallbackUri()); - } - - @Test - public void testFailGetSubscriptionWithInvalidSubscriptionId() { - final String invalidId = "invalidSubscriptionId"; - mockRestServiceServer.expect(requestTo(msbEndpoint + "/" + invalidId)).andExpect(method(HttpMethod.GET)) - .andRespond(withStatus(HttpStatus.NOT_FOUND)); - final ResponseEntity response = sol003PackageManagementSubscriptionController.getSubscription(invalidId); - assertEquals(HttpStatus.NOT_FOUND, response.getStatusCode()); - assertTrue(response.getBody() instanceof ProblemDetails); - } - - @Test - public void testSuccessGetSubscriptions() throws GeneralSecurityException { - final PkgmSubscription pkgmSubscription = buildPkgmSubscription(); - final PkgmSubscriptionRequest pkgmSubscriptionRequest = buildPkgmSubscriptionRequest(); - - mockRestServiceServer.expect(requestTo(msbEndpoint)).andExpect(method(HttpMethod.POST)) - .andRespond(withSuccess(gson.toJson(pkgmSubscription), MediaType.APPLICATION_JSON)); - mockRestServiceServer.expect(requestTo(msbEndpoint + "/" + ID)).andExpect(method(HttpMethod.GET)) - .andRespond(withSuccess(gson.toJson(new NsdmSubscription().id(ID)), MediaType.APPLICATION_JSON)); - - sol003PackageManagementSubscriptionController.postSubscriptionRequest(pkgmSubscriptionRequest); - final ResponseEntity> response = - sol003PackageManagementSubscriptionController.getSubscriptions(); - - final List subscriptionsList = response.getBody(); - - assertEquals(Objects.requireNonNull(response.getBody()).get(0).getFilter(), - pkgmSubscriptionRequest.getFilter()); - assertNotNull(subscriptionsList != null); - assertNotEquals('0', subscriptionsList.size()); - assertEquals(HttpStatus.OK, response.getStatusCode()); - } - - @Test - public void testSuccessDeleteSubscriptionWithSubscriptionId() throws GeneralSecurityException { - final PkgmSubscriptionRequest pkgmSubscriptionRequest = buildPkgmSubscriptionRequest(); - final PkgmSubscription pkgmSubscription = buildPkgmSubscription(); - final String subscriptionId = pkgmSubscription.getId(); - - mockRestServiceServer.expect(requestTo(msbEndpoint)).andExpect(method(HttpMethod.POST)) - .andRespond(withSuccess(gson.toJson(pkgmSubscription), MediaType.APPLICATION_JSON)); - - mockRestServiceServer.expect(requestTo(msbEndpoint + "/" + subscriptionId)).andExpect(method(HttpMethod.DELETE)) - .andRespond(withStatus(HttpStatus.NO_CONTENT)); - mockRestServiceServer.expect(requestTo(msbEndpoint + "/" + subscriptionId)).andExpect(method(HttpMethod.GET)) - .andRespond(withSuccess(gson.toJson(new NsdmSubscription().id(subscriptionId)), - MediaType.APPLICATION_JSON)); - - final ResponseEntity responsePost = - (ResponseEntity) sol003PackageManagementSubscriptionController - .postSubscriptionRequest(pkgmSubscriptionRequest); - - final ResponseEntity responseDelete = - sol003PackageManagementSubscriptionController.deleteSubscription(subscriptionId); - - // Attempt to retrieve the subscription after delete - final ResponseEntity responseGetSubscription = - (ResponseEntity) sol003PackageManagementSubscriptionController - .getSubscription(subscriptionId); - - assertEquals(HttpStatus.NOT_FOUND, responseGetSubscription.getStatusCode()); - assertEquals(HttpStatus.NO_CONTENT, responseDelete.getStatusCode()); - } - - @Test - public void testDeleteSubscription_SubscripitonNotFoundInEtsiCatalogManager_SubscriptionDeletedFromLocalCache() - throws GeneralSecurityException { - final PkgmSubscriptionRequest pkgmSubscriptionRequest = buildPkgmSubscriptionRequest(); - final PkgmSubscription pkgmSubscription = buildPkgmSubscription(); - - mockRestServiceServer.expect(requestTo(msbEndpoint)).andExpect(method(HttpMethod.POST)) - .andRespond(withSuccess(gson.toJson(pkgmSubscription), MediaType.APPLICATION_JSON)); - - mockRestServiceServer.expect(requestTo(msbEndpoint + "/" + ID)).andExpect(method(HttpMethod.DELETE)) - .andRespond(withStatus(HttpStatus.NOT_FOUND)); - - final ResponseEntity responsePost = - (ResponseEntity) sol003PackageManagementSubscriptionController - .postSubscriptionRequest(pkgmSubscriptionRequest); - - final Cache cache = - cacheServiceProvider.getCache(PackageManagementConstants.PACKAGE_MANAGEMENT_SUBSCRIPTION_CACHE); - assertNotNull(cache.get(ID)); - - final ResponseEntity responseDelete = sol003PackageManagementSubscriptionController.deleteSubscription(ID); - - assertEquals(HttpStatus.NO_CONTENT, responseDelete.getStatusCode()); - assertNull(cache.get(ID)); - - } - - @Test - public void testFailDeleteSubscriptionWithInvalidSubscriptionId() throws URISyntaxException, InterruptedException { - final ResponseEntity responseDelete = (ResponseEntity) sol003PackageManagementSubscriptionController - .deleteSubscription("invalidSubscriptionId"); - assertEquals(HttpStatus.NOT_FOUND, responseDelete.getStatusCode()); - } - - - @Test - public void testSuccessPostSubscriptionWithValidNotificationTypes() throws Exception { - - final String file = getAbsolutePath("src/test/resources/requests/SubscriptionRequest.json"); - final String json = new String(Files.readAllBytes(Paths.get(file))); - final PkgmSubscriptionRequest request = gson.fromJson(json, PkgmSubscriptionRequest.class); - - mockRestServiceServer.expect(requestTo(msbEndpoint)).andExpect(method(HttpMethod.POST)) - .andExpect(MockRestRequestMatchers.content().json(gson.toJson(getEtsiCatalogPkgmSubscriptionRequest()))) - .andRespond(withSuccess(gson.toJson(buildPkgmSubscription()), MediaType.APPLICATION_JSON)); - - - final ResponseEntity responseEntity = - testRestTemplate.postForEntity(LOCALHOST_URL + port + PACKAGE_MANAGEMENT_BASE_URL + "/subscriptions", - request, InlineResponse201.class); - - assertEquals(HttpStatus.CREATED, responseEntity.getStatusCode()); - assertTrue(responseEntity.hasBody()); - final InlineResponse201 actual = responseEntity.getBody(); - assertEquals(ID, actual.getId()); - - - } - - private org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.model.PkgmSubscriptionRequest getEtsiCatalogPkgmSubscriptionRequest() { - return new org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.model.PkgmSubscriptionRequest() - .filter(new PkgmNotificationsFilter() - .addNotificationTypesItem( - PkgmNotificationsFilter.NotificationTypesEnum.VNFPACKAGEONBOARDINGNOTIFICATION) - .addVnfdIdItem("VNFDID").addVnfPkgIdItem("VNFPKGID") - .addOperationalStateItem(PkgmNotificationsFilter.OperationalStateEnum.ENABLED) - .addVnfProductsFromProvidersItem(new VnfProductsProviders().vnfProvider("EST") - .addVnfProductsItem(new VnfProducts().vnfProductName("VnfProducts") - .addVersionsItem(new Version().vnfSoftwareVersion("vnfSoftwareVersion") - .addVnfdVersionsItem("version1"))))) - .callbackUri(_NOTIFICATION_CALLBACK_URI).authentication( - new SubscriptionAuthentication().addAuthTypeItem(SubscriptionAuthentication.AuthTypeEnum.BASIC) - .paramsBasic(new BasicAuth().userName("vnfm").password("password1$"))); - } - - private PkgmSubscriptionRequest buildPkgmSubscriptionRequest() { - final PkgmSubscriptionRequest pkgmSubscriptionRequest = new PkgmSubscriptionRequest(); - final SubscriptionsFilter1 sub = buildSubscriptionsFilter(); - final SubscriptionsAuthentication auth = new SubscriptionsAuthentication(); - pkgmSubscriptionRequest.setFilter(sub); - pkgmSubscriptionRequest.setCallbackUri(msbEndpoint.toString()); - pkgmSubscriptionRequest.setAuthentication(auth); - return pkgmSubscriptionRequest; - } - - private SubscriptionsFilter1 buildSubscriptionsFilter() { - final SubscriptionsFilter1 sub = new SubscriptionsFilter1(); - final List vnfdIdList = new ArrayList<>(); - final List vnfPkgIdList = new ArrayList<>(); - final List notificationTypes = new ArrayList<>(); - final SubscriptionsFilterVnfProductsFromProviders subscriptionsFilterVnfProductsFromProviders = - new SubscriptionsFilterVnfProductsFromProviders(); - final List vnfProductsFromProviders = new ArrayList<>(); - - vnfProductsFromProviders.add(subscriptionsFilterVnfProductsFromProviders); - sub.setVnfdId(vnfdIdList); - sub.setNotificationTypes(notificationTypes); - sub.setVnfPkgId(vnfPkgIdList); - sub.setVnfProductsFromProviders(vnfProductsFromProviders); - return sub; - } - - private PkgmSubscription buildPkgmSubscription() { - final PkgmSubscription pkgmSubscription = new PkgmSubscription(); - final PkgmNotificationsFilter pkgmNotificationsFilter = new PkgmNotificationsFilter(); - final LinkSelf linkSelf = new LinkSelf(); - - pkgmSubscription.setId(ID); - pkgmSubscription.setCallbackUri(msbEndpoint + "/" + pkgmSubscription.getId().toString()); - pkgmSubscription.setFilter(pkgmNotificationsFilter); - pkgmSubscription.setLinks(linkSelf); - return pkgmSubscription; - } - - private PkgmSubscriptionRequest postSubscriptionForTest() { - final PkgmSubscriptionRequest pkgmSubscriptionRequest = buildPkgmSubscriptionRequest(); - final PkgmSubscription pkgmSubscription = buildPkgmSubscription(); - - mockRestServiceServer.expect(requestTo(msbEndpoint)).andExpect(method(HttpMethod.POST)) - .andRespond(withSuccess(gson.toJson(pkgmSubscription), MediaType.APPLICATION_JSON)); - return pkgmSubscriptionRequest; - } - - private HttpHeaders buildHttpHeaders(final String uri) throws URISyntaxException { - final HttpHeaders headers = new HttpHeaders(); - final URI myUri = new URI(uri); - headers.setLocation(myUri); - return headers; - } - - private String getAbsolutePath(final String path) { - final File file = new File(path); - return file.getAbsolutePath(); - } - -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/test/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/TestApplication.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/test/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/TestApplication.java deleted file mode 100755 index 7e3f925a58..0000000000 --- a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/test/java/org/onap/so/adapters/etsi/sol003/adapter/packagemanagement/rest/TestApplication.java +++ /dev/null @@ -1,38 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.rest; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration; -import org.springframework.cache.annotation.EnableCaching; - -@EnableCaching -@SpringBootApplication(scanBasePackages = {"org.onap.so"}) -@EnableAutoConfiguration(exclude = {JacksonAutoConfiguration.class}) -public class TestApplication { - - public static void main(final String[] args) { - new SpringApplication(TestApplication.class).run(args); - } - -} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/test/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/EtsiSubscriptionNotificationControllerTest.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/test/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/EtsiSubscriptionNotificationControllerTest.java new file mode 100644 index 0000000000..efe6891f1e --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/test/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/EtsiSubscriptionNotificationControllerTest.java @@ -0,0 +1,591 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.pkgm.rest; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.onap.so.adapters.etsi.sol003.adapter.common.CommonConstants.ETSI_SUBSCRIPTION_NOTIFICATION_CONTROLLER_BASE_URL; +import static org.onap.so.client.RestTemplateConfig.CONFIGURABLE_REST_TEMPLATE; +import static org.springframework.test.annotation.DirtiesContext.ClassMode.BEFORE_CLASS; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.header; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.jsonPath; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.method; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; +import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus; +import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; +import java.net.URI; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.onap.so.adapters.etsisol003adapter.etsicatalog.notification.model.NOTIFICATIONLINKSERIALIZER; +import org.onap.so.adapters.etsisol003adapter.etsicatalog.notification.model.PkgChangeNotification; +import org.onap.so.adapters.etsisol003adapter.etsicatalog.notification.model.PkgOnboardingNotification; +import org.onap.so.adapters.etsisol003adapter.etsicatalog.notification.model.PkgmLinks; +import org.onap.so.adapters.etsisol003adapter.pkgm.JSON; +import org.onap.so.adapters.etsisol003adapter.pkgm.PackageManagementConstants; +import org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.model.ProblemDetails; +import org.onap.so.adapters.etsisol003adapter.pkgm.extclients.vnfm.notification.model.VnfPackageChangeNotification; +import org.onap.so.adapters.etsisol003adapter.pkgm.extclients.vnfm.notification.model.VnfPackageOnboardingNotification; +import org.onap.so.adapters.etsisol003adapter.pkgm.model.PkgmSubscriptionRequest; +import org.onap.so.adapters.etsisol003adapter.pkgm.model.SubscriptionsAuthentication; +import org.onap.so.adapters.etsisol003adapter.pkgm.model.SubscriptionsAuthenticationParamsBasic; +import org.onap.so.adapters.etsisol003adapter.pkgm.model.SubscriptionsAuthenticationParamsOauth2ClientCredentials; +import org.onap.so.configuration.rest.BasicHttpHeadersProvider; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.cache.Cache; +import org.springframework.cache.CacheManager; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.http.converter.json.GsonHttpMessageConverter; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.client.MockRestServiceServer; +import org.springframework.web.client.RestTemplate; +import com.google.gson.Gson; + +/** + * @author Andrew Lamb (andrew.a.lamb@est.tech) + * + */ +@RunWith(SpringRunner.class) +@SpringBootTest(classes = TestApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@ActiveProfiles("test") +@DirtiesContext(classMode = BEFORE_CLASS) +public class EtsiSubscriptionNotificationControllerTest { + + @LocalServerPort + private int port; + + private static final URI CALLBACK_URI = URI.create("http://test_callback_uri/notification"); + private static final String TOKEN_ENDPOINT = "http://test_token_endpoint_uri/"; + private static final String TOKEN = "dXNlcm5hbWU6cGFzc3dvcmQ=......"; + private static final String JSON_TOKEN = "{\"access_token\":\"" + TOKEN + "\"}"; + private static final String LOCALHOST_URL = "http://localhost:"; + private static final String NOTIFICATION_BASE_URL = + ETSI_SUBSCRIPTION_NOTIFICATION_CONTROLLER_BASE_URL + "/notification"; + private static final String USERNAME = "username"; + private static final String PASSWORD = "password"; + private static final String EXPECTED_BASIC_AUTHORIZATION = "Basic dXNlcm5hbWU6cGFzc3dvcmQ="; + private static final String EXPECTED_OAUTH_AUTHORIZATION = "Bearer " + TOKEN; + private static final String NOTIFICATION_ID = "NOTIFICATION_ID"; + private static final String SUBSCRIPTION_ID = "SUBSCRIPTION_ID"; + private static final String TIME_STAMP_STRING_EXPECTED_FROM_ETSI_CATALOG = "2020-01-01 01:01:01"; + private static final java.time.LocalDateTime TIMESTAMP = java.time.LocalDateTime.of(2020, 1, 1, 1, 1, 1, 1); + private static final String VNFPKG_ID = UUID.randomUUID().toString(); + private static final String VNFD_ID = UUID.randomUUID().toString(); + private static final String EXPECTED_VNF_PACKAGE_HREF = + "https://so-vnfm-adapter.onap:30406/so/vnfm-adapter/v1/vnfpkgm/v1/vnf_packages/" + VNFPKG_ID; + private static final String EXPECTED_SUBSCRIPTION_HREF = + "https://so-vnfm-adapter.onap:30406/so/vnfm-adapter/v1/vnfpkgm/v1/subscriptions/" + SUBSCRIPTION_ID; + + + private BasicHttpHeadersProvider basicHttpHeadersProvider; + + @Autowired + @Qualifier(CONFIGURABLE_REST_TEMPLATE) + private RestTemplate restTemplate; + private MockRestServiceServer mockRestServiceServer; + + private TestRestTemplate testRestTemplate; + + @Autowired + private CacheManager cacheServiceProvider; + private Cache cache; + + @Before + public void setUp() { + mockRestServiceServer = MockRestServiceServer.bindTo(restTemplate).build(); + basicHttpHeadersProvider = new BasicHttpHeadersProvider(); + cache = cacheServiceProvider.getCache(PackageManagementConstants.PACKAGE_MANAGEMENT_SUBSCRIPTION_CACHE); + cache.clear(); + + final Gson gson = JSON.createGson().registerTypeAdapter(LocalDateTime.class, + new EtsiSubscriptionNotificationController.LocalDateTimeTypeAdapter()).create(); + testRestTemplate = new TestRestTemplate( + new RestTemplateBuilder().additionalMessageConverters(new GsonHttpMessageConverter(gson))); + } + + + @After + public void tearDown() { + mockRestServiceServer.reset(); + cache.clear(); + } + + @Test + public void testSubscriptionNotificationEndPoint_ReturnsNoContent() { + final ResponseEntity response = sendHttpGet(NOTIFICATION_BASE_URL); + assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode()); + } + + @Test + public void testOnboardingNotificationSentOnToVnfmCallbackUri_SubscriptionRequestInCache_Success() { + final PkgmSubscriptionRequest subscriptionRequest = + buildPkgmSubscriptionRequest(SubscriptionsAuthentication.AuthTypeEnum.BASIC); + cache.put(SUBSCRIPTION_ID, subscriptionRequest); + final PkgOnboardingNotification notification = buildPkgOnboardingNotification(); + + mockRestServiceServer.expect(requestTo(CALLBACK_URI)).andExpect(method(HttpMethod.POST)) + .andExpect(jsonPath("$.id").value(NOTIFICATION_ID)) + .andExpect(jsonPath("$.notificationType") + .value(VnfPackageOnboardingNotification.NotificationTypeEnum.VNFPACKAGEONBOARDINGNOTIFICATION + .toString())) + .andExpect(jsonPath("$.subscriptionId").value(SUBSCRIPTION_ID)) + .andExpect(jsonPath("$.timeStamp").value(TIME_STAMP_STRING_EXPECTED_FROM_ETSI_CATALOG)) + .andExpect(jsonPath("$.vnfPkgId").value(VNFPKG_ID)).andExpect(jsonPath("$.vnfdId").value(VNFD_ID)) + .andExpect(jsonPath("$._links") + .value(buildPkgmLinks(EXPECTED_VNF_PACKAGE_HREF, EXPECTED_SUBSCRIPTION_HREF))) + .andExpect(header("Authorization", EXPECTED_BASIC_AUTHORIZATION)).andRespond(withSuccess()); + + final ResponseEntity response = sendHttpPost(notification); + + assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode()); + } + + @Test + public void testOnboardingNotificationNotSentOnToVnfmCallbackUri_SubscriptionRequestNotInCache_Fail() { + final PkgOnboardingNotification notification = buildPkgOnboardingNotification(); + final ResponseEntity response = sendHttpPost(notification); + + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); + assertTrue(response.getBody() instanceof ProblemDetails); + + final ProblemDetails problemDetails = (ProblemDetails) response.getBody(); + final String errorMessage = "No subscription found with subscriptionId " + SUBSCRIPTION_ID + + ". Unable to forward notification to subscriber."; + + assertEquals(errorMessage, problemDetails.getDetail()); + } + + @Test + public void testOnboardingNotificationSentOnToVnfmCallbackUri_BadRequestResponseFromCallbackUri_Fail() { + final PkgmSubscriptionRequest subscriptionRequest = + buildPkgmSubscriptionRequest(SubscriptionsAuthentication.AuthTypeEnum.BASIC); + cache.put(SUBSCRIPTION_ID, subscriptionRequest); + final PkgOnboardingNotification notification = buildPkgOnboardingNotification(); + + mockRestServiceServer.expect(requestTo(CALLBACK_URI)).andExpect(method(HttpMethod.POST)) + .andRespond(withStatus(HttpStatus.BAD_REQUEST)); + + final ResponseEntity response = sendHttpPost(notification); + + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); + assertTrue(response.getBody() instanceof ProblemDetails); + + final ProblemDetails problemDetails = (ProblemDetails) response.getBody(); + final String errorMessage = "An error occurred. Sending of notification to VNFM failed with response: " + + HttpStatus.BAD_REQUEST + ".\n" + "No result found for given url: " + CALLBACK_URI; + + assertEquals(errorMessage, problemDetails.getDetail()); + } + + @Test + public void testOnboardingNotificationSentOnToVnfmCallbackUri_301MovedPermanentlyResponseFromCallbackUri_Fail() { + final PkgmSubscriptionRequest subscriptionRequest = + buildPkgmSubscriptionRequest(SubscriptionsAuthentication.AuthTypeEnum.BASIC); + cache.put(SUBSCRIPTION_ID, subscriptionRequest); + final PkgOnboardingNotification notification = buildPkgOnboardingNotification(); + + mockRestServiceServer.expect(requestTo(CALLBACK_URI)).andExpect(method(HttpMethod.POST)) + .andRespond(withStatus(HttpStatus.MOVED_PERMANENTLY)); + + final ResponseEntity response = sendHttpPost(notification); + + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); + assertTrue(response.getBody() instanceof ProblemDetails); + + final ProblemDetails problemDetails = (ProblemDetails) response.getBody(); + final String errorMessage = "An error occurred. Sending of notification to VNFM failed."; + + assertEquals(errorMessage, problemDetails.getDetail()); + } + + @Test + public void testOnboardingNotificationSentOnToVnfmCallbackUri_NotFoundResponseFromCallbackUri_Fail() { + final PkgmSubscriptionRequest subscriptionRequest = + buildPkgmSubscriptionRequest(SubscriptionsAuthentication.AuthTypeEnum.BASIC); + cache.put(SUBSCRIPTION_ID, subscriptionRequest); + final PkgOnboardingNotification notification = buildPkgOnboardingNotification(); + + mockRestServiceServer.expect(requestTo(CALLBACK_URI)).andExpect(method(HttpMethod.POST)) + .andRespond(withStatus(HttpStatus.NOT_FOUND)); + + final ResponseEntity response = sendHttpPost(notification); + + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); + assertTrue(response.getBody() instanceof ProblemDetails); + + final ProblemDetails problemDetails = (ProblemDetails) response.getBody(); + final String errorMessage = "An error occurred. Sending of notification to VNFM failed with response: " + + HttpStatus.NOT_FOUND + ".\n" + "No result found for given url: " + CALLBACK_URI; + + assertEquals(errorMessage, problemDetails.getDetail()); + } + + @Test + public void testOnboardingNotificationSentOnToVnfmCallbackUri_InternalServerErrorResponseFromCallbackUri_Fail() { + final PkgmSubscriptionRequest subscriptionRequest = + buildPkgmSubscriptionRequest(SubscriptionsAuthentication.AuthTypeEnum.BASIC); + cache.put(SUBSCRIPTION_ID, subscriptionRequest); + final PkgOnboardingNotification notification = buildPkgOnboardingNotification(); + + mockRestServiceServer.expect(requestTo(CALLBACK_URI)).andExpect(method(HttpMethod.POST)) + .andRespond(withStatus(HttpStatus.INTERNAL_SERVER_ERROR)); + + final ResponseEntity response = sendHttpPost(notification); + + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); + assertTrue(response.getBody() instanceof ProblemDetails); + + final ProblemDetails problemDetails = (ProblemDetails) response.getBody(); + final String errorMessage = "An error occurred. Sending of notification to VNFM failed with response: " + + HttpStatus.INTERNAL_SERVER_ERROR.value() + ".\n" + "Unable to invoke HTTP POST using URL: " + + CALLBACK_URI; + + assertEquals(errorMessage, problemDetails.getDetail()); + } + + @Test + public void testChangeNotificationSentOnToVnfmCallbackUri_SubscriptionRequestInCache_Success() { + final PkgmSubscriptionRequest subscriptionRequest = + buildPkgmSubscriptionRequest(SubscriptionsAuthentication.AuthTypeEnum.BASIC); + cache.put(SUBSCRIPTION_ID, subscriptionRequest); + final PkgChangeNotification notification = buildPkgChangeNotification(); + + mockRestServiceServer.expect(requestTo(CALLBACK_URI)).andExpect(method(HttpMethod.POST)) + .andExpect(jsonPath("$.id").value(NOTIFICATION_ID)) + .andExpect(jsonPath("$.notificationType").value( + VnfPackageChangeNotification.NotificationTypeEnum.VNFPACKAGECHANGENOTIFICATION.getValue())) + .andExpect(jsonPath("$.subscriptionId").value(SUBSCRIPTION_ID)) + .andExpect(jsonPath("$.timeStamp").value(TIME_STAMP_STRING_EXPECTED_FROM_ETSI_CATALOG)) + .andExpect(jsonPath("$.vnfPkgId").value(VNFPKG_ID)).andExpect(jsonPath("$.vnfdId").value(VNFD_ID)) + .andExpect( + jsonPath("$.changeType").value(PkgChangeNotification.ChangeTypeEnum.OP_STATE_CHANGE.toString())) + .andExpect(jsonPath("$.operationalState") + .value(PkgChangeNotification.OperationalStateEnum.ENABLED.toString())) + .andExpect(jsonPath("$._links") + .value(buildPkgmLinks(EXPECTED_VNF_PACKAGE_HREF, EXPECTED_SUBSCRIPTION_HREF))) + .andExpect(header("Authorization", EXPECTED_BASIC_AUTHORIZATION)).andRespond(withSuccess()); + + final ResponseEntity response = sendHttpPost(notification); + + assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode()); + } + + @Test + public void testChangeNotificationNotSentOnToVnfmCallbackUri_SubscriptionRequestNotInCache_Fail() { + final PkgChangeNotification notification = buildPkgChangeNotification(); + final ResponseEntity response = sendHttpPost(notification); + + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); + assertTrue(response.getBody() instanceof ProblemDetails); + + final ProblemDetails problemDetails = (ProblemDetails) response.getBody(); + final String errorMessage = "No subscription found with subscriptionId " + SUBSCRIPTION_ID + + ". Unable to forward notification to subscriber."; + + assertEquals(errorMessage, problemDetails.getDetail()); + } + + @Test + public void testChangeNotificationSentOnToVnfmCallbackUri_BadRequestResponseFromCallbackUri_Fail() { + final PkgmSubscriptionRequest subscriptionRequest = + buildPkgmSubscriptionRequest(SubscriptionsAuthentication.AuthTypeEnum.BASIC); + cache.put(SUBSCRIPTION_ID, subscriptionRequest); + final PkgChangeNotification notification = buildPkgChangeNotification(); + + mockRestServiceServer.expect(requestTo(CALLBACK_URI)).andExpect(method(HttpMethod.POST)) + .andRespond(withStatus(HttpStatus.BAD_REQUEST)); + + final ResponseEntity response = sendHttpPost(notification); + + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); + assertTrue(response.getBody() instanceof ProblemDetails); + + final ProblemDetails problemDetails = (ProblemDetails) response.getBody(); + final String errorMessage = "An error occurred. Sending of notification to VNFM failed with response: " + + HttpStatus.BAD_REQUEST + ".\n" + "No result found for given url: " + CALLBACK_URI; + + assertEquals(errorMessage, problemDetails.getDetail()); + } + + @Test + public void testChangeNotificationSentOnToVnfmCallbackUri_NotFoundResponseFromCallbackUri_Fail() { + final PkgmSubscriptionRequest subscriptionRequest = + buildPkgmSubscriptionRequest(SubscriptionsAuthentication.AuthTypeEnum.BASIC); + cache.put(SUBSCRIPTION_ID, subscriptionRequest); + final PkgChangeNotification notification = buildPkgChangeNotification(); + + mockRestServiceServer.expect(requestTo(CALLBACK_URI)).andExpect(method(HttpMethod.POST)) + .andRespond(withStatus(HttpStatus.NOT_FOUND)); + + final ResponseEntity response = sendHttpPost(notification); + + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); + assertTrue(response.getBody() instanceof ProblemDetails); + + final ProblemDetails problemDetails = (ProblemDetails) response.getBody(); + final String errorMessage = "An error occurred. Sending of notification to VNFM failed with response: " + + HttpStatus.NOT_FOUND + ".\n" + "No result found for given url: " + CALLBACK_URI; + + assertEquals(errorMessage, problemDetails.getDetail()); + } + + @Test + public void testChangeNotificationSentOnToVnfmCallbackUri_InternalServerErrorResponseFromCallbackUri_Fail() { + final PkgmSubscriptionRequest subscriptionRequest = + buildPkgmSubscriptionRequest(SubscriptionsAuthentication.AuthTypeEnum.BASIC); + cache.put(SUBSCRIPTION_ID, subscriptionRequest); + final PkgChangeNotification notification = buildPkgChangeNotification(); + + mockRestServiceServer.expect(requestTo(CALLBACK_URI)).andExpect(method(HttpMethod.POST)) + .andRespond(withStatus(HttpStatus.INTERNAL_SERVER_ERROR)); + + final ResponseEntity response = sendHttpPost(notification); + + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); + assertTrue(response.getBody() instanceof ProblemDetails); + + final ProblemDetails problemDetails = (ProblemDetails) response.getBody(); + final String errorMessage = "An error occurred. Sending of notification to VNFM failed with response: " + + HttpStatus.INTERNAL_SERVER_ERROR.value() + ".\n" + "Unable to invoke HTTP POST using URL: " + + CALLBACK_URI; + + assertEquals(errorMessage, problemDetails.getDetail()); + } + + @Test + public void testNotificationSentOnToVnfm_BasicAuthUserPasswordAuthorized_Success() { + final PkgmSubscriptionRequest subscriptionRequest = + buildPkgmSubscriptionRequest(SubscriptionsAuthentication.AuthTypeEnum.BASIC); + cache.put(SUBSCRIPTION_ID, subscriptionRequest); + final PkgOnboardingNotification notification = buildPkgOnboardingNotification(); + + mockRestServiceServer.expect(requestTo(CALLBACK_URI)).andExpect(method(HttpMethod.POST)) + .andExpect(jsonPath("$.id").value(NOTIFICATION_ID)) + .andExpect(jsonPath("$.notificationType") + .value(VnfPackageOnboardingNotification.NotificationTypeEnum.VNFPACKAGEONBOARDINGNOTIFICATION + .toString())) + .andExpect(jsonPath("$.subscriptionId").value(SUBSCRIPTION_ID)) + .andExpect(jsonPath("$.timeStamp").value(TIME_STAMP_STRING_EXPECTED_FROM_ETSI_CATALOG)) + .andExpect(jsonPath("$.vnfPkgId").value(VNFPKG_ID)).andExpect(jsonPath("$.vnfdId").value(VNFD_ID)) + .andExpect(jsonPath("$._links") + .value(buildPkgmLinks(EXPECTED_VNF_PACKAGE_HREF, EXPECTED_SUBSCRIPTION_HREF))) + .andExpect(header("Authorization", EXPECTED_BASIC_AUTHORIZATION)).andRespond(withSuccess()); + + final ResponseEntity response = sendHttpPost(notification); + + assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode()); + } + + @Test + public void testNotificationSentOnToVnfm_BasicAuthUserPasswordNotAuthorized_Fail() { + final PkgmSubscriptionRequest subscriptionRequest = + buildPkgmSubscriptionRequest(SubscriptionsAuthentication.AuthTypeEnum.BASIC); + cache.put(SUBSCRIPTION_ID, subscriptionRequest); + final PkgChangeNotification notification = buildPkgChangeNotification(); + + mockRestServiceServer.expect(requestTo(CALLBACK_URI)).andExpect(method(HttpMethod.POST)) + .andExpect(header("Authorization", EXPECTED_BASIC_AUTHORIZATION)) + .andRespond(withStatus(HttpStatus.UNAUTHORIZED)); + + final ResponseEntity response = sendHttpPost(notification); + + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); + assertTrue(response.getBody() instanceof ProblemDetails); + + final ProblemDetails problemDetails = (ProblemDetails) response.getBody(); + final String errorMessage = "An error occurred. Sending of notification to VNFM failed with response: " + + HttpStatus.UNAUTHORIZED.value() + ".\n" + "Unable to invoke HTTP POST using URL: " + CALLBACK_URI; + + assertEquals(errorMessage, problemDetails.getDetail()); + } + + @Test + public void testNotificationSentOnToVnfm_OAuthAuthorized_Success() { + final PkgmSubscriptionRequest subscriptionRequest = + buildPkgmSubscriptionRequest(SubscriptionsAuthentication.AuthTypeEnum.OAUTH2_CLIENT_CREDENTIALS); + cache.put(SUBSCRIPTION_ID, subscriptionRequest); + final PkgChangeNotification notification = buildPkgChangeNotification(); + + mockRestServiceServer.expect(requestTo(TOKEN_ENDPOINT)).andExpect(method(HttpMethod.POST)) + .andExpect(header("Authorization", EXPECTED_BASIC_AUTHORIZATION)) + .andRespond(withSuccess(JSON_TOKEN, MediaType.APPLICATION_JSON)); + + mockRestServiceServer.expect(requestTo(CALLBACK_URI)).andExpect(method(HttpMethod.POST)) + .andExpect(header("Authorization", EXPECTED_OAUTH_AUTHORIZATION)) + .andExpect(jsonPath("$.id").value(NOTIFICATION_ID)) + .andExpect(jsonPath("$.notificationType").value( + VnfPackageChangeNotification.NotificationTypeEnum.VNFPACKAGECHANGENOTIFICATION.toString())) + .andExpect(jsonPath("$.subscriptionId").value(SUBSCRIPTION_ID)) + .andExpect(jsonPath("$.timeStamp").value(TIME_STAMP_STRING_EXPECTED_FROM_ETSI_CATALOG)) + .andExpect(jsonPath("$.vnfPkgId").value(VNFPKG_ID)).andExpect(jsonPath("$.vnfdId").value(VNFD_ID)) + .andExpect( + jsonPath("$.changeType").value(PkgChangeNotification.ChangeTypeEnum.OP_STATE_CHANGE.toString())) + .andExpect(jsonPath("$.operationalState") + .value(PkgChangeNotification.OperationalStateEnum.ENABLED.toString())) + .andExpect(jsonPath("$._links") + .value(buildPkgmLinks(EXPECTED_VNF_PACKAGE_HREF, EXPECTED_SUBSCRIPTION_HREF))) + .andRespond(withSuccess()); + + final ResponseEntity response = sendHttpPost(notification); + + assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode()); + } + + @Test + public void testNotificationSentOnToVnfm_OAuthTokenNotReceived_Fail() { + final PkgmSubscriptionRequest subscriptionRequest = + buildPkgmSubscriptionRequest(SubscriptionsAuthentication.AuthTypeEnum.OAUTH2_CLIENT_CREDENTIALS); + cache.put(SUBSCRIPTION_ID, subscriptionRequest); + final PkgChangeNotification notification = buildPkgChangeNotification(); + + mockRestServiceServer.expect(requestTo(TOKEN_ENDPOINT)).andExpect(method(HttpMethod.POST)) + .andExpect(header("Authorization", EXPECTED_BASIC_AUTHORIZATION)).andRespond(withSuccess()); + + final ResponseEntity response = sendHttpPost(notification); + + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); + assertTrue(response.getBody() instanceof ProblemDetails); + + final ProblemDetails problemDetails = (ProblemDetails) response.getBody(); + final String errorMessage = "An error occurred. Unable to retrieve OAuth Token from VNFM for notification."; + + assertEquals(errorMessage, problemDetails.getDetail()); + } + + @Test + public void testNotificationSentOnToVnfm_TLSCertNotYetSupported_Fail() { + final PkgmSubscriptionRequest subscriptionRequest = + buildPkgmSubscriptionRequest(SubscriptionsAuthentication.AuthTypeEnum.TLS_CERT); + cache.put(SUBSCRIPTION_ID, subscriptionRequest); + final PkgChangeNotification notification = buildPkgChangeNotification(); + + final ResponseEntity response = sendHttpPost(notification); + + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); + assertTrue(response.getBody() instanceof ProblemDetails); + + final ProblemDetails problemDetails = (ProblemDetails) response.getBody(); + final String errorMessage = "An error occurred. Authentication type " + + subscriptionRequest.getAuthentication().getAuthType().toString() + " not currently supported."; + + assertEquals(errorMessage, problemDetails.getDetail()); + } + + private PkgOnboardingNotification buildPkgOnboardingNotification() { + final PkgOnboardingNotification notification = new PkgOnboardingNotification(); + notification.setId(NOTIFICATION_ID); + notification + .setNotificationType(PkgOnboardingNotification.NotificationTypeEnum.VNFPACKAGEONBOARDINGNOTIFICATION); + notification.setSubscriptionId(SUBSCRIPTION_ID); + notification.setTimeStamp(TIMESTAMP); + notification.setVnfPkgId(VNFPKG_ID); + notification.setVnfdId(VNFD_ID); + notification.setLinks(buildPkgmLinks()); + return notification; + } + + private PkgChangeNotification buildPkgChangeNotification() { + final PkgChangeNotification notification = new PkgChangeNotification(); + notification.setId(NOTIFICATION_ID); + notification.setNotificationType(PkgChangeNotification.NotificationTypeEnum.VNFPACKAGECHANGENOTIFICATION); + notification.setSubscriptionId(SUBSCRIPTION_ID); + notification.setTimeStamp(TIMESTAMP); + notification.setVnfPkgId(VNFPKG_ID); + notification.setVnfdId(VNFD_ID); + notification.setChangeType(PkgChangeNotification.ChangeTypeEnum.OP_STATE_CHANGE); + notification.setOperationalState(PkgChangeNotification.OperationalStateEnum.ENABLED); + notification.setLinks(buildPkgmLinks()); + return notification; + } + + private PkgmLinks buildPkgmLinks() { + return buildPkgmLinks("vnf_package_href", "subscription_href"); + } + + private PkgmLinks buildPkgmLinks(final String vnfPkgHref, final String subscriptionHref) { + return new PkgmLinks().vnfPackage(new NOTIFICATIONLINKSERIALIZER().href(vnfPkgHref)) + .subscription(new NOTIFICATIONLINKSERIALIZER().href(subscriptionHref)); + } + + private PkgmSubscriptionRequest buildPkgmSubscriptionRequest( + final SubscriptionsAuthentication.AuthTypeEnum authTypeEnum) { + final PkgmSubscriptionRequest subscriptionRequest = new PkgmSubscriptionRequest(); + subscriptionRequest.setCallbackUri(CALLBACK_URI.toString()); + subscriptionRequest.setAuthentication(buildSubscriptionsAuthentication(authTypeEnum)); + return subscriptionRequest; + } + + // TODO update for auth types other than basicAuth + private SubscriptionsAuthentication buildSubscriptionsAuthentication( + final SubscriptionsAuthentication.AuthTypeEnum authTypeEnum) { + final SubscriptionsAuthentication subscriptionsAuthentication = new SubscriptionsAuthentication(); + final List authTypes = new ArrayList<>(); + authTypes.add(authTypeEnum); + subscriptionsAuthentication.setAuthType(authTypes); + if (authTypeEnum == SubscriptionsAuthentication.AuthTypeEnum.TLS_CERT) { + // TODO: remove basic params and code for TLS + final SubscriptionsAuthenticationParamsBasic basicParams = + new SubscriptionsAuthenticationParamsBasic().userName(USERNAME).password(PASSWORD); + subscriptionsAuthentication.setParamsBasic(basicParams); + } else if (authTypeEnum == SubscriptionsAuthentication.AuthTypeEnum.OAUTH2_CLIENT_CREDENTIALS) { + final SubscriptionsAuthenticationParamsOauth2ClientCredentials oathParams = + new SubscriptionsAuthenticationParamsOauth2ClientCredentials().clientId(USERNAME) + .clientPassword(PASSWORD).tokenEndpoint(TOKEN_ENDPOINT); + subscriptionsAuthentication.setParamsOauth2ClientCredentials(oathParams); + } else { + final SubscriptionsAuthenticationParamsBasic basicParams = + new SubscriptionsAuthenticationParamsBasic().userName(USERNAME).password(PASSWORD); + subscriptionsAuthentication.setParamsBasic(basicParams); + } + + return subscriptionsAuthentication; + } + + private ResponseEntity sendHttpPost(final T notification) { + final String testURL = LOCALHOST_URL + port + NOTIFICATION_BASE_URL; + final HttpEntity request = new HttpEntity<>(notification, basicHttpHeadersProvider.getHttpHeaders()); + return testRestTemplate.withBasicAuth("test", "test").exchange(testURL, HttpMethod.POST, request, + ProblemDetails.class); + } + + private ResponseEntity sendHttpGet(final String url) { + final String testURL = LOCALHOST_URL + port + url; + final HttpEntity request = new HttpEntity<>(basicHttpHeadersProvider.getHttpHeaders()); + return testRestTemplate.withBasicAuth("test", "test").exchange(testURL, HttpMethod.GET, request, Void.class); + } + +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/test/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/Sol003PackageManagementControllerTest.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/test/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/Sol003PackageManagementControllerTest.java new file mode 100644 index 0000000000..10e4ea3a58 --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/test/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/Sol003PackageManagementControllerTest.java @@ -0,0 +1,677 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.pkgm.rest; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.onap.so.adapters.etsi.sol003.adapter.common.CommonConstants.PACKAGE_MANAGEMENT_BASE_URL; +import static org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.EtsiCatalogServiceProviderConfiguration.ETSI_CATALOG_REST_TEMPLATE_BEAN; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.method; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; +import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus; +import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; +import java.util.ArrayList; +import java.util.List; +import java.util.Random; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.model.Checksum; +import org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.model.ProblemDetails; +import org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.model.UriLink; +import org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.model.VNFPKGMLinkSerializer; +import org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.model.VnfPackageArtifactInfo; +import org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.model.VnfPackageSoftwareImageInfo; +import org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.model.VnfPkgInfo; +import org.onap.so.adapters.etsisol003adapter.pkgm.model.InlineResponse2001; +import org.onap.so.adapters.etsisol003adapter.pkgm.model.VnfPackagesLinks; +import org.onap.so.configuration.rest.BasicHttpHeadersProvider; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.client.MockRestServiceServer; +import org.springframework.web.client.RestTemplate; +import com.google.gson.Gson; + +/** + * @author gareth.roper@est.tech + */ +@RunWith(SpringRunner.class) +@SpringBootTest(classes = TestApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@ActiveProfiles("test") +public class Sol003PackageManagementControllerTest { + + @LocalServerPort + private int port; + + @Autowired + @Qualifier(ETSI_CATALOG_REST_TEMPLATE_BEAN) + private RestTemplate restTemplate; + + @Autowired + private TestRestTemplate testRestTemplate; + + private static final String VNF_PACKAGE_ID = "myVnfPackageId"; + private static final String ARTIFACT_PATH = "myArtifactPath"; + private static final String MSB_BASE_URL = "http://msb-iag.onap:80/api/vnfpkgm/v1/vnf_packages"; + private static final String VNFPKGM_BASE_URL = PACKAGE_MANAGEMENT_BASE_URL + "/vnf_packages"; + private static final String localhostUrl = "http://localhost:"; + private static final String GET_VNF_PACKAGES_URL = ""; + private static final String GET_VNF_PACKAGE_BY_ID_URL = "/" + VNF_PACKAGE_ID; + private static final String VNFD_ID = "vnfdId"; + private static final String VNF_PROVIDER = "vnfProvider"; + private static final String VNF_PRODUCT_NAME = "vnfProductName"; + private static final String VNF_SOFTWARE_VERSION = "vnfSoftwareVersion"; + private static final String VNFD_VERSION = "vnfdVersion"; + private static final String ALGORITHM = "algorithm"; + private static final String HASH = "hash"; + private static final String EXPECTED_BASE_URL = + "https://so-vnfm-adapter.onap:30406/so/vnfm-adapter/v1/vnfpkgm/v1/vnf_packages/"; + private static final String EXPECTED_SELF_HREF = EXPECTED_BASE_URL + VNF_PACKAGE_ID; + private static final String EXPECTED_VNFD_HREF = EXPECTED_BASE_URL + VNF_PACKAGE_ID + "/vnfd"; + private static final String EXPECTED_PACKAGE_CONTENT_HREF = EXPECTED_BASE_URL + VNF_PACKAGE_ID + "/package_content"; + + private MockRestServiceServer mockRestServiceServer; + private BasicHttpHeadersProvider basicHttpHeadersProvider; + private final Gson gson = new Gson(); + + public Sol003PackageManagementControllerTest() {} + + @Before + public void setUp() { + final MockRestServiceServer.MockRestServiceServerBuilder builder = MockRestServiceServer.bindTo(restTemplate); + builder.ignoreExpectOrder(true); + mockRestServiceServer = builder.build(); + basicHttpHeadersProvider = new BasicHttpHeadersProvider(); + } + + @After + public void after() { + mockRestServiceServer.reset(); + } + + @Test + public void testGetPackageContent_ValidArray_Success() { + final byte[] responseArray = buildByteArrayWithRandomData(10); + + mockRestServiceServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/package_content")) + .andExpect(method(HttpMethod.GET)) + .andRespond(withSuccess(responseArray, MediaType.APPLICATION_OCTET_STREAM)); + + final String testURL = "http://localhost:" + port + PACKAGE_MANAGEMENT_BASE_URL + "/vnf_packages/" + + VNF_PACKAGE_ID + "/package_content"; + final HttpEntity request = new HttpEntity<>(basicHttpHeadersProvider.getHttpHeaders()); + final ResponseEntity responseEntity = + testRestTemplate.withBasicAuth("test", "test").exchange(testURL, HttpMethod.GET, request, byte[].class); + + assertEquals(byte[].class, responseEntity.getBody().getClass()); + assertArrayEquals(responseEntity.getBody(), responseArray); + assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); + } + + @Test + public void testOnGetPackageContent_Conflict_Fail() { + mockRestServiceServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/package_content")) + .andExpect(method(HttpMethod.GET)).andRespond(withStatus(HttpStatus.CONFLICT)); + + final ResponseEntity responseEntity = sendHttpRequest(VNF_PACKAGE_ID + "/package_content"); + + assertTrue(responseEntity.getBody() instanceof ProblemDetails); + assertEquals(HttpStatus.CONFLICT, responseEntity.getStatusCode()); + } + + @Test + public void testOnGetPackageContent_NotFound_Fail() { + mockRestServiceServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/package_content")) + .andExpect(method(HttpMethod.GET)).andRespond(withStatus(HttpStatus.NOT_FOUND)); + + final ResponseEntity responseEntity = sendHttpRequest(VNF_PACKAGE_ID + "/package_content"); + + assertTrue(responseEntity.getBody() instanceof ProblemDetails); + assertEquals(HttpStatus.NOT_FOUND, responseEntity.getStatusCode()); + } + + @Test + public void testOnGetPackageContent_UnauthorizedClient_Fail() { + final String testURL = "http://localhost:" + port + PACKAGE_MANAGEMENT_BASE_URL + "/vnf_packages/" + + VNF_PACKAGE_ID + "/package_content"; + + mockRestServiceServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/package_content")) + .andExpect(method(HttpMethod.GET)).andRespond(withStatus(HttpStatus.UNAUTHORIZED)); + + final HttpEntity request = new HttpEntity<>(basicHttpHeadersProvider.getHttpHeaders()); + + + final ResponseEntity responseEntity = + testRestTemplate.exchange(testURL, HttpMethod.GET, request, ProblemDetails.class); + + assertTrue(responseEntity.getBody() instanceof ProblemDetails); + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); + } + + @Test + public void testOnGetPackageContent_InternalServerError_Fail() { + mockRestServiceServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/package_content")) + .andExpect(method(HttpMethod.GET)).andRespond(withStatus(HttpStatus.INTERNAL_SERVER_ERROR)); + + final ResponseEntity responseEntity = sendHttpRequest(VNF_PACKAGE_ID + "/package_content"); + + assertTrue(responseEntity.getBody() instanceof ProblemDetails); + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); + } + + @Test + public void testOnGetPackageContent_BadRequest_Fail() { + mockRestServiceServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/package_content")) + .andExpect(method(HttpMethod.GET)).andRespond(withStatus(HttpStatus.BAD_REQUEST)); + + final ResponseEntity responseEntity = sendHttpRequest(VNF_PACKAGE_ID + "/package_content"); + + assertTrue(responseEntity.getBody() instanceof ProblemDetails); + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); + } + + @Test + public void testOnGetPackageContent_UnauthorizedServer_InternalError_Fail() { + mockRestServiceServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/package_content")) + .andExpect(method(HttpMethod.GET)).andRespond(withStatus(HttpStatus.UNAUTHORIZED)); + + final ResponseEntity responseEntity = sendHttpRequest(VNF_PACKAGE_ID + "/package_content"); + + assertTrue(responseEntity.getBody() instanceof ProblemDetails); + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); + } + + @Test + public void testGetPackageContent_SuccessResponseFromServerWithNullPackage_Fail() { + mockRestServiceServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/package_content")) + .andExpect(method(HttpMethod.GET)).andRespond(withSuccess()); + + final ResponseEntity responseEntity = sendHttpRequest(VNF_PACKAGE_ID + "/package_content"); + + assertEquals(ProblemDetails.class, responseEntity.getBody().getClass()); + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); + } + + @Test + public void testGetPackageArtifact_ValidArray_Success() { + final byte[] responseArray = buildByteArrayWithRandomData(10); + + mockRestServiceServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/artifacts/" + ARTIFACT_PATH)) + .andExpect(method(HttpMethod.GET)) + .andRespond(withSuccess(responseArray, MediaType.APPLICATION_OCTET_STREAM)); + + final String testURL = "http://localhost:" + port + PACKAGE_MANAGEMENT_BASE_URL + "/vnf_packages/" + + VNF_PACKAGE_ID + "/artifacts/" + ARTIFACT_PATH; + final HttpEntity request = new HttpEntity<>(basicHttpHeadersProvider.getHttpHeaders()); + final ResponseEntity responseEntity = + testRestTemplate.withBasicAuth("test", "test").exchange(testURL, HttpMethod.GET, request, byte[].class); + + assertEquals(byte[].class, responseEntity.getBody().getClass()); + assertArrayEquals(responseEntity.getBody(), responseArray); + assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); + } + + @Test + public void testOnGetPackageArtifact_Conflict_Fail() { + mockRestServiceServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/artifacts/" + ARTIFACT_PATH)) + .andExpect(method(HttpMethod.GET)).andRespond(withStatus(HttpStatus.CONFLICT)); + + final ResponseEntity responseEntity = + sendHttpRequest(VNF_PACKAGE_ID + "/artifacts/" + ARTIFACT_PATH); + + assertNotNull(responseEntity.getBody()); + assertEquals(HttpStatus.CONFLICT, responseEntity.getStatusCode()); + } + + @Test + public void testOnGetPackageArtifact_NotFound_Fail() { + mockRestServiceServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/artifacts/" + ARTIFACT_PATH)) + .andExpect(method(HttpMethod.GET)).andRespond(withStatus(HttpStatus.NOT_FOUND)); + + final ResponseEntity responseEntity = + sendHttpRequest(VNF_PACKAGE_ID + "/artifacts/" + ARTIFACT_PATH); + + assertNotNull(responseEntity.getBody()); + assertEquals(HttpStatus.NOT_FOUND, responseEntity.getStatusCode()); + } + + @Test + public void testOnGetPackageArtifact_UnauthorizedClient_Fail() { + final String testURL = "http://localhost:" + port + PACKAGE_MANAGEMENT_BASE_URL + "/vnf_packages/" + + VNF_PACKAGE_ID + "/artifacts/" + ARTIFACT_PATH; + + mockRestServiceServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/artifacts/" + ARTIFACT_PATH)) + .andExpect(method(HttpMethod.GET)).andRespond(withStatus(HttpStatus.UNAUTHORIZED)); + + final HttpEntity request = new HttpEntity<>(basicHttpHeadersProvider.getHttpHeaders()); + final ResponseEntity responseEntity = + testRestTemplate.exchange(testURL, HttpMethod.GET, request, ProblemDetails.class); + + assertNotNull(responseEntity.getBody()); + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); + } + + @Test + public void testOnGetPackageArtifact_InternalServerError_Fail() { + mockRestServiceServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/artifacts/" + ARTIFACT_PATH)) + .andExpect(method(HttpMethod.GET)).andRespond(withStatus(HttpStatus.INTERNAL_SERVER_ERROR)); + + final ResponseEntity responseEntity = + sendHttpRequest(VNF_PACKAGE_ID + "/artifacts/" + ARTIFACT_PATH); + + assertNotNull(responseEntity.getBody()); + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); + } + + @Test + public void testOnGetPackageArtifact_BadRequest_Fail() { + mockRestServiceServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/artifacts/" + ARTIFACT_PATH)) + .andExpect(method(HttpMethod.GET)).andRespond(withStatus(HttpStatus.BAD_REQUEST)); + + final ResponseEntity responseEntity = + sendHttpRequest(VNF_PACKAGE_ID + "/artifacts/" + ARTIFACT_PATH); + + assertNotNull(responseEntity.getBody()); + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); + } + + @Test + public void testOnGetPackageArtifact_UnauthorizedServer_InternalError_Fail() { + mockRestServiceServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/artifacts/" + ARTIFACT_PATH)) + .andExpect(method(HttpMethod.GET)).andRespond(withStatus(HttpStatus.UNAUTHORIZED)); + + final ResponseEntity responseEntity = + sendHttpRequest(VNF_PACKAGE_ID + "/artifacts/" + ARTIFACT_PATH); + + assertNotNull(responseEntity.getBody()); + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); + } + + @Test + public void testGetPackageArtifact_SuccessResponseFromServerWithNullPackage_Fail() { + mockRestServiceServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/artifacts/" + ARTIFACT_PATH)) + .andExpect(method(HttpMethod.GET)).andRespond(withSuccess()); + + final ResponseEntity responseEntity = + sendHttpRequest(VNF_PACKAGE_ID + "/artifacts/" + ARTIFACT_PATH); + + assertNotNull(responseEntity.getBody()); + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); + } + + @Test + public void testVnfPackagesReceivedAsInlineResponse2001ListIfGetVnfPackagesSuccessful() { + final VnfPkgInfo[] responses = createVnfPkgArray(); + + mockRestServiceServer.expect(requestTo(MSB_BASE_URL)).andExpect(method(HttpMethod.GET)) + .andRespond(withSuccess(gson.toJson(responses), MediaType.APPLICATION_JSON)); + + final String testURL = localhostUrl + port + VNFPKGM_BASE_URL; + final HttpEntity request = new HttpEntity<>(basicHttpHeadersProvider.getHttpHeaders()); + + final ResponseEntity responseEntity = testRestTemplate.withBasicAuth("test", "test") + .exchange(testURL, HttpMethod.GET, request, InlineResponse2001[].class); + + assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); + assertNotNull(responseEntity.getBody()); + final InlineResponse2001[] inlineResponse2001array = responseEntity.getBody(); + final InlineResponse2001 inlineResponse2001 = inlineResponse2001array[0]; + assertEquals(VNF_PACKAGE_ID, inlineResponse2001.getId()); + assertEquals(VNFD_ID, inlineResponse2001.getVnfdId()); + assertEquals(VNFD_ID, inlineResponse2001.getSoftwareImages().get(0).getId()); + assertEquals(VNF_PRODUCT_NAME, inlineResponse2001.getSoftwareImages().get(0).getName()); + assertEquals(ALGORITHM, inlineResponse2001.getChecksum().getAlgorithm()); + assertEquals(HASH, inlineResponse2001.getChecksum().getHash()); + assertEquals(ARTIFACT_PATH, inlineResponse2001.getAdditionalArtifacts().get(0).getArtifactPath()); + assertEquals(ALGORITHM, inlineResponse2001.getAdditionalArtifacts().get(0).getChecksum().getAlgorithm()); + assertEquals(HASH, inlineResponse2001.getAdditionalArtifacts().get(0).getChecksum().getHash()); + final VnfPackagesLinks links = inlineResponse2001.getLinks(); + assertNotNull(links); + assertEquals(EXPECTED_SELF_HREF, links.getSelf().getHref()); + assertEquals(EXPECTED_VNFD_HREF, links.getVnfd().getHref()); + assertEquals(EXPECTED_PACKAGE_CONTENT_HREF, links.getPackageContent().getHref()); + } + + @Test + public void test400BadRequestInfoReceivedAsProblemDetailsIfGetVnfPackagesIs400BadRequest() { + mockRestServiceServer.expect(requestTo(MSB_BASE_URL)).andExpect(method(HttpMethod.GET)) + .andRespond(withStatus(HttpStatus.BAD_REQUEST)); + + final ResponseEntity responseEntity = sendHttpRequest(GET_VNF_PACKAGES_URL); + assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode()); + + assertNotNull(responseEntity.getBody()); + final ProblemDetails problemDetails = responseEntity.getBody(); + assertEquals("Error: Bad Request Received", problemDetails.getDetail()); + } + + @Test + public void test404NotFoundInfoReceivedAsProblemDetailsIfGetVnfPackagesIs404NotFound() { + mockRestServiceServer.expect(requestTo(MSB_BASE_URL)).andExpect(method(HttpMethod.GET)) + .andRespond(withStatus(HttpStatus.NOT_FOUND)); + + final ResponseEntity responseEntity = sendHttpRequest(GET_VNF_PACKAGES_URL); + assertEquals(HttpStatus.NOT_FOUND, responseEntity.getStatusCode()); + + assertNotNull(responseEntity.getBody()); + final ProblemDetails problemDetails = responseEntity.getBody(); + assertEquals("No Vnf Packages found", problemDetails.getDetail()); + } + + @Test + public void test500InternalServerErrorProblemDetailsReceivedIfGetVnfPackagesReturns500InternalServerError() { + mockRestServiceServer.expect(requestTo(MSB_BASE_URL)).andExpect(method(HttpMethod.GET)) + .andRespond(withStatus(HttpStatus.INTERNAL_SERVER_ERROR)); + + final ResponseEntity responseEntity = sendHttpRequest(GET_VNF_PACKAGES_URL); + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); + + assertNotNull(responseEntity.getBody()); + final ProblemDetails problemDetails = responseEntity.getBody(); + assertEquals("Internal Server Error Occurred.", problemDetails.getDetail()); + } + + @Test + public void test500InternalServerErrorProblemDetailsReceivedIfGetVnfPackagesReturnsANullPackage() { + mockRestServiceServer.expect(requestTo(MSB_BASE_URL)).andExpect(method(HttpMethod.GET)) + .andRespond(withSuccess()); + + final ResponseEntity responseEntity = sendHttpRequest(GET_VNF_PACKAGES_URL); + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); + + assertNotNull(responseEntity.getBody()); + final ProblemDetails problemDetails = responseEntity.getBody(); + assertEquals("An error occurred, a null response was received by the\n" + + " Sol003PackageManagementController from the EtsiCatalogManager using the GET \"vnf_packages\" \n" + + "endpoint.", problemDetails.getDetail()); + } + + @Test + public void testVnfPackageReceivedAsInlineResponse2001IfGetVnfPackageByIdSuccessful() { + final VnfPkgInfo response = createVnfPkgInfo(VNF_PACKAGE_ID); + + mockRestServiceServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID)).andExpect(method(HttpMethod.GET)) + .andRespond(withSuccess(gson.toJson(response), MediaType.APPLICATION_JSON)); + + final String testURL = localhostUrl + port + VNFPKGM_BASE_URL + "/" + VNF_PACKAGE_ID; + final HttpEntity request = new HttpEntity<>(basicHttpHeadersProvider.getHttpHeaders()); + final ResponseEntity responseEntity = testRestTemplate.withBasicAuth("test", "test") + .exchange(testURL, HttpMethod.GET, request, InlineResponse2001.class); + + assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); + assertNotNull(responseEntity.getBody()); + final InlineResponse2001 inlineResponse2001 = responseEntity.getBody(); + assertEquals(VNF_PACKAGE_ID, inlineResponse2001.getId()); + assertEquals(VNFD_ID, inlineResponse2001.getVnfdId()); + assertEquals(VNFD_ID, inlineResponse2001.getSoftwareImages().get(0).getId()); + assertEquals(VNF_PRODUCT_NAME, inlineResponse2001.getSoftwareImages().get(0).getName()); + assertEquals(ALGORITHM, inlineResponse2001.getChecksum().getAlgorithm()); + assertEquals(HASH, inlineResponse2001.getChecksum().getHash()); + assertEquals(ARTIFACT_PATH, inlineResponse2001.getAdditionalArtifacts().get(0).getArtifactPath()); + assertEquals(ALGORITHM, inlineResponse2001.getAdditionalArtifacts().get(0).getChecksum().getAlgorithm()); + assertEquals(HASH, inlineResponse2001.getAdditionalArtifacts().get(0).getChecksum().getHash()); + final VnfPackagesLinks links = inlineResponse2001.getLinks(); + assertNotNull(links); + assertEquals(EXPECTED_SELF_HREF, links.getSelf().getHref()); + assertEquals(EXPECTED_VNFD_HREF, links.getVnfd().getHref()); + assertEquals(EXPECTED_PACKAGE_CONTENT_HREF, links.getPackageContent().getHref()); + + } + + @Test + public void test400BadRequestInfoReceivedAsProblemDetailsIfGetVnfPackageByIdIs400BadRequest() { + mockRestServiceServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID)).andExpect(method(HttpMethod.GET)) + .andRespond(withStatus(HttpStatus.BAD_REQUEST)); + + final ResponseEntity responseEntity = sendHttpRequest(GET_VNF_PACKAGE_BY_ID_URL); + + assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode()); + assertNotNull(responseEntity.getBody()); + final ProblemDetails problemDetails = responseEntity.getBody(); + assertEquals("Error: Bad Request Received", problemDetails.getDetail()); + } + + @Test + public void test404NotFoundInfoReceivedAsProblemDetailsIfGetVnfPackageByIdIs404NotFound() { + mockRestServiceServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID)).andExpect(method(HttpMethod.GET)) + .andRespond(withStatus(HttpStatus.NOT_FOUND)); + + final ResponseEntity responseEntity = sendHttpRequest(GET_VNF_PACKAGE_BY_ID_URL); + + assertEquals(HttpStatus.NOT_FOUND, responseEntity.getStatusCode()); + assertNotNull(responseEntity.getBody()); + final ProblemDetails problemDetails = responseEntity.getBody(); + assertEquals("No Vnf Package found with vnfPkgId: " + VNF_PACKAGE_ID, problemDetails.getDetail()); + } + + @Test + public void test500InternalServerErrorProblemDetailsReceivedIfGetVnfPackageByIdReturns500InternalServerError() { + mockRestServiceServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID)).andExpect(method(HttpMethod.GET)) + .andRespond(withStatus(HttpStatus.INTERNAL_SERVER_ERROR)); + + final ResponseEntity responseEntity = sendHttpRequest(GET_VNF_PACKAGE_BY_ID_URL); + + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); + assertNotNull(responseEntity.getBody()); + final ProblemDetails problemDetails = responseEntity.getBody(); + assertEquals("Internal Server Error Occurred.", problemDetails.getDetail()); + } + + @Test + public void test500InternalServerErrorProblemDetailsReceivedIfGetVnfPackageByIdReturnsANullPackage() { + mockRestServiceServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID)).andExpect(method(HttpMethod.GET)) + .andRespond(withSuccess()); + + final ResponseEntity responseEntity = sendHttpRequest(GET_VNF_PACKAGE_BY_ID_URL); + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); + + assertNotNull(responseEntity.getBody()); + final ProblemDetails problemDetails = responseEntity.getBody(); + assertEquals("An error occurred, a null response was received by the\n" + + " Sol003PackageManagementController from the EtsiCatalogManager using the GET \"vnf_packages\" by vnfPkgId: \"" + + VNF_PACKAGE_ID + "\" \n" + "endpoint.", problemDetails.getDetail()); + } + + // The below test method is here to improve code coverage and provide a foundation for writing + // future tests + @Test + public void testGetPackageVnfd_ValidArray_Success() { + final byte[] responseArray = buildByteArrayWithRandomData(10); + + mockRestServiceServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/vnfd")) + .andExpect(method(HttpMethod.GET)) + .andRespond(withSuccess(responseArray, MediaType.APPLICATION_OCTET_STREAM)); + + final String testURL = + "http://localhost:" + port + PACKAGE_MANAGEMENT_BASE_URL + "/vnf_packages/" + VNF_PACKAGE_ID + "/vnfd"; + final HttpEntity request = new HttpEntity<>(basicHttpHeadersProvider.getHttpHeaders()); + final ResponseEntity responseEntity = + testRestTemplate.withBasicAuth("test", "test").exchange(testURL, HttpMethod.GET, request, byte[].class); + + assertEquals(byte[].class, responseEntity.getBody().getClass()); + assertArrayEquals(responseEntity.getBody(), responseArray); + assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); + } + + @Test + public void testOnGetPackageVnfd_Conflict_Fail() { + mockRestServiceServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/vnfd")) + .andExpect(method(HttpMethod.GET)).andRespond(withStatus(HttpStatus.CONFLICT)); + + final ResponseEntity responseEntity = sendHttpRequest(VNF_PACKAGE_ID + "/vnfd"); + + assertTrue(responseEntity.getBody() instanceof ProblemDetails); + assertEquals(HttpStatus.CONFLICT, responseEntity.getStatusCode()); + } + + @Test + public void testOnGetPackageVnfd_NotFound_Fail() { + mockRestServiceServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/vnfd")) + .andExpect(method(HttpMethod.GET)).andRespond(withStatus(HttpStatus.NOT_FOUND)); + + final ResponseEntity responseEntity = sendHttpRequest(VNF_PACKAGE_ID + "/vnfd"); + + assertTrue(responseEntity.getBody() instanceof ProblemDetails); + assertEquals(HttpStatus.NOT_FOUND, responseEntity.getStatusCode()); + } + + @Test + public void testOnGetPackageVnfd_UnauthorizedClient_Fail() { + mockRestServiceServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/vnfd")) + .andExpect(method(HttpMethod.GET)).andRespond(withStatus(HttpStatus.UNAUTHORIZED)); + + final ResponseEntity responseEntity = sendHttpRequest(VNF_PACKAGE_ID + "/vnfd"); + + assertTrue(responseEntity.getBody() instanceof ProblemDetails); + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); + } + + @Test + public void testOnGetPackageVnfd_InternalServerError_Fail() { + mockRestServiceServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/vnfd")) + .andExpect(method(HttpMethod.GET)).andRespond(withStatus(HttpStatus.INTERNAL_SERVER_ERROR)); + + final ResponseEntity responseEntity = sendHttpRequest(VNF_PACKAGE_ID + "/vnfd"); + + assertTrue(responseEntity.getBody() instanceof ProblemDetails); + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); + } + + @Test + public void testOnGetPackageVnfd_BadRequest_Fail() { + mockRestServiceServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/vnfd")) + .andExpect(method(HttpMethod.GET)).andRespond(withStatus(HttpStatus.BAD_REQUEST)); + + final ResponseEntity responseEntity = sendHttpRequest(VNF_PACKAGE_ID + "/vnfd"); + + assertTrue(responseEntity.getBody() instanceof ProblemDetails); + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); + } + + @Test + public void testOnGetPackageVnfd_UnauthorizedServer_InternalError_Fail() { + mockRestServiceServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/vnfd")) + .andExpect(method(HttpMethod.GET)).andRespond(withStatus(HttpStatus.UNAUTHORIZED)); + + final ResponseEntity responseEntity = sendHttpRequest(VNF_PACKAGE_ID + "/vnfd"); + + assertTrue(responseEntity.getBody() instanceof ProblemDetails); + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); + } + + @Test + public void testGetPackageVnfd_SuccessResponseFromServerWithNullPackage_Fail() { + mockRestServiceServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/vnfd")) + .andExpect(method(HttpMethod.GET)).andRespond(withSuccess()); + + final ResponseEntity responseEntity = sendHttpRequest(VNF_PACKAGE_ID + "/vnfd"); + + assertEquals(ProblemDetails.class, responseEntity.getBody().getClass()); + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); + } + + // Simply returns a byte array filled with random data, for use in the tests. + private byte[] buildByteArrayWithRandomData(final int sizeInKb) { + final Random rnd = new Random(); + final byte[] b = new byte[sizeInKb * 1024]; // converting kb to byte + rnd.nextBytes(b); + return b; + } + + private ResponseEntity sendHttpRequest(final String url) { + final String testURL = localhostUrl + port + VNFPKGM_BASE_URL + "/" + url; + final HttpEntity request = new HttpEntity<>(basicHttpHeadersProvider.getHttpHeaders()); + return testRestTemplate.withBasicAuth("test", "test").exchange(testURL, HttpMethod.GET, request, + ProblemDetails.class); + } + + private VnfPkgInfo[] createVnfPkgArray() { + final VnfPkgInfo[] vnfPkgInfoArray = new VnfPkgInfo[1]; + final VnfPkgInfo vnfPkgInfo = createVnfPkgInfo(VNF_PACKAGE_ID); + vnfPkgInfoArray[0] = vnfPkgInfo; + return vnfPkgInfoArray; + } + + private VnfPkgInfo createVnfPkgInfo(final String vnfPackageId) { + final VnfPkgInfo vnfPkgInfo = new VnfPkgInfo(); + vnfPkgInfo.setId(vnfPackageId); + vnfPkgInfo.setVnfdId(VNFD_ID); + vnfPkgInfo.setVnfProvider(VNF_PROVIDER); + vnfPkgInfo.setVnfProductName(VNF_PRODUCT_NAME); + vnfPkgInfo.setVnfSoftwareVersion(VNF_SOFTWARE_VERSION); + vnfPkgInfo.setVnfdVersion(VNFD_VERSION); + vnfPkgInfo.setChecksum(createVnfPkgChecksum()); + vnfPkgInfo.setSoftwareImages(createSoftwareImages()); + vnfPkgInfo.setAdditionalArtifacts(createAdditionalArtifacts()); + vnfPkgInfo.setLinks(createVNFPKGMLinkSerializerLinks()); + return vnfPkgInfo; + } + + private Checksum createVnfPkgChecksum() { + final Checksum checksum = new Checksum(); + checksum.setAlgorithm(ALGORITHM); + checksum.setHash(HASH); + return checksum; + } + + private List createSoftwareImages() { + final List softwareImages = new ArrayList<>(); + final VnfPackageSoftwareImageInfo vnfPackageSoftwareImageInfo = new VnfPackageSoftwareImageInfo(); + vnfPackageSoftwareImageInfo.setId(VNFD_ID); + vnfPackageSoftwareImageInfo.setName(VNF_PRODUCT_NAME); + vnfPackageSoftwareImageInfo.setProvider(""); + vnfPackageSoftwareImageInfo.setVersion(""); + vnfPackageSoftwareImageInfo.setChecksum(createVnfPkgChecksum()); + vnfPackageSoftwareImageInfo + .setContainerFormat(VnfPackageSoftwareImageInfo.ContainerFormatEnum.fromValue("AKI")); + softwareImages.add(vnfPackageSoftwareImageInfo); + return softwareImages; + } + + private List createAdditionalArtifacts() { + final List vnfPackageArtifactInfos = new ArrayList<>(); + final VnfPackageArtifactInfo vnfPackageArtifactInfo = + new VnfPackageArtifactInfo().artifactPath(ARTIFACT_PATH).checksum(createVnfPkgChecksum()); + vnfPackageArtifactInfos.add(vnfPackageArtifactInfo); + return vnfPackageArtifactInfos; + } + + private VNFPKGMLinkSerializer createVNFPKGMLinkSerializerLinks() { + final String baseUrl = "http://msb-iag:443/api/vnfpkgm/v1/vnf_packages"; + return new VNFPKGMLinkSerializer().self(new UriLink().href(baseUrl + "/myVnfPackageId")) + .vnfd(new UriLink().href(baseUrl + "/myVnfPackageId/vnfd")) + .packageContent(new UriLink().href(baseUrl + "/myVnfPackageId/package_content")); + } + +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/test/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/Sol003PackageManagementSubscriptionControllerTest.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/test/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/Sol003PackageManagementSubscriptionControllerTest.java new file mode 100644 index 0000000000..65be6a87f0 --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/test/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/Sol003PackageManagementSubscriptionControllerTest.java @@ -0,0 +1,403 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.pkgm.rest; + +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.onap.so.adapters.etsi.sol003.adapter.common.CommonConstants.ETSI_SUBSCRIPTION_NOTIFICATION_BASE_URL; +import static org.onap.so.adapters.etsi.sol003.adapter.common.CommonConstants.PACKAGE_MANAGEMENT_BASE_URL; +import static org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.EtsiCatalogServiceProviderConfiguration.ETSI_CATALOG_REST_TEMPLATE_BEAN; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.method; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; +import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus; +import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; +import java.io.File; +import java.net.URI; +import java.net.URISyntaxException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.security.GeneralSecurityException; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.onap.so.adapters.etsisol003adapter.pkgm.PackageManagementConstants; +import org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.model.BasicAuth; +import org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.model.LinkSelf; +import org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.model.NsdmSubscription; +import org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.model.PkgmNotificationsFilter; +import org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.model.PkgmSubscription; +import org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.model.ProblemDetails; +import org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.model.SubscriptionAuthentication; +import org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.model.Version; +import org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.model.VnfProducts; +import org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.model.VnfProductsProviders; +import org.onap.so.adapters.etsisol003adapter.pkgm.model.InlineResponse2002; +import org.onap.so.adapters.etsisol003adapter.pkgm.model.InlineResponse201; +import org.onap.so.adapters.etsisol003adapter.pkgm.model.PkgmSubscriptionRequest; +import org.onap.so.adapters.etsisol003adapter.pkgm.model.SubscriptionsAuthentication; +import org.onap.so.adapters.etsisol003adapter.pkgm.model.SubscriptionsFilter1; +import org.onap.so.adapters.etsisol003adapter.pkgm.model.SubscriptionsFilterVnfProductsFromProviders; +import org.onap.so.adapters.etsisol003adapter.pkgm.model.SubscriptionsLinks; +import org.onap.so.adapters.etsisol003adapter.pkgm.model.VnfPackagesLinksSelf; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.cache.Cache; +import org.springframework.cache.CacheManager; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.client.MockRestServiceServer; +import org.springframework.test.web.client.match.MockRestRequestMatchers; +import org.springframework.web.client.RestTemplate; +import com.google.gson.Gson; + +/** + * @author Ronan Kenny (ronan.kenny@est.tech) + * @author Gareth Roper (gareth.roper@est.tech) + */ +@RunWith(SpringRunner.class) +@SpringBootTest(classes = TestApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@ActiveProfiles("test") +public class Sol003PackageManagementSubscriptionControllerTest { + + private final Gson gson = new Gson(); + private final URI msbEndpoint = URI.create("http://msb-iag.onap:80/api/vnfpkgm/v1/subscriptions"); + private static final String _NOTIFICATION_CALLBACK_URI = + "https://so-vnfm-adapter.onap:30406" + ETSI_SUBSCRIPTION_NOTIFICATION_BASE_URL; + private static final String LOCALHOST_URL = "http://localhost:"; + + @Autowired + @Qualifier(ETSI_CATALOG_REST_TEMPLATE_BEAN) + private RestTemplate restTemplate; + private MockRestServiceServer mockRestServiceServer; + @Autowired + private CacheManager cacheServiceProvider; + @Autowired + private Sol003PackageManagementSubscriptionController sol003PackageManagementSubscriptionController; + + @Autowired + private TestRestTemplate testRestTemplate; + + @LocalServerPort + private int port; + + private static final String ID = UUID.randomUUID().toString(); + + @Before + public void setUp() { + mockRestServiceServer = MockRestServiceServer.bindTo(restTemplate).build(); + final Cache cache = + cacheServiceProvider.getCache(PackageManagementConstants.PACKAGE_MANAGEMENT_SUBSCRIPTION_CACHE); + cache.clear(); + } + + @After + public void after() { + mockRestServiceServer.reset(); + } + + @Test + public void testSuccessPostSubscription() throws GeneralSecurityException, URISyntaxException { + final PkgmSubscriptionRequest pkgmSubscriptionRequest = postSubscriptionForTest(); + final ResponseEntity response = + (ResponseEntity) sol003PackageManagementSubscriptionController + .postSubscriptionRequest(pkgmSubscriptionRequest); + + final HttpHeaders headers = buildHttpHeaders(Objects.requireNonNull(response.getBody()).getCallbackUri()); + + final SubscriptionsLinks subscriptionsLinks = new SubscriptionsLinks(); + final VnfPackagesLinksSelf vnfPackagesLinksSelf = new VnfPackagesLinksSelf(); + vnfPackagesLinksSelf.setHref("https://so-vnfm-adapter.onap:30406" + PACKAGE_MANAGEMENT_BASE_URL + + "/subscriptions/" + response.getBody().getId()); + subscriptionsLinks.setSelf(vnfPackagesLinksSelf); + + assertEquals(pkgmSubscriptionRequest.getFilter(), response.getBody().getFilter()); + assertEquals(subscriptionsLinks, response.getBody().getLinks()); + assertEquals(response.getBody().getFilter(), pkgmSubscriptionRequest.getFilter()); + assert (response.getHeaders().equals(headers)); + assertThat(response.getStatusCode(), is(HttpStatus.CREATED)); + assertNotNull(response.getBody().getCallbackUri()); + } + + @Test + public void testFailPostSubscriptionAlreadyExists() throws GeneralSecurityException { + final PkgmSubscriptionRequest pkgmSubscriptionRequest = postSubscriptionForTest(); + + final ResponseEntity response = + (ResponseEntity) sol003PackageManagementSubscriptionController + .postSubscriptionRequest(pkgmSubscriptionRequest); + + // Create duplicate entry + final PkgmSubscriptionRequest pkgmSubscriptionRequest2 = buildPkgmSubscriptionRequest(); + + final ResponseEntity response2002 = + (ResponseEntity) sol003PackageManagementSubscriptionController + .postSubscriptionRequest(pkgmSubscriptionRequest2); + + assertEquals(HttpStatus.SEE_OTHER, response2002.getStatusCode()); + } + + @Test + public void testSuccessGetSubscriptionWithSubscriptionId() throws GeneralSecurityException, URISyntaxException { + + final PkgmSubscriptionRequest pkgmSubscriptionRequest = postSubscriptionForTest(); + + mockRestServiceServer.expect(requestTo(msbEndpoint + "/" + ID)).andExpect(method(HttpMethod.GET)) + .andRespond(withSuccess(gson.toJson(new NsdmSubscription().id(ID)), MediaType.APPLICATION_JSON)); + + final ResponseEntity response = + (ResponseEntity) sol003PackageManagementSubscriptionController + .postSubscriptionRequest(pkgmSubscriptionRequest); + final String subscriptionId = response.getBody().getId(); + + + + final ResponseEntity responseEntity = + (ResponseEntity) sol003PackageManagementSubscriptionController + .getSubscription(subscriptionId); + + final HttpHeaders headers = buildHttpHeaders(response.getBody().getCallbackUri()); + + assertEquals(response.getBody().getFilter(), pkgmSubscriptionRequest.getFilter()); + assertEquals(response.getHeaders(), headers); + assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); + assertEquals(pkgmSubscriptionRequest.getFilter(), response.getBody().getFilter()); + // Ensure CallBackUri is set to new URI + assertNotEquals(pkgmSubscriptionRequest.getCallbackUri(), response.getBody().getCallbackUri()); + } + + @Test + public void testFailGetSubscriptionWithInvalidSubscriptionId() { + final String invalidId = "invalidSubscriptionId"; + mockRestServiceServer.expect(requestTo(msbEndpoint + "/" + invalidId)).andExpect(method(HttpMethod.GET)) + .andRespond(withStatus(HttpStatus.NOT_FOUND)); + final ResponseEntity response = sol003PackageManagementSubscriptionController.getSubscription(invalidId); + assertEquals(HttpStatus.NOT_FOUND, response.getStatusCode()); + assertTrue(response.getBody() instanceof ProblemDetails); + } + + @Test + public void testSuccessGetSubscriptions() throws GeneralSecurityException { + final PkgmSubscription pkgmSubscription = buildPkgmSubscription(); + final PkgmSubscriptionRequest pkgmSubscriptionRequest = buildPkgmSubscriptionRequest(); + + mockRestServiceServer.expect(requestTo(msbEndpoint)).andExpect(method(HttpMethod.POST)) + .andRespond(withSuccess(gson.toJson(pkgmSubscription), MediaType.APPLICATION_JSON)); + mockRestServiceServer.expect(requestTo(msbEndpoint + "/" + ID)).andExpect(method(HttpMethod.GET)) + .andRespond(withSuccess(gson.toJson(new NsdmSubscription().id(ID)), MediaType.APPLICATION_JSON)); + + sol003PackageManagementSubscriptionController.postSubscriptionRequest(pkgmSubscriptionRequest); + final ResponseEntity> response = + sol003PackageManagementSubscriptionController.getSubscriptions(); + + final List subscriptionsList = response.getBody(); + + assertEquals(Objects.requireNonNull(response.getBody()).get(0).getFilter(), + pkgmSubscriptionRequest.getFilter()); + assertNotNull(subscriptionsList != null); + assertNotEquals('0', subscriptionsList.size()); + assertEquals(HttpStatus.OK, response.getStatusCode()); + } + + @Test + public void testSuccessDeleteSubscriptionWithSubscriptionId() throws GeneralSecurityException { + final PkgmSubscriptionRequest pkgmSubscriptionRequest = buildPkgmSubscriptionRequest(); + final PkgmSubscription pkgmSubscription = buildPkgmSubscription(); + final String subscriptionId = pkgmSubscription.getId(); + + mockRestServiceServer.expect(requestTo(msbEndpoint)).andExpect(method(HttpMethod.POST)) + .andRespond(withSuccess(gson.toJson(pkgmSubscription), MediaType.APPLICATION_JSON)); + + mockRestServiceServer.expect(requestTo(msbEndpoint + "/" + subscriptionId)).andExpect(method(HttpMethod.DELETE)) + .andRespond(withStatus(HttpStatus.NO_CONTENT)); + mockRestServiceServer.expect(requestTo(msbEndpoint + "/" + subscriptionId)).andExpect(method(HttpMethod.GET)) + .andRespond(withSuccess(gson.toJson(new NsdmSubscription().id(subscriptionId)), + MediaType.APPLICATION_JSON)); + + final ResponseEntity responsePost = + (ResponseEntity) sol003PackageManagementSubscriptionController + .postSubscriptionRequest(pkgmSubscriptionRequest); + + final ResponseEntity responseDelete = + sol003PackageManagementSubscriptionController.deleteSubscription(subscriptionId); + + // Attempt to retrieve the subscription after delete + final ResponseEntity responseGetSubscription = + (ResponseEntity) sol003PackageManagementSubscriptionController + .getSubscription(subscriptionId); + + assertEquals(HttpStatus.NOT_FOUND, responseGetSubscription.getStatusCode()); + assertEquals(HttpStatus.NO_CONTENT, responseDelete.getStatusCode()); + } + + @Test + public void testDeleteSubscription_SubscripitonNotFoundInEtsiCatalogManager_SubscriptionDeletedFromLocalCache() + throws GeneralSecurityException { + final PkgmSubscriptionRequest pkgmSubscriptionRequest = buildPkgmSubscriptionRequest(); + final PkgmSubscription pkgmSubscription = buildPkgmSubscription(); + + mockRestServiceServer.expect(requestTo(msbEndpoint)).andExpect(method(HttpMethod.POST)) + .andRespond(withSuccess(gson.toJson(pkgmSubscription), MediaType.APPLICATION_JSON)); + + mockRestServiceServer.expect(requestTo(msbEndpoint + "/" + ID)).andExpect(method(HttpMethod.DELETE)) + .andRespond(withStatus(HttpStatus.NOT_FOUND)); + + final ResponseEntity responsePost = + (ResponseEntity) sol003PackageManagementSubscriptionController + .postSubscriptionRequest(pkgmSubscriptionRequest); + + final Cache cache = + cacheServiceProvider.getCache(PackageManagementConstants.PACKAGE_MANAGEMENT_SUBSCRIPTION_CACHE); + assertNotNull(cache.get(ID)); + + final ResponseEntity responseDelete = sol003PackageManagementSubscriptionController.deleteSubscription(ID); + + assertEquals(HttpStatus.NO_CONTENT, responseDelete.getStatusCode()); + assertNull(cache.get(ID)); + + } + + @Test + public void testFailDeleteSubscriptionWithInvalidSubscriptionId() throws URISyntaxException, InterruptedException { + final ResponseEntity responseDelete = (ResponseEntity) sol003PackageManagementSubscriptionController + .deleteSubscription("invalidSubscriptionId"); + assertEquals(HttpStatus.NOT_FOUND, responseDelete.getStatusCode()); + } + + + @Test + public void testSuccessPostSubscriptionWithValidNotificationTypes() throws Exception { + + final String file = getAbsolutePath("src/test/resources/requests/SubscriptionRequest.json"); + final String json = new String(Files.readAllBytes(Paths.get(file))); + final PkgmSubscriptionRequest request = gson.fromJson(json, PkgmSubscriptionRequest.class); + + mockRestServiceServer.expect(requestTo(msbEndpoint)).andExpect(method(HttpMethod.POST)) + .andExpect(MockRestRequestMatchers.content().json(gson.toJson(getEtsiCatalogPkgmSubscriptionRequest()))) + .andRespond(withSuccess(gson.toJson(buildPkgmSubscription()), MediaType.APPLICATION_JSON)); + + + final ResponseEntity responseEntity = + testRestTemplate.postForEntity(LOCALHOST_URL + port + PACKAGE_MANAGEMENT_BASE_URL + "/subscriptions", + request, InlineResponse201.class); + + assertEquals(HttpStatus.CREATED, responseEntity.getStatusCode()); + assertTrue(responseEntity.hasBody()); + final InlineResponse201 actual = responseEntity.getBody(); + assertEquals(ID, actual.getId()); + + + } + + private org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.model.PkgmSubscriptionRequest getEtsiCatalogPkgmSubscriptionRequest() { + return new org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.model.PkgmSubscriptionRequest() + .filter(new PkgmNotificationsFilter() + .addNotificationTypesItem( + PkgmNotificationsFilter.NotificationTypesEnum.VNFPACKAGEONBOARDINGNOTIFICATION) + .addVnfdIdItem("VNFDID").addVnfPkgIdItem("VNFPKGID") + .addOperationalStateItem(PkgmNotificationsFilter.OperationalStateEnum.ENABLED) + .addVnfProductsFromProvidersItem(new VnfProductsProviders().vnfProvider("EST") + .addVnfProductsItem(new VnfProducts().vnfProductName("VnfProducts") + .addVersionsItem(new Version().vnfSoftwareVersion("vnfSoftwareVersion") + .addVnfdVersionsItem("version1"))))) + .callbackUri(_NOTIFICATION_CALLBACK_URI).authentication( + new SubscriptionAuthentication().addAuthTypeItem(SubscriptionAuthentication.AuthTypeEnum.BASIC) + .paramsBasic(new BasicAuth().userName("vnfm").password("password1$"))); + } + + private PkgmSubscriptionRequest buildPkgmSubscriptionRequest() { + final PkgmSubscriptionRequest pkgmSubscriptionRequest = new PkgmSubscriptionRequest(); + final SubscriptionsFilter1 sub = buildSubscriptionsFilter(); + final SubscriptionsAuthentication auth = new SubscriptionsAuthentication(); + pkgmSubscriptionRequest.setFilter(sub); + pkgmSubscriptionRequest.setCallbackUri(msbEndpoint.toString()); + pkgmSubscriptionRequest.setAuthentication(auth); + return pkgmSubscriptionRequest; + } + + private SubscriptionsFilter1 buildSubscriptionsFilter() { + final SubscriptionsFilter1 sub = new SubscriptionsFilter1(); + final List vnfdIdList = new ArrayList<>(); + final List vnfPkgIdList = new ArrayList<>(); + final List notificationTypes = new ArrayList<>(); + final SubscriptionsFilterVnfProductsFromProviders subscriptionsFilterVnfProductsFromProviders = + new SubscriptionsFilterVnfProductsFromProviders(); + final List vnfProductsFromProviders = new ArrayList<>(); + + vnfProductsFromProviders.add(subscriptionsFilterVnfProductsFromProviders); + sub.setVnfdId(vnfdIdList); + sub.setNotificationTypes(notificationTypes); + sub.setVnfPkgId(vnfPkgIdList); + sub.setVnfProductsFromProviders(vnfProductsFromProviders); + return sub; + } + + private PkgmSubscription buildPkgmSubscription() { + final PkgmSubscription pkgmSubscription = new PkgmSubscription(); + final PkgmNotificationsFilter pkgmNotificationsFilter = new PkgmNotificationsFilter(); + final LinkSelf linkSelf = new LinkSelf(); + + pkgmSubscription.setId(ID); + pkgmSubscription.setCallbackUri(msbEndpoint + "/" + pkgmSubscription.getId().toString()); + pkgmSubscription.setFilter(pkgmNotificationsFilter); + pkgmSubscription.setLinks(linkSelf); + return pkgmSubscription; + } + + private PkgmSubscriptionRequest postSubscriptionForTest() { + final PkgmSubscriptionRequest pkgmSubscriptionRequest = buildPkgmSubscriptionRequest(); + final PkgmSubscription pkgmSubscription = buildPkgmSubscription(); + + mockRestServiceServer.expect(requestTo(msbEndpoint)).andExpect(method(HttpMethod.POST)) + .andRespond(withSuccess(gson.toJson(pkgmSubscription), MediaType.APPLICATION_JSON)); + return pkgmSubscriptionRequest; + } + + private HttpHeaders buildHttpHeaders(final String uri) throws URISyntaxException { + final HttpHeaders headers = new HttpHeaders(); + final URI myUri = new URI(uri); + headers.setLocation(myUri); + return headers; + } + + private String getAbsolutePath(final String path) { + final File file = new File(path); + return file.getAbsolutePath(); + } + +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/test/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/TestApplication.java b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/test/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/TestApplication.java new file mode 100755 index 0000000000..33535523d6 --- /dev/null +++ b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-adapter/src/test/java/org/onap/so/adapters/etsisol003adapter/pkgm/rest/TestApplication.java @@ -0,0 +1,38 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.etsisol003adapter.pkgm.rest; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration; +import org.springframework.cache.annotation.EnableCaching; + +@EnableCaching +@SpringBootApplication(scanBasePackages = {"org.onap.so"}) +@EnableAutoConfiguration(exclude = {JacksonAutoConfiguration.class}) +public class TestApplication { + + public static void main(final String[] args) { + new SpringApplication(TestApplication.class).run(args); + } + +} diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-api/pom.xml b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-api/pom.xml index 64c551c4ce..fa09a2d484 100644 --- a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-api/pom.xml +++ b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-api/pom.xml @@ -25,8 +25,8 @@ java okhttp-gson ${project.build.directory}/generated-sources/etsicatalog/notification - org.onap.so.adapters.etsi.sol003.adapter.etsicatalog.notification.api - org.onap.so.adapters.etsi.sol003.adapter.etsicatalog.notification.model + org.onap.so.adapters.etsisol003adapter.etsicatalog.notification.api + org.onap.so.adapters.etsisol003adapter.etsicatalog.notification.model false false @@ -48,8 +48,8 @@ java okhttp-gson ${project.build.directory}/generated-sources/sol003-vnf-packagemanagement - org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.api - org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.model + org.onap.so.adapters.etsisol003adapter.pkgm.api + org.onap.so.adapters.etsisol003adapter.pkgm.model false false diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-ext-clients/pom.xml b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-ext-clients/pom.xml index 9df110b718..f049466cb4 100644 --- a/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-ext-clients/pom.xml +++ b/adapters/etsi-sol003-adapter/etsi-sol003-package-management/etsi-sol003-package-management-ext-clients/pom.xml @@ -25,8 +25,8 @@ java okhttp-gson ${project.build.directory}/generated-sources/etsicatalog - org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.api - org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.etsicatalog.model + org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.api + org.onap.so.adapters.etsisol003adapter.pkgm.extclients.etsicatalog.model false false @@ -47,8 +47,8 @@ java okhttp-gson ${project.build.directory}/generated-sources/sol003-vnf-packagemanagement/notification - org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.vnfm.notification.api - org.onap.so.adapters.etsi.sol003.adapter.packagemanagement.extclients.vnfm.notification.model + org.onap.so.adapters.etsisol003adapter.pkgm.extclients.vnfm.notification.api + org.onap.so.adapters.etsisol003adapter.pkgm.extclients.vnfm.notification.model false false -- cgit 1.2.3-korg