From db28d2837ac4636aebc28311c3be4e22ac4537fc Mon Sep 17 00:00:00 2001 From: Roy Clarkson Date: Fri, 17 Jan 2025 16:01:46 -0500 Subject: [PATCH] Apply spring formatter and checkstyle rules --- build.gradle | 13 +- settings.gradle | 1 + .../build.gradle | 2 +- .../acceptance/AppBrokerApplication.java | 19 +- .../acceptance/ManagementController.java | 69 +- .../BackingApplicationIdsProvider.java | 23 +- .../acceptance/logging/package-info.java | 20 + .../appbroker/acceptance/package-info.java | 20 + .../NoOpCreateServiceInstanceWorkflow.java | 9 +- .../NoOpDeleteServiceInstanceWorkflow.java | 8 +- .../NoOpServiceInstanceBindingService.java | 9 +- .../NoOpUpdateServiceInstanceWorkflow.java | 8 +- .../acceptance/services/package-info.java | 20 + .../acceptance/AcceptanceTestProperties.java | 2 +- .../acceptance/AppBrokerTestProperties.java | 2 +- ... AppManagementRestageAcceptanceTests.java} | 33 +- ... AppManagementRestartAcceptanceTests.java} | 33 +- ...=> AppManagementStartAcceptanceTests.java} | 40 +- ... => AppManagementStopAcceptanceTests.java} | 35 +- .../acceptance/BrokerProperties.java | 8 +- .../BrokerPropertiesParameterResolver.java | 7 +- ....java => CloudFoundryAcceptanceTests.java} | 284 +++-- ...ava => CreateInstanceAcceptanceTests.java} | 36 +- ...nstanceWithParametersAcceptanceTests.java} | 28 +- ...tanceGuidSuffixTargetAcceptanceTests.java} | 27 +- ...eInstanceWithServicesAcceptanceTests.java} | 39 +- ...ServiceInstanceTargetAcceptanceTests.java} | 41 +- ...ServiceInstanceTargetAcceptanceTests.java} | 34 +- .../appbroker/acceptance/HealthListener.java | 44 +- ...java => LoggingRecentAcceptanceTests.java} | 23 +- ...a => LoggingStreamingAcceptanceTests.java} | 40 +- ...ava => UpdateInstanceAcceptanceTests.java} | 42 +- ...anceWithHostAndDomainAcceptanceTests.java} | 31 +- ...nstanceWithNewServiceAcceptanceTests.java} | 54 +- ...thNewServiceAndTargetAcceptanceTests.java} | 57 +- ...eInstanceWithServicesAcceptanceTests.java} | 37 +- ...ateInstanceWithTargetAcceptanceTests.java} | 29 +- ...va => UpgradeInstanceAcceptanceTests.java} | 60 +- .../cf/CloudFoundryClientConfiguration.java | 62 +- .../fixtures/cf/CloudFoundryProperties.java | 35 +- .../fixtures/cf/CloudFoundryService.java | 349 +++---- .../fixtures/cf/UserCloudFoundryService.java | 83 +- .../acceptance/fixtures/uaa/UaaService.java | 36 +- .../build.gradle | 2 +- .../AppBrokerAutoConfiguration.java | 193 ++-- ...udFoundryAppDeployerAutoConfiguration.java | 89 +- ...iceInstanceLogStreamAutoConfiguration.java | 16 +- ...ceInstanceRecentLogsAutoConfiguration.java | 9 +- .../appbroker/autoconfigure/package-info.java | 20 + ...a => AppBrokerAutoConfigurationTests.java} | 149 ++- ...dryAppDeployerAutoConfigurationTests.java} | 63 +- ...tanceLogStreamAutoConfigurationTests.java} | 43 +- ...anceRecentLogsAutoConfigurationTests.java} | 37 +- spring-cloud-app-broker-core/build.gradle | 2 +- .../deployer/BackingAppDeploymentService.java | 37 +- .../deployer/BackingApplication.java | 119 +-- .../deployer/BackingApplications.java | 9 +- .../appbroker/deployer/BackingService.java | 67 +- .../appbroker/deployer/BackingServices.java | 9 +- .../BackingServicesProvisionService.java | 2 +- .../BackingSpaceManagementService.java | 2 +- .../appbroker/deployer/BrokeredService.java | 40 +- .../appbroker/deployer/BrokeredServices.java | 4 +- .../DefaultBackingAppDeploymentService.java | 26 +- ...efaultBackingServicesProvisionService.java | 20 +- .../DefaultBackingSpaceManagementService.java | 8 +- .../appbroker/deployer/DeployerClient.java | 165 ++- .../deployer/ParametersTransformerSpec.java | 11 +- .../appbroker/deployer/ServicesSpec.java | 14 +- .../cloud/appbroker/deployer/TargetSpec.java | 13 +- .../appbroker/deployer/package-info.java | 20 + .../extensions/AbstractExtensionFactory.java | 2 +- .../extensions/ExtensionFactory.java | 2 +- .../extensions/ExtensionLocator.java | 15 +- .../appbroker/extensions/package-info.java | 20 + ...ationsParametersTransformationService.java | 32 +- ...rvicesParametersTransformationService.java | 33 +- ...ntMappingParametersTransformerFactory.java | 44 +- ...erMappingParametersTransformerFactory.java | 18 +- .../parameters/ParametersTransformer.java | 2 +- .../ParametersTransformerFactory.java | 2 +- ...tyMappingParametersTransformerFactory.java | 18 +- .../extensions/parameters/package-info.java | 20 + .../support/ConfigurationBeanUtils.java | 13 +- .../KebabCasePropertyBeanIntrospector.java | 36 +- .../extensions/support/package-info.java | 20 + .../extensions/targets/ArtifactDetails.java | 8 +- .../targets/ServiceInstanceGuidSuffix.java | 3 +- .../targets/SpacePerServiceInstance.java | 8 +- .../appbroker/extensions/targets/Target.java | 2 +- .../extensions/targets/TargetFactory.java | 2 +- .../extensions/targets/TargetService.java | 67 +- .../extensions/targets/package-info.java | 20 + .../manager/BackingAppManagementService.java | 200 ++-- .../appbroker/manager/ManagementClient.java | 72 +- .../cloud/appbroker/manager/package-info.java | 20 + .../cloud/appbroker/package-info.java | 20 + ...eateServiceInstanceAppBindingWorkflow.java | 8 +- ...teServiceInstanceRouteBindingWorkflow.java | 8 +- .../CreateServiceInstanceWorkflow.java | 7 +- .../DeleteServiceInstanceBindingWorkflow.java | 6 +- .../DeleteServiceInstanceWorkflow.java | 4 +- .../UpdateServiceInstanceWorkflow.java | 4 +- ...WorkflowServiceInstanceBindingService.java | 215 ++-- .../WorkflowServiceInstanceService.java | 201 ++-- .../cloud/appbroker/service/package-info.java | 20 + ...ServiceInstanceBindingStateRepository.java | 72 +- ...nMemoryServiceInstanceStateRepository.java | 43 +- ...ServiceInstanceBindingStateRepository.java | 6 +- .../appbroker/state/ServiceInstanceState.java | 8 +- .../state/ServiceInstanceStateRepository.java | 4 +- .../cloud/appbroker/state/package-info.java | 20 + ...ploymentCreateServiceInstanceWorkflow.java | 76 +- ...ploymentDeleteServiceInstanceWorkflow.java | 139 ++- .../AppDeploymentInstanceWorkflow.java | 36 +- ...ploymentUpdateServiceInstanceWorkflow.java | 142 ++- .../workflow/instance/package-info.java | 20 + ...Test.java => BackingApplicationTests.java} | 7 +- ...aultBackingAppDeploymentServiceTests.java} | 59 +- ...BackingServicesProvisionServiceTests.java} | 46 +- ...ltBackingSpaceManagementServiceTests.java} | 20 +- ...ientTest.java => DeployerClientTests.java} | 266 ++--- ....java => ConfigurationBeanUtilsTests.java} | 39 +- ...ParametersTransformationServiceTests.java} | 42 +- ...ingParametersTransformerFactoryTests.java} | 18 +- ...ingParametersTransformerFactoryTests.java} | 18 +- ...ingParametersTransformerFactoryTests.java} | 18 +- ...sTransformationServiceTest.java => s.java} | 99 +- ...rviceTest.java => TargetServiceTests.java} | 66 +- .../BackingAppManagementServiceTest.java | 446 -------- .../BackingAppManagementServiceTests.java | 353 +++++++ ...ementServiceWithServiceInstanceIdTest.java | 320 ------ ...mentServiceWithServiceInstanceIdTests.java | 273 +++++ .../manager/ManagementClientTest.java | 147 --- .../manager/ManagementClientTests.java | 132 +++ ...flowServiceInstanceBindingServiceTest.java | 978 ------------------ ...lowServiceInstanceBindingServiceTests.java | 926 +++++++++++++++++ .../WorkflowServiceInstanceServiceTest.java | 741 ------------- .../WorkflowServiceInstanceServiceTests.java | 626 +++++++++++ ...rviceInstanceSyncBindingServiceTests.java} | 32 +- ...eInstanceBindingStateRepositoryTests.java} | 87 +- ...oryServiceInstanceStateRepositoryTest.java | 154 --- ...ryServiceInstanceStateRepositoryTests.java | 131 +++ ...ntCreateServiceInstanceWorkflowTests.java} | 133 +-- ...ntDeleteServiceInstanceWorkflowTests.java} | 192 ++-- ...> AppDeploymentInstanceWorkflowTests.java} | 73 +- ...ntUpdateServiceInstanceWorkflowTests.java} | 166 ++- .../build.gradle | 2 +- .../cloudfoundry/CloudFoundryAppDeployer.java | 821 +++++++-------- .../cloudfoundry/CloudFoundryAppManager.java | 68 +- .../CloudFoundryDeploymentProperties.java | 82 +- .../CloudFoundryOAuth2Client.java | 16 +- .../CloudFoundryOperationsUtils.java | 15 +- .../CloudFoundryTargetProperties.java | 28 +- .../deployer/cloudfoundry/package-info.java | 20 + .../cloudfoundry/workflow/package-info.java | 20 + ...udFoundryAppDeployerDeleteSpaceTests.java} | 121 +-- ...java => CloudFoundryAppDeployerTests.java} | 743 ++++++------- ...dryAppDeployerUpdateApplicationTests.java} | 591 +++++------ .../CloudFoundryAppManagerTest.java | 230 ---- .../CloudFoundryAppManagerTests.java | 207 ++++ ...ava => CloudFoundryOAuth2ClientTests.java} | 47 +- ... => CloudFoundryOperationsUtilsTests.java} | 29 +- spring-cloud-app-broker-deployer/build.gradle | 2 +- .../CreateServiceInstanceRequest.java | 20 +- .../CreateServiceInstanceResponse.java | 4 +- .../deployer/DeleteBackingSpaceRequest.java | 4 +- .../deployer/DeleteBackingSpaceResponse.java | 4 +- .../DeleteServiceInstanceRequest.java | 6 +- .../DeleteServiceInstanceResponse.java | 4 +- .../deployer/DeployApplicationRequest.java | 18 +- .../deployer/DeployApplicationResponse.java | 4 +- .../deployer/DeploymentProperties.java | 54 +- .../deployer/GetApplicationRequest.java | 10 +- .../deployer/GetApplicationResponse.java | 14 +- .../deployer/GetServiceInstanceRequest.java | 12 +- .../deployer/GetServiceInstanceResponse.java | 12 +- .../deployer/UndeployApplicationRequest.java | 6 +- .../deployer/UndeployApplicationResponse.java | 2 +- .../deployer/UpdateApplicationRequest.java | 18 +- .../deployer/UpdateApplicationResponse.java | 4 +- .../UpdateServiceInstanceRequest.java | 17 +- .../UpdateServiceInstanceResponse.java | 4 +- .../deployer/deployer/package-info.java | 20 + .../deployer/deployer/util/ByteSizeUtils.java | 16 +- .../deployer/deployer/util/package-info.java | 20 + .../deployer/manager/AppManager.java | 4 +- .../manager/RestageApplicationRequest.java | 10 +- .../manager/RestartApplicationRequest.java | 10 +- .../manager/StartApplicationRequest.java | 10 +- .../manager/StopApplicationRequest.java | 10 +- .../deployer/manager/package-info.java | 20 + .../oauth2/CreateOAuth2ClientRequest.java | 58 +- .../oauth2/CreateOAuth2ClientResponse.java | 38 +- .../oauth2/DeleteOAuth2ClientRequest.java | 23 +- .../oauth2/DeleteOAuth2ClientResponse.java | 38 +- .../deployer/oauth2/package-info.java | 20 + ...va => GetServiceInstanceRequestTests.java} | 17 +- .../RestageApplicationRequestTests.java} | 24 +- .../RestartApplicationRequestTests.java} | 24 +- .../StartApplicationRequestTests.java} | 24 +- .../manager/StopApplicationRequestTests.java} | 24 +- spring-cloud-app-broker-docs/build.gradle | 2 +- .../build.gradle | 2 +- .../integration/AppBrokerApplication.java | 7 +- .../appbroker/integration/package-info.java | 20 + ...icationTest.java => ApplicationTests.java} | 16 +- ...ntTest.java => CatalogComponentTests.java} | 14 +- ...java => CreateInstanceComponentTests.java} | 52 +- ...ustomParametersMappingComponentTests.java} | 70 +- ...stanceWithCustomTargetComponentTests.java} | 70 +- ...nstanceWithEnvironmentComponentTests.java} | 60 +- ...ceWithExistingServicesComponentTests.java} | 48 +- ...ithOnlyABackingServiceComponentTests.java} | 36 +- ...eWithParametersMappingComponentTests.java} | 55 +- ...InstanceWithPropertiesComponentTests.java} | 55 +- ...stanceGuidSuffixTargetComponentTests.java} | 77 +- ...teInstanceWithServicesComponentTests.java} | 52 +- ...WithServicesParametersComponentTests.java} | 57 +- ...rServiceInstanceTargetComponentTests.java} | 58 +- ...java => DeleteInstanceComponentTests.java} | 66 +- ...nceWithAppsAndServicesComponentTests.java} | 108 +- ...teInstanceWithServicesComponentTests.java} | 64 +- ...java => UpdateInstanceComponentTests.java} | 42 +- ...ithNewServiceAndTargetComponentTests.java} | 79 +- ...InstanceWithNewServiceComponentTests.java} | 69 +- ...teInstanceWithServicesComponentTests.java} | 52 +- ...hServicesHostAndDomainComponentTests.java} | 38 +- ...WithServicesParametersComponentTests.java} | 61 +- ...anceWithServicesRebindComponentTests.java} | 63 +- ...ateInstanceWithUpgradeComponentTests.java} | 38 +- ...tTest.java => WiremockComponentTests.java} | 41 +- .../fixtures/CloudControllerStubFixture.java | 486 +++------ .../fixtures/OpenServiceBrokerApiFixture.java | 65 +- .../integration/fixtures/UaaStubFixture.java | 74 +- .../fixtures/WiremockServerFixture.java | 36 +- .../fixtures/WiremockStubFixture.java | 26 +- spring-cloud-app-broker-logging/build.gradle | 2 +- .../logging/ApplicationIdsProvider.java | 2 +- .../cloud/appbroker/logging/LoggingUtils.java | 8 +- .../cloud/appbroker/logging/package-info.java | 20 + .../recent/ApplicationRecentLogsProvider.java | 12 +- .../logging/recent/RecentLogsProvider.java | 2 +- .../recent/endpoint/EncodingException.java | 4 +- .../recent/endpoint/LogMessageComparator.java | 2 +- .../recent/endpoint/MultipartEncoder.java | 48 +- .../recent/endpoint/RecentLogsController.java | 8 +- .../logging/recent/endpoint/package-info.java | 20 + .../logging/recent/package-info.java | 20 + .../ApplicationLogStreamPublisher.java | 33 +- .../streaming/LogCacheStreamPublisher.java | 94 +- .../StreamingLogWebSocketHandler.java | 33 +- .../streaming/endpoint/package-info.java | 20 + .../events/ServiceInstanceLogEvent.java | 7 +- .../events/ServiceInstanceLoggingEvent.java | 9 +- .../streaming/events/package-info.java | 20 + .../logging/streaming/package-info.java | 20 + .../example/recentlog/RecentLogsTestApp.java | 7 +- .../streaming/LogStreamingTestApp.java | 8 +- ...va => ServiceInstanceRecentLogsTests.java} | 46 +- ... => ServiceInstanceLogStreamingTests.java} | 77 +- .../build.gradle | 2 +- .../build.gradle | 2 +- spring-cloud-starter-app-broker/build.gradle | 2 +- src/checkstyle/checkstyle-suppressions.xml | 31 - src/checkstyle/checkstyle-test.xml | 24 + src/checkstyle/checkstyle.xml | 204 +--- src/checkstyle/license.header | 2 +- 268 files changed, 8346 insertions(+), 9658 deletions(-) create mode 100644 spring-cloud-app-broker-acceptance-tests/src/main/java/org/springframework/cloud/appbroker/acceptance/logging/package-info.java create mode 100644 spring-cloud-app-broker-acceptance-tests/src/main/java/org/springframework/cloud/appbroker/acceptance/package-info.java create mode 100644 spring-cloud-app-broker-acceptance-tests/src/main/java/org/springframework/cloud/appbroker/acceptance/services/package-info.java rename spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/{AppManagementRestageAcceptanceTest.java => AppManagementRestageAcceptanceTests.java} (75%) rename spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/{AppManagementRestartAcceptanceTest.java => AppManagementRestartAcceptanceTests.java} (74%) rename spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/{AppManagementStartAcceptanceTest.java => AppManagementStartAcceptanceTests.java} (65%) rename spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/{AppManagementStopAcceptanceTest.java => AppManagementStopAcceptanceTests.java} (66%) rename spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/{CloudFoundryAcceptanceTest.java => CloudFoundryAcceptanceTests.java} (60%) rename spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/{CreateInstanceAcceptanceTest.java => CreateInstanceAcceptanceTests.java} (71%) rename spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/{CreateInstanceWithParametersAcceptanceTest.java => CreateInstanceWithParametersAcceptanceTests.java} (70%) rename spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/{CreateInstanceWithServiceInstanceGuidSuffixTargetAcceptanceTest.java => CreateInstanceWithServiceInstanceGuidSuffixTargetAcceptanceTests.java} (76%) rename spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/{CreateInstanceWithServicesAcceptanceTest.java => CreateInstanceWithServicesAcceptanceTests.java} (68%) rename spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/{CreateInstanceWithServicesSpacePerServiceInstanceTargetAcceptanceTest.java => CreateInstanceWithServicesSpacePerServiceInstanceTargetAcceptanceTests.java} (70%) rename spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/{CreateInstanceWithSpacePerServiceInstanceTargetAcceptanceTest.java => CreateInstanceWithSpacePerServiceInstanceTargetAcceptanceTests.java} (71%) rename spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/{LoggingRecentAcceptanceTest.java => LoggingRecentAcceptanceTests.java} (69%) rename spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/{LoggingStreamingAcceptanceTest.java => LoggingStreamingAcceptanceTests.java} (66%) rename spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/{UpdateInstanceAcceptanceTest.java => UpdateInstanceAcceptanceTests.java} (68%) rename spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/{UpdateInstanceWithHostAndDomainAcceptanceTest.java => UpdateInstanceWithHostAndDomainAcceptanceTests.java} (71%) rename spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/{UpdateInstanceWithNewServiceAcceptanceTest.java => UpdateInstanceWithNewServiceAcceptanceTests.java} (69%) rename spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/{UpdateInstanceWithNewServiceAndTargetAcceptanceTest.java => UpdateInstanceWithNewServiceAndTargetAcceptanceTests.java} (68%) rename spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/{UpdateInstanceWithServicesAcceptanceTest.java => UpdateInstanceWithServicesAcceptanceTests.java} (72%) rename spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/{UpdateInstanceWithTargetAcceptanceTest.java => UpdateInstanceWithTargetAcceptanceTests.java} (77%) rename spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/{UpgradeInstanceAcceptanceTest.java => UpgradeInstanceAcceptanceTests.java} (67%) create mode 100644 spring-cloud-app-broker-autoconfigure/src/main/java/org/springframework/cloud/appbroker/autoconfigure/package-info.java rename spring-cloud-app-broker-autoconfigure/src/test/java/org/springframework/cloud/appbroker/autoconfigure/{AppBrokerAutoConfigurationTest.java => AppBrokerAutoConfigurationTests.java} (78%) rename spring-cloud-app-broker-autoconfigure/src/test/java/org/springframework/cloud/appbroker/autoconfigure/{CloudFoundryAppDeployerAutoConfigurationTest.java => CloudFoundryAppDeployerAutoConfigurationTests.java} (72%) rename spring-cloud-app-broker-autoconfigure/src/test/java/org/springframework/cloud/appbroker/autoconfigure/{ServiceInstanceLogStreamAutoConfigurationTest.java => ServiceInstanceLogStreamAutoConfigurationTests.java} (67%) rename spring-cloud-app-broker-autoconfigure/src/test/java/org/springframework/cloud/appbroker/autoconfigure/{ServiceInstanceRecentLogsAutoConfigurationTest.java => ServiceInstanceRecentLogsAutoConfigurationTests.java} (66%) create mode 100644 spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/package-info.java create mode 100644 spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/package-info.java create mode 100644 spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/parameters/package-info.java create mode 100644 spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/support/package-info.java create mode 100644 spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/targets/package-info.java create mode 100644 spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/manager/package-info.java create mode 100644 spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/package-info.java create mode 100644 spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/service/package-info.java create mode 100644 spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/state/package-info.java create mode 100644 spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/workflow/instance/package-info.java rename spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/deployer/{BackingApplicationTest.java => BackingApplicationTests.java} (91%) rename spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/deployer/{DefaultBackingAppDeploymentServiceTest.java => DefaultBackingAppDeploymentServiceTests.java} (61%) rename spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/deployer/{DefaultBackingServicesProvisionServiceTest.java => DefaultBackingServicesProvisionServiceTests.java} (65%) rename spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/deployer/{DefaultBackingSpaceManagementServiceTest.java => DefaultBackingSpaceManagementServiceTests.java} (75%) rename spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/deployer/{DeployerClientTest.java => DeployerClientTests.java} (51%) rename spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/extensions/{ConfigurationBeanUtilsTest.java => ConfigurationBeanUtilsTests.java} (71%) rename spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/extensions/parameters/{BackingServicesParametersTransformationServiceTest.java => BackingServicesParametersTransformationServiceTests.java} (59%) rename spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/extensions/parameters/{EnvironmentMappingParametersTransformerFactoryTest.java => EnvironmentMappingParametersTransformerFactoryTests.java} (85%) rename spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/extensions/parameters/{ParameterMappingParametersTransformerFactoryTest.java => ParameterMappingParametersTransformerFactoryTests.java} (79%) rename spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/extensions/parameters/{PropertyMappingParametersTransformerFactoryTest.java => PropertyMappingParametersTransformerFactoryTests.java} (85%) rename spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/extensions/parameters/{BackingApplicationsParametersTransformationServiceTest.java => s.java} (69%) rename spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/extensions/targets/{TargetServiceTest.java => TargetServiceTests.java} (69%) delete mode 100644 spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/manager/BackingAppManagementServiceTest.java create mode 100644 spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/manager/BackingAppManagementServiceTests.java delete mode 100644 spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/manager/BackingAppManagementServiceWithServiceInstanceIdTest.java create mode 100644 spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/manager/BackingAppManagementServiceWithServiceInstanceIdTests.java delete mode 100644 spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/manager/ManagementClientTest.java create mode 100644 spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/manager/ManagementClientTests.java delete mode 100644 spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/service/WorkflowServiceInstanceBindingServiceTest.java create mode 100644 spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/service/WorkflowServiceInstanceBindingServiceTests.java delete mode 100644 spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/service/WorkflowServiceInstanceServiceTest.java create mode 100644 spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/service/WorkflowServiceInstanceServiceTests.java rename spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/service/{WorkflowServiceInstanceSyncBindingServiceTest.java => WorkflowServiceInstanceSyncBindingServiceTests.java} (80%) rename spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/state/{InMemoryServiceInstanceBindingStateRepositoryTest.java => InMemoryServiceInstanceBindingStateRepositoryTests.java} (57%) delete mode 100644 spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/state/InMemoryServiceInstanceStateRepositoryTest.java create mode 100644 spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/state/InMemoryServiceInstanceStateRepositoryTests.java rename spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/workflow/instance/{AppDeploymentCreateServiceInstanceWorkflowTest.java => AppDeploymentCreateServiceInstanceWorkflowTests.java} (61%) rename spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/workflow/instance/{AppDeploymentDeleteServiceInstanceWorkflowTest.java => AppDeploymentDeleteServiceInstanceWorkflowTests.java} (69%) rename spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/workflow/instance/{AppDeploymentInstanceWorkflowTest.java => AppDeploymentInstanceWorkflowTests.java} (67%) rename spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/workflow/instance/{AppDeploymentUpdateServiceInstanceWorkflowTest.java => AppDeploymentUpdateServiceInstanceWorkflowTests.java} (65%) create mode 100644 spring-cloud-app-broker-deployer-cloudfoundry/src/main/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/package-info.java create mode 100644 spring-cloud-app-broker-deployer-cloudfoundry/src/main/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/workflow/package-info.java rename spring-cloud-app-broker-deployer-cloudfoundry/src/test/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/{CloudFoundryAppDeployerDeleteSpaceTest.java => CloudFoundryAppDeployerDeleteSpaceTests.java} (56%) rename spring-cloud-app-broker-deployer-cloudfoundry/src/test/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/{CloudFoundryAppDeployerTest.java => CloudFoundryAppDeployerTests.java} (51%) rename spring-cloud-app-broker-deployer-cloudfoundry/src/test/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/{CloudFoundryAppDeployerUpdateApplicationTest.java => CloudFoundryAppDeployerUpdateApplicationTests.java} (50%) delete mode 100644 spring-cloud-app-broker-deployer-cloudfoundry/src/test/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryAppManagerTest.java create mode 100644 spring-cloud-app-broker-deployer-cloudfoundry/src/test/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryAppManagerTests.java rename spring-cloud-app-broker-deployer-cloudfoundry/src/test/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/{CloudFoundryOAuth2ClientTest.java => CloudFoundryOAuth2ClientTests.java} (73%) rename spring-cloud-app-broker-deployer-cloudfoundry/src/test/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/{CloudFoundryOperationsUtilsTest.java => CloudFoundryOperationsUtilsTests.java} (67%) create mode 100644 spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/package-info.java create mode 100644 spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/util/package-info.java create mode 100644 spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/manager/package-info.java create mode 100644 spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/oauth2/package-info.java rename spring-cloud-app-broker-deployer/src/test/java/org/springframework/cloud/appbroker/deployer/deployer/{GetServiceInstanceRequestTest.java => GetServiceInstanceRequestTests.java} (84%) rename spring-cloud-app-broker-deployer/src/test/java/org/springframework/cloud/appbroker/deployer/{manager/RestageApplicationRequestTest.java => deployer/manager/RestageApplicationRequestTests.java} (77%) rename spring-cloud-app-broker-deployer/src/test/java/org/springframework/cloud/appbroker/deployer/{manager/RestartApplicationRequestTest.java => deployer/manager/RestartApplicationRequestTests.java} (77%) rename spring-cloud-app-broker-deployer/src/test/java/org/springframework/cloud/appbroker/deployer/{manager/StartApplicationRequestTest.java => deployer/manager/StartApplicationRequestTests.java} (78%) rename spring-cloud-app-broker-deployer/src/test/java/org/springframework/cloud/appbroker/deployer/{manager/StopApplicationRequestTest.java => deployer/manager/StopApplicationRequestTests.java} (78%) create mode 100644 spring-cloud-app-broker-integration-tests/src/main/java/org/springframework/cloud/appbroker/integration/package-info.java rename spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/{ApplicationTest.java => ApplicationTests.java} (82%) rename spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/{CatalogComponentTest.java => CatalogComponentTests.java} (88%) rename spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/{CreateInstanceComponentTest.java => CreateInstanceComponentTests.java} (58%) rename spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/{CreateInstanceWithCustomParametersMappingComponentTest.java => CreateInstanceWithCustomParametersMappingComponentTests.java} (71%) rename spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/{CreateInstanceWithCustomTargetComponentTest.java => CreateInstanceWithCustomTargetComponentTests.java} (64%) rename spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/{CreateInstanceWithEnvironmentComponentTest.java => CreateInstanceWithEnvironmentComponentTests.java} (52%) rename spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/{CreateInstanceWithExistingServicesComponentTest.java => CreateInstanceWithExistingServicesComponentTests.java} (59%) rename spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/{CreateInstanceWithOnlyABackingServiceComponentTest.java => CreateInstanceWithOnlyABackingServiceComponentTests.java} (67%) rename spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/{CreateInstanceWithParametersMappingComponentTest.java => CreateInstanceWithParametersMappingComponentTests.java} (54%) rename spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/{CreateInstanceWithPropertiesComponentTest.java => CreateInstanceWithPropertiesComponentTests.java} (53%) rename spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/{CreateInstanceWithServiceInstanceGuidSuffixTargetComponentTest.java => CreateInstanceWithServiceInstanceGuidSuffixTargetComponentTests.java} (56%) rename spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/{CreateInstanceWithServicesComponentTest.java => CreateInstanceWithServicesComponentTests.java} (58%) rename spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/{CreateInstanceWithServicesParametersComponentTest.java => CreateInstanceWithServicesParametersComponentTests.java} (59%) rename spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/{CreateInstanceWithSpacePerServiceInstanceTargetComponentTest.java => CreateInstanceWithSpacePerServiceInstanceTargetComponentTests.java} (55%) rename spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/{DeleteInstanceComponentTest.java => DeleteInstanceComponentTests.java} (58%) rename spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/{DeleteInstanceWithAppsAndServicesComponentTest.java => DeleteInstanceWithAppsAndServicesComponentTests.java} (50%) rename spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/{DeleteInstanceWithServicesComponentTest.java => DeleteInstanceWithServicesComponentTests.java} (58%) rename spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/{UpdateInstanceComponentTest.java => UpdateInstanceComponentTests.java} (63%) rename spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/{UpdateInstanceWithNewServiceAndTargetComponentTest.java => UpdateInstanceWithNewServiceAndTargetComponentTests.java} (51%) rename spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/{UpdateInstanceWithNewServiceComponentTest.java => UpdateInstanceWithNewServiceComponentTests.java} (55%) rename spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/{UpdateInstanceWithServicesComponentTest.java => UpdateInstanceWithServicesComponentTests.java} (60%) rename spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/{UpdateInstanceWithServicesHostAndDomainComponentTest.java => UpdateInstanceWithServicesHostAndDomainComponentTests.java} (64%) rename spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/{UpdateInstanceWithServicesParametersComponentTest.java => UpdateInstanceWithServicesParametersComponentTests.java} (59%) rename spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/{UpdateInstanceWithServicesRebindComponentTest.java => UpdateInstanceWithServicesRebindComponentTests.java} (55%) rename spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/{UpdateInstanceWithUpgradeComponentTest.java => UpdateInstanceWithUpgradeComponentTests.java} (63%) rename spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/{WiremockComponentTest.java => WiremockComponentTests.java} (63%) create mode 100644 spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/package-info.java create mode 100644 spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/recent/endpoint/package-info.java create mode 100644 spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/recent/package-info.java create mode 100644 spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/streaming/endpoint/package-info.java create mode 100644 spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/streaming/events/package-info.java create mode 100644 spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/streaming/package-info.java rename spring-cloud-app-broker-logging/src/test/java/org/springframework/cloud/appbroker/logging/recent/{ServiceInstanceRecentLogsTest.java => ServiceInstanceRecentLogsTests.java} (72%) rename spring-cloud-app-broker-logging/src/test/java/org/springframework/cloud/appbroker/logging/streaming/{ServiceInstanceLogStreamingTest.java => ServiceInstanceLogStreamingTests.java} (71%) delete mode 100644 src/checkstyle/checkstyle-suppressions.xml create mode 100644 src/checkstyle/checkstyle-test.xml diff --git a/build.gradle b/build.gradle index 5ab5476..91488cd 100644 --- a/build.gradle +++ b/build.gradle @@ -1,7 +1,7 @@ import java.util.concurrent.ConcurrentHashMap /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,7 +28,9 @@ buildscript { } plugins { - id "io.spring.nohttp" + id 'checkstyle' + id 'io.spring.nohttp' + id 'io.spring.javaformat' id 'distribution' id 'jacoco' } @@ -193,7 +195,8 @@ configure(libraryProjects) { } configure(staticAnalysisProjects) { - apply plugin: "checkstyle" + apply plugin: 'checkstyle' + apply plugin: 'io.spring.javaformat' apply plugin: "jacoco" checkstyle { @@ -205,6 +208,10 @@ configure(staticAnalysisProjects) { } checkstyleTest { source = "src/test/java" + configFile = configDirectory.get().file("checkstyle-test.xml").asFile + } + dependencies { + checkstyle("io.spring.javaformat:spring-javaformat-checkstyle:0.0.43") } } diff --git a/settings.gradle b/settings.gradle index 7515fa4..e797019 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1,6 +1,7 @@ pluginManagement { plugins { id "io.spring.nohttp" version "0.0.11" + id "io.spring.javaformat" version "0.0.43" id 'org.springframework.boot' version "3.4.2" id 'org.asciidoctor.jvm.pdf' version '4.0.4' id 'org.asciidoctor.jvm.convert' version '4.0.4' diff --git a/spring-cloud-app-broker-acceptance-tests/build.gradle b/spring-cloud-app-broker-acceptance-tests/build.gradle index 60e31c3..174c857 100644 --- a/spring-cloud-app-broker-acceptance-tests/build.gradle +++ b/spring-cloud-app-broker-acceptance-tests/build.gradle @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020. the original author or authors. + * Copyright 2016-2020. the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-cloud-app-broker-acceptance-tests/src/main/java/org/springframework/cloud/appbroker/acceptance/AppBrokerApplication.java b/spring-cloud-app-broker-acceptance-tests/src/main/java/org/springframework/cloud/appbroker/acceptance/AppBrokerApplication.java index 1f40736..2390b3c 100644 --- a/spring-cloud-app-broker-acceptance-tests/src/main/java/org/springframework/cloud/appbroker/acceptance/AppBrokerApplication.java +++ b/spring-cloud-app-broker-acceptance-tests/src/main/java/org/springframework/cloud/appbroker/acceptance/AppBrokerApplication.java @@ -29,14 +29,15 @@ import org.springframework.cloud.servicebroker.service.ServiceInstanceBindingSer import org.springframework.context.annotation.Bean; /** - * A Spring Boot application for running acceptance tests + * A Spring Boot application for running acceptance tests. + * + * @author Roy Clarkson */ @SpringBootApplication public class AppBrokerApplication { /** - * main application entry point - * + * main application entry point. * @param args the args */ public static void main(String[] args) { @@ -44,8 +45,7 @@ public class AppBrokerApplication { } /** - * A no-op CreateServiceInstanceWorkflow bean - * + * A no-op CreateServiceInstanceWorkflow bean. * @return the bean */ @Bean @@ -54,8 +54,7 @@ public class AppBrokerApplication { } /** - * A no-op UpdateServiceInstanceWorkflow bean - * + * A no-op UpdateServiceInstanceWorkflow bean. * @return the bean */ @Bean @@ -64,8 +63,7 @@ public class AppBrokerApplication { } /** - * A no-op DeleteServiceInstanceWorkflow bean - * + * A no-op DeleteServiceInstanceWorkflow bean. * @return the bean */ @Bean @@ -74,8 +72,7 @@ public class AppBrokerApplication { } /** - * A no-op ServiceInstanceBindingService bean - * + * A no-op ServiceInstanceBindingService bean. * @return the bean */ @Bean diff --git a/spring-cloud-app-broker-acceptance-tests/src/main/java/org/springframework/cloud/appbroker/acceptance/ManagementController.java b/spring-cloud-app-broker-acceptance-tests/src/main/java/org/springframework/cloud/appbroker/acceptance/ManagementController.java index 2c6a2fb..6567435 100644 --- a/spring-cloud-app-broker-acceptance-tests/src/main/java/org/springframework/cloud/appbroker/acceptance/ManagementController.java +++ b/spring-cloud-app-broker-acceptance-tests/src/main/java/org/springframework/cloud/appbroker/acceptance/ManagementController.java @@ -1,11 +1,11 @@ /* - * Copyright 2002-2020 the original author or authors + * Copyright 2002-2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * https://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -24,7 +24,9 @@ import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; /** - * A controller for testing the {@link BackingAppManagementService} + * A controller for testing the {@link BackingAppManagementService}. + * + * @author Roy Clarkson */ @RestController public class ManagementController { @@ -32,8 +34,7 @@ public class ManagementController { private final BackingAppManagementService service; /** - * Construct a new {@literal ManagementController} - * + * Construct a new {@literal ManagementController}. * @param service the service to test */ public ManagementController(BackingAppManagementService service) { @@ -41,66 +42,56 @@ public class ManagementController { } /** - * Tests service start - * + * Tests service start. * @param serviceInstanceId the id of the service to test + * @param serviceName the name of the service + * @param planName the name of the plan * @return a response */ @GetMapping("/start/{serviceName}/{planName}/{serviceInstanceId}") - public Mono startApplications( - @PathVariable String serviceInstanceId, - @PathVariable String serviceName, - @PathVariable String planName - ) { - return service.start(serviceInstanceId, serviceName, planName) - .thenReturn("starting " + serviceInstanceId); + public Mono startApplications(@PathVariable String serviceInstanceId, @PathVariable String serviceName, + @PathVariable String planName) { + return this.service.start(serviceInstanceId, serviceName, planName).thenReturn("starting " + serviceInstanceId); } /** - * Tests service stop - * + * Tests service stop. * @param serviceInstanceId the id of the service to test + * @param serviceName the name of the service + * @param planName the name of the plan * @return a response */ @GetMapping("/stop/{serviceName}/{planName}/{serviceInstanceId}") - public Mono stopApplications( - @PathVariable String serviceInstanceId, - @PathVariable String serviceName, - @PathVariable String planName - ) { - return service.stop(serviceInstanceId, serviceName, planName) - .thenReturn("stopping " + serviceInstanceId); + public Mono stopApplications(@PathVariable String serviceInstanceId, @PathVariable String serviceName, + @PathVariable String planName) { + return this.service.stop(serviceInstanceId, serviceName, planName).thenReturn("stopping " + serviceInstanceId); } /** - * Tests service restart - * + * Tests service restart. * @param serviceInstanceId the id of the service to test + * @param serviceName the name of the service + * @param planName the name of the plan * @return a response */ @GetMapping("/restart/{serviceName}/{planName}/{serviceInstanceId}") - public Mono restartApplications( - @PathVariable String serviceInstanceId, - @PathVariable String serviceName, - @PathVariable String planName - ) { - return service.restart(serviceInstanceId, serviceName, planName) + public Mono restartApplications(@PathVariable String serviceInstanceId, @PathVariable String serviceName, + @PathVariable String planName) { + return this.service.restart(serviceInstanceId, serviceName, planName) .thenReturn("restarting " + serviceInstanceId); } /** - * Tests service restage - * + * Tests service restage. * @param serviceInstanceId the id of the service to test + * @param serviceName the name of the service + * @param planName the name of the plan * @return a response */ @GetMapping("/restage/{serviceName}/{planName}/{serviceInstanceId}") - public Mono restageApplications( - @PathVariable String serviceInstanceId, - @PathVariable String serviceName, - @PathVariable String planName - ) { - return service.restage(serviceInstanceId, serviceName, planName) + public Mono restageApplications(@PathVariable String serviceInstanceId, @PathVariable String serviceName, + @PathVariable String planName) { + return this.service.restage(serviceInstanceId, serviceName, planName) .thenReturn("restaging " + serviceInstanceId); } diff --git a/spring-cloud-app-broker-acceptance-tests/src/main/java/org/springframework/cloud/appbroker/acceptance/logging/BackingApplicationIdsProvider.java b/spring-cloud-app-broker-acceptance-tests/src/main/java/org/springframework/cloud/appbroker/acceptance/logging/BackingApplicationIdsProvider.java index a0ad2cc..c75f68e 100644 --- a/spring-cloud-app-broker-acceptance-tests/src/main/java/org/springframework/cloud/appbroker/acceptance/logging/BackingApplicationIdsProvider.java +++ b/spring-cloud-app-broker-acceptance-tests/src/main/java/org/springframework/cloud/appbroker/acceptance/logging/BackingApplicationIdsProvider.java @@ -1,11 +1,11 @@ /* - * Copyright 2016-2024 the original author or authors + * Copyright 2016-2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * https://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -16,7 +16,6 @@ package org.springframework.cloud.appbroker.acceptance.logging; - import org.cloudfoundry.client.CloudFoundryClient; import org.cloudfoundry.client.v3.applications.ApplicationResource; import org.cloudfoundry.client.v3.applications.ListApplicationsRequest; @@ -35,23 +34,21 @@ class BackingApplicationIdsProvider implements ApplicationIdsProvider { private final CloudFoundryOperations cloudFoundryOperations; - public BackingApplicationIdsProvider(CloudFoundryClient cloudFoundryClient, - CloudFoundryOperations cloudFoundryOperations) { + BackingApplicationIdsProvider(CloudFoundryClient cloudFoundryClient, + CloudFoundryOperations cloudFoundryOperations) { this.cloudFoundryClient = cloudFoundryClient; this.cloudFoundryOperations = cloudFoundryOperations; } @Override public Flux getApplicationIds(String serviceInstanceId) { - return cloudFoundryOperations.spaces().get(GetSpaceRequest.builder().name(serviceInstanceId).build()) + return this.cloudFoundryOperations.spaces() + .get(GetSpaceRequest.builder().name(serviceInstanceId).build()) .map(SpaceDetail::getId) - .flatMap(spaceId -> - cloudFoundryClient.applicationsV3() - .list(ListApplicationsRequest.builder().spaceIds(spaceId).build()) - ) - .flatMapMany( - listApplicationsResponse -> Flux.fromIterable(listApplicationsResponse.getResources()) - .map(ApplicationResource::getId)); + .flatMap((spaceId) -> this.cloudFoundryClient.applicationsV3() + .list(ListApplicationsRequest.builder().spaceIds(spaceId).build())) + .flatMapMany((listApplicationsResponse) -> Flux.fromIterable(listApplicationsResponse.getResources()) + .map(ApplicationResource::getId)); } } diff --git a/spring-cloud-app-broker-acceptance-tests/src/main/java/org/springframework/cloud/appbroker/acceptance/logging/package-info.java b/spring-cloud-app-broker-acceptance-tests/src/main/java/org/springframework/cloud/appbroker/acceptance/logging/package-info.java new file mode 100644 index 0000000..77245bf --- /dev/null +++ b/spring-cloud-app-broker-acceptance-tests/src/main/java/org/springframework/cloud/appbroker/acceptance/logging/package-info.java @@ -0,0 +1,20 @@ +/* + * Copyright 2002-2024 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Acceptance test application logging. + */ +package org.springframework.cloud.appbroker.acceptance.logging; diff --git a/spring-cloud-app-broker-acceptance-tests/src/main/java/org/springframework/cloud/appbroker/acceptance/package-info.java b/spring-cloud-app-broker-acceptance-tests/src/main/java/org/springframework/cloud/appbroker/acceptance/package-info.java new file mode 100644 index 0000000..a1a812d --- /dev/null +++ b/spring-cloud-app-broker-acceptance-tests/src/main/java/org/springframework/cloud/appbroker/acceptance/package-info.java @@ -0,0 +1,20 @@ +/* + * Copyright 2002-2024 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Acceptance test application. + */ +package org.springframework.cloud.appbroker.acceptance; diff --git a/spring-cloud-app-broker-acceptance-tests/src/main/java/org/springframework/cloud/appbroker/acceptance/services/NoOpCreateServiceInstanceWorkflow.java b/spring-cloud-app-broker-acceptance-tests/src/main/java/org/springframework/cloud/appbroker/acceptance/services/NoOpCreateServiceInstanceWorkflow.java index 7e0c7f5..b775b22 100644 --- a/spring-cloud-app-broker-acceptance-tests/src/main/java/org/springframework/cloud/appbroker/acceptance/services/NoOpCreateServiceInstanceWorkflow.java +++ b/spring-cloud-app-broker-acceptance-tests/src/main/java/org/springframework/cloud/appbroker/acceptance/services/NoOpCreateServiceInstanceWorkflow.java @@ -27,7 +27,10 @@ import org.springframework.cloud.servicebroker.model.instance.CreateServiceInsta import org.springframework.cloud.servicebroker.model.instance.CreateServiceInstanceResponse.CreateServiceInstanceResponseBuilder; /** - * A no-op implementation of {@link CreateServiceInstanceWorkflow} + * A no-op implementation of {@link CreateServiceInstanceWorkflow}. + * + * @author Scott Frederick + * @author Roy Clarkson */ public class NoOpCreateServiceInstanceWorkflow implements CreateServiceInstanceWorkflow { @@ -46,12 +49,12 @@ public class NoOpCreateServiceInstanceWorkflow implements CreateServiceInstanceW if (LOG.isInfoEnabled()) { LOG.info("Got request to create service instance: " + request); } - return Mono.just(request.getServiceDefinitionId().equals(backingServiceId)); + return Mono.just(request.getServiceDefinitionId().equals(this.backingServiceId)); } @Override public Mono buildResponse(CreateServiceInstanceRequest request, - CreateServiceInstanceResponseBuilder responseBuilder) { + CreateServiceInstanceResponseBuilder responseBuilder) { if (LOG.isInfoEnabled()) { LOG.info("Got request to create service instance: " + request); } diff --git a/spring-cloud-app-broker-acceptance-tests/src/main/java/org/springframework/cloud/appbroker/acceptance/services/NoOpDeleteServiceInstanceWorkflow.java b/spring-cloud-app-broker-acceptance-tests/src/main/java/org/springframework/cloud/appbroker/acceptance/services/NoOpDeleteServiceInstanceWorkflow.java index b2dc040..f27ce68 100644 --- a/spring-cloud-app-broker-acceptance-tests/src/main/java/org/springframework/cloud/appbroker/acceptance/services/NoOpDeleteServiceInstanceWorkflow.java +++ b/spring-cloud-app-broker-acceptance-tests/src/main/java/org/springframework/cloud/appbroker/acceptance/services/NoOpDeleteServiceInstanceWorkflow.java @@ -25,7 +25,9 @@ import org.springframework.cloud.servicebroker.model.instance.DeleteServiceInsta import org.springframework.cloud.servicebroker.model.instance.DeleteServiceInstanceResponse.DeleteServiceInstanceResponseBuilder; /** - * A no-op implementation of {@link DeleteServiceInstanceWorkflow} + * A no-op implementation of {@link DeleteServiceInstanceWorkflow}. + * + * @author Scott Frederick */ public class NoOpDeleteServiceInstanceWorkflow implements DeleteServiceInstanceWorkflow { @@ -39,12 +41,12 @@ public class NoOpDeleteServiceInstanceWorkflow implements DeleteServiceInstanceW @Override public Mono accept(DeleteServiceInstanceRequest request) { - return Mono.just(request.getServiceDefinitionId().equals(backingServiceId)); + return Mono.just(request.getServiceDefinitionId().equals(this.backingServiceId)); } @Override public Mono buildResponse(DeleteServiceInstanceRequest request, - DeleteServiceInstanceResponseBuilder responseBuilder) { + DeleteServiceInstanceResponseBuilder responseBuilder) { return Mono.just(responseBuilder); } diff --git a/spring-cloud-app-broker-acceptance-tests/src/main/java/org/springframework/cloud/appbroker/acceptance/services/NoOpServiceInstanceBindingService.java b/spring-cloud-app-broker-acceptance-tests/src/main/java/org/springframework/cloud/appbroker/acceptance/services/NoOpServiceInstanceBindingService.java index 99f7931..dea2dee 100644 --- a/spring-cloud-app-broker-acceptance-tests/src/main/java/org/springframework/cloud/appbroker/acceptance/services/NoOpServiceInstanceBindingService.java +++ b/spring-cloud-app-broker-acceptance-tests/src/main/java/org/springframework/cloud/appbroker/acceptance/services/NoOpServiceInstanceBindingService.java @@ -26,19 +26,22 @@ import org.springframework.cloud.servicebroker.model.binding.DeleteServiceInstan import org.springframework.cloud.servicebroker.service.ServiceInstanceBindingService; /** - * A no-op implementation of {@link ServiceInstanceBindingService} + * A no-op implementation of {@link ServiceInstanceBindingService}. + * + * @author Scott Frederick + * @author Roy Clarkson */ public class NoOpServiceInstanceBindingService implements ServiceInstanceBindingService { @Override public Mono createServiceInstanceBinding( - CreateServiceInstanceBindingRequest request) { + CreateServiceInstanceBindingRequest request) { return Mono.just(CreateServiceInstanceAppBindingResponse.builder().build()); } @Override public Mono deleteServiceInstanceBinding( - DeleteServiceInstanceBindingRequest request) { + DeleteServiceInstanceBindingRequest request) { return Mono.just(DeleteServiceInstanceBindingResponse.builder().build()); } diff --git a/spring-cloud-app-broker-acceptance-tests/src/main/java/org/springframework/cloud/appbroker/acceptance/services/NoOpUpdateServiceInstanceWorkflow.java b/spring-cloud-app-broker-acceptance-tests/src/main/java/org/springframework/cloud/appbroker/acceptance/services/NoOpUpdateServiceInstanceWorkflow.java index 60ec535..4022814 100644 --- a/spring-cloud-app-broker-acceptance-tests/src/main/java/org/springframework/cloud/appbroker/acceptance/services/NoOpUpdateServiceInstanceWorkflow.java +++ b/spring-cloud-app-broker-acceptance-tests/src/main/java/org/springframework/cloud/appbroker/acceptance/services/NoOpUpdateServiceInstanceWorkflow.java @@ -25,7 +25,9 @@ import org.springframework.cloud.servicebroker.model.instance.UpdateServiceInsta import org.springframework.cloud.servicebroker.model.instance.UpdateServiceInstanceResponse.UpdateServiceInstanceResponseBuilder; /** - * A no-op implementation of {@link UpdateServiceInstanceWorkflow} + * A no-op implementation of {@link UpdateServiceInstanceWorkflow}. + * + * @author Scott Frederick */ public class NoOpUpdateServiceInstanceWorkflow implements UpdateServiceInstanceWorkflow { @@ -39,12 +41,12 @@ public class NoOpUpdateServiceInstanceWorkflow implements UpdateServiceInstanceW @Override public Mono accept(UpdateServiceInstanceRequest request) { - return Mono.just(request.getServiceDefinitionId().equals(backingServiceId)); + return Mono.just(request.getServiceDefinitionId().equals(this.backingServiceId)); } @Override public Mono buildResponse(UpdateServiceInstanceRequest request, - UpdateServiceInstanceResponseBuilder responseBuilder) { + UpdateServiceInstanceResponseBuilder responseBuilder) { return Mono.just(responseBuilder); } diff --git a/spring-cloud-app-broker-acceptance-tests/src/main/java/org/springframework/cloud/appbroker/acceptance/services/package-info.java b/spring-cloud-app-broker-acceptance-tests/src/main/java/org/springframework/cloud/appbroker/acceptance/services/package-info.java new file mode 100644 index 0000000..f346191 --- /dev/null +++ b/spring-cloud-app-broker-acceptance-tests/src/main/java/org/springframework/cloud/appbroker/acceptance/services/package-info.java @@ -0,0 +1,20 @@ +/* + * Copyright 2002-2024 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Acceptance test application services. + */ +package org.springframework.cloud.appbroker.acceptance.services; diff --git a/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/AcceptanceTestProperties.java b/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/AcceptanceTestProperties.java index 491ed6c..980615a 100644 --- a/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/AcceptanceTestProperties.java +++ b/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/AcceptanceTestProperties.java @@ -24,7 +24,7 @@ public class AcceptanceTestProperties { private String brokerAppPath; public String getBrokerAppPath() { - return brokerAppPath; + return this.brokerAppPath; } public void setBrokerAppPath(String brokerAppPath) { diff --git a/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/AppBrokerTestProperties.java b/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/AppBrokerTestProperties.java index 5a64bb2..82b8036 100644 --- a/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/AppBrokerTestProperties.java +++ b/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/AppBrokerTestProperties.java @@ -21,7 +21,7 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -@Target({ElementType.ANNOTATION_TYPE, ElementType.METHOD}) +@Target({ ElementType.ANNOTATION_TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) public @interface AppBrokerTestProperties { diff --git a/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/AppManagementRestageAcceptanceTest.java b/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/AppManagementRestageAcceptanceTests.java similarity index 75% rename from spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/AppManagementRestageAcceptanceTest.java rename to spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/AppManagementRestageAcceptanceTests.java index 2c85b8d..8f06029 100644 --- a/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/AppManagementRestageAcceptanceTest.java +++ b/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/AppManagementRestageAcceptanceTests.java @@ -1,11 +1,11 @@ /* - * Copyright 2002-2020 the original author or authors + * Copyright 2002-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * https://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -27,7 +27,7 @@ import reactor.test.StepVerifier; import static org.assertj.core.api.Assertions.assertThat; -class AppManagementRestageAcceptanceTest extends CloudFoundryAcceptanceTest { +class AppManagementRestageAcceptanceTests extends CloudFoundryAcceptanceTests { private static final String SUFFIX = "app-management-restage"; @@ -58,35 +58,30 @@ class AppManagementRestageAcceptanceTest extends CloudFoundryAcceptanceTest { @BeforeEach void setUp() { - StepVerifier.create(userCloudFoundryService.deleteServiceInstance(SI_NAME)) - .verifyComplete(); + StepVerifier.create(userCloudFoundryService.deleteServiceInstance(SI_NAME)).verifyComplete(); StepVerifier.create(userCloudFoundryService.createServiceInstance(PLAN_NAME, APP_SERVICE_NAME, SI_NAME, null)) .verifyComplete(); StepVerifier.create(userCloudFoundryService.getServiceInstance(SI_NAME)) - .assertNext(serviceInstance -> assertThat(serviceInstance.getStatus()).isEqualTo("succeeded")) + .assertNext((serviceInstance) -> assertThat(serviceInstance.getStatus()).isEqualTo("succeeded")) .verifyComplete(); } @AfterEach void cleanUp() { - StepVerifier.create(userCloudFoundryService.deleteServiceInstance(SI_NAME)) - .verifyComplete(); + StepVerifier.create(userCloudFoundryService.deleteServiceInstance(SI_NAME)).verifyComplete(); - StepVerifier.create(getApplications(APP_1, APP_2)) - .verifyError(); + StepVerifier.create(getApplications(APP_1, APP_2)).verifyError(); } @Test - @AppBrokerTestProperties({ - "spring.cloud.appbroker.services[0].service-name=" + APP_SERVICE_NAME, - "spring.cloud.appbroker.services[0].plan-name=" + PLAN_NAME, - "spring.cloud.appbroker.services[0].apps[0].name=" + APP_1, - "spring.cloud.appbroker.services[0].apps[0].path=" + BACKING_APP_PATH, - "spring.cloud.appbroker.services[0].apps[1].name=" + APP_2, - "spring.cloud.appbroker.services[0].apps[1].path=" + BACKING_APP_PATH - }) + @AppBrokerTestProperties({ "spring.cloud.appbroker.services[0].service-name=" + APP_SERVICE_NAME, + "spring.cloud.appbroker.services[0].plan-name=" + PLAN_NAME, + "spring.cloud.appbroker.services[0].apps[0].name=" + APP_1, + "spring.cloud.appbroker.services[0].apps[0].path=" + BACKING_APP_PATH, + "spring.cloud.appbroker.services[0].apps[1].name=" + APP_2, + "spring.cloud.appbroker.services[0].apps[1].path=" + BACKING_APP_PATH }) void restageApps() throws Exception { List apps = getApplications(APP_1, APP_2).block(); Date originallySince1 = apps.get(0).getInstanceDetails().get(0).getSince(); @@ -94,7 +89,7 @@ class AppManagementRestageAcceptanceTest extends CloudFoundryAcceptanceTest { assertThat(apps).extracting("runningInstances").containsOnly(1); StepVerifier.create(manageApps(SI_NAME, APP_SERVICE_NAME, PLAN_NAME, "restage")) - .assertNext(result -> assertThat(result).contains("restaging")) + .assertNext((result) -> assertThat(result).contains("restaging")) .verifyComplete(); List restagedApps = getApplications(APP_1, APP_2).block(); diff --git a/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/AppManagementRestartAcceptanceTest.java b/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/AppManagementRestartAcceptanceTests.java similarity index 74% rename from spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/AppManagementRestartAcceptanceTest.java rename to spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/AppManagementRestartAcceptanceTests.java index 15cc0b5..b6cbf8a 100644 --- a/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/AppManagementRestartAcceptanceTest.java +++ b/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/AppManagementRestartAcceptanceTests.java @@ -1,11 +1,11 @@ /* - * Copyright 2002-2020 the original author or authors + * Copyright 2002-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * https://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -27,7 +27,7 @@ import reactor.test.StepVerifier; import static org.assertj.core.api.Assertions.assertThat; -class AppManagementRestartAcceptanceTest extends CloudFoundryAcceptanceTest { +class AppManagementRestartAcceptanceTests extends CloudFoundryAcceptanceTests { private static final String SUFFIX = "app-management-restart"; @@ -58,42 +58,37 @@ class AppManagementRestartAcceptanceTest extends CloudFoundryAcceptanceTest { @BeforeEach void setUp() { - StepVerifier.create(userCloudFoundryService.deleteServiceInstance(SI_NAME)) - .verifyComplete(); + StepVerifier.create(userCloudFoundryService.deleteServiceInstance(SI_NAME)).verifyComplete(); StepVerifier.create(userCloudFoundryService.createServiceInstance(PLAN_NAME, APP_SERVICE_NAME, SI_NAME, null)) .verifyComplete(); StepVerifier.create(userCloudFoundryService.getServiceInstance(SI_NAME)) - .assertNext(serviceInstance -> assertThat(serviceInstance.getStatus()).isEqualTo("succeeded")) + .assertNext((serviceInstance) -> assertThat(serviceInstance.getStatus()).isEqualTo("succeeded")) .verifyComplete(); } @AfterEach void cleanUp() { - StepVerifier.create(userCloudFoundryService.deleteServiceInstance(SI_NAME)) - .verifyComplete(); + StepVerifier.create(userCloudFoundryService.deleteServiceInstance(SI_NAME)).verifyComplete(); - StepVerifier.create(getApplications(APP_1, APP_2)) - .verifyError(); + StepVerifier.create(getApplications(APP_1, APP_2)).verifyError(); } @Test - @AppBrokerTestProperties({ - "spring.cloud.appbroker.services[0].service-name=" + APP_SERVICE_NAME, - "spring.cloud.appbroker.services[0].plan-name=" + PLAN_NAME, - "spring.cloud.appbroker.services[0].apps[0].name=" + APP_1, - "spring.cloud.appbroker.services[0].apps[0].path=" + BACKING_APP_PATH, - "spring.cloud.appbroker.services[0].apps[1].name=" + APP_2, - "spring.cloud.appbroker.services[0].apps[1].path=" + BACKING_APP_PATH - }) + @AppBrokerTestProperties({ "spring.cloud.appbroker.services[0].service-name=" + APP_SERVICE_NAME, + "spring.cloud.appbroker.services[0].plan-name=" + PLAN_NAME, + "spring.cloud.appbroker.services[0].apps[0].name=" + APP_1, + "spring.cloud.appbroker.services[0].apps[0].path=" + BACKING_APP_PATH, + "spring.cloud.appbroker.services[0].apps[1].name=" + APP_2, + "spring.cloud.appbroker.services[0].apps[1].path=" + BACKING_APP_PATH }) void restartApps() { List apps = getApplications(APP_1, APP_2).block(); Date originallySince1 = apps.get(0).getInstanceDetails().get(0).getSince(); Date originallySince2 = apps.get(1).getInstanceDetails().get(0).getSince(); StepVerifier.create(manageApps(SI_NAME, APP_SERVICE_NAME, PLAN_NAME, "restart")) - .assertNext(result -> assertThat(result).contains("restarting")) + .assertNext((result) -> assertThat(result).contains("restarting")) .verifyComplete(); List restagedApps = getApplications(APP_1, APP_2).block(); diff --git a/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/AppManagementStartAcceptanceTest.java b/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/AppManagementStartAcceptanceTests.java similarity index 65% rename from spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/AppManagementStartAcceptanceTest.java rename to spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/AppManagementStartAcceptanceTests.java index 20e5eaa..0250cc1 100644 --- a/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/AppManagementStartAcceptanceTest.java +++ b/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/AppManagementStartAcceptanceTests.java @@ -1,11 +1,11 @@ /* - * Copyright 2002-2020 the original author or authors + * Copyright 2002-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * https://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -23,7 +23,7 @@ import reactor.test.StepVerifier; import static org.assertj.core.api.Assertions.assertThat; -class AppManagementStartAcceptanceTest extends CloudFoundryAcceptanceTest { +class AppManagementStartAcceptanceTests extends CloudFoundryAcceptanceTests { private static final String SUFFIX = "app-management-start"; @@ -54,50 +54,44 @@ class AppManagementStartAcceptanceTest extends CloudFoundryAcceptanceTest { @BeforeEach void setUp() { - StepVerifier.create(userCloudFoundryService.deleteServiceInstance(SI_NAME)) - .verifyComplete(); + StepVerifier.create(userCloudFoundryService.deleteServiceInstance(SI_NAME)).verifyComplete(); StepVerifier.create(userCloudFoundryService.createServiceInstance(PLAN_NAME, APP_SERVICE_NAME, SI_NAME, null)) .verifyComplete(); StepVerifier.create(userCloudFoundryService.getServiceInstance(SI_NAME)) - .assertNext(serviceInstance -> assertThat(serviceInstance.getStatus()).isEqualTo("succeeded")) + .assertNext((serviceInstance) -> assertThat(serviceInstance.getStatus()).isEqualTo("succeeded")) .verifyComplete(); } @AfterEach void cleanUp() { - StepVerifier.create(userCloudFoundryService.deleteServiceInstance(SI_NAME)) - .verifyComplete(); + StepVerifier.create(userCloudFoundryService.deleteServiceInstance(SI_NAME)).verifyComplete(); - StepVerifier.create(getApplications(APP_1, APP_2)) - .verifyError(); + StepVerifier.create(getApplications(APP_1, APP_2)).verifyError(); } @Test - @AppBrokerTestProperties({ - "spring.cloud.appbroker.services[0].service-name=" + APP_SERVICE_NAME, - "spring.cloud.appbroker.services[0].plan-name=" + PLAN_NAME, - "spring.cloud.appbroker.services[0].apps[0].name=" + APP_1, - "spring.cloud.appbroker.services[0].apps[0].path=" + BACKING_APP_PATH, - "spring.cloud.appbroker.services[0].apps[1].name=" + APP_2, - "spring.cloud.appbroker.services[0].apps[1].path=" + BACKING_APP_PATH - }) + @AppBrokerTestProperties({ "spring.cloud.appbroker.services[0].service-name=" + APP_SERVICE_NAME, + "spring.cloud.appbroker.services[0].plan-name=" + PLAN_NAME, + "spring.cloud.appbroker.services[0].apps[0].name=" + APP_1, + "spring.cloud.appbroker.services[0].apps[0].path=" + BACKING_APP_PATH, + "spring.cloud.appbroker.services[0].apps[1].name=" + APP_2, + "spring.cloud.appbroker.services[0].apps[1].path=" + BACKING_APP_PATH }) void startApps() { - StepVerifier.create(cloudFoundryService.stopApplication(APP_1) - .then(cloudFoundryService.stopApplication(APP_2))) + StepVerifier.create(cloudFoundryService.stopApplication(APP_1).then(cloudFoundryService.stopApplication(APP_2))) .verifyComplete(); StepVerifier.create(getApplications(APP_1, APP_2)) - .assertNext(apps -> assertThat(apps).extracting("runningInstances").containsOnly(0)) + .assertNext((apps) -> assertThat(apps).extracting("runningInstances").containsOnly(0)) .verifyComplete(); StepVerifier.create(manageApps(SI_NAME, APP_SERVICE_NAME, PLAN_NAME, "start")) - .assertNext(result -> assertThat(result).contains("starting")) + .assertNext((result) -> assertThat(result).contains("starting")) .verifyComplete(); StepVerifier.create(getApplications(APP_1, APP_2)) - .assertNext(apps -> assertThat(apps).extracting("runningInstances").containsOnly(1)) + .assertNext((apps) -> assertThat(apps).extracting("runningInstances").containsOnly(1)) .verifyComplete(); } diff --git a/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/AppManagementStopAcceptanceTest.java b/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/AppManagementStopAcceptanceTests.java similarity index 66% rename from spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/AppManagementStopAcceptanceTest.java rename to spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/AppManagementStopAcceptanceTests.java index f541efa..4d2b886 100644 --- a/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/AppManagementStopAcceptanceTest.java +++ b/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/AppManagementStopAcceptanceTests.java @@ -1,11 +1,11 @@ /* - * Copyright 2002-2020 the original author or authors + * Copyright 2002-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * https://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -23,7 +23,7 @@ import reactor.test.StepVerifier; import static org.assertj.core.api.Assertions.assertThat; -class AppManagementStopAcceptanceTest extends CloudFoundryAcceptanceTest { +class AppManagementStopAcceptanceTests extends CloudFoundryAcceptanceTests { private static final String SUFFIX = "app-management-stop"; @@ -54,42 +54,37 @@ class AppManagementStopAcceptanceTest extends CloudFoundryAcceptanceTest { @BeforeEach void setUp() { - StepVerifier.create(userCloudFoundryService.deleteServiceInstance(SI_NAME)) - .verifyComplete(); + StepVerifier.create(userCloudFoundryService.deleteServiceInstance(SI_NAME)).verifyComplete(); StepVerifier.create(userCloudFoundryService.createServiceInstance(PLAN_NAME, APP_SERVICE_NAME, SI_NAME, null)) .verifyComplete(); StepVerifier.create(userCloudFoundryService.getServiceInstance(SI_NAME)) - .assertNext(serviceInstance -> assertThat(serviceInstance.getStatus()).isEqualTo("succeeded")) + .assertNext((serviceInstance) -> assertThat(serviceInstance.getStatus()).isEqualTo("succeeded")) .verifyComplete(); } @AfterEach void cleanUp() { - StepVerifier.create(userCloudFoundryService.deleteServiceInstance(SI_NAME)) - .verifyComplete(); + StepVerifier.create(userCloudFoundryService.deleteServiceInstance(SI_NAME)).verifyComplete(); - StepVerifier.create(getApplications(APP_1, APP_2)) - .verifyError(); + StepVerifier.create(getApplications(APP_1, APP_2)).verifyError(); } @Test - @AppBrokerTestProperties({ - "spring.cloud.appbroker.services[0].service-name=" + APP_SERVICE_NAME, - "spring.cloud.appbroker.services[0].plan-name=" + PLAN_NAME, - "spring.cloud.appbroker.services[0].apps[0].name=" + APP_1, - "spring.cloud.appbroker.services[0].apps[0].path=" + BACKING_APP_PATH, - "spring.cloud.appbroker.services[0].apps[1].name=" + APP_2, - "spring.cloud.appbroker.services[0].apps[1].path=" + BACKING_APP_PATH - }) + @AppBrokerTestProperties({ "spring.cloud.appbroker.services[0].service-name=" + APP_SERVICE_NAME, + "spring.cloud.appbroker.services[0].plan-name=" + PLAN_NAME, + "spring.cloud.appbroker.services[0].apps[0].name=" + APP_1, + "spring.cloud.appbroker.services[0].apps[0].path=" + BACKING_APP_PATH, + "spring.cloud.appbroker.services[0].apps[1].name=" + APP_2, + "spring.cloud.appbroker.services[0].apps[1].path=" + BACKING_APP_PATH }) void stopApps() { StepVerifier.create(manageApps(SI_NAME, APP_SERVICE_NAME, PLAN_NAME, "stop")) - .assertNext(result -> assertThat(result).contains("stopping")) + .assertNext((result) -> assertThat(result).contains("stopping")) .verifyComplete(); StepVerifier.create(getApplications(APP_1, APP_2)) - .assertNext(apps -> assertThat(apps).extracting("runningInstances").containsOnly(0)) + .assertNext((apps) -> assertThat(apps).extracting("runningInstances").containsOnly(0)) .verifyComplete(); } diff --git a/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/BrokerProperties.java b/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/BrokerProperties.java index 1d50578..a26db6f 100644 --- a/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/BrokerProperties.java +++ b/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/BrokerProperties.java @@ -26,18 +26,18 @@ class BrokerProperties { private final List properties = new ArrayList<>(); - public BrokerProperties(List properties) { + BrokerProperties(List properties) { if (!CollectionUtils.isEmpty(properties)) { this.properties.addAll(properties); } } - public BrokerProperties(String... properties) { + BrokerProperties(String... properties) { this(Arrays.asList(properties)); } - public List getProperties() { - return properties; + List getProperties() { + return this.properties; } } diff --git a/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/BrokerPropertiesParameterResolver.java b/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/BrokerPropertiesParameterResolver.java index 06326f4..f05c958 100644 --- a/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/BrokerPropertiesParameterResolver.java +++ b/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/BrokerPropertiesParameterResolver.java @@ -28,21 +28,20 @@ class BrokerPropertiesParameterResolver implements ParameterResolver { @Override public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) - throws ParameterResolutionException { + throws ParameterResolutionException { return parameterContext.getParameter().getType() == BrokerProperties.class; } @Override public BrokerProperties resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) - throws ParameterResolutionException { + throws ParameterResolutionException { String[] properties = getValueHolderProperties(extensionContext); return new BrokerProperties(properties); } private static String[] getValueHolderProperties(ExtensionContext extensionContext) { Optional testInstance = extensionContext.getTestMethod(); - return testInstance - .map(method -> method.getAnnotation(AppBrokerTestProperties.class).value()) + return testInstance.map((method) -> method.getAnnotation(AppBrokerTestProperties.class).value()) .orElseGet(() -> new String[] {}); } diff --git a/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/CloudFoundryAcceptanceTest.java b/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/CloudFoundryAcceptanceTests.java similarity index 60% rename from spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/CloudFoundryAcceptanceTest.java rename to spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/CloudFoundryAcceptanceTests.java index ed63c59..811eec6 100644 --- a/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/CloudFoundryAcceptanceTest.java +++ b/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/CloudFoundryAcceptanceTests.java @@ -41,6 +41,8 @@ import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; +import javax.net.ssl.SSLException; + import com.jayway.jsonpath.Configuration; import com.jayway.jsonpath.DocumentContext; import com.jayway.jsonpath.JsonPath; @@ -51,7 +53,6 @@ import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider; import com.jayway.jsonpath.spi.mapper.MappingProvider; import io.netty.handler.ssl.SslContextBuilder; import io.netty.handler.ssl.util.InsecureTrustManagerFactory; -import javax.net.ssl.SSLException; import org.cloudfoundry.operations.applications.ApplicationDetail; import org.cloudfoundry.operations.applications.ApplicationEnvironments; import org.cloudfoundry.operations.applications.ApplicationSummary; @@ -86,26 +87,15 @@ import org.springframework.web.client.RestTemplate; import org.springframework.web.reactive.function.client.WebClient; import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.cloud.appbroker.acceptance.fixtures.cf.CloudFoundryClientConfiguration.APP_BROKER_CLIENT_AUTHORITIES; -import static org.springframework.cloud.appbroker.acceptance.fixtures.cf.CloudFoundryClientConfiguration.APP_BROKER_CLIENT_SECRET; -import static org.springframework.cloud.appbroker.acceptance.fixtures.cf.CloudFoundryClientConfiguration.USER_CLIENT_AUTHORITIES; -import static org.springframework.cloud.appbroker.acceptance.fixtures.cf.CloudFoundryClientConfiguration.USER_CLIENT_ID; -import static org.springframework.cloud.appbroker.acceptance.fixtures.cf.CloudFoundryClientConfiguration.USER_CLIENT_SECRET; -@SpringBootTest(classes = { - CloudFoundryClientConfiguration.class, - CloudFoundryService.class, - UserCloudFoundryService.class, - UaaService.class, - HealthListener.class, - RestTemplate.class -}) +@SpringBootTest(classes = { CloudFoundryClientConfiguration.class, CloudFoundryService.class, + UserCloudFoundryService.class, UaaService.class, HealthListener.class, RestTemplate.class }) @ExtendWith(SpringExtension.class) @ExtendWith(BrokerPropertiesParameterResolver.class) @EnableConfigurationProperties(AcceptanceTestProperties.class) -abstract class CloudFoundryAcceptanceTest { +abstract class CloudFoundryAcceptanceTests { - private static final Logger LOG = LoggerFactory.getLogger(CloudFoundryAcceptanceTest.class); + private static final Logger LOG = LoggerFactory.getLogger(CloudFoundryAcceptanceTests.class); private static final String BACKING_SERVICE_PLAN_ID = UUID.randomUUID().toString(); @@ -170,28 +160,26 @@ abstract class CloudFoundryAcceptanceTest { } private List getAppBrokerProperties(BrokerProperties brokerProperties) { - String[] openServiceBrokerProperties = { - "spring.cloud.openservicebroker.catalog.services[0].id=" + SERVICE_ID, - "spring.cloud.openservicebroker.catalog.services[0].name=" + appServiceName(), - "spring.cloud.openservicebroker.catalog.services[0].description=A service that deploys a backing app", - "spring.cloud.openservicebroker.catalog.services[0].bindable=true", - "spring.cloud.openservicebroker.catalog.services[0].metadata.properties.serviceInstanceLogsEndpoint=" + - getServiceInstanceLogsEndpoint(), - "spring.cloud.openservicebroker.catalog.services[0].plans[0].id=" + PLAN_ID, - "spring.cloud.openservicebroker.catalog.services[0].plans[0].name=standard", - "spring.cloud.openservicebroker.catalog.services[0].plans[0].bindable=true", - "spring.cloud.openservicebroker.catalog.services[0].plans[0].description=A simple plan", - "spring.cloud.openservicebroker.catalog.services[0].plans[0].free=true", - "spring.cloud.openservicebroker.catalog.services[1].id=" + BACKING_SERVICE_ID, - "spring.cloud.openservicebroker.catalog.services[1].name=" + backingServiceName(), - "spring.cloud.openservicebroker.catalog.services[1].description=A backing service that can be bound to backing apps", - "spring.cloud.openservicebroker.catalog.services[1].bindable=true", - "spring.cloud.openservicebroker.catalog.services[1].plans[0].id=" + BACKING_SERVICE_PLAN_ID, - "spring.cloud.openservicebroker.catalog.services[1].plans[0].name=standard", - "spring.cloud.openservicebroker.catalog.services[1].plans[0].bindable=true", - "spring.cloud.openservicebroker.catalog.services[1].plans[0].description=A simple plan", - "spring.cloud.openservicebroker.catalog.services[1].plans[0].free=true" - }; + String[] openServiceBrokerProperties = { "spring.cloud.openservicebroker.catalog.services[0].id=" + SERVICE_ID, + "spring.cloud.openservicebroker.catalog.services[0].name=" + appServiceName(), + "spring.cloud.openservicebroker.catalog.services[0].description=A service that deploys a backing app", + "spring.cloud.openservicebroker.catalog.services[0].bindable=true", + "spring.cloud.openservicebroker.catalog.services[0].metadata.properties.serviceInstanceLogsEndpoint=" + + getServiceInstanceLogsEndpoint(), + "spring.cloud.openservicebroker.catalog.services[0].plans[0].id=" + PLAN_ID, + "spring.cloud.openservicebroker.catalog.services[0].plans[0].name=standard", + "spring.cloud.openservicebroker.catalog.services[0].plans[0].bindable=true", + "spring.cloud.openservicebroker.catalog.services[0].plans[0].description=A simple plan", + "spring.cloud.openservicebroker.catalog.services[0].plans[0].free=true", + "spring.cloud.openservicebroker.catalog.services[1].id=" + BACKING_SERVICE_ID, + "spring.cloud.openservicebroker.catalog.services[1].name=" + backingServiceName(), + "spring.cloud.openservicebroker.catalog.services[1].description=A backing service that can be bound to backing apps", + "spring.cloud.openservicebroker.catalog.services[1].bindable=true", + "spring.cloud.openservicebroker.catalog.services[1].plans[0].id=" + BACKING_SERVICE_PLAN_ID, + "spring.cloud.openservicebroker.catalog.services[1].plans[0].name=standard", + "spring.cloud.openservicebroker.catalog.services[1].plans[0].bindable=true", + "spring.cloud.openservicebroker.catalog.services[1].plans[0].description=A simple plan", + "spring.cloud.openservicebroker.catalog.services[1].plans[0].free=true" }; List appBrokerProperties = new ArrayList<>(); appBrokerProperties.addAll(Arrays.asList(openServiceBrokerProperties)); @@ -200,7 +188,8 @@ abstract class CloudFoundryAcceptanceTest { } private String getServiceInstanceLogsEndpoint() { - return "https://" + testBrokerAppName() + "." + cloudFoundryProperties.getApiHost().substring(4) + "/logs/"; + return "https://" + testBrokerAppName() + "." + this.cloudFoundryProperties.getApiHost().substring(4) + + "/logs/"; } @BeforeEach @@ -212,12 +201,12 @@ abstract class CloudFoundryAcceptanceTest { @Override public JsonProvider jsonProvider() { - return jacksonJsonProvider; + return this.jacksonJsonProvider; } @Override public MappingProvider mappingProvider() { - return jacksonMappingProvider; + return this.jacksonMappingProvider; } @Override @@ -228,57 +217,57 @@ abstract class CloudFoundryAcceptanceTest { } @AfterEach - public void tearDown(TestInfo testInfo) { - blockingSubscribe(cloudFoundryService.getOrCreateDefaultOrg() + void tearDown(TestInfo testInfo) { + blockingSubscribe(this.cloudFoundryService.getOrCreateDefaultOrg() .map(OrganizationSummary::getId) - .flatMap(orgId -> cloudFoundryService.getOrCreateDefaultSpace() + .flatMap((orgId) -> this.cloudFoundryService.getOrCreateDefaultSpace() .map(SpaceSummary::getId) - .flatMap(spaceId -> cleanup(orgId, spaceId)))); + .flatMap((spaceId) -> cleanup(orgId, spaceId)))); } private Mono initializeUser() { - return cloudFoundryService.getOrCreateOrganization(userCloudFoundryService.getOrgName()) + return this.cloudFoundryService.getOrCreateOrganization(this.userCloudFoundryService.getOrgName()) .map(OrganizationSummary::getId) - .flatMap(orgId -> cloudFoundryService - .getOrCreateSpace(userCloudFoundryService.getOrgName(), userCloudFoundryService.getSpaceName()) + .flatMap((orgId) -> this.cloudFoundryService + .getOrCreateSpace(this.userCloudFoundryService.getOrgName(), + this.userCloudFoundryService.getSpaceName()) .map(SpaceSummary::getId) - .flatMap(spaceId -> uaaService.createClient(USER_CLIENT_ID, USER_CLIENT_SECRET, USER_CLIENT_AUTHORITIES) - .then(cloudFoundryService - .associateClientWithOrgAndSpace(USER_CLIENT_ID, orgId, spaceId)))); + .flatMap((spaceId) -> this.uaaService + .createClient(CloudFoundryClientConfiguration.USER_CLIENT_ID, + CloudFoundryClientConfiguration.USER_CLIENT_SECRET, + CloudFoundryClientConfiguration.USER_CLIENT_AUTHORITIES) + .then(this.cloudFoundryService.associateClientWithOrgAndSpace( + CloudFoundryClientConfiguration.USER_CLIENT_ID, orgId, spaceId)))); } private Mono initializeBroker(List appBrokerProperties) { - return cloudFoundryService.getOrCreateDefaultOrg() + return this.cloudFoundryService.getOrCreateDefaultOrg() .map(OrganizationSummary::getId) - .flatMap(orgId -> cloudFoundryService - .getOrCreateDefaultSpace() + .flatMap((orgId) -> this.cloudFoundryService.getOrCreateDefaultSpace() .map(SpaceSummary::getId) - .flatMap(spaceId -> cleanup(orgId, spaceId) - .then(uaaService.createClient( - brokerClientId(), - APP_BROKER_CLIENT_SECRET, - APP_BROKER_CLIENT_AUTHORITIES)) - .then(cloudFoundryService - .associateAppBrokerClientWithOrgAndSpace(brokerClientId(), orgId, spaceId)) - .then(cloudFoundryService - .pushBrokerApp(testBrokerAppName(), getTestBrokerAppPath(), brokerClientId(), - appBrokerProperties)) - .then(cloudFoundryService.createServiceBroker(serviceBrokerName(), testBrokerAppName())) - .then(cloudFoundryService.enableServiceBrokerAccess(appServiceName())) - .then(cloudFoundryService.enableServiceBrokerAccess(backingServiceName())))); + .flatMap((spaceId) -> cleanup(orgId, spaceId) + .then(this.uaaService.createClient(brokerClientId(), + CloudFoundryClientConfiguration.APP_BROKER_CLIENT_SECRET, + CloudFoundryClientConfiguration.APP_BROKER_CLIENT_AUTHORITIES)) + .then(this.cloudFoundryService.associateAppBrokerClientWithOrgAndSpace(brokerClientId(), orgId, + spaceId)) + .then(this.cloudFoundryService.pushBrokerApp(testBrokerAppName(), getTestBrokerAppPath(), + brokerClientId(), appBrokerProperties)) + .then(this.cloudFoundryService.createServiceBroker(serviceBrokerName(), testBrokerAppName())) + .then(this.cloudFoundryService.enableServiceBrokerAccess(appServiceName())) + .then(this.cloudFoundryService.enableServiceBrokerAccess(backingServiceName())))); } private Mono updateBroker(List appBrokerProperties) { - return cloudFoundryService - .updateBrokerApp(testBrokerAppName(), brokerClientId(), appBrokerProperties) - .then(cloudFoundryService.updateServiceBroker(serviceBrokerName(), testBrokerAppName())); + return this.cloudFoundryService.updateBrokerApp(testBrokerAppName(), brokerClientId(), appBrokerProperties) + .then(this.cloudFoundryService.updateServiceBroker(serviceBrokerName(), testBrokerAppName())); } private Mono cleanup(String orgId, String spaceId) { - return cloudFoundryService.deleteServiceBroker(serviceBrokerName()) - .then(cloudFoundryService.deleteApp(testBrokerAppName())) - .then(cloudFoundryService.removeAppBrokerClientFromOrgAndSpace(brokerClientId(), orgId, spaceId)) - .onErrorResume(e -> Mono.empty()); + return this.cloudFoundryService.deleteServiceBroker(serviceBrokerName()) + .then(this.cloudFoundryService.deleteApp(testBrokerAppName())) + .then(this.cloudFoundryService.removeAppBrokerClientFromOrgAndSpace(brokerClientId(), orgId, spaceId)) + .onErrorResume((e) -> Mono.empty()); } protected void createServiceInstance(String serviceInstanceName) { @@ -289,13 +278,11 @@ abstract class CloudFoundryAcceptanceTest { createServiceInstance(appServiceName(), PLAN_NAME, serviceInstanceName, parameters); } - protected void createServiceInstance(String serviceName, - String planName, - String serviceInstanceName, - Map parameters) { - userCloudFoundryService.createServiceInstance(planName, serviceName, serviceInstanceName, parameters) + protected void createServiceInstance(String serviceName, String planName, String serviceInstanceName, + Map parameters) { + this.userCloudFoundryService.createServiceInstance(planName, serviceName, serviceInstanceName, parameters) .then(getServiceInstanceMono(serviceInstanceName)) - .flatMap(serviceInstance -> { + .flatMap((serviceInstance) -> { assertThat(serviceInstance.getStatus()) .withFailMessage("Create service instance failed:" + serviceInstance.getMessage()) .isEqualTo("succeeded"); @@ -304,13 +291,11 @@ abstract class CloudFoundryAcceptanceTest { .block(); } - protected void createBackingServiceInstance(String serviceName, - String planName, - String serviceInstanceName, - Map parameters) { - cloudFoundryService.createBackingServiceInstance(planName, serviceName, serviceInstanceName, parameters) - .then(cloudFoundryService.getServiceInstance(serviceInstanceName)) - .flatMap(serviceInstance -> { + protected void createBackingServiceInstance(String serviceName, String planName, String serviceInstanceName, + Map parameters) { + this.cloudFoundryService.createBackingServiceInstance(planName, serviceName, serviceInstanceName, parameters) + .then(this.cloudFoundryService.getServiceInstance(serviceInstanceName)) + .flatMap((serviceInstance) -> { assertThat(serviceInstance.getStatus()) .withFailMessage("Create service instance failed:" + serviceInstance.getMessage()) .isEqualTo("succeeded"); @@ -320,9 +305,9 @@ abstract class CloudFoundryAcceptanceTest { } protected void updateServiceInstance(String serviceInstanceName, Map parameters) { - userCloudFoundryService.updateServiceInstance(serviceInstanceName, parameters) + this.userCloudFoundryService.updateServiceInstance(serviceInstanceName, parameters) .then(getServiceInstanceMono(serviceInstanceName)) - .flatMap(serviceInstance -> { + .flatMap((serviceInstance) -> { assertThat(serviceInstance.getStatus()) .withFailMessage("Update service instance failed:" + serviceInstance.getMessage()) .isEqualTo("succeeded"); @@ -332,60 +317,56 @@ abstract class CloudFoundryAcceptanceTest { } protected void deleteServiceInstance(String serviceInstanceName) { - blockingSubscribe(userCloudFoundryService.deleteServiceInstance(serviceInstanceName)); + blockingSubscribe(this.userCloudFoundryService.deleteServiceInstance(serviceInstanceName)); } protected List listServiceInstances() { - return cloudFoundryService.listServiceInstances() + return this.cloudFoundryService.listServiceInstances() .map(ServiceInstanceSummary::getName) .collectList() .block(); } protected ServiceInstance getBackingServiceInstance(String serviceInstanceName) { - return cloudFoundryService.getServiceInstance(serviceInstanceName).block(); + return this.cloudFoundryService.getServiceInstance(serviceInstanceName).block(); } protected ServiceInstance getBackingServiceInstance(String serviceInstanceName, String space) { - return cloudFoundryService.getServiceInstance(serviceInstanceName, space).block(); + return this.cloudFoundryService.getServiceInstance(serviceInstanceName, space).block(); } protected String getServiceInstanceGuid(String serviceInstanceName) { - return getServiceInstanceMono(serviceInstanceName) - .map(ServiceInstance::getId) - .block(); + return getServiceInstanceMono(serviceInstanceName).map(ServiceInstance::getId).block(); } Mono getServiceInstanceMono(String serviceInstanceName) { - return userCloudFoundryService.getServiceInstance(serviceInstanceName); + return this.userCloudFoundryService.getServiceInstance(serviceInstanceName); } protected Optional getApplicationSummary(String appName) { - return cloudFoundryService - .getApplications() + return this.cloudFoundryService.getApplications() .flatMapMany(Flux::fromIterable) - .filter(applicationSummary -> appName.equals(applicationSummary.getName())) + .filter((applicationSummary) -> appName.equals(applicationSummary.getName())) .next() .blockOptional(); } protected Optional getApplicationDetail(String appName) { - return cloudFoundryService - .getApplication(appName) - .filter(applicationSummary -> appName.equals(applicationSummary.getName())) + return this.cloudFoundryService.getApplication(appName) + .filter((applicationSummary) -> appName.equals(applicationSummary.getName())) .blockOptional(); } protected Optional getApplicationSummary(String appName, String space) { - return cloudFoundryService.getApplication(appName, space).blockOptional(); + return this.cloudFoundryService.getApplication(appName, space).blockOptional(); } private ApplicationEnvironments getApplicationEnvironment(String appName) { - return cloudFoundryService.getApplicationEnvironment(appName).block(); + return this.cloudFoundryService.getApplicationEnvironment(appName).block(); } private ApplicationEnvironments getApplicationEnvironment(String appName, String space) { - return cloudFoundryService.getApplicationEnvironment(appName, space).block(); + return this.cloudFoundryService.getApplicationEnvironment(appName, space).block(); } protected DocumentContext getSpringAppJson(String appName) { @@ -401,29 +382,28 @@ abstract class CloudFoundryAcceptanceTest { } protected List getSpaces() { - return cloudFoundryService.getSpaces().block(); + return this.cloudFoundryService.getSpaces().block(); } protected Optional getUaaClient(String clientId) { - return uaaService.getUaaClient(clientId) - .blockOptional(); + return this.uaaService.getUaaClient(clientId).blockOptional(); } protected void createDomain(String domain) { - cloudFoundryService.createDomain(domain).block(); + this.cloudFoundryService.createDomain(domain).block(); } protected void deleteDomain(String domain) { - cloudFoundryService.deleteDomain(domain).block(); + this.cloudFoundryService.deleteDomain(domain).block(); } private Path getTestBrokerAppPath() { - return Paths.get(acceptanceTestProperties.getBrokerAppPath(), ""); + return Paths.get(this.acceptanceTestProperties.getBrokerAppPath(), ""); } private void blockingSubscribe(Mono publisher) { CountDownLatch latch = new CountDownLatch(1); - publisher.subscribe(System.out::println, t -> { + publisher.subscribe(System.out::println, (t) -> { if (LOG.isDebugEnabled()) { LOG.debug("error subscribing to publisher", t); } @@ -432,51 +412,39 @@ abstract class CloudFoundryAcceptanceTest { try { latch.await(); } - catch (InterruptedException e) { - throw new RuntimeException(e); + catch (InterruptedException ex) { + throw new RuntimeException(ex); } } - protected Mono manageApps(String serviceInstanceName, String serviceName, - String planName, String operation) { - return userCloudFoundryService - .getServiceInstance(serviceInstanceName) + protected Mono manageApps(String serviceInstanceName, String serviceName, String planName, + String operation) { + return this.userCloudFoundryService.getServiceInstance(serviceInstanceName) .map(ServiceInstance::getId) - .flatMap(serviceInstanceId -> - cloudFoundryService - .getApplicationRoute(testBrokerAppName()) - .flatMap(appRoute -> - webClient.get() - .uri(URI.create( - appRoute + "/" + operation + "/" + serviceName + "/" + planName + "/" + serviceInstanceId)) - .retrieve() - .toEntity(String.class) - .map(HttpEntity::getBody))); + .flatMap((serviceInstanceId) -> this.cloudFoundryService.getApplicationRoute(testBrokerAppName()) + .flatMap((appRoute) -> this.webClient.get() + .uri(URI.create( + appRoute + "/" + operation + "/" + serviceName + "/" + planName + "/" + serviceInstanceId)) + .retrieve() + .toEntity(String.class) + .map(HttpEntity::getBody))); } private WebClient getSslIgnoringWebClient() { - return WebClient.builder() - .clientConnector(new ReactorClientHttpConnector(HttpClient - .create() - .secure(t -> { - try { - t.sslContext(SslContextBuilder - .forClient() - .trustManager(InsecureTrustManagerFactory.INSTANCE) - .build()); - } - catch (SSLException e) { - if (LOG.isDebugEnabled()) { - LOG.debug("problem ignoring SSL in WebClient", e); - } - } - }))) - .build(); + return WebClient.builder().clientConnector(new ReactorClientHttpConnector(HttpClient.create().secure((t) -> { + try { + t.sslContext(SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build()); + } + catch (SSLException ex) { + if (LOG.isDebugEnabled()) { + LOG.debug("problem ignoring SSL in WebClient", ex); + } + } + }))).build(); } protected Mono> getApplications(String app1, String app2) { - return Flux.merge(cloudFoundryService.getApplication(app1), - cloudFoundryService.getApplication(app2)) + return Flux.merge(this.cloudFoundryService.getApplication(app1), this.cloudFoundryService.getApplication(app2)) .parallel() .runOn(Schedulers.parallel()) .sequential() @@ -485,21 +453,17 @@ abstract class CloudFoundryAcceptanceTest { private void prepareCLI() { try { - cfHome = Files.createTempDirectory("app-broker-acceptance-tests").toString(); + this.cfHome = Files.createTempDirectory("app-broker-acceptance-tests").toString(); - callCLICommand(List.of("cf", "login", "-a", - cloudFoundryProperties.getApiHost(), - "--skip-ssl-validation", "-u", - cloudFoundryProperties.getUsername(), - "-p", - cloudFoundryProperties.getPassword(), - "-o", "test-instances")) + callCLICommand(List.of("cf", "login", "-a", this.cloudFoundryProperties.getApiHost(), + "--skip-ssl-validation", "-u", this.cloudFoundryProperties.getUsername(), "-p", + this.cloudFoundryProperties.getPassword(), "-o", "test-instances")) .block(Duration.ofSeconds(60)); callCLICommand(List.of("cf", "install-plugin", "-f", "-r", "Cf-Community", "Service Instance Logging")) .block(Duration.ofSeconds(60)); } - catch (IOException e) { - throw new RuntimeException(e); + catch (IOException ex) { + throw new RuntimeException(ex); } } @@ -509,7 +473,7 @@ abstract class CloudFoundryAcceptanceTest { LOG.debug("Executing command: {}", command); } ProcessBuilder processBuilder = new ProcessBuilder(command); - processBuilder.environment().put("CF_HOME", cfHome); + processBuilder.environment().put("CF_HOME", this.cfHome); processBuilder.redirectErrorStream(true); Process process = processBuilder.start(); @@ -524,7 +488,7 @@ abstract class CloudFoundryAcceptanceTest { try { future.get(30, TimeUnit.SECONDS); } - catch (TimeoutException e) { + catch (TimeoutException ex) { LOG.info("Process reading timed out after 30 seconds"); } finally { diff --git a/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/CreateInstanceAcceptanceTest.java b/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/CreateInstanceAcceptanceTests.java similarity index 71% rename from spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/CreateInstanceAcceptanceTest.java rename to spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/CreateInstanceAcceptanceTests.java index 7019f65..0189475 100644 --- a/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/CreateInstanceAcceptanceTest.java +++ b/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/CreateInstanceAcceptanceTests.java @@ -25,7 +25,7 @@ import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; -class CreateInstanceAcceptanceTest extends CloudFoundryAcceptanceTest { +class CreateInstanceAcceptanceTests extends CloudFoundryAcceptanceTests { private static final String APP_CREATE_1 = "app-create-1"; @@ -55,45 +55,39 @@ class CreateInstanceAcceptanceTest extends CloudFoundryAcceptanceTest { } @Test - @AppBrokerTestProperties({ - "spring.cloud.appbroker.services[0].service-name=" + APP_SERVICE_NAME, - "spring.cloud.appbroker.services[0].plan-name=" + PLAN_NAME, + @AppBrokerTestProperties({ "spring.cloud.appbroker.services[0].service-name=" + APP_SERVICE_NAME, + "spring.cloud.appbroker.services[0].plan-name=" + PLAN_NAME, - "spring.cloud.appbroker.services[0].apps[0].name=" + APP_CREATE_1, - "spring.cloud.appbroker.services[0].apps[0].path=" + BACKING_APP_PATH, + "spring.cloud.appbroker.services[0].apps[0].name=" + APP_CREATE_1, + "spring.cloud.appbroker.services[0].apps[0].path=" + BACKING_APP_PATH, - "spring.cloud.appbroker.services[0].apps[0].environment.ENV_VAR_1=value1", - "spring.cloud.appbroker.services[0].apps[0].environment.ENV_VAR_2=value2", - "spring.cloud.appbroker.services[0].apps[0].properties.memory=2G", - "spring.cloud.appbroker.services[0].apps[0].properties.count=2", + "spring.cloud.appbroker.services[0].apps[0].environment.ENV_VAR_1=value1", + "spring.cloud.appbroker.services[0].apps[0].environment.ENV_VAR_2=value2", + "spring.cloud.appbroker.services[0].apps[0].properties.memory=2G", + "spring.cloud.appbroker.services[0].apps[0].properties.count=2", - "spring.cloud.appbroker.services[0].apps[1].name=" + APP_CREATE_2, - "spring.cloud.appbroker.services[0].apps[1].path=" + BACKING_APP_PATH, + "spring.cloud.appbroker.services[0].apps[1].name=" + APP_CREATE_2, + "spring.cloud.appbroker.services[0].apps[1].path=" + BACKING_APP_PATH, - "spring.cloud.appbroker.deployer.cloudfoundry.properties.stack=cflinuxfs4" - }) + "spring.cloud.appbroker.deployer.cloudfoundry.properties.stack=cflinuxfs4" }) void deployAppsOnCreateService() { // when a service instance is created createServiceInstance(SI_NAME); // then a backing applications are deployed Optional backingApplication1 = getApplicationSummary(APP_CREATE_1); - assertThat(backingApplication1).hasValueSatisfying(app -> { + assertThat(backingApplication1).hasValueSatisfying((app) -> { assertThat(app.getInstances()).isEqualTo(2); assertThat(app.getRunningInstances()).isGreaterThanOrEqualTo(1); assertThat(app.getMemoryLimit()).isEqualTo(2048); }); Optional backingApplication2 = getApplicationSummary(APP_CREATE_2); - assertThat(backingApplication2).hasValueSatisfying(app -> - assertThat(app.getRunningInstances()).isEqualTo(1)); - + assertThat(backingApplication2).hasValueSatisfying((app) -> assertThat(app.getRunningInstances()).isEqualTo(1)); // and stack is updated when specified Optional application1Detail = getApplicationDetail(APP_CREATE_1); - assertThat(application1Detail).hasValueSatisfying(app -> { - assertThat(app.getStack()).isEqualTo("cflinuxfs4"); - }); + assertThat(application1Detail).hasValueSatisfying((app) -> assertThat(app.getStack()).isEqualTo("cflinuxfs4")); // and has the environment variables DocumentContext json = getSpringAppJson(APP_CREATE_1); diff --git a/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/CreateInstanceWithParametersAcceptanceTest.java b/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/CreateInstanceWithParametersAcceptanceTests.java similarity index 70% rename from spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/CreateInstanceWithParametersAcceptanceTest.java rename to spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/CreateInstanceWithParametersAcceptanceTests.java index a5d753c..d04672e 100644 --- a/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/CreateInstanceWithParametersAcceptanceTest.java +++ b/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/CreateInstanceWithParametersAcceptanceTests.java @@ -26,7 +26,7 @@ import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; -class CreateInstanceWithParametersAcceptanceTest extends CloudFoundryAcceptanceTest { +class CreateInstanceWithParametersAcceptanceTests extends CloudFoundryAcceptanceTests { private static final String APP_NAME = "app-create-params"; @@ -54,19 +54,17 @@ class CreateInstanceWithParametersAcceptanceTest extends CloudFoundryAcceptanceT } @Test - @AppBrokerTestProperties({ - "spring.cloud.appbroker.services[0].service-name=" + APP_SERVICE_NAME, - "spring.cloud.appbroker.services[0].plan-name=" + PLAN_NAME, - "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME, - "spring.cloud.appbroker.services[0].apps[0].path=" + BACKING_APP_PATH, - "spring.cloud.appbroker.services[0].apps[0].environment.parameter1=config1", - "spring.cloud.appbroker.services[0].apps[0].environment.parameter2=config2", - "spring.cloud.appbroker.services[0].apps[0].environment.parameter3=config3", - "spring.cloud.appbroker.services[0].apps[0].parameters-transformers[0].name=EnvironmentMapping", - "spring.cloud.appbroker.services[0].apps[0].parameters-transformers[0].args.include=parameter1,parameter3", - "spring.cloud.appbroker.services[0].apps[0].parameters-transformers[1].name=PropertyMapping", - "spring.cloud.appbroker.services[0].apps[0].parameters-transformers[1].args.include=memory" - }) + @AppBrokerTestProperties({ "spring.cloud.appbroker.services[0].service-name=" + APP_SERVICE_NAME, + "spring.cloud.appbroker.services[0].plan-name=" + PLAN_NAME, + "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME, + "spring.cloud.appbroker.services[0].apps[0].path=" + BACKING_APP_PATH, + "spring.cloud.appbroker.services[0].apps[0].environment.parameter1=config1", + "spring.cloud.appbroker.services[0].apps[0].environment.parameter2=config2", + "spring.cloud.appbroker.services[0].apps[0].environment.parameter3=config3", + "spring.cloud.appbroker.services[0].apps[0].parameters-transformers[0].name=EnvironmentMapping", + "spring.cloud.appbroker.services[0].apps[0].parameters-transformers[0].args.include=parameter1,parameter3", + "spring.cloud.appbroker.services[0].apps[0].parameters-transformers[1].name=PropertyMapping", + "spring.cloud.appbroker.services[0].apps[0].parameters-transformers[1].args.include=memory" }) void deployAppsWithParametersOnCreateService() { // when a service instance is created Map parameters = new HashMap<>(); @@ -80,7 +78,7 @@ class CreateInstanceWithParametersAcceptanceTest extends CloudFoundryAcceptanceT // then a backing application is deployed Optional backingApplication = getApplicationSummary(APP_NAME); - assertThat(backingApplication).hasValueSatisfying(app -> { + assertThat(backingApplication).hasValueSatisfying((app) -> { assertThat(app.getInstances()).isEqualTo(1); assertThat(app.getRunningInstances()).isEqualTo(1); assertThat(app.getMemoryLimit()).isEqualTo(2048); diff --git a/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/CreateInstanceWithServiceInstanceGuidSuffixTargetAcceptanceTest.java b/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/CreateInstanceWithServiceInstanceGuidSuffixTargetAcceptanceTests.java similarity index 76% rename from spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/CreateInstanceWithServiceInstanceGuidSuffixTargetAcceptanceTest.java rename to spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/CreateInstanceWithServiceInstanceGuidSuffixTargetAcceptanceTests.java index e79fe10..3e6f3ce 100644 --- a/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/CreateInstanceWithServiceInstanceGuidSuffixTargetAcceptanceTest.java +++ b/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/CreateInstanceWithServiceInstanceGuidSuffixTargetAcceptanceTests.java @@ -25,7 +25,7 @@ import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; -class CreateInstanceWithServiceInstanceGuidSuffixTargetAcceptanceTest extends CloudFoundryAcceptanceTest { +class CreateInstanceWithServiceInstanceGuidSuffixTargetAcceptanceTests extends CloudFoundryAcceptanceTests { private static final String SUFFIX = "create-si-guid"; @@ -55,17 +55,15 @@ class CreateInstanceWithServiceInstanceGuidSuffixTargetAcceptanceTest extends Cl } @Test - @AppBrokerTestProperties({ - "spring.cloud.appbroker.services[0].service-name=" + APP_SERVICE_NAME, - "spring.cloud.appbroker.services[0].plan-name=" + PLAN_NAME, - "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME_1, - "spring.cloud.appbroker.services[0].apps[0].path=" + BACKING_APP_PATH, - "spring.cloud.appbroker.services[0].apps[0].services[0].service-instance-name=" + BACKING_SI_NAME, - "spring.cloud.appbroker.services[0].services[0].name=" + BACKING_SERVICE_NAME, - "spring.cloud.appbroker.services[0].services[0].plan=" + PLAN_NAME, - "spring.cloud.appbroker.services[0].services[0].service-instance-name=" + BACKING_SI_NAME, - "spring.cloud.appbroker.services[0].target.name=ServiceInstanceGuidSuffix" - }) + @AppBrokerTestProperties({ "spring.cloud.appbroker.services[0].service-name=" + APP_SERVICE_NAME, + "spring.cloud.appbroker.services[0].plan-name=" + PLAN_NAME, + "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME_1, + "spring.cloud.appbroker.services[0].apps[0].path=" + BACKING_APP_PATH, + "spring.cloud.appbroker.services[0].apps[0].services[0].service-instance-name=" + BACKING_SI_NAME, + "spring.cloud.appbroker.services[0].services[0].name=" + BACKING_SERVICE_NAME, + "spring.cloud.appbroker.services[0].services[0].plan=" + PLAN_NAME, + "spring.cloud.appbroker.services[0].services[0].service-instance-name=" + BACKING_SI_NAME, + "spring.cloud.appbroker.services[0].target.name=ServiceInstanceGuidSuffix" }) void deployAppsWithServiceInstanceGuidSuffixOnCreateService() { // when a service instance is created with target createServiceInstance(SI_NAME); @@ -73,11 +71,12 @@ class CreateInstanceWithServiceInstanceGuidSuffixTargetAcceptanceTest extends Cl // then backing application is created final String serviceInstanceGuid = getServiceInstanceGuid(SI_NAME); - // then backing application is named as the concatenation of the name and it's service instance id + // then backing application is named as the concatenation of the name and it's + // service instance id final String truncatedAppName = APP_NAME_1.substring(0, 13); final String expectedApplicationName = truncatedAppName + "-" + serviceInstanceGuid; Optional backingApplication = getApplicationSummary(expectedApplicationName); - assertThat(backingApplication).hasValueSatisfying(app -> { + assertThat(backingApplication).hasValueSatisfying((app) -> { assertThat(app.getName()).isEqualTo(expectedApplicationName); assertThat(app.getRunningInstances()).isEqualTo(1); }); diff --git a/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/CreateInstanceWithServicesAcceptanceTest.java b/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/CreateInstanceWithServicesAcceptanceTests.java similarity index 68% rename from spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/CreateInstanceWithServicesAcceptanceTest.java rename to spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/CreateInstanceWithServicesAcceptanceTests.java index 8313257..e276a93 100644 --- a/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/CreateInstanceWithServicesAcceptanceTest.java +++ b/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/CreateInstanceWithServicesAcceptanceTests.java @@ -26,7 +26,7 @@ import static java.util.Collections.emptyMap; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; -class CreateInstanceWithServicesAcceptanceTest extends CloudFoundryAcceptanceTest { +class CreateInstanceWithServicesAcceptanceTests extends CloudFoundryAcceptanceTests { private static final String APP_NAME = "app-create-services"; @@ -58,17 +58,15 @@ class CreateInstanceWithServicesAcceptanceTest extends CloudFoundryAcceptanceTes } @Test - @AppBrokerTestProperties({ - "spring.cloud.appbroker.services[0].service-name=" + APP_SERVICE_NAME, - "spring.cloud.appbroker.services[0].plan-name=" + PLAN_NAME, - "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME, - "spring.cloud.appbroker.services[0].apps[0].path=" + BACKING_APP_PATH, - "spring.cloud.appbroker.services[0].apps[0].services[0].service-instance-name=" + BACKING_SI_1_NAME, - "spring.cloud.appbroker.services[0].apps[0].services[1].service-instance-name=" + BACKING_SI_2_NAME, - "spring.cloud.appbroker.services[0].services[0].name=" + BACKING_SERVICE_NAME, - "spring.cloud.appbroker.services[0].services[0].plan=" + PLAN_NAME, - "spring.cloud.appbroker.services[0].services[0].service-instance-name=" + BACKING_SI_1_NAME - }) + @AppBrokerTestProperties({ "spring.cloud.appbroker.services[0].service-name=" + APP_SERVICE_NAME, + "spring.cloud.appbroker.services[0].plan-name=" + PLAN_NAME, + "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME, + "spring.cloud.appbroker.services[0].apps[0].path=" + BACKING_APP_PATH, + "spring.cloud.appbroker.services[0].apps[0].services[0].service-instance-name=" + BACKING_SI_1_NAME, + "spring.cloud.appbroker.services[0].apps[0].services[1].service-instance-name=" + BACKING_SI_2_NAME, + "spring.cloud.appbroker.services[0].services[0].name=" + BACKING_SERVICE_NAME, + "spring.cloud.appbroker.services[0].services[0].plan=" + PLAN_NAME, + "spring.cloud.appbroker.services[0].services[0].service-instance-name=" + BACKING_SI_1_NAME }) void deployAppsAndCreateServicesOnCreateService() { // given that a service is available in the marketplace createBackingServiceInstance(BACKING_SERVICE_NAME, PLAN_NAME, BACKING_SI_2_NAME, emptyMap()); @@ -78,8 +76,7 @@ class CreateInstanceWithServicesAcceptanceTest extends CloudFoundryAcceptanceTes // then a backing application is deployed Optional backingApplication = getApplicationSummary(APP_NAME); - assertThat(backingApplication).hasValueSatisfying(app -> - assertThat(app.getRunningInstances()).isEqualTo(1)); + assertThat(backingApplication).hasValueSatisfying((app) -> assertThat(app.getRunningInstances()).isEqualTo(1)); // and the services are bound to it ServiceInstance serviceInstance1 = getBackingServiceInstance(BACKING_SI_1_NAME); @@ -95,12 +92,14 @@ class CreateInstanceWithServicesAcceptanceTest extends CloudFoundryAcceptanceTes await().untilAsserted(() -> assertThat(listServiceInstances()).doesNotContain(BACKING_SI_1_NAME)); await().untilAsserted(() -> assertThat(listServiceInstances()).doesNotContain(BACKING_SI_2_NAME)); - // TODO: another story to only remove the instances with service definition specified (https://github.com/spring-cloud/spring-cloud-app-broker/issues/316) -// // service without specification has no applications bound to it -// ServiceInstance serviceInstance2AfterDeletion = getServiceInstance(BACKING_SI_2_NAME); -// assertThat(serviceInstance2AfterDeletion.getApplications()).isEmpty(); -// -// deleteServiceInstance(BACKING_SI_2_NAME); + // TODO: another story to only remove the instances with service definition + // specified (https://github.com/spring-cloud/spring-cloud-app-broker/issues/316) + // // service without specification has no applications bound to it + // ServiceInstance serviceInstance2AfterDeletion = + // getServiceInstance(BACKING_SI_2_NAME); + // assertThat(serviceInstance2AfterDeletion.getApplications()).isEmpty(); + // + // deleteServiceInstance(BACKING_SI_2_NAME); } } diff --git a/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/CreateInstanceWithServicesSpacePerServiceInstanceTargetAcceptanceTest.java b/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/CreateInstanceWithServicesSpacePerServiceInstanceTargetAcceptanceTests.java similarity index 70% rename from spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/CreateInstanceWithServicesSpacePerServiceInstanceTargetAcceptanceTest.java rename to spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/CreateInstanceWithServicesSpacePerServiceInstanceTargetAcceptanceTests.java index 6e2aadb..dcd4dd2 100644 --- a/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/CreateInstanceWithServicesSpacePerServiceInstanceTargetAcceptanceTest.java +++ b/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/CreateInstanceWithServicesSpacePerServiceInstanceTargetAcceptanceTests.java @@ -25,14 +25,20 @@ import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; -class CreateInstanceWithServicesSpacePerServiceInstanceTargetAcceptanceTest extends CloudFoundryAcceptanceTest { +class CreateInstanceWithServicesSpacePerServiceInstanceTargetAcceptanceTests extends CloudFoundryAcceptanceTests { private static final String APP_NAME = "app-create-two-space-per"; + private static final String SI_NAME = "si-create-two-space-per"; + private static final String BACKING_SI_NAME_1 = "backing-service-two-space-per-target-1"; + private static final String BACKING_SI_NAME_2 = "backing-service-two-space-per-target-2"; + private static final String SUFFIX = "two-space-per-si"; + private static final String APP_SERVICE_NAME = "app-service-" + SUFFIX; + private static final String BACKING_SERVICE_NAME = "backing-service-" + SUFFIX; @Override @@ -51,33 +57,32 @@ class CreateInstanceWithServicesSpacePerServiceInstanceTargetAcceptanceTest exte } @Test - @AppBrokerTestProperties({ - "spring.cloud.appbroker.services[0].service-name=" + APP_SERVICE_NAME, - "spring.cloud.appbroker.services[0].plan-name=" + PLAN_NAME, - "spring.cloud.appbroker.services[0].target.name=SpacePerServiceInstance", + @AppBrokerTestProperties({ "spring.cloud.appbroker.services[0].service-name=" + APP_SERVICE_NAME, + "spring.cloud.appbroker.services[0].plan-name=" + PLAN_NAME, + "spring.cloud.appbroker.services[0].target.name=SpacePerServiceInstance", - "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME, - "spring.cloud.appbroker.services[0].apps[0].path=" + BACKING_APP_PATH, - "spring.cloud.appbroker.services[0].apps[0].services[0].service-instance-name=" + BACKING_SI_NAME_1, - "spring.cloud.appbroker.services[0].apps[0].services[1].service-instance-name=" + BACKING_SI_NAME_2, + "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME, + "spring.cloud.appbroker.services[0].apps[0].path=" + BACKING_APP_PATH, + "spring.cloud.appbroker.services[0].apps[0].services[0].service-instance-name=" + BACKING_SI_NAME_1, + "spring.cloud.appbroker.services[0].apps[0].services[1].service-instance-name=" + BACKING_SI_NAME_2, - "spring.cloud.appbroker.services[0].services[0].name=" + BACKING_SERVICE_NAME, - "spring.cloud.appbroker.services[0].services[0].plan=" + PLAN_NAME, - "spring.cloud.appbroker.services[0].services[0].service-instance-name=" + BACKING_SI_NAME_1, + "spring.cloud.appbroker.services[0].services[0].name=" + BACKING_SERVICE_NAME, + "spring.cloud.appbroker.services[0].services[0].plan=" + PLAN_NAME, + "spring.cloud.appbroker.services[0].services[0].service-instance-name=" + BACKING_SI_NAME_1, - "spring.cloud.appbroker.services[0].services[1].name=" + BACKING_SERVICE_NAME, - "spring.cloud.appbroker.services[0].services[1].plan=" + PLAN_NAME, - "spring.cloud.appbroker.services[0].services[1].service-instance-name=" + BACKING_SI_NAME_2 - }) + "spring.cloud.appbroker.services[0].services[1].name=" + BACKING_SERVICE_NAME, + "spring.cloud.appbroker.services[0].services[1].plan=" + PLAN_NAME, + "spring.cloud.appbroker.services[0].services[1].service-instance-name=" + BACKING_SI_NAME_2 }) void deployAppsInTargetSpaceOnCreateService() { // when a service instance is created with targets createServiceInstance(SI_NAME); - // then backing applications are deployed in a space named as the service instance id + // then backing applications are deployed in a space named as the service instance + // id String spaceName = getServiceInstanceGuid(SI_NAME); Optional backingApplication1 = getApplicationSummary(APP_NAME, spaceName); - assertThat(backingApplication1).hasValueSatisfying(app -> { + assertThat(backingApplication1).hasValueSatisfying((app) -> { assertThat(app.getRunningInstances()).isEqualTo(1); // and has its route with the service instance id appended to it diff --git a/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/CreateInstanceWithSpacePerServiceInstanceTargetAcceptanceTest.java b/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/CreateInstanceWithSpacePerServiceInstanceTargetAcceptanceTests.java similarity index 71% rename from spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/CreateInstanceWithSpacePerServiceInstanceTargetAcceptanceTest.java rename to spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/CreateInstanceWithSpacePerServiceInstanceTargetAcceptanceTests.java index c970926..8ef4f54 100644 --- a/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/CreateInstanceWithSpacePerServiceInstanceTargetAcceptanceTest.java +++ b/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/CreateInstanceWithSpacePerServiceInstanceTargetAcceptanceTests.java @@ -25,7 +25,7 @@ import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; -class CreateInstanceWithSpacePerServiceInstanceTargetAcceptanceTest extends CloudFoundryAcceptanceTest { +class CreateInstanceWithSpacePerServiceInstanceTargetAcceptanceTests extends CloudFoundryAcceptanceTests { private static final String APP_NAME_1 = "app-create-space-per1"; @@ -57,32 +57,31 @@ class CreateInstanceWithSpacePerServiceInstanceTargetAcceptanceTest extends Clou } @Test - @AppBrokerTestProperties({ - "spring.cloud.appbroker.services[0].service-name=" + APP_SERVICE_NAME, - "spring.cloud.appbroker.services[0].plan-name=" + PLAN_NAME, + @AppBrokerTestProperties({ "spring.cloud.appbroker.services[0].service-name=" + APP_SERVICE_NAME, + "spring.cloud.appbroker.services[0].plan-name=" + PLAN_NAME, - "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME_1, - "spring.cloud.appbroker.services[0].apps[0].path=" + BACKING_APP_PATH, - "spring.cloud.appbroker.services[0].apps[0].services[0].service-instance-name=" + BACKING_SI_NAME, + "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME_1, + "spring.cloud.appbroker.services[0].apps[0].path=" + BACKING_APP_PATH, + "spring.cloud.appbroker.services[0].apps[0].services[0].service-instance-name=" + BACKING_SI_NAME, - "spring.cloud.appbroker.services[0].apps[1].name=" + APP_NAME_2, - "spring.cloud.appbroker.services[0].apps[1].path=" + BACKING_APP_PATH, + "spring.cloud.appbroker.services[0].apps[1].name=" + APP_NAME_2, + "spring.cloud.appbroker.services[0].apps[1].path=" + BACKING_APP_PATH, - "spring.cloud.appbroker.services[0].services[0].name=" + BACKING_SERVICE_NAME, - "spring.cloud.appbroker.services[0].services[0].plan=" + PLAN_NAME, - "spring.cloud.appbroker.services[0].services[0].service-instance-name=" + BACKING_SI_NAME, + "spring.cloud.appbroker.services[0].services[0].name=" + BACKING_SERVICE_NAME, + "spring.cloud.appbroker.services[0].services[0].plan=" + PLAN_NAME, + "spring.cloud.appbroker.services[0].services[0].service-instance-name=" + BACKING_SI_NAME, - "spring.cloud.appbroker.services[0].target.name=SpacePerServiceInstance" - }) + "spring.cloud.appbroker.services[0].target.name=SpacePerServiceInstance" }) void deployAppsInTargetSpaceOnCreateService() { // when a service instance is created with targets createServiceInstance(SI_NAME); - // then backing applications are deployed in a space named as the service instance id + // then backing applications are deployed in a space named as the service instance + // id String spaceName = getServiceInstanceGuid(SI_NAME); Optional backingApplication1 = getApplicationSummary(APP_NAME_1, spaceName); - assertThat(backingApplication1).hasValueSatisfying(app -> { + assertThat(backingApplication1).hasValueSatisfying((app) -> { assertThat(app.getRunningInstances()).isEqualTo(1); // and has its route with the service instance id appended to it @@ -91,8 +90,7 @@ class CreateInstanceWithSpacePerServiceInstanceTargetAcceptanceTest extends Clou }); Optional backingApplication2 = getApplicationSummary(APP_NAME_2, spaceName); - assertThat(backingApplication2).hasValueSatisfying(app -> - assertThat(app.getRunningInstances()).isEqualTo(1)); + assertThat(backingApplication2).hasValueSatisfying((app) -> assertThat(app.getRunningInstances()).isEqualTo(1)); // and the services are bound to it ServiceInstance serviceInstance1 = getBackingServiceInstance(BACKING_SI_NAME, spaceName); diff --git a/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/HealthListener.java b/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/HealthListener.java index f9ed1b2..76e5c24 100644 --- a/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/HealthListener.java +++ b/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/HealthListener.java @@ -44,55 +44,55 @@ class HealthListener { private final RestTemplate restTemplate; - public HealthListener(RestTemplate restTemplate) { + HealthListener(RestTemplate restTemplate) { this.restTemplate = restTemplate; } - public void start(String path) { - if (running.get()) { + void start(String path) { + if (this.running.get()) { throw new IllegalStateException("cannot start when test is already running"); } - requests.set(0); - errors.set(0); - running.set(true); + this.requests.set(0); + this.errors.set(0); + this.running.set(true); - runner = new Thread(() -> { - while (running.get()) { + this.runner = new Thread(() -> { + while (this.running.get()) { try { - requests.incrementAndGet(); - ResponseEntity response = restTemplate + this.requests.incrementAndGet(); + ResponseEntity response = this.restTemplate .getForEntity(URI.create("http://" + path + "/actuator/health"), String.class); if (response.getStatusCode() != HttpStatus.OK) { - errors.incrementAndGet(); + this.errors.incrementAndGet(); } Thread.sleep(1000); } catch (RestClientException | InterruptedException re) { - errors.incrementAndGet(); + this.errors.incrementAndGet(); } } }); - runner.start(); + this.runner.start(); } - public void stop() { - running.set(false); + void stop() { + this.running.set(false); try { - runner.join(); + this.runner.join(); } - catch (InterruptedException e) { + catch (InterruptedException ex) { if (LOG.isDebugEnabled()) { - LOG.debug("thread was interrupted while waiting to die", e); + LOG.debug("thread was interrupted while waiting to die", ex); } } } - public int getSuccesses() { - return requests.get(); + int getSuccesses() { + return this.requests.get(); } - public int getFailures() { - return errors.get(); + int getFailures() { + return this.errors.get(); } } diff --git a/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/LoggingRecentAcceptanceTest.java b/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/LoggingRecentAcceptanceTests.java similarity index 69% rename from spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/LoggingRecentAcceptanceTest.java rename to spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/LoggingRecentAcceptanceTests.java index 9e33823..e00e2c8 100644 --- a/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/LoggingRecentAcceptanceTest.java +++ b/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/LoggingRecentAcceptanceTests.java @@ -1,11 +1,11 @@ /* - * Copyright 2002-2020 the original author or authors + * Copyright 2002-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * https://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -24,7 +24,7 @@ import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; -class LoggingRecentAcceptanceTest extends CloudFoundryAcceptanceTest { +class LoggingRecentAcceptanceTests extends CloudFoundryAcceptanceTests { private static final String APP_CREATE_1 = "app-logging-recent-1"; @@ -52,19 +52,16 @@ class LoggingRecentAcceptanceTest extends CloudFoundryAcceptanceTest { } @Test - @AppBrokerTestProperties({ - "spring.cloud.appbroker.services[0].service-name=" + APP_SERVICE_NAME, - "spring.cloud.appbroker.services[0].plan-name=" + PLAN_NAME, - "spring.cloud.appbroker.services[0].apps[0].name=" + APP_CREATE_1, - "spring.cloud.appbroker.services[0].apps[0].path=" + BACKING_APP_PATH, - "spring.cloud.appbroker.services[0].target.name=SpacePerServiceInstance", - "spring.cloud.appbroker.deployer.cloudfoundry.properties.stack=cflinuxfs4" - }) + @AppBrokerTestProperties({ "spring.cloud.appbroker.services[0].service-name=" + APP_SERVICE_NAME, + "spring.cloud.appbroker.services[0].plan-name=" + PLAN_NAME, + "spring.cloud.appbroker.services[0].apps[0].name=" + APP_CREATE_1, + "spring.cloud.appbroker.services[0].apps[0].path=" + BACKING_APP_PATH, + "spring.cloud.appbroker.services[0].target.name=SpacePerServiceInstance", + "spring.cloud.appbroker.deployer.cloudfoundry.properties.stack=cflinuxfs4" }) void shouldReturnBackingApplicationLogs() { createServiceInstance(SI_NAME); - String lines = callCLICommand( - List.of("cf", "service-logs", SI_NAME, "--recent", "--skip-ssl-validation")) + String lines = callCLICommand(List.of("cf", "service-logs", SI_NAME, "--recent", "--skip-ssl-validation")) .block(Duration.ofSeconds(35)); assertThat(lines).isNotEmpty(); diff --git a/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/LoggingStreamingAcceptanceTest.java b/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/LoggingStreamingAcceptanceTests.java similarity index 66% rename from spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/LoggingStreamingAcceptanceTest.java rename to spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/LoggingStreamingAcceptanceTests.java index 94b7784..2bbd66b 100644 --- a/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/LoggingStreamingAcceptanceTest.java +++ b/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/LoggingStreamingAcceptanceTests.java @@ -1,11 +1,11 @@ /* - * Copyright 2002-2020 the original author or authors + * Copyright 2002-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * https://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -28,7 +28,7 @@ import reactor.test.StepVerifier; import static org.assertj.core.api.Assertions.assertThat; -class LoggingStreamingAcceptanceTest extends CloudFoundryAcceptanceTest { +class LoggingStreamingAcceptanceTests extends CloudFoundryAcceptanceTests { private static final String APP_CREATE_1 = "app-logging-stream-1"; @@ -56,30 +56,26 @@ class LoggingStreamingAcceptanceTest extends CloudFoundryAcceptanceTest { } @Test - @AppBrokerTestProperties({ - "spring.cloud.appbroker.services[0].service-name=" + APP_SERVICE_NAME, - "spring.cloud.appbroker.services[0].plan-name=" + PLAN_NAME, - "spring.cloud.appbroker.services[0].apps[0].name=" + APP_CREATE_1, - "spring.cloud.appbroker.services[0].apps[0].path=" + BACKING_APP_PATH, - "spring.cloud.appbroker.services[0].target.name=SpacePerServiceInstance", - "spring.cloud.appbroker.deployer.cloudfoundry.properties.stack=cflinuxfs4" - }) + @AppBrokerTestProperties({ "spring.cloud.appbroker.services[0].service-name=" + APP_SERVICE_NAME, + "spring.cloud.appbroker.services[0].plan-name=" + PLAN_NAME, + "spring.cloud.appbroker.services[0].apps[0].name=" + APP_CREATE_1, + "spring.cloud.appbroker.services[0].apps[0].path=" + BACKING_APP_PATH, + "spring.cloud.appbroker.services[0].target.name=SpacePerServiceInstance", + "spring.cloud.appbroker.deployer.cloudfoundry.properties.stack=cflinuxfs4" }) void shouldStreamBackingApplicationLogs() { - Mono createServiceInstanceMono = Mono.fromRunnable(() -> - CompletableFuture.runAsync(() -> - createServiceInstance(SI_NAME))) + Mono createServiceInstanceMono = Mono + .fromRunnable(() -> CompletableFuture.runAsync(() -> createServiceInstance(SI_NAME))) .subscribeOn(Schedulers.boundedElastic()); - Mono logStreamingMono = Mono.defer(() -> callCLICommand( - List.of("cf", "service-logs", SI_NAME, "--skip-ssl-validation") - )).subscribeOn(Schedulers.boundedElastic()); + Mono logStreamingMono = Mono + .defer(() -> callCLICommand(List.of("cf", "service-logs", SI_NAME, "--skip-ssl-validation"))) + .subscribeOn(Schedulers.boundedElastic()); - StepVerifier.create(createServiceInstanceMono - .then(Mono.delay(Duration.ofSeconds(20)).then()) + StepVerifier + .create(createServiceInstanceMono.then(Mono.delay(Duration.ofSeconds(20)).then()) .then(getServiceInstanceMono(SI_NAME).retry(5)) - .then(Mono.zip(logStreamingMono, logStreamingMono)) - ) - .assertNext(tuple -> { + .then(Mono.zip(logStreamingMono, logStreamingMono))) + .assertNext((tuple) -> { assertThat(tuple.getT1()).isNotEmpty(); assertThat(tuple.getT1()).contains("Connected, tailing logs for service instance"); assertThat(tuple.getT1()).contains("[STG/0]"); diff --git a/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/UpdateInstanceAcceptanceTest.java b/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/UpdateInstanceAcceptanceTests.java similarity index 68% rename from spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/UpdateInstanceAcceptanceTest.java rename to spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/UpdateInstanceAcceptanceTests.java index 1e22f89..1f939d1 100644 --- a/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/UpdateInstanceAcceptanceTest.java +++ b/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/UpdateInstanceAcceptanceTests.java @@ -28,7 +28,7 @@ import org.springframework.beans.factory.annotation.Autowired; import static org.assertj.core.api.Assertions.assertThat; -class UpdateInstanceAcceptanceTest extends CloudFoundryAcceptanceTest { +class UpdateInstanceAcceptanceTests extends CloudFoundryAcceptanceTests { private static final String APP_NAME = "app-update"; @@ -59,28 +59,25 @@ class UpdateInstanceAcceptanceTest extends CloudFoundryAcceptanceTest { } @Test - @AppBrokerTestProperties({ - "spring.cloud.appbroker.services[0].service-name=" + APP_SERVICE_NAME, - "spring.cloud.appbroker.services[0].plan-name=" + PLAN_NAME, - "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME, - "spring.cloud.appbroker.services[0].apps[0].path=" + BACKING_APP_PATH, - "spring.cloud.appbroker.services[0].apps[0].environment.parameter1=config1", - "spring.cloud.appbroker.services[0].apps[0].environment.parameter2=config2", - "spring.cloud.appbroker.services[0].apps[0].environment.parameter3=config3", - "spring.cloud.appbroker.services[0].apps[0].environment.parameter4=config4", - "spring.cloud.appbroker.services[0].apps[0].parameters-transformers[0].name=EnvironmentMapping", - "spring.cloud.appbroker.services[0].apps[0].parameters-transformers[0].args.include=parameter1,parameter3", - "spring.cloud.appbroker.services[0].apps[0].parameters-transformers[1].name=PropertyMapping", - "spring.cloud.appbroker.services[0].apps[0].parameters-transformers[1].args.include=count" - }) + @AppBrokerTestProperties({ "spring.cloud.appbroker.services[0].service-name=" + APP_SERVICE_NAME, + "spring.cloud.appbroker.services[0].plan-name=" + PLAN_NAME, + "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME, + "spring.cloud.appbroker.services[0].apps[0].path=" + BACKING_APP_PATH, + "spring.cloud.appbroker.services[0].apps[0].environment.parameter1=config1", + "spring.cloud.appbroker.services[0].apps[0].environment.parameter2=config2", + "spring.cloud.appbroker.services[0].apps[0].environment.parameter3=config3", + "spring.cloud.appbroker.services[0].apps[0].environment.parameter4=config4", + "spring.cloud.appbroker.services[0].apps[0].parameters-transformers[0].name=EnvironmentMapping", + "spring.cloud.appbroker.services[0].apps[0].parameters-transformers[0].args.include=parameter1,parameter3", + "spring.cloud.appbroker.services[0].apps[0].parameters-transformers[1].name=PropertyMapping", + "spring.cloud.appbroker.services[0].apps[0].parameters-transformers[1].args.include=count" }) void deployAppsOnUpdateService() { // given a service instance is created createServiceInstance(SI_NAME); // and a backing application is deployed Optional backingApplication = getApplicationSummary(APP_NAME); - assertThat(backingApplication).hasValueSatisfying(app -> - assertThat(app.getRunningInstances()).isEqualTo(1)); + assertThat(backingApplication).hasValueSatisfying((app) -> assertThat(app.getRunningInstances()).isEqualTo(1)); DocumentContext json = getSpringAppJson(APP_NAME); assertThat(json.read("$.parameter1").toString()).isEqualTo("config1"); @@ -88,7 +85,7 @@ class UpdateInstanceAcceptanceTest extends CloudFoundryAcceptanceTest { assertThat(json.read("$.parameter3").toString()).isEqualTo("config3"); String path = backingApplication.get().getUrls().get(0); - healthListener.start(path); + this.healthListener.start(path); // when the service instance is updated Map parameters = new HashMap<>(); @@ -99,9 +96,9 @@ class UpdateInstanceAcceptanceTest extends CloudFoundryAcceptanceTest { updateServiceInstance(SI_NAME, parameters); // then the backing application was updated with zero downtime - healthListener.stop(); - assertThat(healthListener.getFailures()).isEqualTo(0); - assertThat(healthListener.getSuccesses()).isGreaterThan(0); + this.healthListener.stop(); + assertThat(this.healthListener.getFailures()).isEqualTo(0); + assertThat(this.healthListener.getSuccesses()).isGreaterThan(0); // the backing application is updated with the new parameters json = getSpringAppJson(APP_NAME); @@ -111,8 +108,7 @@ class UpdateInstanceAcceptanceTest extends CloudFoundryAcceptanceTest { assertThat(json.read("$.parameter4").toString()).isEqualTo("config4"); backingApplication = getApplicationSummary(APP_NAME); - assertThat(backingApplication).hasValueSatisfying(app -> - assertThat(app.getRunningInstances()).isEqualTo(2)); + assertThat(backingApplication).hasValueSatisfying((app) -> assertThat(app.getRunningInstances()).isEqualTo(2)); // when the service instance is deleted deleteServiceInstance(SI_NAME); diff --git a/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/UpdateInstanceWithHostAndDomainAcceptanceTest.java b/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/UpdateInstanceWithHostAndDomainAcceptanceTests.java similarity index 71% rename from spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/UpdateInstanceWithHostAndDomainAcceptanceTest.java rename to spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/UpdateInstanceWithHostAndDomainAcceptanceTests.java index 866348d..040a17c 100644 --- a/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/UpdateInstanceWithHostAndDomainAcceptanceTest.java +++ b/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/UpdateInstanceWithHostAndDomainAcceptanceTests.java @@ -27,7 +27,7 @@ import org.springframework.beans.factory.annotation.Autowired; import static org.assertj.core.api.Assertions.assertThat; -class UpdateInstanceWithHostAndDomainAcceptanceTest extends CloudFoundryAcceptanceTest { +class UpdateInstanceWithHostAndDomainAcceptanceTests extends CloudFoundryAcceptanceTests { private static final String APP_NAME = "app-update-domain"; @@ -58,26 +58,23 @@ class UpdateInstanceWithHostAndDomainAcceptanceTest extends CloudFoundryAcceptan } @Test - @AppBrokerTestProperties({ - "spring.cloud.appbroker.services[0].service-name=" + APP_SERVICE_NAME, - "spring.cloud.appbroker.services[0].plan-name=" + PLAN_NAME, + @AppBrokerTestProperties({ "spring.cloud.appbroker.services[0].service-name=" + APP_SERVICE_NAME, + "spring.cloud.appbroker.services[0].plan-name=" + PLAN_NAME, - "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME, - "spring.cloud.appbroker.services[0].apps[0].path=" + BACKING_APP_PATH, - "spring.cloud.appbroker.services[0].apps[0].parameters-transformers[0].name=PropertyMapping", - "spring.cloud.appbroker.services[0].apps[0].parameters-transformers[0].args.include=host,domain" - }) + "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME, + "spring.cloud.appbroker.services[0].apps[0].path=" + BACKING_APP_PATH, + "spring.cloud.appbroker.services[0].apps[0].parameters-transformers[0].name=PropertyMapping", + "spring.cloud.appbroker.services[0].apps[0].parameters-transformers[0].args.include=host,domain" }) void deployAppsOnUpdateService() { // given a service instance is created createServiceInstance(SI_NAME); // and a backing application is deployed Optional backingApplication = getApplicationSummary(APP_NAME); - assertThat(backingApplication).hasValueSatisfying(app -> - assertThat(app.getRunningInstances()).isEqualTo(1)); + assertThat(backingApplication).hasValueSatisfying((app) -> assertThat(app.getRunningInstances()).isEqualTo(1)); String path = backingApplication.get().getUrls().get(0); - healthListener.start(path); + this.healthListener.start(path); // and the domain exists createDomain("mydomain.com"); @@ -89,13 +86,13 @@ class UpdateInstanceWithHostAndDomainAcceptanceTest extends CloudFoundryAcceptan updateServiceInstance(SI_NAME, parameters); // then the backing application was updated with zero downtime - healthListener.stop(); - assertThat(healthListener.getFailures()).isEqualTo(0); - assertThat(healthListener.getSuccesses()).isGreaterThan(0); + this.healthListener.stop(); + assertThat(this.healthListener.getFailures()).isEqualTo(0); + assertThat(this.healthListener.getSuccesses()).isGreaterThan(0); backingApplication = getApplicationSummary(APP_NAME); - assertThat(backingApplication).hasValueSatisfying(app -> - assertThat(app.getUrls()).contains("myhost.mydomain.com")); + assertThat(backingApplication) + .hasValueSatisfying((app) -> assertThat(app.getUrls()).contains("myhost.mydomain.com")); // when the service instance is deleted deleteServiceInstance(SI_NAME); diff --git a/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/UpdateInstanceWithNewServiceAcceptanceTest.java b/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/UpdateInstanceWithNewServiceAcceptanceTests.java similarity index 69% rename from spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/UpdateInstanceWithNewServiceAcceptanceTest.java rename to spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/UpdateInstanceWithNewServiceAcceptanceTests.java index 9f6ee6d..9767a13 100644 --- a/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/UpdateInstanceWithNewServiceAcceptanceTest.java +++ b/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/UpdateInstanceWithNewServiceAcceptanceTests.java @@ -36,7 +36,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; @TestMethodOrder(MethodOrderer.OrderAnnotation.class) -class UpdateInstanceWithNewServiceAcceptanceTest extends CloudFoundryAcceptanceTest { +class UpdateInstanceWithNewServiceAcceptanceTests extends CloudFoundryAcceptanceTests { private static final String APP_NAME = "app-update-with-new-services"; @@ -56,7 +56,6 @@ class UpdateInstanceWithNewServiceAcceptanceTest extends CloudFoundryAcceptanceT private static final String BACKING_SERVICE_NAME = "backing-service-" + SUFFIX; - @Autowired private HealthListener healthListener; @@ -78,63 +77,58 @@ class UpdateInstanceWithNewServiceAcceptanceTest extends CloudFoundryAcceptanceT @Test @Tag("first") @Order(FIRST_TEST) - @AppBrokerTestProperties({ - "spring.cloud.appbroker.services[0].service-name=" + APP_SERVICE_NAME, - "spring.cloud.appbroker.services[0].plan-name=" + PLAN_NAME, + @AppBrokerTestProperties({ "spring.cloud.appbroker.services[0].service-name=" + APP_SERVICE_NAME, + "spring.cloud.appbroker.services[0].plan-name=" + PLAN_NAME, - "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME, - "spring.cloud.appbroker.services[0].apps[0].path=" + BACKING_APP_PATH, - "spring.cloud.appbroker.services[0].apps[0].services[0].service-instance-name=" + OLD_BACKING_SI_NAME, + "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME, + "spring.cloud.appbroker.services[0].apps[0].path=" + BACKING_APP_PATH, + "spring.cloud.appbroker.services[0].apps[0].services[0].service-instance-name=" + OLD_BACKING_SI_NAME, - "spring.cloud.appbroker.services[0].services[0].name=" + BACKING_SERVICE_NAME, - "spring.cloud.appbroker.services[0].services[0].plan=" + PLAN_NAME, - "spring.cloud.appbroker.services[0].services[0].service-instance-name=" + OLD_BACKING_SI_NAME - }) + "spring.cloud.appbroker.services[0].services[0].name=" + BACKING_SERVICE_NAME, + "spring.cloud.appbroker.services[0].services[0].plan=" + PLAN_NAME, + "spring.cloud.appbroker.services[0].services[0].service-instance-name=" + OLD_BACKING_SI_NAME }) void weCreateAService() { // when a service instance is created createServiceInstance(SI_NAME); // then a backing application is deployed Optional backingApplication = getApplicationSummary(APP_NAME); - assertThat(backingApplication).hasValueSatisfying(app -> - assertThat(app.getRunningInstances()).isEqualTo(1)); + assertThat(backingApplication).hasValueSatisfying((app) -> assertThat(app.getRunningInstances()).isEqualTo(1)); // and the services are bound to it ServiceInstance backingServiceInstance = getBackingServiceInstance(OLD_BACKING_SI_NAME); assertThat(backingServiceInstance.getApplications()).contains(APP_NAME); String path = backingApplication.get().getUrls().get(0); - healthListener.start(path); + this.healthListener.start(path); } @Test @Order(SECOND_TEST) @Tag("last") - @AppBrokerTestProperties({ - "spring.cloud.appbroker.services[0].service-name=" + APP_SERVICE_NAME, - "spring.cloud.appbroker.services[0].plan-name=" + PLAN_NAME, + @AppBrokerTestProperties({ "spring.cloud.appbroker.services[0].service-name=" + APP_SERVICE_NAME, + "spring.cloud.appbroker.services[0].plan-name=" + PLAN_NAME, - "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME, - "spring.cloud.appbroker.services[0].apps[0].path=" + BACKING_APP_PATH, - "spring.cloud.appbroker.services[0].apps[0].services[0].service-instance-name=" + NEW_BACKING_SI_NAME, + "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME, + "spring.cloud.appbroker.services[0].apps[0].path=" + BACKING_APP_PATH, + "spring.cloud.appbroker.services[0].apps[0].services[0].service-instance-name=" + NEW_BACKING_SI_NAME, - "spring.cloud.appbroker.services[0].services[0].name=" + BACKING_SERVICE_NAME, - "spring.cloud.appbroker.services[0].services[0].plan=" + PLAN_NAME, - "spring.cloud.appbroker.services[0].services[0].service-instance-name=" + NEW_BACKING_SI_NAME - }) + "spring.cloud.appbroker.services[0].services[0].name=" + BACKING_SERVICE_NAME, + "spring.cloud.appbroker.services[0].services[0].plan=" + PLAN_NAME, + "spring.cloud.appbroker.services[0].services[0].service-instance-name=" + NEW_BACKING_SI_NAME }) void weUpdateTheServiceInstanceWithANewBackingService() { // when the service instance is updated with a new service updateServiceInstance(SI_NAME, Collections.emptyMap()); // then the backing application was updated with zero downtime - healthListener.stop(); - assertThat(healthListener.getFailures()).isEqualTo(0); - assertThat(healthListener.getSuccesses()).isGreaterThan(0); + this.healthListener.stop(); + assertThat(this.healthListener.getFailures()).isEqualTo(0); + assertThat(this.healthListener.getSuccesses()).isGreaterThan(0); // then a backing application is re-deployed Optional updatedBackingApplication = getApplicationSummary(APP_NAME); - assertThat(updatedBackingApplication).hasValueSatisfying(app -> - assertThat(app.getRunningInstances()).isEqualTo(1)); + assertThat(updatedBackingApplication) + .hasValueSatisfying((app) -> assertThat(app.getRunningInstances()).isEqualTo(1)); // and the new backing service is bound to it ServiceInstance newBackingServiceInstance = getBackingServiceInstance(NEW_BACKING_SI_NAME); diff --git a/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/UpdateInstanceWithNewServiceAndTargetAcceptanceTest.java b/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/UpdateInstanceWithNewServiceAndTargetAcceptanceTests.java similarity index 68% rename from spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/UpdateInstanceWithNewServiceAndTargetAcceptanceTest.java rename to spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/UpdateInstanceWithNewServiceAndTargetAcceptanceTests.java index 09881cb..4398685 100644 --- a/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/UpdateInstanceWithNewServiceAndTargetAcceptanceTest.java +++ b/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/UpdateInstanceWithNewServiceAndTargetAcceptanceTests.java @@ -36,7 +36,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; @TestMethodOrder(MethodOrderer.OrderAnnotation.class) -class UpdateInstanceWithNewServiceAndTargetAcceptanceTest extends CloudFoundryAcceptanceTest { +class UpdateInstanceWithNewServiceAndTargetAcceptanceTests extends CloudFoundryAcceptanceTests { private static final String APP_NAME = "app-new-service"; @@ -56,7 +56,6 @@ class UpdateInstanceWithNewServiceAndTargetAcceptanceTest extends CloudFoundryAc private static final String BACKING_SERVICE_NAME = "backing-service-" + SUFFIX; - @Autowired private HealthListener healthListener; @@ -78,20 +77,18 @@ class UpdateInstanceWithNewServiceAndTargetAcceptanceTest extends CloudFoundryAc @Test @Tag("first") @Order(FIRST_TEST) - @AppBrokerTestProperties({ - "spring.cloud.appbroker.services[0].service-name=" + APP_SERVICE_NAME, - "spring.cloud.appbroker.services[0].plan-name=" + PLAN_NAME, + @AppBrokerTestProperties({ "spring.cloud.appbroker.services[0].service-name=" + APP_SERVICE_NAME, + "spring.cloud.appbroker.services[0].plan-name=" + PLAN_NAME, - "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME, - "spring.cloud.appbroker.services[0].apps[0].path=" + BACKING_APP_PATH, - "spring.cloud.appbroker.services[0].apps[0].services[0].service-instance-name=" + OLD_BACKING_SI_NAME, + "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME, + "spring.cloud.appbroker.services[0].apps[0].path=" + BACKING_APP_PATH, + "spring.cloud.appbroker.services[0].apps[0].services[0].service-instance-name=" + OLD_BACKING_SI_NAME, - "spring.cloud.appbroker.services[0].services[0].name=" + BACKING_SERVICE_NAME, - "spring.cloud.appbroker.services[0].services[0].plan=" + PLAN_NAME, - "spring.cloud.appbroker.services[0].services[0].service-instance-name=" + OLD_BACKING_SI_NAME, + "spring.cloud.appbroker.services[0].services[0].name=" + BACKING_SERVICE_NAME, + "spring.cloud.appbroker.services[0].services[0].plan=" + PLAN_NAME, + "spring.cloud.appbroker.services[0].services[0].service-instance-name=" + OLD_BACKING_SI_NAME, - "spring.cloud.appbroker.services[0].target.name=SpacePerServiceInstance" - }) + "spring.cloud.appbroker.services[0].target.name=SpacePerServiceInstance" }) void weCreateAService() { // when a service instance is created createServiceInstance(SI_NAME); @@ -100,47 +97,45 @@ class UpdateInstanceWithNewServiceAndTargetAcceptanceTest extends CloudFoundryAc String spaceName = getServiceInstanceGuid(SI_NAME); Optional backingApplication = getApplicationSummary(APP_NAME, spaceName); - assertThat(backingApplication).hasValueSatisfying(app -> assertThat(app.getRunningInstances()).isEqualTo(1)); + assertThat(backingApplication).hasValueSatisfying((app) -> assertThat(app.getRunningInstances()).isEqualTo(1)); // and the services are bound to it ServiceInstance backingServiceInstance = getBackingServiceInstance(OLD_BACKING_SI_NAME, spaceName); assertThat(backingServiceInstance.getApplications()).contains(APP_NAME); String path = backingApplication.get().getUrls().get(0); - healthListener.start(path); + this.healthListener.start(path); } @Test @Order(SECOND_TEST) @Tag("last") - @AppBrokerTestProperties({ - "spring.cloud.appbroker.services[0].service-name=" + APP_SERVICE_NAME, - "spring.cloud.appbroker.services[0].plan-name=" + PLAN_NAME, + @AppBrokerTestProperties({ "spring.cloud.appbroker.services[0].service-name=" + APP_SERVICE_NAME, + "spring.cloud.appbroker.services[0].plan-name=" + PLAN_NAME, - "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME, - "spring.cloud.appbroker.services[0].apps[0].path=" + BACKING_APP_PATH, - "spring.cloud.appbroker.services[0].apps[0].services[0].service-instance-name=" + NEW_BACKING_SI_NAME, + "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME, + "spring.cloud.appbroker.services[0].apps[0].path=" + BACKING_APP_PATH, + "spring.cloud.appbroker.services[0].apps[0].services[0].service-instance-name=" + NEW_BACKING_SI_NAME, - "spring.cloud.appbroker.services[0].services[0].name=" + BACKING_SERVICE_NAME, - "spring.cloud.appbroker.services[0].services[0].plan=" + PLAN_NAME, - "spring.cloud.appbroker.services[0].services[0].service-instance-name=" + NEW_BACKING_SI_NAME, + "spring.cloud.appbroker.services[0].services[0].name=" + BACKING_SERVICE_NAME, + "spring.cloud.appbroker.services[0].services[0].plan=" + PLAN_NAME, + "spring.cloud.appbroker.services[0].services[0].service-instance-name=" + NEW_BACKING_SI_NAME, - "spring.cloud.appbroker.services[0].target.name=SpacePerServiceInstance" - }) + "spring.cloud.appbroker.services[0].target.name=SpacePerServiceInstance" }) void weUpdateTheServiceInstanceWithANewBackingService() { // when the service instance is updated with a new service updateServiceInstance(SI_NAME, Collections.emptyMap()); String spaceName = getServiceInstanceGuid(SI_NAME); // then the backing application was updated with zero downtime - healthListener.stop(); - assertThat(healthListener.getFailures()).isEqualTo(0); - assertThat(healthListener.getSuccesses()).isGreaterThan(0); + this.healthListener.stop(); + assertThat(this.healthListener.getFailures()).isEqualTo(0); + assertThat(this.healthListener.getSuccesses()).isGreaterThan(0); // then a backing application is re-deployed Optional updatedBackingApplication = getApplicationSummary(APP_NAME, spaceName); - assertThat(updatedBackingApplication).hasValueSatisfying(app -> - assertThat(app.getRunningInstances()).isEqualTo(1)); + assertThat(updatedBackingApplication) + .hasValueSatisfying((app) -> assertThat(app.getRunningInstances()).isEqualTo(1)); // and the new backing service is bound to it ServiceInstance newBackingServiceInstance = getBackingServiceInstance(NEW_BACKING_SI_NAME, spaceName); diff --git a/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/UpdateInstanceWithServicesAcceptanceTest.java b/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/UpdateInstanceWithServicesAcceptanceTests.java similarity index 72% rename from spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/UpdateInstanceWithServicesAcceptanceTest.java rename to spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/UpdateInstanceWithServicesAcceptanceTests.java index 6cb4319..ffc000f 100644 --- a/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/UpdateInstanceWithServicesAcceptanceTest.java +++ b/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/UpdateInstanceWithServicesAcceptanceTests.java @@ -29,7 +29,7 @@ import org.springframework.beans.factory.annotation.Autowired; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; -class UpdateInstanceWithServicesAcceptanceTest extends CloudFoundryAcceptanceTest { +class UpdateInstanceWithServicesAcceptanceTests extends CloudFoundryAcceptanceTests { private static final String APP_NAME = "app-update-services"; @@ -62,34 +62,31 @@ class UpdateInstanceWithServicesAcceptanceTest extends CloudFoundryAcceptanceTes } @Test - @AppBrokerTestProperties({ - "spring.cloud.appbroker.services[0].service-name=" + APP_SERVICE_NAME, - "spring.cloud.appbroker.services[0].plan-name=" + PLAN_NAME, + @AppBrokerTestProperties({ "spring.cloud.appbroker.services[0].service-name=" + APP_SERVICE_NAME, + "spring.cloud.appbroker.services[0].plan-name=" + PLAN_NAME, - "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME, - "spring.cloud.appbroker.services[0].apps[0].path=" + BACKING_APP_PATH, - "spring.cloud.appbroker.services[0].apps[0].services[0].service-instance-name=" + BACKING_SI_NAME, + "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME, + "spring.cloud.appbroker.services[0].apps[0].path=" + BACKING_APP_PATH, + "spring.cloud.appbroker.services[0].apps[0].services[0].service-instance-name=" + BACKING_SI_NAME, - "spring.cloud.appbroker.services[0].services[0].name=" + BACKING_SERVICE_NAME, - "spring.cloud.appbroker.services[0].services[0].plan=" + PLAN_NAME, - "spring.cloud.appbroker.services[0].services[0].service-instance-name=" + BACKING_SI_NAME, - "spring.cloud.appbroker.services[0].services[0].rebind-on-update=true" - }) + "spring.cloud.appbroker.services[0].services[0].name=" + BACKING_SERVICE_NAME, + "spring.cloud.appbroker.services[0].services[0].plan=" + PLAN_NAME, + "spring.cloud.appbroker.services[0].services[0].service-instance-name=" + BACKING_SI_NAME, + "spring.cloud.appbroker.services[0].services[0].rebind-on-update=true" }) void shouldPushAppWithServicesBind() { // when a service instance is created createServiceInstance(SI_NAME); // then a backing application is deployed Optional backingApplication = getApplicationSummary(APP_NAME); - assertThat(backingApplication).hasValueSatisfying(app -> - assertThat(app.getRunningInstances()).isEqualTo(1)); + assertThat(backingApplication).hasValueSatisfying((app) -> assertThat(app.getRunningInstances()).isEqualTo(1)); // and the services are bound to it ServiceInstance backingServiceInstance = getBackingServiceInstance(BACKING_SI_NAME); assertThat(backingServiceInstance.getApplications()).contains(APP_NAME); String path = backingApplication.get().getUrls().get(0); - healthListener.start(path); + this.healthListener.start(path); // when the service instance is updated Map parameters = new HashMap<>(); @@ -99,14 +96,14 @@ class UpdateInstanceWithServicesAcceptanceTest extends CloudFoundryAcceptanceTes updateServiceInstance(SI_NAME, parameters); // then the backing application was updated with zero downtime - healthListener.stop(); - assertThat(healthListener.getFailures()).isEqualTo(0); - assertThat(healthListener.getSuccesses()).isGreaterThan(0); + this.healthListener.stop(); + assertThat(this.healthListener.getFailures()).isEqualTo(0); + assertThat(this.healthListener.getSuccesses()).isGreaterThan(0); // then a backing application is re-deployed Optional updatedBackingApplication = getApplicationSummary(APP_NAME); - assertThat(updatedBackingApplication).hasValueSatisfying(app -> - assertThat(app.getRunningInstances()).isEqualTo(1)); + assertThat(updatedBackingApplication) + .hasValueSatisfying((app) -> assertThat(app.getRunningInstances()).isEqualTo(1)); // and the services are still bound to it ServiceInstance backingServiceInstanceUpdated = getBackingServiceInstance(BACKING_SI_NAME); diff --git a/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/UpdateInstanceWithTargetAcceptanceTest.java b/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/UpdateInstanceWithTargetAcceptanceTests.java similarity index 77% rename from spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/UpdateInstanceWithTargetAcceptanceTest.java rename to spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/UpdateInstanceWithTargetAcceptanceTests.java index c7bed55..4cce36f 100644 --- a/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/UpdateInstanceWithTargetAcceptanceTest.java +++ b/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/UpdateInstanceWithTargetAcceptanceTests.java @@ -28,7 +28,7 @@ import org.springframework.beans.factory.annotation.Autowired; import static org.assertj.core.api.Assertions.assertThat; -class UpdateInstanceWithTargetAcceptanceTest extends CloudFoundryAcceptanceTest { +class UpdateInstanceWithTargetAcceptanceTests extends CloudFoundryAcceptanceTests { private static final String APP_NAME = "app-update-target"; @@ -59,25 +59,24 @@ class UpdateInstanceWithTargetAcceptanceTest extends CloudFoundryAcceptanceTest } @Test - @AppBrokerTestProperties({ - "spring.cloud.appbroker.services[0].service-name=" + APP_SERVICE_NAME, - "spring.cloud.appbroker.services[0].plan-name=" + PLAN_NAME, + @AppBrokerTestProperties({ "spring.cloud.appbroker.services[0].service-name=" + APP_SERVICE_NAME, + "spring.cloud.appbroker.services[0].plan-name=" + PLAN_NAME, - "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME, - "spring.cloud.appbroker.services[0].apps[0].path=" + BACKING_APP_PATH, - "spring.cloud.appbroker.services[0].apps[0].environment.parameter1=config1", + "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME, + "spring.cloud.appbroker.services[0].apps[0].path=" + BACKING_APP_PATH, + "spring.cloud.appbroker.services[0].apps[0].environment.parameter1=config1", - "spring.cloud.appbroker.services[0].target.name=SpacePerServiceInstance" - }) + "spring.cloud.appbroker.services[0].target.name=SpacePerServiceInstance" }) void deployAppsInTargetSpaceOnUpdateService() { // when a service instance is created createServiceInstance(SI_NAME); - // then a backing application is deployed in a space named as the service instance id + // then a backing application is deployed in a space named as the service instance + // id String spaceName = getServiceInstanceGuid(SI_NAME); Optional backingApplication = getApplicationSummary(APP_NAME, spaceName); - assertThat(backingApplication).hasValueSatisfying(app -> { + assertThat(backingApplication).hasValueSatisfying((app) -> { assertThat(app.getRunningInstances()).isEqualTo(1); // and has its route with the service instance id appended to it @@ -86,15 +85,15 @@ class UpdateInstanceWithTargetAcceptanceTest extends CloudFoundryAcceptanceTest }); String path = backingApplication.get().getUrls().get(0); - healthListener.start(path); + this.healthListener.start(path); // when the service instance is updated updateServiceInstance(SI_NAME, Collections.singletonMap("parameter2", "config2")); // then the backing application was updated with zero downtime - healthListener.stop(); - assertThat(healthListener.getFailures()).isEqualTo(0); - assertThat(healthListener.getSuccesses()).isGreaterThan(0); + this.healthListener.stop(); + assertThat(this.healthListener.getFailures()).isEqualTo(0); + assertThat(this.healthListener.getSuccesses()).isGreaterThan(0); // then the service instance has the initial parameters DocumentContext json = getSpringAppJson(APP_NAME, spaceName); diff --git a/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/UpgradeInstanceAcceptanceTest.java b/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/UpgradeInstanceAcceptanceTests.java similarity index 67% rename from spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/UpgradeInstanceAcceptanceTest.java rename to spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/UpgradeInstanceAcceptanceTests.java index 31d4e2a..4b573c2 100644 --- a/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/UpgradeInstanceAcceptanceTest.java +++ b/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/UpgradeInstanceAcceptanceTests.java @@ -36,7 +36,7 @@ import org.springframework.beans.factory.annotation.Autowired; import static org.assertj.core.api.Assertions.assertThat; @TestMethodOrder(MethodOrderer.OrderAnnotation.class) -class UpgradeInstanceAcceptanceTest extends CloudFoundryAcceptanceTest { +class UpgradeInstanceAcceptanceTests extends CloudFoundryAcceptanceTests { private static final String APP_NAME = "app-upgrade"; @@ -73,24 +73,21 @@ class UpgradeInstanceAcceptanceTest extends CloudFoundryAcceptanceTest { @Test @Tag("first") @Order(FIRST_TEST) - @AppBrokerTestProperties({ - "spring.cloud.appbroker.services[0].service-name=" + APP_SERVICE_NAME, - "spring.cloud.appbroker.services[0].plan-name=" + PLAN_NAME, - "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME, - "spring.cloud.appbroker.services[0].apps[0].path=" + BACKING_APP_PATH, - "spring.cloud.appbroker.services[0].apps[0].environment.parameter1=old-config1", - "spring.cloud.appbroker.services[0].apps[0].environment.parameter2=old-config2", - "spring.cloud.appbroker.services[0].apps[0].parameters-transformers[0].name=PropertyMapping", - "spring.cloud.appbroker.services[0].apps[0].parameters-transformers[0].args.include=upgrade" - }) + @AppBrokerTestProperties({ "spring.cloud.appbroker.services[0].service-name=" + APP_SERVICE_NAME, + "spring.cloud.appbroker.services[0].plan-name=" + PLAN_NAME, + "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME, + "spring.cloud.appbroker.services[0].apps[0].path=" + BACKING_APP_PATH, + "spring.cloud.appbroker.services[0].apps[0].environment.parameter1=old-config1", + "spring.cloud.appbroker.services[0].apps[0].environment.parameter2=old-config2", + "spring.cloud.appbroker.services[0].apps[0].parameters-transformers[0].name=PropertyMapping", + "spring.cloud.appbroker.services[0].apps[0].parameters-transformers[0].args.include=upgrade" }) void createsServiceInstance() { // when a service instance is created createServiceInstance(SI_NAME); // then a backing application is deployed Optional backingApplication = getApplicationSummary(APP_NAME); - assertThat(backingApplication).hasValueSatisfying(app -> - assertThat(app.getRunningInstances()).isEqualTo(1)); + assertThat(backingApplication).hasValueSatisfying((app) -> assertThat(app.getRunningInstances()).isEqualTo(1)); // and the environment variables are applied correctly DocumentContext json = getSpringAppJson(APP_NAME); @@ -98,31 +95,29 @@ class UpgradeInstanceAcceptanceTest extends CloudFoundryAcceptanceTest { assertThat(json.read("$.parameter2").toString()).isEqualTo("old-config2"); String path = backingApplication.get().getUrls().get(0); - healthListener.start(path); + this.healthListener.start(path); } @Test @Order(SECOND_TEST) @Tag("last") - @AppBrokerTestProperties({ - "spring.cloud.appbroker.services[0].service-name=" + APP_SERVICE_NAME, - "spring.cloud.appbroker.services[0].plan-name=" + PLAN_NAME, - "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME, - "spring.cloud.appbroker.services[0].apps[0].path=" + BACKING_APP_PATH, - "spring.cloud.appbroker.services[0].apps[0].environment.parameter1=new-config1", - "spring.cloud.appbroker.services[0].apps[0].environment.parameter3=new-config3", - "spring.cloud.appbroker.services[0].apps[0].parameters-transformers[0].name=PropertyMapping", - "spring.cloud.appbroker.services[0].apps[0].parameters-transformers[0].args.include=upgrade", - "spring.cloud.appbroker.deployer.cloudfoundry.properties.stack=cflinuxfs4" - }) + @AppBrokerTestProperties({ "spring.cloud.appbroker.services[0].service-name=" + APP_SERVICE_NAME, + "spring.cloud.appbroker.services[0].plan-name=" + PLAN_NAME, + "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME, + "spring.cloud.appbroker.services[0].apps[0].path=" + BACKING_APP_PATH, + "spring.cloud.appbroker.services[0].apps[0].environment.parameter1=new-config1", + "spring.cloud.appbroker.services[0].apps[0].environment.parameter3=new-config3", + "spring.cloud.appbroker.services[0].apps[0].parameters-transformers[0].name=PropertyMapping", + "spring.cloud.appbroker.services[0].apps[0].parameters-transformers[0].args.include=upgrade", + "spring.cloud.appbroker.deployer.cloudfoundry.properties.stack=cflinuxfs4" }) void upgradesTheServiceInstanceWithNewBackingServiceAndEnvironmentVariables() { // when the service instance is updated with a new service updateServiceInstance(SI_NAME, Collections.singletonMap("upgrade", true)); // then a backing application is re-deployed Optional updatedBackingApplication = getApplicationSummary(APP_NAME); - assertThat(updatedBackingApplication).hasValueSatisfying(app -> - assertThat(app.getRunningInstances()).isEqualTo(1)); + assertThat(updatedBackingApplication) + .hasValueSatisfying((app) -> assertThat(app.getRunningInstances()).isEqualTo(1)); // the backing application is updated with the new parameters DocumentContext json = getSpringAppJson(APP_NAME); @@ -132,14 +127,12 @@ class UpgradeInstanceAcceptanceTest extends CloudFoundryAcceptanceTest { // and stack is updated when specified Optional application1Detail = getApplicationDetail(APP_NAME); - assertThat(application1Detail).hasValueSatisfying(app -> { - assertThat(app.getStack()).isEqualTo("cflinuxfs4"); - }); + assertThat(application1Detail).hasValueSatisfying((app) -> assertThat(app.getStack()).isEqualTo("cflinuxfs4")); // then the backing application was updated with zero downtime - healthListener.stop(); - assertThat(healthListener.getFailures()).isEqualTo(0); - assertThat(healthListener.getSuccesses()).isGreaterThan(0); + this.healthListener.stop(); + assertThat(this.healthListener.getFailures()).isEqualTo(0); + assertThat(this.healthListener.getSuccesses()).isGreaterThan(0); // when the service instance is deleted deleteServiceInstance(SI_NAME); @@ -167,4 +160,5 @@ class UpgradeInstanceAcceptanceTest extends CloudFoundryAcceptanceTest { super.tearDown(testInfo); } } + } diff --git a/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/fixtures/cf/CloudFoundryClientConfiguration.java b/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/fixtures/cf/CloudFoundryClientConfiguration.java index 998e34f..4b53134 100644 --- a/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/fixtures/cf/CloudFoundryClientConfiguration.java +++ b/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/fixtures/cf/CloudFoundryClientConfiguration.java @@ -45,18 +45,17 @@ import org.springframework.context.annotation.Configuration; public class CloudFoundryClientConfiguration { /** - * The broker client secret - * Please note that acceptance tests setup would not recreate the client if client id or authorities doesn't change. - * Manual environment clean up is needed on existing test environments if secret changes are necessary. + * The broker client secret Please note that acceptance tests setup would not recreate + * the client if client id or authorities doesn't change. Manual environment clean up + * is needed on existing test environments if secret changes are necessary. */ public static final String APP_BROKER_CLIENT_SECRET = "app-broker-client-secret"; /** * The broker client authorities */ - public static final String[] APP_BROKER_CLIENT_AUTHORITIES = { - "cloud_controller.read", "cloud_controller.write", "clients.write" - }; + public static final String[] APP_BROKER_CLIENT_AUTHORITIES = { "cloud_controller.read", "cloud_controller.write", + "clients.write" }; /** * The user client id @@ -64,24 +63,20 @@ public class CloudFoundryClientConfiguration { public static final String USER_CLIENT_ID = "app-broker-user-client"; /** - * The user client secret - * Please note that acceptance tests setup would not recreate the client if client id or authorities doesn't change. - * Manual environment clean up is needed on existing test environments if secret changes are necessary. + * The user client secret Please note that acceptance tests setup would not recreate + * the client if client id or authorities doesn't change. Manual environment clean up + * is needed on existing test environments if secret changes are necessary. */ public static final String USER_CLIENT_SECRET = "app-broker-user-client-secret"; /** * The user client authorities */ - public static final String[] USER_CLIENT_AUTHORITIES = { - "cloud_controller.read", "cloud_controller.write" - }; + public static final String[] USER_CLIENT_AUTHORITIES = { "cloud_controller.read", "cloud_controller.write" }; @Bean protected CloudFoundryOperations cloudFoundryOperations(CloudFoundryProperties properties, - CloudFoundryClient client, - DopplerClient dopplerClient, - @Qualifier("userCredentials") UaaClient uaaClient) { + CloudFoundryClient client, DopplerClient dopplerClient, @Qualifier("userCredentials") UaaClient uaaClient) { return DefaultCloudFoundryOperations.builder() .cloudFoundryClient(client) .dopplerClient(dopplerClient) @@ -93,7 +88,7 @@ public class CloudFoundryClientConfiguration { @Bean protected CloudFoundryClient cloudFoundryClient(ConnectionContext connectionContext, - @Qualifier("userCredentials") TokenProvider tokenProvider) { + @Qualifier("userCredentials") TokenProvider tokenProvider) { return ReactorCloudFoundryClient.builder() .connectionContext(connectionContext) .tokenProvider(tokenProvider) @@ -112,16 +107,13 @@ public class CloudFoundryClientConfiguration { @Bean protected DopplerClient dopplerClient(ConnectionContext connectionContext, - @Qualifier("userCredentials") TokenProvider tokenProvider) { - return ReactorDopplerClient.builder() - .connectionContext(connectionContext) - .tokenProvider(tokenProvider) - .build(); + @Qualifier("userCredentials") TokenProvider tokenProvider) { + return ReactorDopplerClient.builder().connectionContext(connectionContext).tokenProvider(tokenProvider).build(); } @Bean protected LogCacheClient logCacheClient(ConnectionContext connectionContext, - @Qualifier("userCredentials") TokenProvider tokenProvider) { + @Qualifier("userCredentials") TokenProvider tokenProvider) { return ReactorLogCacheClient.builder() .connectionContext(connectionContext) .tokenProvider(tokenProvider) @@ -131,29 +123,21 @@ public class CloudFoundryClientConfiguration { @Bean @Qualifier("userCredentials") protected UaaClient userCredentialsUaaClient(ConnectionContext connectionContext, - @Qualifier("userCredentials") TokenProvider tokenProvider) { - return ReactorUaaClient.builder() - .connectionContext(connectionContext) - .tokenProvider(tokenProvider) - .build(); + @Qualifier("userCredentials") TokenProvider tokenProvider) { + return ReactorUaaClient.builder().connectionContext(connectionContext).tokenProvider(tokenProvider).build(); } @Bean @Qualifier("clientCredentials") protected UaaClient clientCredentialsUaaClient(ConnectionContext connectionContext, - @Qualifier("clientCredentials") TokenProvider tokenProvider) { - return ReactorUaaClient.builder() - .connectionContext(connectionContext) - .tokenProvider(tokenProvider) - .build(); + @Qualifier("clientCredentials") TokenProvider tokenProvider) { + return ReactorUaaClient.builder().connectionContext(connectionContext).tokenProvider(tokenProvider).build(); } @Bean @Qualifier("userCredentials") - @ConditionalOnProperty({ - CloudFoundryProperties.PROPERTY_PREFIX + ".username", - CloudFoundryProperties.PROPERTY_PREFIX + ".password" - }) + @ConditionalOnProperty({ CloudFoundryProperties.PROPERTY_PREFIX + ".username", + CloudFoundryProperties.PROPERTY_PREFIX + ".password" }) protected PasswordGrantTokenProvider passwordTokenProvider(CloudFoundryProperties properties) { return PasswordGrantTokenProvider.builder() .password(properties.getPassword()) @@ -163,10 +147,8 @@ public class CloudFoundryClientConfiguration { @Bean @Qualifier("clientCredentials") - @ConditionalOnProperty({ - CloudFoundryProperties.PROPERTY_PREFIX + ".client-id", - CloudFoundryProperties.PROPERTY_PREFIX + ".client-secret" - }) + @ConditionalOnProperty({ CloudFoundryProperties.PROPERTY_PREFIX + ".client-id", + CloudFoundryProperties.PROPERTY_PREFIX + ".client-secret" }) protected ClientCredentialsGrantTokenProvider clientTokenProvider(CloudFoundryProperties properties) { return ClientCredentialsGrantTokenProvider.builder() .clientId(properties.getClientId()) diff --git a/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/fixtures/cf/CloudFoundryProperties.java b/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/fixtures/cf/CloudFoundryProperties.java index 095aa0d..8f2658a 100644 --- a/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/fixtures/cf/CloudFoundryProperties.java +++ b/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/fixtures/cf/CloudFoundryProperties.java @@ -16,23 +16,20 @@ package org.springframework.cloud.appbroker.acceptance.fixtures.cf; -import jakarta.validation.constraints.Min; -import jakarta.validation.constraints.NotBlank; - import java.net.URI; +import jakarta.validation.constraints.Min; +import jakarta.validation.constraints.NotBlank; import org.cloudfoundry.reactor.ProxyConfiguration; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.validation.annotation.Validated; -import static org.springframework.cloud.appbroker.acceptance.fixtures.cf.CloudFoundryProperties.PROPERTY_PREFIX; - -@ConfigurationProperties(PROPERTY_PREFIX) +@ConfigurationProperties(CloudFoundryProperties.PROPERTY_PREFIX) @Validated public class CloudFoundryProperties { - protected static final String PROPERTY_PREFIX = "spring.cloud.appbroker.acceptancetest.cloudfoundry"; + protected static final String PROPERTY_PREFIX = "spring.cloud.appbroker.acceptancetest" + ".cloudfoundry"; @NotBlank private String apiHost; @@ -65,7 +62,7 @@ public class CloudFoundryProperties { private boolean skipSslValidation; public String getApiHost() { - return apiHost; + return this.apiHost; } public void setApiHost(String apiHost) { @@ -73,7 +70,7 @@ public class CloudFoundryProperties { } public Integer getApiPort() { - return apiPort; + return this.apiPort; } public void setApiPort(int apiPort) { @@ -81,7 +78,7 @@ public class CloudFoundryProperties { } public String getDefaultOrg() { - return defaultOrg; + return this.defaultOrg; } public void setDefaultOrg(String defaultOrg) { @@ -89,7 +86,7 @@ public class CloudFoundryProperties { } public String getDefaultSpace() { - return defaultSpace; + return this.defaultSpace; } public void setDefaultSpace(String defaultSpace) { @@ -97,7 +94,7 @@ public class CloudFoundryProperties { } public String getUsername() { - return username; + return this.username; } public void setUsername(String username) { @@ -105,7 +102,7 @@ public class CloudFoundryProperties { } public String getPassword() { - return password; + return this.password; } public void setPassword(String password) { @@ -113,7 +110,7 @@ public class CloudFoundryProperties { } public String getClientId() { - return clientId; + return this.clientId; } public void setClientId(String clientId) { @@ -121,7 +118,7 @@ public class CloudFoundryProperties { } public String getClientSecret() { - return clientSecret; + return this.clientSecret; } public void setClientSecret(String clientSecret) { @@ -129,7 +126,7 @@ public class CloudFoundryProperties { } public String getIdentityZoneSubdomain() { - return identityZoneSubdomain; + return this.identityZoneSubdomain; } public void setIdentityZoneSubdomain(String identityZoneSubdomain) { @@ -141,7 +138,7 @@ public class CloudFoundryProperties { } public boolean isSecure() { - return secure; + return this.secure; } public void setSecure(boolean secure) { @@ -149,7 +146,7 @@ public class CloudFoundryProperties { } public boolean isSkipSslValidation() { - return skipSslValidation; + return this.skipSslValidation; } public void setSkipSslValidation(boolean skipSslValidation) { @@ -158,7 +155,7 @@ public class CloudFoundryProperties { private static String parseApiHost(String api) { final URI uri = URI.create(api); - return uri.getHost() == null ? api : uri.getHost(); + return (uri.getHost() == null) ? api : uri.getHost(); } } diff --git a/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/fixtures/cf/CloudFoundryService.java b/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/fixtures/cf/CloudFoundryService.java index b169d20..c44f8bb 100644 --- a/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/fixtures/cf/CloudFoundryService.java +++ b/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/fixtures/cf/CloudFoundryService.java @@ -88,179 +88,173 @@ public class CloudFoundryService { private final CloudFoundryProperties cloudFoundryProperties; - public CloudFoundryService( - CloudFoundryClient cloudFoundryClient, - CloudFoundryOperations cloudFoundryOperations, - CloudFoundryProperties cloudFoundryProperties) { + public CloudFoundryService(CloudFoundryClient cloudFoundryClient, CloudFoundryOperations cloudFoundryOperations, + CloudFoundryProperties cloudFoundryProperties) { this.cloudFoundryClient = cloudFoundryClient; this.cloudFoundryOperations = cloudFoundryOperations; this.cloudFoundryProperties = cloudFoundryProperties; } public Mono enableServiceBrokerAccess(String serviceName) { - return cloudFoundryOperations.serviceAdmin().enableServiceAccess(EnableServiceAccessRequest.builder() - .serviceName(serviceName) - .build()) - .doOnSuccess(v -> LOG.info("Enabled access to service. serviceName={}", serviceName)) - .doOnError(e -> LOG.error(String.format("Error enabling access to service. serviceName=%s, error=%s", - serviceName, e.getMessage()), e)); + return this.cloudFoundryOperations.serviceAdmin() + .enableServiceAccess(EnableServiceAccessRequest.builder().serviceName(serviceName).build()) + .doOnSuccess((v) -> LOG.info("Enabled access to service. serviceName={}", serviceName)) + .doOnError((e) -> LOG.error(String.format("Error enabling access to service. serviceName=%s, error=%s", + serviceName, e.getMessage()), e)); } public Mono createServiceBroker(String brokerName, String testBrokerAppName) { - return getApplicationRoute(testBrokerAppName) - .flatMap(url -> cloudFoundryOperations.serviceAdmin().create(CreateServiceBrokerRequest.builder() + return getApplicationRoute(testBrokerAppName).flatMap((url) -> this.cloudFoundryOperations.serviceAdmin() + .create(CreateServiceBrokerRequest.builder() .name(brokerName) .username("user") .password("password") .url(url) .build()) - .doOnSuccess(v -> LOG.info("Success creating service broker. brokerName={}", brokerName)) - .doOnError(e -> LOG.error(String.format("Error creating service broker. brokerName=%s, error=%s", - brokerName, e.getMessage()), e))); + .doOnSuccess((v) -> LOG.info("Success creating service broker. brokerName={}", brokerName)) + .doOnError((e) -> LOG.error( + String.format("Error creating service broker. brokerName=%s, error=%s", brokerName, e.getMessage()), + e))); } public Mono updateServiceBroker(String brokerName, String testBrokerAppName) { - return getApplicationRoute(testBrokerAppName) - .flatMap(url -> cloudFoundryOperations.serviceAdmin().update(UpdateServiceBrokerRequest.builder() + return getApplicationRoute(testBrokerAppName).flatMap((url) -> this.cloudFoundryOperations.serviceAdmin() + .update(UpdateServiceBrokerRequest.builder() .name(brokerName) .username("user") .password("password") .url(url) .build()) - .doOnSuccess(v -> LOG.info("Success updating service broker. brokerName={}", brokerName)) - .doOnError(e -> LOG.error(String.format("Error updating service broker. brokerName=%s, error=%s", - brokerName, e.getMessage()), e))); + .doOnSuccess((v) -> LOG.info("Success updating service broker. brokerName={}", brokerName)) + .doOnError((e) -> LOG.error( + String.format("Error updating service broker. brokerName=%s, error=%s", brokerName, e.getMessage()), + e))); } public Mono getApplicationRoute(String appName) { - return cloudFoundryOperations.applications().get(GetApplicationRequest.builder() - .name(appName) - .build()) - .doOnSuccess(item -> LOG.info("Success getting route for app. appName={}", appName)) - .doOnError(e -> LOG.error(String.format("Error getting route for app. appName=%s, error=%s", appName, - e.getMessage()), e)) + return this.cloudFoundryOperations.applications() + .get(GetApplicationRequest.builder().name(appName).build()) + .doOnSuccess((item) -> LOG.info("Success getting route for app. appName={}", appName)) + .doOnError((e) -> LOG + .error(String.format("Error getting route for app. appName=%s, error=%s", appName, e.getMessage()), e)) .map(ApplicationDetail::getUrls) .flatMapMany(Flux::fromIterable) .next() - .map(url -> "https://" + url); + .map((url) -> "https://" + url); } public Mono pushBrokerApp(String appName, Path appPath, String brokerClientId, - List appBrokerProperties) { - return cloudFoundryOperations.applications().pushManifest(PushApplicationManifestRequest.builder() - .manifest(ApplicationManifest.builder() - .environmentVariables(appBrokerDeployerEnvironmentVariables(brokerClientId)) - .putAllEnvironmentVariables(propertiesToEnvironment(appBrokerProperties)) - .name(appName) - .path(appPath) - .memory(1024) + List appBrokerProperties) { + return this.cloudFoundryOperations.applications() + .pushManifest(PushApplicationManifestRequest.builder() + .manifest(ApplicationManifest.builder() + .environmentVariables(appBrokerDeployerEnvironmentVariables(brokerClientId)) + .putAllEnvironmentVariables(propertiesToEnvironment(appBrokerProperties)) + .name(appName) + .path(appPath) + .memory(1024) + .build()) .build()) - .build()) - .doOnSuccess(v -> LOG.info("Success pushing broker app. appName={}", appName)) - .doOnError(e -> LOG.error(String.format("Error pushing broker app. appName=%s, error=%s", appName, - e.getMessage()), e)); + .doOnSuccess((v) -> LOG.info("Success pushing broker app. appName={}", appName)) + .doOnError((e) -> LOG + .error(String.format("Error pushing broker app. appName=%s, error=%s", appName, e.getMessage()), e)); } public Mono updateBrokerApp(String appName, String brokerClientId, List appBrokerProperties) { - return cloudFoundryOperations.applications().get(GetApplicationRequest.builder().name(appName).build()) + return this.cloudFoundryOperations.applications() + .get(GetApplicationRequest.builder().name(appName).build()) .map(ApplicationDetail::getId) - .flatMap(applicationId -> cloudFoundryClient.applicationsV2().update(UpdateApplicationRequest - .builder() - .applicationId(applicationId) - .putAllEnvironmentJsons(appBrokerDeployerEnvironmentVariables(brokerClientId)) - .putAllEnvironmentJsons(propertiesToEnvironment(appBrokerProperties)) - .name(appName) - .memory(1024) - .build()) + .flatMap((applicationId) -> this.cloudFoundryClient.applicationsV2() + .update(UpdateApplicationRequest.builder() + .applicationId(applicationId) + .putAllEnvironmentJsons(appBrokerDeployerEnvironmentVariables(brokerClientId)) + .putAllEnvironmentJsons(propertiesToEnvironment(appBrokerProperties)) + .name(appName) + .memory(1024) + .build()) .thenReturn(applicationId)) - .then(cloudFoundryOperations.applications().restart(RestartApplicationRequest.builder() - .name(appName) - .build())) - .doOnSuccess(item -> LOG.info("Updated broker app " + appName)) - .doOnError(error -> LOG.error("Error updating broker app " + appName + ": " + error)) + .then(this.cloudFoundryOperations.applications() + .restart(RestartApplicationRequest.builder().name(appName).build())) + .doOnSuccess((item) -> LOG.info("Updated broker app " + appName)) + .doOnError((error) -> LOG.error("Error updating broker app " + appName + ": " + error)) .then(); } public Mono deleteApp(String appName) { - return cloudFoundryOperations.applications().list() - .filter(app -> appName.equals(app.getName())) + return this.cloudFoundryOperations.applications() + .list() + .filter((app) -> appName.equals(app.getName())) .singleOrEmpty() - .flatMap(app -> cloudFoundryOperations.applications().delete(DeleteApplicationRequest.builder() - .name(appName) - .deleteRoutes(true) - .build())) - .doOnSuccess(item -> LOG.info("Success deleting app. appName={}", appName)) - .doOnError(e -> LOG.warn(String.format("Error deleting app. appName=%s, error=%s", appName, - e.getMessage()), e)) - .onErrorResume(e -> Mono.empty()); + .flatMap((app) -> this.cloudFoundryOperations.applications() + .delete(DeleteApplicationRequest.builder().name(appName).deleteRoutes(true).build())) + .doOnSuccess((item) -> LOG.info("Success deleting app. appName={}", appName)) + .doOnError((e) -> LOG + .warn(String.format("Error deleting app. appName=%s, error=%s", appName, e.getMessage()), e)) + .onErrorResume((e) -> Mono.empty()); } public Mono deleteServiceBroker(String brokerName) { - return cloudFoundryOperations.serviceAdmin().list() - .filter(serviceBroker -> brokerName.equals(serviceBroker.getName())) + return this.cloudFoundryOperations.serviceAdmin() + .list() + .filter((serviceBroker) -> brokerName.equals(serviceBroker.getName())) .singleOrEmpty() - .flatMap(serviceBroker -> cloudFoundryOperations.serviceAdmin() - .delete(DeleteServiceBrokerRequest.builder().name(brokerName).build()) - ) - .doOnSuccess(item -> LOG.info("Success deleting service broker. brokerName={}", brokerName)) - .doOnError(e -> LOG.warn(String.format("Error deleting service broker. brokerName=%s, error=%s ", - brokerName, e.getMessage()), e)) - .onErrorResume(e -> Mono.empty()); + .flatMap((serviceBroker) -> this.cloudFoundryOperations.serviceAdmin() + .delete(DeleteServiceBrokerRequest.builder().name(brokerName).build())) + .doOnSuccess((item) -> LOG.info("Success deleting service broker. brokerName={}", brokerName)) + .doOnError((e) -> LOG.warn(String.format("Error deleting service broker. brokerName=%s, error=%s ", + brokerName, e.getMessage()), e)) + .onErrorResume((e) -> Mono.empty()); } - public Mono createBackingServiceInstance(String planName, - String serviceName, - String serviceInstanceName, - Map parameters) { - return cloudFoundryOperations.services().createInstance(CreateServiceInstanceRequest.builder() - .planName(planName) - .serviceName(serviceName) - .serviceInstanceName(serviceInstanceName) - .parameters(parameters) - .build()) - .doOnSuccess(item -> LOG.info("Success creating service instance. serviceInstanceName={}", - serviceInstanceName)) - .doOnError(e -> LOG.error(String.format("Error creating service instance. serviceInstanceName=%s, " + - "error=%s", serviceInstanceName, e.getMessage()), e)); + public Mono createBackingServiceInstance(String planName, String serviceName, String serviceInstanceName, + Map parameters) { + return this.cloudFoundryOperations.services() + .createInstance(CreateServiceInstanceRequest.builder() + .planName(planName) + .serviceName(serviceName) + .serviceInstanceName(serviceInstanceName) + .parameters(parameters) + .build()) + .doOnSuccess((item) -> LOG.info("Success creating service instance. serviceInstanceName={}", + serviceInstanceName)) + .doOnError((e) -> LOG + .error(String.format("Error creating service instance. serviceInstanceName=%s, " + "error=%s", + serviceInstanceName, e.getMessage()), e)); } public Flux listServiceInstances() { - return cloudFoundryOperations.services().listInstances(); + return this.cloudFoundryOperations.services().listInstances(); } public Mono getServiceInstance(String serviceInstanceName) { - return getServiceInstance(cloudFoundryOperations, serviceInstanceName); + return getServiceInstance(this.cloudFoundryOperations, serviceInstanceName); } public Mono getServiceInstance(String serviceInstanceName, String space) { return getServiceInstance(createOperationsForSpace(space), serviceInstanceName); } - private Mono getServiceInstance(CloudFoundryOperations operations, - String serviceInstanceName) { - return operations.services().getInstance(GetServiceInstanceRequest.builder() - .name(serviceInstanceName) - .build()) - .doOnSuccess(item -> LOG.info("Success getting service instance. serviceInstanceName={}", - serviceInstanceName)) - .doOnError(e -> LOG.error(String.format("Error getting service instance. serviceInstanceName=%s, " + - "error=%s", serviceInstanceName, e.getMessage()), e)); + private Mono getServiceInstance(CloudFoundryOperations operations, String serviceInstanceName) { + return operations.services() + .getInstance(GetServiceInstanceRequest.builder().name(serviceInstanceName).build()) + .doOnSuccess( + (item) -> LOG.info("Success getting service instance. serviceInstanceName={}", serviceInstanceName)) + .doOnError((e) -> LOG + .error(String.format("Error getting service instance. serviceInstanceName=%s, " + "error=%s", + serviceInstanceName, e.getMessage()), e)); } public Mono> getApplications() { - return listApplications(cloudFoundryOperations) - .collectList(); + return listApplications(this.cloudFoundryOperations).collectList(); } public Mono getApplication(String appName) { - return cloudFoundryOperations.applications().get(GetApplicationRequest.builder() - .name(appName) - .build()); + return this.cloudFoundryOperations.applications().get(GetApplicationRequest.builder().name(appName).build()); } public Mono getApplication(String appName, String space) { return listApplications(createOperationsForSpace(space)) - .filter(applicationSummary -> applicationSummary.getName().equals(appName)) + .filter((applicationSummary) -> applicationSummary.getName().equals(appName)) .single(); } @@ -268,11 +262,11 @@ public class CloudFoundryService { return operations.applications() .list() .doOnComplete(() -> LOG.info("Listed applications")) - .doOnError(e -> LOG.error(String.format("Error listing applications. error=%s", e.getMessage()), e)); + .doOnError((e) -> LOG.error(String.format("Error listing applications. error=%s", e.getMessage()), e)); } public Mono getApplicationEnvironment(String appName) { - return getApplicationEnvironment(cloudFoundryOperations, appName); + return getApplicationEnvironment(this.cloudFoundryOperations, appName); } public Mono getApplicationEnvironment(String appName, String space) { @@ -281,32 +275,31 @@ public class CloudFoundryService { private Mono getApplicationEnvironment(CloudFoundryOperations operations, String appName) { return operations.applications() - .getEnvironments(GetApplicationEnvironmentsRequest.builder() - .name(appName) - .build()) - .doOnSuccess(item -> LOG.info("Success getting environment for application. appName={}", appName)) - .doOnError(e -> LOG.error(String.format("Error getting environment for application. appName=%s, " + - "error=%s", appName, e.getMessage()), e)); + .getEnvironments(GetApplicationEnvironmentsRequest.builder().name(appName).build()) + .doOnSuccess((item) -> LOG.info("Success getting environment for application. appName={}", appName)) + .doOnError((e) -> LOG + .error(String.format("Error getting environment for application. appName=%s, " + "error=%s", appName, + e.getMessage()), e)); } public Mono stopApplication(String appName) { - return cloudFoundryOperations.applications().stop(StopApplicationRequest.builder() - .name(appName) - .build()); + return this.cloudFoundryOperations.applications().stop(StopApplicationRequest.builder().name(appName).build()); } public Mono getOrCreateDefaultSpace() { - return getOrCreateSpace(cloudFoundryProperties.getDefaultOrg(), cloudFoundryProperties.getDefaultSpace()); + return getOrCreateSpace(this.cloudFoundryProperties.getDefaultOrg(), + this.cloudFoundryProperties.getDefaultSpace()); } public Mono getOrCreateDefaultOrg() { - return getOrCreateOrganization(cloudFoundryProperties.getDefaultOrg()); + return getOrCreateOrganization(this.cloudFoundryProperties.getDefaultOrg()); } public Mono> getSpaces() { - return cloudFoundryOperations.spaces().list() + return this.cloudFoundryOperations.spaces() + .list() .doOnComplete(() -> LOG.info("Success listing spaces")) - .doOnError(e -> LOG.error(String.format("Error listing spaces. error=%s", e.getMessage()), e)) + .doOnError((e) -> LOG.error(String.format("Error listing spaces. error=%s", e.getMessage()), e)) .map(SpaceSummary::getName) .collectList(); } @@ -318,132 +311,98 @@ public class CloudFoundryService { .build() .spaces(); - return getSpace(spaceOperations, spaceName).switchIfEmpty(spaceOperations.create(CreateSpaceRequest.builder() - .name(spaceName) - .organization(orgName) - .build()) - .then(getSpace(spaceOperations, spaceName))); + return getSpace(spaceOperations, spaceName).switchIfEmpty( + spaceOperations.create(CreateSpaceRequest.builder().name(spaceName).organization(orgName).build()) + .then(getSpace(spaceOperations, spaceName))); } public Mono getOrCreateOrganization(String orgName) { - Organizations organizationOperations = cloudFoundryOperations.organizations(); + Organizations organizationOperations = this.cloudFoundryOperations.organizations(); - return getOrg(organizationOperations, orgName) - .switchIfEmpty(organizationOperations.create(CreateOrganizationRequest.builder() - .organizationName(orgName) - .build()) - .then(getOrg(organizationOperations, orgName))); + return getOrg(organizationOperations, orgName).switchIfEmpty( + organizationOperations.create(CreateOrganizationRequest.builder().organizationName(orgName).build()) + .then(getOrg(organizationOperations, orgName))); } private Mono getOrg(Organizations orgOperations, String orgName) { - return orgOperations.list() - .filter(r -> r - .getName() - .equals(orgName)) - .next(); + return orgOperations.list().filter((r) -> r.getName().equals(orgName)).next(); } private Mono getSpace(Spaces spaceOperations, String spaceName) { - return spaceOperations.list() - .filter(r -> r - .getName() - .equals(spaceName)) - .next(); + return spaceOperations.list().filter((r) -> r.getName().equals(spaceName)).next(); } public Mono associateAppBrokerClientWithOrgAndSpace(String brokerClientId, String orgId, String spaceId) { return Mono.justOrEmpty(brokerClientId) - .flatMap(userId -> associateOrgUser(orgId, userId) - .then(associateOrgManager(orgId, userId)) + .flatMap((userId) -> associateOrgUser(orgId, userId).then(associateOrgManager(orgId, userId)) .then(associateSpaceDeveloper(spaceId, userId))) .then(); } public Mono associateClientWithOrgAndSpace(String clientId, String orgId, String spaceId) { - return associateOrgUser(orgId, clientId) - .then(associateSpaceDeveloper(spaceId, clientId)) - .then(); + return associateOrgUser(orgId, clientId).then(associateSpaceDeveloper(spaceId, clientId)).then(); } public Mono removeAppBrokerClientFromOrgAndSpace(String brokerClientId, String orgId, String spaceId) { return Mono.justOrEmpty(brokerClientId) - .flatMap(userId -> removeSpaceDeveloper(spaceId, userId) - .then(removeOrgManager(orgId, userId)) + .flatMap((userId) -> removeSpaceDeveloper(spaceId, userId).then(removeOrgManager(orgId, userId)) .then(removeOrgUser(orgId, userId))); } public Mono createDomain(String domain) { - return cloudFoundryOperations - .domains() - .create(CreateDomainRequest - .builder() + return this.cloudFoundryOperations.domains() + .create(CreateDomainRequest.builder() .domain(domain) - .organization(cloudFoundryProperties.getDefaultOrg()) + .organization(this.cloudFoundryProperties.getDefaultOrg()) .build()) - .onErrorResume(e -> Mono.empty()); + .onErrorResume((e) -> Mono.empty()); } public Mono deleteDomain(String domain) { - return cloudFoundryOperations - .domains() + return this.cloudFoundryOperations.domains() .list() - .filter(d -> d.getName().equals(domain)) + .filter((d) -> d.getName().equals(domain)) .map(Domain::getId) - .flatMap(domainId -> cloudFoundryClient - .privateDomains() - .delete(DeletePrivateDomainRequest - .builder() - .privateDomainId(domainId) - .build())) + .flatMap((domainId) -> this.cloudFoundryClient.privateDomains() + .delete(DeletePrivateDomainRequest.builder().privateDomainId(domainId).build())) .then(); } private Mono associateOrgUser(String orgId, String userId) { - return cloudFoundryClient.organizations().associateUser(AssociateOrganizationUserRequest.builder() - .organizationId(orgId) - .userId(userId) - .build()); + return this.cloudFoundryClient.organizations() + .associateUser(AssociateOrganizationUserRequest.builder().organizationId(orgId).userId(userId).build()); } private Mono associateOrgManager(String orgId, String userId) { - return cloudFoundryClient.organizations().associateManager(AssociateOrganizationManagerRequest.builder() - .organizationId(orgId) - .managerId(userId) - .build()); + return this.cloudFoundryClient.organizations() + .associateManager( + AssociateOrganizationManagerRequest.builder().organizationId(orgId).managerId(userId).build()); } private Mono associateSpaceDeveloper(String spaceId, String userId) { - return cloudFoundryClient.spaces().associateDeveloper(AssociateSpaceDeveloperRequest.builder() - .spaceId(spaceId) - .developerId(userId) - .build()); + return this.cloudFoundryClient.spaces() + .associateDeveloper(AssociateSpaceDeveloperRequest.builder().spaceId(spaceId).developerId(userId).build()); } private Mono removeOrgUser(String orgId, String userId) { - return cloudFoundryClient.organizations().removeUser(RemoveOrganizationUserRequest.builder() - .organizationId(orgId) - .userId(userId) - .build()); + return this.cloudFoundryClient.organizations() + .removeUser(RemoveOrganizationUserRequest.builder().organizationId(orgId).userId(userId).build()); } private Mono removeOrgManager(String orgId, String userId) { - return cloudFoundryClient.organizations().removeManager(RemoveOrganizationManagerRequest.builder() - .organizationId(orgId) - .managerId(userId) - .build()); + return this.cloudFoundryClient.organizations() + .removeManager(RemoveOrganizationManagerRequest.builder().organizationId(orgId).managerId(userId).build()); } private Mono removeSpaceDeveloper(String spaceId, String userId) { - return cloudFoundryClient.spaces().removeDeveloper(RemoveSpaceDeveloperRequest.builder() - .spaceId(spaceId) - .developerId(userId) - .build()); + return this.cloudFoundryClient.spaces() + .removeDeveloper(RemoveSpaceDeveloperRequest.builder().spaceId(spaceId).developerId(userId).build()); } private CloudFoundryOperations createOperationsForSpace(String space) { - final String defaultOrg = cloudFoundryProperties.getDefaultOrg(); + final String defaultOrg = this.cloudFoundryProperties.getDefaultOrg(); return DefaultCloudFoundryOperations.builder() - .from((DefaultCloudFoundryOperations) cloudFoundryOperations) + .from((DefaultCloudFoundryOperations) this.cloudFoundryOperations) .organization(defaultOrg) .space(space) .build(); @@ -452,20 +411,18 @@ public class CloudFoundryService { private Map appBrokerDeployerEnvironmentVariables(String brokerClientId) { Map deployerVariables = new HashMap<>(); deployerVariables.put(JBP_CONFIG_OPEN_JDK_JRE_ENV_VAR_NAME, JBP_CONFIG_OPEN_JDK_JRE_17); - deployerVariables.put(DEPLOYER_PROPERTY_PREFIX + "api-host", - cloudFoundryProperties.getApiHost()); + deployerVariables.put(DEPLOYER_PROPERTY_PREFIX + "api-host", this.cloudFoundryProperties.getApiHost()); deployerVariables.put(DEPLOYER_PROPERTY_PREFIX + "api-port", - String.valueOf(cloudFoundryProperties.getApiPort())); - deployerVariables.put(DEPLOYER_PROPERTY_PREFIX + "default-org", - cloudFoundryProperties.getDefaultOrg()); + String.valueOf(this.cloudFoundryProperties.getApiPort())); + deployerVariables.put(DEPLOYER_PROPERTY_PREFIX + "default-org", this.cloudFoundryProperties.getDefaultOrg()); deployerVariables.put(DEPLOYER_PROPERTY_PREFIX + "default-space", - cloudFoundryProperties.getDefaultSpace()); + this.cloudFoundryProperties.getDefaultSpace()); deployerVariables.put(DEPLOYER_PROPERTY_PREFIX + "skip-ssl-validation", - String.valueOf(cloudFoundryProperties.isSkipSslValidation())); + String.valueOf(this.cloudFoundryProperties.isSkipSslValidation())); deployerVariables.put(DEPLOYER_PROPERTY_PREFIX + "properties.memory", "1024M"); deployerVariables.put(DEPLOYER_PROPERTY_PREFIX + "client-id", brokerClientId); deployerVariables.put(DEPLOYER_PROPERTY_PREFIX + "client-secret", - CloudFoundryClientConfiguration.APP_BROKER_CLIENT_SECRET); + CloudFoundryClientConfiguration.APP_BROKER_CLIENT_SECRET); return deployerVariables; } @@ -478,7 +435,7 @@ public class CloudFoundryService { } else { throw new IllegalArgumentException(String.format("App Broker property '%s' is incorrectly formatted", - Arrays.toString(propertyKeyValue))); + Arrays.toString(propertyKeyValue))); } } return environment; diff --git a/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/fixtures/cf/UserCloudFoundryService.java b/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/fixtures/cf/UserCloudFoundryService.java index 84dcd6f..bc4ba13 100644 --- a/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/fixtures/cf/UserCloudFoundryService.java +++ b/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/fixtures/cf/UserCloudFoundryService.java @@ -34,28 +34,27 @@ import reactor.core.publisher.Mono; import org.springframework.stereotype.Service; -import static org.springframework.cloud.appbroker.acceptance.fixtures.cf.CloudFoundryClientConfiguration.USER_CLIENT_ID; -import static org.springframework.cloud.appbroker.acceptance.fixtures.cf.CloudFoundryClientConfiguration.USER_CLIENT_SECRET; - @Service public final class UserCloudFoundryService { private static final Logger LOG = LoggerFactory.getLogger(UserCloudFoundryService.class); private final CloudFoundryOperations cloudFoundryOperations; + private final String targetOrg; + private final String targetSpace; - public UserCloudFoundryService(CloudFoundryOperations cloudFoundryOperations, CloudFoundryProperties cloudFoundryProperties) { - DefaultCloudFoundryOperations sourceCloudFoundryOperations = - (DefaultCloudFoundryOperations) cloudFoundryOperations; + public UserCloudFoundryService(CloudFoundryOperations cloudFoundryOperations, + CloudFoundryProperties cloudFoundryProperties) { + DefaultCloudFoundryOperations sourceCloudFoundryOperations = (DefaultCloudFoundryOperations) cloudFoundryOperations; this.targetOrg = cloudFoundryProperties.getDefaultOrg() + "-instances"; this.targetSpace = cloudFoundryProperties.getDefaultSpace(); ClientCredentialsGrantTokenProvider tokenProvider = ClientCredentialsGrantTokenProvider.builder() - .clientId(USER_CLIENT_ID) - .clientSecret(USER_CLIENT_SECRET) + .clientId(CloudFoundryClientConfiguration.USER_CLIENT_ID) + .clientSecret(CloudFoundryClientConfiguration.USER_CLIENT_SECRET) .build(); ReactorCloudFoundryClient cloudFoundryClient = ReactorCloudFoundryClient.builder() @@ -63,11 +62,10 @@ public final class UserCloudFoundryService { .tokenProvider(tokenProvider) .build(); - this.cloudFoundryOperations = DefaultCloudFoundryOperations - .builder() + this.cloudFoundryOperations = DefaultCloudFoundryOperations.builder() .from(sourceCloudFoundryOperations) - .space(targetSpace) - .organization(targetOrg) + .space(this.targetSpace) + .organization(this.targetOrg) .cloudFoundryClient(cloudFoundryClient) .build(); } @@ -82,49 +80,45 @@ public final class UserCloudFoundryService { public Mono deleteServiceInstance(String serviceInstanceName) { return getServiceInstance(serviceInstanceName) - .flatMap(si -> cloudFoundryOperations.services().deleteInstance(DeleteServiceInstanceRequest.builder() - .name(si.getName()) - .build()) - .doOnSuccess(v -> LOG.info("Success deleting service instance. serviceInstanceName={}", - serviceInstanceName)) - .doOnError(error -> logError("deleting service instance", serviceInstanceName, error)) - .onErrorResume(e -> Mono.empty())) - .doOnError(error -> logError("getting service instance", serviceInstanceName, error)) - .onErrorResume(e -> Mono.empty()); + .flatMap((si) -> this.cloudFoundryOperations.services() + .deleteInstance(DeleteServiceInstanceRequest.builder().name(si.getName()).build()) + .doOnSuccess((v) -> LOG.info("Success deleting service instance. serviceInstanceName={}", + serviceInstanceName)) + .doOnError((error) -> logError("deleting service instance", serviceInstanceName, error)) + .onErrorResume((e) -> Mono.empty())) + .doOnError((error) -> logError("getting service instance", serviceInstanceName, error)) + .onErrorResume((e) -> Mono.empty()); } - public Mono createServiceInstance(String planName, - String serviceName, - String serviceInstanceName, - Map parameters) { - return cloudFoundryOperations.services().createInstance(CreateServiceInstanceRequest.builder() - .planName(planName) - .serviceName(serviceName) - .serviceInstanceName(serviceInstanceName) - .parameters(parameters) - .build()) - .doOnSuccess(item -> LOG.info("Success creating service instance. serviceInstanceName={}", - serviceInstanceName)) - .doOnError(error -> logError("creating service instance", serviceInstanceName, error)); + public Mono createServiceInstance(String planName, String serviceName, String serviceInstanceName, + Map parameters) { + return this.cloudFoundryOperations.services() + .createInstance(CreateServiceInstanceRequest.builder() + .planName(planName) + .serviceName(serviceName) + .serviceInstanceName(serviceInstanceName) + .parameters(parameters) + .build()) + .doOnSuccess((item) -> LOG.info("Success creating service instance. serviceInstanceName={}", + serviceInstanceName)) + .doOnError((error) -> logError("creating service instance", serviceInstanceName, error)); } public Mono updateServiceInstance(String serviceInstanceName, Map parameters) { - return cloudFoundryOperations.services() + return this.cloudFoundryOperations.services() .updateInstance(UpdateServiceInstanceRequest.builder() .serviceInstanceName(serviceInstanceName) .parameters(parameters) .build()) - .doOnSuccess(item -> LOG.info("Updated service instance " + serviceInstanceName)) - .doOnError(error -> logError("updating service instance", serviceInstanceName, error)); + .doOnSuccess((item) -> LOG.info("Updated service instance " + serviceInstanceName)) + .doOnError((error) -> logError("updating service instance", serviceInstanceName, error)); } public Mono getServiceInstance(String serviceInstanceName) { - return cloudFoundryOperations.services() - .getInstance(GetServiceInstanceRequest.builder() - .name(serviceInstanceName) - .build()) - .doOnSuccess(item -> LOG.info("Got service instance " + serviceInstanceName)) - .doOnError(error -> logError("getting service instance", serviceInstanceName, error)); + return this.cloudFoundryOperations.services() + .getInstance(GetServiceInstanceRequest.builder().name(serviceInstanceName).build()) + .doOnSuccess((item) -> LOG.info("Got service instance " + serviceInstanceName)) + .doOnError((error) -> logError("getting service instance", serviceInstanceName, error)); } private static void logError(String operation, String serviceInstanceName, Throwable error) { @@ -132,11 +126,12 @@ public final class UserCloudFoundryService { if (error instanceof UnknownCloudFoundryException) { UnknownCloudFoundryException unknownCloudFoundryException = (UnknownCloudFoundryException) error; logMessage = String.format("Error %s %s: %s %s", operation, serviceInstanceName, - unknownCloudFoundryException.getMessage(), unknownCloudFoundryException.getPayload()); + unknownCloudFoundryException.getMessage(), unknownCloudFoundryException.getPayload()); } else { logMessage = String.format("Error %s %s: %s", operation, serviceInstanceName, error); } LOG.error(logMessage, error); } + } diff --git a/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/fixtures/uaa/UaaService.java b/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/fixtures/uaa/UaaService.java index fc72b8f..2525a2c 100644 --- a/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/fixtures/uaa/UaaService.java +++ b/spring-cloud-app-broker-acceptance-tests/src/test/java/org/springframework/cloud/appbroker/acceptance/fixtures/uaa/UaaService.java @@ -43,45 +43,41 @@ public class UaaService { } public Mono getUaaClient(String clientId) { - return uaaClient.clients().get(GetClientRequest - .builder() - .clientId(clientId) - .build()) - .onErrorResume(e -> Mono.empty()); + return this.uaaClient.clients() + .get(GetClientRequest.builder().clientId(clientId).build()) + .onErrorResume((e) -> Mono.empty()); } public Mono createClient(String clientId, String clientSecret, String... authorities) { final String clientNotFound = "CLIENT_NOT_FOUND"; return getUaaClient(clientId) - .defaultIfEmpty(GetClientResponse.builder() - .clientId(clientNotFound) - .authorities(clientNotFound) - .build()) - .filter(response -> authoritiesChanged(response, authorities)) - .delayUntil(response -> { + .defaultIfEmpty(GetClientResponse.builder().clientId(clientNotFound).authorities(clientNotFound).build()) + .filter((response) -> authoritiesChanged(response, authorities)) + .delayUntil((response) -> { if (!clientNotFound.equals(response.getClientId())) { - return uaaClient.clients() + return this.uaaClient.clients() .delete(DeleteClientRequest.builder().clientId(clientId).build()) - .doOnError(error -> LOG.error("Error deleting client: " + clientId + " with error: " + error)); + .doOnError( + (error) -> LOG.error("Error deleting client: " + clientId + " with error: " + error)); } return Mono.empty(); }) - .flatMap(response -> uaaClient.clients() - .create(CreateClientRequest - .builder() + .flatMap((response) -> this.uaaClient.clients() + .create(CreateClientRequest.builder() .clientId(clientId) .clientSecret(clientSecret) .authorizedGrantType(GrantType.CLIENT_CREDENTIALS) .authorities(authorities) .build()) - .onErrorResume(e -> e.getMessage().contains("Client already exists: " + clientId), e -> Mono.empty()) - .doOnError(error -> LOG.error("Error creating client: " + clientId + " with error: " + error))) + .onErrorResume((e) -> e.getMessage().contains("Client already exists: " + clientId), + (e) -> Mono.empty()) + .doOnError((error) -> LOG.error("Error creating client: " + clientId + " with error: " + error))) .then(); } private boolean authoritiesChanged(GetClientResponse response, String... authorities) { - return !response.getAuthorities().containsAll(Arrays.asList(authorities)) || - response.getAuthorities().size() != authorities.length; + return !response.getAuthorities().containsAll(Arrays.asList(authorities)) + || response.getAuthorities().size() != authorities.length; } } diff --git a/spring-cloud-app-broker-autoconfigure/build.gradle b/spring-cloud-app-broker-autoconfigure/build.gradle index ffd9107..2d626c7 100644 --- a/spring-cloud-app-broker-autoconfigure/build.gradle +++ b/spring-cloud-app-broker-autoconfigure/build.gradle @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-cloud-app-broker-autoconfigure/src/main/java/org/springframework/cloud/appbroker/autoconfigure/AppBrokerAutoConfiguration.java b/spring-cloud-app-broker-autoconfigure/src/main/java/org/springframework/cloud/appbroker/autoconfigure/AppBrokerAutoConfiguration.java index a6d217b..d47e172 100644 --- a/spring-cloud-app-broker-autoconfigure/src/main/java/org/springframework/cloud/appbroker/autoconfigure/AppBrokerAutoConfiguration.java +++ b/spring-cloud-app-broker-autoconfigure/src/main/java/org/springframework/cloud/appbroker/autoconfigure/AppBrokerAutoConfiguration.java @@ -71,7 +71,11 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** - * App Broker Auto-configuration + * App Broker Auto-configuration. + * + * @author Scott Frederick + * @author Roy Clarkson + * @author Alberto Rios */ @Configuration @AutoConfigureAfter(CloudFoundryAppDeployerAutoConfiguration.class) @@ -83,8 +87,7 @@ public class AppBrokerAutoConfiguration { private static final String PROPERTY_PREFIX = "spring.cloud.appbroker"; /** - * Provide a {@link DeployerClient} bean - * + * Provide a {@link DeployerClient} bean. * @param appDeployer the AppDeployer bean * @return the bean */ @@ -94,8 +97,7 @@ public class AppBrokerAutoConfiguration { } /** - * Provide a {@link BackingAppDeploymentService} bean - * + * Provide a {@link BackingAppDeploymentService} bean. * @param deployerClient the DeployerClient bean * @return the bean */ @@ -106,8 +108,7 @@ public class AppBrokerAutoConfiguration { } /** - * Provide a {@link ManagementClient} bean - * + * Provide a {@link ManagementClient} bean. * @param appManager the AppManager bean * @return the bean */ @@ -117,8 +118,7 @@ public class AppBrokerAutoConfiguration { } /** - * Provide a {@link BackingAppManagementService} bean - * + * Provide a {@link BackingAppManagementService} bean. * @param managementClient the ManagementClient bean * @param appDeployer the AppDeployer bean * @param brokeredServices the BrokeredServices bean @@ -127,13 +127,12 @@ public class AppBrokerAutoConfiguration { */ @Bean public BackingAppManagementService backingAppManagementService(ManagementClient managementClient, - AppDeployer appDeployer, BrokeredServices brokeredServices, TargetService targetService) { + AppDeployer appDeployer, BrokeredServices brokeredServices, TargetService targetService) { return new BackingAppManagementService(managementClient, appDeployer, brokeredServices, targetService); } /** - * Provide a {@link BrokeredServices} bean - * + * Provide a {@link BrokeredServices} bean. * @return the bean */ @Bean @@ -144,38 +143,35 @@ public class AppBrokerAutoConfiguration { } /** - * Provide a {@link ServiceInstanceStateRepository} bean - * + * Provide a {@link ServiceInstanceStateRepository} bean. * @return the bean */ @Bean @ConditionalOnMissingBean(ServiceInstanceStateRepository.class) public ServiceInstanceStateRepository serviceInstanceStateRepository() { if (LOG.isWarnEnabled()) { - LOG.warn("The InMemoryServiceInstanceStateRepository is provided for demonstration and testing purposes " + - "only. It is not suitable for production applications!"); + LOG.warn("The InMemoryServiceInstanceStateRepository is provided for demonstration and testing purposes " + + "only. It is not suitable for production applications!"); } return new InMemoryServiceInstanceStateRepository(); } /** - * Provide a {@link ServiceInstanceBindingStateRepository} bean - * + * Provide a {@link ServiceInstanceBindingStateRepository} bean. * @return the bean */ @Bean @ConditionalOnMissingBean(ServiceInstanceBindingStateRepository.class) public ServiceInstanceBindingStateRepository serviceInstanceBindingStateRepository() { if (LOG.isWarnEnabled()) { - LOG.warn("The InMemoryServiceInstanceBindingStateRepository is provided for demonstration and testing " + - "purposes only. It is not suitable for production applications!"); + LOG.warn("The InMemoryServiceInstanceBindingStateRepository is provided for demonstration and testing " + + "purposes only. It is not suitable for production applications!"); } return new InMemoryServiceInstanceBindingStateRepository(); } /** - * Provide an {@link EnvironmentMappingParametersTransformerFactory} bean - * + * Provide an {@link EnvironmentMappingParametersTransformerFactory} bean. * @return the bean */ @Bean @@ -184,8 +180,7 @@ public class AppBrokerAutoConfiguration { } /** - * Provide a {@link ParameterMappingParametersTransformerFactory} bean - * + * Provide a {@link ParameterMappingParametersTransformerFactory} bean. * @return the bean */ @Bean @@ -194,8 +189,7 @@ public class AppBrokerAutoConfiguration { } /** - * Provide a {@link ParameterMappingParametersTransformerFactory} bean - * + * Provide a {@link ParameterMappingParametersTransformerFactory} bean. * @return the bean */ @Bean @@ -204,32 +198,29 @@ public class AppBrokerAutoConfiguration { } /** - * Provide a {@link BackingApplicationsParametersTransformationService} bean - * + * Provide a {@link BackingApplicationsParametersTransformationService} bean. * @param transformers a collection of parameter transformers * @return the bean */ @Bean public BackingApplicationsParametersTransformationService backingApplicationsParametersTransformationService( - List> transformers) { + List> transformers) { return new BackingApplicationsParametersTransformationService(transformers); } /** - * Provide a {@link BackingServicesParametersTransformationService} bean - * + * Provide a {@link BackingServicesParametersTransformationService} bean. * @param transformers a collection of parameter transformers * @return the bean */ @Bean public BackingServicesParametersTransformationService backingServicesParametersTransformationService( - List> transformers) { + List> transformers) { return new BackingServicesParametersTransformationService(transformers); } /** - * Provide a {@link SpacePerServiceInstance} bean - * + * Provide a {@link SpacePerServiceInstance} bean. * @return the bean */ @Bean @@ -238,8 +229,7 @@ public class AppBrokerAutoConfiguration { } /** - * Provide a {@link ServiceInstanceGuidSuffix} bean - * + * Provide a {@link ServiceInstanceGuidSuffix} bean. * @return the bean */ @Bean @@ -248,8 +238,7 @@ public class AppBrokerAutoConfiguration { } /** - * Provide a {@link TargetService} bean - * + * Provide a {@link TargetService} bean. * @param targets a collection of targets * @return the bean */ @@ -259,8 +248,7 @@ public class AppBrokerAutoConfiguration { } /** - * Provide a {@link BackingServicesProvisionService} bean - * + * Provide a {@link BackingServicesProvisionService} bean. * @param deployerClient the DeployerClient bean * @return the bean */ @@ -271,8 +259,7 @@ public class AppBrokerAutoConfiguration { } /** - * Provide a {@link BackingSpaceManagementService} bean - * + * Provide a {@link BackingSpaceManagementService} bean. * @param deployerClient the DeployerClient bean * @return the bean */ @@ -283,94 +270,79 @@ public class AppBrokerAutoConfiguration { } /** - * Provide a {@link CreateServiceInstanceWorkflow} bean - * + * Provide a {@link CreateServiceInstanceWorkflow} bean. * @param brokeredServices the BrokeredServices bean * @param backingAppDeploymentService the BackingAppDeploymentService bean - * @param appsParametersTransformationService the BackingApplicationsParametersTransformationService bean - * @param servicesParametersTransformationService the BackingServicesParametersTransformationService bean + * @param appsParametersTransformationService the + * BackingApplicationsParametersTransformationService bean + * @param servicesParametersTransformationService the + * BackingServicesParametersTransformationService bean * @param targetService the TargetService bean * @param backingServicesProvisionService the BackingServicesProvisionService bean * @return the bean */ @Bean - public CreateServiceInstanceWorkflow appDeploymentCreateServiceInstanceWorkflow( - BrokeredServices brokeredServices, BackingAppDeploymentService backingAppDeploymentService, - BackingApplicationsParametersTransformationService appsParametersTransformationService, - BackingServicesParametersTransformationService servicesParametersTransformationService, - TargetService targetService, BackingServicesProvisionService backingServicesProvisionService) { - return new AppDeploymentCreateServiceInstanceWorkflow( - brokeredServices, - backingAppDeploymentService, - backingServicesProvisionService, - appsParametersTransformationService, - servicesParametersTransformationService, - targetService); + public CreateServiceInstanceWorkflow appDeploymentCreateServiceInstanceWorkflow(BrokeredServices brokeredServices, + BackingAppDeploymentService backingAppDeploymentService, + BackingApplicationsParametersTransformationService appsParametersTransformationService, + BackingServicesParametersTransformationService servicesParametersTransformationService, + TargetService targetService, BackingServicesProvisionService backingServicesProvisionService) { + return new AppDeploymentCreateServiceInstanceWorkflow(brokeredServices, backingAppDeploymentService, + backingServicesProvisionService, appsParametersTransformationService, + servicesParametersTransformationService, targetService); } /** - * Provide a {@link UpdateServiceInstanceWorkflow} bean - * + * Provide a {@link UpdateServiceInstanceWorkflow} bean. * @param brokeredServices the BrokeredServices bean * @param backingAppDeploymentService the BackingAppDeploymentService bean * @param backingAppManagementService the BackingAppManagementService bean * @param backingServicesProvisionService the BackingServicesProvisionService bean - * @param appsParametersTransformationService the BackingApplicationsParametersTransformationService bean - * @param servicesParametersTransformationService the BackingServicesParametersTransformationService bean + * @param appsParametersTransformationService the + * BackingApplicationsParametersTransformationService bean + * @param servicesParametersTransformationService the + * BackingServicesParametersTransformationService bean * @param targetService the TargetService bean * @return the bean */ @Bean - public UpdateServiceInstanceWorkflow appDeploymentUpdateServiceInstanceWorkflow( - BrokeredServices brokeredServices, - BackingAppDeploymentService backingAppDeploymentService, - BackingAppManagementService backingAppManagementService, - BackingServicesProvisionService backingServicesProvisionService, - BackingApplicationsParametersTransformationService appsParametersTransformationService, - BackingServicesParametersTransformationService servicesParametersTransformationService, - TargetService targetService) { + public UpdateServiceInstanceWorkflow appDeploymentUpdateServiceInstanceWorkflow(BrokeredServices brokeredServices, + BackingAppDeploymentService backingAppDeploymentService, + BackingAppManagementService backingAppManagementService, + BackingServicesProvisionService backingServicesProvisionService, + BackingApplicationsParametersTransformationService appsParametersTransformationService, + BackingServicesParametersTransformationService servicesParametersTransformationService, + TargetService targetService) { - return new AppDeploymentUpdateServiceInstanceWorkflow( - brokeredServices, - backingAppDeploymentService, - backingAppManagementService, - backingServicesProvisionService, - appsParametersTransformationService, - servicesParametersTransformationService, - targetService); + return new AppDeploymentUpdateServiceInstanceWorkflow(brokeredServices, backingAppDeploymentService, + backingAppManagementService, backingServicesProvisionService, appsParametersTransformationService, + servicesParametersTransformationService, targetService); } /** - * Provide a {@link DeleteServiceInstanceWorkflow} bean - * + * Provide a {@link DeleteServiceInstanceWorkflow} bean. * @param brokeredServices the BrokeredServices bean * @param backingAppDeploymentService the BackingAppDeploymentService bean * @param backingAppManagementService the BackingAppManagementService bean * @param backingServicesProvisionService the BackingServicesProvisionService bean + * @param backingSpaceManagementService the BackingSpaceManagementService bean * @param targetService the TargetService bean * @return the bean */ @Bean - public DeleteServiceInstanceWorkflow appDeploymentDeleteServiceInstanceWorkflow( - BrokeredServices brokeredServices, BackingAppDeploymentService backingAppDeploymentService, - BackingAppManagementService backingAppManagementService, - BackingServicesProvisionService backingServicesProvisionService, - BackingSpaceManagementService backingSpaceManagementService, - TargetService targetService) { + public DeleteServiceInstanceWorkflow appDeploymentDeleteServiceInstanceWorkflow(BrokeredServices brokeredServices, + BackingAppDeploymentService backingAppDeploymentService, + BackingAppManagementService backingAppManagementService, + BackingServicesProvisionService backingServicesProvisionService, + BackingSpaceManagementService backingSpaceManagementService, TargetService targetService) { - return new AppDeploymentDeleteServiceInstanceWorkflow( - brokeredServices, - backingAppDeploymentService, - backingAppManagementService, - backingServicesProvisionService, - backingSpaceManagementService, - targetService - ); + return new AppDeploymentDeleteServiceInstanceWorkflow(brokeredServices, backingAppDeploymentService, + backingAppManagementService, backingServicesProvisionService, backingSpaceManagementService, + targetService); } /** - * Provide a {@link WorkflowServiceInstanceService} bean - * + * Provide a {@link WorkflowServiceInstanceService} bean. * @param stateRepository the ServiceInstanceStateRepository bean * @param createWorkflows a collection of create workflows * @param deleteWorkflows a collection of delete workflows @@ -380,30 +352,33 @@ public class AppBrokerAutoConfiguration { @Bean @ConditionalOnMissingBean(ServiceInstanceService.class) public WorkflowServiceInstanceService serviceInstanceService(ServiceInstanceStateRepository stateRepository, - List createWorkflows, List deleteWorkflows, - List updateWorkflows) { + List createWorkflows, List deleteWorkflows, + List updateWorkflows) { return new WorkflowServiceInstanceService(stateRepository, createWorkflows, deleteWorkflows, updateWorkflows); } /** - * Provide a {@link WorkflowServiceInstanceBindingService} bean - * + * Provide a {@link WorkflowServiceInstanceBindingService} bean. * @param stateRepository the ServiceInstanceBindingStateRepository bean - * @param createServiceInstanceAppBindingWorkflows a collection of create app binding workflows - * @param createServiceInstanceRouteBindingWorkflows a collection of create route binding workflows + * @param createServiceInstanceAppBindingWorkflows a collection of create app binding + * workflows + * @param createServiceInstanceRouteBindingWorkflows a collection of create route + * binding workflows * @param deleteServiceInstanceBindingWorkflows a collection of update workflows * @return the bean */ @Bean @ConditionalOnMissingBean(ServiceInstanceBindingService.class) public WorkflowServiceInstanceBindingService serviceInstanceBindingService( - ServiceInstanceBindingStateRepository stateRepository, - @Autowired(required = false) List createServiceInstanceAppBindingWorkflows, - @Autowired(required = false) List createServiceInstanceRouteBindingWorkflows, - @Autowired(required = false) List deleteServiceInstanceBindingWorkflows) { - return new WorkflowServiceInstanceBindingService(stateRepository, - createServiceInstanceAppBindingWorkflows, createServiceInstanceRouteBindingWorkflows, - deleteServiceInstanceBindingWorkflows); + ServiceInstanceBindingStateRepository stateRepository, + @Autowired( + required = false) List createServiceInstanceAppBindingWorkflows, + @Autowired( + required = false) List createServiceInstanceRouteBindingWorkflows, + @Autowired( + required = false) List deleteServiceInstanceBindingWorkflows) { + return new WorkflowServiceInstanceBindingService(stateRepository, createServiceInstanceAppBindingWorkflows, + createServiceInstanceRouteBindingWorkflows, deleteServiceInstanceBindingWorkflows); } } diff --git a/spring-cloud-app-broker-autoconfigure/src/main/java/org/springframework/cloud/appbroker/autoconfigure/CloudFoundryAppDeployerAutoConfiguration.java b/spring-cloud-app-broker-autoconfigure/src/main/java/org/springframework/cloud/appbroker/autoconfigure/CloudFoundryAppDeployerAutoConfiguration.java index 90ed32a..3bc2910 100644 --- a/spring-cloud-app-broker-autoconfigure/src/main/java/org/springframework/cloud/appbroker/autoconfigure/CloudFoundryAppDeployerAutoConfiguration.java +++ b/spring-cloud-app-broker-autoconfigure/src/main/java/org/springframework/cloud/appbroker/autoconfigure/CloudFoundryAppDeployerAutoConfiguration.java @@ -58,7 +58,11 @@ import org.springframework.core.io.ResourceLoader; import org.springframework.util.StringUtils; /** - * Auto-configuration support for deploying apps to Cloud Foundry + * Auto-configuration support for deploying apps to Cloud Foundry. + * + * @author Roy Clarkson + * @author Scott Frederick + * @author Alberto Rios */ @Configuration @ConditionalOnProperty(CloudFoundryAppDeployerAutoConfiguration.PROPERTY_PREFIX + ".api-host") @@ -68,8 +72,7 @@ public class CloudFoundryAppDeployerAutoConfiguration { protected static final String PROPERTY_PREFIX = "spring.cloud.appbroker.deployer.cloudfoundry"; /** - * Provide a {@link CloudFoundryDeploymentProperties} bean - * + * Provide a {@link CloudFoundryDeploymentProperties} bean. * @return the bean */ @Bean @@ -79,8 +82,7 @@ public class CloudFoundryAppDeployerAutoConfiguration { } /** - * Provide a {@link CloudFoundryTargetProperties} bean - * + * Provide a {@link CloudFoundryTargetProperties} bean. * @return the bean */ @Bean @@ -90,8 +92,7 @@ public class CloudFoundryAppDeployerAutoConfiguration { } /** - * Provide a {@link AppDeployer} bean - * + * Provide a {@link AppDeployer} bean. * @param deploymentProperties the CloudFoundryDeploymentProperties bean * @param cloudFoundryOperations the CloudFoundryOperations bean * @param cloudFoundryClient the CloudFoundryClient bean @@ -102,16 +103,15 @@ public class CloudFoundryAppDeployerAutoConfiguration { */ @Bean public AppDeployer cloudFoundryAppDeployer(CloudFoundryDeploymentProperties deploymentProperties, - CloudFoundryOperations cloudFoundryOperations, CloudFoundryClient cloudFoundryClient, - CloudFoundryOperationsUtils operationsUtils, CloudFoundryTargetProperties targetProperties, - ResourceLoader resourceLoader) { + CloudFoundryOperations cloudFoundryOperations, CloudFoundryClient cloudFoundryClient, + CloudFoundryOperationsUtils operationsUtils, CloudFoundryTargetProperties targetProperties, + ResourceLoader resourceLoader) { return new CloudFoundryAppDeployer(deploymentProperties, cloudFoundryOperations, cloudFoundryClient, - operationsUtils, targetProperties, resourceLoader); + operationsUtils, targetProperties, resourceLoader); } /** - * Provide an {@link AppManager} bean - * + * Provide an {@link AppManager} bean. * @param cloudFoundryOperationsUtils the CloudFoundryOperationsUtils bean * @return the bean */ @@ -121,8 +121,7 @@ public class CloudFoundryAppDeployerAutoConfiguration { } /** - * Provide an {@link OAuth2Client} bean - * + * Provide an {@link OAuth2Client} bean. * @param uaaClient the UaaClient bean * @return the bean */ @@ -132,15 +131,14 @@ public class CloudFoundryAppDeployerAutoConfiguration { } /** - * Provide a {@link ReactorCloudFoundryClient} bean - * + * Provide a {@link ReactorCloudFoundryClient} bean. * @param connectionContext the ConnectionContext bean * @param tokenProvider the TokenProvider bean * @return the bean */ @Bean public ReactorCloudFoundryClient cloudFoundryClient(@ConnectionContextQualifier ConnectionContext connectionContext, - @TokenQualifier TokenProvider tokenProvider) { + @TokenQualifier TokenProvider tokenProvider) { return ReactorCloudFoundryClient.builder() .connectionContext(connectionContext) .tokenProvider(tokenProvider) @@ -148,8 +146,7 @@ public class CloudFoundryAppDeployerAutoConfiguration { } /** - * Provide a {@link CloudFoundryOperations} bean - * + * Provide a {@link CloudFoundryOperations} bean. * @param properties the CloudFoundryTargetProperties bean * @param client the CloudFoundryClient bean * @param dopplerClient the DopplerClient bean @@ -158,7 +155,7 @@ public class CloudFoundryAppDeployerAutoConfiguration { */ @Bean public CloudFoundryOperations cloudFoundryOperations(CloudFoundryTargetProperties properties, - CloudFoundryClient client, DopplerClient dopplerClient, @UaaClientQualifier UaaClient uaaClient) { + CloudFoundryClient client, DopplerClient dopplerClient, @UaaClientQualifier UaaClient uaaClient) { return DefaultCloudFoundryOperations.builder() .cloudFoundryClient(client) .dopplerClient(dopplerClient) @@ -169,8 +166,7 @@ public class CloudFoundryAppDeployerAutoConfiguration { } /** - * Provide a {@link CloudFoundryOperationsUtils} bean - * + * Provide a {@link CloudFoundryOperationsUtils} bean. * @param operations the CloudFoundryOperations bean * @return the bean */ @@ -180,8 +176,7 @@ public class CloudFoundryAppDeployerAutoConfiguration { } /** - * Provide a {@link DefaultConnectionContext} bean - * + * Provide a {@link DefaultConnectionContext} bean. * @param properties the CloudFoundryTargetProperties bean * @return the bean */ @@ -197,31 +192,26 @@ public class CloudFoundryAppDeployerAutoConfiguration { } /** - * Provide a {@link ReactorDopplerClient} bean - * + * Provide a {@link ReactorDopplerClient} bean. * @param connectionContext the ConnectionContext bean * @param tokenProvider the TokenProvider bean * @return the bean */ @Bean public ReactorDopplerClient dopplerClient(@ConnectionContextQualifier ConnectionContext connectionContext, - @TokenQualifier TokenProvider tokenProvider) { - return ReactorDopplerClient.builder() - .connectionContext(connectionContext) - .tokenProvider(tokenProvider) - .build(); + @TokenQualifier TokenProvider tokenProvider) { + return ReactorDopplerClient.builder().connectionContext(connectionContext).tokenProvider(tokenProvider).build(); } /** - * Provide a {@link LogCacheClient} bean - * + * Provide a {@link LogCacheClient} bean. * @param connectionContext the ConnectionContext bean * @param tokenProvider the TokenProvider bean * @return the bean */ @Bean public LogCacheClient logCacheClient(@ConnectionContextQualifier ConnectionContext connectionContext, - @TokenQualifier TokenProvider tokenProvider) { + @TokenQualifier TokenProvider tokenProvider) { return ReactorLogCacheClient.builder() .connectionContext(connectionContext) .tokenProvider(tokenProvider) @@ -229,8 +219,7 @@ public class CloudFoundryAppDeployerAutoConfiguration { } /** - * Provide a {@link TokenProvider} bean - * + * Provide a {@link TokenProvider} bean. * @param properties the CloudFoundryTargetProperties bean * @return the bean */ @@ -242,9 +231,8 @@ public class CloudFoundryAppDeployerAutoConfiguration { boolean isUsernameAndPasswordSet = Stream.of(properties.getUsername(), properties.getPassword()) .allMatch(StringUtils::hasText); if (isClientIdAndSecretSet && isUsernameAndPasswordSet) { - throw new IllegalStateException( - String.format("(%1$s.client_id / %1$s.client_secret) must not be set when\n" + - "(%1$s.username / %1$s.password) are also set", PROPERTY_PREFIX)); + throw new IllegalStateException(String.format("(%1$s.client_id / %1$s.client_secret) must not be set when\n" + + "(%1$s.username / %1$s.password) are also set", PROPERTY_PREFIX)); } else if (isClientIdAndSecretSet) { return ClientCredentialsGrantTokenProvider.builder() @@ -260,15 +248,13 @@ public class CloudFoundryAppDeployerAutoConfiguration { .build(); } else { - throw new IllegalStateException( - String.format("Either (%1$s.client_id and %1$s.client_secret) or\n" + - "(%1$s.username and %1$s.password) properties must be set", PROPERTY_PREFIX)); + throw new IllegalStateException(String.format("Either (%1$s.client_id and %1$s.client_secret) or\n" + + "(%1$s.username and %1$s.password) properties must be set", PROPERTY_PREFIX)); } } /** - * Provide a {@link ReactorUaaClient} bean - * + * Provide a {@link ReactorUaaClient} bean. * @param connectionContext the ConnectionContext bean * @param tokenProvider the TokenProvider bean * @return the bean @@ -276,15 +262,12 @@ public class CloudFoundryAppDeployerAutoConfiguration { @UaaClientQualifier @Bean public ReactorUaaClient uaaClient(@ConnectionContextQualifier ConnectionContext connectionContext, - @TokenQualifier TokenProvider tokenProvider) { - return ReactorUaaClient.builder() - .connectionContext(connectionContext) - .tokenProvider(tokenProvider) - .build(); + @TokenQualifier TokenProvider tokenProvider) { + return ReactorUaaClient.builder().connectionContext(connectionContext).tokenProvider(tokenProvider).build(); } @Qualifier - @Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD, ElementType.TYPE}) + @Target({ ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD, ElementType.TYPE }) @Retention(RetentionPolicy.RUNTIME) public @interface TokenQualifier { @@ -293,7 +276,7 @@ public class CloudFoundryAppDeployerAutoConfiguration { } @Qualifier - @Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD, ElementType.TYPE}) + @Target({ ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD, ElementType.TYPE }) @Retention(RetentionPolicy.RUNTIME) public @interface UaaClientQualifier { @@ -302,7 +285,7 @@ public class CloudFoundryAppDeployerAutoConfiguration { } @Qualifier - @Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD, ElementType.TYPE}) + @Target({ ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD, ElementType.TYPE }) @Retention(RetentionPolicy.RUNTIME) public @interface ConnectionContextQualifier { diff --git a/spring-cloud-app-broker-autoconfigure/src/main/java/org/springframework/cloud/appbroker/autoconfigure/ServiceInstanceLogStreamAutoConfiguration.java b/spring-cloud-app-broker-autoconfigure/src/main/java/org/springframework/cloud/appbroker/autoconfigure/ServiceInstanceLogStreamAutoConfiguration.java index 6e0e51b..50c0f92 100644 --- a/spring-cloud-app-broker-autoconfigure/src/main/java/org/springframework/cloud/appbroker/autoconfigure/ServiceInstanceLogStreamAutoConfiguration.java +++ b/spring-cloud-app-broker-autoconfigure/src/main/java/org/springframework/cloud/appbroker/autoconfigure/ServiceInstanceLogStreamAutoConfiguration.java @@ -1,11 +1,11 @@ /* - * Copyright 2016-2024 the original author or authors + * Copyright 2002-2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * https://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -45,7 +45,7 @@ public class ServiceInstanceLogStreamAutoConfiguration { @Bean public StreamingLogWebSocketHandler streamingLogWebSocketHandler( - ApplicationEventPublisher applicationEventPublisher) { + ApplicationEventPublisher applicationEventPublisher) { return new StreamingLogWebSocketHandler(applicationEventPublisher); } @@ -69,15 +69,15 @@ public class ServiceInstanceLogStreamAutoConfiguration { @Bean @ConditionalOnMissingBean public LogStreamPublisher streamLogsPublisher( - CloudFoundryClient cloudFoundryClient, - LogCacheClient logCacheClient, - ApplicationIdsProvider applicationIdsProvider) { + CloudFoundryClient cloudFoundryClient, LogCacheClient logCacheClient, + ApplicationIdsProvider applicationIdsProvider) { return new LogCacheStreamPublisher(cloudFoundryClient, logCacheClient, applicationIdsProvider); } @Bean - public ApplicationLogStreamPublisher applicationLogsPublisher(LogStreamPublisher logStreamPublisher, - ApplicationEventPublisher eventPublisher) { + public ApplicationLogStreamPublisher applicationLogsPublisher( + LogStreamPublisher logStreamPublisher, + ApplicationEventPublisher eventPublisher) { return new ApplicationLogStreamPublisher(logStreamPublisher, eventPublisher); } diff --git a/spring-cloud-app-broker-autoconfigure/src/main/java/org/springframework/cloud/appbroker/autoconfigure/ServiceInstanceRecentLogsAutoConfiguration.java b/spring-cloud-app-broker-autoconfigure/src/main/java/org/springframework/cloud/appbroker/autoconfigure/ServiceInstanceRecentLogsAutoConfiguration.java index 7c08e69..a558ace 100644 --- a/spring-cloud-app-broker-autoconfigure/src/main/java/org/springframework/cloud/appbroker/autoconfigure/ServiceInstanceRecentLogsAutoConfiguration.java +++ b/spring-cloud-app-broker-autoconfigure/src/main/java/org/springframework/cloud/appbroker/autoconfigure/ServiceInstanceRecentLogsAutoConfiguration.java @@ -1,11 +1,11 @@ /* - * Copyright 2016-2024 the original author or authors + * Copyright 2002-2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * https://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -34,9 +34,8 @@ import org.springframework.context.annotation.Configuration; public class ServiceInstanceRecentLogsAutoConfiguration { @Bean - public RecentLogsProvider recentLogsProvider( - LogCacheClient logCacheClient, - ApplicationIdsProvider applicationIdsProvider) { + public RecentLogsProvider recentLogsProvider(LogCacheClient logCacheClient, + ApplicationIdsProvider applicationIdsProvider) { return new ApplicationRecentLogsProvider(logCacheClient, applicationIdsProvider); } diff --git a/spring-cloud-app-broker-autoconfigure/src/main/java/org/springframework/cloud/appbroker/autoconfigure/package-info.java b/spring-cloud-app-broker-autoconfigure/src/main/java/org/springframework/cloud/appbroker/autoconfigure/package-info.java new file mode 100644 index 0000000..804d558 --- /dev/null +++ b/spring-cloud-app-broker-autoconfigure/src/main/java/org/springframework/cloud/appbroker/autoconfigure/package-info.java @@ -0,0 +1,20 @@ +/* + * Copyright 2016-2024 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * App Broker Auto-Configuration. + */ +package org.springframework.cloud.appbroker.autoconfigure; diff --git a/spring-cloud-app-broker-autoconfigure/src/test/java/org/springframework/cloud/appbroker/autoconfigure/AppBrokerAutoConfigurationTest.java b/spring-cloud-app-broker-autoconfigure/src/test/java/org/springframework/cloud/appbroker/autoconfigure/AppBrokerAutoConfigurationTests.java similarity index 78% rename from spring-cloud-app-broker-autoconfigure/src/test/java/org/springframework/cloud/appbroker/autoconfigure/AppBrokerAutoConfigurationTest.java rename to spring-cloud-app-broker-autoconfigure/src/test/java/org/springframework/cloud/appbroker/autoconfigure/AppBrokerAutoConfigurationTests.java index 8495240..1c55f34 100644 --- a/spring-cloud-app-broker-autoconfigure/src/test/java/org/springframework/cloud/appbroker/autoconfigure/AppBrokerAutoConfigurationTest.java +++ b/spring-cloud-app-broker-autoconfigure/src/test/java/org/springframework/cloud/appbroker/autoconfigure/AppBrokerAutoConfigurationTests.java @@ -63,73 +63,61 @@ import org.springframework.context.annotation.Configuration; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -class AppBrokerAutoConfigurationTest { +class AppBrokerAutoConfigurationTests { - private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of( - CloudFoundryAppDeployerAutoConfiguration.class, - AppBrokerAutoConfiguration.class - )); + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().withConfiguration( + AutoConfigurations.of(CloudFoundryAppDeployerAutoConfiguration.class, AppBrokerAutoConfiguration.class)); @Test void servicesAreCreatedWithCloudFoundryConfigured() { - configuredContext() - .run(context -> { - assertBeansCreated(context); - assertPropertiesLoaded(context); + configuredContext().run((context) -> { + assertBeansCreated(context); + assertPropertiesLoaded(context); - assertThat(context) - .hasSingleBean(ServiceInstanceBindingService.class) - .getBean(ServiceInstanceBindingService.class) - .isExactlyInstanceOf(WorkflowServiceInstanceBindingService.class); - }); + assertThat(context).hasSingleBean(ServiceInstanceBindingService.class) + .getBean(ServiceInstanceBindingService.class) + .isExactlyInstanceOf(WorkflowServiceInstanceBindingService.class); + }); } @Test void servicesAreNotCreatedWithoutDeployerConfiguration() { - this.contextRunner - .run((context) -> { - assertThat(context).doesNotHaveBean(BackingApplications.class); - assertThat(context).doesNotHaveBean(DeployerClient.class); - }); + this.contextRunner.run((context) -> { + assertThat(context).doesNotHaveBean(BackingApplications.class); + assertThat(context).doesNotHaveBean(DeployerClient.class); + }); } @Test void bindingServiceIsNotCreatedIfProvided() { - configuredContext() - .withUserConfiguration(CustomBindingServiceConfiguration.class) - .run(context -> { - assertBeansCreated(context); + configuredContext().withUserConfiguration(CustomBindingServiceConfiguration.class).run((context) -> { + assertBeansCreated(context); - assertThat(context) - .hasSingleBean(ServiceInstanceBindingService.class) - .getBean(ServiceInstanceBindingService.class) - .isExactlyInstanceOf(TestServiceInstanceBindingService.class); - }); + assertThat(context).hasSingleBean(ServiceInstanceBindingService.class) + .getBean(ServiceInstanceBindingService.class) + .isExactlyInstanceOf(TestServiceInstanceBindingService.class); + }); } @Test void serviceInstanceIsNotCreatedIfProvided() { - configuredContext() - .withUserConfiguration(CustomServiceConfiguration.class) - .run(context -> { - assertBeansCreated(context); + configuredContext().withUserConfiguration(CustomServiceConfiguration.class).run((context) -> { + assertBeansCreated(context); - assertThat(context) - .hasSingleBean(ServiceInstanceService.class) - .getBean(ServiceInstanceService.class) - .isExactlyInstanceOf(TestServiceInstanceService.class); - }); + assertThat(context).hasSingleBean(ServiceInstanceService.class) + .getBean(ServiceInstanceService.class) + .isExactlyInstanceOf(TestServiceInstanceService.class); + }); } @Test void clientCredentialsNotAllowedWhenUsernameAndPasswordSet() { assertThatThrownBy(() -> this.contextRunner .withPropertyValues("spring.cloud.appbroker.deployer.cloudfoundry.api-host=https://api.example.local", - "spring.cloud.appbroker.deployer.cloudfoundry.username=user", - "spring.cloud.appbroker.deployer.cloudfoundry.password=secret", - "spring.cloud.appbroker.deployer.cloudfoundry.client_id=user", - "spring.cloud.appbroker.deployer.cloudfoundry.client_secret=secret") + "spring.cloud.appbroker.deployer.cloudfoundry.username=user", + "spring.cloud.appbroker.deployer.cloudfoundry.password=secret", + "spring.cloud.appbroker.deployer.cloudfoundry.client_id=user", + "spring.cloud.appbroker.deployer.cloudfoundry.client_secret=secret") .run(Lifecycle::start)); } @@ -137,7 +125,7 @@ class AppBrokerAutoConfigurationTest { void clientIdWithoutSecretNotAllowed() { assertThatThrownBy(() -> this.contextRunner .withPropertyValues("spring.cloud.appbroker.deployer.cloudfoundry.api-host=https://api.example.local", - "spring.cloud.appbroker.deployer.cloudfoundry.client_id=user") + "spring.cloud.appbroker.deployer.cloudfoundry.client_id=user") .run(Lifecycle::start)); } @@ -145,9 +133,9 @@ class AppBrokerAutoConfigurationTest { void configureCloudFoundryClientWithClientCredentials() { this.contextRunner .withPropertyValues("spring.cloud.appbroker.deployer.cloudfoundry.api-host=https://api.example.local", - "spring.cloud.appbroker.deployer.cloudfoundry.client_id=user", - "spring.cloud.appbroker.deployer.cloudfoundry.client_secret=secret") - .run(context -> { + "spring.cloud.appbroker.deployer.cloudfoundry.client_id=user", + "spring.cloud.appbroker.deployer.cloudfoundry.client_secret=secret") + .run((context) -> { assertThat(context).hasSingleBean(TokenProvider.class); assertThat(context).hasSingleBean(ReactorCloudFoundryClient.class); }); @@ -155,50 +143,39 @@ class AppBrokerAutoConfigurationTest { @Test void serviceInstanceStateRepositoryIsNotCreatedIfProvided() { - configuredContext() - .withUserConfiguration(CustomStateRepositoriesConfiguration.class) - .run(context -> { - assertBeansCreated(context); + configuredContext().withUserConfiguration(CustomStateRepositoriesConfiguration.class).run((context) -> { + assertBeansCreated(context); - assertThat(context) - .hasSingleBean(ServiceInstanceStateRepository.class) - .getBean(ServiceInstanceStateRepository.class) - .isExactlyInstanceOf(TestServiceInstanceStateRepository.class); - }); + assertThat(context).hasSingleBean(ServiceInstanceStateRepository.class) + .getBean(ServiceInstanceStateRepository.class) + .isExactlyInstanceOf(TestServiceInstanceStateRepository.class); + }); } @Test void brokeredServicesIsNotCreatedIfProvided() { - configuredContext() - .withUserConfiguration(CustomBrokeredServicesConfiguration.class) - .run(context -> { - assertBeansCreated(context); + configuredContext().withUserConfiguration(CustomBrokeredServicesConfiguration.class).run((context) -> { + assertBeansCreated(context); - assertThat(context) - .hasSingleBean(BrokeredServices.class) - .getBean(BrokeredServices.class) - .isEqualTo(new CustomBrokeredServicesConfiguration().brokeredServices()); - }); + assertThat(context).hasSingleBean(BrokeredServices.class) + .getBean(BrokeredServices.class) + .isEqualTo(new CustomBrokeredServicesConfiguration().brokeredServices()); + }); } @Test void serviceInstanceBindingStateRepositoryIsNotCreatedIfProvided() { - configuredContext() - .withUserConfiguration(CustomStateRepositoriesConfiguration.class) - .run(context -> { - assertBeansCreated(context); + configuredContext().withUserConfiguration(CustomStateRepositoriesConfiguration.class).run((context) -> { + assertBeansCreated(context); - assertThat(context) - .hasSingleBean(ServiceInstanceBindingStateRepository.class) - .getBean(ServiceInstanceBindingStateRepository.class) - .isExactlyInstanceOf(TestServiceInstanceBindingStateRepository.class); - }); + assertThat(context).hasSingleBean(ServiceInstanceBindingStateRepository.class) + .getBean(ServiceInstanceBindingStateRepository.class) + .isExactlyInstanceOf(TestServiceInstanceBindingStateRepository.class); + }); } private ApplicationContextRunner configuredContext() { - return this.contextRunner - .withPropertyValues( - "spring.cloud.appbroker.services[0].service-name=service1", + return this.contextRunner.withPropertyValues("spring.cloud.appbroker.services[0].service-name=service1", "spring.cloud.appbroker.services[0].plan-name=service1-plan1", "spring.cloud.appbroker.services[0].apps[0].path=classpath:app1.jar", @@ -220,8 +197,7 @@ class AppBrokerAutoConfigurationTest { "spring.cloud.appbroker.deployer.cloudfoundry.username=user", "spring.cloud.appbroker.deployer.cloudfoundry.password=secret", "spring.cloud.appbroker.deployer.cloudfoundry.staging-timeout=3", - "spring.cloud.appbroker.deployer.cloudfoundry.deployment-timeout=4" - ); + "spring.cloud.appbroker.deployer.cloudfoundry.deployment-timeout=4"); } private void assertBeansCreated(AssertableApplicationContext context) { @@ -312,13 +288,11 @@ class AppBrokerAutoConfigurationTest { @Bean public BrokeredServices brokeredServices() { - return BrokeredServices.builder().service( - BrokeredService.builder() - .serviceName("single-service") - .planName("service1-plan1") - .build()) + return BrokeredServices.builder() + .service(BrokeredService.builder().serviceName("single-service").planName("service1-plan1").build()) .build(); } + } @Configuration @@ -337,6 +311,7 @@ class AppBrokerAutoConfigurationTest { } private static class TestServiceInstanceBindingService implements ServiceInstanceBindingService { + } private static class TestServiceInstanceService implements ServiceInstanceService { @@ -353,8 +328,12 @@ class AppBrokerAutoConfigurationTest { } - private static class TestServiceInstanceStateRepository implements ServiceInstanceStateRepository {} + private static class TestServiceInstanceStateRepository implements ServiceInstanceStateRepository { - private static class TestServiceInstanceBindingStateRepository implements ServiceInstanceBindingStateRepository {} + } + + private static class TestServiceInstanceBindingStateRepository implements ServiceInstanceBindingStateRepository { + + } } diff --git a/spring-cloud-app-broker-autoconfigure/src/test/java/org/springframework/cloud/appbroker/autoconfigure/CloudFoundryAppDeployerAutoConfigurationTest.java b/spring-cloud-app-broker-autoconfigure/src/test/java/org/springframework/cloud/appbroker/autoconfigure/CloudFoundryAppDeployerAutoConfigurationTests.java similarity index 72% rename from spring-cloud-app-broker-autoconfigure/src/test/java/org/springframework/cloud/appbroker/autoconfigure/CloudFoundryAppDeployerAutoConfigurationTest.java rename to spring-cloud-app-broker-autoconfigure/src/test/java/org/springframework/cloud/appbroker/autoconfigure/CloudFoundryAppDeployerAutoConfigurationTests.java index 1ab130a..901f0cb 100644 --- a/spring-cloud-app-broker-autoconfigure/src/test/java/org/springframework/cloud/appbroker/autoconfigure/CloudFoundryAppDeployerAutoConfigurationTest.java +++ b/spring-cloud-app-broker-autoconfigure/src/test/java/org/springframework/cloud/appbroker/autoconfigure/CloudFoundryAppDeployerAutoConfigurationTests.java @@ -38,7 +38,7 @@ import org.springframework.cloud.appbroker.deployer.oauth2.OAuth2Client; import static org.assertj.core.api.Assertions.assertThat; -class CloudFoundryAppDeployerAutoConfigurationTest { +class CloudFoundryAppDeployerAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(CloudFoundryAppDeployerAutoConfiguration.class)); @@ -46,19 +46,17 @@ class CloudFoundryAppDeployerAutoConfigurationTest { @Test void clientIsCreatedWithPasswordGrantConfiguration() { this.contextRunner - .withPropertyValues( - "spring.cloud.appbroker.deployer.cloudfoundry.api-host=api.example.local", - "spring.cloud.appbroker.deployer.cloudfoundry.api-port=443", - "spring.cloud.appbroker.deployer.cloudfoundry.default-org=example-org", - "spring.cloud.appbroker.deployer.cloudfoundry.default-space=example-space", - "spring.cloud.appbroker.deployer.cloudfoundry.username=user", - "spring.cloud.appbroker.deployer.cloudfoundry.password=secret", - "spring.cloud.appbroker.deployer.cloudfoundry.properties.memory=2G", - "spring.cloud.appbroker.deployer.cloudfoundry.properties.count=3", - "spring.cloud.appbroker.deployer.cloudfoundry.properties.buildpack=example-buildpack", - "spring.cloud.appbroker.deployer.cloudfoundry.properties.stack=customstack", - "spring.cloud.appbroker.deployer.cloudfoundry.properties.domain=example.local" - ) + .withPropertyValues("spring.cloud.appbroker.deployer.cloudfoundry.api-host=api.example.local", + "spring.cloud.appbroker.deployer.cloudfoundry.api-port=443", + "spring.cloud.appbroker.deployer.cloudfoundry.default-org=example-org", + "spring.cloud.appbroker.deployer.cloudfoundry.default-space=example-space", + "spring.cloud.appbroker.deployer.cloudfoundry.username=user", + "spring.cloud.appbroker.deployer.cloudfoundry.password=secret", + "spring.cloud.appbroker.deployer.cloudfoundry.properties.memory=2G", + "spring.cloud.appbroker.deployer.cloudfoundry.properties.count=3", + "spring.cloud.appbroker.deployer.cloudfoundry.properties.buildpack=example-buildpack", + "spring.cloud.appbroker.deployer.cloudfoundry.properties.stack=customstack", + "spring.cloud.appbroker.deployer.cloudfoundry.properties.domain=example.local") .run((context) -> { assertThat(context).hasSingleBean(CloudFoundryTargetProperties.class); CloudFoundryTargetProperties targetProperties = context.getBean(CloudFoundryTargetProperties.class); @@ -95,14 +93,12 @@ class CloudFoundryAppDeployerAutoConfigurationTest { @Test void clientIsCreatedWithCredentialsGrantConfiguration() { this.contextRunner - .withPropertyValues( - "spring.cloud.appbroker.deployer.cloudfoundry.api-host=api.example.local", - "spring.cloud.appbroker.deployer.cloudfoundry.api-port=443", - "spring.cloud.appbroker.deployer.cloudfoundry.default-org=example-org", - "spring.cloud.appbroker.deployer.cloudfoundry.default-space=example-space", - "spring.cloud.appbroker.deployer.cloudfoundry.client-id=oauth-client", - "spring.cloud.appbroker.deployer.cloudfoundry.client-secret=secret" - ) + .withPropertyValues("spring.cloud.appbroker.deployer.cloudfoundry.api-host=api.example.local", + "spring.cloud.appbroker.deployer.cloudfoundry.api-port=443", + "spring.cloud.appbroker.deployer.cloudfoundry.default-org=example-org", + "spring.cloud.appbroker.deployer.cloudfoundry.default-space=example-space", + "spring.cloud.appbroker.deployer.cloudfoundry.client-id=oauth-client", + "spring.cloud.appbroker.deployer.cloudfoundry.client-secret=secret") .run((context) -> { assertThat(context).hasSingleBean(CloudFoundryTargetProperties.class); CloudFoundryTargetProperties targetProperties = context.getBean(CloudFoundryTargetProperties.class); @@ -128,18 +124,17 @@ class CloudFoundryAppDeployerAutoConfigurationTest { @Test void clientIsNotCreatedWithoutConfiguration() { - this.contextRunner - .run((context) -> { - assertThat(context).doesNotHaveBean(CloudFoundryTargetProperties.class); - assertThat(context).doesNotHaveBean(CloudFoundryDeploymentProperties.class); - assertThat(context).doesNotHaveBean(ReactorCloudFoundryClient.class); - assertThat(context).doesNotHaveBean(ReactorDopplerClient.class); - assertThat(context).doesNotHaveBean(ReactorUaaClient.class); - assertThat(context).doesNotHaveBean(CloudFoundryOperations.class); - assertThat(context).doesNotHaveBean(CloudFoundryOperationsUtils.class); - assertThat(context).doesNotHaveBean(ConnectionContext.class); - assertThat(context).doesNotHaveBean(TokenProvider.class); - }); + this.contextRunner.run((context) -> { + assertThat(context).doesNotHaveBean(CloudFoundryTargetProperties.class); + assertThat(context).doesNotHaveBean(CloudFoundryDeploymentProperties.class); + assertThat(context).doesNotHaveBean(ReactorCloudFoundryClient.class); + assertThat(context).doesNotHaveBean(ReactorDopplerClient.class); + assertThat(context).doesNotHaveBean(ReactorUaaClient.class); + assertThat(context).doesNotHaveBean(CloudFoundryOperations.class); + assertThat(context).doesNotHaveBean(CloudFoundryOperationsUtils.class); + assertThat(context).doesNotHaveBean(ConnectionContext.class); + assertThat(context).doesNotHaveBean(TokenProvider.class); + }); } } diff --git a/spring-cloud-app-broker-autoconfigure/src/test/java/org/springframework/cloud/appbroker/autoconfigure/ServiceInstanceLogStreamAutoConfigurationTest.java b/spring-cloud-app-broker-autoconfigure/src/test/java/org/springframework/cloud/appbroker/autoconfigure/ServiceInstanceLogStreamAutoConfigurationTests.java similarity index 67% rename from spring-cloud-app-broker-autoconfigure/src/test/java/org/springframework/cloud/appbroker/autoconfigure/ServiceInstanceLogStreamAutoConfigurationTest.java rename to spring-cloud-app-broker-autoconfigure/src/test/java/org/springframework/cloud/appbroker/autoconfigure/ServiceInstanceLogStreamAutoConfigurationTests.java index 49cb131..18184cf 100644 --- a/spring-cloud-app-broker-autoconfigure/src/test/java/org/springframework/cloud/appbroker/autoconfigure/ServiceInstanceLogStreamAutoConfigurationTest.java +++ b/spring-cloud-app-broker-autoconfigure/src/test/java/org/springframework/cloud/appbroker/autoconfigure/ServiceInstanceLogStreamAutoConfigurationTests.java @@ -33,27 +33,20 @@ import org.springframework.web.reactive.socket.server.support.WebSocketHandlerAd import static org.assertj.core.api.Assertions.assertThat; -class ServiceInstanceLogStreamAutoConfigurationTest { +class ServiceInstanceLogStreamAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of( - AppBrokerAutoConfiguration.class, - CloudFoundryAppDeployerAutoConfiguration.class, - ServiceInstanceLogStreamAutoConfiguration.class - )) - .withPropertyValues( - "spring.cloud.appbroker.deployer.cloudfoundry.api-host=https://api.example.local", - "spring.cloud.appbroker.deployer.cloudfoundry.username=user", - "spring.cloud.appbroker.deployer.cloudfoundry.password=secret" - ); + .withConfiguration(AutoConfigurations.of(AppBrokerAutoConfiguration.class, + CloudFoundryAppDeployerAutoConfiguration.class, ServiceInstanceLogStreamAutoConfiguration.class)) + .withPropertyValues("spring.cloud.appbroker.deployer.cloudfoundry.api-host=https://api.example.local", + "spring.cloud.appbroker.deployer.cloudfoundry.username=user", + "spring.cloud.appbroker.deployer.cloudfoundry.password=secret"); @Test void servicesAreNotCreatedWhenPublisherIsNotConfigured() { - contextRunner - .withClassLoader(new FilteredClassLoader(ApplicationLogStreamPublisher.class)) + this.contextRunner.withClassLoader(new FilteredClassLoader(ApplicationLogStreamPublisher.class)) .withUserConfiguration(LoggingConfiguration.class) - .run(context -> assertThat(context) - .doesNotHaveBean(StreamingLogWebSocketHandler.class) + .run((context) -> assertThat(context).doesNotHaveBean(StreamingLogWebSocketHandler.class) .doesNotHaveBean(WebSocketHandlerAdapter.class) .doesNotHaveBean(HandlerMapping.class) .doesNotHaveBean(LogStreamPublisher.class) @@ -62,21 +55,17 @@ class ServiceInstanceLogStreamAutoConfigurationTest { @Test void servicesAreNotCreatedWhenLoggingIsNotConfigured() { - contextRunner - .run(context -> assertThat(context) - .doesNotHaveBean(StreamingLogWebSocketHandler.class) - .doesNotHaveBean(WebSocketHandlerAdapter.class) - .doesNotHaveBean(HandlerMapping.class) - .doesNotHaveBean(LogStreamPublisher.class) - .doesNotHaveBean(ApplicationLogStreamPublisher.class)); + this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(StreamingLogWebSocketHandler.class) + .doesNotHaveBean(WebSocketHandlerAdapter.class) + .doesNotHaveBean(HandlerMapping.class) + .doesNotHaveBean(LogStreamPublisher.class) + .doesNotHaveBean(ApplicationLogStreamPublisher.class)); } @Test void servicesAreCreatedWithLoggingConfigured() { - contextRunner - .withUserConfiguration(LoggingConfiguration.class) - .run(context -> assertThat(context) - .hasSingleBean(StreamingLogWebSocketHandler.class) + this.contextRunner.withUserConfiguration(LoggingConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(StreamingLogWebSocketHandler.class) .hasSingleBean(WebSocketHandlerAdapter.class) .hasSingleBean(HandlerMapping.class) .hasSingleBean(LogStreamPublisher.class) @@ -88,7 +77,7 @@ class ServiceInstanceLogStreamAutoConfigurationTest { @Bean public ApplicationIdsProvider applicationIdsProvider() { - return serviceInstanceId -> Flux.just("app1"); + return (serviceInstanceId) -> Flux.just("app1"); } } diff --git a/spring-cloud-app-broker-autoconfigure/src/test/java/org/springframework/cloud/appbroker/autoconfigure/ServiceInstanceRecentLogsAutoConfigurationTest.java b/spring-cloud-app-broker-autoconfigure/src/test/java/org/springframework/cloud/appbroker/autoconfigure/ServiceInstanceRecentLogsAutoConfigurationTests.java similarity index 66% rename from spring-cloud-app-broker-autoconfigure/src/test/java/org/springframework/cloud/appbroker/autoconfigure/ServiceInstanceRecentLogsAutoConfigurationTest.java rename to spring-cloud-app-broker-autoconfigure/src/test/java/org/springframework/cloud/appbroker/autoconfigure/ServiceInstanceRecentLogsAutoConfigurationTests.java index e523d1a..fa425c3 100644 --- a/spring-cloud-app-broker-autoconfigure/src/test/java/org/springframework/cloud/appbroker/autoconfigure/ServiceInstanceRecentLogsAutoConfigurationTest.java +++ b/spring-cloud-app-broker-autoconfigure/src/test/java/org/springframework/cloud/appbroker/autoconfigure/ServiceInstanceRecentLogsAutoConfigurationTests.java @@ -31,44 +31,33 @@ import org.springframework.context.annotation.Bean; import static org.assertj.core.api.Assertions.assertThat; -class ServiceInstanceRecentLogsAutoConfigurationTest { +class ServiceInstanceRecentLogsAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of( - AppBrokerAutoConfiguration.class, - CloudFoundryAppDeployerAutoConfiguration.class, - ServiceInstanceRecentLogsAutoConfiguration.class - )) - .withPropertyValues( - "spring.cloud.appbroker.deployer.cloudfoundry.api-host=https://api.example.local", - "spring.cloud.appbroker.deployer.cloudfoundry.username=user", - "spring.cloud.appbroker.deployer.cloudfoundry.password=secret" - ); + .withConfiguration(AutoConfigurations.of(AppBrokerAutoConfiguration.class, + CloudFoundryAppDeployerAutoConfiguration.class, ServiceInstanceRecentLogsAutoConfiguration.class)) + .withPropertyValues("spring.cloud.appbroker.deployer.cloudfoundry.api-host=https://api.example.local", + "spring.cloud.appbroker.deployer.cloudfoundry.username=user", + "spring.cloud.appbroker.deployer.cloudfoundry.password=secret"); @Test void servicesAreNotCreatedWithoutLoggingOnClasspath() { - contextRunner - .withClassLoader(new FilteredClassLoader(ApplicationRecentLogsProvider.class)) + this.contextRunner.withClassLoader(new FilteredClassLoader(ApplicationRecentLogsProvider.class)) .withUserConfiguration(LoggingConfiguration.class) - .run(context -> assertThat(context) - .doesNotHaveBean(RecentLogsProvider.class) + .run((context) -> assertThat(context).doesNotHaveBean(RecentLogsProvider.class) .doesNotHaveBean(RecentLogsController.class)); } @Test void servicesAreNotCreatedWithoutRequiredBeansOnClasspath() { - contextRunner - .run(context -> assertThat(context) - .doesNotHaveBean(RecentLogsProvider.class) - .doesNotHaveBean(RecentLogsController.class)); + this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(RecentLogsProvider.class) + .doesNotHaveBean(RecentLogsController.class)); } @Test void servicesAreCreatedWithLoggingConfigured() { - contextRunner - .withUserConfiguration(LoggingConfiguration.class) - .run(context -> assertThat(context) - .hasSingleBean(RecentLogsProvider.class) + this.contextRunner.withUserConfiguration(LoggingConfiguration.class) + .run((context) -> assertThat(context).hasSingleBean(RecentLogsProvider.class) .hasSingleBean(RecentLogsController.class)); } @@ -77,7 +66,7 @@ class ServiceInstanceRecentLogsAutoConfigurationTest { @Bean public ApplicationIdsProvider applicationIdsProvider() { - return serviceInstanceId -> Flux.just("app1"); + return (serviceInstanceId) -> Flux.just("app1"); } } diff --git a/spring-cloud-app-broker-core/build.gradle b/spring-cloud-app-broker-core/build.gradle index 2b117b5..0c191ba 100644 --- a/spring-cloud-app-broker-core/build.gradle +++ b/spring-cloud-app-broker-core/build.gradle @@ -1,7 +1,7 @@ import org.springframework.boot.gradle.plugin.SpringBootPlugin /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/BackingAppDeploymentService.java b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/BackingAppDeploymentService.java index d7426bb..becf165 100644 --- a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/BackingAppDeploymentService.java +++ b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/BackingAppDeploymentService.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,45 +21,52 @@ import java.util.List; import reactor.core.publisher.Flux; /** - * This interface is implemented by service brokers to process requests to deploy, update, and undeploy backing - * applications associated with a service instance. + * This interface is implemented by service brokers to process requests to deploy, update, + * and undeploy backing applications associated with a service instance. + * + * @author Scott Frederick + * @author Roy Clarkson + * @author Oliver Hughes + * @author Alexey Nesterov + * @author Gareth Clay */ public interface BackingAppDeploymentService { /** - * Deploy the backing applications and associate with the service instance - * + * Deploy the backing applications and associate with the service instance. * @param backingApps a collection of backing applications * @param serviceInstanceId the service instance ID - * @return a set of strings, where each corresponds to an application e.g. the application name + * @return a set of strings, where each corresponds to an application e.g. the + * application name */ Flux deploy(List backingApps, String serviceInstanceId); /** - * Performs any steps necessary prior to backing application and backing service updates - * + * Performs any steps necessary prior to backing application and backing service + * updates. * @param backingApps a collection of backing applications * @param serviceInstanceId the service instance ID - * @return a set of strings, where each corresponds to an application. e.g. the application name + * @return a set of strings, where each corresponds to an application. e.g. the + * application name */ default Flux prepareForUpdate(List backingApps, String serviceInstanceId) { return Flux.empty(); } /** - * Update the backing applications and associate with the service instance - * + * Update the backing applications and associate with the service instance. * @param backingApps a collection of backing applications * @param serviceInstanceId the service instance ID - * @return a set of strings, where each corresponds to an application. e.g. the application name + * @return a set of strings, where each corresponds to an application. e.g. the + * application name */ Flux update(List backingApps, String serviceInstanceId); /** - * Undeploy the backing applications - * + * Undeploy the backing applications. * @param backingApps a collection of backing applications - * @return a set of strings, where each corresponds to an application. e.g. the application name + * @return a set of strings, where each corresponds to an application. e.g. the + * application name */ Flux undeploy(List backingApps); diff --git a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/BackingApplication.java b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/BackingApplication.java index 036718c..30682b7 100644 --- a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/BackingApplication.java +++ b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/BackingApplication.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,7 +27,13 @@ import java.util.stream.Collectors; import org.springframework.util.CollectionUtils; /** - * An application deployed as part of the service provisioning process + * An application deployed as part of the service provisioning process. + * + * @author Scott Frederick + * @author Roy Clarkson + * @author Oliver Hughes + * @author Alexey Nesterov + * @author Alberto Rios */ public class BackingApplication { @@ -49,8 +55,7 @@ public class BackingApplication { } /** - * Construct a new {@link BackingApplication} - * + * Construct a new {@link BackingApplication}. * @param name the name of the application * @param path the path to the application * @param properties the properties @@ -58,11 +63,8 @@ public class BackingApplication { * @param services the services required by the application * @param parametersTransformers the parameter transformers */ - public BackingApplication(String name, String path, - Map properties, - Map environment, - List services, - List parametersTransformers) { + public BackingApplication(String name, String path, Map properties, Map environment, + List services, List parametersTransformers) { this.name = name; this.path = path; this.properties = properties; @@ -72,7 +74,7 @@ public class BackingApplication { } public String getName() { - return name; + return this.name; } public void setName(String name) { @@ -80,7 +82,7 @@ public class BackingApplication { } public String getPath() { - return path; + return this.path; } public void setPath(String path) { @@ -88,7 +90,7 @@ public class BackingApplication { } public Map getProperties() { - return properties; + return this.properties; } public void setProperties(Map properties) { @@ -96,8 +98,7 @@ public class BackingApplication { } /** - * Add a single property - * + * Add a single property. * @param key the key * @param value the value */ @@ -106,7 +107,7 @@ public class BackingApplication { } public Map getEnvironment() { - return environment; + return this.environment; } public void setEnvironment(Map environment) { @@ -114,17 +115,16 @@ public class BackingApplication { } /** - * Add a single environment value - * + * Add a single environment value. * @param key the key * @param value the value */ public void addEnvironment(String key, Object value) { - environment.put(key, value); + this.environment.put(key, value); } public List getServices() { - return services; + return this.services; } public void setServices(List services) { @@ -132,7 +132,7 @@ public class BackingApplication { } public List getParametersTransformers() { - return parametersTransformers; + return this.parametersTransformers; } public void setParametersTransformers(List parametersTransformers) { @@ -140,8 +140,8 @@ public class BackingApplication { } /** - * Create a builder that provides a fluent API for constructing a {@literal BackingApplication}. - * + * Create a builder that provides a fluent API for constructing a + * {@literal BackingApplication}. * @return the builder */ public static BackingApplicationBuilder builder() { @@ -157,29 +157,23 @@ public class BackingApplication { return false; } BackingApplication that = (BackingApplication) o; - return Objects.equals(name, that.name) && - Objects.equals(path, that.path) && - Objects.equals(properties, that.properties) && - Objects.equals(environment, that.environment) && - Objects.equals(services, that.services) && - Objects.equals(parametersTransformers, that.parametersTransformers); + return Objects.equals(this.name, that.name) && Objects.equals(this.path, that.path) + && Objects.equals(this.properties, that.properties) + && Objects.equals(this.environment, that.environment) && Objects.equals(this.services, that.services) + && Objects.equals(this.parametersTransformers, that.parametersTransformers); } @Override public final int hashCode() { - return Objects.hash(name, path, properties, environment, services, parametersTransformers); + return Objects.hash(this.name, this.path, this.properties, this.environment, this.services, + this.parametersTransformers); } @Override public String toString() { - return "BackingApplication{" + - "name='" + name + '\'' + - ", path='" + path + '\'' + - ", properties=" + properties + - ", environment=" + sanitizeEnvironment(environment) + - ", services=" + services + - ", parametersTransformers=" + parametersTransformers + - '}'; + return "BackingApplication{" + "name='" + this.name + '\'' + ", path='" + this.path + '\'' + ", properties=" + + this.properties + ", environment=" + sanitizeEnvironment(this.environment) + ", services=" + + this.services + ", parametersTransformers=" + this.parametersTransformers + '}'; } private Map sanitizeEnvironment(Map environment) { @@ -214,8 +208,7 @@ public class BackingApplication { } /** - * Build a backing application based on another application definition - * + * Build a backing application based on another application definition. * @param backingApplication the backing application from which to copy properties * @return the builder */ @@ -225,25 +218,22 @@ public class BackingApplication { .properties(backingApplication.getProperties()) .environment(backingApplication.getEnvironment()); if (!CollectionUtils.isEmpty(backingApplication.getServices())) { - this.services(backingApplication.getServices().stream() - .map(spec -> ServicesSpec.builder() - .spec(spec) - .build()) + this.services(backingApplication.getServices() + .stream() + .map((spec) -> ServicesSpec.builder().spec(spec).build()) .collect(Collectors.toList())); } if (!CollectionUtils.isEmpty(backingApplication.getParametersTransformers())) { - this.parameterTransformers(backingApplication.getParametersTransformers().stream() - .map(spec -> ParametersTransformerSpec.builder() - .spec(spec) - .build()) + this.parameterTransformers(backingApplication.getParametersTransformers() + .stream() + .map((spec) -> ParametersTransformerSpec.builder().spec(spec).build()) .collect(Collectors.toList())); } return this; } /** - * The name of the application - * + * The name of the application. * @param name the name * @return the builder */ @@ -253,8 +243,7 @@ public class BackingApplication { } /** - * The path to the application - * + * The path to the application. * @param path the path * @return the builder */ @@ -264,8 +253,7 @@ public class BackingApplication { } /** - * Properties that describe the application - * + * Properties that describe the application. * @param key the property key * @param value the property value * @return the builder @@ -278,8 +266,7 @@ public class BackingApplication { } /** - * Properties that describe the application - * + * Properties that describe the application. * @param properties the properties * @return the builder */ @@ -291,8 +278,7 @@ public class BackingApplication { } /** - * Environment variables to be set for the application - * + * Environment variables to be set for the application. * @param key the env var key * @param value the env var value * @return the builder @@ -305,8 +291,7 @@ public class BackingApplication { } /** - * Environment variables to be set for the application - * + * Environment variables to be set for the application. * @param environment the env vars * @return the builder */ @@ -318,8 +303,7 @@ public class BackingApplication { } /** - * Services required by the application - * + * Services required by the application. * @param services the services * @return the builder */ @@ -331,8 +315,7 @@ public class BackingApplication { } /** - * Services required by the application - * + * Services required by the application. * @param services the services * @return the builder */ @@ -344,8 +327,7 @@ public class BackingApplication { } /** - * Parameter transformers for the application - * + * Parameter transformers for the application. * @param parameterTransformers the parameter transformers * @return the builder */ @@ -357,8 +339,7 @@ public class BackingApplication { } /** - * Parameter transformers for the application - * + * Parameter transformers for the application. * @param parameterTransformers the parameter transformers * @return the builder */ @@ -371,11 +352,11 @@ public class BackingApplication { /** * Construct a {@link BackingApplication} from the provided values. - * * @return the newly constructed {@literal BackingApplication} */ public BackingApplication build() { - return new BackingApplication(name, path, properties, environment, services, parameterTransformers); + return new BackingApplication(this.name, this.path, this.properties, this.environment, this.services, + this.parameterTransformers); } } diff --git a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/BackingApplications.java b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/BackingApplications.java index 65801d2..e0f3440 100644 --- a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/BackingApplications.java +++ b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/BackingApplications.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,15 +51,14 @@ public class BackingApplications extends ArrayList { public BackingApplicationsBuilder backingApplications(List backingApplications) { if (!CollectionUtils.isEmpty(backingApplications)) { - backingApplications.forEach(backingApplication -> this.backingApplication(BackingApplication.builder() - .backingApplication(backingApplication) - .build())); + backingApplications.forEach((backingApplication) -> this + .backingApplication(BackingApplication.builder().backingApplication(backingApplication).build())); } return this; } public BackingApplications build() { - return new BackingApplications(backingApplications); + return new BackingApplications(this.backingApplications); } } diff --git a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/BackingService.java b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/BackingService.java index ca7edbe..e111be3 100644 --- a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/BackingService.java +++ b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/BackingService.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,13 +45,9 @@ public class BackingService { private BackingService() { } - public BackingService(String serviceInstanceName, - String name, - String plan, - Map parameters, - Map properties, - List parametersTransformers, - boolean rebindOnUpdate) { + public BackingService(String serviceInstanceName, String name, String plan, Map parameters, + Map properties, List parametersTransformers, + boolean rebindOnUpdate) { this.serviceInstanceName = serviceInstanceName; this.name = name; this.plan = plan; @@ -62,7 +58,7 @@ public class BackingService { } public String getServiceInstanceName() { - return serviceInstanceName; + return this.serviceInstanceName; } public void setServiceInstanceName(String serviceInstanceName) { @@ -70,7 +66,7 @@ public class BackingService { } public String getName() { - return name; + return this.name; } public void setName(String name) { @@ -78,7 +74,7 @@ public class BackingService { } public String getPlan() { - return plan; + return this.plan; } public void setPlan(String plan) { @@ -86,7 +82,7 @@ public class BackingService { } public Map getParameters() { - return parameters; + return this.parameters; } public void setParameters(Map parameters) { @@ -94,11 +90,11 @@ public class BackingService { } public void addParameter(String key, Object value) { - parameters.put(key, value); + this.parameters.put(key, value); } public Map getProperties() { - return properties; + return this.properties; } public void setProperties(Map properties) { @@ -106,7 +102,7 @@ public class BackingService { } public List getParametersTransformers() { - return parametersTransformers; + return this.parametersTransformers; } public void setParametersTransformers(List parametersTransformers) { @@ -114,7 +110,7 @@ public class BackingService { } public boolean isRebindOnUpdate() { - return rebindOnUpdate; + return this.rebindOnUpdate; } public void setRebindOnUpdate(boolean rebindOnUpdate) { @@ -123,10 +119,10 @@ public class BackingService { public int serviceInstanceNameAndSpaceHashCode() { String space = null; - if (!CollectionUtils.isEmpty(properties)) { - space = properties.get(DeploymentProperties.TARGET_PROPERTY_KEY); + if (!CollectionUtils.isEmpty(this.properties)) { + space = this.properties.get(DeploymentProperties.TARGET_PROPERTY_KEY); } - return Objects.hash(serviceInstanceName, space); + return Objects.hash(this.serviceInstanceName, space); } @Override @@ -138,32 +134,25 @@ public class BackingService { return false; } BackingService that = (BackingService) o; - return Objects.equals(serviceInstanceName, that.serviceInstanceName) && - Objects.equals(name, that.name) && - Objects.equals(plan, that.plan) && - Objects.equals(parameters, that.parameters) && - Objects.equals(properties, that.properties) && - Objects.equals(parametersTransformers, that.parametersTransformers) && - rebindOnUpdate == that.rebindOnUpdate; + return Objects.equals(this.serviceInstanceName, that.serviceInstanceName) + && Objects.equals(this.name, that.name) && Objects.equals(this.plan, that.plan) + && Objects.equals(this.parameters, that.parameters) && Objects.equals(this.properties, that.properties) + && Objects.equals(this.parametersTransformers, that.parametersTransformers) + && this.rebindOnUpdate == that.rebindOnUpdate; } @Override public int hashCode() { - return Objects - .hash(serviceInstanceName, name, plan, parameters, properties, parametersTransformers, rebindOnUpdate); + return Objects.hash(this.serviceInstanceName, this.name, this.plan, this.parameters, this.properties, + this.parametersTransformers, this.rebindOnUpdate); } @Override public String toString() { - return "BackingService{" + - "serviceInstanceName='" + serviceInstanceName + '\'' + - ", name='" + name + '\'' + - ", plan='" + plan + '\'' + - ", parameters=" + parameters + - ", properties=" + properties + - ", parametersTransformers=" + parametersTransformers + - ", rebindOnUpdate=" + rebindOnUpdate + - '}'; + return "BackingService{" + "serviceInstanceName='" + this.serviceInstanceName + '\'' + ", name='" + this.name + + '\'' + ", plan='" + this.plan + '\'' + ", parameters=" + this.parameters + ", properties=" + + this.properties + ", parametersTransformers=" + this.parametersTransformers + ", rebindOnUpdate=" + + this.rebindOnUpdate + '}'; } public static BackingServiceBuilder builder() { @@ -248,8 +237,8 @@ public class BackingService { } public BackingService build() { - return new BackingService(serviceInstanceName, name, plan, parameters, properties, parameterTransformers, - rebindOnUpdate); + return new BackingService(this.serviceInstanceName, this.name, this.plan, this.parameters, this.properties, + this.parameterTransformers, this.rebindOnUpdate); } } diff --git a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/BackingServices.java b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/BackingServices.java index 9aee30d..c430991 100644 --- a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/BackingServices.java +++ b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/BackingServices.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,15 +50,14 @@ public class BackingServices extends ArrayList { public BackingServicesBuilder backingServices(BackingServices backingServices) { if (!CollectionUtils.isEmpty(backingServices)) { - backingServices.forEach(backingService -> this.backingService(BackingService.builder() - .backingService(backingService) - .build())); + backingServices.forEach((backingService) -> this + .backingService(BackingService.builder().backingService(backingService).build())); } return this; } public BackingServices build() { - return new BackingServices(backingServices); + return new BackingServices(this.backingServices); } } diff --git a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/BackingServicesProvisionService.java b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/BackingServicesProvisionService.java index 7a9a239..8422ecf 100644 --- a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/BackingServicesProvisionService.java +++ b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/BackingServicesProvisionService.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/BackingSpaceManagementService.java b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/BackingSpaceManagementService.java index 41ad96e..0ad22ef 100644 --- a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/BackingSpaceManagementService.java +++ b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/BackingSpaceManagementService.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2021 the original author or authors. + * Copyright 2016-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/BrokeredService.java b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/BrokeredService.java index bb1a577..471a71a 100644 --- a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/BrokeredService.java +++ b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/BrokeredService.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,7 +37,7 @@ public class BrokeredService { } public BrokeredService(String serviceName, String planName, BackingApplications apps, BackingServices services, - TargetSpec target) { + TargetSpec target) { super(); this.serviceName = serviceName; this.planName = planName; @@ -47,7 +47,7 @@ public class BrokeredService { } public String getServiceName() { - return serviceName; + return this.serviceName; } public void setServiceName(String serviceName) { @@ -55,7 +55,7 @@ public class BrokeredService { } public String getPlanName() { - return planName; + return this.planName; } public void setPlanName(String planName) { @@ -63,7 +63,7 @@ public class BrokeredService { } public BackingApplications getApps() { - return apps; + return this.apps; } public void setApps(BackingApplications apps) { @@ -71,7 +71,7 @@ public class BrokeredService { } public BackingServices getServices() { - return services; + return this.services; } public void setServices(BackingServices services) { @@ -79,7 +79,7 @@ public class BrokeredService { } public TargetSpec getTarget() { - return target; + return this.target; } public void setTarget(TargetSpec target) { @@ -99,27 +99,20 @@ public class BrokeredService { return false; } BrokeredService that = (BrokeredService) o; - return Objects.equals(serviceName, that.serviceName) && - Objects.equals(planName, that.planName) && - Objects.equals(apps, that.apps) && - Objects.equals(services, that.services) && - Objects.equals(target, that.target); + return Objects.equals(this.serviceName, that.serviceName) && Objects.equals(this.planName, that.planName) + && Objects.equals(this.apps, that.apps) && Objects.equals(this.services, that.services) + && Objects.equals(this.target, that.target); } @Override public final int hashCode() { - return Objects.hash(serviceName, planName, apps, services, target); + return Objects.hash(this.serviceName, this.planName, this.apps, this.services, this.target); } @Override public String toString() { - return "BrokeredService{" + - "serviceName='" + serviceName + '\'' + - ", planName='" + planName + '\'' + - ", apps=" + apps + - ", services=" + services + - ", target=" + target + - '}'; + return "BrokeredService{" + "serviceName='" + this.serviceName + '\'' + ", planName='" + this.planName + '\'' + + ", apps=" + this.apps + ", services=" + this.services + ", target=" + this.target + '}'; } public static class BrokeredServiceBuilder { @@ -155,9 +148,7 @@ public class BrokeredService { public BrokeredServiceBuilder services(BackingServices backingServices) { if (!CollectionUtils.isEmpty(backingServices)) { - this.backingServices = BackingServices.builder() - .backingServices(backingServices) - .build(); + this.backingServices = BackingServices.builder().backingServices(backingServices).build(); } return this; } @@ -168,7 +159,8 @@ public class BrokeredService { } public BrokeredService build() { - return new BrokeredService(id, planId, backingApplications, backingServices, target); + return new BrokeredService(this.id, this.planId, this.backingApplications, this.backingServices, + this.target); } } diff --git a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/BrokeredServices.java b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/BrokeredServices.java index dc4dd3e..6663fc1 100644 --- a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/BrokeredServices.java +++ b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/BrokeredServices.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -56,7 +56,7 @@ public class BrokeredServices extends ArrayList { } public BrokeredServices build() { - return new BrokeredServices(brokeredServices); + return new BrokeredServices(this.brokeredServices); } } diff --git a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/DefaultBackingAppDeploymentService.java b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/DefaultBackingAppDeploymentService.java index 911cbe1..2dd2c9c 100644 --- a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/DefaultBackingAppDeploymentService.java +++ b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/DefaultBackingAppDeploymentService.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,9 +40,9 @@ public class DefaultBackingAppDeploymentService implements BackingAppDeploymentS return Flux.fromIterable(backingApps) .parallel() .runOn(Schedulers.parallel()) - .flatMap(backingApplication -> deployerClient.deploy(backingApplication, serviceInstanceId)) + .flatMap((backingApplication) -> this.deployerClient.deploy(backingApplication, serviceInstanceId)) .sequential() - .doOnRequest(l -> { + .doOnRequest((l) -> { LOG.info("Deploying applications"); LOG.debug(BACKINGAPPS_LOG_TEMPLATE, backingApps); }) @@ -50,7 +50,7 @@ public class DefaultBackingAppDeploymentService implements BackingAppDeploymentS LOG.info("Finish deploying applications"); LOG.debug(BACKINGAPPS_LOG_TEMPLATE, backingApps); }) - .doOnError(e -> { + .doOnError((e) -> { LOG.error(String.format("Error deploying applications. error=%s", e.getMessage()), e); LOG.debug(BACKINGAPPS_LOG_TEMPLATE, backingApps); }); @@ -61,9 +61,9 @@ public class DefaultBackingAppDeploymentService implements BackingAppDeploymentS return Flux.fromIterable(backingApps) .parallel() .runOn(Schedulers.parallel()) - .flatMap(backingApplication -> deployerClient.preUpdate(backingApplication, serviceInstanceId)) + .flatMap((backingApplication) -> this.deployerClient.preUpdate(backingApplication, serviceInstanceId)) .sequential() - .doOnRequest(l -> { + .doOnRequest((l) -> { LOG.info("Preparing applications for update"); LOG.debug(BACKINGAPPS_LOG_TEMPLATE, backingApps); }) @@ -71,7 +71,7 @@ public class DefaultBackingAppDeploymentService implements BackingAppDeploymentS LOG.info("Finish preparing applications for update"); LOG.debug(BACKINGAPPS_LOG_TEMPLATE, backingApps); }) - .doOnError(e -> { + .doOnError((e) -> { LOG.error(String.format("Error preparing applications for update. error=%s", e.getMessage()), e); LOG.debug(BACKINGAPPS_LOG_TEMPLATE, backingApps); }); @@ -82,9 +82,9 @@ public class DefaultBackingAppDeploymentService implements BackingAppDeploymentS return Flux.fromIterable(backingApps) .parallel() .runOn(Schedulers.parallel()) - .flatMap(backingApplication -> deployerClient.update(backingApplication, serviceInstanceId)) + .flatMap((backingApplication) -> this.deployerClient.update(backingApplication, serviceInstanceId)) .sequential() - .doOnRequest(l -> { + .doOnRequest((l) -> { LOG.info("Updating applications"); LOG.debug(BACKINGAPPS_LOG_TEMPLATE, backingApps); }) @@ -92,7 +92,7 @@ public class DefaultBackingAppDeploymentService implements BackingAppDeploymentS LOG.info("Finish updating applications"); LOG.debug(BACKINGAPPS_LOG_TEMPLATE, backingApps); }) - .doOnError(e -> { + .doOnError((e) -> { LOG.error(String.format("Error updating applications. error=%s", e.getMessage()), e); LOG.debug(BACKINGAPPS_LOG_TEMPLATE, backingApps); }); @@ -103,9 +103,9 @@ public class DefaultBackingAppDeploymentService implements BackingAppDeploymentS return Flux.fromIterable(backingApps) .parallel() .runOn(Schedulers.parallel()) - .flatMap(deployerClient::undeploy) + .flatMap(this.deployerClient::undeploy) .sequential() - .doOnRequest(l -> { + .doOnRequest((l) -> { LOG.info("Undeploying applications"); LOG.debug(BACKINGAPPS_LOG_TEMPLATE, backingApps); }) @@ -113,7 +113,7 @@ public class DefaultBackingAppDeploymentService implements BackingAppDeploymentS LOG.info("Finish undeploying applications"); LOG.debug(BACKINGAPPS_LOG_TEMPLATE, backingApps); }) - .doOnError(e -> { + .doOnError((e) -> { LOG.error(String.format("Error undeploying applications. error=%s", e.getMessage()), e); LOG.debug(BACKINGAPPS_LOG_TEMPLATE, backingApps); }); diff --git a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/DefaultBackingServicesProvisionService.java b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/DefaultBackingServicesProvisionService.java index 0174cd8..16e4fc4 100644 --- a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/DefaultBackingServicesProvisionService.java +++ b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/DefaultBackingServicesProvisionService.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,9 +40,9 @@ public class DefaultBackingServicesProvisionService implements BackingServicesPr return Flux.fromIterable(backingServices) .parallel() .runOn(Schedulers.parallel()) - .flatMap(deployerClient::createServiceInstance) + .flatMap(this.deployerClient::createServiceInstance) .sequential() - .doOnRequest(l -> { + .doOnRequest((l) -> { LOG.info("Creating backing services"); LOG.debug(BACKINGSERVICES_LOG_TEMPLATE, backingServices); }) @@ -50,7 +50,7 @@ public class DefaultBackingServicesProvisionService implements BackingServicesPr LOG.info("Finish creating backing services"); LOG.debug(BACKINGSERVICES_LOG_TEMPLATE, backingServices); }) - .doOnError(e -> LOG.error(String.format("Error creating backing services. error=%s", e.getMessage()), e)); + .doOnError((e) -> LOG.error(String.format("Error creating backing services. error=%s", e.getMessage()), e)); } @Override @@ -58,9 +58,9 @@ public class DefaultBackingServicesProvisionService implements BackingServicesPr return Flux.fromIterable(backingServices) .parallel() .runOn(Schedulers.parallel()) - .flatMap(deployerClient::updateServiceInstance) + .flatMap(this.deployerClient::updateServiceInstance) .sequential() - .doOnRequest(l -> { + .doOnRequest((l) -> { LOG.info("Updating backing services"); LOG.debug(BACKINGSERVICES_LOG_TEMPLATE, backingServices); }) @@ -68,7 +68,7 @@ public class DefaultBackingServicesProvisionService implements BackingServicesPr LOG.info("Finish updating backing services"); LOG.debug(BACKINGSERVICES_LOG_TEMPLATE, backingServices); }) - .doOnError(e -> LOG.error(String.format("Error updating backing services. error=%s", e.getMessage()), e)); + .doOnError((e) -> LOG.error(String.format("Error updating backing services. error=%s", e.getMessage()), e)); } @Override @@ -76,9 +76,9 @@ public class DefaultBackingServicesProvisionService implements BackingServicesPr return Flux.fromIterable(backingServices) .parallel() .runOn(Schedulers.parallel()) - .flatMap(deployerClient::deleteServiceInstance) + .flatMap(this.deployerClient::deleteServiceInstance) .sequential() - .doOnRequest(l -> { + .doOnRequest((l) -> { LOG.info("Deleting backing services"); LOG.debug(BACKINGSERVICES_LOG_TEMPLATE, backingServices); }) @@ -86,7 +86,7 @@ public class DefaultBackingServicesProvisionService implements BackingServicesPr LOG.info("Finish deleting backing services"); LOG.debug(BACKINGSERVICES_LOG_TEMPLATE, backingServices); }) - .doOnError(e -> LOG.error(String.format("Error deleting backing services. error=%s", e.getMessage()), e)); + .doOnError((e) -> LOG.error(String.format("Error deleting backing services. error=%s", e.getMessage()), e)); } } diff --git a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/DefaultBackingSpaceManagementService.java b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/DefaultBackingSpaceManagementService.java index 31219a2..7f5377c 100644 --- a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/DefaultBackingSpaceManagementService.java +++ b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/DefaultBackingSpaceManagementService.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2021 the original author or authors. + * Copyright 2016-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,9 +40,9 @@ public class DefaultBackingSpaceManagementService implements BackingSpaceManagem return Flux.fromIterable(targetSpaces) .parallel() .runOn(Schedulers.parallel()) - .flatMap(deployerClient::deleteSpace) + .flatMap(this.deployerClient::deleteSpace) .sequential() - .doOnRequest(l -> { + .doOnRequest((l) -> { LOG.info("Deleting backing spaces"); LOG.debug(BACKINGSPACES_LOG_TEMPLATE, targetSpaces); }) @@ -50,7 +50,7 @@ public class DefaultBackingSpaceManagementService implements BackingSpaceManagem LOG.info("Finish deleting backing spaces"); LOG.debug(BACKINGSPACES_LOG_TEMPLATE, targetSpaces); }) - .doOnError(e -> LOG.error(String.format("Error deleting backing spaces. error=%s", e.getMessage()), e)); + .doOnError((e) -> LOG.error(String.format("Error deleting backing spaces. error=%s", e.getMessage()), e)); } } diff --git a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/DeployerClient.java b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/DeployerClient.java index 508592a..36d3cbe 100644 --- a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/DeployerClient.java +++ b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/DeployerClient.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2021 the original author or authors. + * Copyright 2016-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,209 +49,185 @@ public class DeployerClient { } public Mono deploy(BackingApplication backingApplication, String serviceInstanceId) { - return appDeployer - .deploy(DeployApplicationRequest - .builder() + return this.appDeployer + .deploy(DeployApplicationRequest.builder() .name(backingApplication.getName()) .path(backingApplication.getPath()) .properties(backingApplication.getProperties()) .environment(backingApplication.getEnvironment()) - .services(backingApplication.getServices().stream() + .services(backingApplication.getServices() + .stream() .map(ServicesSpec::getServiceInstanceName) .collect(Collectors.toList())) .serviceInstanceId(serviceInstanceId) .build()) - .doOnRequest(l -> { + .doOnRequest((l) -> { LOG.info("Deploying application. backingAppName={}", backingApplication.getName()); debugLog(backingApplication); }) - .doOnSuccess(response -> { + .doOnSuccess((response) -> { LOG.info("Success deploying application. backingAppName={}", backingApplication.getName()); debugLog(response, backingApplication); }) - .doOnError(e -> { + .doOnError((e) -> { LOG.error(String.format("Error deploying application. backingAppName=%s, error=%s", - backingApplication.getName(), e.getMessage()), e); + backingApplication.getName(), e.getMessage()), e); debugLog(backingApplication); }) .map(DeployApplicationResponse::getName); } public Mono preUpdate(BackingApplication backingApplication, String serviceInstanceId) { - return appDeployer.preUpdate(getUpdateApplicationRequest(backingApplication, serviceInstanceId)) - .doOnRequest(l -> { + return this.appDeployer.preUpdate(getUpdateApplicationRequest(backingApplication, serviceInstanceId)) + .doOnRequest((l) -> { LOG.info("Pre-updating application. backingAppName={}", backingApplication.getName()); debugLog(backingApplication); }) - .doOnSuccess(response -> { + .doOnSuccess((response) -> { LOG.info("Success pre-updating application. backingAppName={}", backingApplication.getName()); debugLog(response, backingApplication); }) - .doOnError(e -> { + .doOnError((e) -> { LOG.error(String.format("Error pre-updating application. backingAppName=%s, error=%s", - backingApplication.getName(), e.getMessage()), e); + backingApplication.getName(), e.getMessage()), e); debugLog(backingApplication); }) .map(UpdateApplicationResponse::getName); } public Mono update(BackingApplication backingApplication, String serviceInstanceId) { - return appDeployer - .update(getUpdateApplicationRequest(backingApplication, serviceInstanceId)) - .doOnRequest(l -> { + return this.appDeployer.update(getUpdateApplicationRequest(backingApplication, serviceInstanceId)) + .doOnRequest((l) -> { LOG.info("Updating application. backingAppName={}", backingApplication.getName()); debugLog(backingApplication); }) - .doOnSuccess(response -> { + .doOnSuccess((response) -> { LOG.info("Success updating application. backingAppName={}", backingApplication.getName()); debugLog(response, backingApplication); }) - .doOnError(e -> { + .doOnError((e) -> { LOG.error(String.format("Error updating application. backingAppName=%s, error=%s", - backingApplication.getName(), e.getMessage()), e); + backingApplication.getName(), e.getMessage()), e); debugLog(backingApplication); }) .map(UpdateApplicationResponse::getName); } public Mono undeploy(BackingApplication backingApplication) { - return appDeployer - .undeploy(UndeployApplicationRequest - .builder() + return this.appDeployer + .undeploy(UndeployApplicationRequest.builder() .properties(backingApplication.getProperties()) .name(backingApplication.getName()) .build()) - .doOnRequest(l -> { + .doOnRequest((l) -> { LOG.info("Undeploying application. backingAppName={}", backingApplication.getName()); debugLog(backingApplication); }) - .doOnSuccess(response -> { + .doOnSuccess((response) -> { LOG.info("Success undeploying application. backingAppName={}", backingApplication.getName()); debugLog(response, backingApplication); }) - .doOnError(e -> { + .doOnError((e) -> { LOG.error(String.format("Error undeploying application. backingAppName=%s, error=%s", - backingApplication.getName(), e.getMessage()), e); + backingApplication.getName(), e.getMessage()), e); debugLog(backingApplication); }) - .onErrorReturn(UndeployApplicationResponse.builder() - .name(backingApplication.getName()) - .build()) + .onErrorReturn(UndeployApplicationResponse.builder().name(backingApplication.getName()).build()) .map(UndeployApplicationResponse::getName); } public Mono createServiceInstance(BackingService backingService) { - return appDeployer - .createServiceInstance( - CreateServiceInstanceRequest - .builder() - .serviceInstanceName(backingService.getServiceInstanceName()) - .name(backingService.getName()) - .plan(backingService.getPlan()) - .parameters(backingService.getParameters()) - .properties(backingService.getProperties()) - .build()) - .doOnRequest(l -> { + return this.appDeployer + .createServiceInstance(CreateServiceInstanceRequest.builder() + .serviceInstanceName(backingService.getServiceInstanceName()) + .name(backingService.getName()) + .plan(backingService.getPlan()) + .parameters(backingService.getParameters()) + .properties(backingService.getProperties()) + .build()) + .doOnRequest((l) -> { LOG.info("Creating backing service {}", backingService.getName()); debugLog(backingService); }) - .doOnSuccess(response -> { + .doOnSuccess((response) -> { LOG.info("Success creating backing service {}", backingService.getName()); debugLog(response, backingService); }) - .doOnError(e -> { + .doOnError((e) -> { LOG.error(String.format("Error creating backing service. backingServiceName=%s, error=%s", - backingService.getName(), e.getMessage()), e); + backingService.getName(), e.getMessage()), e); debugLog(backingService); }) .map(CreateServiceInstanceResponse::getName); } public Mono updateServiceInstance(BackingService backingService) { - return appDeployer - .updateServiceInstance( - UpdateServiceInstanceRequest - .builder() - .serviceInstanceName(backingService.getServiceInstanceName()) - .parameters(backingService.getParameters()) - .properties(backingService.getProperties()) - .rebindOnUpdate(backingService.isRebindOnUpdate()) - .build()) - .doOnRequest(l -> { + return this.appDeployer + .updateServiceInstance(UpdateServiceInstanceRequest.builder() + .serviceInstanceName(backingService.getServiceInstanceName()) + .parameters(backingService.getParameters()) + .properties(backingService.getProperties()) + .rebindOnUpdate(backingService.isRebindOnUpdate()) + .build()) + .doOnRequest((l) -> { LOG.info("Updating backing service {}", backingService.getName()); debugLog(backingService); }) - .doOnSuccess(response -> { + .doOnSuccess((response) -> { LOG.info("Success updating backing service {}", backingService.getName()); debugLog(response, backingService); }) - .doOnError(e -> { + .doOnError((e) -> { LOG.error(String.format("Error updating backing service. backingServiceName=%s, error=%s", - backingService.getName(), e.getMessage()), e); + backingService.getName(), e.getMessage()), e); debugLog(backingService); }) .map(UpdateServiceInstanceResponse::getName); } public Mono deleteServiceInstance(BackingService backingService) { - return appDeployer - .deleteServiceInstance( - DeleteServiceInstanceRequest - .builder() - .serviceInstanceName(backingService.getServiceInstanceName()) - .properties(backingService.getProperties()) - .build()) - .doOnRequest(l -> { + return this.appDeployer + .deleteServiceInstance(DeleteServiceInstanceRequest.builder() + .serviceInstanceName(backingService.getServiceInstanceName()) + .properties(backingService.getProperties()) + .build()) + .doOnRequest((l) -> { LOG.info("Deleting backing service {}", backingService.getName()); debugLog(backingService); }) - .doOnSuccess(response -> { + .doOnSuccess((response) -> { LOG.info("Success deleting backing service {}", backingService.getName()); debugLog(response, backingService); }) - .doOnError(e -> { + .doOnError((e) -> { LOG.error(String.format("Error deleting backing service. backingServiceName=%s, error=%s", - backingService.getName(), e.getMessage()), e); + backingService.getName(), e.getMessage()), e); debugLog(backingService); }) - .onErrorReturn(DeleteServiceInstanceResponse.builder() - .name(backingService.getServiceInstanceName()) - .build()) + .onErrorReturn( + DeleteServiceInstanceResponse.builder().name(backingService.getServiceInstanceName()).build()) .map(DeleteServiceInstanceResponse::getName); } public Mono deleteSpace(String spaceName) { - return appDeployer - .deleteBackingSpace( - DeleteBackingSpaceRequest - .builder() - .name(spaceName) - .build()) - .doOnRequest(l -> { - LOG.info("Deleting backing space {}", spaceName); - }) - .doOnSuccess(response -> { - LOG.info("Success deleting backing space {}", spaceName); - }) - .doOnError(e -> { - LOG.error(String.format("Error deleting backing space. backingSpaceName=%s, error=%s", - spaceName, e.getMessage()), e); - }) - .onErrorReturn(DeleteBackingSpaceResponse.builder() - .name(spaceName) - .build()) + return this.appDeployer.deleteBackingSpace(DeleteBackingSpaceRequest.builder().name(spaceName).build()) + .doOnRequest((l) -> LOG.info("Deleting backing space {}", spaceName)) + .doOnSuccess((response) -> LOG.info("Success deleting backing space {}", spaceName)) + .doOnError((e) -> LOG.error(String.format("Error deleting backing space. backingSpaceName=%s, error=%s", + spaceName, e.getMessage()), e)) + .onErrorReturn(DeleteBackingSpaceResponse.builder().name(spaceName).build()) .map(DeleteBackingSpaceResponse::getName); } private static UpdateApplicationRequest getUpdateApplicationRequest(BackingApplication backingApplication, - String serviceInstanceId) { - return UpdateApplicationRequest - .builder() + String serviceInstanceId) { + return UpdateApplicationRequest.builder() .name(backingApplication.getName()) .path(backingApplication.getPath()) .properties(backingApplication.getProperties()) .environment(backingApplication.getEnvironment()) - .services(backingApplication.getServices().stream() + .services(backingApplication.getServices() + .stream() .map(ServicesSpec::getServiceInstanceName) .collect(Collectors.toList())) .serviceInstanceId(serviceInstanceId) @@ -273,4 +249,5 @@ public class DeployerClient { private static void debugLog(Object response, BackingService backingService) { LOG.debug("response={}, backingService={}", response, backingService); } + } diff --git a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/ParametersTransformerSpec.java b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/ParametersTransformerSpec.java index 4f73e23..dc42d4f 100644 --- a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/ParametersTransformerSpec.java +++ b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/ParametersTransformerSpec.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,7 +36,7 @@ public class ParametersTransformerSpec { } public String getName() { - return name; + return this.name; } public void setName(String name) { @@ -44,7 +44,7 @@ public class ParametersTransformerSpec { } public Map getArgs() { - return args; + return this.args; } public void setArgs(Map args) { @@ -65,8 +65,7 @@ public class ParametersTransformerSpec { } public ParametersTransformerSpecBuilder spec(ParametersTransformerSpec spec) { - return this.name(spec.getName()) - .args(spec.getArgs()); + return this.name(spec.getName()).args(spec.getArgs()); } public ParametersTransformerSpecBuilder name(String name) { @@ -89,7 +88,7 @@ public class ParametersTransformerSpec { } public ParametersTransformerSpec build() { - return new ParametersTransformerSpec(name, args); + return new ParametersTransformerSpec(this.name, this.args); } } diff --git a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/ServicesSpec.java b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/ServicesSpec.java index 6363af3..9aed816 100644 --- a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/ServicesSpec.java +++ b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/ServicesSpec.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,7 +30,7 @@ public class ServicesSpec { } public String getServiceInstanceName() { - return serviceInstanceName; + return this.serviceInstanceName; } public void setServiceInstanceName(String serviceInstanceName) { @@ -50,19 +50,17 @@ public class ServicesSpec { return false; } ServicesSpec that = (ServicesSpec) o; - return Objects.equals(serviceInstanceName, that.serviceInstanceName); + return Objects.equals(this.serviceInstanceName, that.serviceInstanceName); } @Override public int hashCode() { - return Objects.hash(serviceInstanceName); + return Objects.hash(this.serviceInstanceName); } @Override public String toString() { - return "ServicesSpec{" + - "serviceInstanceName='" + serviceInstanceName + '\'' + - '}'; + return "ServicesSpec{" + "serviceInstanceName='" + this.serviceInstanceName + '\'' + '}'; } public static final class ServicesSpecBuilder { @@ -82,7 +80,7 @@ public class ServicesSpec { } public ServicesSpec build() { - return new ServicesSpec(serviceInstanceName); + return new ServicesSpec(this.serviceInstanceName); } } diff --git a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/TargetSpec.java b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/TargetSpec.java index e60a965..3c17780 100644 --- a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/TargetSpec.java +++ b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/TargetSpec.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,14 +30,13 @@ public class TargetSpec { } public String getName() { - return name; + return this.name; } public void setName(String name) { this.name = name; } - public static TargetSpecBuilder builder() { return new TargetSpecBuilder(); } @@ -51,12 +50,12 @@ public class TargetSpec { return false; } TargetSpec that = (TargetSpec) o; - return Objects.equals(name, that.name); + return Objects.equals(this.name, that.name); } @Override public int hashCode() { - return Objects.hash(name); + return Objects.hash(this.name); } public static final class TargetSpecBuilder { @@ -70,9 +69,11 @@ public class TargetSpec { this.name = name; return this; } + public TargetSpec build() { - return new TargetSpec(name); + return new TargetSpec(this.name); } } + } diff --git a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/package-info.java b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/package-info.java new file mode 100644 index 0000000..ecc94e0 --- /dev/null +++ b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/deployer/package-info.java @@ -0,0 +1,20 @@ +/* + * Copyright 2016-2024 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * App Broker Deployer. + */ +package org.springframework.cloud.appbroker.deployer; diff --git a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/AbstractExtensionFactory.java b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/AbstractExtensionFactory.java index 962ab93..9a1b364 100644 --- a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/AbstractExtensionFactory.java +++ b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/AbstractExtensionFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/ExtensionFactory.java b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/ExtensionFactory.java index d675d36..0829ae4 100644 --- a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/ExtensionFactory.java +++ b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/ExtensionFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/ExtensionLocator.java b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/ExtensionLocator.java index 9091266..72739d9 100644 --- a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/ExtensionLocator.java +++ b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/ExtensionLocator.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,7 +28,7 @@ public class ExtensionLocator { private final Map> factoriesByName = new HashMap<>(); public ExtensionLocator(List> factories) { - factories.forEach(extension -> this.factoriesByName.put(extension.getName(), extension)); + factories.forEach((extension) -> this.factoriesByName.put(extension.getName(), extension)); } public T getByName(String name) { @@ -41,17 +41,16 @@ public class ExtensionLocator { } private ExtensionFactory getFactoryByName(String name) { - if (factoriesByName.containsKey(name)) { - return factoriesByName.get(name); + if (this.factoriesByName.containsKey(name)) { + return this.factoriesByName.get(name); } else { - throw new ServiceBrokerException("Unknown extension " + name + ". " + - "Registered extensions are " + factoriesByName.keySet()); + throw new ServiceBrokerException( + "Unknown extension " + name + ". " + "Registered extensions are " + this.factoriesByName.keySet()); } } - private T getExtensionFromFactory(ExtensionFactory factory, - Map args) { + private T getExtensionFromFactory(ExtensionFactory factory, Map args) { return factory.createWithConfig(args); } diff --git a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/package-info.java b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/package-info.java new file mode 100644 index 0000000..f902153 --- /dev/null +++ b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/package-info.java @@ -0,0 +1,20 @@ +/* + * Copyright 2016-2024 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * App Broker Extensions. + */ +package org.springframework.cloud.appbroker.extensions; diff --git a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/parameters/BackingApplicationsParametersTransformationService.java b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/parameters/BackingApplicationsParametersTransformationService.java index e5aae6a..a515b51 100644 --- a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/parameters/BackingApplicationsParametersTransformationService.java +++ b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/parameters/BackingApplicationsParametersTransformationService.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,30 +32,26 @@ public class BackingApplicationsParametersTransformationService { private final ExtensionLocator> locator; public BackingApplicationsParametersTransformationService( - List> factories) { - locator = new ExtensionLocator<>(factories); + List> factories) { + this.locator = new ExtensionLocator<>(factories); } public Mono> transformParameters(List backingApplications, - Map parameters) { - return Flux.fromIterable(backingApplications) - .flatMap(backingApplication -> { - List specs = getTransformerSpecsForApplication(backingApplication); + Map parameters) { + return Flux.fromIterable(backingApplications).flatMap((backingApplication) -> { + List specs = getTransformerSpecsForApplication(backingApplication); - return Flux.fromIterable(specs) - .flatMap(spec -> { - ParametersTransformer transformer = locator - .getByName(spec.getName(), spec.getArgs()); - return transformer.transform(backingApplication, parameters); - }) - .then(Mono.just(backingApplication)); - }) - .collectList(); + return Flux.fromIterable(specs).flatMap((spec) -> { + ParametersTransformer transformer = this.locator.getByName(spec.getName(), + spec.getArgs()); + return transformer.transform(backingApplication, parameters); + }).then(Mono.just(backingApplication)); + }).collectList(); } private List getTransformerSpecsForApplication(BackingApplication backingApplication) { - return backingApplication.getParametersTransformers() == null ? Collections.emptyList() : - backingApplication.getParametersTransformers(); + return (backingApplication.getParametersTransformers() == null) ? Collections.emptyList() + : backingApplication.getParametersTransformers(); } } diff --git a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/parameters/BackingServicesParametersTransformationService.java b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/parameters/BackingServicesParametersTransformationService.java index 7c0f2c4..56d5659 100644 --- a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/parameters/BackingServicesParametersTransformationService.java +++ b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/parameters/BackingServicesParametersTransformationService.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,31 +32,26 @@ public class BackingServicesParametersTransformationService { private final ExtensionLocator> locator; public BackingServicesParametersTransformationService( - List> factories) { - locator = new ExtensionLocator<>(factories); + List> factories) { + this.locator = new ExtensionLocator<>(factories); } public Mono> transformParameters(List backingServices, - Map parameters) { - return Flux.fromIterable(backingServices) - .flatMap(backingService -> { - List specs = getTransformerSpecsForService(backingService); + Map parameters) { + return Flux.fromIterable(backingServices).flatMap((backingService) -> { + List specs = getTransformerSpecsForService(backingService); - return Flux.fromIterable(specs) - .flatMap(spec -> { - ParametersTransformer transformer = locator - .getByName(spec.getName(), spec.getArgs()); - return transformer.transform(backingService, parameters); - }) - .then(Mono.just(backingService)); - }) - .collectList(); + return Flux.fromIterable(specs).flatMap((spec) -> { + ParametersTransformer transformer = this.locator.getByName(spec.getName(), + spec.getArgs()); + return transformer.transform(backingService, parameters); + }).then(Mono.just(backingService)); + }).collectList(); } private List getTransformerSpecsForService(BackingService backingService) { - return backingService.getParametersTransformers() == null - ? Collections.emptyList() - : backingService.getParametersTransformers(); + return (backingService.getParametersTransformers() == null) ? Collections.emptyList() + : backingService.getParametersTransformers(); } } diff --git a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/parameters/EnvironmentMappingParametersTransformerFactory.java b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/parameters/EnvironmentMappingParametersTransformerFactory.java index d2412e5..f68e47d 100644 --- a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/parameters/EnvironmentMappingParametersTransformerFactory.java +++ b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/parameters/EnvironmentMappingParametersTransformerFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,7 +29,7 @@ import reactor.util.Loggers; import org.springframework.cloud.appbroker.deployer.BackingApplication; public class EnvironmentMappingParametersTransformerFactory extends - ParametersTransformerFactory { + ParametersTransformerFactory { private static final Logger LOG = Loggers.getLogger(EnvironmentMappingParametersTransformerFactory.class); @@ -44,30 +44,26 @@ public class EnvironmentMappingParametersTransformerFactory extends return (backingType, parameters) -> transform(backingType, parameters, config.getIncludes()); } - private Mono transform(BackingApplication backingApplication, - Map parameters, - List include) { + private Mono transform(BackingApplication backingApplication, Map parameters, + List include) { if (parameters != null) { - parameters - .keySet().stream() - .filter(include::contains) - .forEach(key -> { - Object value = parameters.get(key); - String valueString; - if (value instanceof String) { + parameters.keySet().stream().filter(include::contains).forEach((key) -> { + Object value = parameters.get(key); + String valueString; + if (value instanceof String) { + valueString = value.toString(); + } + else { + try { + valueString = OBJECT_MAPPER.writeValueAsString(value); + } + catch (JsonProcessingException ex) { + LOG.error("Failed to write object as JSON String", ex); valueString = value.toString(); } - else { - try { - valueString = OBJECT_MAPPER.writeValueAsString(value); - } - catch (JsonProcessingException e) { - LOG.error("Failed to write object as JSON String", e); - valueString = value.toString(); - } - } - backingApplication.addEnvironment(key, valueString); - }); + } + backingApplication.addEnvironment(key, valueString); + }); } return Mono.just(backingApplication); @@ -79,7 +75,7 @@ public class EnvironmentMappingParametersTransformerFactory extends private String include; public List getIncludes() { - return Arrays.asList(include.split(",")); + return Arrays.asList(this.include.split(",")); } public void setInclude(String include) { diff --git a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/parameters/ParameterMappingParametersTransformerFactory.java b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/parameters/ParameterMappingParametersTransformerFactory.java index cca64a9..d4dce57 100644 --- a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/parameters/ParameterMappingParametersTransformerFactory.java +++ b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/parameters/ParameterMappingParametersTransformerFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,8 +24,8 @@ import reactor.core.publisher.Mono; import org.springframework.cloud.appbroker.deployer.BackingService; -public class ParameterMappingParametersTransformerFactory extends - ParametersTransformerFactory { +public class ParameterMappingParametersTransformerFactory + extends ParametersTransformerFactory { public ParameterMappingParametersTransformerFactory() { super(Config.class); @@ -36,13 +36,13 @@ public class ParameterMappingParametersTransformerFactory extends return (backingType, parameters) -> transform(backingType, parameters, config.getIncludes()); } - private Mono transform(BackingService backingService, - Map parameters, - List include) { + private Mono transform(BackingService backingService, Map parameters, + List include) { if (parameters != null) { - parameters.keySet().stream() + parameters.keySet() + .stream() .filter(include::contains) - .forEach(key -> backingService.addParameter(key, parameters.get(key))); + .forEach((key) -> backingService.addParameter(key, parameters.get(key))); } return Mono.just(backingService); @@ -54,7 +54,7 @@ public class ParameterMappingParametersTransformerFactory extends private String include; public List getIncludes() { - return Arrays.asList(include.split(",")); + return Arrays.asList(this.include.split(",")); } public void setInclude(String include) { diff --git a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/parameters/ParametersTransformer.java b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/parameters/ParametersTransformer.java index 2616719..c5c798d 100644 --- a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/parameters/ParametersTransformer.java +++ b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/parameters/ParametersTransformer.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/parameters/ParametersTransformerFactory.java b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/parameters/ParametersTransformerFactory.java index 0e1f6dd..759f73d 100644 --- a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/parameters/ParametersTransformerFactory.java +++ b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/parameters/ParametersTransformerFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/parameters/PropertyMappingParametersTransformerFactory.java b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/parameters/PropertyMappingParametersTransformerFactory.java index 6d58605..03f5389 100644 --- a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/parameters/PropertyMappingParametersTransformerFactory.java +++ b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/parameters/PropertyMappingParametersTransformerFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,8 +24,8 @@ import reactor.core.publisher.Mono; import org.springframework.cloud.appbroker.deployer.BackingApplication; -public class PropertyMappingParametersTransformerFactory extends - ParametersTransformerFactory { +public class PropertyMappingParametersTransformerFactory + extends ParametersTransformerFactory { public PropertyMappingParametersTransformerFactory() { super(Config.class); @@ -36,13 +36,13 @@ public class PropertyMappingParametersTransformerFactory extends return (backingApplication, parameters) -> transform(backingApplication, parameters, config.getIncludes()); } - private Mono transform(BackingApplication backingApplication, - Map parameters, - List include) { + private Mono transform(BackingApplication backingApplication, Map parameters, + List include) { if (parameters != null) { - parameters.keySet().stream() + parameters.keySet() + .stream() .filter(include::contains) - .forEach(key -> backingApplication.addProperty(key, parameters.get(key).toString())); + .forEach((key) -> backingApplication.addProperty(key, parameters.get(key).toString())); } return Mono.just(backingApplication); } @@ -53,7 +53,7 @@ public class PropertyMappingParametersTransformerFactory extends private String include; public List getIncludes() { - return Arrays.asList(include.split(",")); + return Arrays.asList(this.include.split(",")); } public void setInclude(String include) { diff --git a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/parameters/package-info.java b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/parameters/package-info.java new file mode 100644 index 0000000..7fe180f --- /dev/null +++ b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/parameters/package-info.java @@ -0,0 +1,20 @@ +/* + * Copyright 2016-2024 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * App Broker Extensions Parameters. + */ +package org.springframework.cloud.appbroker.extensions.parameters; diff --git a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/support/ConfigurationBeanUtils.java b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/support/ConfigurationBeanUtils.java index 4e8569b..719f0b0 100644 --- a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/support/ConfigurationBeanUtils.java +++ b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/support/ConfigurationBeanUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,9 +49,10 @@ public final class ConfigurationBeanUtils { beanUtils.getPropertyUtils().addBeanIntrospector(SuppressPropertiesBeanIntrospector.SUPPRESS_CLASS); beanUtils.copyProperties(target, properties); } - catch (IllegalAccessException | InvocationTargetException e) { - throw new IllegalArgumentException("Failed to populate target of type " + targetObject.getClass() - + " with properties " + properties, e); + catch (IllegalAccessException | InvocationTargetException ex) { + throw new IllegalArgumentException( + "Failed to populate target of type " + targetObject.getClass() + " with properties " + properties, + ex); } } @@ -62,8 +63,8 @@ public final class ConfigurationBeanUtils { return (T) ((Advised) candidate).getTargetSource().getTarget(); } } - catch (Exception e) { - throw new IllegalStateException("Failed to unwrap proxied object", e); + catch (Exception ex) { + throw new IllegalStateException("Failed to unwrap proxied object", ex); } return (T) candidate; } diff --git a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/support/KebabCasePropertyBeanIntrospector.java b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/support/KebabCasePropertyBeanIntrospector.java index 52a5082..898eade 100644 --- a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/support/KebabCasePropertyBeanIntrospector.java +++ b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/support/KebabCasePropertyBeanIntrospector.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.appbroker.extensions.support; import java.beans.IntrospectionException; @@ -28,12 +29,14 @@ import reactor.util.Logger; import reactor.util.Loggers; /** - * An implementation of the {@link BeanIntrospector} interface that provides property descriptors following the - * kebab-case convention. + * An implementation of the {@link BeanIntrospector} interface that provides property + * descriptors following the kebab-case convention. *

- * This implementation is intended to collaborate with a {@link DefaultBeanIntrospector} object. Best results are - * achieved by adding this instance as custom {@link BeanIntrospector} after the {@link DefaultBeanIntrospector} - * object. + * This implementation is intended to collaborate with a {@link DefaultBeanIntrospector} + * object. Best results are achieved by adding this instance as custom + * {@link BeanIntrospector} after the {@link DefaultBeanIntrospector} object. + * + * @author Scott Frederick */ public class KebabCasePropertyBeanIntrospector implements BeanIntrospector { @@ -42,10 +45,9 @@ public class KebabCasePropertyBeanIntrospector implements BeanIntrospector { private static final String WRITE_METHOD_PREFIX = "set"; /** - * Performs introspection. This method scans the current class's methods for property write methods add adds a - * property descriptor using the kebab-case naming convention to match each property descriptor that uses the - * camel-case Java Bean convention. - * + * Performs introspection. This method scans the current class's methods for property + * write methods add adds a property descriptor using the kebab-case naming convention + * to match each property descriptor that uses the camel-case Java Bean convention. * @param context the introspection context */ @Override @@ -59,10 +61,10 @@ public class KebabCasePropertyBeanIntrospector implements BeanIntrospector { context.addPropertyDescriptor(createPropertyDescriptor(m)); } } - catch (final IntrospectionException e) { + catch (final IntrospectionException ex) { if (LOG.isErrorEnabled()) { - LOG.error(String.format("Error when creating PropertyDescriptor for method '%s'. This " + - "property will be ignored. %s", m), e); + LOG.error(String.format("Error when creating PropertyDescriptor for method '%s'. This " + + "property will be ignored. %s", m), ex); } } } @@ -71,20 +73,17 @@ public class KebabCasePropertyBeanIntrospector implements BeanIntrospector { /** * Derives the camel-case name of a property from the given set method. - * * @param m the method * @return the corresponding property name */ private String camelCasePropertyName(final Method m) { final String methodName = m.getName().substring(WRITE_METHOD_PREFIX.length()); - return methodName.length() > 1 ? - Introspector.decapitalize(methodName) : - methodName.toLowerCase(Locale.ENGLISH); + return (methodName.length() > 1) ? Introspector.decapitalize(methodName) + : methodName.toLowerCase(Locale.ENGLISH); } /** * Derives the kebab-case name of a property from the given set method. - * * @param m the method * @return the corresponding property name */ @@ -106,7 +105,6 @@ public class KebabCasePropertyBeanIntrospector implements BeanIntrospector { /** * Creates a property descriptor for a property. - * * @param m the set method for the property * @return the descriptor * @throws IntrospectionException if an error occurs diff --git a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/support/package-info.java b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/support/package-info.java new file mode 100644 index 0000000..8b4b2b1 --- /dev/null +++ b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/support/package-info.java @@ -0,0 +1,20 @@ +/* + * Copyright 2016-2024 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * App Broker Extensions Support. + */ +package org.springframework.cloud.appbroker.extensions.support; diff --git a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/targets/ArtifactDetails.java b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/targets/ArtifactDetails.java index 446c116..016f207 100644 --- a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/targets/ArtifactDetails.java +++ b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/targets/ArtifactDetails.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,11 +33,11 @@ public class ArtifactDetails { } public String getName() { - return name; + return this.name; } public Map getProperties() { - return properties; + return this.properties; } public static ArtifactDetailsBuilder builder() { @@ -66,7 +66,7 @@ public class ArtifactDetails { } public ArtifactDetails build() { - return new ArtifactDetails(name, properties); + return new ArtifactDetails(this.name, this.properties); } } diff --git a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/targets/ServiceInstanceGuidSuffix.java b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/targets/ServiceInstanceGuidSuffix.java index fb7273d..2398c06 100644 --- a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/targets/ServiceInstanceGuidSuffix.java +++ b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/targets/ServiceInstanceGuidSuffix.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,6 +54,7 @@ public class ServiceInstanceGuidSuffix extends TargetFactory locator; public TargetService(List> factories) { - locator = new ExtensionLocator<>(factories); + this.locator = new ExtensionLocator<>(factories); } public Mono> addToBackingApplications(List backingApplications, - TargetSpec targetSpec, String serviceInstanceId) { - return Flux.fromIterable(backingApplications) - .flatMap(backingApplication -> { - if (targetSpec != null) { - ArtifactDetails appDetails = getArtifactDetails(targetSpec, serviceInstanceId, + TargetSpec targetSpec, String serviceInstanceId) { + return Flux.fromIterable(backingApplications).flatMap((backingApplication) -> { + if (targetSpec != null) { + ArtifactDetails appDetails = getArtifactDetails(targetSpec, serviceInstanceId, backingApplication.getName(), backingApplication.getProperties()); - backingApplication.setName(appDetails.getName()); - backingApplication.setProperties(appDetails.getProperties()); + backingApplication.setName(appDetails.getName()); + backingApplication.setProperties(appDetails.getProperties()); - backingApplication.getServices().forEach(servicesSpec -> { - ArtifactDetails serviceDetails = getArtifactDetails(targetSpec, serviceInstanceId, - servicesSpec.getServiceInstanceName(), new HashMap<>()); - servicesSpec.setServiceInstanceName(serviceDetails.getName()); - }); - } - return Mono.just(backingApplication); - }) - .collectList(); - } - - public Mono> addToBackingServices(List backingServices, - TargetSpec targetSpec, - String serviceInstanceId) { - return Flux.fromIterable(backingServices) - .flatMap(backingService -> { - if (targetSpec != null) { + backingApplication.getServices().forEach((servicesSpec) -> { ArtifactDetails serviceDetails = getArtifactDetails(targetSpec, serviceInstanceId, - backingService.getServiceInstanceName(), backingService.getProperties()); - backingService.setServiceInstanceName(serviceDetails.getName()); - backingService.setProperties(serviceDetails.getProperties()); - } - return Mono.just(backingService); - }) - .collectList(); + servicesSpec.getServiceInstanceName(), new HashMap<>()); + servicesSpec.setServiceInstanceName(serviceDetails.getName()); + }); + } + return Mono.just(backingApplication); + }).collectList(); } - private ArtifactDetails getArtifactDetails(TargetSpec targetSpec, String serviceInstanceId, - String name, Map properties) { - Target target = locator.getByName(targetSpec.getName()); + public Mono> addToBackingServices(List backingServices, TargetSpec targetSpec, + String serviceInstanceId) { + return Flux.fromIterable(backingServices).flatMap((backingService) -> { + if (targetSpec != null) { + ArtifactDetails serviceDetails = getArtifactDetails(targetSpec, serviceInstanceId, + backingService.getServiceInstanceName(), backingService.getProperties()); + backingService.setServiceInstanceName(serviceDetails.getName()); + backingService.setProperties(serviceDetails.getProperties()); + } + return Mono.just(backingService); + }).collectList(); + } + + private ArtifactDetails getArtifactDetails(TargetSpec targetSpec, String serviceInstanceId, String name, + Map properties) { + Target target = this.locator.getByName(targetSpec.getName()); return target.apply(properties, name, serviceInstanceId); } diff --git a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/targets/package-info.java b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/targets/package-info.java new file mode 100644 index 0000000..4539139 --- /dev/null +++ b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/extensions/targets/package-info.java @@ -0,0 +1,20 @@ +/* + * Copyright 2016-2024 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * App Broker Extensions Targets. + */ +package org.springframework.cloud.appbroker.extensions.targets; diff --git a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/manager/BackingAppManagementService.java b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/manager/BackingAppManagementService.java index b320d99..21bce46 100644 --- a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/manager/BackingAppManagementService.java +++ b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/manager/BackingAppManagementService.java @@ -1,11 +1,11 @@ /* - * Copyright 2002-2021 the original author or authors + * Copyright 2016-2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * https://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -49,7 +49,7 @@ public class BackingAppManagementService { private final TargetService targetService; public BackingAppManagementService(ManagementClient managementClient, AppDeployer appDeployer, - BrokeredServices brokeredServices, TargetService targetService) { + BrokeredServices brokeredServices, TargetService targetService) { this.managementClient = managementClient; this.appDeployer = appDeployer; this.brokeredServices = brokeredServices; @@ -57,14 +57,15 @@ public class BackingAppManagementService { } /** - * Helper method that fetches service name and plan name from Cloud Foundry Service Instances API (CF API) and - * invokes {@code stop(serviceInstanceId, serviceName, planName)}. + * Helper method that fetches service name and plan name from Cloud Foundry Service + * Instances API (CF API) and invokes + * {@code stop(serviceInstanceId, serviceName, planName)}. * - * Because this method will try to fetch user-created service instance, UAA client used by the broker has to be a - * space developer of the space containing the service instance, or has to have {@code cloud_controller.admin} - * authority. If you want to avoid CF API call, use + * Because this method will try to fetch user-created service instance, UAA client + * used by the broker has to be a space developer of the space containing the service + * instance, or has to have {@code cloud_controller.admin} authority. If you want to + * avoid CF API call, use * {@link BackingAppManagementService#stop(String, String, String)} method. - * * @param serviceInstanceId target service instance id * @return completes when the operation is completed */ @@ -72,9 +73,8 @@ public class BackingAppManagementService { return fetchServiceDetailsAndInvoke(serviceInstanceId, this::stop); } - /** - * Stops the backing applications for the service instance with the given id + * Stops the backing applications for the service instance with the given id. * @param serviceInstanceId target service instance id * @param serviceName service name * @param planName plan name @@ -82,11 +82,11 @@ public class BackingAppManagementService { */ public Mono stop(String serviceInstanceId, String serviceName, String planName) { return getBackingApplicationsForService(serviceInstanceId, serviceName, planName) - .flatMapMany(backingApps -> Flux.fromIterable(backingApps) + .flatMapMany((backingApps) -> Flux.fromIterable(backingApps) .parallel() .runOn(Schedulers.parallel()) - .flatMap(managementClient::stop) - .doOnRequest(l -> { + .flatMap(this.managementClient::stop) + .doOnRequest((l) -> { LOG.info("Stopping applications"); LOG.debug(BACKINGAPPS_LOG_TEMPLATE, backingApps); }) @@ -94,7 +94,7 @@ public class BackingAppManagementService { LOG.info("Finish stopping applications"); LOG.debug(BACKINGAPPS_LOG_TEMPLATE, backingApps); }) - .doOnError(e -> { + .doOnError((e) -> { LOG.error(String.format("Error stopping applications. error=%s", e.getMessage()), e); LOG.debug(BACKINGAPPS_LOG_TEMPLATE, backingApps); })) @@ -102,14 +102,15 @@ public class BackingAppManagementService { } /** - * Helper method that fetches service name and plan name from Cloud Foundry Service Instances API (CF API) and - * invokes {@code start(serviceInstanceId, serviceName, planName)}. + * Helper method that fetches service name and plan name from Cloud Foundry Service + * Instances API (CF API) and invokes + * {@code start(serviceInstanceId, serviceName, planName)}. * - * Because this method will try to fetch user-created service instance, UAA client used by the broker has to be a - * space developer of the space containing the service instance, or has to have {@code cloud_controller.admin} - * authority. If you want to avoid CF API call, use + * Because this method will try to fetch user-created service instance, UAA client + * used by the broker has to be a space developer of the space containing the service + * instance, or has to have {@code cloud_controller.admin} authority. If you want to + * avoid CF API call, use * {@link BackingAppManagementService#start(String, String, String)} method. - * * @param serviceInstanceId target service instance id * @return completes when the operation is completed */ @@ -118,7 +119,7 @@ public class BackingAppManagementService { } /** - * Starts the backing applications for the service instance with the given id + * Starts the backing applications for the service instance with the given id. * @param serviceInstanceId target service instance id * @param serviceName service name * @param planName plan name @@ -126,11 +127,11 @@ public class BackingAppManagementService { */ public Mono start(String serviceInstanceId, String serviceName, String planName) { return getBackingApplicationsForService(serviceInstanceId, serviceName, planName) - .flatMapMany(backingApps -> Flux.fromIterable(backingApps) + .flatMapMany((backingApps) -> Flux.fromIterable(backingApps) .parallel() .runOn(Schedulers.parallel()) - .flatMap(managementClient::start) - .doOnRequest(l -> { + .flatMap(this.managementClient::start) + .doOnRequest((l) -> { LOG.info("Starting applications"); LOG.debug(BACKINGAPPS_LOG_TEMPLATE, backingApps); }) @@ -138,7 +139,7 @@ public class BackingAppManagementService { LOG.info("Finish starting applications"); LOG.debug(BACKINGAPPS_LOG_TEMPLATE, backingApps); }) - .doOnError(e -> { + .doOnError((e) -> { LOG.error(String.format("Error starting applications. error=%s", e.getMessage()), e); LOG.debug(BACKINGAPPS_LOG_TEMPLATE, backingApps); })) @@ -146,14 +147,15 @@ public class BackingAppManagementService { } /** - * Helper method that fetches service name and plan name from Cloud Foundry Service Instances API (CF API) and - * invokes {@code restart(serviceInstanceId, serviceName, planName)}. + * Helper method that fetches service name and plan name from Cloud Foundry Service + * Instances API (CF API) and invokes + * {@code restart(serviceInstanceId, serviceName, planName)}. * - * Because this method will try to fetch user-created service instance, UAA client used by the broker has to be a - * space developer of the space containing the service instance, or has to have {@code cloud_controller.admin} - * authority. If you want to avoid CF API call, use + * Because this method will try to fetch user-created service instance, UAA client + * used by the broker has to be a space developer of the space containing the service + * instance, or has to have {@code cloud_controller.admin} authority. If you want to + * avoid CF API call, use * {@link BackingAppManagementService#restart(String, String, String)} method. - * * @param serviceInstanceId target service instance id * @return completes when the operation is completed */ @@ -162,7 +164,7 @@ public class BackingAppManagementService { } /** - * Restarts the backing applications for the service instance with the given id + * Restarts the backing applications for the service instance with the given id. * @param serviceInstanceId target service instance id * @param serviceName service name * @param planName plan name @@ -170,11 +172,11 @@ public class BackingAppManagementService { */ public Mono restart(String serviceInstanceId, String serviceName, String planName) { return getBackingApplicationsForService(serviceInstanceId, serviceName, planName) - .flatMapMany(backingApps -> Flux.fromIterable(backingApps) + .flatMapMany((backingApps) -> Flux.fromIterable(backingApps) .parallel() .runOn(Schedulers.parallel()) - .flatMap(managementClient::restart) - .doOnRequest(l -> { + .flatMap(this.managementClient::restart) + .doOnRequest((l) -> { LOG.info("Restarting applications"); LOG.debug(BACKINGAPPS_LOG_TEMPLATE, backingApps); }) @@ -182,7 +184,7 @@ public class BackingAppManagementService { LOG.info("Finish restarting applications"); LOG.debug(BACKINGAPPS_LOG_TEMPLATE, backingApps); }) - .doOnError(e -> { + .doOnError((e) -> { LOG.error(String.format("Error restarting applications. error=%s", e.getMessage()), e); LOG.debug(BACKINGAPPS_LOG_TEMPLATE, backingApps); })) @@ -190,14 +192,15 @@ public class BackingAppManagementService { } /** - * Helper method that fetches service name and plan name from Cloud Foundry Service Instances API (CF API) and - * invokes {@code restage(serviceInstanceId, serviceName, planName)}. + * Helper method that fetches service name and plan name from Cloud Foundry Service + * Instances API (CF API) and invokes + * {@code restage(serviceInstanceId, serviceName, planName)}. * - * Because this method will try to fetch user-created service instance, UAA client used by the broker has to be a - * space developer of the space containing the service instance, or has to have {@code cloud_controller.admin} - * authority. If you want to avoid CF API call, use + * Because this method will try to fetch user-created service instance, UAA client + * used by the broker has to be a space developer of the space containing the service + * instance, or has to have {@code cloud_controller.admin} authority. If you want to + * avoid CF API call, use * {@link BackingAppManagementService#restage(String, String, String)} method. - * * @param serviceInstanceId target service instance id * @return completes when the operation is completed */ @@ -206,7 +209,7 @@ public class BackingAppManagementService { } /** - * Restages the backing applications for the service instance with the given id + * Restages the backing applications for the service instance with the given id. * @param serviceInstanceId target service instance id * @param serviceName service name * @param planName plan name @@ -214,11 +217,11 @@ public class BackingAppManagementService { */ public Mono restage(String serviceInstanceId, String serviceName, String planName) { return getBackingApplicationsForService(serviceInstanceId, serviceName, planName) - .flatMapMany(backingApps -> Flux.fromIterable(backingApps) + .flatMapMany((backingApps) -> Flux.fromIterable(backingApps) .parallel() .runOn(Schedulers.parallel()) - .flatMap(managementClient::restage) - .doOnRequest(l -> { + .flatMap(this.managementClient::restage) + .doOnRequest((l) -> { LOG.info("Restaging applications"); LOG.debug(BACKINGAPPS_LOG_TEMPLATE, backingApps); }) @@ -226,7 +229,7 @@ public class BackingAppManagementService { LOG.info("Finish restaging applications"); LOG.debug(BACKINGAPPS_LOG_TEMPLATE, backingApps); }) - .doOnError(e -> { + .doOnError((e) -> { LOG.error(String.format("Error restaging applications. error=%s", e.getMessage()), e); LOG.debug(BACKINGAPPS_LOG_TEMPLATE, backingApps); })) @@ -234,14 +237,16 @@ public class BackingAppManagementService { } /** - * Helper method that fetches service name and plan name from Cloud Foundry Service Instances API (CF API) and - * invokes {@code getDeployedBackingApplications(serviceInstanceId, serviceName, planName)}. - * - * Because this method will try to fetch user-created service instance, UAA client used by the broker has to be a - * space developer of the space containing the service instance, or has to have {@code cloud_controller.admin} - * authority. If you want to avoid CF API call, use - * {@link BackingAppManagementService#getDeployedBackingApplications(String, String, String)} method. + * Helper method that fetches service name and plan name from Cloud Foundry Service + * Instances API (CF API) and invokes + * {@code getDeployedBackingApplications(serviceInstanceId, serviceName, planName)}. * + * Because this method will try to fetch user-created service instance, UAA client + * used by the broker has to be a space developer of the space containing the service + * instance, or has to have {@code cloud_controller.admin} authority. If you want to + * avoid CF API call, use + * {@link BackingAppManagementService#getDeployedBackingApplications(String, String, String)} + * method. * @param serviceInstanceId target service instance id * @return backing applications for the target service instance */ @@ -250,82 +255,77 @@ public class BackingAppManagementService { } /** - * Returns a list of backing applications for the service instance with the given id + * Returns a list of backing applications for the service instance with the given id. * @param serviceInstanceId target service instance id * @param serviceName service name * @param planName plan name * @return backing applications for the target service instance */ - public Mono getDeployedBackingApplications(String serviceInstanceId, String serviceName, String planName) { + public Mono getDeployedBackingApplications(String serviceInstanceId, String serviceName, + String planName) { return getBackingApplicationsForService(serviceInstanceId, serviceName, planName) .flatMapMany(Flux::fromIterable) - .flatMap(app -> - appDeployer - .get(GetApplicationRequest.builder() - .name(app.getName()) + .flatMap((app) -> this.appDeployer + .get(GetApplicationRequest.builder().name(app.getName()).properties(app.getProperties()).build()) + .flatMap((response) -> Flux.fromIterable(response.getServices()) + .map((boundServiceName) -> ServicesSpec.builder().serviceInstanceName(boundServiceName).build()) + .collectList() + .map((services) -> BackingApplication.builder() + .name(response.getName()) + .services(services) .properties(app.getProperties()) - .build()) - .flatMap(response -> Flux.fromIterable(response.getServices()) - .map(boundServiceName -> - ServicesSpec.builder() - .serviceInstanceName(boundServiceName) - .build()) - .collectList() - .map(services -> BackingApplication - .builder() - .name(response.getName()) - .services(services) - .properties(app.getProperties()) - .environment(response.getEnvironment()) - .build())) - .doOnRequest(l -> { - LOG.info("Getting deployed backing application. appName={}", app.getName()); - LOG.debug("backingApp={}", app); - }) - .doOnError(e -> { - LOG.error(String.format("Error getting deployed backing application. appName=%s, error=%s", + .environment(response.getEnvironment()) + .build())) + .doOnRequest((l) -> { + LOG.info("Getting deployed backing application. appName={}", app.getName()); + LOG.debug("backingApp={}", app); + }) + .doOnError((e) -> { + LOG.error(String.format("Error getting deployed backing application. appName=%s, error=%s", app.getName(), e.getMessage()), e); - LOG.debug("backingApp={}", app); - }) - .onErrorResume(exception -> Mono.empty())) + LOG.debug("backingApp={}", app); + }) + .onErrorResume((exception) -> Mono.empty())) .collectList() .map(BackingApplications::new) - .doOnSuccess(backingApplications -> LOG.debug("backingApplications={}", backingApplications)); + .doOnSuccess((backingApplications) -> LOG.debug("backingApplications={}", backingApplications)); } public Mono getBackingApplicationsForService(String serviceInstanceId, String serviceName, - String planName) { + String planName) { return findBrokeredService(serviceName, planName) - .flatMap(brokeredService -> updateBackingApps(brokeredService, serviceInstanceId)) - .map(backingApplications -> BackingApplications.builder().backingApplications(backingApplications).build()); + .flatMap((brokeredService) -> updateBackingApps(brokeredService, serviceInstanceId)) + .map((backingApplications) -> BackingApplications.builder() + .backingApplications(backingApplications) + .build()); } private Mono fetchServiceDetailsAndInvoke(String serviceInstanceId, BackingAppAction action) { - return appDeployer + return this.appDeployer .getServiceInstance(GetServiceInstanceRequest.builder().serviceInstanceId(serviceInstanceId).build()) - .flatMap(serviceInstance -> action.invoke(serviceInstanceId, serviceInstance.getService(), - serviceInstance.getPlan())); + .flatMap((serviceInstance) -> action.invoke(serviceInstanceId, serviceInstance.getService(), + serviceInstance.getPlan())); } private Mono findBrokeredService(String serviceName, String planName) { - return Flux.fromIterable(brokeredServices) - .filter(brokeredService -> brokeredService.getServiceName().equals(serviceName) - && brokeredService.getPlanName().equals(planName)) + return Flux.fromIterable(this.brokeredServices) + .filter((brokeredService) -> brokeredService.getServiceName().equals(serviceName) + && brokeredService.getPlanName().equals(planName)) .singleOrEmpty(); } private Mono> updateBackingApps(BrokeredService brokeredService, - String serviceInstanceId) { - return Mono.just(BackingApplications.builder() - .backingApplications(brokeredService.getApps()) - .build()) - .flatMap(backingApps -> targetService.addToBackingApplications(backingApps, - brokeredService.getTarget(), serviceInstanceId)); + String serviceInstanceId) { + return Mono.just(BackingApplications.builder().backingApplications(brokeredService.getApps()).build()) + .flatMap((backingApps) -> this.targetService.addToBackingApplications(backingApps, + brokeredService.getTarget(), serviceInstanceId)); } @FunctionalInterface private interface BackingAppAction { + Mono invoke(String serviceInstanceId, String serviceName, String planName); + } } diff --git a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/manager/ManagementClient.java b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/manager/ManagementClient.java index 6eef67d..f631e44 100644 --- a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/manager/ManagementClient.java +++ b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/manager/ManagementClient.java @@ -1,11 +1,11 @@ /* - * Copyright 2002-2020 the original author or authors + * Copyright 2016-2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * https://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -41,84 +41,88 @@ public class ManagementClient { public Mono start(BackingApplication backingApplication) { return Mono.justOrEmpty(backingApplication) - .flatMap(backingApp -> appManager.start(StartApplicationRequest.builder() - .name(backingApp.getName()) - .properties(backingApp.getProperties()) - .build()) - .doOnRequest(l -> { + .flatMap((backingApp) -> this.appManager + .start(StartApplicationRequest.builder() + .name(backingApp.getName()) + .properties(backingApp.getProperties()) + .build()) + .doOnRequest((l) -> { LOG.info("Starting application. backingAppName={}", backingApp.getName()); LOG.debug(BACKINGAPP_LOG_TEMPLATE, backingApp); }) - .doOnSuccess(response -> { + .doOnSuccess((response) -> { LOG.info("Success starting application. backingAppName={}", backingApp.getName()); LOG.debug(BACKINGAPP_LOG_TEMPLATE, backingApp); }) - .doOnError(e -> { + .doOnError((e) -> { LOG.error(String.format("Error starting application. backingAppName=%s, error=%s", - backingApp.getName(), e.getMessage()), e); + backingApp.getName(), e.getMessage()), e); LOG.debug(BACKINGAPP_LOG_TEMPLATE, backingApp); })); } public Mono stop(BackingApplication backingApplication) { return Mono.justOrEmpty(backingApplication) - .flatMap(backingApp -> appManager.stop(StopApplicationRequest.builder() - .name(backingApp.getName()) - .properties(backingApp.getProperties()) - .build()) - .doOnRequest(l -> { + .flatMap((backingApp) -> this.appManager + .stop(StopApplicationRequest.builder() + .name(backingApp.getName()) + .properties(backingApp.getProperties()) + .build()) + .doOnRequest((l) -> { LOG.info("Stopping application. backingAppName={}", backingApp.getName()); LOG.debug(BACKINGAPP_LOG_TEMPLATE, backingApp); }) - .doOnSuccess(response -> { + .doOnSuccess((response) -> { LOG.info("Success stopping application. backingAppName={}", backingApp.getName()); LOG.debug(BACKINGAPP_LOG_TEMPLATE, backingApp); }) - .doOnError(e -> { + .doOnError((e) -> { LOG.error(String.format("Error stopping application. backingAppName=%s, error=%s", - backingApp.getName(), e.getMessage()), e); + backingApp.getName(), e.getMessage()), e); LOG.debug(BACKINGAPP_LOG_TEMPLATE, backingApp); })); } public Mono restart(BackingApplication backingApplication) { return Mono.justOrEmpty(backingApplication) - .flatMap(backingApp -> appManager.restart(RestartApplicationRequest.builder() - .name(backingApp.getName()) - .properties(backingApp.getProperties()) - .build()) - .doOnRequest(l -> { + .flatMap((backingApp) -> this.appManager + .restart(RestartApplicationRequest.builder() + .name(backingApp.getName()) + .properties(backingApp.getProperties()) + .build()) + .doOnRequest((l) -> { LOG.info("Restarting application. backingAppName={}", backingApp.getName()); LOG.debug(BACKINGAPP_LOG_TEMPLATE, backingApp); }) - .doOnSuccess(response -> { + .doOnSuccess((response) -> { LOG.info("Success restarting application. backingAppName={}", backingApp.getName()); LOG.debug(BACKINGAPP_LOG_TEMPLATE, backingApp); }) - .doOnError(e -> { + .doOnError((e) -> { LOG.error(String.format("Error restarting application. backingAppName=%s, error=%s", - backingApp.getName(), e.getMessage()), e); + backingApp.getName(), e.getMessage()), e); LOG.debug(BACKINGAPP_LOG_TEMPLATE, backingApp); })); } public Mono restage(BackingApplication backingApplication) { return Mono.justOrEmpty(backingApplication) - .flatMap(backingApp -> appManager.restage(RestageApplicationRequest.builder() - .name(backingApp.getName()) - .properties(backingApp.getProperties()) - .build()) - .doOnRequest(l -> { + .flatMap((backingApp) -> this.appManager + .restage(RestageApplicationRequest.builder() + .name(backingApp.getName()) + .properties(backingApp.getProperties()) + .build()) + .doOnRequest((l) -> { LOG.info("Restaging application. backingAppName={}", backingApp.getName()); LOG.debug(BACKINGAPP_LOG_TEMPLATE, backingApp); }) - .doOnSuccess(response -> { + .doOnSuccess((response) -> { LOG.info("Success restaging application. backingAppName={}", backingApp.getName()); LOG.debug(BACKINGAPP_LOG_TEMPLATE, backingApp); }) - .doOnError(e -> { + .doOnError((e) -> { LOG.error(String.format("Error restaging application. backingAppName=%s, error=%s", - backingApp.getName(), e.getMessage()), e); + backingApp.getName(), e.getMessage()), e); LOG.debug(BACKINGAPP_LOG_TEMPLATE, backingApp); })); } diff --git a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/manager/package-info.java b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/manager/package-info.java new file mode 100644 index 0000000..a5cdfe7 --- /dev/null +++ b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/manager/package-info.java @@ -0,0 +1,20 @@ +/* + * Copyright 2016-2024 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * App Broker Manager. + */ +package org.springframework.cloud.appbroker.manager; diff --git a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/package-info.java b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/package-info.java new file mode 100644 index 0000000..b106d90 --- /dev/null +++ b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/package-info.java @@ -0,0 +1,20 @@ +/* + * Copyright 2016-2024 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * App Broker Core. + */ +package org.springframework.cloud.appbroker; diff --git a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/service/CreateServiceInstanceAppBindingWorkflow.java b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/service/CreateServiceInstanceAppBindingWorkflow.java index 21b38e6..5e8221f 100644 --- a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/service/CreateServiceInstanceAppBindingWorkflow.java +++ b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/service/CreateServiceInstanceAppBindingWorkflow.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,7 +25,7 @@ import org.springframework.cloud.servicebroker.model.binding.CreateServiceInstan public interface CreateServiceInstanceAppBindingWorkflow { default Mono create(CreateServiceInstanceBindingRequest request, - CreateServiceInstanceAppBindingResponse response) { + CreateServiceInstanceAppBindingResponse response) { return Mono.empty(); } @@ -34,8 +34,8 @@ public interface CreateServiceInstanceAppBindingWorkflow { } default Mono buildResponse( - CreateServiceInstanceBindingRequest request, - CreateServiceInstanceAppBindingResponseBuilder responseBuilder) { + CreateServiceInstanceBindingRequest request, + CreateServiceInstanceAppBindingResponseBuilder responseBuilder) { return Mono.just(responseBuilder); } diff --git a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/service/CreateServiceInstanceRouteBindingWorkflow.java b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/service/CreateServiceInstanceRouteBindingWorkflow.java index 018888f..f5bc61e 100644 --- a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/service/CreateServiceInstanceRouteBindingWorkflow.java +++ b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/service/CreateServiceInstanceRouteBindingWorkflow.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,7 +25,7 @@ import org.springframework.cloud.servicebroker.model.binding.CreateServiceInstan public interface CreateServiceInstanceRouteBindingWorkflow { default Mono create(CreateServiceInstanceBindingRequest request, - CreateServiceInstanceRouteBindingResponse response) { + CreateServiceInstanceRouteBindingResponse response) { return Mono.empty(); } @@ -34,8 +34,8 @@ public interface CreateServiceInstanceRouteBindingWorkflow { } default Mono buildResponse( - CreateServiceInstanceBindingRequest request, - CreateServiceInstanceRouteBindingResponseBuilder responseBuilder) { + CreateServiceInstanceBindingRequest request, + CreateServiceInstanceRouteBindingResponseBuilder responseBuilder) { return Mono.just(responseBuilder); } diff --git a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/service/CreateServiceInstanceWorkflow.java b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/service/CreateServiceInstanceWorkflow.java index 865b330..a8ec598 100644 --- a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/service/CreateServiceInstanceWorkflow.java +++ b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/service/CreateServiceInstanceWorkflow.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,8 +24,7 @@ import org.springframework.cloud.servicebroker.model.instance.CreateServiceInsta public interface CreateServiceInstanceWorkflow { - default Mono create(CreateServiceInstanceRequest request, - CreateServiceInstanceResponse response) { + default Mono create(CreateServiceInstanceRequest request, CreateServiceInstanceResponse response) { return Mono.empty(); } @@ -34,7 +33,7 @@ public interface CreateServiceInstanceWorkflow { } default Mono buildResponse(CreateServiceInstanceRequest request, - CreateServiceInstanceResponseBuilder responseBuilder) { + CreateServiceInstanceResponseBuilder responseBuilder) { return Mono.just(responseBuilder); } diff --git a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/service/DeleteServiceInstanceBindingWorkflow.java b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/service/DeleteServiceInstanceBindingWorkflow.java index 8d66194..82ecd2b 100644 --- a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/service/DeleteServiceInstanceBindingWorkflow.java +++ b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/service/DeleteServiceInstanceBindingWorkflow.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,7 +25,7 @@ import org.springframework.cloud.servicebroker.model.binding.DeleteServiceInstan public interface DeleteServiceInstanceBindingWorkflow { default Mono delete(DeleteServiceInstanceBindingRequest request, - DeleteServiceInstanceBindingResponse response) { + DeleteServiceInstanceBindingResponse response) { return Mono.empty(); } @@ -34,7 +34,7 @@ public interface DeleteServiceInstanceBindingWorkflow { } default Mono buildResponse(DeleteServiceInstanceBindingRequest request, - DeleteServiceInstanceBindingResponseBuilder responseBuilder) { + DeleteServiceInstanceBindingResponseBuilder responseBuilder) { return Mono.just(responseBuilder); } diff --git a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/service/DeleteServiceInstanceWorkflow.java b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/service/DeleteServiceInstanceWorkflow.java index 55ae773..fe493a6 100644 --- a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/service/DeleteServiceInstanceWorkflow.java +++ b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/service/DeleteServiceInstanceWorkflow.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,7 +33,7 @@ public interface DeleteServiceInstanceWorkflow { } default Mono buildResponse(DeleteServiceInstanceRequest request, - DeleteServiceInstanceResponseBuilder responseBuilder) { + DeleteServiceInstanceResponseBuilder responseBuilder) { return Mono.just(responseBuilder); } diff --git a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/service/UpdateServiceInstanceWorkflow.java b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/service/UpdateServiceInstanceWorkflow.java index dc44821..a630adb 100644 --- a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/service/UpdateServiceInstanceWorkflow.java +++ b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/service/UpdateServiceInstanceWorkflow.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,7 +33,7 @@ public interface UpdateServiceInstanceWorkflow { } default Mono buildResponse(UpdateServiceInstanceRequest request, - UpdateServiceInstanceResponseBuilder responseBuilder) { + UpdateServiceInstanceResponseBuilder responseBuilder) { return Mono.just(responseBuilder); } diff --git a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/service/WorkflowServiceInstanceBindingService.java b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/service/WorkflowServiceInstanceBindingService.java index b60d086..ad98cd1 100644 --- a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/service/WorkflowServiceInstanceBindingService.java +++ b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/service/WorkflowServiceInstanceBindingService.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -59,10 +59,10 @@ public class WorkflowServiceInstanceBindingService implements ServiceInstanceBin private final List deleteServiceInstanceBindingWorkflows = new ArrayList<>(); public WorkflowServiceInstanceBindingService( - ServiceInstanceBindingStateRepository serviceInstanceBindingStateRepository, - List createServiceInstanceAppBindingWorkflows, - List createServiceInstanceRouteBindingWorkflows, - List deleteServiceInstanceBindingWorkflows) { + ServiceInstanceBindingStateRepository serviceInstanceBindingStateRepository, + List createServiceInstanceAppBindingWorkflows, + List createServiceInstanceRouteBindingWorkflows, + List deleteServiceInstanceBindingWorkflows) { this.stateRepository = serviceInstanceBindingStateRepository; if (!CollectionUtils.isEmpty(createServiceInstanceAppBindingWorkflows)) { this.createServiceInstanceAppBindingWorkflows.addAll(createServiceInstanceAppBindingWorkflows); @@ -80,22 +80,21 @@ public class WorkflowServiceInstanceBindingService implements ServiceInstanceBin @Override public Mono createServiceInstanceBinding( - CreateServiceInstanceBindingRequest request) { - return invokeCreateResponseBuilders(request) - .flatMap(response -> { - if (response.isAsync()) { - return Mono.just(response).publishOn(Schedulers.parallel()) - .doOnNext(r -> create(request, r) - .subscribe()); - } - else { - return create(request, response).thenReturn(response); - } - }); + CreateServiceInstanceBindingRequest request) { + return invokeCreateResponseBuilders(request).flatMap((response) -> { + if (response.isAsync()) { + return Mono.just(response) + .publishOn(Schedulers.parallel()) + .doOnNext((r) -> create(request, r).subscribe()); + } + else { + return create(request, response).thenReturn(response); + } + }); } private Mono invokeCreateResponseBuilders( - CreateServiceInstanceBindingRequest request) { + CreateServiceInstanceBindingRequest request) { return Mono.defer(() -> { if (isAppBindingRequest(request)) { CreateServiceInstanceAppBindingResponseBuilder builder = CreateServiceInstanceAppBindingResponse @@ -108,7 +107,7 @@ public class WorkflowServiceInstanceBindingService implements ServiceInstanceBin CreateServiceInstanceRouteBindingResponseBuilder builder = CreateServiceInstanceRouteBindingResponse .builder(); return invokeRouteBindingBuildResponse(builder, request, - this.createServiceInstanceRouteBindingWorkflows) + this.createServiceInstanceRouteBindingWorkflows) .last(builder) .map(CreateServiceInstanceRouteBindingResponseBuilder::build); } @@ -117,75 +116,73 @@ public class WorkflowServiceInstanceBindingService implements ServiceInstanceBin } private Flux invokeAppBindingBuildResponse( - CreateServiceInstanceAppBindingResponseBuilder builder, CreateServiceInstanceBindingRequest request, - List workflows) { + CreateServiceInstanceAppBindingResponseBuilder builder, CreateServiceInstanceBindingRequest request, + List workflows) { AtomicReference responseBuilder = new AtomicReference<>( - builder); + builder); return Flux.fromIterable(workflows) - .filterWhen(workflow -> workflow.accept(request)) - .concatMap(workflow -> workflow.buildResponse(request, responseBuilder.get()) + .filterWhen((workflow) -> workflow.accept(request)) + .concatMap((workflow) -> workflow.buildResponse(request, responseBuilder.get()) .doOnNext(responseBuilder::set)); } private Flux invokeRouteBindingBuildResponse( - CreateServiceInstanceRouteBindingResponseBuilder builder, CreateServiceInstanceBindingRequest request, - List workflows) { + CreateServiceInstanceRouteBindingResponseBuilder builder, CreateServiceInstanceBindingRequest request, + List workflows) { AtomicReference responseBuilder = new AtomicReference<>( - builder); + builder); return Flux.fromIterable(workflows) - .filterWhen(workflow -> workflow.accept(request)) - .concatMap(workflow -> workflow.buildResponse(request, responseBuilder.get()) + .filterWhen((workflow) -> workflow.accept(request)) + .concatMap((workflow) -> workflow.buildResponse(request, responseBuilder.get()) .doOnNext(responseBuilder::set)); } private boolean isAppBindingRequest(CreateServiceInstanceBindingRequest request) { - return request.getBindResource() != null - && ObjectUtils.isEmpty(request.getBindResource().getRoute()); + return request.getBindResource() != null && ObjectUtils.isEmpty(request.getBindResource().getRoute()); } private boolean isRouteBindingRequest(CreateServiceInstanceBindingRequest request) { - return request.getBindResource() != null - && StringUtils.hasText(request.getBindResource().getRoute()); + return request.getBindResource() != null && StringUtils.hasText(request.getBindResource().getRoute()); } private Mono create(CreateServiceInstanceBindingRequest request, - CreateServiceInstanceBindingResponse response) { - return stateRepository.saveState(request.getServiceInstanceId(), request.getBindingId(), - OperationState.IN_PROGRESS, "create service instance binding started") - .thenMany(invokeCreateWorkflows(request, response) - .doOnRequest(l -> { - LOG.info("Creating service instance binding"); - LOG.debug("request={}", request); - }) - .doOnComplete(() -> { - LOG.debug("Finish creating service instance binding"); - LOG.debug("request={}, response={}", request, response); - }) - .doOnError(e -> LOG.error(String.format("Error creating service instance binding. error=%s", - e.getMessage()), e))) - .thenEmpty(stateRepository.saveState(request.getServiceInstanceId(), request.getBindingId(), - OperationState.SUCCEEDED, "create service instance binding completed") + CreateServiceInstanceBindingResponse response) { + return this.stateRepository + .saveState(request.getServiceInstanceId(), request.getBindingId(), OperationState.IN_PROGRESS, + "create service instance binding started") + .thenMany(invokeCreateWorkflows(request, response).doOnRequest((l) -> { + LOG.info("Creating service instance binding"); + LOG.debug("request={}", request); + }).doOnComplete(() -> { + LOG.debug("Finish creating service instance binding"); + LOG.debug("request={}, response={}", request, response); + }) + .doOnError((e) -> LOG + .error(String.format("Error creating service instance binding. error=%s", e.getMessage()), e))) + .thenEmpty(this.stateRepository + .saveState(request.getServiceInstanceId(), request.getBindingId(), OperationState.SUCCEEDED, + "create service instance binding completed") .then()) - .onErrorResume( - exception -> stateRepository.saveState(request.getServiceInstanceId(), request.getBindingId(), - OperationState.FAILED, exception.getMessage()) - .then()); + .onErrorResume((exception) -> this.stateRepository + .saveState(request.getServiceInstanceId(), request.getBindingId(), OperationState.FAILED, + exception.getMessage()) + .then()); } private Flux invokeCreateWorkflows(CreateServiceInstanceBindingRequest request, - CreateServiceInstanceBindingResponse response) { + CreateServiceInstanceBindingResponse response) { return Flux.defer(() -> { if (isAppBindingRequest(request)) { - return Flux.fromIterable(createServiceInstanceAppBindingWorkflows) - .filterWhen(workflow -> workflow.accept(request)) - .concatMap(workflow -> workflow.create(request, - (CreateServiceInstanceAppBindingResponse) response)); + return Flux.fromIterable(this.createServiceInstanceAppBindingWorkflows) + .filterWhen((workflow) -> workflow.accept(request)) + .concatMap( + (workflow) -> workflow.create(request, (CreateServiceInstanceAppBindingResponse) response)); } else if (isRouteBindingRequest(request)) { - return Flux.fromIterable(createServiceInstanceRouteBindingWorkflows) - .filterWhen(workflow -> workflow.accept(request)) - .concatMap(workflow -> workflow.create(request, - (CreateServiceInstanceRouteBindingResponse) response)); + return Flux.fromIterable(this.createServiceInstanceRouteBindingWorkflows) + .filterWhen((workflow) -> workflow.accept(request)) + .concatMap((workflow) -> workflow.create(request, + (CreateServiceInstanceRouteBindingResponse) response)); } return Flux.empty(); }); @@ -193,70 +190,70 @@ public class WorkflowServiceInstanceBindingService implements ServiceInstanceBin @Override public Mono deleteServiceInstanceBinding( - DeleteServiceInstanceBindingRequest request) { - return invokeDeleteResponseBuilders(request) - .flatMap(response -> { - if (response.isAsync()) { - return Mono.just(response).publishOn(Schedulers.parallel()) - .doOnNext(r -> delete(request, r) - .subscribe()); - } - else { - return delete(request, response).thenReturn(response); - } - }); + DeleteServiceInstanceBindingRequest request) { + return invokeDeleteResponseBuilders(request).flatMap((response) -> { + if (response.isAsync()) { + return Mono.just(response) + .publishOn(Schedulers.parallel()) + .doOnNext((r) -> delete(request, r).subscribe()); + } + else { + return delete(request, response).thenReturn(response); + } + }); } private Mono invokeDeleteResponseBuilders( - DeleteServiceInstanceBindingRequest request) { - AtomicReference responseBuilder = - new AtomicReference<>(DeleteServiceInstanceBindingResponse.builder()); + DeleteServiceInstanceBindingRequest request) { + AtomicReference responseBuilder = new AtomicReference<>( + DeleteServiceInstanceBindingResponse.builder()); - return Flux.fromIterable(deleteServiceInstanceBindingWorkflows) - .filterWhen(workflow -> workflow.accept(request)) - .flatMap(workflow -> workflow.buildResponse(request, responseBuilder.get()) - .doOnNext(responseBuilder::set)) + return Flux.fromIterable(this.deleteServiceInstanceBindingWorkflows) + .filterWhen((workflow) -> workflow.accept(request)) + .flatMap( + (workflow) -> workflow.buildResponse(request, responseBuilder.get()).doOnNext(responseBuilder::set)) .last(responseBuilder.get()) .map(DeleteServiceInstanceBindingResponseBuilder::build); } private Mono delete(DeleteServiceInstanceBindingRequest request, - DeleteServiceInstanceBindingResponse response) { - return stateRepository.saveState(request.getServiceInstanceId(), request.getBindingId(), - OperationState.IN_PROGRESS, "delete service instance binding started") - .thenMany(invokeDeleteWorkflows(request, response) - .doOnRequest(l -> { - LOG.info("Deleting service instance binding"); - LOG.debug("request={}", request); - }) - .doOnComplete(() -> { - LOG.info("Finish deleting service instance binding"); - LOG.debug("request={}, response={}", request, response); - }) - .doOnError(e -> LOG.error(String.format("Error deleting service instance binding. error=%s", - e.getMessage()), e))) - .thenEmpty(stateRepository.saveState(request.getServiceInstanceId(), request.getBindingId(), - OperationState.SUCCEEDED, "delete service instance binding completed") + DeleteServiceInstanceBindingResponse response) { + return this.stateRepository + .saveState(request.getServiceInstanceId(), request.getBindingId(), OperationState.IN_PROGRESS, + "delete service instance binding started") + .thenMany(invokeDeleteWorkflows(request, response).doOnRequest((l) -> { + LOG.info("Deleting service instance binding"); + LOG.debug("request={}", request); + }).doOnComplete(() -> { + LOG.info("Finish deleting service instance binding"); + LOG.debug("request={}, response={}", request, response); + }) + .doOnError((e) -> LOG + .error(String.format("Error deleting service instance binding. error=%s", e.getMessage()), e))) + .thenEmpty(this.stateRepository + .saveState(request.getServiceInstanceId(), request.getBindingId(), OperationState.SUCCEEDED, + "delete service instance binding completed") .then()) - .onErrorResume( - exception -> stateRepository.saveState(request.getServiceInstanceId(), request.getBindingId(), - OperationState.FAILED, exception.getMessage()) - .then()); + .onErrorResume((exception) -> this.stateRepository + .saveState(request.getServiceInstanceId(), request.getBindingId(), OperationState.FAILED, + exception.getMessage()) + .then()); } private Flux invokeDeleteWorkflows(DeleteServiceInstanceBindingRequest request, - DeleteServiceInstanceBindingResponse response) { - return Flux.fromIterable(deleteServiceInstanceBindingWorkflows) - .filterWhen(workflow -> workflow.accept(request)) - .concatMap(workflow -> workflow.delete(request, response)); + DeleteServiceInstanceBindingResponse response) { + return Flux.fromIterable(this.deleteServiceInstanceBindingWorkflows) + .filterWhen((workflow) -> workflow.accept(request)) + .concatMap((workflow) -> workflow.delete(request, response)); } @Override public Mono getLastOperation( - GetLastServiceBindingOperationRequest request) { - return stateRepository.getState(request.getServiceInstanceId(), request.getBindingId()) - .doOnError(exception -> Mono.error(new ServiceInstanceBindingDoesNotExistException(request.getBindingId()))) - .map(serviceInstanceState -> GetLastServiceBindingOperationResponse.builder() + GetLastServiceBindingOperationRequest request) { + return this.stateRepository.getState(request.getServiceInstanceId(), request.getBindingId()) + .doOnError( + (exception) -> Mono.error(new ServiceInstanceBindingDoesNotExistException(request.getBindingId()))) + .map((serviceInstanceState) -> GetLastServiceBindingOperationResponse.builder() .operationState(serviceInstanceState.getOperationState()) .description(serviceInstanceState.getDescription()) .build()); diff --git a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/service/WorkflowServiceInstanceService.java b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/service/WorkflowServiceInstanceService.java index b7733ee..0134358 100644 --- a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/service/WorkflowServiceInstanceService.java +++ b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/service/WorkflowServiceInstanceService.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,8 +45,11 @@ import org.springframework.cloud.servicebroker.service.ServiceInstanceService; import org.springframework.core.annotation.AnnotationAwareOrderComparator; /** - * A {@code ServiceInstanceService} that delegates to a set of discrete Workflow objects for each service broker - * operation. + * A {@code ServiceInstanceService} that delegates to a set of discrete Workflow objects + * for each service broker operation. + * + * @author Scott Frederick + * @author Roy Clarkson */ public class WorkflowServiceInstanceService implements ServiceInstanceService { @@ -61,9 +64,9 @@ public class WorkflowServiceInstanceService implements ServiceInstanceService { private final ServiceInstanceStateRepository stateRepository; public WorkflowServiceInstanceService(ServiceInstanceStateRepository serviceInstanceStateRepository, - List createServiceInstanceWorkflows, - List deleteServiceInstanceWorkflows, - List updateServiceInstanceWorkflows) { + List createServiceInstanceWorkflows, + List deleteServiceInstanceWorkflows, + List updateServiceInstanceWorkflows) { this.stateRepository = serviceInstanceStateRepository; this.createServiceInstanceWorkflows = createServiceInstanceWorkflows; this.deleteServiceInstanceWorkflows = deleteServiceInstanceWorkflows; @@ -76,157 +79,147 @@ public class WorkflowServiceInstanceService implements ServiceInstanceService { @Override public Mono createServiceInstance(CreateServiceInstanceRequest request) { - return invokeCreateResponseBuilders(request) - .publishOn(Schedulers.parallel()) - .doOnNext(response -> create(request, response) - .subscribe()); + return invokeCreateResponseBuilders(request).publishOn(Schedulers.parallel()) + .doOnNext((response) -> create(request, response).subscribe()); } private Mono invokeCreateResponseBuilders(CreateServiceInstanceRequest request) { - AtomicReference responseBuilder = - new AtomicReference<>(CreateServiceInstanceResponse.builder()); + AtomicReference responseBuilder = new AtomicReference<>( + CreateServiceInstanceResponse.builder()); - return Flux.fromIterable(createServiceInstanceWorkflows) - .filterWhen(workflow -> workflow.accept(request)) - .flatMap(workflow -> workflow.buildResponse(request, responseBuilder.get()) - .doOnNext(responseBuilder::set)) + return Flux.fromIterable(this.createServiceInstanceWorkflows) + .filterWhen((workflow) -> workflow.accept(request)) + .flatMap( + (workflow) -> workflow.buildResponse(request, responseBuilder.get()).doOnNext(responseBuilder::set)) .last(responseBuilder.get()) .map(CreateServiceInstanceResponseBuilder::build); } private Mono create(CreateServiceInstanceRequest request, CreateServiceInstanceResponse response) { - return stateRepository.saveState(request.getServiceInstanceId(), - OperationState.IN_PROGRESS, - "create service instance started") - .thenMany(invokeCreateWorkflows(request, response) - .doOnRequest(l -> { - LOG.info("Creating service instance"); - LOG.debug("request={}", request); - }) - .doOnComplete(() -> { - LOG.info("Finish creating service instance"); - LOG.debug("request={}, response={}", request, response); - }) - .doOnError(e -> LOG.error(String.format("Error creating service instance. error=%s", - e.getMessage()), e))) - .thenEmpty(stateRepository.saveState(request.getServiceInstanceId(), - OperationState.SUCCEEDED, "create service instance completed") + return this.stateRepository + .saveState(request.getServiceInstanceId(), OperationState.IN_PROGRESS, "create service instance started") + .thenMany(invokeCreateWorkflows(request, response).doOnRequest((l) -> { + LOG.info("Creating service instance"); + LOG.debug("request={}", request); + }).doOnComplete(() -> { + LOG.info("Finish creating service instance"); + LOG.debug("request={}, response={}", request, response); + }) + .doOnError((e) -> LOG.error(String.format("Error creating service instance. error=%s", e.getMessage()), + e))) + .thenEmpty(this.stateRepository + .saveState(request.getServiceInstanceId(), OperationState.SUCCEEDED, + "create service instance completed") .then()) - .onErrorResume(exception -> stateRepository.saveState(request.getServiceInstanceId(), - OperationState.FAILED, exception.getMessage()) + .onErrorResume((exception) -> this.stateRepository + .saveState(request.getServiceInstanceId(), OperationState.FAILED, exception.getMessage()) .then()); } private Flux invokeCreateWorkflows(CreateServiceInstanceRequest request, - CreateServiceInstanceResponse response) { - return Flux.fromIterable(createServiceInstanceWorkflows) - .filterWhen(workflow -> workflow.accept(request)) - .concatMap(workflow -> workflow.create(request, response)); + CreateServiceInstanceResponse response) { + return Flux.fromIterable(this.createServiceInstanceWorkflows) + .filterWhen((workflow) -> workflow.accept(request)) + .concatMap((workflow) -> workflow.create(request, response)); } @Override public Mono deleteServiceInstance(DeleteServiceInstanceRequest request) { - return invokeDeleteResponseBuilders(request) - .publishOn(Schedulers.parallel()) - .doOnNext(response -> delete(request, response) - .subscribe()); + return invokeDeleteResponseBuilders(request).publishOn(Schedulers.parallel()) + .doOnNext((response) -> delete(request, response).subscribe()); } private Mono invokeDeleteResponseBuilders(DeleteServiceInstanceRequest request) { - AtomicReference responseBuilder = - new AtomicReference<>(DeleteServiceInstanceResponse.builder()); + AtomicReference responseBuilder = new AtomicReference<>( + DeleteServiceInstanceResponse.builder()); - return Flux.fromIterable(deleteServiceInstanceWorkflows) - .filterWhen(workflow -> workflow.accept(request)) - .flatMap(workflow -> workflow.buildResponse(request, responseBuilder.get()) - .doOnNext(responseBuilder::set)) + return Flux.fromIterable(this.deleteServiceInstanceWorkflows) + .filterWhen((workflow) -> workflow.accept(request)) + .flatMap( + (workflow) -> workflow.buildResponse(request, responseBuilder.get()).doOnNext(responseBuilder::set)) .last(responseBuilder.get()) .map(DeleteServiceInstanceResponseBuilder::build); } private Mono delete(DeleteServiceInstanceRequest request, DeleteServiceInstanceResponse response) { - return stateRepository.saveState(request.getServiceInstanceId(), - OperationState.IN_PROGRESS, "delete service instance started") - .thenMany(invokeDeleteWorkflows(request, response) - .doOnRequest(l -> { - LOG.info("Deleting service instance"); - LOG.debug("request={}", request); - }) - .doOnComplete(() -> { - LOG.info("Finish deleting service instance"); - LOG.debug("request={}, response={}", request, response); - }) - .doOnError(e -> LOG.error(String.format("Error deleting service instance. error=%s", - e.getMessage()), e))) - .thenEmpty(stateRepository.saveState(request.getServiceInstanceId(), - OperationState.SUCCEEDED, "delete service instance completed") + return this.stateRepository + .saveState(request.getServiceInstanceId(), OperationState.IN_PROGRESS, "delete service instance started") + .thenMany(invokeDeleteWorkflows(request, response).doOnRequest((l) -> { + LOG.info("Deleting service instance"); + LOG.debug("request={}", request); + }).doOnComplete(() -> { + LOG.info("Finish deleting service instance"); + LOG.debug("request={}, response={}", request, response); + }) + .doOnError((e) -> LOG.error(String.format("Error deleting service instance. error=%s", e.getMessage()), + e))) + .thenEmpty(this.stateRepository + .saveState(request.getServiceInstanceId(), OperationState.SUCCEEDED, + "delete service instance completed") .then()) - .onErrorResume(e -> stateRepository.saveState(request.getServiceInstanceId(), - OperationState.FAILED, e.getMessage()) + .onErrorResume((e) -> this.stateRepository + .saveState(request.getServiceInstanceId(), OperationState.FAILED, e.getMessage()) .then()); } private Flux invokeDeleteWorkflows(DeleteServiceInstanceRequest request, - DeleteServiceInstanceResponse response) { - return Flux.fromIterable(deleteServiceInstanceWorkflows) - .filterWhen(workflow -> workflow.accept(request)) - .concatMap(workflow -> workflow.delete(request, response)); + DeleteServiceInstanceResponse response) { + return Flux.fromIterable(this.deleteServiceInstanceWorkflows) + .filterWhen((workflow) -> workflow.accept(request)) + .concatMap((workflow) -> workflow.delete(request, response)); } @Override public Mono updateServiceInstance(UpdateServiceInstanceRequest request) { - return invokeUpdateResponseBuilders(request) - .publishOn(Schedulers.parallel()) - .doOnNext(response -> update(request, response) - .subscribe()); + return invokeUpdateResponseBuilders(request).publishOn(Schedulers.parallel()) + .doOnNext((response) -> update(request, response).subscribe()); } private Mono invokeUpdateResponseBuilders(UpdateServiceInstanceRequest request) { - AtomicReference responseBuilder = - new AtomicReference<>(UpdateServiceInstanceResponse.builder()); + AtomicReference responseBuilder = new AtomicReference<>( + UpdateServiceInstanceResponse.builder()); - return Flux.fromIterable(updateServiceInstanceWorkflows) - .filterWhen(workflow -> workflow.accept(request)) - .flatMap(workflow -> workflow.buildResponse(request, responseBuilder.get()) - .doOnNext(responseBuilder::set)) + return Flux.fromIterable(this.updateServiceInstanceWorkflows) + .filterWhen((workflow) -> workflow.accept(request)) + .flatMap( + (workflow) -> workflow.buildResponse(request, responseBuilder.get()).doOnNext(responseBuilder::set)) .last(responseBuilder.get()) .map(UpdateServiceInstanceResponseBuilder::build); } private Mono update(UpdateServiceInstanceRequest request, UpdateServiceInstanceResponse response) { - return stateRepository.saveState(request.getServiceInstanceId(), - OperationState.IN_PROGRESS, "update service instance started") - .thenMany(invokeUpdateWorkflows(request, response) - .doOnRequest(l -> { - LOG.info("Updating service instance"); - LOG.debug("request={}", request); - }) - .doOnComplete(() -> { - LOG.info("Finish updating service instance"); - LOG.debug("request={}, response={}", request, response); - }) - .doOnError(e -> LOG.error(String.format("Error updating service instance. error=%s", - e.getMessage()), e))) - .thenEmpty(stateRepository.saveState(request.getServiceInstanceId(), - OperationState.SUCCEEDED, "update service instance completed") + return this.stateRepository + .saveState(request.getServiceInstanceId(), OperationState.IN_PROGRESS, "update service instance started") + .thenMany(invokeUpdateWorkflows(request, response).doOnRequest((l) -> { + LOG.info("Updating service instance"); + LOG.debug("request={}", request); + }).doOnComplete(() -> { + LOG.info("Finish updating service instance"); + LOG.debug("request={}, response={}", request, response); + }) + .doOnError((e) -> LOG.error(String.format("Error updating service instance. error=%s", e.getMessage()), + e))) + .thenEmpty(this.stateRepository + .saveState(request.getServiceInstanceId(), OperationState.SUCCEEDED, + "update service instance completed") .then()) - .onErrorResume(exception -> stateRepository.saveState(request.getServiceInstanceId(), - OperationState.FAILED, exception.getMessage()) + .onErrorResume((exception) -> this.stateRepository + .saveState(request.getServiceInstanceId(), OperationState.FAILED, exception.getMessage()) .then()); } private Flux invokeUpdateWorkflows(UpdateServiceInstanceRequest request, - UpdateServiceInstanceResponse response) { - return Flux.fromIterable(updateServiceInstanceWorkflows) - .filterWhen(workflow -> workflow.accept(request)) - .concatMap(workflow -> workflow.update(request, response)); + UpdateServiceInstanceResponse response) { + return Flux.fromIterable(this.updateServiceInstanceWorkflows) + .filterWhen((workflow) -> workflow.accept(request)) + .concatMap((workflow) -> workflow.update(request, response)); } @Override public Mono getLastOperation(GetLastServiceOperationRequest request) { - return stateRepository.getState(request.getServiceInstanceId()) - .doOnError(e -> Mono.error(new ServiceInstanceDoesNotExistException(request.getServiceInstanceId()))) - .map(serviceInstanceState -> GetLastServiceOperationResponse.builder() + return this.stateRepository.getState(request.getServiceInstanceId()) + .doOnError((e) -> Mono.error(new ServiceInstanceDoesNotExistException(request.getServiceInstanceId()))) + .map((serviceInstanceState) -> GetLastServiceOperationResponse.builder() .operationState(serviceInstanceState.getOperationState()) .description(serviceInstanceState.getDescription()) .build()); @@ -234,7 +227,7 @@ public class WorkflowServiceInstanceService implements ServiceInstanceService { @Override public Mono getServiceInstance(GetServiceInstanceRequest request) { - //TODO add functionality + // TODO add functionality return Mono.empty(); } diff --git a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/service/package-info.java b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/service/package-info.java new file mode 100644 index 0000000..18dfb90 --- /dev/null +++ b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/service/package-info.java @@ -0,0 +1,20 @@ +/* + * Copyright 2016-2024 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * App Broker Server. + */ +package org.springframework.cloud.appbroker.service; diff --git a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/state/InMemoryServiceInstanceBindingStateRepository.java b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/state/InMemoryServiceInstanceBindingStateRepository.java index 38e806d..deb6c27 100644 --- a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/state/InMemoryServiceInstanceBindingStateRepository.java +++ b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/state/InMemoryServiceInstanceBindingStateRepository.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,10 +27,12 @@ import reactor.core.publisher.Mono; import org.springframework.cloud.servicebroker.model.instance.OperationState; /** - * Default implementation of {@link ServiceInstanceBindingStateRepository} meant for demonstration and testing purposes - * only. + * Default implementation of {@link ServiceInstanceBindingStateRepository} meant for + * demonstration and testing purposes only. *

* WARNING: This implementation is not intended for production applications! + * + * @author Roy Clarkson */ public class InMemoryServiceInstanceBindingStateRepository implements ServiceInstanceBindingStateRepository { @@ -38,41 +40,39 @@ public class InMemoryServiceInstanceBindingStateRepository implements ServiceIns @Override public Mono saveState(String serviceInstanceId, String bindingId, OperationState state, - String description) { + String description) { return Mono.just(new BindingKey(serviceInstanceId, bindingId)) - .flatMap(bindingKey -> Mono + .flatMap((bindingKey) -> Mono .just(new ServiceInstanceState(state, description, new Timestamp(Instant.now().toEpochMilli()))) - .flatMap( - serviceInstanceState -> Mono.fromCallable(() -> this.states.put(bindingKey, serviceInstanceState)) - .thenReturn(serviceInstanceState))); + .flatMap((serviceInstanceState) -> Mono + .fromCallable(() -> this.states.put(bindingKey, serviceInstanceState)) + .thenReturn(serviceInstanceState))); } @Override public Mono getState(String serviceInstanceId, String bindingId) { return Mono.just(new BindingKey(serviceInstanceId, bindingId)) - .flatMap(bindingKey -> containsState(bindingKey) - .flatMap(contains -> Mono.defer(() -> { - if (contains) { - return Mono.fromCallable(() -> this.states.get(bindingKey)); - } - else { - return Mono.error(new IllegalArgumentException("Unknown binding " + bindingKey)); - } - }))); + .flatMap((bindingKey) -> containsState(bindingKey).flatMap((contains) -> Mono.defer(() -> { + if (contains) { + return Mono.fromCallable(() -> this.states.get(bindingKey)); + } + else { + return Mono.error(new IllegalArgumentException("Unknown binding " + bindingKey)); + } + }))); } @Override public Mono removeState(String serviceInstanceId, String bindingId) { return Mono.just(new BindingKey(serviceInstanceId, bindingId)) - .flatMap(bindingKey -> containsState(bindingKey) - .flatMap(contains -> Mono.defer(() -> { - if (contains) { - return Mono.fromCallable(() -> this.states.remove(bindingKey)); - } - else { - return Mono.error(new IllegalArgumentException("Unknown binding " + bindingKey)); - } - }))); + .flatMap((bindingKey) -> containsState(bindingKey).flatMap((contains) -> Mono.defer(() -> { + if (contains) { + return Mono.fromCallable(() -> this.states.remove(bindingKey)); + } + else { + return Mono.error(new IllegalArgumentException("Unknown binding " + bindingKey)); + } + }))); } private Mono containsState(BindingKey bindingKey) { @@ -85,15 +85,15 @@ public class InMemoryServiceInstanceBindingStateRepository implements ServiceIns private final String bindingId; - public String getServiceInstanceId() { + String getServiceInstanceId() { return this.serviceInstanceId; } - public String getBindingId() { + String getBindingId() { return this.bindingId; } - public BindingKey(String serviceInstanceId, String bindingId) { + BindingKey(String serviceInstanceId, String bindingId) { this.serviceInstanceId = serviceInstanceId; this.bindingId = bindingId; } @@ -107,27 +107,25 @@ public class InMemoryServiceInstanceBindingStateRepository implements ServiceIns return false; } BindingKey that = (BindingKey) obj; - return Objects.equals(this.bindingId, that.bindingId) && - Objects.equals(this.serviceInstanceId, that.serviceInstanceId); + return Objects.equals(this.bindingId, that.bindingId) + && Objects.equals(this.serviceInstanceId, that.serviceInstanceId); } @Override public int hashCode() { - return Objects.hash(serviceInstanceId, bindingId); + return Objects.hash(this.serviceInstanceId, this.bindingId); } @Override public String toString() { - return "BindingKey{" + - "serviceInstanceId='" + serviceInstanceId + '\'' + - ", bindingId='" + bindingId + '\'' + - '}'; + return "BindingKey{" + "serviceInstanceId='" + this.serviceInstanceId + '\'' + ", bindingId='" + + this.bindingId + '\'' + '}'; } @Override public int compareTo(BindingKey other) { int compare = this.serviceInstanceId.compareTo(other.serviceInstanceId); - return compare == 0 ? this.bindingId.compareTo(other.bindingId) : compare; + return (compare == 0) ? this.bindingId.compareTo(other.bindingId) : compare; } } diff --git a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/state/InMemoryServiceInstanceStateRepository.java b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/state/InMemoryServiceInstanceStateRepository.java index f43504e..e7247fd 100644 --- a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/state/InMemoryServiceInstanceStateRepository.java +++ b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/state/InMemoryServiceInstanceStateRepository.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,9 +26,12 @@ import reactor.core.publisher.Mono; import org.springframework.cloud.servicebroker.model.instance.OperationState; /** - * Default implementation of {@link ServiceInstanceStateRepository} meant for demonstration and testing purposes only. + * Default implementation of {@link ServiceInstanceStateRepository} meant for + * demonstration and testing purposes only. *

* WARNING: This implementation is not intended for production applications! + * + * @author Roy Clarkson */ public class InMemoryServiceInstanceStateRepository implements ServiceInstanceStateRepository { @@ -37,35 +40,33 @@ public class InMemoryServiceInstanceStateRepository implements ServiceInstanceSt @Override public Mono saveState(String serviceInstanceId, OperationState state, String description) { return Mono.just(new ServiceInstanceState(state, description, new Timestamp(Instant.now().toEpochMilli()))) - .flatMap(serviceInstanceState -> Mono + .flatMap((serviceInstanceState) -> Mono .fromCallable(() -> this.states.put(serviceInstanceId, serviceInstanceState)) .thenReturn(serviceInstanceState)); } @Override public Mono getState(String serviceInstanceId) { - return containsState(serviceInstanceId) - .flatMap(contains -> Mono.defer(() -> { - if (contains) { - return Mono.fromCallable(() -> this.states.get(serviceInstanceId)); - } - else { - return Mono.error(new IllegalArgumentException("Unknown service instance ID " + serviceInstanceId)); - } - })); + return containsState(serviceInstanceId).flatMap((contains) -> Mono.defer(() -> { + if (contains) { + return Mono.fromCallable(() -> this.states.get(serviceInstanceId)); + } + else { + return Mono.error(new IllegalArgumentException("Unknown service instance ID " + serviceInstanceId)); + } + })); } @Override public Mono removeState(String serviceInstanceId) { - return containsState(serviceInstanceId) - .flatMap(contains -> Mono.defer(() -> { - if (contains) { - return Mono.fromCallable(() -> this.states.remove(serviceInstanceId)); - } - else { - return Mono.error(new IllegalArgumentException("Unknown service instance ID " + serviceInstanceId)); - } - })); + return containsState(serviceInstanceId).flatMap((contains) -> Mono.defer(() -> { + if (contains) { + return Mono.fromCallable(() -> this.states.remove(serviceInstanceId)); + } + else { + return Mono.error(new IllegalArgumentException("Unknown service instance ID " + serviceInstanceId)); + } + })); } private Mono containsState(String serviceInstanceId) { diff --git a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/state/ServiceInstanceBindingStateRepository.java b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/state/ServiceInstanceBindingStateRepository.java index 26f8dee..980617d 100644 --- a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/state/ServiceInstanceBindingStateRepository.java +++ b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/state/ServiceInstanceBindingStateRepository.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,12 +21,14 @@ import reactor.core.publisher.Mono; import org.springframework.cloud.servicebroker.model.instance.OperationState; /** + * Interface for a service instance binding state repository. + * * @author Roy Clarkson */ public interface ServiceInstanceBindingStateRepository { default Mono saveState(String serviceInstanceId, String bindingId, OperationState state, - String description) { + String description) { return Mono.empty(); } diff --git a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/state/ServiceInstanceState.java b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/state/ServiceInstanceState.java index 86219d6..cbe4b3d 100644 --- a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/state/ServiceInstanceState.java +++ b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/state/ServiceInstanceState.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,7 +21,7 @@ import java.sql.Timestamp; import org.springframework.cloud.servicebroker.model.instance.OperationState; /** - * Object for persisting the state of a service instance operation + * Object for persisting the state of a service instance operation. * * @author Roy Clarkson */ @@ -34,11 +34,11 @@ public class ServiceInstanceState { private final Timestamp lastUpdated; public OperationState getOperationState() { - return operationState; + return this.operationState; } public String getDescription() { - return description; + return this.description; } public Timestamp getLastUpdated() { diff --git a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/state/ServiceInstanceStateRepository.java b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/state/ServiceInstanceStateRepository.java index e367d84..1f03873 100644 --- a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/state/ServiceInstanceStateRepository.java +++ b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/state/ServiceInstanceStateRepository.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,6 +21,8 @@ import reactor.core.publisher.Mono; import org.springframework.cloud.servicebroker.model.instance.OperationState; /** + * Interface for service instance state repository. + * * @author Roy Clarkson */ public interface ServiceInstanceStateRepository { diff --git a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/state/package-info.java b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/state/package-info.java new file mode 100644 index 0000000..930d9d0 --- /dev/null +++ b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/state/package-info.java @@ -0,0 +1,20 @@ +/* + * Copyright 2016-2024 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * App Broker State. + */ +package org.springframework.cloud.appbroker.state; diff --git a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/workflow/instance/AppDeploymentCreateServiceInstanceWorkflow.java b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/workflow/instance/AppDeploymentCreateServiceInstanceWorkflow.java index 1588234..762c6fe 100644 --- a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/workflow/instance/AppDeploymentCreateServiceInstanceWorkflow.java +++ b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/workflow/instance/AppDeploymentCreateServiceInstanceWorkflow.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,9 +34,8 @@ import org.springframework.cloud.servicebroker.model.instance.CreateServiceInsta import org.springframework.core.annotation.Order; @Order(0) -public class AppDeploymentCreateServiceInstanceWorkflow - extends AppDeploymentInstanceWorkflow - implements CreateServiceInstanceWorkflow { +public class AppDeploymentCreateServiceInstanceWorkflow extends AppDeploymentInstanceWorkflow + implements CreateServiceInstanceWorkflow { private static final Logger LOG = Loggers.getLogger(AppDeploymentCreateServiceInstanceWorkflow.class); @@ -53,11 +52,11 @@ public class AppDeploymentCreateServiceInstanceWorkflow private final TargetService targetService; public AppDeploymentCreateServiceInstanceWorkflow(BrokeredServices brokeredServices, - BackingAppDeploymentService deploymentService, - BackingServicesProvisionService backingServicesProvisionService, - BackingApplicationsParametersTransformationService appsParametersTransformationService, - BackingServicesParametersTransformationService servicesParametersTransformationService, - TargetService targetService) { + BackingAppDeploymentService deploymentService, + BackingServicesProvisionService backingServicesProvisionService, + BackingApplicationsParametersTransformationService appsParametersTransformationService, + BackingServicesParametersTransformationService servicesParametersTransformationService, + TargetService targetService) { super(brokeredServices); this.deploymentService = deploymentService; this.backingServicesProvisionService = backingServicesProvisionService; @@ -68,36 +67,33 @@ public class AppDeploymentCreateServiceInstanceWorkflow @Override public Mono create(CreateServiceInstanceRequest request, CreateServiceInstanceResponse response) { - return createBackingServices(request) - .thenMany(deployBackingApplications(request)) - .then(); + return createBackingServices(request).thenMany(deployBackingApplications(request)).then(); } private Flux createBackingServices(CreateServiceInstanceRequest request) { return getBackingServicesForService(request.getServiceDefinition(), request.getPlan()) - .flatMap(backingServices -> getTargetForService(request.getServiceDefinition(), request.getPlan()) - .flatMap(targetSpec -> targetService.addToBackingServices(backingServices, targetSpec, - request.getServiceInstanceId())) + .flatMap((backingServices) -> getTargetForService(request.getServiceDefinition(), request.getPlan()) + .flatMap((targetSpec) -> this.targetService.addToBackingServices(backingServices, targetSpec, + request.getServiceInstanceId())) .defaultIfEmpty(backingServices)) - .flatMap(backingServices -> - servicesParametersTransformationService.transformParameters(backingServices, - request.getParameters())) - .flatMapMany(backingServicesProvisionService::createServiceInstance) - .doOnRequest(l -> { + .flatMap((backingServices) -> this.servicesParametersTransformationService + .transformParameters(backingServices, request.getParameters())) + .flatMapMany(this.backingServicesProvisionService::createServiceInstance) + .doOnRequest((l) -> { LOG.info("Creating backing services. serviceDefinitionName={}, planName={}", - request.getServiceDefinition().getName(), request.getPlan().getName()); + request.getServiceDefinition().getName(), request.getPlan().getName()); LOG.debug(REQUEST_LOG_TEMPLATE, request); }) .doOnComplete(() -> { LOG.info("Finish creating backing services. serviceDefinitionName={}, planName={}", - request.getServiceDefinition().getName(), request.getPlan().getName()); + request.getServiceDefinition().getName(), request.getPlan().getName()); LOG.debug(REQUEST_LOG_TEMPLATE, request); }) - .doOnError(e -> { + .doOnError((e) -> { if (LOG.isErrorEnabled()) { - LOG.error(String.format("Error creating backing services. serviceDefinitionName=%s, planName=%s, " + - "error=%s", - request.getServiceDefinition().getName(), request.getPlan().getName(), e.getMessage()), e); + LOG.error(String.format( + "Error creating backing services. serviceDefinitionName=%s, planName=%s, " + "error=%s", + request.getServiceDefinition().getName(), request.getPlan().getName(), e.getMessage()), e); } LOG.debug(REQUEST_LOG_TEMPLATE, request); }); @@ -105,29 +101,29 @@ public class AppDeploymentCreateServiceInstanceWorkflow private Flux deployBackingApplications(CreateServiceInstanceRequest request) { return getBackingApplicationsForService(request.getServiceDefinition(), request.getPlan()) - .flatMap(backingApps -> getTargetForService(request.getServiceDefinition(), request.getPlan()) - .flatMap(targetSpec -> targetService.addToBackingApplications(backingApps, targetSpec, - request.getServiceInstanceId())) + .flatMap((backingApps) -> getTargetForService(request.getServiceDefinition(), request.getPlan()) + .flatMap((targetSpec) -> this.targetService.addToBackingApplications(backingApps, targetSpec, + request.getServiceInstanceId())) .defaultIfEmpty(backingApps)) - .flatMap(backingApps -> - appsParametersTransformationService.transformParameters(backingApps, + .flatMap((backingApps) -> this.appsParametersTransformationService.transformParameters(backingApps, request.getParameters())) - .flatMapMany(backingApps -> deploymentService.deploy(backingApps, request.getServiceInstanceId())) - .doOnRequest(l -> { + .flatMapMany((backingApps) -> this.deploymentService.deploy(backingApps, request.getServiceInstanceId())) + .doOnRequest((l) -> { LOG.info("Deploying backing applications. serviceDefinitionName={}, planName={}", - request.getServiceDefinition().getName(), request.getPlan().getName()); + request.getServiceDefinition().getName(), request.getPlan().getName()); LOG.debug(REQUEST_LOG_TEMPLATE, request); }) .doOnComplete(() -> { LOG.info("Finish deploying backing applications. serviceDefinitionName={}, planName={}", - request.getServiceDefinition().getName(), request.getPlan().getName()); + request.getServiceDefinition().getName(), request.getPlan().getName()); LOG.debug(REQUEST_LOG_TEMPLATE, request); }) - .doOnError(e -> { + .doOnError((e) -> { if (LOG.isErrorEnabled()) { - LOG.error(String.format("Error deploying backing applications. serviceDefinitionName=%s, " + - "planName=%s, error=%s", request.getServiceDefinition().getName(), request.getPlan().getName(), - e.getMessage()), e); + LOG.error(String.format( + "Error deploying backing applications. serviceDefinitionName=%s, " + + "planName=%s, error=%s", + request.getServiceDefinition().getName(), request.getPlan().getName(), e.getMessage()), e); } LOG.debug(REQUEST_LOG_TEMPLATE, request); }); @@ -140,7 +136,7 @@ public class AppDeploymentCreateServiceInstanceWorkflow @Override public Mono buildResponse(CreateServiceInstanceRequest request, - CreateServiceInstanceResponseBuilder responseBuilder) { + CreateServiceInstanceResponseBuilder responseBuilder) { return Mono.just(responseBuilder.async(true)); } diff --git a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/workflow/instance/AppDeploymentDeleteServiceInstanceWorkflow.java b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/workflow/instance/AppDeploymentDeleteServiceInstanceWorkflow.java index 7bf2f3c..154bd2e 100644 --- a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/workflow/instance/AppDeploymentDeleteServiceInstanceWorkflow.java +++ b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/workflow/instance/AppDeploymentDeleteServiceInstanceWorkflow.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2021 the original author or authors. + * Copyright 2016-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,9 +42,8 @@ import org.springframework.core.annotation.Order; import org.springframework.util.CollectionUtils; @Order(0) -public class AppDeploymentDeleteServiceInstanceWorkflow - extends AppDeploymentInstanceWorkflow - implements DeleteServiceInstanceWorkflow { +public class AppDeploymentDeleteServiceInstanceWorkflow extends AppDeploymentInstanceWorkflow + implements DeleteServiceInstanceWorkflow { private static final Logger LOG = Loggers.getLogger(AppDeploymentDeleteServiceInstanceWorkflow.class); @@ -61,11 +60,9 @@ public class AppDeploymentDeleteServiceInstanceWorkflow private final TargetService targetService; public AppDeploymentDeleteServiceInstanceWorkflow(BrokeredServices brokeredServices, - BackingAppDeploymentService deploymentService, - BackingAppManagementService backingAppManagementService, - BackingServicesProvisionService backingServicesProvisionService, - BackingSpaceManagementService backingSpaceManagementService, - TargetService targetService) { + BackingAppDeploymentService deploymentService, BackingAppManagementService backingAppManagementService, + BackingServicesProvisionService backingServicesProvisionService, + BackingSpaceManagementService backingSpaceManagementService, TargetService targetService) { super(brokeredServices); this.deploymentService = deploymentService; this.backingAppManagementService = backingAppManagementService; @@ -76,74 +73,67 @@ public class AppDeploymentDeleteServiceInstanceWorkflow @Override public Mono delete(DeleteServiceInstanceRequest request, DeleteServiceInstanceResponse response) { - return deleteBackingServices(request) - .flatMapMany(Flux::fromIterable) + return deleteBackingServices(request).flatMapMany(Flux::fromIterable) .map(BackingService::getProperties) - .concatWith(undeployBackingApplications(request) - .flatMapMany(Flux::fromIterable) + .concatWith(undeployBackingApplications(request).flatMapMany(Flux::fromIterable) .map(BackingApplication::getProperties)) - .filter(properties -> - properties != null && properties.containsKey(DeploymentProperties.TARGET_PROPERTY_KEY)) - .map(properties -> properties.get(DeploymentProperties.TARGET_PROPERTY_KEY)) + .filter((properties) -> properties != null + && properties.containsKey(DeploymentProperties.TARGET_PROPERTY_KEY)) + .map((properties) -> properties.get(DeploymentProperties.TARGET_PROPERTY_KEY)) .distinct() .collectList() - .flatMapMany(backingSpaceManagementService::deleteTargetSpaces) + .flatMapMany(this.backingSpaceManagementService::deleteTargetSpaces) .then(); } private Mono> deleteBackingServices(DeleteServiceInstanceRequest request) { - return collectBackingServices(request) - .collectList() - .delayUntil(backingServices -> { - if (!CollectionUtils.isEmpty(backingServices)) { - return backingServicesProvisionService.deleteServiceInstance(backingServices) - .doOnRequest(l -> { - LOG.info("Deleting backing services. serviceDefinitionName={}, planName={}", - request.getServiceDefinition().getName(), request.getPlan().getName()); - LOG.debug(REQUEST_LOG_TEMPLATE, request); - }) - .doOnComplete(() -> { - LOG.info("Finish deleting backing services. serviceDefinitionName={}, planName={}", - request.getServiceDefinition().getName(), request.getPlan().getName()); - LOG.debug(REQUEST_LOG_TEMPLATE, request); - }) - .doOnError(e -> { - if (LOG.isErrorEnabled()) { - LOG.error(String.format("Error deleting backing services. " + - "serviceDefinitionName=%s, planName=%s, error=%s", - request.getServiceDefinition().getName(), - request.getPlan().getName(), e.getMessage()), e); - } - LOG.debug(REQUEST_LOG_TEMPLATE, request); - }); - } - return Flux.empty(); - }); + return collectBackingServices(request).collectList().delayUntil((backingServices) -> { + if (!CollectionUtils.isEmpty(backingServices)) { + return this.backingServicesProvisionService.deleteServiceInstance(backingServices).doOnRequest((l) -> { + LOG.info("Deleting backing services. serviceDefinitionName={}, planName={}", + request.getServiceDefinition().getName(), request.getPlan().getName()); + LOG.debug(REQUEST_LOG_TEMPLATE, request); + }).doOnComplete(() -> { + LOG.info("Finish deleting backing services. serviceDefinitionName={}, planName={}", + request.getServiceDefinition().getName(), request.getPlan().getName()); + LOG.debug(REQUEST_LOG_TEMPLATE, request); + }).doOnError((e) -> { + if (LOG.isErrorEnabled()) { + LOG.error(String.format( + "Error deleting backing services. " + "serviceDefinitionName=%s, planName=%s, error=%s", + request.getServiceDefinition().getName(), request.getPlan().getName(), e.getMessage()), + e); + } + LOG.debug(REQUEST_LOG_TEMPLATE, request); + }); + } + return Flux.empty(); + }); } private Flux collectBackingServices(DeleteServiceInstanceRequest request) { - return collectConfiguredBackingServices(request) - .concatWith(collectBoundBackingServices(request)) + return collectConfiguredBackingServices(request).concatWith(collectBoundBackingServices(request)) .distinct(BackingService::serviceInstanceNameAndSpaceHashCode); } private Flux collectConfiguredBackingServices(DeleteServiceInstanceRequest request) { return getBackingServicesForService(request.getServiceDefinition(), request.getPlan()) - .flatMap(backingServices -> getTargetForService(request.getServiceDefinition(), request.getPlan()) - .flatMap(targetSpec -> targetService.addToBackingServices(backingServices, targetSpec, - request.getServiceInstanceId())) + .flatMap((backingServices) -> getTargetForService(request.getServiceDefinition(), request.getPlan()) + .flatMap((targetSpec) -> this.targetService.addToBackingServices(backingServices, targetSpec, + request.getServiceInstanceId())) .defaultIfEmpty(backingServices)) .flatMapMany(Flux::fromIterable); } private Flux collectBoundBackingServices(DeleteServiceInstanceRequest request) { - return backingAppManagementService.getDeployedBackingApplications(request.getServiceInstanceId(), - request.getServiceDefinition().getName(), request.getPlan().getName()) + return this.backingAppManagementService + .getDeployedBackingApplications(request.getServiceInstanceId(), request.getServiceDefinition().getName(), + request.getPlan().getName()) .flatMapMany(Flux::fromIterable) - .flatMap(backingApplication -> Mono.justOrEmpty(backingApplication.getServices()) + .flatMap((backingApplication) -> Mono.justOrEmpty(backingApplication.getServices()) .flatMapMany(Flux::fromIterable) - .flatMap(servicesSpec -> Mono.justOrEmpty(servicesSpec.getServiceInstanceName())) - .map(serviceInstanceName -> { + .flatMap((servicesSpec) -> Mono.justOrEmpty(servicesSpec.getServiceInstanceName())) + .map((serviceInstanceName) -> { Map properties = null; if (!CollectionUtils.isEmpty(backingApplication.getProperties())) { String target = backingApplication.getProperties() @@ -159,30 +149,27 @@ public class AppDeploymentDeleteServiceInstanceWorkflow private Mono> undeployBackingApplications(DeleteServiceInstanceRequest request) { return getBackingApplicationsForService(request.getServiceDefinition(), request.getPlan()) - .flatMap(backingApps -> getTargetForService(request.getServiceDefinition(), request.getPlan()) - .flatMap(targetSpec -> targetService.addToBackingApplications(backingApps, targetSpec, - request.getServiceInstanceId())) + .flatMap((backingApps) -> getTargetForService(request.getServiceDefinition(), request.getPlan()) + .flatMap((targetSpec) -> this.targetService.addToBackingApplications(backingApps, targetSpec, + request.getServiceInstanceId())) .defaultIfEmpty(backingApps)) - .delayUntil(backingApps -> deploymentService.undeploy(backingApps) - .doOnRequest(l -> { - LOG.info("Undeploying backing applications. serviceDefinitionName={}, planName={}", + .delayUntil((backingApps) -> this.deploymentService.undeploy(backingApps).doOnRequest((l) -> { + LOG.info("Undeploying backing applications. serviceDefinitionName={}, planName={}", request.getServiceDefinition().getName(), request.getPlan().getName()); - LOG.debug(REQUEST_LOG_TEMPLATE, request); - }) - .doOnComplete(() -> { - LOG.info("Finish undeploying backing applications. serviceDefinitionName={}, planName={}", + LOG.debug(REQUEST_LOG_TEMPLATE, request); + }).doOnComplete(() -> { + LOG.info("Finish undeploying backing applications. serviceDefinitionName={}, planName={}", request.getServiceDefinition().getName(), request.getPlan().getName()); - LOG.debug(REQUEST_LOG_TEMPLATE, request); - }) - .doOnError(e -> { - if (LOG.isErrorEnabled()) { - LOG.error(String.format("Error undeploying backing applications. serviceDefinitionName=%s, " + - "planName=%s, error=%s", request.getServiceDefinition().getName(), - request.getPlan().getName(), - e.getMessage()), e); - } - LOG.debug(REQUEST_LOG_TEMPLATE, request); - })); + LOG.debug(REQUEST_LOG_TEMPLATE, request); + }).doOnError((e) -> { + if (LOG.isErrorEnabled()) { + LOG.error(String.format( + "Error undeploying backing applications. serviceDefinitionName=%s, " + + "planName=%s, error=%s", + request.getServiceDefinition().getName(), request.getPlan().getName(), e.getMessage()), e); + } + LOG.debug(REQUEST_LOG_TEMPLATE, request); + })); } @Override @@ -192,7 +179,7 @@ public class AppDeploymentDeleteServiceInstanceWorkflow @Override public Mono buildResponse(DeleteServiceInstanceRequest request, - DeleteServiceInstanceResponseBuilder responseBuilder) { + DeleteServiceInstanceResponseBuilder responseBuilder) { return Mono.just(responseBuilder.async(true)); } diff --git a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/workflow/instance/AppDeploymentInstanceWorkflow.java b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/workflow/instance/AppDeploymentInstanceWorkflow.java index a2b75c7..ac577ba 100644 --- a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/workflow/instance/AppDeploymentInstanceWorkflow.java +++ b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/workflow/instance/AppDeploymentInstanceWorkflow.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,41 +41,39 @@ public class AppDeploymentInstanceWorkflow { protected Mono accept(ServiceDefinition serviceDefinition, Plan plan) { return getBackingApplicationsForService(serviceDefinition, plan) - .map(backingApplications -> !backingApplications.isEmpty()) - .filter(Boolean::booleanValue) // filter out Boolean.False to proceed with flux, see https://stackoverflow.com/questions/49860558/project-reactor-conditional-execution - .switchIfEmpty( - getBackingServicesForService(serviceDefinition, plan) - .map(backingServices -> !backingServices.isEmpty()) - .defaultIfEmpty(false) - ); + .map((backingApplications) -> !backingApplications.isEmpty()) + .filter(Boolean::booleanValue) // filter out Boolean.False to proceed with + // flux, see + // https://stackoverflow.com/questions/49860558/project-reactor-conditional-execution + .switchIfEmpty(getBackingServicesForService(serviceDefinition, plan) + .map((backingServices) -> !backingServices.isEmpty()) + .defaultIfEmpty(false)); } protected Mono getTargetForService(ServiceDefinition serviceDefinition, Plan plan) { return findBrokeredService(serviceDefinition, plan) - .flatMap(brokeredService -> Mono.justOrEmpty(brokeredService.getTarget())); + .flatMap((brokeredService) -> Mono.justOrEmpty(brokeredService.getTarget())); } protected Mono> getBackingApplicationsForService(ServiceDefinition serviceDefinition, - Plan plan) { + Plan plan) { return findBrokeredService(serviceDefinition, plan) - .flatMap(brokeredService -> Mono.justOrEmpty(brokeredService.getApps())) - .map(backingApplications -> BackingApplications.builder() + .flatMap((brokeredService) -> Mono.justOrEmpty(brokeredService.getApps())) + .map((backingApplications) -> BackingApplications.builder() .backingApplications(backingApplications) .build()); } protected Mono> getBackingServicesForService(ServiceDefinition serviceDefinition, Plan plan) { return findBrokeredService(serviceDefinition, plan) - .flatMap(brokeredService -> Mono.justOrEmpty(brokeredService.getServices())) - .map(backingServices -> BackingServices.builder() - .backingServices(backingServices) - .build()); + .flatMap((brokeredService) -> Mono.justOrEmpty(brokeredService.getServices())) + .map((backingServices) -> BackingServices.builder().backingServices(backingServices).build()); } private Mono findBrokeredService(ServiceDefinition serviceDefinition, Plan plan) { - return Flux.fromIterable(brokeredServices) - .filter(brokeredService -> brokeredService.getServiceName().equals(serviceDefinition.getName()) - && brokeredService.getPlanName().equals(plan.getName())) + return Flux.fromIterable(this.brokeredServices) + .filter((brokeredService) -> brokeredService.getServiceName().equals(serviceDefinition.getName()) + && brokeredService.getPlanName().equals(plan.getName())) .singleOrEmpty(); } diff --git a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/workflow/instance/AppDeploymentUpdateServiceInstanceWorkflow.java b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/workflow/instance/AppDeploymentUpdateServiceInstanceWorkflow.java index 642a492..db5361c 100644 --- a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/workflow/instance/AppDeploymentUpdateServiceInstanceWorkflow.java +++ b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/workflow/instance/AppDeploymentUpdateServiceInstanceWorkflow.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2021 the original author or authors. + * Copyright 2016-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,7 +48,7 @@ import org.springframework.core.annotation.Order; @Order(0) public class AppDeploymentUpdateServiceInstanceWorkflow extends AppDeploymentInstanceWorkflow - implements UpdateServiceInstanceWorkflow { + implements UpdateServiceInstanceWorkflow { private static final Logger LOG = Loggers.getLogger(AppDeploymentUpdateServiceInstanceWorkflow.class); @@ -67,12 +67,11 @@ public class AppDeploymentUpdateServiceInstanceWorkflow extends AppDeploymentIns private final TargetService targetService; public AppDeploymentUpdateServiceInstanceWorkflow(BrokeredServices brokeredServices, - BackingAppDeploymentService deploymentService, - BackingAppManagementService backingAppManagementService, - BackingServicesProvisionService backingServicesProvisionService, - BackingApplicationsParametersTransformationService appsParametersTransformationService, - BackingServicesParametersTransformationService servicesParametersTransformationService, - TargetService targetService) { + BackingAppDeploymentService deploymentService, BackingAppManagementService backingAppManagementService, + BackingServicesProvisionService backingServicesProvisionService, + BackingApplicationsParametersTransformationService appsParametersTransformationService, + BackingServicesParametersTransformationService servicesParametersTransformationService, + TargetService targetService) { super(brokeredServices); this.deploymentService = deploymentService; this.backingAppManagementService = backingAppManagementService; @@ -85,36 +84,38 @@ public class AppDeploymentUpdateServiceInstanceWorkflow extends AppDeploymentIns @Override public Mono update(UpdateServiceInstanceRequest request, UpdateServiceInstanceResponse response) { return preUpdateBackingApplications(request) - .flatMap(backingApps -> updateBackingServices(request).then(Mono.just(backingApps))) - .flatMapMany(backingApps -> updateBackingApplications(request, backingApps)) + .flatMap((backingApps) -> updateBackingServices(request).then(Mono.just(backingApps))) + .flatMapMany((backingApps) -> updateBackingApplications(request, backingApps)) .then(); } private Mono> preUpdateBackingApplications(UpdateServiceInstanceRequest request) { return getBackingApplicationsForService(request.getServiceDefinition(), request.getPlan()) - .flatMap(backingApps -> getTargetForService(request.getServiceDefinition(), request.getPlan()) - .flatMap(targetSpec -> targetService.addToBackingApplications(backingApps, targetSpec, - request.getServiceInstanceId())) + .flatMap((backingApps) -> getTargetForService(request.getServiceDefinition(), request.getPlan()) + .flatMap((targetSpec) -> this.targetService.addToBackingApplications(backingApps, targetSpec, + request.getServiceInstanceId())) .defaultIfEmpty(backingApps)) - .flatMap(backingApps -> - appsParametersTransformationService.transformParameters(backingApps, request.getParameters())) - .flatMap(backingApps -> deploymentService.prepareForUpdate(backingApps, request.getServiceInstanceId()) + .flatMap((backingApps) -> this.appsParametersTransformationService.transformParameters(backingApps, + request.getParameters())) + .flatMap((backingApps) -> this.deploymentService + .prepareForUpdate(backingApps, request.getServiceInstanceId()) .then(Mono.just(backingApps))) - .doOnRequest(l -> { + .doOnRequest((l) -> { LOG.info("Preparing for update of backing applications. serviceDefinitionName={}, planName={}", - request.getServiceDefinition().getName(), request.getPlan().getName()); + request.getServiceDefinition().getName(), request.getPlan().getName()); LOG.debug(REQUEST_LOG_TEMPLATE, request); }) - .doOnSuccess(backingApplications -> { + .doOnSuccess((backingApplications) -> { LOG.info("Finish preparing for update of backing applications. serviceDefinitionName={}, planName={}", - request.getServiceDefinition().getName(), request.getPlan().getName()); + request.getServiceDefinition().getName(), request.getPlan().getName()); LOG.debug(REQUEST_LOG_TEMPLATE, request); }) - .doOnError(e -> { + .doOnError((e) -> { if (LOG.isErrorEnabled()) { - LOG.error(String.format("Error preparing for update of backing applications. serviceDefinitionName=%s, " + - "planName=%s, error=%s", request.getServiceDefinition().getName(), request.getPlan().getName(), - e.getMessage()), e); + LOG.error(String.format( + "Error preparing for update of backing applications. serviceDefinitionName=%s, " + + "planName=%s, error=%s", + request.getServiceDefinition().getName(), request.getPlan().getName(), e.getMessage()), e); } LOG.debug(REQUEST_LOG_TEMPLATE, request); }); @@ -122,17 +123,16 @@ public class AppDeploymentUpdateServiceInstanceWorkflow extends AppDeploymentIns private Flux updateBackingServices(UpdateServiceInstanceRequest request) { return getBackingServicesForService(request.getServiceDefinition(), request.getPlan()) - .flatMap(backingServices -> getTargetForService(request.getServiceDefinition(), request.getPlan()) - .flatMap(targetSpec -> targetService.addToBackingServices(backingServices, targetSpec, - request.getServiceInstanceId())) + .flatMap((backingServices) -> getTargetForService(request.getServiceDefinition(), request.getPlan()) + .flatMap((targetSpec) -> this.targetService.addToBackingServices(backingServices, targetSpec, + request.getServiceInstanceId())) .defaultIfEmpty(backingServices)) - .flatMap(backingServices -> - servicesParametersTransformationService.transformParameters(backingServices, - request.getParameters())) - .flatMap(backingServices -> Flux.fromIterable(backingServices) + .flatMap((backingServices) -> this.servicesParametersTransformationService + .transformParameters(backingServices, request.getParameters())) + .flatMap((backingServices) -> Flux.fromIterable(backingServices) .collectMap(BackingService::getServiceInstanceName, Function.identity())) .zipWith(getExistingBackingServiceNameMap(request)) - .flatMapMany(newAndExisting -> { + .flatMapMany((newAndExisting) -> { Map newServices = newAndExisting.getT1(); Map existingServices = newAndExisting.getT2(); @@ -142,66 +142,64 @@ public class AppDeploymentUpdateServiceInstanceWorkflow extends AppDeploymentIns List servicesToUpdate = servicesInNameList(newServices, serviceNamesToUpdate); List servicesToCreate = servicesInNameList(newServices, serviceNamesToCreate); - List servicesToDelete = servicesInNameList(existingServices, - serviceNamesToDelete); + List servicesToDelete = servicesInNameList(existingServices, serviceNamesToDelete); LOG.debug("Backing services to update: {}", serviceNamesToUpdate); LOG.debug("Backing services to create: {}", serviceNamesToCreate); LOG.debug("Backing services to delete: {}", serviceNamesToDelete); - return Flux.concat( - backingServicesProvisionService.updateServiceInstance(servicesToUpdate), - backingServicesProvisionService.createServiceInstance(servicesToCreate), - backingServicesProvisionService.deleteServiceInstance(servicesToDelete)) + return Flux + .concat(this.backingServicesProvisionService.updateServiceInstance(servicesToUpdate), + this.backingServicesProvisionService.createServiceInstance(servicesToCreate), + this.backingServicesProvisionService.deleteServiceInstance(servicesToDelete)) .parallel() .runOn(Schedulers.parallel()); }) - .doOnRequest(l -> { + .doOnRequest((l) -> { LOG.info("Updating backing services. serviceDefinitionName={}, planName={}", - request.getServiceDefinition().getName(), request.getPlan().getName()); + request.getServiceDefinition().getName(), request.getPlan().getName()); LOG.debug(REQUEST_LOG_TEMPLATE, request); }) .doOnComplete(() -> { LOG.info("Finish updating backing services. serviceDefinitionName={}, planName={}", - request.getServiceDefinition().getName(), request.getPlan().getName()); + request.getServiceDefinition().getName(), request.getPlan().getName()); LOG.debug(REQUEST_LOG_TEMPLATE, request); }) - .doOnError(e -> { + .doOnError((e) -> { if (LOG.isErrorEnabled()) { - LOG.error(String.format("Error updating backing services. serviceDefinitionName=%s, planName=%s, " + - "error=%s", request.getServiceDefinition().getName(), request.getPlan().getName(), - e.getMessage()), e); + LOG.error(String.format( + "Error updating backing services. serviceDefinitionName=%s, planName=%s, " + "error=%s", + request.getServiceDefinition().getName(), request.getPlan().getName(), e.getMessage()), e); } LOG.debug(REQUEST_LOG_TEMPLATE, request); }); } private Mono> getExistingBackingServiceNameMap(UpdateServiceInstanceRequest request) { - return backingAppManagementService.getDeployedBackingApplications(request.getServiceInstanceId(), - request.getServiceDefinition().getName(), request.getPlan().getName()) + return this.backingAppManagementService + .getDeployedBackingApplications(request.getServiceInstanceId(), request.getServiceDefinition().getName(), + request.getPlan().getName()) .flatMapMany(Flux::fromIterable) - .flatMap(backingApplication -> Flux - .fromIterable(backingApplication.getServices()) - .map(servicesSpec -> { - Map properties = null; - if (backingApplication.getProperties() != null) { - String target = backingApplication.getProperties().get(DeploymentProperties.TARGET_PROPERTY_KEY); - if (target != null) { - properties = Collections.singletonMap(DeploymentProperties.TARGET_PROPERTY_KEY, target); - } + .flatMap((backingApplication) -> Flux.fromIterable(backingApplication.getServices()).map((servicesSpec) -> { + Map properties = null; + if (backingApplication.getProperties() != null) { + String target = backingApplication.getProperties().get(DeploymentProperties.TARGET_PROPERTY_KEY); + if (target != null) { + properties = Collections.singletonMap(DeploymentProperties.TARGET_PROPERTY_KEY, target); } - return BackingService.builder() - .serviceInstanceName(servicesSpec.getServiceInstanceName()) - .properties(properties) - .build(); - })) + } + return BackingService.builder() + .serviceInstanceName(servicesSpec.getServiceInstanceName()) + .properties(properties) + .build(); + })) .distinct() .collectMap(BackingService::getServiceInstanceName, Function.identity()); } private List servicesInNameList(Map services, Set nameList) { List servicesToKeep = new ArrayList<>(services.values()); - servicesToKeep.removeIf(service -> !nameList.contains(service.getServiceInstanceName())); + servicesToKeep.removeIf((service) -> !nameList.contains(service.getServiceInstanceName())); return servicesToKeep; } @@ -218,24 +216,24 @@ public class AppDeploymentUpdateServiceInstanceWorkflow extends AppDeploymentIns } private Flux updateBackingApplications(UpdateServiceInstanceRequest request, - List preTransformedBackingApplications) { + List preTransformedBackingApplications) { return Mono.just(preTransformedBackingApplications) - .flatMapMany(backingApps -> deploymentService.update(backingApps, request.getServiceInstanceId())) - .doOnRequest(l -> { + .flatMapMany((backingApps) -> this.deploymentService.update(backingApps, request.getServiceInstanceId())) + .doOnRequest((l) -> { LOG.info("Updating backing applications. serviceDefinitionName={}, planName={}", - request.getServiceDefinition().getName(), request.getPlan().getName()); + request.getServiceDefinition().getName(), request.getPlan().getName()); LOG.debug(REQUEST_LOG_TEMPLATE, request); }) .doOnComplete(() -> { LOG.info("Finish updating backing applications. serviceDefinitionName={}, planName={}", - request.getServiceDefinition().getName(), request.getPlan().getName()); + request.getServiceDefinition().getName(), request.getPlan().getName()); LOG.debug(REQUEST_LOG_TEMPLATE, request); }) - .doOnError(e -> { + .doOnError((e) -> { if (LOG.isErrorEnabled()) { - LOG.error(String.format("Error updating backing applications. serviceDefinitionName=%s, " + - "planName=%s, error=%s", request.getServiceDefinition().getName(), request.getPlan().getName(), - e.getMessage()), e); + LOG.error(String.format( + "Error updating backing applications. serviceDefinitionName=%s, " + "planName=%s, error=%s", + request.getServiceDefinition().getName(), request.getPlan().getName(), e.getMessage()), e); } LOG.debug(REQUEST_LOG_TEMPLATE, request); }); @@ -248,7 +246,7 @@ public class AppDeploymentUpdateServiceInstanceWorkflow extends AppDeploymentIns @Override public Mono buildResponse(UpdateServiceInstanceRequest request, - UpdateServiceInstanceResponseBuilder responseBuilder) { + UpdateServiceInstanceResponseBuilder responseBuilder) { return Mono.just(responseBuilder.async(true)); } diff --git a/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/workflow/instance/package-info.java b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/workflow/instance/package-info.java new file mode 100644 index 0000000..06446fa --- /dev/null +++ b/spring-cloud-app-broker-core/src/main/java/org/springframework/cloud/appbroker/workflow/instance/package-info.java @@ -0,0 +1,20 @@ +/* + * Copyright 2016-2024 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * App Broker Workflow Instance. + */ +package org.springframework.cloud.appbroker.workflow.instance; diff --git a/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/deployer/BackingApplicationTest.java b/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/deployer/BackingApplicationTests.java similarity index 91% rename from spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/deployer/BackingApplicationTest.java rename to spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/deployer/BackingApplicationTests.java index 572f441..906e12a 100644 --- a/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/deployer/BackingApplicationTest.java +++ b/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/deployer/BackingApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,12 +20,11 @@ import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; -class BackingApplicationTest { +class BackingApplicationTests { @Test void stringRepresentationShouldNotExposeSensitiveInformationFromTheEnvironment() { - BackingApplication backingApp = BackingApplication - .builder() + BackingApplication backingApp = BackingApplication.builder() .name("Test") .environment("privateKey", "secret-private-key") .environment("databasePassword", "password") diff --git a/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/deployer/DefaultBackingAppDeploymentServiceTest.java b/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/deployer/DefaultBackingAppDeploymentServiceTests.java similarity index 61% rename from spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/deployer/DefaultBackingAppDeploymentServiceTest.java rename to spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/deployer/DefaultBackingAppDeploymentServiceTests.java index 073f1ac..a3cb9c2 100644 --- a/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/deployer/DefaultBackingAppDeploymentServiceTest.java +++ b/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/deployer/DefaultBackingAppDeploymentServiceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,7 +30,7 @@ import reactor.test.StepVerifier; import static org.mockito.Mockito.doReturn; @ExtendWith(MockitoExtension.class) -class DefaultBackingAppDeploymentServiceTest { +class DefaultBackingAppDeploymentServiceTests { @Mock private DeployerClient deployerClient; @@ -41,32 +41,25 @@ class DefaultBackingAppDeploymentServiceTest { @BeforeEach void setUp() { - backingAppDeploymentService = new DefaultBackingAppDeploymentService(deployerClient); - backingApps = BackingApplications.builder() - .backingApplication(BackingApplication.builder() - .name("testApp1") - .path("https://myfiles/app1.jar") - .build()) - .backingApplication(BackingApplication.builder() - .name("testApp2") - .path("https://myfiles/app2.jar") - .build()) + this.backingAppDeploymentService = new DefaultBackingAppDeploymentService(this.deployerClient); + this.backingApps = BackingApplications.builder() + .backingApplication(BackingApplication.builder().name("testApp1").path("https://myfiles/app1.jar").build()) + .backingApplication(BackingApplication.builder().name("testApp2").path("https://myfiles/app2.jar").build()) .build(); } @Test void shouldDeployApplications() { - doReturn(Mono.just("app1")) - .when(deployerClient).deploy(backingApps.get(0), "instance-id"); - doReturn(Mono.just("app2")) - .when(deployerClient).deploy(backingApps.get(1), "instance-id"); + doReturn(Mono.just("app1")).when(this.deployerClient).deploy(this.backingApps.get(0), "instance-id"); + doReturn(Mono.just("app2")).when(this.deployerClient).deploy(this.backingApps.get(1), "instance-id"); List expectedValues = new ArrayList<>(); expectedValues.add("app1"); expectedValues.add("app2"); - StepVerifier.create(backingAppDeploymentService.deploy(backingApps, "instance-id")) - // deployments are run in parallel, so the order of completion is not predictable + StepVerifier.create(this.backingAppDeploymentService.deploy(this.backingApps, "instance-id")) + // deployments are run in parallel, so the order of completion is not + // predictable // ensure that both expected signals are sent in any order .expectNextMatches(expectedValues::remove) .expectNextMatches(expectedValues::remove) @@ -75,17 +68,16 @@ class DefaultBackingAppDeploymentServiceTest { @Test void shouldPrepareApplicationsForUpdate() { - doReturn(Mono.just("app1")) - .when(deployerClient).preUpdate(backingApps.get(0), "instance-id"); - doReturn(Mono.just("app2")) - .when(deployerClient).preUpdate(backingApps.get(1), "instance-id"); + doReturn(Mono.just("app1")).when(this.deployerClient).preUpdate(this.backingApps.get(0), "instance-id"); + doReturn(Mono.just("app2")).when(this.deployerClient).preUpdate(this.backingApps.get(1), "instance-id"); List expectedValues = new ArrayList<>(); expectedValues.add("app1"); expectedValues.add("app2"); - StepVerifier.create(backingAppDeploymentService.prepareForUpdate(backingApps, "instance-id")) - // update preparations are run in parallel, so the order of completion is not predictable + StepVerifier.create(this.backingAppDeploymentService.prepareForUpdate(this.backingApps, "instance-id")) + // update preparations are run in parallel, so the order of completion is not + // predictable // ensure that both expected signals are sent in any order .expectNextMatches(expectedValues::remove) .expectNextMatches(expectedValues::remove) @@ -94,16 +86,14 @@ class DefaultBackingAppDeploymentServiceTest { @Test void shouldUpdateApplications() { - doReturn(Mono.just("app1")) - .when(deployerClient).update(backingApps.get(0), "instance-id"); - doReturn(Mono.just("app2")) - .when(deployerClient).update(backingApps.get(1), "instance-id"); + doReturn(Mono.just("app1")).when(this.deployerClient).update(this.backingApps.get(0), "instance-id"); + doReturn(Mono.just("app2")).when(this.deployerClient).update(this.backingApps.get(1), "instance-id"); List expectedValues = new ArrayList<>(); expectedValues.add("app1"); expectedValues.add("app2"); - StepVerifier.create(backingAppDeploymentService.update(backingApps, "instance-id")) + StepVerifier.create(this.backingAppDeploymentService.update(this.backingApps, "instance-id")) // updates are run in parallel, so the order of completion is not predictable // ensure that both expected signals are sent in any order .expectNextMatches(expectedValues::remove) @@ -113,17 +103,16 @@ class DefaultBackingAppDeploymentServiceTest { @Test void shouldUndeployApplications() { - doReturn(Mono.just("deleted1")) - .when(deployerClient).undeploy(backingApps.get(0)); - doReturn(Mono.just("deleted2")) - .when(deployerClient).undeploy(backingApps.get(1)); + doReturn(Mono.just("deleted1")).when(this.deployerClient).undeploy(this.backingApps.get(0)); + doReturn(Mono.just("deleted2")).when(this.deployerClient).undeploy(this.backingApps.get(1)); List expectedValues = new ArrayList<>(); expectedValues.add("deleted1"); expectedValues.add("deleted2"); - StepVerifier.create(backingAppDeploymentService.undeploy(backingApps)) - // deployments are run in parallel, so the order of completion is not predictable + StepVerifier.create(this.backingAppDeploymentService.undeploy(this.backingApps)) + // deployments are run in parallel, so the order of completion is not + // predictable // ensure that both expected signals are sent in any order .expectNextMatches(expectedValues::remove) .expectNextMatches(expectedValues::remove) diff --git a/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/deployer/DefaultBackingServicesProvisionServiceTest.java b/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/deployer/DefaultBackingServicesProvisionServiceTests.java similarity index 65% rename from spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/deployer/DefaultBackingServicesProvisionServiceTest.java rename to spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/deployer/DefaultBackingServicesProvisionServiceTests.java index 4474693..fef7448 100644 --- a/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/deployer/DefaultBackingServicesProvisionServiceTest.java +++ b/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/deployer/DefaultBackingServicesProvisionServiceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,7 +32,7 @@ import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.verifyNoMoreInteractions; @ExtendWith(MockitoExtension.class) -class DefaultBackingServicesProvisionServiceTest { +class DefaultBackingServicesProvisionServiceTests { @Mock private DeployerClient deployerClient; @@ -43,36 +43,31 @@ class DefaultBackingServicesProvisionServiceTest { @BeforeEach void setUp() { - backingServicesProvisionService = new DefaultBackingServicesProvisionService(deployerClient); - backingServices = BackingServices.builder() + this.backingServicesProvisionService = new DefaultBackingServicesProvisionService(this.deployerClient); + this.backingServices = BackingServices.builder() .backingService(BackingService.builder() .serviceInstanceName("si1") .name("service1") .plan("standard") .parameters(Collections.singletonMap("key1", "value1")) .build()) - .backingService(BackingService.builder() - .serviceInstanceName("si2") - .name("service2") - .plan("free") - .build()) + .backingService(BackingService.builder().serviceInstanceName("si2").name("service2").plan("free").build()) .build(); } @Test @SuppressWarnings("UnassignedFluxMonoInstance") void createServiceInstance() { - doReturn(Mono.just("si1")) - .when(deployerClient).createServiceInstance(backingServices.get(0)); - doReturn(Mono.just("si2")) - .when(deployerClient).createServiceInstance(backingServices.get(1)); + doReturn(Mono.just("si1")).when(this.deployerClient).createServiceInstance(this.backingServices.get(0)); + doReturn(Mono.just("si2")).when(this.deployerClient).createServiceInstance(this.backingServices.get(1)); List expectedValues = new ArrayList<>(); expectedValues.add("si1"); expectedValues.add("si2"); - StepVerifier.create(backingServicesProvisionService.createServiceInstance(backingServices)) - // deployments are run in parallel, so the order of completion is not predictable + StepVerifier.create(this.backingServicesProvisionService.createServiceInstance(this.backingServices)) + // deployments are run in parallel, so the order of completion is not + // predictable // ensure that both expected signals are sent in any order .expectNextMatches(expectedValues::remove) .expectNextMatches(expectedValues::remove) @@ -82,37 +77,34 @@ class DefaultBackingServicesProvisionServiceTest { @Test @SuppressWarnings("UnassignedFluxMonoInstance") void updateServiceInstance() { - doReturn(Mono.just("updated1")) - .when(deployerClient).updateServiceInstance(backingServices.get(0)); - doReturn(Mono.just("updated2")) - .when(deployerClient).updateServiceInstance(backingServices.get(1)); + doReturn(Mono.just("updated1")).when(this.deployerClient).updateServiceInstance(this.backingServices.get(0)); + doReturn(Mono.just("updated2")).when(this.deployerClient).updateServiceInstance(this.backingServices.get(1)); List expectedValues = new ArrayList<>(); expectedValues.add("updated1"); expectedValues.add("updated2"); - StepVerifier.create(backingServicesProvisionService.updateServiceInstance(backingServices)) + StepVerifier.create(this.backingServicesProvisionService.updateServiceInstance(this.backingServices)) .expectNextMatches(expectedValues::remove) .expectNextMatches(expectedValues::remove) .verifyComplete(); - verifyNoMoreInteractions(deployerClient); + verifyNoMoreInteractions(this.deployerClient); } @Test @SuppressWarnings("UnassignedFluxMonoInstance") void deleteServiceInstance() { - doReturn(Mono.just("deleted1")) - .when(deployerClient).deleteServiceInstance(backingServices.get(0)); - doReturn(Mono.just("deleted2")) - .when(deployerClient).deleteServiceInstance(backingServices.get(1)); + doReturn(Mono.just("deleted1")).when(this.deployerClient).deleteServiceInstance(this.backingServices.get(0)); + doReturn(Mono.just("deleted2")).when(this.deployerClient).deleteServiceInstance(this.backingServices.get(1)); List expectedValues = new ArrayList<>(); expectedValues.add("deleted1"); expectedValues.add("deleted2"); - StepVerifier.create(backingServicesProvisionService.deleteServiceInstance(backingServices)) - // deployments are run in parallel, so the order of completion is not predictable + StepVerifier.create(this.backingServicesProvisionService.deleteServiceInstance(this.backingServices)) + // deployments are run in parallel, so the order of completion is not + // predictable // ensure that both expected signals are sent in any order .expectNextMatches(expectedValues::remove) .expectNextMatches(expectedValues::remove) diff --git a/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/deployer/DefaultBackingSpaceManagementServiceTest.java b/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/deployer/DefaultBackingSpaceManagementServiceTests.java similarity index 75% rename from spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/deployer/DefaultBackingSpaceManagementServiceTest.java rename to spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/deployer/DefaultBackingSpaceManagementServiceTests.java index 24721dd..abf5d9c 100644 --- a/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/deployer/DefaultBackingSpaceManagementServiceTest.java +++ b/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/deployer/DefaultBackingSpaceManagementServiceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2021 the original author or authors. + * Copyright 2016-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,6 +17,7 @@ package org.springframework.cloud.appbroker.deployer; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import org.junit.jupiter.api.BeforeEach; @@ -27,11 +28,10 @@ import org.mockito.junit.jupiter.MockitoExtension; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; -import static java.util.Arrays.asList; import static org.mockito.Mockito.doReturn; @ExtendWith(MockitoExtension.class) -class DefaultBackingSpaceManagementServiceTest { +class DefaultBackingSpaceManagementServiceTests { @Mock private DeployerClient deployerClient; @@ -40,7 +40,7 @@ class DefaultBackingSpaceManagementServiceTest { @BeforeEach void setUp() { - backingSpaceManagementService = new DefaultBackingSpaceManagementService(deployerClient); + this.backingSpaceManagementService = new DefaultBackingSpaceManagementService(this.deployerClient); } @Test @@ -48,17 +48,17 @@ class DefaultBackingSpaceManagementServiceTest { void deleteSpace() { final String spaceName1 = "space1"; final String spaceName2 = "space2"; - doReturn(Mono.just("returned-space-1")) - .when(deployerClient).deleteSpace(spaceName1); - doReturn(Mono.just("returned-space-2")) - .when(deployerClient).deleteSpace(spaceName2); + doReturn(Mono.just("returned-space-1")).when(this.deployerClient).deleteSpace(spaceName1); + doReturn(Mono.just("returned-space-2")).when(this.deployerClient).deleteSpace(spaceName2); List expectedValues = new ArrayList<>(); expectedValues.add("returned-space-1"); expectedValues.add("returned-space-2"); - StepVerifier.create(backingSpaceManagementService.deleteTargetSpaces(asList(spaceName1, spaceName2))) - // deployments are run in parallel, so the order of completion is not predictable + StepVerifier + .create(this.backingSpaceManagementService.deleteTargetSpaces(Arrays.asList(spaceName1, spaceName2))) + // deployments are run in parallel, so the order of completion is not + // predictable // ensure that both expected signals are sent in any order .expectNextMatches(expectedValues::remove) .expectNextMatches(expectedValues::remove) diff --git a/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/deployer/DeployerClientTest.java b/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/deployer/DeployerClientTests.java similarity index 51% rename from spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/deployer/DeployerClientTest.java rename to spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/deployer/DeployerClientTests.java index fb5bcf6..88876a5 100644 --- a/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/deployer/DeployerClientTest.java +++ b/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/deployer/DeployerClientTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2021 the original author or authors. + * Copyright 2016-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,7 +49,7 @@ import static org.mockito.BDDMockito.then; @ExtendWith(MockitoExtension.class) @SuppressWarnings("UnassignedFluxMonoInstance") -class DeployerClientTest { +class DeployerClientTests { private static final String APP_NAME = "helloworld"; @@ -65,34 +65,23 @@ class DeployerClientTest { private AppDeployer appDeployer; private static ArgumentMatcher matchesDeploymentRequest(String appName, String appArchive, - Map properties, - Map environment, - List services) { - return request -> - request.getName().equals(appName) && - request.getPath().equals(appArchive) && - request.getProperties().equals(properties) && - request.getEnvironment().equals(environment) && - request.getServices().equals(services); + Map properties, Map environment, List services) { + return (request) -> request.getName().equals(appName) && request.getPath().equals(appArchive) + && request.getProperties().equals(properties) && request.getEnvironment().equals(environment) + && request.getServices().equals(services); } private static ArgumentMatcher matchesUpdateRequest(String appName, String appArchive, - Map properties, - Map environment, - List services, - String serviceInstanceId) { - return request -> - request.getName().equals(appName) && - request.getPath().equals(appArchive) && - request.getProperties().equals(properties) && - request.getEnvironment().equals(environment) && - request.getServices().equals(services) && - request.getServiceInstanceId().equals(serviceInstanceId); + Map properties, Map environment, List services, + String serviceInstanceId) { + return (request) -> request.getName().equals(appName) && request.getPath().equals(appArchive) + && request.getProperties().equals(properties) && request.getEnvironment().equals(environment) + && request.getServices().equals(services) && request.getServiceInstanceId().equals(serviceInstanceId); } @BeforeEach void setUp() { - deployerClient = new DeployerClient(appDeployer); + this.deployerClient = new DeployerClient(this.appDeployer); } @Nested @@ -103,20 +92,17 @@ class DeployerClientTest { // given setupAppDeployer(); - BackingApplication application = BackingApplication.builder() - .name(APP_NAME) - .path(APP_PATH) - .build(); + BackingApplication application = BackingApplication.builder().name(APP_NAME).path(APP_PATH).build(); // when - StepVerifier.create(deployerClient.deploy(application, "instance-id")) + StepVerifier.create(DeployerClientTests.this.deployerClient.deploy(application, "instance-id")) // then .expectNext(APP_NAME) .verifyComplete(); - then(appDeployer).should() + then(DeployerClientTests.this.appDeployer).should() .deploy(argThat(matchesDeploymentRequest(APP_NAME, APP_PATH, Collections.emptyMap(), - Collections.emptyMap(), Collections.emptyList()))); + Collections.emptyMap(), Collections.emptyList()))); } @Test @@ -124,10 +110,12 @@ class DeployerClientTest { void shouldDeployAppWithProperties() { setupAppDeployer(); - Map properties = new HashMap() {{ - put("memory", "1G"); - put("instances", "2"); - }}; + Map properties = new HashMap() { + { + put("memory", "1G"); + put("instances", "2"); + } + }; BackingApplication application = BackingApplication.builder() .name(APP_NAME) .path(APP_PATH) @@ -135,13 +123,14 @@ class DeployerClientTest { .build(); // when - StepVerifier.create(deployerClient.deploy(application, "instance-id")) + StepVerifier.create(DeployerClientTests.this.deployerClient.deploy(application, "instance-id")) // then .expectNext(APP_NAME) .verifyComplete(); - then(appDeployer).should().deploy(argThat(matchesDeploymentRequest(APP_NAME, APP_PATH, properties, - Collections.emptyMap(), Collections.emptyList()))); + then(DeployerClientTests.this.appDeployer).should() + .deploy(argThat(matchesDeploymentRequest(APP_NAME, APP_PATH, properties, Collections.emptyMap(), + Collections.emptyList()))); } @Test @@ -149,25 +138,21 @@ class DeployerClientTest { void shouldDeployAppWithService() { setupAppDeployer(); - BackingApplication application = - BackingApplication - .builder() - .name(APP_NAME) - .path(APP_PATH) - .services(ServicesSpec.builder() - .serviceInstanceName("my-db-service") - .build()) - .build(); + BackingApplication application = BackingApplication.builder() + .name(APP_NAME) + .path(APP_PATH) + .services(ServicesSpec.builder().serviceInstanceName("my-db-service").build()) + .build(); // when - StepVerifier.create(deployerClient.deploy(application, "instance-id")) + StepVerifier.create(DeployerClientTests.this.deployerClient.deploy(application, "instance-id")) // then .expectNext(APP_NAME) .verifyComplete(); - then(appDeployer).should() + then(DeployerClientTests.this.appDeployer).should() .deploy(argThat(matchesDeploymentRequest(APP_NAME, APP_PATH, Collections.emptyMap(), - Collections.emptyMap(), Collections.singletonList("my-db-service")))); + Collections.emptyMap(), Collections.singletonList("my-db-service")))); } @Test @@ -175,10 +160,12 @@ class DeployerClientTest { void shouldDeployAppWithEnvironmentVariables() { setupAppDeployer(); - Map environment = new HashMap() {{ - put("ENV_VAR_1", "value1"); - put("ENV_VAR_2", "value2"); - }}; + Map environment = new HashMap() { + { + put("ENV_VAR_1", "value1"); + put("ENV_VAR_2", "value2"); + } + }; BackingApplication application = BackingApplication.builder() .name(APP_NAME) .path(APP_PATH) @@ -186,22 +173,21 @@ class DeployerClientTest { .build(); // when - StepVerifier.create(deployerClient.deploy(application, "instance-id")) + StepVerifier.create(DeployerClientTests.this.deployerClient.deploy(application, "instance-id")) // then .expectNext(APP_NAME) .verifyComplete(); - then(appDeployer).should() - .deploy(argThat(matchesDeploymentRequest(APP_NAME, APP_PATH, Collections.emptyMap(), - environment, Collections.emptyList()))); + then(DeployerClientTests.this.appDeployer).should() + .deploy(argThat(matchesDeploymentRequest(APP_NAME, APP_PATH, Collections.emptyMap(), environment, + Collections.emptyList()))); } private void setupAppDeployer() { - given(appDeployer.deploy(any())) - .willReturn(Mono.just(DeployApplicationResponse.builder() - .name(APP_NAME) - .build())); + given(DeployerClientTests.this.appDeployer.deploy(any())) + .willReturn(Mono.just(DeployApplicationResponse.builder().name(APP_NAME).build())); } + } @Nested @@ -213,28 +199,24 @@ class DeployerClientTest { setupAppDeployer(); final String serviceInstanceId = "instance-id"; - BackingApplication application = BackingApplication.builder() - .name(APP_NAME) - .path(APP_PATH) - .build(); + BackingApplication application = BackingApplication.builder().name(APP_NAME).path(APP_PATH).build(); // when - StepVerifier.create(deployerClient.preUpdate(application, serviceInstanceId)) + StepVerifier.create(DeployerClientTests.this.deployerClient.preUpdate(application, serviceInstanceId)) // then .expectNext(APP_NAME) .verifyComplete(); - then(appDeployer).should().preUpdate(argThat(matchesUpdateRequest(APP_NAME, - APP_PATH, Collections.emptyMap(), Collections.emptyMap(), Collections.emptyList(), serviceInstanceId))); + then(DeployerClientTests.this.appDeployer).should() + .preUpdate(argThat(matchesUpdateRequest(APP_NAME, APP_PATH, Collections.emptyMap(), + Collections.emptyMap(), Collections.emptyList(), serviceInstanceId))); } - private void setupAppDeployer() { - given(appDeployer.preUpdate(any())) - .willReturn(Mono.just(UpdateApplicationResponse.builder() - .name(APP_NAME) - .build())); + given(DeployerClientTests.this.appDeployer.preUpdate(any())) + .willReturn(Mono.just(UpdateApplicationResponse.builder().name(APP_NAME).build())); } + } @Nested @@ -246,28 +228,24 @@ class DeployerClientTest { setupAppDeployer(); final String serviceInstanceId = "instance-id"; - BackingApplication application = BackingApplication.builder() - .name(APP_NAME) - .path(APP_PATH) - .build(); + BackingApplication application = BackingApplication.builder().name(APP_NAME).path(APP_PATH).build(); // when - StepVerifier.create(deployerClient.update(application, serviceInstanceId)) + StepVerifier.create(DeployerClientTests.this.deployerClient.update(application, serviceInstanceId)) // then .expectNext(APP_NAME) .verifyComplete(); - then(appDeployer).should().update(argThat(matchesUpdateRequest(APP_NAME, - APP_PATH, Collections.emptyMap(), Collections.emptyMap(), Collections.emptyList(), serviceInstanceId))); + then(DeployerClientTests.this.appDeployer).should() + .update(argThat(matchesUpdateRequest(APP_NAME, APP_PATH, Collections.emptyMap(), Collections.emptyMap(), + Collections.emptyList(), serviceInstanceId))); } - private void setupAppDeployer() { - given(appDeployer.update(any())) - .willReturn(Mono.just(UpdateApplicationResponse.builder() - .name(APP_NAME) - .build())); + given(DeployerClientTests.this.appDeployer.update(any())) + .willReturn(Mono.just(UpdateApplicationResponse.builder().name(APP_NAME).build())); } + } @Nested @@ -275,42 +253,36 @@ class DeployerClientTest { @Test void shouldUndeployApp() { - given(appDeployer.undeploy(any())) - .willReturn(Mono.just(UndeployApplicationResponse.builder() - .name(APP_NAME) - .build())); + given(DeployerClientTests.this.appDeployer.undeploy(any())) + .willReturn(Mono.just(UndeployApplicationResponse.builder().name(APP_NAME).build())); - BackingApplication application = BackingApplication.builder() - .name(APP_NAME) - .path(APP_PATH) - .build(); + BackingApplication application = BackingApplication.builder().name(APP_NAME).path(APP_PATH).build(); // when - StepVerifier.create(deployerClient.undeploy(application)) + StepVerifier.create(DeployerClientTests.this.deployerClient.undeploy(application)) // then .expectNext(APP_NAME) .verifyComplete(); - then(appDeployer).should().undeploy(argThat(request -> APP_NAME.equals(request.getName()))); + then(DeployerClientTests.this.appDeployer).should() + .undeploy(argThat((request) -> APP_NAME.equals(request.getName()))); } @Test void shouldNotReturnErrorWhenUndeployingAppThatDoesNotExist() { - given(appDeployer.undeploy(any())) + given(DeployerClientTests.this.appDeployer.undeploy(any())) .willReturn(Mono.error(new IllegalStateException("app does not exist"))); - BackingApplication application = BackingApplication.builder() - .name(APP_NAME) - .path(APP_PATH) - .build(); + BackingApplication application = BackingApplication.builder().name(APP_NAME).path(APP_PATH).build(); // when - StepVerifier.create(deployerClient.undeploy(application)) + StepVerifier.create(DeployerClientTests.this.deployerClient.undeploy(application)) // then .expectNext(APP_NAME) .verifyComplete(); - then(appDeployer).should().undeploy(argThat(request -> APP_NAME.equals(request.getName()))); + then(DeployerClientTests.this.appDeployer).should() + .undeploy(argThat((request) -> APP_NAME.equals(request.getName()))); } } @@ -320,23 +292,20 @@ class DeployerClientTest { @Test void shouldCreateServiceInstance() { - given(appDeployer.createServiceInstance(any())) - .willReturn(Mono.just(CreateServiceInstanceResponse.builder() - .name(SERVICE_INSTANCE_NAME) - .build())); + given(DeployerClientTests.this.appDeployer.createServiceInstance(any())) + .willReturn(Mono.just(CreateServiceInstanceResponse.builder().name(SERVICE_INSTANCE_NAME).build())); - BackingService service = BackingService.builder() - .serviceInstanceName(SERVICE_INSTANCE_NAME) - .build(); + BackingService service = BackingService.builder().serviceInstanceName(SERVICE_INSTANCE_NAME).build(); // when - StepVerifier.create(deployerClient.createServiceInstance(service)) + StepVerifier.create(DeployerClientTests.this.deployerClient.createServiceInstance(service)) // then .expectNext(SERVICE_INSTANCE_NAME) .verifyComplete(); - then(appDeployer).should().createServiceInstance(argThat(request -> - SERVICE_INSTANCE_NAME.equals(request.getServiceInstanceName()))); + then(DeployerClientTests.this.appDeployer).should() + .createServiceInstance( + argThat((request) -> SERVICE_INSTANCE_NAME.equals(request.getServiceInstanceName()))); } } @@ -346,42 +315,38 @@ class DeployerClientTest { @Test void shouldUpdateServiceInstance() { - given(appDeployer.updateServiceInstance(any())) - .willReturn(Mono.just(UpdateServiceInstanceResponse.builder() - .name(SERVICE_INSTANCE_NAME) - .build())); + given(DeployerClientTests.this.appDeployer.updateServiceInstance(any())) + .willReturn(Mono.just(UpdateServiceInstanceResponse.builder().name(SERVICE_INSTANCE_NAME).build())); - BackingService service = BackingService.builder() - .serviceInstanceName(SERVICE_INSTANCE_NAME) - .build(); + BackingService service = BackingService.builder().serviceInstanceName(SERVICE_INSTANCE_NAME).build(); // when - StepVerifier.create(deployerClient.updateServiceInstance(service)) + StepVerifier.create(DeployerClientTests.this.deployerClient.updateServiceInstance(service)) // then .expectNext(SERVICE_INSTANCE_NAME) .verifyComplete(); - then(appDeployer).should().updateServiceInstance(argThat(request -> - SERVICE_INSTANCE_NAME.equals(request.getServiceInstanceName()))); + then(DeployerClientTests.this.appDeployer).should() + .updateServiceInstance( + argThat((request) -> SERVICE_INSTANCE_NAME.equals(request.getServiceInstanceName()))); } @Test void shouldReturnErrorWhenUpdatingServiceInstanceThatDoesNotExist() { - given(appDeployer.updateServiceInstance(any())) + given(DeployerClientTests.this.appDeployer.updateServiceInstance(any())) .willReturn(Mono.error(new IllegalStateException("service instance does not exist"))); - BackingService service = BackingService.builder() - .serviceInstanceName(SERVICE_INSTANCE_NAME) - .build(); + BackingService service = BackingService.builder().serviceInstanceName(SERVICE_INSTANCE_NAME).build(); // when - StepVerifier.create(deployerClient.updateServiceInstance(service)) + StepVerifier.create(DeployerClientTests.this.deployerClient.updateServiceInstance(service)) // then .expectErrorMessage("service instance does not exist") .verify(); - then(appDeployer).should().updateServiceInstance(argThat(request -> - SERVICE_INSTANCE_NAME.equals(request.getServiceInstanceName()))); + then(DeployerClientTests.this.appDeployer).should() + .updateServiceInstance( + argThat((request) -> SERVICE_INSTANCE_NAME.equals(request.getServiceInstanceName()))); } } @@ -391,42 +356,38 @@ class DeployerClientTest { @Test void shouldDeleteServiceInstance() { - given(appDeployer.deleteServiceInstance(any())) - .willReturn(Mono.just(DeleteServiceInstanceResponse.builder() - .name(SERVICE_INSTANCE_NAME) - .build())); + given(DeployerClientTests.this.appDeployer.deleteServiceInstance(any())) + .willReturn(Mono.just(DeleteServiceInstanceResponse.builder().name(SERVICE_INSTANCE_NAME).build())); - BackingService service = BackingService.builder() - .serviceInstanceName(SERVICE_INSTANCE_NAME) - .build(); + BackingService service = BackingService.builder().serviceInstanceName(SERVICE_INSTANCE_NAME).build(); // when - StepVerifier.create(deployerClient.deleteServiceInstance(service)) + StepVerifier.create(DeployerClientTests.this.deployerClient.deleteServiceInstance(service)) // then .expectNext(SERVICE_INSTANCE_NAME) .verifyComplete(); - then(appDeployer).should().deleteServiceInstance(argThat(request -> - SERVICE_INSTANCE_NAME.equals(request.getServiceInstanceName()))); + then(DeployerClientTests.this.appDeployer).should() + .deleteServiceInstance( + argThat((request) -> SERVICE_INSTANCE_NAME.equals(request.getServiceInstanceName()))); } @Test void shouldNotReturnErrorWhenDeletingServiceInstanceThatDoesNotExist() { - given(appDeployer.deleteServiceInstance(any())) + given(DeployerClientTests.this.appDeployer.deleteServiceInstance(any())) .willReturn(Mono.error(new IllegalStateException("service instance does not exist"))); - BackingService service = BackingService.builder() - .serviceInstanceName(SERVICE_INSTANCE_NAME) - .build(); + BackingService service = BackingService.builder().serviceInstanceName(SERVICE_INSTANCE_NAME).build(); // when - StepVerifier.create(deployerClient.deleteServiceInstance(service)) + StepVerifier.create(DeployerClientTests.this.deployerClient.deleteServiceInstance(service)) // then .expectNext(SERVICE_INSTANCE_NAME) .verifyComplete(); - then(appDeployer).should().deleteServiceInstance(argThat(request -> - SERVICE_INSTANCE_NAME.equals(request.getServiceInstanceName()))); + then(DeployerClientTests.this.appDeployer).should() + .deleteServiceInstance( + argThat((request) -> SERVICE_INSTANCE_NAME.equals(request.getServiceInstanceName()))); } } @@ -442,21 +403,20 @@ class DeployerClientTest { setupAppDeployer(); // when - StepVerifier.create(deployerClient.deleteSpace("test-space")) + StepVerifier.create(DeployerClientTests.this.deployerClient.deleteSpace("test-space")) // then .expectNext(RETURNED_SPACE_NAME) .verifyComplete(); - then(appDeployer).should().deleteBackingSpace(argThat(space -> "test-space".equals(space.getName()))); + then(DeployerClientTests.this.appDeployer).should() + .deleteBackingSpace(argThat((space) -> "test-space".equals(space.getName()))); } - private void setupAppDeployer() { - given(appDeployer.deleteBackingSpace(any())) - .willReturn(Mono.just(DeleteBackingSpaceResponse.builder() - .name(RETURNED_SPACE_NAME) - .build())); + given(DeployerClientTests.this.appDeployer.deleteBackingSpace(any())) + .willReturn(Mono.just(DeleteBackingSpaceResponse.builder().name(RETURNED_SPACE_NAME).build())); } + } } diff --git a/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/extensions/ConfigurationBeanUtilsTest.java b/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/extensions/ConfigurationBeanUtilsTests.java similarity index 71% rename from spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/extensions/ConfigurationBeanUtilsTest.java rename to spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/extensions/ConfigurationBeanUtilsTests.java index c7c2f16..ad6effe 100644 --- a/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/extensions/ConfigurationBeanUtilsTest.java +++ b/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/extensions/ConfigurationBeanUtilsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,8 +25,7 @@ import org.springframework.cloud.appbroker.extensions.support.ConfigurationBeanU import static org.assertj.core.api.Assertions.assertThat; -class ConfigurationBeanUtilsTest { - +class ConfigurationBeanUtilsTests { private final TestProperties targetObject = new TestProperties(); @@ -34,38 +33,38 @@ class ConfigurationBeanUtilsTest { @Test void populateWithCamelCaseProperties() { - properties.put("stringValue", "value"); - properties.put("intValue", 41); - properties.put("booleanValue", true); + this.properties.put("stringValue", "value"); + this.properties.put("intValue", 41); + this.properties.put("booleanValue", true); - ConfigurationBeanUtils.populate(targetObject, properties); + ConfigurationBeanUtils.populate(this.targetObject, this.properties); - assertValuesPopulated(targetObject); + assertValuesPopulated(this.targetObject); } @Test void populateWithKebabCaseProperties() { - properties.put("string-value", "value"); - properties.put("int-value", 41); - properties.put("boolean-value", true); + this.properties.put("string-value", "value"); + this.properties.put("int-value", 41); + this.properties.put("boolean-value", true); - ConfigurationBeanUtils.populate(targetObject, properties); + ConfigurationBeanUtils.populate(this.targetObject, this.properties); - assertValuesPopulated(targetObject); + assertValuesPopulated(this.targetObject); } @Test void populateWithEmptyProperties() { - ConfigurationBeanUtils.populate(targetObject, properties); + ConfigurationBeanUtils.populate(this.targetObject, this.properties); - assertValuesNotPopulated(targetObject); + assertValuesNotPopulated(this.targetObject); } @Test void populateWithNullProperties() { - ConfigurationBeanUtils.populate(targetObject, null); + ConfigurationBeanUtils.populate(this.targetObject, null); - assertValuesNotPopulated(targetObject); + assertValuesNotPopulated(this.targetObject); } private void assertValuesPopulated(TestProperties targetObject) { @@ -90,7 +89,7 @@ class ConfigurationBeanUtilsTest { private boolean booleanValue; public String getStringValue() { - return stringValue; + return this.stringValue; } public void setStringValue(String stringValue) { @@ -98,7 +97,7 @@ class ConfigurationBeanUtilsTest { } public int getIntValue() { - return intValue; + return this.intValue; } public void setIntValue(int intValue) { @@ -106,7 +105,7 @@ class ConfigurationBeanUtilsTest { } public boolean isBooleanValue() { - return booleanValue; + return this.booleanValue; } public void setBooleanValue(boolean booleanValue) { diff --git a/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/extensions/parameters/BackingServicesParametersTransformationServiceTest.java b/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/extensions/parameters/BackingServicesParametersTransformationServiceTests.java similarity index 59% rename from spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/extensions/parameters/BackingServicesParametersTransformationServiceTest.java rename to spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/extensions/parameters/BackingServicesParametersTransformationServiceTests.java index cca4a15..5dea2e6 100644 --- a/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/extensions/parameters/BackingServicesParametersTransformationServiceTest.java +++ b/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/extensions/parameters/BackingServicesParametersTransformationServiceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,58 +29,48 @@ import org.springframework.cloud.servicebroker.exception.ServiceBrokerException; import static org.assertj.core.api.Assertions.assertThat; -class BackingServicesParametersTransformationServiceTest { +class BackingServicesParametersTransformationServiceTests { @Test void transformParametersWithNoBackingServices() { - BackingServicesParametersTransformationService service = - new BackingServicesParametersTransformationService(Collections.emptyList()); + BackingServicesParametersTransformationService service = new BackingServicesParametersTransformationService( + Collections.emptyList()); - BackingServices backingServices = BackingServices.builder() - .build(); + BackingServices backingServices = BackingServices.builder().build(); - StepVerifier - .create(service.transformParameters(backingServices, new HashMap<>())) + StepVerifier.create(service.transformParameters(backingServices, new HashMap<>())) .expectNext(backingServices) .verifyComplete(); } @Test void transformParametersWithNoTransformers() { - BackingServicesParametersTransformationService service = - new BackingServicesParametersTransformationService(Collections.emptyList()); + BackingServicesParametersTransformationService service = new BackingServicesParametersTransformationService( + Collections.emptyList()); - BackingServices backingServices = BackingServices - .builder() + BackingServices backingServices = BackingServices.builder() .backingService(BackingService.builder().build()) .build(); - StepVerifier - .create(service.transformParameters(backingServices, new HashMap<>())) + StepVerifier.create(service.transformParameters(backingServices, new HashMap<>())) .expectNext(backingServices) .verifyComplete(); } @Test void transformParametersWithUnknownTransformer() { - BackingServicesParametersTransformationService service = - new BackingServicesParametersTransformationService(Collections.emptyList()); + BackingServicesParametersTransformationService service = new BackingServicesParametersTransformationService( + Collections.emptyList()); - BackingServices backingServices = BackingServices - .builder() + BackingServices backingServices = BackingServices.builder() .backingService(BackingService.builder() .name("misconfigured-service") - .parameterTransformers(ParametersTransformerSpec - .builder() - .name("unknown-transformer") - .build()) + .parameterTransformers(ParametersTransformerSpec.builder().name("unknown-transformer").build()) .build()) .build(); - StepVerifier - .create(service.transformParameters(backingServices, new HashMap<>())) - .expectErrorSatisfies(e -> assertThat(e) - .isInstanceOf(ServiceBrokerException.class) + StepVerifier.create(service.transformParameters(backingServices, new HashMap<>())) + .expectErrorSatisfies((e) -> assertThat(e).isInstanceOf(ServiceBrokerException.class) .hasMessageContaining("unknown-transformer")) .verify(); } diff --git a/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/extensions/parameters/EnvironmentMappingParametersTransformerFactoryTest.java b/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/extensions/parameters/EnvironmentMappingParametersTransformerFactoryTests.java similarity index 85% rename from spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/extensions/parameters/EnvironmentMappingParametersTransformerFactoryTest.java rename to spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/extensions/parameters/EnvironmentMappingParametersTransformerFactoryTests.java index 5ec8ac8..c6e5d92 100644 --- a/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/extensions/parameters/EnvironmentMappingParametersTransformerFactoryTest.java +++ b/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/extensions/parameters/EnvironmentMappingParametersTransformerFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,21 +28,19 @@ import org.springframework.cloud.appbroker.deployer.BackingApplication; import static org.assertj.core.api.Assertions.assertThat; -class EnvironmentMappingParametersTransformerFactoryTest { +class EnvironmentMappingParametersTransformerFactoryTests { private ParametersTransformer transformer; @BeforeEach void setUp() { - transformer = new EnvironmentMappingParametersTransformerFactory() - .createWithConfig(config -> - config.setInclude("parameter1,parameter2,parameter4,parameter5")); + this.transformer = new EnvironmentMappingParametersTransformerFactory() + .createWithConfig((config) -> config.setInclude("parameter1,parameter2,parameter4,parameter5")); } @Test void parametersAreMappedToApplicationEnvironment() { - BackingApplication backingApplication = BackingApplication.builder() - .build(); + BackingApplication backingApplication = BackingApplication.builder().build(); Map parameters = new HashMap<>(); parameters.put("parameter1", "value1"); @@ -51,8 +49,7 @@ class EnvironmentMappingParametersTransformerFactoryTest { parameters.put("parameter4", Collections.singletonList("value4")); parameters.put("parameter5", Collections.singletonList(Collections.singletonMap("key5", "value5"))); - StepVerifier - .create(transformer.transform(backingApplication, parameters)) + StepVerifier.create(this.transformer.transform(backingApplication, parameters)) .expectNext(backingApplication) .verifyComplete(); @@ -75,8 +72,7 @@ class EnvironmentMappingParametersTransformerFactoryTest { parameters.put("parameter2", "value2"); parameters.put("parameter3", "value3"); - StepVerifier - .create(transformer.transform(backingApplication, parameters)) + StepVerifier.create(this.transformer.transform(backingApplication, parameters)) .expectNext(backingApplication) .verifyComplete(); diff --git a/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/extensions/parameters/ParameterMappingParametersTransformerFactoryTest.java b/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/extensions/parameters/ParameterMappingParametersTransformerFactoryTests.java similarity index 79% rename from spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/extensions/parameters/ParameterMappingParametersTransformerFactoryTest.java rename to spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/extensions/parameters/ParameterMappingParametersTransformerFactoryTests.java index a351396..c40742e 100644 --- a/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/extensions/parameters/ParameterMappingParametersTransformerFactoryTest.java +++ b/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/extensions/parameters/ParameterMappingParametersTransformerFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,15 +27,14 @@ import org.springframework.cloud.appbroker.deployer.BackingService; import static org.assertj.core.api.Assertions.assertThat; -class ParameterMappingParametersTransformerFactoryTest { +class ParameterMappingParametersTransformerFactoryTests { private ParametersTransformer transformer; @BeforeEach void setUp() { - transformer = new ParameterMappingParametersTransformerFactory() - .createWithConfig(config -> - config.setInclude("parameter1,parameter2")); + this.transformer = new ParameterMappingParametersTransformerFactory() + .createWithConfig((config) -> config.setInclude("parameter1,parameter2")); } @Test @@ -45,18 +44,13 @@ class ParameterMappingParametersTransformerFactoryTest { inputParameters.put("parameter2", "value2"); inputParameters.put("parameter3", "value3"); - Map expectedParameters = new HashMap<>(); expectedParameters.put("parameter1", "value1"); expectedParameters.put("parameter2", "value2"); - BackingService backingService = - BackingService.builder() - .parameters(expectedParameters) - .build(); + BackingService backingService = BackingService.builder().parameters(expectedParameters).build(); - StepVerifier - .create(transformer.transform(backingService, inputParameters)) + StepVerifier.create(this.transformer.transform(backingService, inputParameters)) .expectNext(backingService) .verifyComplete(); diff --git a/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/extensions/parameters/PropertyMappingParametersTransformerFactoryTest.java b/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/extensions/parameters/PropertyMappingParametersTransformerFactoryTests.java similarity index 85% rename from spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/extensions/parameters/PropertyMappingParametersTransformerFactoryTest.java rename to spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/extensions/parameters/PropertyMappingParametersTransformerFactoryTests.java index 55cfd93..d268007 100644 --- a/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/extensions/parameters/PropertyMappingParametersTransformerFactoryTest.java +++ b/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/extensions/parameters/PropertyMappingParametersTransformerFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,29 +27,26 @@ import org.springframework.cloud.appbroker.deployer.BackingApplication; import static org.assertj.core.api.Assertions.assertThat; -class PropertyMappingParametersTransformerFactoryTest { +class PropertyMappingParametersTransformerFactoryTests { private ParametersTransformer transformer; @BeforeEach void setUp() { - transformer = new PropertyMappingParametersTransformerFactory() - .createWithConfig(config -> - config.setInclude("count,memory")); + this.transformer = new PropertyMappingParametersTransformerFactory() + .createWithConfig((config) -> config.setInclude("count,memory")); } @Test void parametersAreMappedToApplicationProperties() { - BackingApplication backingApplication = BackingApplication.builder() - .build(); + BackingApplication backingApplication = BackingApplication.builder().build(); Map parameters = new HashMap<>(); parameters.put("count", 2); parameters.put("memory", "2G"); parameters.put("health-check-type", "none"); - StepVerifier - .create(transformer.transform(backingApplication, parameters)) + StepVerifier.create(this.transformer.transform(backingApplication, parameters)) .expectNext(backingApplication) .verifyComplete(); @@ -72,8 +69,7 @@ class PropertyMappingParametersTransformerFactoryTest { parameters.put("memory", "2G"); parameters.put("health-check-type", "none"); - StepVerifier - .create(transformer.transform(backingApplication, parameters)) + StepVerifier.create(this.transformer.transform(backingApplication, parameters)) .expectNext(backingApplication) .verifyComplete(); diff --git a/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/extensions/parameters/BackingApplicationsParametersTransformationServiceTest.java b/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/extensions/parameters/s.java similarity index 69% rename from spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/extensions/parameters/BackingApplicationsParametersTransformationServiceTest.java rename to spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/extensions/parameters/s.java index 28e9eb4..dd26c9c 100644 --- a/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/extensions/parameters/BackingApplicationsParametersTransformationServiceTest.java +++ b/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/extensions/parameters/s.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,58 +33,48 @@ import org.springframework.cloud.servicebroker.exception.ServiceBrokerException; import static org.assertj.core.api.Assertions.assertThat; -class BackingApplicationsParametersTransformationServiceTest { +class s { @Test void transformParametersWithNoBackingApps() { - BackingApplicationsParametersTransformationService service = - new BackingApplicationsParametersTransformationService(Collections.emptyList()); + BackingApplicationsParametersTransformationService service = new BackingApplicationsParametersTransformationService( + Collections.emptyList()); - BackingApplications backingApplications = BackingApplications.builder() - .build(); + BackingApplications backingApplications = BackingApplications.builder().build(); - StepVerifier - .create(service.transformParameters(backingApplications, new HashMap<>())) + StepVerifier.create(service.transformParameters(backingApplications, new HashMap<>())) .expectNext(backingApplications) .verifyComplete(); } @Test void transformParametersWithNoTransformers() { - BackingApplicationsParametersTransformationService service = - new BackingApplicationsParametersTransformationService(Collections.emptyList()); + BackingApplicationsParametersTransformationService service = new BackingApplicationsParametersTransformationService( + Collections.emptyList()); - BackingApplications backingApplications = BackingApplications - .builder() + BackingApplications backingApplications = BackingApplications.builder() .backingApplication(BackingApplication.builder().build()) .build(); - StepVerifier - .create(service.transformParameters(backingApplications, new HashMap<>())) + StepVerifier.create(service.transformParameters(backingApplications, new HashMap<>())) .expectNext(backingApplications) .verifyComplete(); } @Test void transformParametersWithUnknownTransformer() { - BackingApplicationsParametersTransformationService service = - new BackingApplicationsParametersTransformationService(Collections.emptyList()); + BackingApplicationsParametersTransformationService service = new BackingApplicationsParametersTransformationService( + Collections.emptyList()); - BackingApplications backingApplications = BackingApplications - .builder() - .backingApplication(BackingApplication - .builder() + BackingApplications backingApplications = BackingApplications.builder() + .backingApplication(BackingApplication.builder() .name("misconfigured-app") - .parameterTransformers(ParametersTransformerSpec.builder() - .name("unknown-transformer") - .build()) + .parameterTransformers(ParametersTransformerSpec.builder().name("unknown-transformer").build()) .build()) .build(); - StepVerifier - .create(service.transformParameters(backingApplications, new HashMap<>())) - .expectErrorSatisfies(e -> assertThat(e) - .isInstanceOf(ServiceBrokerException.class) + StepVerifier.create(service.transformParameters(backingApplications, new HashMap<>())) + .expectErrorSatisfies((e) -> assertThat(e).isInstanceOf(ServiceBrokerException.class) .hasMessageContaining("unknown-transformer")) .verify(); } @@ -97,24 +87,15 @@ class BackingApplicationsParametersTransformationServiceTest { BackingApplication app1 = BackingApplication.builder() .name("app1") - .parameterTransformers(ParametersTransformerSpec - .builder() - .name("transformer1") - .build()) + .parameterTransformers(ParametersTransformerSpec.builder().name("transformer1").build()) .build(); - BackingApplication app2 = BackingApplication - .builder() + BackingApplication app2 = BackingApplication.builder() .name("app2") - .parameterTransformers(ParametersTransformerSpec - .builder() - .name("transformer1") - .arg("arg1", "value1") - .arg("arg2", 5) - .build(), - ParametersTransformerSpec - .builder() - .name("transformer2") - .build()) + .parameterTransformers(ParametersTransformerSpec.builder() + .name("transformer1") + .arg("arg1", "value1") + .arg("arg2", 5) + .build(), ParametersTransformerSpec.builder().name("transformer2").build()) .build(); BackingApplications backingApplications = BackingApplications.builder() .backingApplication(app1) @@ -124,13 +105,11 @@ class BackingApplicationsParametersTransformationServiceTest { TestFactory factory1 = new TestFactory("transformer1"); TestFactory factory2 = new TestFactory("transformer2"); - BackingApplicationsParametersTransformationService service = - new BackingApplicationsParametersTransformationService( + BackingApplicationsParametersTransformationService service = new BackingApplicationsParametersTransformationService( Arrays.asList(factory1, factory2)); - StepVerifier - .create(service.transformParameters(backingApplications, parameters)) - .expectNextMatches(transformedBackingApplications -> { + StepVerifier.create(service.transformParameters(backingApplications, parameters)) + .expectNextMatches((transformedBackingApplications) -> { Map app1ExpectedTransformedEnvironment = new HashMap<>(app1.getEnvironment()); app1ExpectedTransformedEnvironment.put("0", "transformer1"); @@ -163,7 +142,7 @@ class BackingApplicationsParametersTransformationServiceTest { private Config actualConfig; - public TestFactory(String name) { + TestFactory(String name) { super(Config.class); this.name = name; } @@ -180,18 +159,18 @@ class BackingApplicationsParametersTransformationServiceTest { } private Mono doTransform(BackingApplication backingApplication, - Map parameters) { + Map parameters) { this.actualParameters = parameters; backingApplication.addEnvironment(Integer.toString(backingApplication.getEnvironment().size()), getName()); return Mono.just(backingApplication); } public Map getActualParameters() { - return actualParameters; + return this.actualParameters; } public Config getActualConfig() { - return actualConfig; + return this.actualConfig; } } @@ -206,13 +185,13 @@ class BackingApplicationsParametersTransformationServiceTest { private Config() { } - public Config(String arg1, Integer arg2) { + Config(String arg1, Integer arg2) { this.arg1 = arg1; this.arg2 = arg2; } public String getArg1() { - return arg1; + return this.arg1; } public void setArg1(String arg1) { @@ -220,7 +199,7 @@ class BackingApplicationsParametersTransformationServiceTest { } public int getArg2() { - return arg2; + return this.arg2; } public void setArg2(int arg2) { @@ -236,21 +215,17 @@ class BackingApplicationsParametersTransformationServiceTest { return false; } Config config = (Config) o; - return Objects.equals(arg2, config.arg2) && - Objects.equals(arg1, config.arg1); + return Objects.equals(this.arg2, config.arg2) && Objects.equals(this.arg1, config.arg1); } @Override public int hashCode() { - return Objects.hash(arg1, arg2); + return Objects.hash(this.arg1, this.arg2); } @Override public String toString() { - return "Config{" + - "arg1='" + arg1 + '\'' + - ", arg2=" + arg2 + - '}'; + return "Config{" + "arg1='" + this.arg1 + '\'' + ", arg2=" + this.arg2 + '}'; } } diff --git a/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/extensions/targets/TargetServiceTest.java b/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/extensions/targets/TargetServiceTests.java similarity index 69% rename from spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/extensions/targets/TargetServiceTest.java rename to spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/extensions/targets/TargetServiceTests.java index 25bf89f..990e7bd 100644 --- a/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/extensions/targets/TargetServiceTest.java +++ b/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/extensions/targets/TargetServiceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,6 +17,7 @@ package org.springframework.cloud.appbroker.extensions.targets; import java.util.Arrays; +import java.util.Collections; import java.util.List; import java.util.UUID; @@ -28,17 +29,16 @@ import reactor.test.StepVerifier; import org.springframework.cloud.appbroker.deployer.BackingApplication; import org.springframework.cloud.appbroker.deployer.TargetSpec; -import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; -class TargetServiceTest { +class TargetServiceTests { private TargetService targetService; @BeforeEach void setUp() { - targetService = new TargetService( - Arrays.asList(new SpacePerServiceInstance(), new ServiceInstanceGuidSuffix())); + this.targetService = new TargetService( + Arrays.asList(new SpacePerServiceInstance(), new ServiceInstanceGuidSuffix())); } @Test @@ -47,13 +47,12 @@ class TargetServiceTest { TargetSpec targetSpec = TargetSpec.builder().name("SpacePerServiceInstance").build(); BackingApplication backingApplication = BackingApplication.builder().name("app-name").build(); - //when add gets called - List updatedBackingApplications = - targetService - .addToBackingApplications(singletonList(backingApplication), targetSpec, "service-id") - .block(); + // when add gets called + List updatedBackingApplications = this.targetService + .addToBackingApplications(Collections.singletonList(backingApplication), targetSpec, "service-id") + .block(); - //then a host and space are added + // then a host and space are added BackingApplication updatedBackingApplication = updatedBackingApplications.get(0); assertThat(updatedBackingApplication.getName()).isEqualTo("app-name"); assertThat(updatedBackingApplication.getProperties().get("host")).isEqualTo("app-name-service-id"); @@ -67,14 +66,13 @@ class TargetServiceTest { BackingApplication backingApplication1 = BackingApplication.builder().name("app-name1").build(); BackingApplication backingApplication2 = BackingApplication.builder().name("app-name2").build(); - //when add gets called - List updatedBackingApplications = - targetService - .addToBackingApplications(Lists.newArrayList(backingApplication1, backingApplication2), targetSpec, + // when add gets called + List updatedBackingApplications = this.targetService + .addToBackingApplications(Lists.newArrayList(backingApplication1, backingApplication2), targetSpec, "service-id") - .block(); + .block(); - //then a host and space are added + // then a host and space are added BackingApplication updatedBackingApplication1 = updatedBackingApplications.get(0); assertThat(updatedBackingApplication1.getName()).isEqualTo("app-name1"); assertThat(updatedBackingApplication1.getProperties().get("host")).isEqualTo("app-name1-service-id"); @@ -93,14 +91,15 @@ class TargetServiceTest { final TargetSpec targetSpec = TargetSpec.builder().name("ServiceInstanceGuidSuffix").build(); final BackingApplication backingApplication = BackingApplication.builder().name(appName).build(); - StepVerifier.create(targetService.addToBackingApplications(singletonList(backingApplication), targetSpec, - serviceInstanceId)) - .consumeNextWith(backingApplications -> { - String name = backingApplications.get(0).getName(); - assertThat(name.length()).isLessThan(50).isGreaterThan(serviceInstanceId.length()); - assertThat(name).contains(serviceInstanceId).contains(appName); - }) - .verifyComplete(); + StepVerifier + .create(this.targetService.addToBackingApplications(Collections.singletonList(backingApplication), + targetSpec, serviceInstanceId)) + .consumeNextWith((backingApplications) -> { + String name = backingApplications.get(0).getName(); + assertThat(name.length()).isLessThan(50).isGreaterThan(serviceInstanceId.length()); + assertThat(name).contains(serviceInstanceId).contains(appName); + }) + .verifyComplete(); } @Test @@ -110,14 +109,15 @@ class TargetServiceTest { final TargetSpec targetSpec = TargetSpec.builder().name("ServiceInstanceGuidSuffix").build(); final BackingApplication backingApplication = BackingApplication.builder().name(appName).build(); - StepVerifier.create(targetService.addToBackingApplications(singletonList(backingApplication), targetSpec, - serviceInstanceId)) - .consumeNextWith(backingApplications -> { - String name = backingApplications.get(0).getName(); - assertThat(name.length()).isEqualTo(50); - assertThat(name).contains(serviceInstanceId); - }) - .verifyComplete(); + StepVerifier + .create(this.targetService.addToBackingApplications(Collections.singletonList(backingApplication), + targetSpec, serviceInstanceId)) + .consumeNextWith((backingApplications) -> { + String name = backingApplications.get(0).getName(); + assertThat(name.length()).isEqualTo(50); + assertThat(name).contains(serviceInstanceId); + }) + .verifyComplete(); } } diff --git a/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/manager/BackingAppManagementServiceTest.java b/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/manager/BackingAppManagementServiceTest.java deleted file mode 100644 index 01c7036..0000000 --- a/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/manager/BackingAppManagementServiceTest.java +++ /dev/null @@ -1,446 +0,0 @@ -/* - * Copyright 2002-2021 the original author or authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.appbroker.manager; - -import java.util.Collections; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; -import reactor.core.publisher.Mono; -import reactor.test.StepVerifier; - -import org.springframework.cloud.appbroker.deployer.BackingApplication; -import org.springframework.cloud.appbroker.deployer.BackingApplications; -import org.springframework.cloud.appbroker.deployer.BrokeredService; -import org.springframework.cloud.appbroker.deployer.BrokeredServices; -import org.springframework.cloud.appbroker.deployer.ServicesSpec; -import org.springframework.cloud.appbroker.deployer.deployer.AppDeployer; -import org.springframework.cloud.appbroker.deployer.deployer.GetApplicationRequest; -import org.springframework.cloud.appbroker.deployer.deployer.GetApplicationResponse; -import org.springframework.cloud.appbroker.deployer.deployer.GetServiceInstanceRequest; -import org.springframework.cloud.appbroker.deployer.deployer.GetServiceInstanceResponse; -import org.springframework.cloud.appbroker.extensions.targets.TargetService; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.argThat; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.BDDMockito.given; -import static org.mockito.BDDMockito.then; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.verifyNoMoreInteractions; - -@ExtendWith(MockitoExtension.class) -class BackingAppManagementServiceTest { - - private BackingAppManagementService backingAppManagementService; - - private BackingApplications backingApps; - - @Mock - private ManagementClient managementClient; - - @Mock - private AppDeployer appDeployer; - - @Mock - private TargetService targetService; - - @BeforeEach - void setUp() { - this.backingApps = BackingApplications.builder() - .backingApplication(BackingApplication.builder() - .name("testApp1") - .properties(Collections.singletonMap("target", "customTarget")) - .path("https://myfiles/app1.jar") - .build()) - .backingApplication(BackingApplication.builder() - .name("testApp2") - .path("https://myfiles/app2.jar") - .build()) - .build(); - - BrokeredServices brokeredServices = BrokeredServices - .builder() - .service(BrokeredService - .builder() - .serviceName("service1") - .planName("plan1") - .apps(backingApps) - .build()) - .build(); - - this.backingAppManagementService = new BackingAppManagementService(managementClient, appDeployer, - brokeredServices, - targetService); - } - - @Test - void stopApplications() { - doReturn(Mono.empty()).when(managementClient).stop(backingApps.get(0)); - doReturn(Mono.empty()).when(managementClient).stop(backingApps.get(1)); - - given(appDeployer.getServiceInstance(any(GetServiceInstanceRequest.class))) - .willReturn(Mono.just(GetServiceInstanceResponse.builder() - .name("foo-service") - .plan("plan1") - .service("service1") - .build())); - - given(targetService.addToBackingApplications(eq(backingApps), any(), eq("foo-service-id"))) - .willReturn(Mono.just(backingApps)); - - StepVerifier.create(backingAppManagementService.stop("foo-service-id")) - .expectNext() - .expectNext() - .verifyComplete(); - - verify(appDeployer).getServiceInstance(any(GetServiceInstanceRequest.class)); - verify(targetService).addToBackingApplications(eq(backingApps), any(), eq("foo-service-id")); - verify(managementClient, times(2)).stop(any(BackingApplication.class)); - verifyNoMoreInteractions(appDeployer, targetService, managementClient); - } - - @Test - void stopApplicationsWithEmptyApplications() { - BackingApplications emptyBackingApps = BackingApplications.builder().build(); - - BrokeredServices brokeredServicesNoApps = BrokeredServices - .builder() - .service(BrokeredService - .builder() - .serviceName("service1") - .planName("plan1") - .apps(emptyBackingApps) - .build()) - .build(); - - this.backingAppManagementService = new BackingAppManagementService(managementClient, appDeployer, - brokeredServicesNoApps, - targetService); - - given(appDeployer.getServiceInstance(any(GetServiceInstanceRequest.class))) - .willReturn(Mono.just(GetServiceInstanceResponse.builder() - .name("foo-service") - .plan("plan1") - .service("service1") - .build())); - - given(targetService.addToBackingApplications(eq(emptyBackingApps), any(), eq("foo-service-id"))) - .willReturn(Mono.just(emptyBackingApps)); - - StepVerifier.create(backingAppManagementService.stop("foo-service-id")) - .verifyComplete(); - - verify(appDeployer).getServiceInstance(any(GetServiceInstanceRequest.class)); - verify(targetService).addToBackingApplications(eq(emptyBackingApps), any(), eq("foo-service-id")); - verifyNoInteractions(managementClient); - verifyNoMoreInteractions(appDeployer, targetService, managementClient); - } - - @Test - void stopApplicationsServiceNotFound() { - given(appDeployer.getServiceInstance(any(GetServiceInstanceRequest.class))) - .willReturn(Mono.just(GetServiceInstanceResponse.builder() - .build())); - - StepVerifier.create(backingAppManagementService.stop("unknown-service-id")) - .verifyComplete(); - - verifyNoMoreInteractions(appDeployer, targetService, managementClient); - } - - @Test - void startApplications() { - given(appDeployer.getServiceInstance(any(GetServiceInstanceRequest.class))) - .willReturn(Mono.just(GetServiceInstanceResponse.builder() - .name("foo-service") - .plan("plan1") - .service("service1") - .build())); - - given(targetService.addToBackingApplications(eq(backingApps), any(), eq("foo-service-id"))) - .willReturn(Mono.just(backingApps)); - - doReturn(Mono.empty()).when(managementClient).start(backingApps.get(0)); - doReturn(Mono.empty()).when(managementClient).start(backingApps.get(1)); - - StepVerifier.create(backingAppManagementService.start("foo-service-id")) - .expectNext() - .expectNext() - .verifyComplete(); - - verify(appDeployer).getServiceInstance(any(GetServiceInstanceRequest.class)); - verify(targetService).addToBackingApplications(eq(backingApps), any(), eq("foo-service-id")); - verify(managementClient, times(2)).start(any(BackingApplication.class)); - verifyNoMoreInteractions(appDeployer, targetService, managementClient); - } - - @Test - void startApplicationsServiceNotFound() { - given(appDeployer.getServiceInstance(any(GetServiceInstanceRequest.class))) - .willReturn(Mono.just(GetServiceInstanceResponse.builder() - .build())); - - StepVerifier.create(backingAppManagementService.start("unknown-service-id")) - .verifyComplete(); - - verifyNoMoreInteractions(appDeployer, targetService, managementClient); - } - - @Test - void startApplicationsWithEmptyApplications() { - BackingApplications emptyBackingApps = BackingApplications.builder().build(); - - BrokeredServices brokeredServicesNoApps = BrokeredServices - .builder() - .service(BrokeredService - .builder() - .serviceName("service1") - .planName("plan1") - .apps(emptyBackingApps) - .build()) - .build(); - - this.backingAppManagementService = new BackingAppManagementService(managementClient, appDeployer, - brokeredServicesNoApps, - targetService); - - given(appDeployer.getServiceInstance(any(GetServiceInstanceRequest.class))) - .willReturn(Mono.just(GetServiceInstanceResponse.builder() - .name("foo-service") - .plan("plan1") - .service("service1") - .build())); - - given(targetService.addToBackingApplications(eq(emptyBackingApps), any(), eq("foo-service-id"))) - .willReturn(Mono.just(emptyBackingApps)); - - StepVerifier.create(backingAppManagementService.start("foo-service-id")) - .verifyComplete(); - - verify(appDeployer).getServiceInstance(any(GetServiceInstanceRequest.class)); - verify(targetService).addToBackingApplications(eq(emptyBackingApps), any(), eq("foo-service-id")); - verifyNoInteractions(managementClient); - verifyNoMoreInteractions(appDeployer, targetService, managementClient); - } - - @Test - void restartApplications() { - given(appDeployer.getServiceInstance(any(GetServiceInstanceRequest.class))) - .willReturn(Mono.just(GetServiceInstanceResponse.builder() - .name("foo-service") - .plan("plan1") - .service("service1") - .build())); - - given(targetService.addToBackingApplications(eq(backingApps), any(), eq("foo-service-id"))) - .willReturn(Mono.just(backingApps)); - - doReturn(Mono.empty()).when(managementClient).restart(backingApps.get(0)); - doReturn(Mono.empty()).when(managementClient).restart(backingApps.get(1)); - - StepVerifier.create(backingAppManagementService.restart("foo-service-id")) - .expectNext() - .expectNext() - .verifyComplete(); - - verify(appDeployer).getServiceInstance(any(GetServiceInstanceRequest.class)); - verify(targetService).addToBackingApplications(eq(backingApps), any(), eq("foo-service-id")); - verify(managementClient, times(2)).restart(any(BackingApplication.class)); - verifyNoMoreInteractions(appDeployer, targetService, managementClient); - } - - @Test - void restartApplicationsServiceNotFound() { - given(appDeployer.getServiceInstance(any(GetServiceInstanceRequest.class))) - .willReturn(Mono.just(GetServiceInstanceResponse.builder() - .build())); - - StepVerifier.create(backingAppManagementService.restart("unknown-service-id")) - .verifyComplete(); - - verifyNoMoreInteractions(appDeployer, targetService, managementClient); - } - - @Test - void restartApplicationsWithEmptyApplications() { - BackingApplications emptyBackingApps = BackingApplications.builder().build(); - - BrokeredServices brokeredServicesNoApps = BrokeredServices - .builder() - .service(BrokeredService - .builder() - .serviceName("service1") - .planName("plan1") - .apps(emptyBackingApps) - .build()) - .build(); - - this.backingAppManagementService = new BackingAppManagementService(managementClient, appDeployer, - brokeredServicesNoApps, - targetService); - - given(appDeployer.getServiceInstance(any(GetServiceInstanceRequest.class))) - .willReturn(Mono.just(GetServiceInstanceResponse.builder() - .name("foo-service") - .plan("plan1") - .service("service1") - .build())); - - given(targetService.addToBackingApplications(eq(emptyBackingApps), any(), eq("foo-service-id"))) - .willReturn(Mono.just(emptyBackingApps)); - - StepVerifier.create(backingAppManagementService.restart("foo-service-id")) - .verifyComplete(); - - verify(appDeployer).getServiceInstance(any(GetServiceInstanceRequest.class)); - verify(targetService).addToBackingApplications(eq(emptyBackingApps), any(), eq("foo-service-id")); - verifyNoInteractions(managementClient); - verifyNoMoreInteractions(appDeployer, targetService, managementClient); - } - - @Test - @SuppressWarnings("unchecked") - void getDeployedBackingApplications() { - given(appDeployer.getServiceInstance(any(GetServiceInstanceRequest.class))) - .willReturn(Mono.just(GetServiceInstanceResponse.builder() - .name("foo-service") - .plan("plan1") - .service("service1") - .build())); - - given(appDeployer.get(any(GetApplicationRequest.class))) - .willReturn(Mono.just(GetApplicationResponse.builder() - .name("testApp1") - .service("service1") - .service("service2") - .build()), - Mono.just(GetApplicationResponse.builder() - .name("testApp2") - .service("service3") - .build())); - - given(targetService.addToBackingApplications(eq(backingApps), any(), eq("foo-service-id"))) - .willReturn(Mono.just(backingApps)); - - StepVerifier.create(backingAppManagementService.getDeployedBackingApplications("foo-service-id")) - .expectNext(BackingApplications.builder() - .backingApplication(BackingApplication.builder() - .name("testApp1") - .properties(Collections.singletonMap("target", "customTarget")) - .services( - ServicesSpec.builder().serviceInstanceName("service1").build(), - ServicesSpec.builder().serviceInstanceName("service2").build()) - .build()) - .backingApplication(BackingApplication.builder() - .name("testApp2") - .services(ServicesSpec.builder().serviceInstanceName("service3").build()) - .build()) - .build()) - .verifyComplete(); - - then(targetService).should().addToBackingApplications(eq(backingApps), any(), eq("foo-service-id")); - then(appDeployer).should().getServiceInstance(argThat(req -> "foo-service-id".equals(req.getServiceInstanceId()))); - then(appDeployer).should().get(argThat(req -> "testApp1".equals(req.getName()))); - then(appDeployer).should().get(argThat(req -> "testApp2".equals(req.getName()))); - - verifyNoInteractions(managementClient); - verifyNoMoreInteractions(appDeployer, targetService, managementClient); - } - - @Test - void restageApplications() { - given(appDeployer.getServiceInstance(any(GetServiceInstanceRequest.class))) - .willReturn(Mono.just(GetServiceInstanceResponse.builder() - .name("foo-service") - .plan("plan1") - .service("service1") - .build())); - - given(targetService.addToBackingApplications(eq(backingApps), any(), eq("foo-service-id"))) - .willReturn(Mono.just(backingApps)); - - doReturn(Mono.empty()).when(managementClient).restage(backingApps.get(0)); - doReturn(Mono.empty()).when(managementClient).restage(backingApps.get(1)); - - StepVerifier.create(backingAppManagementService.restage("foo-service-id")) - .expectNext() - .expectNext() - .verifyComplete(); - - verify(appDeployer).getServiceInstance(any(GetServiceInstanceRequest.class)); - verify(targetService).addToBackingApplications(eq(backingApps), any(), eq("foo-service-id")); - verify(managementClient, times(2)).restage(any(BackingApplication.class)); - verifyNoMoreInteractions(appDeployer, targetService, managementClient); - } - - @Test - void restageApplicationsServiceNotFound() { - given(appDeployer.getServiceInstance(any(GetServiceInstanceRequest.class))) - .willReturn(Mono.just(GetServiceInstanceResponse.builder() - .build())); - - StepVerifier.create(backingAppManagementService.restage("unknown-service-id")) - .verifyComplete(); - - verifyNoMoreInteractions(appDeployer, targetService, managementClient); - } - - @Test - void restageApplicationsWithEmptyApplications() { - BackingApplications emptyBackingApps = BackingApplications.builder().build(); - - BrokeredServices brokeredServicesNoApps = BrokeredServices - .builder() - .service(BrokeredService - .builder() - .serviceName("service1") - .planName("plan1") - .apps(emptyBackingApps) - .build()) - .build(); - - this.backingAppManagementService = new BackingAppManagementService(managementClient, appDeployer, - brokeredServicesNoApps, - targetService); - - given(appDeployer.getServiceInstance(any(GetServiceInstanceRequest.class))) - .willReturn(Mono.just(GetServiceInstanceResponse.builder() - .name("foo-service") - .plan("plan1") - .service("service1") - .build())); - - given(targetService.addToBackingApplications(eq(emptyBackingApps), any(), eq("foo-service-id"))) - .willReturn(Mono.just(emptyBackingApps)); - - StepVerifier.create(backingAppManagementService.restage("foo-service-id")) - .verifyComplete(); - - verify(appDeployer).getServiceInstance(any(GetServiceInstanceRequest.class)); - verify(targetService).addToBackingApplications(eq(emptyBackingApps), any(), eq("foo-service-id")); - verifyNoInteractions(managementClient); - verifyNoMoreInteractions(appDeployer, targetService, managementClient); - } - -} diff --git a/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/manager/BackingAppManagementServiceTests.java b/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/manager/BackingAppManagementServiceTests.java new file mode 100644 index 0000000..f93b8b6 --- /dev/null +++ b/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/manager/BackingAppManagementServiceTests.java @@ -0,0 +1,353 @@ +/* + * Copyright 2016-2021 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.cloud.appbroker.manager; + +import java.util.Collections; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +import org.springframework.cloud.appbroker.deployer.BackingApplication; +import org.springframework.cloud.appbroker.deployer.BackingApplications; +import org.springframework.cloud.appbroker.deployer.BrokeredService; +import org.springframework.cloud.appbroker.deployer.BrokeredServices; +import org.springframework.cloud.appbroker.deployer.ServicesSpec; +import org.springframework.cloud.appbroker.deployer.deployer.AppDeployer; +import org.springframework.cloud.appbroker.deployer.deployer.GetApplicationRequest; +import org.springframework.cloud.appbroker.deployer.deployer.GetApplicationResponse; +import org.springframework.cloud.appbroker.deployer.deployer.GetServiceInstanceRequest; +import org.springframework.cloud.appbroker.deployer.deployer.GetServiceInstanceResponse; +import org.springframework.cloud.appbroker.extensions.targets.TargetService; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.BDDMockito.given; +import static org.mockito.BDDMockito.then; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; + +@ExtendWith(MockitoExtension.class) +class BackingAppManagementServiceTests { + + private BackingAppManagementService backingAppManagementService; + + private BackingApplications backingApps; + + @Mock + private ManagementClient managementClient; + + @Mock + private AppDeployer appDeployer; + + @Mock + private TargetService targetService; + + @BeforeEach + void setUp() { + this.backingApps = BackingApplications.builder() + .backingApplication(BackingApplication.builder() + .name("testApp1") + .properties(Collections.singletonMap("target", "customTarget")) + .path("https://myfiles/app1.jar") + .build()) + .backingApplication(BackingApplication.builder().name("testApp2").path("https://myfiles/app2.jar").build()) + .build(); + + BrokeredServices brokeredServices = BrokeredServices.builder() + .service(BrokeredService.builder().serviceName("service1").planName("plan1").apps(this.backingApps).build()) + .build(); + + this.backingAppManagementService = new BackingAppManagementService(this.managementClient, this.appDeployer, + brokeredServices, this.targetService); + } + + @Test + void stopApplications() { + doReturn(Mono.empty()).when(this.managementClient).stop(this.backingApps.get(0)); + doReturn(Mono.empty()).when(this.managementClient).stop(this.backingApps.get(1)); + + given(this.appDeployer.getServiceInstance(any(GetServiceInstanceRequest.class))).willReturn(Mono + .just(GetServiceInstanceResponse.builder().name("foo-service").plan("plan1").service("service1").build())); + + given(this.targetService.addToBackingApplications(eq(this.backingApps), any(), eq("foo-service-id"))) + .willReturn(Mono.just(this.backingApps)); + + StepVerifier.create(this.backingAppManagementService.stop("foo-service-id")) + .expectNext() + .expectNext() + .verifyComplete(); + + verify(this.appDeployer).getServiceInstance(any(GetServiceInstanceRequest.class)); + verify(this.targetService).addToBackingApplications(eq(this.backingApps), any(), eq("foo-service-id")); + verify(this.managementClient, times(2)).stop(any(BackingApplication.class)); + verifyNoMoreInteractions(this.appDeployer, this.targetService, this.managementClient); + } + + @Test + void stopApplicationsWithEmptyApplications() { + BackingApplications emptyBackingApps = BackingApplications.builder().build(); + + BrokeredServices brokeredServicesNoApps = BrokeredServices.builder() + .service(BrokeredService.builder().serviceName("service1").planName("plan1").apps(emptyBackingApps).build()) + .build(); + + this.backingAppManagementService = new BackingAppManagementService(this.managementClient, this.appDeployer, + brokeredServicesNoApps, this.targetService); + + given(this.appDeployer.getServiceInstance(any(GetServiceInstanceRequest.class))).willReturn(Mono + .just(GetServiceInstanceResponse.builder().name("foo-service").plan("plan1").service("service1").build())); + + given(this.targetService.addToBackingApplications(eq(emptyBackingApps), any(), eq("foo-service-id"))) + .willReturn(Mono.just(emptyBackingApps)); + + StepVerifier.create(this.backingAppManagementService.stop("foo-service-id")).verifyComplete(); + + verify(this.appDeployer).getServiceInstance(any(GetServiceInstanceRequest.class)); + verify(this.targetService).addToBackingApplications(eq(emptyBackingApps), any(), eq("foo-service-id")); + verifyNoInteractions(this.managementClient); + verifyNoMoreInteractions(this.appDeployer, this.targetService, this.managementClient); + } + + @Test + void stopApplicationsServiceNotFound() { + given(this.appDeployer.getServiceInstance(any(GetServiceInstanceRequest.class))) + .willReturn(Mono.just(GetServiceInstanceResponse.builder().build())); + + StepVerifier.create(this.backingAppManagementService.stop("unknown-service-id")).verifyComplete(); + + verifyNoMoreInteractions(this.appDeployer, this.targetService, this.managementClient); + } + + @Test + void startApplications() { + given(this.appDeployer.getServiceInstance(any(GetServiceInstanceRequest.class))).willReturn(Mono + .just(GetServiceInstanceResponse.builder().name("foo-service").plan("plan1").service("service1").build())); + + given(this.targetService.addToBackingApplications(eq(this.backingApps), any(), eq("foo-service-id"))) + .willReturn(Mono.just(this.backingApps)); + + doReturn(Mono.empty()).when(this.managementClient).start(this.backingApps.get(0)); + doReturn(Mono.empty()).when(this.managementClient).start(this.backingApps.get(1)); + + StepVerifier.create(this.backingAppManagementService.start("foo-service-id")) + .expectNext() + .expectNext() + .verifyComplete(); + + verify(this.appDeployer).getServiceInstance(any(GetServiceInstanceRequest.class)); + verify(this.targetService).addToBackingApplications(eq(this.backingApps), any(), eq("foo-service-id")); + verify(this.managementClient, times(2)).start(any(BackingApplication.class)); + verifyNoMoreInteractions(this.appDeployer, this.targetService, this.managementClient); + } + + @Test + void startApplicationsServiceNotFound() { + given(this.appDeployer.getServiceInstance(any(GetServiceInstanceRequest.class))) + .willReturn(Mono.just(GetServiceInstanceResponse.builder().build())); + + StepVerifier.create(this.backingAppManagementService.start("unknown-service-id")).verifyComplete(); + + verifyNoMoreInteractions(this.appDeployer, this.targetService, this.managementClient); + } + + @Test + void startApplicationsWithEmptyApplications() { + BackingApplications emptyBackingApps = BackingApplications.builder().build(); + + BrokeredServices brokeredServicesNoApps = BrokeredServices.builder() + .service(BrokeredService.builder().serviceName("service1").planName("plan1").apps(emptyBackingApps).build()) + .build(); + + this.backingAppManagementService = new BackingAppManagementService(this.managementClient, this.appDeployer, + brokeredServicesNoApps, this.targetService); + + given(this.appDeployer.getServiceInstance(any(GetServiceInstanceRequest.class))).willReturn(Mono + .just(GetServiceInstanceResponse.builder().name("foo-service").plan("plan1").service("service1").build())); + + given(this.targetService.addToBackingApplications(eq(emptyBackingApps), any(), eq("foo-service-id"))) + .willReturn(Mono.just(emptyBackingApps)); + + StepVerifier.create(this.backingAppManagementService.start("foo-service-id")).verifyComplete(); + + verify(this.appDeployer).getServiceInstance(any(GetServiceInstanceRequest.class)); + verify(this.targetService).addToBackingApplications(eq(emptyBackingApps), any(), eq("foo-service-id")); + verifyNoInteractions(this.managementClient); + verifyNoMoreInteractions(this.appDeployer, this.targetService, this.managementClient); + } + + @Test + void restartApplications() { + given(this.appDeployer.getServiceInstance(any(GetServiceInstanceRequest.class))).willReturn(Mono + .just(GetServiceInstanceResponse.builder().name("foo-service").plan("plan1").service("service1").build())); + + given(this.targetService.addToBackingApplications(eq(this.backingApps), any(), eq("foo-service-id"))) + .willReturn(Mono.just(this.backingApps)); + + doReturn(Mono.empty()).when(this.managementClient).restart(this.backingApps.get(0)); + doReturn(Mono.empty()).when(this.managementClient).restart(this.backingApps.get(1)); + + StepVerifier.create(this.backingAppManagementService.restart("foo-service-id")) + .expectNext() + .expectNext() + .verifyComplete(); + + verify(this.appDeployer).getServiceInstance(any(GetServiceInstanceRequest.class)); + verify(this.targetService).addToBackingApplications(eq(this.backingApps), any(), eq("foo-service-id")); + verify(this.managementClient, times(2)).restart(any(BackingApplication.class)); + verifyNoMoreInteractions(this.appDeployer, this.targetService, this.managementClient); + } + + @Test + void restartApplicationsServiceNotFound() { + given(this.appDeployer.getServiceInstance(any(GetServiceInstanceRequest.class))) + .willReturn(Mono.just(GetServiceInstanceResponse.builder().build())); + + StepVerifier.create(this.backingAppManagementService.restart("unknown-service-id")).verifyComplete(); + + verifyNoMoreInteractions(this.appDeployer, this.targetService, this.managementClient); + } + + @Test + void restartApplicationsWithEmptyApplications() { + BackingApplications emptyBackingApps = BackingApplications.builder().build(); + + BrokeredServices brokeredServicesNoApps = BrokeredServices.builder() + .service(BrokeredService.builder().serviceName("service1").planName("plan1").apps(emptyBackingApps).build()) + .build(); + + this.backingAppManagementService = new BackingAppManagementService(this.managementClient, this.appDeployer, + brokeredServicesNoApps, this.targetService); + + given(this.appDeployer.getServiceInstance(any(GetServiceInstanceRequest.class))).willReturn(Mono + .just(GetServiceInstanceResponse.builder().name("foo-service").plan("plan1").service("service1").build())); + + given(this.targetService.addToBackingApplications(eq(emptyBackingApps), any(), eq("foo-service-id"))) + .willReturn(Mono.just(emptyBackingApps)); + + StepVerifier.create(this.backingAppManagementService.restart("foo-service-id")).verifyComplete(); + + verify(this.appDeployer).getServiceInstance(any(GetServiceInstanceRequest.class)); + verify(this.targetService).addToBackingApplications(eq(emptyBackingApps), any(), eq("foo-service-id")); + verifyNoInteractions(this.managementClient); + verifyNoMoreInteractions(this.appDeployer, this.targetService, this.managementClient); + } + + @Test + @SuppressWarnings("unchecked") + void getDeployedBackingApplications() { + given(this.appDeployer.getServiceInstance(any(GetServiceInstanceRequest.class))).willReturn(Mono + .just(GetServiceInstanceResponse.builder().name("foo-service").plan("plan1").service("service1").build())); + + given(this.appDeployer.get(any(GetApplicationRequest.class))).willReturn(Mono + .just(GetApplicationResponse.builder().name("testApp1").service("service1").service("service2").build()), + Mono.just(GetApplicationResponse.builder().name("testApp2").service("service3").build())); + + given(this.targetService.addToBackingApplications(eq(this.backingApps), any(), eq("foo-service-id"))) + .willReturn(Mono.just(this.backingApps)); + + StepVerifier.create(this.backingAppManagementService.getDeployedBackingApplications("foo-service-id")) + .expectNext(BackingApplications.builder() + .backingApplication(BackingApplication.builder() + .name("testApp1") + .properties(Collections.singletonMap("target", "customTarget")) + .services(ServicesSpec.builder().serviceInstanceName("service1").build(), + ServicesSpec.builder().serviceInstanceName("service2").build()) + .build()) + .backingApplication(BackingApplication.builder() + .name("testApp2") + .services(ServicesSpec.builder().serviceInstanceName("service3").build()) + .build()) + .build()) + .verifyComplete(); + + then(this.targetService).should().addToBackingApplications(eq(this.backingApps), any(), eq("foo-service-id")); + then(this.appDeployer).should() + .getServiceInstance(argThat((req) -> "foo-service-id".equals(req.getServiceInstanceId()))); + then(this.appDeployer).should().get(argThat((req) -> "testApp1".equals(req.getName()))); + then(this.appDeployer).should().get(argThat((req) -> "testApp2".equals(req.getName()))); + + verifyNoInteractions(this.managementClient); + verifyNoMoreInteractions(this.appDeployer, this.targetService, this.managementClient); + } + + @Test + void restageApplications() { + given(this.appDeployer.getServiceInstance(any(GetServiceInstanceRequest.class))).willReturn(Mono + .just(GetServiceInstanceResponse.builder().name("foo-service").plan("plan1").service("service1").build())); + + given(this.targetService.addToBackingApplications(eq(this.backingApps), any(), eq("foo-service-id"))) + .willReturn(Mono.just(this.backingApps)); + + doReturn(Mono.empty()).when(this.managementClient).restage(this.backingApps.get(0)); + doReturn(Mono.empty()).when(this.managementClient).restage(this.backingApps.get(1)); + + StepVerifier.create(this.backingAppManagementService.restage("foo-service-id")) + .expectNext() + .expectNext() + .verifyComplete(); + + verify(this.appDeployer).getServiceInstance(any(GetServiceInstanceRequest.class)); + verify(this.targetService).addToBackingApplications(eq(this.backingApps), any(), eq("foo-service-id")); + verify(this.managementClient, times(2)).restage(any(BackingApplication.class)); + verifyNoMoreInteractions(this.appDeployer, this.targetService, this.managementClient); + } + + @Test + void restageApplicationsServiceNotFound() { + given(this.appDeployer.getServiceInstance(any(GetServiceInstanceRequest.class))) + .willReturn(Mono.just(GetServiceInstanceResponse.builder().build())); + + StepVerifier.create(this.backingAppManagementService.restage("unknown-service-id")).verifyComplete(); + + verifyNoMoreInteractions(this.appDeployer, this.targetService, this.managementClient); + } + + @Test + void restageApplicationsWithEmptyApplications() { + BackingApplications emptyBackingApps = BackingApplications.builder().build(); + + BrokeredServices brokeredServicesNoApps = BrokeredServices.builder() + .service(BrokeredService.builder().serviceName("service1").planName("plan1").apps(emptyBackingApps).build()) + .build(); + + this.backingAppManagementService = new BackingAppManagementService(this.managementClient, this.appDeployer, + brokeredServicesNoApps, this.targetService); + + given(this.appDeployer.getServiceInstance(any(GetServiceInstanceRequest.class))).willReturn(Mono + .just(GetServiceInstanceResponse.builder().name("foo-service").plan("plan1").service("service1").build())); + + given(this.targetService.addToBackingApplications(eq(emptyBackingApps), any(), eq("foo-service-id"))) + .willReturn(Mono.just(emptyBackingApps)); + + StepVerifier.create(this.backingAppManagementService.restage("foo-service-id")).verifyComplete(); + + verify(this.appDeployer).getServiceInstance(any(GetServiceInstanceRequest.class)); + verify(this.targetService).addToBackingApplications(eq(emptyBackingApps), any(), eq("foo-service-id")); + verifyNoInteractions(this.managementClient); + verifyNoMoreInteractions(this.appDeployer, this.targetService, this.managementClient); + } + +} diff --git a/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/manager/BackingAppManagementServiceWithServiceInstanceIdTest.java b/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/manager/BackingAppManagementServiceWithServiceInstanceIdTest.java deleted file mode 100644 index 6f8fa7c..0000000 --- a/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/manager/BackingAppManagementServiceWithServiceInstanceIdTest.java +++ /dev/null @@ -1,320 +0,0 @@ -/* - * Copyright 2002-2020 the original author or authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.appbroker.manager; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; -import reactor.core.publisher.Mono; -import reactor.test.StepVerifier; - -import org.springframework.cloud.appbroker.deployer.BackingApplication; -import org.springframework.cloud.appbroker.deployer.BackingApplications; -import org.springframework.cloud.appbroker.deployer.BrokeredService; -import org.springframework.cloud.appbroker.deployer.BrokeredServices; -import org.springframework.cloud.appbroker.deployer.ServicesSpec; -import org.springframework.cloud.appbroker.deployer.deployer.AppDeployer; -import org.springframework.cloud.appbroker.deployer.deployer.GetApplicationRequest; -import org.springframework.cloud.appbroker.deployer.deployer.GetApplicationResponse; -import org.springframework.cloud.appbroker.extensions.targets.TargetService; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.argThat; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.BDDMockito.given; -import static org.mockito.BDDMockito.then; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.verifyNoMoreInteractions; - -@ExtendWith(MockitoExtension.class) -class BackingAppManagementServiceWithServiceInstanceIdTest { - - private BackingAppManagementService backingAppManagementService; - - private BackingApplications backingApps; - - @Mock - private ManagementClient managementClient; - - @Mock - private AppDeployer appDeployer; - - @Mock - private TargetService targetService; - - @BeforeEach - void setUp() { - this.backingApps = BackingApplications.builder() - .backingApplication(BackingApplication.builder() - .name("testApp1") - .path("https://myfiles/app1.jar") - .build()) - .backingApplication(BackingApplication.builder() - .name("testApp2") - .path("https://myfiles/app2.jar") - .build()) - .build(); - - BrokeredServices brokeredServices = BrokeredServices - .builder() - .service(BrokeredService - .builder() - .serviceName("service1") - .planName("plan1") - .apps(backingApps) - .build()) - .build(); - - this.backingAppManagementService = new BackingAppManagementService(managementClient, appDeployer, - brokeredServices, - targetService); - } - - @Test - void stopApplications() { - doReturn(Mono.empty()).when(managementClient).stop(backingApps.get(0)); - doReturn(Mono.empty()).when(managementClient).stop(backingApps.get(1)); - - given(targetService.addToBackingApplications(eq(backingApps), any(), eq("foo-service-id"))) - .willReturn(Mono.just(backingApps)); - - StepVerifier.create(backingAppManagementService.stop("foo-service-id", "service1", "plan1")) - .expectNext() - .expectNext() - .verifyComplete(); - - verify(targetService).addToBackingApplications(eq(backingApps), any(), eq("foo-service-id")); - verify(managementClient, times(2)).stop(any(BackingApplication.class)); - verifyNoMoreInteractions(appDeployer, targetService, managementClient); - } - - @Test - void stopApplicationsWithEmptyApplications() { - BackingApplications emptyBackingApps = BackingApplications.builder().build(); - - BrokeredServices brokeredServicesNoApps = BrokeredServices - .builder() - .service(BrokeredService - .builder() - .serviceName("service1") - .planName("plan1") - .apps(emptyBackingApps) - .build()) - .build(); - - this.backingAppManagementService = new BackingAppManagementService(managementClient, appDeployer, - brokeredServicesNoApps, - targetService); - - given(targetService.addToBackingApplications(eq(emptyBackingApps), any(), eq("foo-service-id"))) - .willReturn(Mono.just(emptyBackingApps)); - - StepVerifier.create(backingAppManagementService.stop("foo-service-id", "service1", "plan1")) - .verifyComplete(); - - verify(targetService).addToBackingApplications(eq(emptyBackingApps), any(), eq("foo-service-id")); - verifyNoInteractions(managementClient); - verifyNoMoreInteractions(appDeployer, targetService, managementClient); - } - - @Test - void startApplications() { - given(targetService.addToBackingApplications(eq(backingApps), any(), eq("foo-service-id"))) - .willReturn(Mono.just(backingApps)); - - doReturn(Mono.empty()).when(managementClient).start(backingApps.get(0)); - doReturn(Mono.empty()).when(managementClient).start(backingApps.get(1)); - - StepVerifier.create(backingAppManagementService.start("foo-service-id", "service1", "plan1")) - .expectNext() - .expectNext() - .verifyComplete(); - - verify(targetService).addToBackingApplications(eq(backingApps), any(), eq("foo-service-id")); - verify(managementClient, times(2)).start(any(BackingApplication.class)); - verifyNoMoreInteractions(appDeployer, targetService, managementClient); - } - - @Test - void startApplicationsWithEmptyApplications() { - BackingApplications emptyBackingApps = BackingApplications.builder().build(); - - BrokeredServices brokeredServicesNoApps = BrokeredServices - .builder() - .service(BrokeredService - .builder() - .serviceName("service1") - .planName("plan1") - .apps(emptyBackingApps) - .build()) - .build(); - - this.backingAppManagementService = new BackingAppManagementService(managementClient, appDeployer, - brokeredServicesNoApps, - targetService); - - given(targetService.addToBackingApplications(eq(emptyBackingApps), any(), eq("foo-service-id"))) - .willReturn(Mono.just(emptyBackingApps)); - - StepVerifier.create(backingAppManagementService.start("foo-service-id", "service1", "plan1")) - .verifyComplete(); - - verify(targetService).addToBackingApplications(eq(emptyBackingApps), any(), eq("foo-service-id")); - verifyNoInteractions(managementClient); - verifyNoMoreInteractions(appDeployer, targetService, managementClient); - } - - @Test - void restartApplications() { - given(targetService.addToBackingApplications(eq(backingApps), any(), eq("foo-service-id"))) - .willReturn(Mono.just(backingApps)); - - doReturn(Mono.empty()).when(managementClient).restart(backingApps.get(0)); - doReturn(Mono.empty()).when(managementClient).restart(backingApps.get(1)); - - StepVerifier.create(backingAppManagementService.restart("foo-service-id", "service1", "plan1")) - .expectNext() - .expectNext() - .verifyComplete(); - - verify(targetService).addToBackingApplications(eq(backingApps), any(), eq("foo-service-id")); - verify(managementClient, times(2)).restart(any(BackingApplication.class)); - verifyNoMoreInteractions(appDeployer, targetService, managementClient); - } - - @Test - void restartApplicationsWithEmptyApplications() { - BackingApplications emptyBackingApps = BackingApplications.builder().build(); - - BrokeredServices brokeredServicesNoApps = BrokeredServices - .builder() - .service(BrokeredService - .builder() - .serviceName("service1") - .planName("plan1") - .apps(emptyBackingApps) - .build()) - .build(); - - this.backingAppManagementService = new BackingAppManagementService(managementClient, appDeployer, - brokeredServicesNoApps, - targetService); - - given(targetService.addToBackingApplications(eq(emptyBackingApps), any(), eq("foo-service-id"))) - .willReturn(Mono.just(emptyBackingApps)); - - StepVerifier.create(backingAppManagementService.restart("foo-service-id", "service1", "plan1")) - .verifyComplete(); - - verify(targetService).addToBackingApplications(eq(emptyBackingApps), any(), eq("foo-service-id")); - verifyNoInteractions(managementClient); - verifyNoMoreInteractions(appDeployer, targetService, managementClient); - } - - @Test - @SuppressWarnings("unchecked") - void getDeployedBackingApplications() { - given(appDeployer.get(any(GetApplicationRequest.class))) - .willReturn(Mono.just(GetApplicationResponse.builder() - .name("testApp1") - .service("service1") - .service("service2") - .build()), - Mono.just(GetApplicationResponse.builder() - .name("testApp2") - .service("service3") - .build())); - - given(targetService.addToBackingApplications(eq(backingApps), any(), eq("foo-service-id"))) - .willReturn(Mono.just(backingApps)); - - StepVerifier.create(backingAppManagementService.getDeployedBackingApplications("foo-service-id", "service1", "plan1")) - .expectNext(BackingApplications.builder() - .backingApplication(BackingApplication.builder() - .name("testApp1") - .services( - ServicesSpec.builder().serviceInstanceName("service1").build(), - ServicesSpec.builder().serviceInstanceName("service2").build()) - .build()) - .backingApplication(BackingApplication.builder() - .name("testApp2") - .services(ServicesSpec.builder().serviceInstanceName("service3").build()) - .build()) - .build()) - .verifyComplete(); - - then(targetService).should().addToBackingApplications(eq(backingApps), any(), eq("foo-service-id")); - then(appDeployer).should().get(argThat(req -> "testApp1".equals(req.getName()))); - then(appDeployer).should().get(argThat(req -> "testApp2".equals(req.getName()))); - - verifyNoInteractions(managementClient); - verifyNoMoreInteractions(appDeployer, targetService, managementClient); - } - - @Test - void restageApplications() { - given(targetService.addToBackingApplications(eq(backingApps), any(), eq("foo-service-id"))) - .willReturn(Mono.just(backingApps)); - - doReturn(Mono.empty()).when(managementClient).restage(backingApps.get(0)); - doReturn(Mono.empty()).when(managementClient).restage(backingApps.get(1)); - - StepVerifier.create(backingAppManagementService.restage("foo-service-id", "service1", "plan1")) - .expectNext() - .expectNext() - .verifyComplete(); - - verify(targetService).addToBackingApplications(eq(backingApps), any(), eq("foo-service-id")); - verify(managementClient, times(2)).restage(any(BackingApplication.class)); - verifyNoMoreInteractions(appDeployer, targetService, managementClient); - } - - @Test - void restageApplicationsWithEmptyApplications() { - BackingApplications emptyBackingApps = BackingApplications.builder().build(); - - BrokeredServices brokeredServicesNoApps = BrokeredServices - .builder() - .service(BrokeredService - .builder() - .serviceName("service1") - .planName("plan1") - .apps(emptyBackingApps) - .build()) - .build(); - - this.backingAppManagementService = new BackingAppManagementService(managementClient, appDeployer, - brokeredServicesNoApps, - targetService); - - given(targetService.addToBackingApplications(eq(emptyBackingApps), any(), eq("foo-service-id"))) - .willReturn(Mono.just(emptyBackingApps)); - - StepVerifier.create(backingAppManagementService.restage("foo-service-id", "service1", "plan1")) - .verifyComplete(); - - verify(targetService).addToBackingApplications(eq(emptyBackingApps), any(), eq("foo-service-id")); - verifyNoInteractions(managementClient); - verifyNoMoreInteractions(appDeployer, targetService, managementClient); - } - -} diff --git a/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/manager/BackingAppManagementServiceWithServiceInstanceIdTests.java b/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/manager/BackingAppManagementServiceWithServiceInstanceIdTests.java new file mode 100644 index 0000000..181e93f --- /dev/null +++ b/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/manager/BackingAppManagementServiceWithServiceInstanceIdTests.java @@ -0,0 +1,273 @@ +/* + * Copyright 2016-2020 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.cloud.appbroker.manager; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +import org.springframework.cloud.appbroker.deployer.BackingApplication; +import org.springframework.cloud.appbroker.deployer.BackingApplications; +import org.springframework.cloud.appbroker.deployer.BrokeredService; +import org.springframework.cloud.appbroker.deployer.BrokeredServices; +import org.springframework.cloud.appbroker.deployer.ServicesSpec; +import org.springframework.cloud.appbroker.deployer.deployer.AppDeployer; +import org.springframework.cloud.appbroker.deployer.deployer.GetApplicationRequest; +import org.springframework.cloud.appbroker.deployer.deployer.GetApplicationResponse; +import org.springframework.cloud.appbroker.extensions.targets.TargetService; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.BDDMockito.given; +import static org.mockito.BDDMockito.then; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; + +@ExtendWith(MockitoExtension.class) +class BackingAppManagementServiceWithServiceInstanceIdTests { + + private BackingAppManagementService backingAppManagementService; + + private BackingApplications backingApps; + + @Mock + private ManagementClient managementClient; + + @Mock + private AppDeployer appDeployer; + + @Mock + private TargetService targetService; + + @BeforeEach + void setUp() { + this.backingApps = BackingApplications.builder() + .backingApplication(BackingApplication.builder().name("testApp1").path("https://myfiles/app1.jar").build()) + .backingApplication(BackingApplication.builder().name("testApp2").path("https://myfiles/app2.jar").build()) + .build(); + + BrokeredServices brokeredServices = BrokeredServices.builder() + .service(BrokeredService.builder().serviceName("service1").planName("plan1").apps(this.backingApps).build()) + .build(); + + this.backingAppManagementService = new BackingAppManagementService(this.managementClient, this.appDeployer, + brokeredServices, this.targetService); + } + + @Test + void stopApplications() { + doReturn(Mono.empty()).when(this.managementClient).stop(this.backingApps.get(0)); + doReturn(Mono.empty()).when(this.managementClient).stop(this.backingApps.get(1)); + + given(this.targetService.addToBackingApplications(eq(this.backingApps), any(), eq("foo-service-id"))) + .willReturn(Mono.just(this.backingApps)); + + StepVerifier.create(this.backingAppManagementService.stop("foo-service-id", "service1", "plan1")) + .expectNext() + .expectNext() + .verifyComplete(); + + verify(this.targetService).addToBackingApplications(eq(this.backingApps), any(), eq("foo-service-id")); + verify(this.managementClient, times(2)).stop(any(BackingApplication.class)); + verifyNoMoreInteractions(this.appDeployer, this.targetService, this.managementClient); + } + + @Test + void stopApplicationsWithEmptyApplications() { + BackingApplications emptyBackingApps = BackingApplications.builder().build(); + + BrokeredServices brokeredServicesNoApps = BrokeredServices.builder() + .service(BrokeredService.builder().serviceName("service1").planName("plan1").apps(emptyBackingApps).build()) + .build(); + + this.backingAppManagementService = new BackingAppManagementService(this.managementClient, this.appDeployer, + brokeredServicesNoApps, this.targetService); + + given(this.targetService.addToBackingApplications(eq(emptyBackingApps), any(), eq("foo-service-id"))) + .willReturn(Mono.just(emptyBackingApps)); + + StepVerifier.create(this.backingAppManagementService.stop("foo-service-id", "service1", "plan1")) + .verifyComplete(); + + verify(this.targetService).addToBackingApplications(eq(emptyBackingApps), any(), eq("foo-service-id")); + verifyNoInteractions(this.managementClient); + verifyNoMoreInteractions(this.appDeployer, this.targetService, this.managementClient); + } + + @Test + void startApplications() { + given(this.targetService.addToBackingApplications(eq(this.backingApps), any(), eq("foo-service-id"))) + .willReturn(Mono.just(this.backingApps)); + + doReturn(Mono.empty()).when(this.managementClient).start(this.backingApps.get(0)); + doReturn(Mono.empty()).when(this.managementClient).start(this.backingApps.get(1)); + + StepVerifier.create(this.backingAppManagementService.start("foo-service-id", "service1", "plan1")) + .expectNext() + .expectNext() + .verifyComplete(); + + verify(this.targetService).addToBackingApplications(eq(this.backingApps), any(), eq("foo-service-id")); + verify(this.managementClient, times(2)).start(any(BackingApplication.class)); + verifyNoMoreInteractions(this.appDeployer, this.targetService, this.managementClient); + } + + @Test + void startApplicationsWithEmptyApplications() { + BackingApplications emptyBackingApps = BackingApplications.builder().build(); + + BrokeredServices brokeredServicesNoApps = BrokeredServices.builder() + .service(BrokeredService.builder().serviceName("service1").planName("plan1").apps(emptyBackingApps).build()) + .build(); + + this.backingAppManagementService = new BackingAppManagementService(this.managementClient, this.appDeployer, + brokeredServicesNoApps, this.targetService); + + given(this.targetService.addToBackingApplications(eq(emptyBackingApps), any(), eq("foo-service-id"))) + .willReturn(Mono.just(emptyBackingApps)); + + StepVerifier.create(this.backingAppManagementService.start("foo-service-id", "service1", "plan1")) + .verifyComplete(); + + verify(this.targetService).addToBackingApplications(eq(emptyBackingApps), any(), eq("foo-service-id")); + verifyNoInteractions(this.managementClient); + verifyNoMoreInteractions(this.appDeployer, this.targetService, this.managementClient); + } + + @Test + void restartApplications() { + given(this.targetService.addToBackingApplications(eq(this.backingApps), any(), eq("foo-service-id"))) + .willReturn(Mono.just(this.backingApps)); + + doReturn(Mono.empty()).when(this.managementClient).restart(this.backingApps.get(0)); + doReturn(Mono.empty()).when(this.managementClient).restart(this.backingApps.get(1)); + + StepVerifier.create(this.backingAppManagementService.restart("foo-service-id", "service1", "plan1")) + .expectNext() + .expectNext() + .verifyComplete(); + + verify(this.targetService).addToBackingApplications(eq(this.backingApps), any(), eq("foo-service-id")); + verify(this.managementClient, times(2)).restart(any(BackingApplication.class)); + verifyNoMoreInteractions(this.appDeployer, this.targetService, this.managementClient); + } + + @Test + void restartApplicationsWithEmptyApplications() { + BackingApplications emptyBackingApps = BackingApplications.builder().build(); + + BrokeredServices brokeredServicesNoApps = BrokeredServices.builder() + .service(BrokeredService.builder().serviceName("service1").planName("plan1").apps(emptyBackingApps).build()) + .build(); + + this.backingAppManagementService = new BackingAppManagementService(this.managementClient, this.appDeployer, + brokeredServicesNoApps, this.targetService); + + given(this.targetService.addToBackingApplications(eq(emptyBackingApps), any(), eq("foo-service-id"))) + .willReturn(Mono.just(emptyBackingApps)); + + StepVerifier.create(this.backingAppManagementService.restart("foo-service-id", "service1", "plan1")) + .verifyComplete(); + + verify(this.targetService).addToBackingApplications(eq(emptyBackingApps), any(), eq("foo-service-id")); + verifyNoInteractions(this.managementClient); + verifyNoMoreInteractions(this.appDeployer, this.targetService, this.managementClient); + } + + @Test + @SuppressWarnings("unchecked") + void getDeployedBackingApplications() { + given(this.appDeployer.get(any(GetApplicationRequest.class))).willReturn(Mono + .just(GetApplicationResponse.builder().name("testApp1").service("service1").service("service2").build()), + Mono.just(GetApplicationResponse.builder().name("testApp2").service("service3").build())); + + given(this.targetService.addToBackingApplications(eq(this.backingApps), any(), eq("foo-service-id"))) + .willReturn(Mono.just(this.backingApps)); + + StepVerifier + .create(this.backingAppManagementService.getDeployedBackingApplications("foo-service-id", "service1", + "plan1")) + .expectNext(BackingApplications.builder() + .backingApplication(BackingApplication.builder() + .name("testApp1") + .services(ServicesSpec.builder().serviceInstanceName("service1").build(), + ServicesSpec.builder().serviceInstanceName("service2").build()) + .build()) + .backingApplication(BackingApplication.builder() + .name("testApp2") + .services(ServicesSpec.builder().serviceInstanceName("service3").build()) + .build()) + .build()) + .verifyComplete(); + + then(this.targetService).should().addToBackingApplications(eq(this.backingApps), any(), eq("foo-service-id")); + then(this.appDeployer).should().get(argThat((req) -> "testApp1".equals(req.getName()))); + then(this.appDeployer).should().get(argThat((req) -> "testApp2".equals(req.getName()))); + + verifyNoInteractions(this.managementClient); + verifyNoMoreInteractions(this.appDeployer, this.targetService, this.managementClient); + } + + @Test + void restageApplications() { + given(this.targetService.addToBackingApplications(eq(this.backingApps), any(), eq("foo-service-id"))) + .willReturn(Mono.just(this.backingApps)); + + doReturn(Mono.empty()).when(this.managementClient).restage(this.backingApps.get(0)); + doReturn(Mono.empty()).when(this.managementClient).restage(this.backingApps.get(1)); + + StepVerifier.create(this.backingAppManagementService.restage("foo-service-id", "service1", "plan1")) + .expectNext() + .expectNext() + .verifyComplete(); + + verify(this.targetService).addToBackingApplications(eq(this.backingApps), any(), eq("foo-service-id")); + verify(this.managementClient, times(2)).restage(any(BackingApplication.class)); + verifyNoMoreInteractions(this.appDeployer, this.targetService, this.managementClient); + } + + @Test + void restageApplicationsWithEmptyApplications() { + BackingApplications emptyBackingApps = BackingApplications.builder().build(); + + BrokeredServices brokeredServicesNoApps = BrokeredServices.builder() + .service(BrokeredService.builder().serviceName("service1").planName("plan1").apps(emptyBackingApps).build()) + .build(); + + this.backingAppManagementService = new BackingAppManagementService(this.managementClient, this.appDeployer, + brokeredServicesNoApps, this.targetService); + + given(this.targetService.addToBackingApplications(eq(emptyBackingApps), any(), eq("foo-service-id"))) + .willReturn(Mono.just(emptyBackingApps)); + + StepVerifier.create(this.backingAppManagementService.restage("foo-service-id", "service1", "plan1")) + .verifyComplete(); + + verify(this.targetService).addToBackingApplications(eq(emptyBackingApps), any(), eq("foo-service-id")); + verifyNoInteractions(this.managementClient); + verifyNoMoreInteractions(this.appDeployer, this.targetService, this.managementClient); + } + +} diff --git a/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/manager/ManagementClientTest.java b/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/manager/ManagementClientTest.java deleted file mode 100644 index fc91a2d..0000000 --- a/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/manager/ManagementClientTest.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * Copyright 2002-2020 the original author or authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.appbroker.manager; - -import java.util.Collections; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; -import reactor.core.publisher.Mono; -import reactor.test.StepVerifier; - -import org.springframework.cloud.appbroker.deployer.BackingApplication; -import org.springframework.cloud.appbroker.deployer.manager.AppManager; -import org.springframework.cloud.appbroker.deployer.manager.RestageApplicationRequest; -import org.springframework.cloud.appbroker.deployer.manager.RestartApplicationRequest; -import org.springframework.cloud.appbroker.deployer.manager.StartApplicationRequest; -import org.springframework.cloud.appbroker.deployer.manager.StopApplicationRequest; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.argThat; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.verifyNoMoreInteractions; - -@ExtendWith(MockitoExtension.class) -class ManagementClientTest { - - private ManagementClient managementClient; - - @Mock - private AppManager appManager; - - private BackingApplication backingApplication; - - @BeforeEach - void setUp() { - this.managementClient = new ManagementClient(appManager); - - this.backingApplication = BackingApplication.builder() - .name("foo-app") - .property("foo", "bar") - .build(); - } - - @Test - void startApplication() { - given(appManager.start(any(StartApplicationRequest.class))) - .willReturn(Mono.empty()); - - StepVerifier.create(managementClient.start(backingApplication)) - .verifyComplete(); - - verify(appManager).start(argThat(request -> "foo-app".equals(request.getName()) && - Collections.singletonMap("foo", "bar").equals(request.getProperties()))); - verifyNoMoreInteractions(appManager); - } - - @Test - void startNullApplication() { - StepVerifier.create(managementClient.start(null)) - .verifyComplete(); - - verifyNoInteractions(appManager); - } - - @Test - void stopApplication() { - given(appManager.stop(any(StopApplicationRequest.class))) - .willReturn(Mono.empty()); - - StepVerifier.create(managementClient.stop(backingApplication)) - .verifyComplete(); - - verify(appManager).stop(argThat(request -> "foo-app".equals(request.getName()) && - Collections.singletonMap("foo", "bar").equals(request.getProperties()))); - verifyNoMoreInteractions(appManager); - } - - @Test - void stopNullApplication() { - StepVerifier.create(managementClient.stop(null)) - .verifyComplete(); - - verifyNoInteractions(appManager); - } - - @Test - void restartApplication() { - given(appManager.restart(any(RestartApplicationRequest.class))) - .willReturn(Mono.empty()); - - StepVerifier.create(managementClient.restart(backingApplication)) - .verifyComplete(); - - verify(appManager).restart(argThat(request -> "foo-app".equals(request.getName()) && - Collections.singletonMap("foo", "bar").equals(request.getProperties()))); - verifyNoMoreInteractions(appManager); - } - - @Test - void restartNullApplication() { - StepVerifier.create(managementClient.restart(null)) - .verifyComplete(); - - verifyNoInteractions(appManager); - } - - @Test - void restageApplication() { - given(appManager.restage(any(RestageApplicationRequest.class))) - .willReturn(Mono.empty()); - - StepVerifier.create(managementClient.restage(backingApplication)) - .verifyComplete(); - - verify(appManager).restage(argThat(request -> "foo-app".equals(request.getName()) && - Collections.singletonMap("foo", "bar").equals(request.getProperties()))); - verifyNoMoreInteractions(appManager); - } - - @Test - void restageNullApplication() { - StepVerifier.create(managementClient.restage(null)) - .verifyComplete(); - - verifyNoInteractions(appManager); - } - -} diff --git a/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/manager/ManagementClientTests.java b/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/manager/ManagementClientTests.java new file mode 100644 index 0000000..b9cb7be --- /dev/null +++ b/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/manager/ManagementClientTests.java @@ -0,0 +1,132 @@ +/* + * Copyright 2016-2020 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.cloud.appbroker.manager; + +import java.util.Collections; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +import org.springframework.cloud.appbroker.deployer.BackingApplication; +import org.springframework.cloud.appbroker.deployer.manager.AppManager; +import org.springframework.cloud.appbroker.deployer.manager.RestageApplicationRequest; +import org.springframework.cloud.appbroker.deployer.manager.RestartApplicationRequest; +import org.springframework.cloud.appbroker.deployer.manager.StartApplicationRequest; +import org.springframework.cloud.appbroker.deployer.manager.StopApplicationRequest; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; + +@ExtendWith(MockitoExtension.class) +class ManagementClientTests { + + private ManagementClient managementClient; + + @Mock + private AppManager appManager; + + private BackingApplication backingApplication; + + @BeforeEach + void setUp() { + this.managementClient = new ManagementClient(this.appManager); + + this.backingApplication = BackingApplication.builder().name("foo-app").property("foo", "bar").build(); + } + + @Test + void startApplication() { + given(this.appManager.start(any(StartApplicationRequest.class))).willReturn(Mono.empty()); + + StepVerifier.create(this.managementClient.start(this.backingApplication)).verifyComplete(); + + verify(this.appManager).start(argThat((request) -> "foo-app".equals(request.getName()) + && Collections.singletonMap("foo", "bar").equals(request.getProperties()))); + verifyNoMoreInteractions(this.appManager); + } + + @Test + void startNullApplication() { + StepVerifier.create(this.managementClient.start(null)).verifyComplete(); + + verifyNoInteractions(this.appManager); + } + + @Test + void stopApplication() { + given(this.appManager.stop(any(StopApplicationRequest.class))).willReturn(Mono.empty()); + + StepVerifier.create(this.managementClient.stop(this.backingApplication)).verifyComplete(); + + verify(this.appManager).stop(argThat((request) -> "foo-app".equals(request.getName()) + && Collections.singletonMap("foo", "bar").equals(request.getProperties()))); + verifyNoMoreInteractions(this.appManager); + } + + @Test + void stopNullApplication() { + StepVerifier.create(this.managementClient.stop(null)).verifyComplete(); + + verifyNoInteractions(this.appManager); + } + + @Test + void restartApplication() { + given(this.appManager.restart(any(RestartApplicationRequest.class))).willReturn(Mono.empty()); + + StepVerifier.create(this.managementClient.restart(this.backingApplication)).verifyComplete(); + + verify(this.appManager).restart(argThat((request) -> "foo-app".equals(request.getName()) + && Collections.singletonMap("foo", "bar").equals(request.getProperties()))); + verifyNoMoreInteractions(this.appManager); + } + + @Test + void restartNullApplication() { + StepVerifier.create(this.managementClient.restart(null)).verifyComplete(); + + verifyNoInteractions(this.appManager); + } + + @Test + void restageApplication() { + given(this.appManager.restage(any(RestageApplicationRequest.class))).willReturn(Mono.empty()); + + StepVerifier.create(this.managementClient.restage(this.backingApplication)).verifyComplete(); + + verify(this.appManager).restage(argThat((request) -> "foo-app".equals(request.getName()) + && Collections.singletonMap("foo", "bar").equals(request.getProperties()))); + verifyNoMoreInteractions(this.appManager); + } + + @Test + void restageNullApplication() { + StepVerifier.create(this.managementClient.restage(null)).verifyComplete(); + + verifyNoInteractions(this.appManager); + } + +} diff --git a/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/service/WorkflowServiceInstanceBindingServiceTest.java b/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/service/WorkflowServiceInstanceBindingServiceTest.java deleted file mode 100644 index 405fd07..0000000 --- a/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/service/WorkflowServiceInstanceBindingServiceTest.java +++ /dev/null @@ -1,978 +0,0 @@ -/* - * Copyright 2002-2020 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.appbroker.service; - -import java.sql.Timestamp; -import java.time.Instant; -import java.util.Arrays; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.InOrder; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; -import reactor.test.StepVerifier; -import reactor.test.publisher.TestPublisher; - -import org.springframework.cloud.appbroker.state.ServiceInstanceBindingStateRepository; -import org.springframework.cloud.appbroker.state.ServiceInstanceState; -import org.springframework.cloud.servicebroker.exception.ServiceBrokerException; -import org.springframework.cloud.servicebroker.model.binding.BindResource; -import org.springframework.cloud.servicebroker.model.binding.CreateServiceInstanceAppBindingResponse; -import org.springframework.cloud.servicebroker.model.binding.CreateServiceInstanceAppBindingResponse.CreateServiceInstanceAppBindingResponseBuilder; -import org.springframework.cloud.servicebroker.model.binding.CreateServiceInstanceBindingRequest; -import org.springframework.cloud.servicebroker.model.binding.CreateServiceInstanceRouteBindingResponse; -import org.springframework.cloud.servicebroker.model.binding.CreateServiceInstanceRouteBindingResponse.CreateServiceInstanceRouteBindingResponseBuilder; -import org.springframework.cloud.servicebroker.model.binding.DeleteServiceInstanceBindingRequest; -import org.springframework.cloud.servicebroker.model.binding.DeleteServiceInstanceBindingResponse; -import org.springframework.cloud.servicebroker.model.binding.DeleteServiceInstanceBindingResponse.DeleteServiceInstanceBindingResponseBuilder; -import org.springframework.cloud.servicebroker.model.instance.OperationState; -import org.springframework.core.Ordered; -import org.springframework.core.annotation.Order; -import org.springframework.test.util.ReflectionTestUtils; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.data.MapEntry.entry; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.BDDMockito.given; -import static org.mockito.BDDMockito.then; -import static org.mockito.Mockito.inOrder; - -@ExtendWith(MockitoExtension.class) -class WorkflowServiceInstanceBindingServiceTest { - - @Mock - private ServiceInstanceBindingStateRepository stateRepository; - - @Mock - private LowOrderCreateServiceInstanceAppBindingWorkflow createServiceInstanceAppBindingWorkflow1; - - @Mock - private HighOrderCreateServiceAppBindingInstanceWorkflow createServiceInstanceAppBindingWorkflow2; - - @Mock - private LowOrderCreateServiceInstanceRouteBindingWorkflow createServiceInstanceRouteBindingWorkflow1; - - @Mock - private HighOrderCreateServiceRouteBindingInstanceWorkflow createServiceInstanceRouteBindingWorkflow2; - - @Mock - private LowOrderDeleteServiceInstanceBindingWorkflow deleteServiceInstanceBindingWorkflow1; - - @Mock - private HighOrderDeleteServiceInstanceBindingWorkflow deleteServiceInstanceBindingWorkflow2; - - private WorkflowServiceInstanceBindingService workflowServiceInstanceBindingService; - - @BeforeEach - void setUp() { - this.workflowServiceInstanceBindingService = new WorkflowServiceInstanceBindingService(stateRepository, - Arrays.asList(createServiceInstanceAppBindingWorkflow1, createServiceInstanceAppBindingWorkflow2), - Arrays.asList(createServiceInstanceRouteBindingWorkflow1, createServiceInstanceRouteBindingWorkflow2), - Arrays.asList(deleteServiceInstanceBindingWorkflow1, deleteServiceInstanceBindingWorkflow2)); - } - - @Test - void createServiceInstanceAppBindingWithNoWorkflows() { - given(stateRepository.saveState(anyString(), anyString(), any(OperationState.class), anyString())) - .willReturn(Mono.just( - new ServiceInstanceState(OperationState.IN_PROGRESS, "create service instance binding started", - new Timestamp(Instant.now().minusSeconds(60).toEpochMilli())))) - .willReturn(Mono.just( - new ServiceInstanceState(OperationState.SUCCEEDED, "create service instance binding completed", - new Timestamp(Instant.now().minusSeconds(30).toEpochMilli())))); - - this.workflowServiceInstanceBindingService = new WorkflowServiceInstanceBindingService( - this.stateRepository, null, null, null); - - CreateServiceInstanceBindingRequest request = CreateServiceInstanceBindingRequest.builder() - .serviceInstanceId("foo-service") - .bindingId("foo-binding") - .bindResource(BindResource.builder() - .appGuid("foo-guid") - .build()) - .build(); - - StepVerifier.create(workflowServiceInstanceBindingService.createServiceInstanceBinding(request)) - .assertNext(response -> { - InOrder repoOrder = inOrder(stateRepository); - repoOrder.verify(stateRepository) - .saveState(eq("foo-service"), eq("foo-binding"), eq(OperationState.IN_PROGRESS), - eq("create service instance binding started")); - repoOrder.verify(stateRepository) - .saveState(eq("foo-service"), eq("foo-binding"), eq(OperationState.SUCCEEDED), - eq("create service instance binding completed")); - repoOrder.verifyNoMoreInteractions(); - - assertThat(response).isNotNull(); - assertThat(response).isInstanceOf(CreateServiceInstanceAppBindingResponse.class); - }) - .verifyComplete(); - } - - @Test - void createServiceInstanceRouteBindingWithNoWorkflows() { - given(stateRepository.saveState(anyString(), anyString(), any(OperationState.class), anyString())) - .willReturn(Mono.just( - new ServiceInstanceState(OperationState.IN_PROGRESS, "create service instance binding started", - new Timestamp(Instant.now().minusSeconds(60).toEpochMilli())))) - .willReturn(Mono.just( - new ServiceInstanceState(OperationState.SUCCEEDED, "create service instance binding completed", - new Timestamp(Instant.now().minusSeconds(30).toEpochMilli())))); - - this.workflowServiceInstanceBindingService = new WorkflowServiceInstanceBindingService( - this.stateRepository, null, null, null); - - CreateServiceInstanceBindingRequest request = CreateServiceInstanceBindingRequest.builder() - .serviceInstanceId("foo-service") - .bindingId("foo-binding") - .bindResource(BindResource.builder() - .route("foo-route") - .build()) - .build(); - - StepVerifier.create(workflowServiceInstanceBindingService.createServiceInstanceBinding(request)) - .assertNext(response -> { - InOrder repoOrder = inOrder(stateRepository); - repoOrder.verify(stateRepository) - .saveState(eq("foo-service"), eq("foo-binding"), eq(OperationState.IN_PROGRESS), - eq("create service instance binding started")); - repoOrder.verify(stateRepository) - .saveState(eq("foo-service"), eq("foo-binding"), eq(OperationState.SUCCEEDED), - eq("create service instance binding completed")); - repoOrder.verifyNoMoreInteractions(); - - assertThat(response).isNotNull(); - assertThat(response).isInstanceOf(CreateServiceInstanceRouteBindingResponse.class); - }) - .verifyComplete(); - } - - @Test - void createServiceInstanceAppBinding() { - given(stateRepository.saveState(anyString(), anyString(), any(OperationState.class), anyString())) - .willReturn(Mono.just( - new ServiceInstanceState(OperationState.IN_PROGRESS, "create service instance binding started", - new Timestamp(Instant.now().minusSeconds(60).toEpochMilli())))) - .willReturn(Mono.just( - new ServiceInstanceState(OperationState.SUCCEEDED, "create service instance binding completed", - new Timestamp(Instant.now().minusSeconds(30).toEpochMilli())))); - - CreateServiceInstanceBindingRequest request = CreateServiceInstanceBindingRequest.builder() - .serviceInstanceId("foo-service") - .bindingId("foo-binding") - .bindResource(BindResource.builder() - .appGuid("foo-guid") - .build()) - .build(); - - CreateServiceInstanceAppBindingResponseBuilder responseBuilder = CreateServiceInstanceAppBindingResponse - .builder(); - CreateServiceInstanceAppBindingResponse builtResponse = CreateServiceInstanceAppBindingResponse.builder() - .async(true) - .credentials("foo", "bar") - .operation("working2") - .build(); - - TestPublisher lowerOrderFlow = TestPublisher.create(); - TestPublisher higherOrderFlow = TestPublisher.create(); - - given(createServiceInstanceAppBindingWorkflow1.accept(request)) - .willReturn(Mono.just(true)); - given(createServiceInstanceAppBindingWorkflow1.create(eq(request), eq(builtResponse))) - .willReturn(lowerOrderFlow.mono()); - given(createServiceInstanceAppBindingWorkflow1 - .buildResponse(eq(request), any(CreateServiceInstanceAppBindingResponseBuilder.class))) - .willReturn(Mono.just(responseBuilder - .async(true) - .operation("working1"))); - - given(createServiceInstanceAppBindingWorkflow2.accept(request)) - .willReturn(Mono.just(true)); - given(createServiceInstanceAppBindingWorkflow2.create(eq(request), eq(builtResponse))) - .willReturn(higherOrderFlow.mono()); - given(createServiceInstanceAppBindingWorkflow2 - .buildResponse(eq(request), any(CreateServiceInstanceAppBindingResponseBuilder.class))) - .willReturn(Mono.just(responseBuilder - .credentials("foo", "bar") - .operation("working2"))); - - StepVerifier.create(workflowServiceInstanceBindingService.createServiceInstanceBinding(request)) - .assertNext(response -> { - InOrder repoOrder = inOrder(stateRepository); - repoOrder.verify(stateRepository) - .saveState(eq("foo-service"), eq("foo-binding"), eq(OperationState.IN_PROGRESS), - eq("create service instance binding started")); - repoOrder.verify(stateRepository) - .saveState(eq("foo-service"), eq("foo-binding"), eq(OperationState.SUCCEEDED), - eq("create service instance binding completed")); - repoOrder.verifyNoMoreInteractions(); - - lowerOrderFlow.complete(); - lowerOrderFlow.assertWasNotRequested(); - - higherOrderFlow.complete(); - lowerOrderFlow.assertWasRequested(); - - InOrder createOrder = inOrder(createServiceInstanceAppBindingWorkflow1, - createServiceInstanceAppBindingWorkflow2); - createOrder.verify(createServiceInstanceAppBindingWorkflow2).buildResponse(eq(request), - any(CreateServiceInstanceAppBindingResponseBuilder.class)); - createOrder.verify(createServiceInstanceAppBindingWorkflow1).buildResponse(eq(request), - any(CreateServiceInstanceAppBindingResponseBuilder.class)); - createOrder.verify(createServiceInstanceAppBindingWorkflow2).create(request, responseBuilder.build()); - createOrder.verify(createServiceInstanceAppBindingWorkflow1).create(request, responseBuilder.build()); - createOrder.verifyNoMoreInteractions(); - - CreateServiceInstanceAppBindingResponse r = (CreateServiceInstanceAppBindingResponse) response; - - assertThat(r).isNotNull(); - assertThat(r.getCredentials()).containsOnly(entry("foo", "bar")); - assertThat(r.isAsync()).isTrue(); - assertThat(r.getOperation()).isEqualTo("working2"); - }) - .verifyComplete(); - } - - @Test - void appBindingBuildResponseAppliesFlowsSequentially() { - CreateServiceInstanceBindingRequest request = CreateServiceInstanceBindingRequest - .builder() - .serviceInstanceId("foo-service") - .bindingId("foo-binding") - .bindResource(BindResource.builder() - .appGuid("foo-guid") - .build()) - .build(); - - CreateServiceInstanceAppBindingResponseBuilder builder = CreateServiceInstanceAppBindingResponse.builder(); - - TestPublisher response1 = TestPublisher.create(); - TestPublisher response2 = TestPublisher.create(); - - CreateServiceInstanceAppBindingWorkflow flow1 = new CreateServiceInstanceAppBindingWorkflow() { - @Override - public Mono buildResponse( - CreateServiceInstanceBindingRequest request, - CreateServiceInstanceAppBindingResponseBuilder responseBuilder) { - return response1.mono(); - } - }; - - CreateServiceInstanceAppBindingWorkflow flow2 = new CreateServiceInstanceAppBindingWorkflow() { - @Override - public Mono buildResponse( - CreateServiceInstanceBindingRequest request, - CreateServiceInstanceAppBindingResponseBuilder responseBuilder) { - return response2.mono(); - } - }; - - Flux buildAppResponse = - ReflectionTestUtils.invokeMethod(workflowServiceInstanceBindingService, "invokeAppBindingBuildResponse", - builder, request, Arrays.asList(flow1, flow2)); - - StepVerifier.create(buildAppResponse) - .then(() -> response1.next(builder)) - .then(() -> response2.next(builder)) - .assertNext(r -> response2.assertWasNotRequested()) - .then(response1::complete) - .assertNext(r -> response2.assertWasRequested()) - .then(response2::complete) - .verifyComplete(); - } - - @Test - void routeBindingBuildResponseAppliesFlowsSequentially() { - CreateServiceInstanceBindingRequest request = CreateServiceInstanceBindingRequest - .builder() - .serviceInstanceId("foo-service") - .bindingId("foo-binding") - .bindResource(BindResource.builder() - .appGuid("foo-guid") - .build()) - .build(); - - CreateServiceInstanceRouteBindingResponseBuilder builder = CreateServiceInstanceRouteBindingResponse.builder(); - - TestPublisher response1 = TestPublisher.create(); - TestPublisher response2 = TestPublisher.create(); - - CreateServiceInstanceRouteBindingWorkflow flow1 = new CreateServiceInstanceRouteBindingWorkflow() { - @Override - public Mono buildResponse( - CreateServiceInstanceBindingRequest request, - CreateServiceInstanceRouteBindingResponseBuilder responseBuilder) { - return response1.mono(); - } - }; - - CreateServiceInstanceRouteBindingWorkflow flow2 = new CreateServiceInstanceRouteBindingWorkflow() { - @Override - public Mono buildResponse( - CreateServiceInstanceBindingRequest request, - CreateServiceInstanceRouteBindingResponseBuilder responseBuilder) { - return response2.mono(); - } - }; - - Flux buildRouteResponse = - ReflectionTestUtils.invokeMethod(workflowServiceInstanceBindingService, "invokeRouteBindingBuildResponse" - , builder, request, Arrays.asList(flow1, flow2)); - - StepVerifier.create(buildRouteResponse) - .then(() -> response1.next(builder)) - .then(() -> response2.next(builder)) - .assertNext(r -> response2.assertWasNotRequested()) - .then(response1::complete) - .assertNext(r -> response2.assertWasRequested()) - .then(response2::complete) - .verifyComplete(); - } - - @Test - void createServiceInstanceRouteBinding() { - given(stateRepository.saveState(anyString(), anyString(), any(OperationState.class), anyString())) - .willReturn(Mono.just( - new ServiceInstanceState(OperationState.IN_PROGRESS, "create service instance binding started", - new Timestamp(Instant.now().minusSeconds(60).toEpochMilli())))) - .willReturn(Mono.just( - new ServiceInstanceState(OperationState.SUCCEEDED, "create service instance binding completed", - new Timestamp(Instant.now().minusSeconds(30).toEpochMilli())))); - - CreateServiceInstanceBindingRequest request = CreateServiceInstanceBindingRequest.builder() - .serviceInstanceId("foo-service") - .bindingId("foo-binding") - .bindResource(BindResource.builder() - .route("foo-route") - .build()) - .build(); - - CreateServiceInstanceRouteBindingResponseBuilder responseBuilder = CreateServiceInstanceRouteBindingResponse - .builder(); - CreateServiceInstanceRouteBindingResponse builtResponse = CreateServiceInstanceRouteBindingResponse.builder() - .async(true) - .routeServiceUrl("foo-url") - .operation("working2") - .build(); - - TestPublisher lowerOrderFlow = TestPublisher.create(); - TestPublisher higherOrderFlow = TestPublisher.create(); - - given(createServiceInstanceRouteBindingWorkflow1.accept(request)) - .willReturn(Mono.just(true)); - given(createServiceInstanceRouteBindingWorkflow1.create(eq(request), eq(builtResponse))) - .willReturn(lowerOrderFlow.mono()); - given(createServiceInstanceRouteBindingWorkflow1 - .buildResponse(eq(request), any(CreateServiceInstanceRouteBindingResponseBuilder.class))) - .willReturn(Mono.just(responseBuilder - .async(true) - .operation("working1"))); - - given(createServiceInstanceRouteBindingWorkflow2.accept(request)) - .willReturn(Mono.just(true)); - given(createServiceInstanceRouteBindingWorkflow2.create(eq(request), eq(builtResponse))) - .willReturn(higherOrderFlow.mono()); - given(createServiceInstanceRouteBindingWorkflow2 - .buildResponse(eq(request), any(CreateServiceInstanceRouteBindingResponseBuilder.class))) - .willReturn(Mono.just(responseBuilder - .routeServiceUrl("foo-url") - .operation("working2"))); - - StepVerifier.create(workflowServiceInstanceBindingService.createServiceInstanceBinding(request)) - .assertNext(response -> { - InOrder repoOrder = inOrder(stateRepository); - repoOrder.verify(stateRepository) - .saveState(eq("foo-service"), eq("foo-binding"), eq(OperationState.IN_PROGRESS), - eq("create service instance binding started")); - repoOrder.verify(stateRepository) - .saveState(eq("foo-service"), eq("foo-binding"), eq(OperationState.SUCCEEDED), - eq("create service instance binding completed")); - repoOrder.verifyNoMoreInteractions(); - - lowerOrderFlow.complete(); - lowerOrderFlow.assertWasNotRequested(); - - higherOrderFlow.complete(); - lowerOrderFlow.assertWasRequested(); - - InOrder createOrder = inOrder(createServiceInstanceRouteBindingWorkflow1, - createServiceInstanceRouteBindingWorkflow2); - createOrder.verify(createServiceInstanceRouteBindingWorkflow2).buildResponse(eq(request), - any(CreateServiceInstanceRouteBindingResponseBuilder.class)); - createOrder.verify(createServiceInstanceRouteBindingWorkflow1).buildResponse(eq(request), - any(CreateServiceInstanceRouteBindingResponseBuilder.class)); - createOrder.verify(createServiceInstanceRouteBindingWorkflow2).create(request, responseBuilder.build()); - createOrder.verify(createServiceInstanceRouteBindingWorkflow1).create(request, responseBuilder.build()); - createOrder.verifyNoMoreInteractions(); - - assertThat(response).isNotNull(); - assertThat(response).isInstanceOf(CreateServiceInstanceRouteBindingResponse.class); - assertThat(((CreateServiceInstanceRouteBindingResponse) response).getRouteServiceUrl()) - .isEqualTo("foo-url"); - assertThat(response.isAsync()).isTrue(); - assertThat(response.getOperation()).isEqualTo("working2"); - }) - .verifyComplete(); - } - - @Test - void createServiceInstanceAppBindingWithAsyncError() { - given(stateRepository.saveState(anyString(), anyString(), any(OperationState.class), anyString())) - .willReturn(Mono.just( - new ServiceInstanceState(OperationState.IN_PROGRESS, "create service instance binding started", - new Timestamp(Instant.now().minusSeconds(60).toEpochMilli())))) - .willReturn( - Mono.just(new ServiceInstanceState(OperationState.FAILED, "create service instance binding failed", - new Timestamp(Instant.now().minusSeconds(30).toEpochMilli())))); - - CreateServiceInstanceBindingRequest request = CreateServiceInstanceBindingRequest.builder() - .serviceInstanceId("foo-service") - .bindingId("foo-binding") - .bindResource(BindResource.builder() - .appGuid("foo-guid") - .build()) - .build(); - - CreateServiceInstanceAppBindingResponseBuilder responseBuilder = CreateServiceInstanceAppBindingResponse - .builder(); - - given(createServiceInstanceAppBindingWorkflow1.accept(request)) - .willReturn(Mono.just(true)); - given(createServiceInstanceAppBindingWorkflow1.create(request, responseBuilder.build())) - .willReturn(Mono.error(new RuntimeException("create foo error"))); - given(createServiceInstanceAppBindingWorkflow1 - .buildResponse(eq(request), any(CreateServiceInstanceAppBindingResponseBuilder.class))) - .willReturn(Mono.just(responseBuilder)); - - given(createServiceInstanceAppBindingWorkflow2.accept(request)) - .willReturn(Mono.just(true)); - given(createServiceInstanceAppBindingWorkflow2.create(request, responseBuilder.build())) - .willReturn(Mono.empty()); - given(createServiceInstanceAppBindingWorkflow2 - .buildResponse(eq(request), any(CreateServiceInstanceAppBindingResponseBuilder.class))) - .willReturn(Mono.just(responseBuilder)); - - StepVerifier.create(workflowServiceInstanceBindingService.createServiceInstanceBinding(request)) - .assertNext(response -> { - InOrder repoOrder = inOrder(stateRepository); - repoOrder.verify(stateRepository) - .saveState(eq("foo-service"), eq("foo-binding"), eq(OperationState.IN_PROGRESS), - eq("create service instance binding started")); - repoOrder.verify(stateRepository) - .saveState(eq("foo-service"), eq("foo-binding"), eq(OperationState.FAILED), eq("create foo error")); - repoOrder.verifyNoMoreInteractions(); - - InOrder createOrder = inOrder(createServiceInstanceAppBindingWorkflow1, - createServiceInstanceAppBindingWorkflow2); - createOrder.verify(createServiceInstanceAppBindingWorkflow2).buildResponse(eq(request), - any(CreateServiceInstanceAppBindingResponseBuilder.class)); - createOrder.verify(createServiceInstanceAppBindingWorkflow1).buildResponse(eq(request), - any(CreateServiceInstanceAppBindingResponseBuilder.class)); - createOrder.verify(createServiceInstanceAppBindingWorkflow2).create(request, responseBuilder.build()); - createOrder.verify(createServiceInstanceAppBindingWorkflow1).create(request, responseBuilder.build()); - createOrder.verifyNoMoreInteractions(); - - assertThat(response).isNotNull(); - assertThat(response).isInstanceOf(CreateServiceInstanceAppBindingResponse.class); - }) - .verifyComplete(); - } - - @Test - void createServiceInstanceRouteBindingWithAsyncError() { - given(stateRepository.saveState(anyString(), anyString(), any(OperationState.class), anyString())) - .willReturn(Mono.just( - new ServiceInstanceState(OperationState.IN_PROGRESS, "create service instance binding started", - new Timestamp(Instant.now().minusSeconds(60).toEpochMilli())))) - .willReturn( - Mono.just(new ServiceInstanceState(OperationState.FAILED, "create service instance binding failed", - new Timestamp(Instant.now().minusSeconds(30).toEpochMilli())))); - - CreateServiceInstanceBindingRequest request = CreateServiceInstanceBindingRequest.builder() - .serviceInstanceId("foo-service") - .bindingId("foo-binding") - .bindResource(BindResource.builder() - .route("foo-route") - .build()) - .build(); - - CreateServiceInstanceRouteBindingResponseBuilder responseBuilder = CreateServiceInstanceRouteBindingResponse - .builder(); - - given(createServiceInstanceRouteBindingWorkflow1.accept(request)) - .willReturn(Mono.just(true)); - given(createServiceInstanceRouteBindingWorkflow1.create(request, responseBuilder.build())) - .willReturn(Mono.error(new RuntimeException("create foo error"))); - given(createServiceInstanceRouteBindingWorkflow1 - .buildResponse(eq(request), any(CreateServiceInstanceRouteBindingResponseBuilder.class))) - .willReturn(Mono.just(responseBuilder)); - - given(createServiceInstanceRouteBindingWorkflow2.accept(request)) - .willReturn(Mono.just(true)); - given(createServiceInstanceRouteBindingWorkflow2.create(request, responseBuilder.build())) - .willReturn(Mono.empty()); - given(createServiceInstanceRouteBindingWorkflow2 - .buildResponse(eq(request), any(CreateServiceInstanceRouteBindingResponseBuilder.class))) - .willReturn(Mono.just(responseBuilder)); - - StepVerifier.create(workflowServiceInstanceBindingService.createServiceInstanceBinding(request)) - .assertNext(response -> { - InOrder repoOrder = inOrder(stateRepository); - repoOrder.verify(stateRepository) - .saveState(eq("foo-service"), eq("foo-binding"), eq(OperationState.IN_PROGRESS), - eq("create service instance binding started")); - repoOrder.verify(stateRepository) - .saveState(eq("foo-service"), eq("foo-binding"), eq(OperationState.FAILED), eq("create foo error")); - repoOrder.verifyNoMoreInteractions(); - - InOrder createOrder = inOrder(createServiceInstanceRouteBindingWorkflow1, - createServiceInstanceRouteBindingWorkflow2); - createOrder.verify(createServiceInstanceRouteBindingWorkflow2).buildResponse(eq(request), - any(CreateServiceInstanceRouteBindingResponseBuilder.class)); - createOrder.verify(createServiceInstanceRouteBindingWorkflow1).buildResponse(eq(request), - any(CreateServiceInstanceRouteBindingResponseBuilder.class)); - createOrder.verify(createServiceInstanceRouteBindingWorkflow2).create(request, responseBuilder.build()); - createOrder.verify(createServiceInstanceRouteBindingWorkflow1).create(request, responseBuilder.build()); - createOrder.verifyNoMoreInteractions(); - - assertThat(response).isNotNull(); - assertThat(response).isInstanceOf(CreateServiceInstanceRouteBindingResponse.class); - }) - .verifyComplete(); - } - - @Test - void createServiceInstanceAppBindingWithResponseError() { - CreateServiceInstanceBindingRequest request = CreateServiceInstanceBindingRequest.builder() - .serviceInstanceId("foo-id") - .bindResource(BindResource.builder() - .appGuid("foo-guid") - .build()) - .build(); - - CreateServiceInstanceAppBindingResponseBuilder responseBuilder = CreateServiceInstanceAppBindingResponse - .builder(); - - given(createServiceInstanceAppBindingWorkflow1.accept(request)) - .willReturn(Mono.just(true)); - given(createServiceInstanceAppBindingWorkflow1 - .buildResponse(eq(request), any(CreateServiceInstanceAppBindingResponseBuilder.class))) - .willReturn(Mono.error(new ServiceBrokerException("create foo error"))); - - given(createServiceInstanceAppBindingWorkflow2.accept(request)) - .willReturn(Mono.just(true)); - given(createServiceInstanceAppBindingWorkflow2 - .buildResponse(eq(request), any(CreateServiceInstanceAppBindingResponseBuilder.class))) - .willReturn(Mono.just(responseBuilder)); - - StepVerifier.create(workflowServiceInstanceBindingService.createServiceInstanceBinding(request)) - .expectErrorSatisfies(e -> assertThat(e) - .isInstanceOf(ServiceBrokerException.class) - .hasMessage("create foo error")) - .verify(); - } - - @Test - void createServiceInstanceRouteBindingWithResponseError() { - CreateServiceInstanceBindingRequest request = CreateServiceInstanceBindingRequest.builder() - .serviceInstanceId("foo-id") - .bindResource(BindResource.builder() - .route("foo-route") - .build()) - .build(); - - CreateServiceInstanceRouteBindingResponseBuilder responseBuilder = CreateServiceInstanceRouteBindingResponse - .builder(); - - given(createServiceInstanceRouteBindingWorkflow1.accept(request)) - .willReturn(Mono.just(true)); - given(createServiceInstanceRouteBindingWorkflow1 - .buildResponse(eq(request), any(CreateServiceInstanceRouteBindingResponseBuilder.class))) - .willReturn(Mono.error(new ServiceBrokerException("create foo error"))); - - given(createServiceInstanceRouteBindingWorkflow2.accept(request)) - .willReturn(Mono.just(true)); - given(createServiceInstanceRouteBindingWorkflow2 - .buildResponse(eq(request), any(CreateServiceInstanceRouteBindingResponseBuilder.class))) - .willReturn(Mono.just(responseBuilder)); - - StepVerifier.create(workflowServiceInstanceBindingService.createServiceInstanceBinding(request)) - .expectErrorSatisfies(e -> assertThat(e) - .isInstanceOf(ServiceBrokerException.class) - .hasMessage("create foo error")) - .verify(); - } - - @Test - void createServiceInstanceAppBindingWithNoAcceptsDoesNothing() { - given(stateRepository.saveState(anyString(), anyString(), any(OperationState.class), anyString())) - .willReturn( - Mono.just(new ServiceInstanceState(OperationState.IN_PROGRESS, "create service instance started", - new Timestamp(Instant.now().minusSeconds(60).toEpochMilli())))) - .willReturn( - Mono.just(new ServiceInstanceState(OperationState.SUCCEEDED, "create service instance completed", - new Timestamp(Instant.now().minusSeconds(30).toEpochMilli())))); - - CreateServiceInstanceBindingRequest request = CreateServiceInstanceBindingRequest.builder() - .serviceInstanceId("foo-service") - .bindingId("foo-binding") - .bindResource(BindResource.builder() - .appGuid("foo-guid") - .build()) - .build(); - - given(createServiceInstanceAppBindingWorkflow1.accept(request)) - .willReturn(Mono.just(false)); - - given(createServiceInstanceAppBindingWorkflow2.accept(request)) - .willReturn(Mono.just(false)); - - StepVerifier.create(workflowServiceInstanceBindingService.createServiceInstanceBinding(request)) - .assertNext(response -> { - InOrder repoOrder = inOrder(stateRepository); - repoOrder.verify(stateRepository) - .saveState(eq("foo-service"), eq("foo-binding"), eq(OperationState.IN_PROGRESS), - eq("create service instance binding started")); - repoOrder.verify(stateRepository) - .saveState(eq("foo-service"), eq("foo-binding"), eq(OperationState.SUCCEEDED), - eq("create service instance binding completed")); - repoOrder.verifyNoMoreInteractions(); - - then(createServiceInstanceAppBindingWorkflow1).shouldHaveNoMoreInteractions(); - then(createServiceInstanceAppBindingWorkflow2).shouldHaveNoMoreInteractions(); - - assertThat(response).isNotNull(); - assertThat(response).isInstanceOf(CreateServiceInstanceAppBindingResponse.class); - }) - .verifyComplete(); - } - - @Test - void createServiceInstanceRouteBindingWithNoAcceptsDoesNothing() { - given(stateRepository.saveState(anyString(), anyString(), any(OperationState.class), anyString())) - .willReturn( - Mono.just(new ServiceInstanceState(OperationState.IN_PROGRESS, "create service instance started", - new Timestamp(Instant.now().minusSeconds(60).toEpochMilli())))) - .willReturn( - Mono.just(new ServiceInstanceState(OperationState.SUCCEEDED, "create service instance completed", - new Timestamp(Instant.now().minusSeconds(30).toEpochMilli())))); - - CreateServiceInstanceBindingRequest request = CreateServiceInstanceBindingRequest.builder() - .serviceInstanceId("foo-service") - .bindingId("foo-binding") - .bindResource(BindResource.builder() - .route("foo-route") - .build()) - .build(); - - given(createServiceInstanceRouteBindingWorkflow1.accept(request)) - .willReturn(Mono.just(false)); - - given(createServiceInstanceRouteBindingWorkflow2.accept(request)) - .willReturn(Mono.just(false)); - - StepVerifier.create(workflowServiceInstanceBindingService.createServiceInstanceBinding(request)) - .assertNext(response -> { - InOrder repoOrder = inOrder(stateRepository); - repoOrder.verify(stateRepository) - .saveState(eq("foo-service"), eq("foo-binding"), eq(OperationState.IN_PROGRESS), - eq("create service instance binding started")); - repoOrder.verify(stateRepository) - .saveState(eq("foo-service"), eq("foo-binding"), eq(OperationState.SUCCEEDED), - eq("create service instance binding completed")); - repoOrder.verifyNoMoreInteractions(); - - then(createServiceInstanceRouteBindingWorkflow1).shouldHaveNoMoreInteractions(); - then(createServiceInstanceRouteBindingWorkflow2).shouldHaveNoMoreInteractions(); - - assertThat(response).isNotNull(); - assertThat(response).isInstanceOf(CreateServiceInstanceRouteBindingResponse.class); - }) - .verifyComplete(); - } - - @Test - void deleteServiceInstanceBindingsWithNoWorkflows() { - given(stateRepository.saveState(anyString(), anyString(), any(OperationState.class), anyString())) - .willReturn( - Mono.just(new ServiceInstanceState(OperationState.IN_PROGRESS, "delete service instance started", - new Timestamp(Instant.now().minusSeconds(60).toEpochMilli())))) - .willReturn( - Mono.just(new ServiceInstanceState(OperationState.SUCCEEDED, "delete service instance completed", - new Timestamp(Instant.now().minusSeconds(30).toEpochMilli())))); - - this.workflowServiceInstanceBindingService = new WorkflowServiceInstanceBindingService( - this.stateRepository, null, null, null); - - DeleteServiceInstanceBindingRequest request = DeleteServiceInstanceBindingRequest.builder() - .serviceInstanceId("foo-service") - .bindingId("foo-binding") - .build(); - - StepVerifier.create(workflowServiceInstanceBindingService.deleteServiceInstanceBinding(request)) - .assertNext(response -> { - InOrder repoOrder = inOrder(stateRepository); - repoOrder.verify(stateRepository) - .saveState(eq("foo-service"), eq("foo-binding"), eq(OperationState.IN_PROGRESS), - eq("delete service instance binding started")); - repoOrder.verify(stateRepository) - .saveState(eq("foo-service"), eq("foo-binding"), eq(OperationState.SUCCEEDED), - eq("delete service instance binding completed")); - repoOrder.verifyNoMoreInteractions(); - - assertThat(response).isNotNull(); - assertThat(response).isInstanceOf(DeleteServiceInstanceBindingResponse.class); - }) - .verifyComplete(); - } - - @Test - void deleteServiceInstanceBinding() { - given(stateRepository.saveState(anyString(), anyString(), any(OperationState.class), anyString())) - .willReturn(Mono.just( - new ServiceInstanceState(OperationState.IN_PROGRESS, "delete service instance binding started", - new Timestamp(Instant.now().minusSeconds(60).toEpochMilli())))) - .willReturn(Mono.just( - new ServiceInstanceState(OperationState.SUCCEEDED, "delete service instance binding completed", - new Timestamp(Instant.now().minusSeconds(30).toEpochMilli())))); - - DeleteServiceInstanceBindingRequest request = DeleteServiceInstanceBindingRequest.builder() - .serviceInstanceId("foo-service") - .bindingId("foo-binding") - .build(); - - DeleteServiceInstanceBindingResponseBuilder responseBuilder = DeleteServiceInstanceBindingResponse.builder(); - DeleteServiceInstanceBindingResponse builtResponse = DeleteServiceInstanceBindingResponse.builder() - .async(true) - .operation("working2") - .build(); - - TestPublisher lowerOrderFlow = TestPublisher.create(); - TestPublisher higherOrderFlow = TestPublisher.create(); - - given(deleteServiceInstanceBindingWorkflow1.accept(request)) - .willReturn(Mono.just(true)); - given(deleteServiceInstanceBindingWorkflow1.delete(eq(request), eq(builtResponse))) - .willReturn(lowerOrderFlow.mono()); - given(deleteServiceInstanceBindingWorkflow1 - .buildResponse(eq(request), any(DeleteServiceInstanceBindingResponseBuilder.class))) - .willReturn(Mono.just(responseBuilder - .async(true) - .operation("working1"))); - - given(deleteServiceInstanceBindingWorkflow2.accept(request)) - .willReturn(Mono.just(true)); - given(deleteServiceInstanceBindingWorkflow2.delete(eq(request), eq(builtResponse))) - .willReturn(higherOrderFlow.mono()); - given(deleteServiceInstanceBindingWorkflow2 - .buildResponse(eq(request), any(DeleteServiceInstanceBindingResponseBuilder.class))) - .willReturn(Mono.just(responseBuilder - .operation("working2"))); - - StepVerifier.create(workflowServiceInstanceBindingService.deleteServiceInstanceBinding(request)) - .assertNext(response -> { - InOrder repoOrder = inOrder(stateRepository); - repoOrder.verify(stateRepository) - .saveState(eq("foo-service"), eq("foo-binding"), eq(OperationState.IN_PROGRESS), - eq("delete service instance binding started")); - repoOrder.verify(stateRepository) - .saveState(eq("foo-service"), eq("foo-binding"), eq(OperationState.SUCCEEDED), - eq("delete service instance binding completed")); - repoOrder.verifyNoMoreInteractions(); - - lowerOrderFlow.complete(); - lowerOrderFlow.assertWasNotRequested(); - - higherOrderFlow.complete(); - lowerOrderFlow.assertWasRequested(); - - InOrder deleteOrder = inOrder(deleteServiceInstanceBindingWorkflow1, - deleteServiceInstanceBindingWorkflow2); - deleteOrder.verify(deleteServiceInstanceBindingWorkflow2).buildResponse(eq(request), - any(DeleteServiceInstanceBindingResponseBuilder.class)); - deleteOrder.verify(deleteServiceInstanceBindingWorkflow1).buildResponse(eq(request), - any(DeleteServiceInstanceBindingResponseBuilder.class)); - deleteOrder.verify(deleteServiceInstanceBindingWorkflow2).delete(request, responseBuilder.build()); - deleteOrder.verify(deleteServiceInstanceBindingWorkflow1).delete(request, responseBuilder.build()); - deleteOrder.verifyNoMoreInteractions(); - - assertThat(response).isNotNull(); - assertThat(response.isAsync()).isTrue(); - assertThat(response.getOperation()).isEqualTo("working2"); - }) - .verifyComplete(); - } - - @Test - void deleteServiceInstanceBindingWithAsyncError() { - given(stateRepository.saveState(anyString(), anyString(), any(OperationState.class), anyString())) - .willReturn( - Mono.just(new ServiceInstanceState(OperationState.IN_PROGRESS, "delete service instance started", - new Timestamp(Instant.now().minusSeconds(60).toEpochMilli())))) - .willReturn(Mono.just(new ServiceInstanceState(OperationState.FAILED, "delete service instance failed", - new Timestamp(Instant.now().minusSeconds(30).toEpochMilli())))); - - DeleteServiceInstanceBindingRequest request = DeleteServiceInstanceBindingRequest.builder() - .serviceInstanceId("foo-service") - .bindingId("foo-binding") - .build(); - - DeleteServiceInstanceBindingResponseBuilder responseBuilder = DeleteServiceInstanceBindingResponse.builder(); - - given(deleteServiceInstanceBindingWorkflow1.accept(request)) - .willReturn(Mono.just(true)); - given(deleteServiceInstanceBindingWorkflow1.delete(request, responseBuilder.build())) - .willReturn(Mono.error(new RuntimeException("delete foo binding error"))); - given(deleteServiceInstanceBindingWorkflow1 - .buildResponse(eq(request), any(DeleteServiceInstanceBindingResponseBuilder.class))) - .willReturn(Mono.just(responseBuilder)); - - given(deleteServiceInstanceBindingWorkflow2.accept(request)) - .willReturn(Mono.just(true)); - given(deleteServiceInstanceBindingWorkflow2.delete(request, responseBuilder.build())) - .willReturn(Mono.empty()); - given(deleteServiceInstanceBindingWorkflow2 - .buildResponse(eq(request), any(DeleteServiceInstanceBindingResponseBuilder.class))) - .willReturn(Mono.just(responseBuilder)); - - StepVerifier.create(workflowServiceInstanceBindingService.deleteServiceInstanceBinding(request)) - .assertNext(response -> { - InOrder repoOrder = inOrder(stateRepository); - repoOrder.verify(stateRepository) - .saveState(eq("foo-service"), eq("foo-binding"), eq(OperationState.IN_PROGRESS), - eq("delete service instance binding started")); - repoOrder.verify(stateRepository) - .saveState(eq("foo-service"), eq("foo-binding"), eq(OperationState.FAILED), - eq("delete foo binding error")); - repoOrder.verifyNoMoreInteractions(); - - InOrder deleteOrder = inOrder(deleteServiceInstanceBindingWorkflow1, - deleteServiceInstanceBindingWorkflow2); - deleteOrder.verify(deleteServiceInstanceBindingWorkflow2).buildResponse(eq(request), - any(DeleteServiceInstanceBindingResponseBuilder.class)); - deleteOrder.verify(deleteServiceInstanceBindingWorkflow1).buildResponse(eq(request), - any(DeleteServiceInstanceBindingResponseBuilder.class)); - deleteOrder.verify(deleteServiceInstanceBindingWorkflow2).delete(request, responseBuilder.build()); - deleteOrder.verify(deleteServiceInstanceBindingWorkflow1).delete(request, responseBuilder.build()); - deleteOrder.verifyNoMoreInteractions(); - - assertThat(response).isNotNull(); - }) - .verifyComplete(); - } - - @Test - void deleteServiceInstanceBindingWithResponseError() { - DeleteServiceInstanceBindingRequest request = DeleteServiceInstanceBindingRequest.builder() - .serviceInstanceId("foo") - .bindingId("bar") - .build(); - - DeleteServiceInstanceBindingResponseBuilder responseBuilder = DeleteServiceInstanceBindingResponse.builder(); - - given(deleteServiceInstanceBindingWorkflow1.accept(request)) - .willReturn(Mono.just(true)); - given(deleteServiceInstanceBindingWorkflow1 - .buildResponse(eq(request), any(DeleteServiceInstanceBindingResponseBuilder.class))) - .willReturn(Mono.error(new ServiceBrokerException("delete foo binding error"))); - - given(deleteServiceInstanceBindingWorkflow2.accept(request)) - .willReturn(Mono.just(true)); - given(deleteServiceInstanceBindingWorkflow2 - .buildResponse(eq(request), any(DeleteServiceInstanceBindingResponseBuilder.class))) - .willReturn(Mono.just(responseBuilder)); - - StepVerifier.create(workflowServiceInstanceBindingService.deleteServiceInstanceBinding(request)) - .expectErrorSatisfies(e -> assertThat(e) - .isInstanceOf(ServiceBrokerException.class) - .hasMessage("delete foo binding error")) - .verify(); - } - - @Test - void deleteServiceInstanceBindingWithNoAcceptsDoesNothing() { - given(stateRepository.saveState(anyString(), anyString(), any(OperationState.class), anyString())) - .willReturn(Mono.just( - new ServiceInstanceState(OperationState.IN_PROGRESS, "delete service instance binding started", - new Timestamp(Instant.now().minusSeconds(60).toEpochMilli())))) - .willReturn(Mono.just( - new ServiceInstanceState(OperationState.SUCCEEDED, "delete service instance binding completed", - new Timestamp(Instant.now().minusSeconds(30).toEpochMilli())))); - - DeleteServiceInstanceBindingRequest request = DeleteServiceInstanceBindingRequest.builder() - .serviceInstanceId("foo-service") - .bindingId("foo-binding") - .build(); - - given(deleteServiceInstanceBindingWorkflow1.accept(request)) - .willReturn(Mono.just(false)); - - given(deleteServiceInstanceBindingWorkflow2.accept(request)) - .willReturn(Mono.just(false)); - - StepVerifier.create(workflowServiceInstanceBindingService.deleteServiceInstanceBinding(request)) - .assertNext(response -> { - InOrder repoOrder = inOrder(stateRepository); - repoOrder.verify(stateRepository) - .saveState(eq("foo-service"), eq("foo-binding"), eq(OperationState.IN_PROGRESS), - eq("delete service instance binding started")); - repoOrder.verify(stateRepository) - .saveState(eq("foo-service"), eq("foo-binding"), eq(OperationState.SUCCEEDED), - eq("delete service instance binding completed")); - repoOrder.verifyNoMoreInteractions(); - - then(deleteServiceInstanceBindingWorkflow1).shouldHaveNoMoreInteractions(); - then(deleteServiceInstanceBindingWorkflow2).shouldHaveNoMoreInteractions(); - - assertThat(response).isNotNull(); - }) - .verifyComplete(); - } - - @Order(Ordered.HIGHEST_PRECEDENCE) - private interface HighOrderCreateServiceAppBindingInstanceWorkflow extends CreateServiceInstanceAppBindingWorkflow { - } - - @Order - private interface LowOrderCreateServiceInstanceAppBindingWorkflow extends CreateServiceInstanceAppBindingWorkflow { - } - - @Order(Ordered.HIGHEST_PRECEDENCE) - private interface HighOrderCreateServiceRouteBindingInstanceWorkflow - extends CreateServiceInstanceRouteBindingWorkflow { - } - - @Order - private interface LowOrderCreateServiceInstanceRouteBindingWorkflow - extends CreateServiceInstanceRouteBindingWorkflow { - } - - @Order(Ordered.HIGHEST_PRECEDENCE) - private interface HighOrderDeleteServiceInstanceBindingWorkflow extends DeleteServiceInstanceBindingWorkflow { - } - - @Order - private interface LowOrderDeleteServiceInstanceBindingWorkflow extends DeleteServiceInstanceBindingWorkflow { - } - -} diff --git a/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/service/WorkflowServiceInstanceBindingServiceTests.java b/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/service/WorkflowServiceInstanceBindingServiceTests.java new file mode 100644 index 0000000..953e9a0 --- /dev/null +++ b/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/service/WorkflowServiceInstanceBindingServiceTests.java @@ -0,0 +1,926 @@ +/* + * Copyright 2016-2020 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.cloud.appbroker.service; + +import java.sql.Timestamp; +import java.time.Instant; +import java.util.Arrays; + +import org.assertj.core.data.MapEntry; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InOrder; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; +import reactor.test.publisher.TestPublisher; + +import org.springframework.cloud.appbroker.state.ServiceInstanceBindingStateRepository; +import org.springframework.cloud.appbroker.state.ServiceInstanceState; +import org.springframework.cloud.servicebroker.exception.ServiceBrokerException; +import org.springframework.cloud.servicebroker.model.binding.BindResource; +import org.springframework.cloud.servicebroker.model.binding.CreateServiceInstanceAppBindingResponse; +import org.springframework.cloud.servicebroker.model.binding.CreateServiceInstanceAppBindingResponse.CreateServiceInstanceAppBindingResponseBuilder; +import org.springframework.cloud.servicebroker.model.binding.CreateServiceInstanceBindingRequest; +import org.springframework.cloud.servicebroker.model.binding.CreateServiceInstanceRouteBindingResponse; +import org.springframework.cloud.servicebroker.model.binding.CreateServiceInstanceRouteBindingResponse.CreateServiceInstanceRouteBindingResponseBuilder; +import org.springframework.cloud.servicebroker.model.binding.DeleteServiceInstanceBindingRequest; +import org.springframework.cloud.servicebroker.model.binding.DeleteServiceInstanceBindingResponse; +import org.springframework.cloud.servicebroker.model.binding.DeleteServiceInstanceBindingResponse.DeleteServiceInstanceBindingResponseBuilder; +import org.springframework.cloud.servicebroker.model.instance.OperationState; +import org.springframework.core.Ordered; +import org.springframework.core.annotation.Order; +import org.springframework.test.util.ReflectionTestUtils; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.BDDMockito.given; +import static org.mockito.BDDMockito.then; +import static org.mockito.Mockito.inOrder; + +@ExtendWith(MockitoExtension.class) +class WorkflowServiceInstanceBindingServiceTests { + + @Mock + private ServiceInstanceBindingStateRepository stateRepository; + + @Mock + private LowOrderCreateServiceInstanceAppBindingWorkflow createServiceInstanceAppBindingWorkflow1; + + @Mock + private HighOrderCreateServiceAppBindingInstanceWorkflow createServiceInstanceAppBindingWorkflow2; + + @Mock + private LowOrderCreateServiceInstanceRouteBindingWorkflow createServiceInstanceRouteBindingWorkflow1; + + @Mock + private HighOrderCreateServiceRouteBindingInstanceWorkflow createServiceInstanceRouteBindingWorkflow2; + + @Mock + private LowOrderDeleteServiceInstanceBindingWorkflow deleteServiceInstanceBindingWorkflow1; + + @Mock + private HighOrderDeleteServiceInstanceBindingWorkflow deleteServiceInstanceBindingWorkflow2; + + private WorkflowServiceInstanceBindingService workflowServiceInstanceBindingService; + + @BeforeEach + void setUp() { + this.workflowServiceInstanceBindingService = new WorkflowServiceInstanceBindingService(this.stateRepository, + Arrays.asList(this.createServiceInstanceAppBindingWorkflow1, + this.createServiceInstanceAppBindingWorkflow2), + Arrays.asList(this.createServiceInstanceRouteBindingWorkflow1, + this.createServiceInstanceRouteBindingWorkflow2), + Arrays.asList(this.deleteServiceInstanceBindingWorkflow1, this.deleteServiceInstanceBindingWorkflow2)); + } + + @Test + void createServiceInstanceAppBindingWithNoWorkflows() { + given(this.stateRepository.saveState(anyString(), anyString(), any(OperationState.class), anyString())) + .willReturn(Mono + .just(new ServiceInstanceState(OperationState.IN_PROGRESS, "create service instance binding started", + new Timestamp(Instant.now().minusSeconds(60).toEpochMilli())))) + .willReturn(Mono + .just(new ServiceInstanceState(OperationState.SUCCEEDED, "create service instance binding completed", + new Timestamp(Instant.now().minusSeconds(30).toEpochMilli())))); + + this.workflowServiceInstanceBindingService = new WorkflowServiceInstanceBindingService(this.stateRepository, + null, null, null); + + CreateServiceInstanceBindingRequest request = CreateServiceInstanceBindingRequest.builder() + .serviceInstanceId("foo-service") + .bindingId("foo-binding") + .bindResource(BindResource.builder().appGuid("foo-guid").build()) + .build(); + + StepVerifier.create(this.workflowServiceInstanceBindingService.createServiceInstanceBinding(request)) + .assertNext((response) -> { + InOrder repoOrder = inOrder(this.stateRepository); + repoOrder.verify(this.stateRepository) + .saveState(eq("foo-service"), eq("foo-binding"), eq(OperationState.IN_PROGRESS), + eq("create service instance binding started")); + repoOrder.verify(this.stateRepository) + .saveState(eq("foo-service"), eq("foo-binding"), eq(OperationState.SUCCEEDED), + eq("create service instance binding completed")); + repoOrder.verifyNoMoreInteractions(); + + assertThat(response).isNotNull(); + assertThat(response).isInstanceOf(CreateServiceInstanceAppBindingResponse.class); + }) + .verifyComplete(); + } + + @Test + void createServiceInstanceRouteBindingWithNoWorkflows() { + given(this.stateRepository.saveState(anyString(), anyString(), any(OperationState.class), anyString())) + .willReturn(Mono + .just(new ServiceInstanceState(OperationState.IN_PROGRESS, "create service instance binding started", + new Timestamp(Instant.now().minusSeconds(60).toEpochMilli())))) + .willReturn(Mono + .just(new ServiceInstanceState(OperationState.SUCCEEDED, "create service instance binding completed", + new Timestamp(Instant.now().minusSeconds(30).toEpochMilli())))); + + this.workflowServiceInstanceBindingService = new WorkflowServiceInstanceBindingService(this.stateRepository, + null, null, null); + + CreateServiceInstanceBindingRequest request = CreateServiceInstanceBindingRequest.builder() + .serviceInstanceId("foo-service") + .bindingId("foo-binding") + .bindResource(BindResource.builder().route("foo-route").build()) + .build(); + + StepVerifier.create(this.workflowServiceInstanceBindingService.createServiceInstanceBinding(request)) + .assertNext((response) -> { + InOrder repoOrder = inOrder(this.stateRepository); + repoOrder.verify(this.stateRepository) + .saveState(eq("foo-service"), eq("foo-binding"), eq(OperationState.IN_PROGRESS), + eq("create service instance binding started")); + repoOrder.verify(this.stateRepository) + .saveState(eq("foo-service"), eq("foo-binding"), eq(OperationState.SUCCEEDED), + eq("create service instance binding completed")); + repoOrder.verifyNoMoreInteractions(); + + assertThat(response).isNotNull(); + assertThat(response).isInstanceOf(CreateServiceInstanceRouteBindingResponse.class); + }) + .verifyComplete(); + } + + @Test + void createServiceInstanceAppBinding() { + given(this.stateRepository.saveState(anyString(), anyString(), any(OperationState.class), anyString())) + .willReturn(Mono + .just(new ServiceInstanceState(OperationState.IN_PROGRESS, "create service instance binding started", + new Timestamp(Instant.now().minusSeconds(60).toEpochMilli())))) + .willReturn(Mono + .just(new ServiceInstanceState(OperationState.SUCCEEDED, "create service instance binding completed", + new Timestamp(Instant.now().minusSeconds(30).toEpochMilli())))); + + CreateServiceInstanceBindingRequest request = CreateServiceInstanceBindingRequest.builder() + .serviceInstanceId("foo-service") + .bindingId("foo-binding") + .bindResource(BindResource.builder().appGuid("foo-guid").build()) + .build(); + + CreateServiceInstanceAppBindingResponseBuilder responseBuilder = CreateServiceInstanceAppBindingResponse + .builder(); + CreateServiceInstanceAppBindingResponse builtResponse = CreateServiceInstanceAppBindingResponse.builder() + .async(true) + .credentials("foo", "bar") + .operation("working2") + .build(); + + TestPublisher lowerOrderFlow = TestPublisher.create(); + TestPublisher higherOrderFlow = TestPublisher.create(); + + given(this.createServiceInstanceAppBindingWorkflow1.accept(request)).willReturn(Mono.just(true)); + given(this.createServiceInstanceAppBindingWorkflow1.create(eq(request), eq(builtResponse))) + .willReturn(lowerOrderFlow.mono()); + given(this.createServiceInstanceAppBindingWorkflow1.buildResponse(eq(request), + any(CreateServiceInstanceAppBindingResponseBuilder.class))) + .willReturn(Mono.just(responseBuilder.async(true).operation("working1"))); + + given(this.createServiceInstanceAppBindingWorkflow2.accept(request)).willReturn(Mono.just(true)); + given(this.createServiceInstanceAppBindingWorkflow2.create(eq(request), eq(builtResponse))) + .willReturn(higherOrderFlow.mono()); + given(this.createServiceInstanceAppBindingWorkflow2.buildResponse(eq(request), + any(CreateServiceInstanceAppBindingResponseBuilder.class))) + .willReturn(Mono.just(responseBuilder.credentials("foo", "bar").operation("working2"))); + + StepVerifier.create(this.workflowServiceInstanceBindingService.createServiceInstanceBinding(request)) + .assertNext((response) -> { + InOrder repoOrder = inOrder(this.stateRepository); + repoOrder.verify(this.stateRepository) + .saveState(eq("foo-service"), eq("foo-binding"), eq(OperationState.IN_PROGRESS), + eq("create service instance binding started")); + repoOrder.verify(this.stateRepository) + .saveState(eq("foo-service"), eq("foo-binding"), eq(OperationState.SUCCEEDED), + eq("create service instance binding completed")); + repoOrder.verifyNoMoreInteractions(); + + lowerOrderFlow.complete(); + lowerOrderFlow.assertWasNotRequested(); + + higherOrderFlow.complete(); + lowerOrderFlow.assertWasRequested(); + + InOrder createOrder = inOrder(this.createServiceInstanceAppBindingWorkflow1, + this.createServiceInstanceAppBindingWorkflow2); + createOrder.verify(this.createServiceInstanceAppBindingWorkflow2) + .buildResponse(eq(request), any(CreateServiceInstanceAppBindingResponseBuilder.class)); + createOrder.verify(this.createServiceInstanceAppBindingWorkflow1) + .buildResponse(eq(request), any(CreateServiceInstanceAppBindingResponseBuilder.class)); + createOrder.verify(this.createServiceInstanceAppBindingWorkflow2) + .create(request, responseBuilder.build()); + createOrder.verify(this.createServiceInstanceAppBindingWorkflow1) + .create(request, responseBuilder.build()); + createOrder.verifyNoMoreInteractions(); + + CreateServiceInstanceAppBindingResponse r = (CreateServiceInstanceAppBindingResponse) response; + + assertThat(r).isNotNull(); + assertThat(r.getCredentials()).containsOnly(MapEntry.entry("foo", "bar")); + assertThat(r.isAsync()).isTrue(); + assertThat(r.getOperation()).isEqualTo("working2"); + }) + .verifyComplete(); + } + + @Test + void appBindingBuildResponseAppliesFlowsSequentially() { + CreateServiceInstanceBindingRequest request = CreateServiceInstanceBindingRequest.builder() + .serviceInstanceId("foo-service") + .bindingId("foo-binding") + .bindResource(BindResource.builder().appGuid("foo-guid").build()) + .build(); + + CreateServiceInstanceAppBindingResponseBuilder builder = CreateServiceInstanceAppBindingResponse.builder(); + + TestPublisher response1 = TestPublisher.create(); + TestPublisher response2 = TestPublisher.create(); + + CreateServiceInstanceAppBindingWorkflow flow1 = new CreateServiceInstanceAppBindingWorkflow() { + @Override + public Mono buildResponse( + CreateServiceInstanceBindingRequest request, + CreateServiceInstanceAppBindingResponseBuilder responseBuilder) { + return response1.mono(); + } + }; + + CreateServiceInstanceAppBindingWorkflow flow2 = new CreateServiceInstanceAppBindingWorkflow() { + @Override + public Mono buildResponse( + CreateServiceInstanceBindingRequest request, + CreateServiceInstanceAppBindingResponseBuilder responseBuilder) { + return response2.mono(); + } + }; + + Flux buildAppResponse = ReflectionTestUtils.invokeMethod( + this.workflowServiceInstanceBindingService, "invokeAppBindingBuildResponse", builder, request, + Arrays.asList(flow1, flow2)); + + StepVerifier.create(buildAppResponse) + .then(() -> response1.next(builder)) + .then(() -> response2.next(builder)) + .assertNext((r) -> response2.assertWasNotRequested()) + .then(response1::complete) + .assertNext((r) -> response2.assertWasRequested()) + .then(response2::complete) + .verifyComplete(); + } + + @Test + void routeBindingBuildResponseAppliesFlowsSequentially() { + CreateServiceInstanceBindingRequest request = CreateServiceInstanceBindingRequest.builder() + .serviceInstanceId("foo-service") + .bindingId("foo-binding") + .bindResource(BindResource.builder().appGuid("foo-guid").build()) + .build(); + + CreateServiceInstanceRouteBindingResponseBuilder builder = CreateServiceInstanceRouteBindingResponse.builder(); + + TestPublisher response1 = TestPublisher.create(); + TestPublisher response2 = TestPublisher.create(); + + CreateServiceInstanceRouteBindingWorkflow flow1 = new CreateServiceInstanceRouteBindingWorkflow() { + @Override + public Mono buildResponse( + CreateServiceInstanceBindingRequest request, + CreateServiceInstanceRouteBindingResponseBuilder responseBuilder) { + return response1.mono(); + } + }; + + CreateServiceInstanceRouteBindingWorkflow flow2 = new CreateServiceInstanceRouteBindingWorkflow() { + @Override + public Mono buildResponse( + CreateServiceInstanceBindingRequest request, + CreateServiceInstanceRouteBindingResponseBuilder responseBuilder) { + return response2.mono(); + } + }; + + Flux buildRouteResponse = ReflectionTestUtils.invokeMethod( + this.workflowServiceInstanceBindingService, "invokeRouteBindingBuildResponse", builder, request, + Arrays.asList(flow1, flow2)); + + StepVerifier.create(buildRouteResponse) + .then(() -> response1.next(builder)) + .then(() -> response2.next(builder)) + .assertNext((r) -> response2.assertWasNotRequested()) + .then(response1::complete) + .assertNext((r) -> response2.assertWasRequested()) + .then(response2::complete) + .verifyComplete(); + } + + @Test + void createServiceInstanceRouteBinding() { + given(this.stateRepository.saveState(anyString(), anyString(), any(OperationState.class), anyString())) + .willReturn(Mono + .just(new ServiceInstanceState(OperationState.IN_PROGRESS, "create service instance binding started", + new Timestamp(Instant.now().minusSeconds(60).toEpochMilli())))) + .willReturn(Mono + .just(new ServiceInstanceState(OperationState.SUCCEEDED, "create service instance binding completed", + new Timestamp(Instant.now().minusSeconds(30).toEpochMilli())))); + + CreateServiceInstanceBindingRequest request = CreateServiceInstanceBindingRequest.builder() + .serviceInstanceId("foo-service") + .bindingId("foo-binding") + .bindResource(BindResource.builder().route("foo-route").build()) + .build(); + + CreateServiceInstanceRouteBindingResponseBuilder responseBuilder = CreateServiceInstanceRouteBindingResponse + .builder(); + CreateServiceInstanceRouteBindingResponse builtResponse = CreateServiceInstanceRouteBindingResponse.builder() + .async(true) + .routeServiceUrl("foo-url") + .operation("working2") + .build(); + + TestPublisher lowerOrderFlow = TestPublisher.create(); + TestPublisher higherOrderFlow = TestPublisher.create(); + + given(this.createServiceInstanceRouteBindingWorkflow1.accept(request)).willReturn(Mono.just(true)); + given(this.createServiceInstanceRouteBindingWorkflow1.create(eq(request), eq(builtResponse))) + .willReturn(lowerOrderFlow.mono()); + given(this.createServiceInstanceRouteBindingWorkflow1.buildResponse(eq(request), + any(CreateServiceInstanceRouteBindingResponseBuilder.class))) + .willReturn(Mono.just(responseBuilder.async(true).operation("working1"))); + + given(this.createServiceInstanceRouteBindingWorkflow2.accept(request)).willReturn(Mono.just(true)); + given(this.createServiceInstanceRouteBindingWorkflow2.create(eq(request), eq(builtResponse))) + .willReturn(higherOrderFlow.mono()); + given(this.createServiceInstanceRouteBindingWorkflow2.buildResponse(eq(request), + any(CreateServiceInstanceRouteBindingResponseBuilder.class))) + .willReturn(Mono.just(responseBuilder.routeServiceUrl("foo-url").operation("working2"))); + + StepVerifier.create(this.workflowServiceInstanceBindingService.createServiceInstanceBinding(request)) + .assertNext((response) -> { + InOrder repoOrder = inOrder(this.stateRepository); + repoOrder.verify(this.stateRepository) + .saveState(eq("foo-service"), eq("foo-binding"), eq(OperationState.IN_PROGRESS), + eq("create service instance binding started")); + repoOrder.verify(this.stateRepository) + .saveState(eq("foo-service"), eq("foo-binding"), eq(OperationState.SUCCEEDED), + eq("create service instance binding completed")); + repoOrder.verifyNoMoreInteractions(); + + lowerOrderFlow.complete(); + lowerOrderFlow.assertWasNotRequested(); + + higherOrderFlow.complete(); + lowerOrderFlow.assertWasRequested(); + + InOrder createOrder = inOrder(this.createServiceInstanceRouteBindingWorkflow1, + this.createServiceInstanceRouteBindingWorkflow2); + createOrder.verify(this.createServiceInstanceRouteBindingWorkflow2) + .buildResponse(eq(request), any(CreateServiceInstanceRouteBindingResponseBuilder.class)); + createOrder.verify(this.createServiceInstanceRouteBindingWorkflow1) + .buildResponse(eq(request), any(CreateServiceInstanceRouteBindingResponseBuilder.class)); + createOrder.verify(this.createServiceInstanceRouteBindingWorkflow2) + .create(request, responseBuilder.build()); + createOrder.verify(this.createServiceInstanceRouteBindingWorkflow1) + .create(request, responseBuilder.build()); + createOrder.verifyNoMoreInteractions(); + + assertThat(response).isNotNull(); + assertThat(response).isInstanceOf(CreateServiceInstanceRouteBindingResponse.class); + assertThat(((CreateServiceInstanceRouteBindingResponse) response).getRouteServiceUrl()) + .isEqualTo("foo-url"); + assertThat(response.isAsync()).isTrue(); + assertThat(response.getOperation()).isEqualTo("working2"); + }) + .verifyComplete(); + } + + @Test + void createServiceInstanceAppBindingWithAsyncError() { + given(this.stateRepository.saveState(anyString(), anyString(), any(OperationState.class), anyString())) + .willReturn(Mono + .just(new ServiceInstanceState(OperationState.IN_PROGRESS, "create service instance binding started", + new Timestamp(Instant.now().minusSeconds(60).toEpochMilli())))) + .willReturn( + Mono.just(new ServiceInstanceState(OperationState.FAILED, "create service instance binding failed", + new Timestamp(Instant.now().minusSeconds(30).toEpochMilli())))); + + CreateServiceInstanceBindingRequest request = CreateServiceInstanceBindingRequest.builder() + .serviceInstanceId("foo-service") + .bindingId("foo-binding") + .bindResource(BindResource.builder().appGuid("foo-guid").build()) + .build(); + + CreateServiceInstanceAppBindingResponseBuilder responseBuilder = CreateServiceInstanceAppBindingResponse + .builder(); + + given(this.createServiceInstanceAppBindingWorkflow1.accept(request)).willReturn(Mono.just(true)); + given(this.createServiceInstanceAppBindingWorkflow1.create(request, responseBuilder.build())) + .willReturn(Mono.error(new RuntimeException("create foo error"))); + given(this.createServiceInstanceAppBindingWorkflow1.buildResponse(eq(request), + any(CreateServiceInstanceAppBindingResponseBuilder.class))) + .willReturn(Mono.just(responseBuilder)); + + given(this.createServiceInstanceAppBindingWorkflow2.accept(request)).willReturn(Mono.just(true)); + given(this.createServiceInstanceAppBindingWorkflow2.create(request, responseBuilder.build())) + .willReturn(Mono.empty()); + given(this.createServiceInstanceAppBindingWorkflow2.buildResponse(eq(request), + any(CreateServiceInstanceAppBindingResponseBuilder.class))) + .willReturn(Mono.just(responseBuilder)); + + StepVerifier.create(this.workflowServiceInstanceBindingService.createServiceInstanceBinding(request)) + .assertNext((response) -> { + InOrder repoOrder = inOrder(this.stateRepository); + repoOrder.verify(this.stateRepository) + .saveState(eq("foo-service"), eq("foo-binding"), eq(OperationState.IN_PROGRESS), + eq("create service instance binding started")); + repoOrder.verify(this.stateRepository) + .saveState(eq("foo-service"), eq("foo-binding"), eq(OperationState.FAILED), eq("create foo error")); + repoOrder.verifyNoMoreInteractions(); + + InOrder createOrder = inOrder(this.createServiceInstanceAppBindingWorkflow1, + this.createServiceInstanceAppBindingWorkflow2); + createOrder.verify(this.createServiceInstanceAppBindingWorkflow2) + .buildResponse(eq(request), any(CreateServiceInstanceAppBindingResponseBuilder.class)); + createOrder.verify(this.createServiceInstanceAppBindingWorkflow1) + .buildResponse(eq(request), any(CreateServiceInstanceAppBindingResponseBuilder.class)); + createOrder.verify(this.createServiceInstanceAppBindingWorkflow2) + .create(request, responseBuilder.build()); + createOrder.verify(this.createServiceInstanceAppBindingWorkflow1) + .create(request, responseBuilder.build()); + createOrder.verifyNoMoreInteractions(); + + assertThat(response).isNotNull(); + assertThat(response).isInstanceOf(CreateServiceInstanceAppBindingResponse.class); + }) + .verifyComplete(); + } + + @Test + void createServiceInstanceRouteBindingWithAsyncError() { + given(this.stateRepository.saveState(anyString(), anyString(), any(OperationState.class), anyString())) + .willReturn(Mono + .just(new ServiceInstanceState(OperationState.IN_PROGRESS, "create service instance binding started", + new Timestamp(Instant.now().minusSeconds(60).toEpochMilli())))) + .willReturn( + Mono.just(new ServiceInstanceState(OperationState.FAILED, "create service instance binding failed", + new Timestamp(Instant.now().minusSeconds(30).toEpochMilli())))); + + CreateServiceInstanceBindingRequest request = CreateServiceInstanceBindingRequest.builder() + .serviceInstanceId("foo-service") + .bindingId("foo-binding") + .bindResource(BindResource.builder().route("foo-route").build()) + .build(); + + CreateServiceInstanceRouteBindingResponseBuilder responseBuilder = CreateServiceInstanceRouteBindingResponse + .builder(); + + given(this.createServiceInstanceRouteBindingWorkflow1.accept(request)).willReturn(Mono.just(true)); + given(this.createServiceInstanceRouteBindingWorkflow1.create(request, responseBuilder.build())) + .willReturn(Mono.error(new RuntimeException("create foo error"))); + given(this.createServiceInstanceRouteBindingWorkflow1.buildResponse(eq(request), + any(CreateServiceInstanceRouteBindingResponseBuilder.class))) + .willReturn(Mono.just(responseBuilder)); + + given(this.createServiceInstanceRouteBindingWorkflow2.accept(request)).willReturn(Mono.just(true)); + given(this.createServiceInstanceRouteBindingWorkflow2.create(request, responseBuilder.build())) + .willReturn(Mono.empty()); + given(this.createServiceInstanceRouteBindingWorkflow2.buildResponse(eq(request), + any(CreateServiceInstanceRouteBindingResponseBuilder.class))) + .willReturn(Mono.just(responseBuilder)); + + StepVerifier.create(this.workflowServiceInstanceBindingService.createServiceInstanceBinding(request)) + .assertNext((response) -> { + InOrder repoOrder = inOrder(this.stateRepository); + repoOrder.verify(this.stateRepository) + .saveState(eq("foo-service"), eq("foo-binding"), eq(OperationState.IN_PROGRESS), + eq("create service instance binding started")); + repoOrder.verify(this.stateRepository) + .saveState(eq("foo-service"), eq("foo-binding"), eq(OperationState.FAILED), eq("create foo error")); + repoOrder.verifyNoMoreInteractions(); + + InOrder createOrder = inOrder(this.createServiceInstanceRouteBindingWorkflow1, + this.createServiceInstanceRouteBindingWorkflow2); + createOrder.verify(this.createServiceInstanceRouteBindingWorkflow2) + .buildResponse(eq(request), any(CreateServiceInstanceRouteBindingResponseBuilder.class)); + createOrder.verify(this.createServiceInstanceRouteBindingWorkflow1) + .buildResponse(eq(request), any(CreateServiceInstanceRouteBindingResponseBuilder.class)); + createOrder.verify(this.createServiceInstanceRouteBindingWorkflow2) + .create(request, responseBuilder.build()); + createOrder.verify(this.createServiceInstanceRouteBindingWorkflow1) + .create(request, responseBuilder.build()); + createOrder.verifyNoMoreInteractions(); + + assertThat(response).isNotNull(); + assertThat(response).isInstanceOf(CreateServiceInstanceRouteBindingResponse.class); + }) + .verifyComplete(); + } + + @Test + void createServiceInstanceAppBindingWithResponseError() { + CreateServiceInstanceBindingRequest request = CreateServiceInstanceBindingRequest.builder() + .serviceInstanceId("foo-id") + .bindResource(BindResource.builder().appGuid("foo-guid").build()) + .build(); + + CreateServiceInstanceAppBindingResponseBuilder responseBuilder = CreateServiceInstanceAppBindingResponse + .builder(); + + given(this.createServiceInstanceAppBindingWorkflow1.accept(request)).willReturn(Mono.just(true)); + given(this.createServiceInstanceAppBindingWorkflow1.buildResponse(eq(request), + any(CreateServiceInstanceAppBindingResponseBuilder.class))) + .willReturn(Mono.error(new ServiceBrokerException("create foo error"))); + + given(this.createServiceInstanceAppBindingWorkflow2.accept(request)).willReturn(Mono.just(true)); + given(this.createServiceInstanceAppBindingWorkflow2.buildResponse(eq(request), + any(CreateServiceInstanceAppBindingResponseBuilder.class))) + .willReturn(Mono.just(responseBuilder)); + + StepVerifier.create(this.workflowServiceInstanceBindingService.createServiceInstanceBinding(request)) + .expectErrorSatisfies( + (e) -> assertThat(e).isInstanceOf(ServiceBrokerException.class).hasMessage("create foo error")) + .verify(); + } + + @Test + void createServiceInstanceRouteBindingWithResponseError() { + CreateServiceInstanceBindingRequest request = CreateServiceInstanceBindingRequest.builder() + .serviceInstanceId("foo-id") + .bindResource(BindResource.builder().route("foo-route").build()) + .build(); + + CreateServiceInstanceRouteBindingResponseBuilder responseBuilder = CreateServiceInstanceRouteBindingResponse + .builder(); + + given(this.createServiceInstanceRouteBindingWorkflow1.accept(request)).willReturn(Mono.just(true)); + given(this.createServiceInstanceRouteBindingWorkflow1.buildResponse(eq(request), + any(CreateServiceInstanceRouteBindingResponseBuilder.class))) + .willReturn(Mono.error(new ServiceBrokerException("create foo error"))); + + given(this.createServiceInstanceRouteBindingWorkflow2.accept(request)).willReturn(Mono.just(true)); + given(this.createServiceInstanceRouteBindingWorkflow2.buildResponse(eq(request), + any(CreateServiceInstanceRouteBindingResponseBuilder.class))) + .willReturn(Mono.just(responseBuilder)); + + StepVerifier.create(this.workflowServiceInstanceBindingService.createServiceInstanceBinding(request)) + .expectErrorSatisfies( + (e) -> assertThat(e).isInstanceOf(ServiceBrokerException.class).hasMessage("create foo error")) + .verify(); + } + + @Test + void createServiceInstanceAppBindingWithNoAcceptsDoesNothing() { + given(this.stateRepository.saveState(anyString(), anyString(), any(OperationState.class), anyString())) + .willReturn(Mono.just(new ServiceInstanceState(OperationState.IN_PROGRESS, + "create service instance started", new Timestamp(Instant.now().minusSeconds(60).toEpochMilli())))) + .willReturn( + Mono.just(new ServiceInstanceState(OperationState.SUCCEEDED, "create service instance completed", + new Timestamp(Instant.now().minusSeconds(30).toEpochMilli())))); + + CreateServiceInstanceBindingRequest request = CreateServiceInstanceBindingRequest.builder() + .serviceInstanceId("foo-service") + .bindingId("foo-binding") + .bindResource(BindResource.builder().appGuid("foo-guid").build()) + .build(); + + given(this.createServiceInstanceAppBindingWorkflow1.accept(request)).willReturn(Mono.just(false)); + + given(this.createServiceInstanceAppBindingWorkflow2.accept(request)).willReturn(Mono.just(false)); + + StepVerifier.create(this.workflowServiceInstanceBindingService.createServiceInstanceBinding(request)) + .assertNext((response) -> { + InOrder repoOrder = inOrder(this.stateRepository); + repoOrder.verify(this.stateRepository) + .saveState(eq("foo-service"), eq("foo-binding"), eq(OperationState.IN_PROGRESS), + eq("create service instance binding started")); + repoOrder.verify(this.stateRepository) + .saveState(eq("foo-service"), eq("foo-binding"), eq(OperationState.SUCCEEDED), + eq("create service instance binding completed")); + repoOrder.verifyNoMoreInteractions(); + + then(this.createServiceInstanceAppBindingWorkflow1).shouldHaveNoMoreInteractions(); + then(this.createServiceInstanceAppBindingWorkflow2).shouldHaveNoMoreInteractions(); + + assertThat(response).isNotNull(); + assertThat(response).isInstanceOf(CreateServiceInstanceAppBindingResponse.class); + }) + .verifyComplete(); + } + + @Test + void createServiceInstanceRouteBindingWithNoAcceptsDoesNothing() { + given(this.stateRepository.saveState(anyString(), anyString(), any(OperationState.class), anyString())) + .willReturn(Mono.just(new ServiceInstanceState(OperationState.IN_PROGRESS, + "create service instance started", new Timestamp(Instant.now().minusSeconds(60).toEpochMilli())))) + .willReturn( + Mono.just(new ServiceInstanceState(OperationState.SUCCEEDED, "create service instance completed", + new Timestamp(Instant.now().minusSeconds(30).toEpochMilli())))); + + CreateServiceInstanceBindingRequest request = CreateServiceInstanceBindingRequest.builder() + .serviceInstanceId("foo-service") + .bindingId("foo-binding") + .bindResource(BindResource.builder().route("foo-route").build()) + .build(); + + given(this.createServiceInstanceRouteBindingWorkflow1.accept(request)).willReturn(Mono.just(false)); + + given(this.createServiceInstanceRouteBindingWorkflow2.accept(request)).willReturn(Mono.just(false)); + + StepVerifier.create(this.workflowServiceInstanceBindingService.createServiceInstanceBinding(request)) + .assertNext((response) -> { + InOrder repoOrder = inOrder(this.stateRepository); + repoOrder.verify(this.stateRepository) + .saveState(eq("foo-service"), eq("foo-binding"), eq(OperationState.IN_PROGRESS), + eq("create service instance binding started")); + repoOrder.verify(this.stateRepository) + .saveState(eq("foo-service"), eq("foo-binding"), eq(OperationState.SUCCEEDED), + eq("create service instance binding completed")); + repoOrder.verifyNoMoreInteractions(); + + then(this.createServiceInstanceRouteBindingWorkflow1).shouldHaveNoMoreInteractions(); + then(this.createServiceInstanceRouteBindingWorkflow2).shouldHaveNoMoreInteractions(); + + assertThat(response).isNotNull(); + assertThat(response).isInstanceOf(CreateServiceInstanceRouteBindingResponse.class); + }) + .verifyComplete(); + } + + @Test + void deleteServiceInstanceBindingsWithNoWorkflows() { + given(this.stateRepository.saveState(anyString(), anyString(), any(OperationState.class), anyString())) + .willReturn(Mono.just(new ServiceInstanceState(OperationState.IN_PROGRESS, + "delete service instance started", new Timestamp(Instant.now().minusSeconds(60).toEpochMilli())))) + .willReturn( + Mono.just(new ServiceInstanceState(OperationState.SUCCEEDED, "delete service instance completed", + new Timestamp(Instant.now().minusSeconds(30).toEpochMilli())))); + + this.workflowServiceInstanceBindingService = new WorkflowServiceInstanceBindingService(this.stateRepository, + null, null, null); + + DeleteServiceInstanceBindingRequest request = DeleteServiceInstanceBindingRequest.builder() + .serviceInstanceId("foo-service") + .bindingId("foo-binding") + .build(); + + StepVerifier.create(this.workflowServiceInstanceBindingService.deleteServiceInstanceBinding(request)) + .assertNext((response) -> { + InOrder repoOrder = inOrder(this.stateRepository); + repoOrder.verify(this.stateRepository) + .saveState(eq("foo-service"), eq("foo-binding"), eq(OperationState.IN_PROGRESS), + eq("delete service instance binding started")); + repoOrder.verify(this.stateRepository) + .saveState(eq("foo-service"), eq("foo-binding"), eq(OperationState.SUCCEEDED), + eq("delete service instance binding completed")); + repoOrder.verifyNoMoreInteractions(); + + assertThat(response).isNotNull(); + assertThat(response).isInstanceOf(DeleteServiceInstanceBindingResponse.class); + }) + .verifyComplete(); + } + + @Test + void deleteServiceInstanceBinding() { + given(this.stateRepository.saveState(anyString(), anyString(), any(OperationState.class), anyString())) + .willReturn(Mono + .just(new ServiceInstanceState(OperationState.IN_PROGRESS, "delete service instance binding started", + new Timestamp(Instant.now().minusSeconds(60).toEpochMilli())))) + .willReturn(Mono + .just(new ServiceInstanceState(OperationState.SUCCEEDED, "delete service instance binding completed", + new Timestamp(Instant.now().minusSeconds(30).toEpochMilli())))); + + DeleteServiceInstanceBindingRequest request = DeleteServiceInstanceBindingRequest.builder() + .serviceInstanceId("foo-service") + .bindingId("foo-binding") + .build(); + + DeleteServiceInstanceBindingResponseBuilder responseBuilder = DeleteServiceInstanceBindingResponse.builder(); + DeleteServiceInstanceBindingResponse builtResponse = DeleteServiceInstanceBindingResponse.builder() + .async(true) + .operation("working2") + .build(); + + TestPublisher lowerOrderFlow = TestPublisher.create(); + TestPublisher higherOrderFlow = TestPublisher.create(); + + given(this.deleteServiceInstanceBindingWorkflow1.accept(request)).willReturn(Mono.just(true)); + given(this.deleteServiceInstanceBindingWorkflow1.delete(eq(request), eq(builtResponse))) + .willReturn(lowerOrderFlow.mono()); + given(this.deleteServiceInstanceBindingWorkflow1.buildResponse(eq(request), + any(DeleteServiceInstanceBindingResponseBuilder.class))) + .willReturn(Mono.just(responseBuilder.async(true).operation("working1"))); + + given(this.deleteServiceInstanceBindingWorkflow2.accept(request)).willReturn(Mono.just(true)); + given(this.deleteServiceInstanceBindingWorkflow2.delete(eq(request), eq(builtResponse))) + .willReturn(higherOrderFlow.mono()); + given(this.deleteServiceInstanceBindingWorkflow2.buildResponse(eq(request), + any(DeleteServiceInstanceBindingResponseBuilder.class))) + .willReturn(Mono.just(responseBuilder.operation("working2"))); + + StepVerifier.create(this.workflowServiceInstanceBindingService.deleteServiceInstanceBinding(request)) + .assertNext((response) -> { + InOrder repoOrder = inOrder(this.stateRepository); + repoOrder.verify(this.stateRepository) + .saveState(eq("foo-service"), eq("foo-binding"), eq(OperationState.IN_PROGRESS), + eq("delete service instance binding started")); + repoOrder.verify(this.stateRepository) + .saveState(eq("foo-service"), eq("foo-binding"), eq(OperationState.SUCCEEDED), + eq("delete service instance binding completed")); + repoOrder.verifyNoMoreInteractions(); + + lowerOrderFlow.complete(); + lowerOrderFlow.assertWasNotRequested(); + + higherOrderFlow.complete(); + lowerOrderFlow.assertWasRequested(); + + InOrder deleteOrder = inOrder(this.deleteServiceInstanceBindingWorkflow1, + this.deleteServiceInstanceBindingWorkflow2); + deleteOrder.verify(this.deleteServiceInstanceBindingWorkflow2) + .buildResponse(eq(request), any(DeleteServiceInstanceBindingResponseBuilder.class)); + deleteOrder.verify(this.deleteServiceInstanceBindingWorkflow1) + .buildResponse(eq(request), any(DeleteServiceInstanceBindingResponseBuilder.class)); + deleteOrder.verify(this.deleteServiceInstanceBindingWorkflow2).delete(request, responseBuilder.build()); + deleteOrder.verify(this.deleteServiceInstanceBindingWorkflow1).delete(request, responseBuilder.build()); + deleteOrder.verifyNoMoreInteractions(); + + assertThat(response).isNotNull(); + assertThat(response.isAsync()).isTrue(); + assertThat(response.getOperation()).isEqualTo("working2"); + }) + .verifyComplete(); + } + + @Test + void deleteServiceInstanceBindingWithAsyncError() { + given(this.stateRepository.saveState(anyString(), anyString(), any(OperationState.class), anyString())) + .willReturn(Mono.just(new ServiceInstanceState(OperationState.IN_PROGRESS, + "delete service instance started", new Timestamp(Instant.now().minusSeconds(60).toEpochMilli())))) + .willReturn(Mono.just(new ServiceInstanceState(OperationState.FAILED, "delete service instance failed", + new Timestamp(Instant.now().minusSeconds(30).toEpochMilli())))); + + DeleteServiceInstanceBindingRequest request = DeleteServiceInstanceBindingRequest.builder() + .serviceInstanceId("foo-service") + .bindingId("foo-binding") + .build(); + + DeleteServiceInstanceBindingResponseBuilder responseBuilder = DeleteServiceInstanceBindingResponse.builder(); + + given(this.deleteServiceInstanceBindingWorkflow1.accept(request)).willReturn(Mono.just(true)); + given(this.deleteServiceInstanceBindingWorkflow1.delete(request, responseBuilder.build())) + .willReturn(Mono.error(new RuntimeException("delete foo binding error"))); + given(this.deleteServiceInstanceBindingWorkflow1.buildResponse(eq(request), + any(DeleteServiceInstanceBindingResponseBuilder.class))) + .willReturn(Mono.just(responseBuilder)); + + given(this.deleteServiceInstanceBindingWorkflow2.accept(request)).willReturn(Mono.just(true)); + given(this.deleteServiceInstanceBindingWorkflow2.delete(request, responseBuilder.build())) + .willReturn(Mono.empty()); + given(this.deleteServiceInstanceBindingWorkflow2.buildResponse(eq(request), + any(DeleteServiceInstanceBindingResponseBuilder.class))) + .willReturn(Mono.just(responseBuilder)); + + StepVerifier.create(this.workflowServiceInstanceBindingService.deleteServiceInstanceBinding(request)) + .assertNext((response) -> { + InOrder repoOrder = inOrder(this.stateRepository); + repoOrder.verify(this.stateRepository) + .saveState(eq("foo-service"), eq("foo-binding"), eq(OperationState.IN_PROGRESS), + eq("delete service instance binding started")); + repoOrder.verify(this.stateRepository) + .saveState(eq("foo-service"), eq("foo-binding"), eq(OperationState.FAILED), + eq("delete foo binding error")); + repoOrder.verifyNoMoreInteractions(); + + InOrder deleteOrder = inOrder(this.deleteServiceInstanceBindingWorkflow1, + this.deleteServiceInstanceBindingWorkflow2); + deleteOrder.verify(this.deleteServiceInstanceBindingWorkflow2) + .buildResponse(eq(request), any(DeleteServiceInstanceBindingResponseBuilder.class)); + deleteOrder.verify(this.deleteServiceInstanceBindingWorkflow1) + .buildResponse(eq(request), any(DeleteServiceInstanceBindingResponseBuilder.class)); + deleteOrder.verify(this.deleteServiceInstanceBindingWorkflow2).delete(request, responseBuilder.build()); + deleteOrder.verify(this.deleteServiceInstanceBindingWorkflow1).delete(request, responseBuilder.build()); + deleteOrder.verifyNoMoreInteractions(); + + assertThat(response).isNotNull(); + }) + .verifyComplete(); + } + + @Test + void deleteServiceInstanceBindingWithResponseError() { + DeleteServiceInstanceBindingRequest request = DeleteServiceInstanceBindingRequest.builder() + .serviceInstanceId("foo") + .bindingId("bar") + .build(); + + DeleteServiceInstanceBindingResponseBuilder responseBuilder = DeleteServiceInstanceBindingResponse.builder(); + + given(this.deleteServiceInstanceBindingWorkflow1.accept(request)).willReturn(Mono.just(true)); + given(this.deleteServiceInstanceBindingWorkflow1.buildResponse(eq(request), + any(DeleteServiceInstanceBindingResponseBuilder.class))) + .willReturn(Mono.error(new ServiceBrokerException("delete foo binding error"))); + + given(this.deleteServiceInstanceBindingWorkflow2.accept(request)).willReturn(Mono.just(true)); + given(this.deleteServiceInstanceBindingWorkflow2.buildResponse(eq(request), + any(DeleteServiceInstanceBindingResponseBuilder.class))) + .willReturn(Mono.just(responseBuilder)); + + StepVerifier.create(this.workflowServiceInstanceBindingService.deleteServiceInstanceBinding(request)) + .expectErrorSatisfies((e) -> assertThat(e).isInstanceOf(ServiceBrokerException.class) + .hasMessage("delete foo binding error")) + .verify(); + } + + @Test + void deleteServiceInstanceBindingWithNoAcceptsDoesNothing() { + given(this.stateRepository.saveState(anyString(), anyString(), any(OperationState.class), anyString())) + .willReturn(Mono + .just(new ServiceInstanceState(OperationState.IN_PROGRESS, "delete service instance binding started", + new Timestamp(Instant.now().minusSeconds(60).toEpochMilli())))) + .willReturn(Mono + .just(new ServiceInstanceState(OperationState.SUCCEEDED, "delete service instance binding completed", + new Timestamp(Instant.now().minusSeconds(30).toEpochMilli())))); + + DeleteServiceInstanceBindingRequest request = DeleteServiceInstanceBindingRequest.builder() + .serviceInstanceId("foo-service") + .bindingId("foo-binding") + .build(); + + given(this.deleteServiceInstanceBindingWorkflow1.accept(request)).willReturn(Mono.just(false)); + + given(this.deleteServiceInstanceBindingWorkflow2.accept(request)).willReturn(Mono.just(false)); + + StepVerifier.create(this.workflowServiceInstanceBindingService.deleteServiceInstanceBinding(request)) + .assertNext((response) -> { + InOrder repoOrder = inOrder(this.stateRepository); + repoOrder.verify(this.stateRepository) + .saveState(eq("foo-service"), eq("foo-binding"), eq(OperationState.IN_PROGRESS), + eq("delete service instance binding started")); + repoOrder.verify(this.stateRepository) + .saveState(eq("foo-service"), eq("foo-binding"), eq(OperationState.SUCCEEDED), + eq("delete service instance binding completed")); + repoOrder.verifyNoMoreInteractions(); + + then(this.deleteServiceInstanceBindingWorkflow1).shouldHaveNoMoreInteractions(); + then(this.deleteServiceInstanceBindingWorkflow2).shouldHaveNoMoreInteractions(); + + assertThat(response).isNotNull(); + }) + .verifyComplete(); + } + + @Order(Ordered.HIGHEST_PRECEDENCE) + private interface HighOrderCreateServiceAppBindingInstanceWorkflow extends CreateServiceInstanceAppBindingWorkflow { + + } + + @Order + private interface LowOrderCreateServiceInstanceAppBindingWorkflow extends CreateServiceInstanceAppBindingWorkflow { + + } + + @Order(Ordered.HIGHEST_PRECEDENCE) + private interface HighOrderCreateServiceRouteBindingInstanceWorkflow + extends CreateServiceInstanceRouteBindingWorkflow { + + } + + @Order + private interface LowOrderCreateServiceInstanceRouteBindingWorkflow + extends CreateServiceInstanceRouteBindingWorkflow { + + } + + @Order(Ordered.HIGHEST_PRECEDENCE) + private interface HighOrderDeleteServiceInstanceBindingWorkflow extends DeleteServiceInstanceBindingWorkflow { + + } + + @Order + private interface LowOrderDeleteServiceInstanceBindingWorkflow extends DeleteServiceInstanceBindingWorkflow { + + } + +} diff --git a/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/service/WorkflowServiceInstanceServiceTest.java b/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/service/WorkflowServiceInstanceServiceTest.java deleted file mode 100644 index 2009378..0000000 --- a/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/service/WorkflowServiceInstanceServiceTest.java +++ /dev/null @@ -1,741 +0,0 @@ -/* - * Copyright 2002-2020 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.appbroker.service; - -import java.sql.Timestamp; -import java.time.Instant; -import java.util.Arrays; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.InOrder; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; -import reactor.core.publisher.Mono; -import reactor.test.StepVerifier; -import reactor.test.publisher.TestPublisher; - -import org.springframework.cloud.appbroker.state.ServiceInstanceState; -import org.springframework.cloud.appbroker.state.ServiceInstanceStateRepository; -import org.springframework.cloud.servicebroker.exception.ServiceBrokerException; -import org.springframework.cloud.servicebroker.model.instance.CreateServiceInstanceRequest; -import org.springframework.cloud.servicebroker.model.instance.CreateServiceInstanceResponse; -import org.springframework.cloud.servicebroker.model.instance.CreateServiceInstanceResponse.CreateServiceInstanceResponseBuilder; -import org.springframework.cloud.servicebroker.model.instance.DeleteServiceInstanceRequest; -import org.springframework.cloud.servicebroker.model.instance.DeleteServiceInstanceResponse; -import org.springframework.cloud.servicebroker.model.instance.DeleteServiceInstanceResponse.DeleteServiceInstanceResponseBuilder; -import org.springframework.cloud.servicebroker.model.instance.OperationState; -import org.springframework.cloud.servicebroker.model.instance.UpdateServiceInstanceRequest; -import org.springframework.cloud.servicebroker.model.instance.UpdateServiceInstanceResponse; -import org.springframework.cloud.servicebroker.model.instance.UpdateServiceInstanceResponse.UpdateServiceInstanceResponseBuilder; -import org.springframework.core.Ordered; -import org.springframework.core.annotation.Order; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.BDDMockito.given; -import static org.mockito.BDDMockito.then; -import static org.mockito.Mockito.inOrder; - -@ExtendWith(MockitoExtension.class) -class WorkflowServiceInstanceServiceTest { - - @Mock - private ServiceInstanceStateRepository serviceInstanceStateRepository; - - @Mock - private LowOrderCreateServiceInstanceWorkflow createServiceInstanceWorkflow1; - - @Mock - private HighOrderCreateServiceInstanceWorkflow createServiceInstanceWorkflow2; - - @Mock - private LowOrderDeleteServiceInstanceWorkflow deleteServiceInstanceWorkflow1; - - @Mock - private HighOrderDeleteServiceInstanceWorkflow deleteServiceInstanceWorkflow2; - - @Mock - private LowOrderUpdateServiceInstanceWorkflow updateServiceInstanceWorkflow1; - - @Mock - private HighOrderUpdateServiceInstanceWorkflow updateServiceInstanceWorkflow2; - - private WorkflowServiceInstanceService workflowServiceInstanceService; - - @BeforeEach - void setUp() { - this.workflowServiceInstanceService = new WorkflowServiceInstanceService(serviceInstanceStateRepository, - Arrays.asList(createServiceInstanceWorkflow1, createServiceInstanceWorkflow2), - Arrays.asList(deleteServiceInstanceWorkflow1, deleteServiceInstanceWorkflow2), - Arrays.asList(updateServiceInstanceWorkflow1, updateServiceInstanceWorkflow2)); - } - - @Test - void createServiceInstance() { - given(serviceInstanceStateRepository.saveState(anyString(), any(OperationState.class), anyString())) - .willReturn( - Mono.just( - new ServiceInstanceState(OperationState.IN_PROGRESS, "create service instance started", - new Timestamp(Instant.now().minusSeconds(60).toEpochMilli())))) - .willReturn( - Mono.just( - new ServiceInstanceState(OperationState.SUCCEEDED, "create service instance completed", - new Timestamp(Instant.now().minusSeconds(300).toEpochMilli())))); - - CreateServiceInstanceRequest request = CreateServiceInstanceRequest.builder() - .serviceInstanceId("foo") - .build(); - - CreateServiceInstanceResponseBuilder responseBuilder = CreateServiceInstanceResponse.builder(); - CreateServiceInstanceResponse builtResponse = CreateServiceInstanceResponse.builder() - .async(true) - .dashboardUrl("https://dashboard.example.local") - .operation("working2") - .build(); - - TestPublisher lowerOrderFlow = TestPublisher.create(); - TestPublisher higherOrderFlow = TestPublisher.create(); - - given(createServiceInstanceWorkflow1.accept(request)) - .willReturn(Mono.just(true)); - given(createServiceInstanceWorkflow1.create(eq(request), eq(builtResponse))) - .willReturn(lowerOrderFlow.mono()); - given( - createServiceInstanceWorkflow1 - .buildResponse(eq(request), any(CreateServiceInstanceResponseBuilder.class))) - .willReturn(Mono.just(responseBuilder - .async(true) - .operation("working1"))); - - given(createServiceInstanceWorkflow2.accept(request)) - .willReturn(Mono.just(true)); - given(createServiceInstanceWorkflow2.create(eq(request), eq(builtResponse))) - .willReturn(higherOrderFlow.mono()); - given(createServiceInstanceWorkflow2 - .buildResponse(eq(request), any(CreateServiceInstanceResponseBuilder.class))) - .willReturn(Mono.just(responseBuilder - .dashboardUrl("https://dashboard.example.local") - .operation("working2"))); - - StepVerifier.create(workflowServiceInstanceService.createServiceInstance(request)) - .assertNext(response -> { - InOrder repoOrder = inOrder(serviceInstanceStateRepository); - repoOrder.verify(serviceInstanceStateRepository) - .saveState(eq("foo"), eq(OperationState.IN_PROGRESS), - eq("create service instance started")); - repoOrder.verify(serviceInstanceStateRepository) - .saveState(eq("foo"), eq(OperationState.SUCCEEDED), - eq("create service instance completed")); - repoOrder.verifyNoMoreInteractions(); - - lowerOrderFlow.complete(); - lowerOrderFlow.assertWasNotRequested(); - - higherOrderFlow.complete(); - lowerOrderFlow.assertWasRequested(); - - InOrder createOrder = inOrder(createServiceInstanceWorkflow1, createServiceInstanceWorkflow2); - createOrder.verify(createServiceInstanceWorkflow2).buildResponse(eq(request), - any(CreateServiceInstanceResponseBuilder.class)); - createOrder.verify(createServiceInstanceWorkflow1).buildResponse(eq(request), - any(CreateServiceInstanceResponseBuilder.class)); - createOrder.verify(createServiceInstanceWorkflow2).create(request, responseBuilder.build()); - createOrder.verify(createServiceInstanceWorkflow1).create(request, responseBuilder.build()); - createOrder.verifyNoMoreInteractions(); - - assertThat(response).isNotNull(); - assertThat(response.isAsync()).isTrue(); - assertThat(response.getDashboardUrl()).isEqualTo("https://dashboard.example.local"); - assertThat(response.getOperation()).isEqualTo("working2"); - }) - .verifyComplete(); - } - - @Test - void createServiceInstanceWithAsyncError() { - given(serviceInstanceStateRepository.saveState(anyString(), any(OperationState.class), anyString())) - .willReturn( - Mono.just( - new ServiceInstanceState(OperationState.IN_PROGRESS, "create service instance started", - new Timestamp(Instant.now().minusSeconds(60).toEpochMilli())))) - .willReturn(Mono.just(new ServiceInstanceState(OperationState.FAILED, "create service instance failed", - new Timestamp(Instant.now().minusSeconds(30).toEpochMilli())))); - - CreateServiceInstanceRequest request = CreateServiceInstanceRequest.builder() - .serviceInstanceId("foo") - .build(); - - CreateServiceInstanceResponseBuilder responseBuilder = CreateServiceInstanceResponse.builder(); - - given(createServiceInstanceWorkflow1.accept(request)) - .willReturn(Mono.just(true)); - given(createServiceInstanceWorkflow1.create(request, responseBuilder.build())) - .willReturn(Mono.error(new RuntimeException("create foo error"))); - given( - createServiceInstanceWorkflow1 - .buildResponse(eq(request), any(CreateServiceInstanceResponseBuilder.class))) - .willReturn(Mono.just(responseBuilder)); - - given(createServiceInstanceWorkflow2.accept(request)) - .willReturn(Mono.just(true)); - given(createServiceInstanceWorkflow2.create(request, responseBuilder.build())) - .willReturn(Mono.empty()); - given( - createServiceInstanceWorkflow2 - .buildResponse(eq(request), any(CreateServiceInstanceResponseBuilder.class))) - .willReturn(Mono.just(responseBuilder)); - - StepVerifier.create(workflowServiceInstanceService.createServiceInstance(request)) - .assertNext(response -> { - InOrder repoOrder = inOrder(serviceInstanceStateRepository); - repoOrder.verify(serviceInstanceStateRepository) - .saveState(eq("foo"), eq(OperationState.IN_PROGRESS), - eq("create service instance started")); - repoOrder.verify(serviceInstanceStateRepository) - .saveState(eq("foo"), eq(OperationState.FAILED), eq("create foo error")); - repoOrder.verifyNoMoreInteractions(); - - InOrder createOrder = inOrder(createServiceInstanceWorkflow1, createServiceInstanceWorkflow2); - createOrder.verify(createServiceInstanceWorkflow2).buildResponse(eq(request), - any(CreateServiceInstanceResponseBuilder.class)); - createOrder.verify(createServiceInstanceWorkflow1).buildResponse(eq(request), - any(CreateServiceInstanceResponseBuilder.class)); - createOrder.verify(createServiceInstanceWorkflow2).create(request, responseBuilder.build()); - createOrder.verify(createServiceInstanceWorkflow1).create(request, responseBuilder.build()); - createOrder.verifyNoMoreInteractions(); - - assertThat(response).isNotNull(); - }) - .verifyComplete(); - } - - @Test - void createServiceInstanceWithResponseError() { - CreateServiceInstanceRequest request = CreateServiceInstanceRequest.builder() - .serviceInstanceId("foo") - .build(); - - CreateServiceInstanceResponseBuilder responseBuilder = CreateServiceInstanceResponse.builder(); - - given(createServiceInstanceWorkflow1.accept(request)) - .willReturn(Mono.just(true)); - given( - createServiceInstanceWorkflow1 - .buildResponse(eq(request), any(CreateServiceInstanceResponseBuilder.class))) - .willReturn(Mono.error(new ServiceBrokerException("create foo error"))); - - given(createServiceInstanceWorkflow2.accept(request)) - .willReturn(Mono.just(true)); - given( - createServiceInstanceWorkflow2 - .buildResponse(eq(request), any(CreateServiceInstanceResponseBuilder.class))) - .willReturn(Mono.just(responseBuilder)); - - StepVerifier.create(workflowServiceInstanceService.createServiceInstance(request)) - .expectErrorSatisfies(e -> assertThat(e) - .isInstanceOf(ServiceBrokerException.class) - .hasMessage("create foo error")) - .verify(); - } - - @Test - void createServiceInstanceWithNoAcceptsDoesNothing() { - given(serviceInstanceStateRepository.saveState(anyString(), any(OperationState.class), anyString())) - .willReturn( - Mono.just( - new ServiceInstanceState(OperationState.IN_PROGRESS, "create service instance started", - new Timestamp(Instant.now().minusSeconds(60).toEpochMilli())))) - .willReturn( - Mono.just( - new ServiceInstanceState(OperationState.SUCCEEDED, "create service instance completed", - new Timestamp(Instant.now().minusSeconds(30).toEpochMilli())))); - - CreateServiceInstanceRequest request = CreateServiceInstanceRequest.builder() - .serviceInstanceId("foo") - .build(); - - given(createServiceInstanceWorkflow1.accept(request)) - .willReturn(Mono.just(false)); - - given(createServiceInstanceWorkflow2.accept(request)) - .willReturn(Mono.just(false)); - - StepVerifier.create(workflowServiceInstanceService.createServiceInstance(request)) - .assertNext(response -> { - InOrder repoOrder = inOrder(serviceInstanceStateRepository); - repoOrder.verify(serviceInstanceStateRepository) - .saveState(eq("foo"), eq(OperationState.IN_PROGRESS), - eq("create service instance started")); - repoOrder.verify(serviceInstanceStateRepository) - .saveState(eq("foo"), eq(OperationState.SUCCEEDED), - eq("create service instance completed")); - repoOrder.verifyNoMoreInteractions(); - - then(createServiceInstanceWorkflow1).shouldHaveNoMoreInteractions(); - then(createServiceInstanceWorkflow2).shouldHaveNoMoreInteractions(); - - assertThat(response).isNotNull(); - }) - .verifyComplete(); - } - - @Test - void deleteServiceInstance() { - given(serviceInstanceStateRepository.saveState(anyString(), any(OperationState.class), anyString())) - .willReturn( - Mono.just( - new ServiceInstanceState(OperationState.IN_PROGRESS, "delete service instance started", - new Timestamp(Instant.now().minusSeconds(60).toEpochMilli())))) - .willReturn( - Mono.just( - new ServiceInstanceState(OperationState.SUCCEEDED, "delete service instance completed", - new Timestamp(Instant.now().minusSeconds(30).toEpochMilli())))); - - DeleteServiceInstanceRequest request = DeleteServiceInstanceRequest.builder() - .serviceInstanceId("foo") - .build(); - - DeleteServiceInstanceResponseBuilder responseBuilder = DeleteServiceInstanceResponse.builder(); - DeleteServiceInstanceResponse builtResponse = DeleteServiceInstanceResponse.builder() - .async(true) - .operation("working2") - .build(); - - TestPublisher lowerOrderFlow = TestPublisher.create(); - TestPublisher higherOrderFlow = TestPublisher.create(); - - given(deleteServiceInstanceWorkflow1.accept(request)) - .willReturn(Mono.just(true)); - given( - deleteServiceInstanceWorkflow1 - .buildResponse(eq(request), any(DeleteServiceInstanceResponseBuilder.class))) - .willReturn(Mono.just(responseBuilder - .async(true) - .operation("working1"))); - given(deleteServiceInstanceWorkflow1.delete(eq(request), eq(builtResponse))) - .willReturn(lowerOrderFlow.mono()); - - given(deleteServiceInstanceWorkflow2.accept(request)) - .willReturn(Mono.just(true)); - given( - deleteServiceInstanceWorkflow2 - .buildResponse(eq(request), any(DeleteServiceInstanceResponseBuilder.class))) - .willReturn(Mono.just(responseBuilder - .operation("working2"))); - given(deleteServiceInstanceWorkflow2.delete(eq(request), eq(builtResponse))) - .willReturn(higherOrderFlow.mono()); - - StepVerifier.create(workflowServiceInstanceService.deleteServiceInstance(request)) - .assertNext(response -> { - InOrder repoOrder = inOrder(serviceInstanceStateRepository); - repoOrder.verify(serviceInstanceStateRepository) - .saveState(eq("foo"), eq(OperationState.IN_PROGRESS), - eq("delete service instance started")); - repoOrder.verify(serviceInstanceStateRepository) - .saveState(eq("foo"), eq(OperationState.SUCCEEDED), - eq("delete service instance completed")); - repoOrder.verifyNoMoreInteractions(); - - lowerOrderFlow.complete(); - lowerOrderFlow.assertWasNotRequested(); - - higherOrderFlow.complete(); - lowerOrderFlow.assertWasRequested(); - - InOrder deleteOrder = inOrder(deleteServiceInstanceWorkflow1, deleteServiceInstanceWorkflow2); - deleteOrder.verify(deleteServiceInstanceWorkflow2).buildResponse(eq(request), - any(DeleteServiceInstanceResponseBuilder.class)); - deleteOrder.verify(deleteServiceInstanceWorkflow1).buildResponse(eq(request), - any(DeleteServiceInstanceResponseBuilder.class)); - deleteOrder.verify(deleteServiceInstanceWorkflow2).delete(request, responseBuilder.build()); - deleteOrder.verify(deleteServiceInstanceWorkflow1).delete(request, responseBuilder.build()); - deleteOrder.verifyNoMoreInteractions(); - - assertThat(response).isNotNull(); - assertThat(response.isAsync()).isTrue(); - assertThat(response.getOperation()).isEqualTo("working2"); - }) - .verifyComplete(); - } - - @Test - void deleteServiceInstanceWithAsyncError() { - given(serviceInstanceStateRepository.saveState(anyString(), any(OperationState.class), anyString())) - .willReturn( - Mono.just( - new ServiceInstanceState(OperationState.IN_PROGRESS, "delete service instance started", - new Timestamp(Instant.now().minusSeconds(60).toEpochMilli())))) - .willReturn(Mono.just(new ServiceInstanceState(OperationState.FAILED, "delete service instance failed", - new Timestamp(Instant.now().minusSeconds(30).toEpochMilli())))); - - DeleteServiceInstanceRequest request = DeleteServiceInstanceRequest.builder() - .serviceInstanceId("foo") - .build(); - - DeleteServiceInstanceResponseBuilder responseBuilder = DeleteServiceInstanceResponse.builder(); - - given(deleteServiceInstanceWorkflow1.accept(request)) - .willReturn(Mono.just(true)); - given(deleteServiceInstanceWorkflow1.delete(request, responseBuilder.build())) - .willReturn(Mono.error(new RuntimeException("delete foo error"))); - given( - deleteServiceInstanceWorkflow1 - .buildResponse(eq(request), any(DeleteServiceInstanceResponseBuilder.class))) - .willReturn(Mono.just(responseBuilder)); - - given(deleteServiceInstanceWorkflow2.accept(request)) - .willReturn(Mono.just(true)); - given(deleteServiceInstanceWorkflow2.delete(request, responseBuilder.build())) - .willReturn(Mono.empty()); - given( - deleteServiceInstanceWorkflow2 - .buildResponse(eq(request), any(DeleteServiceInstanceResponseBuilder.class))) - .willReturn(Mono.just(responseBuilder)); - - StepVerifier.create(workflowServiceInstanceService.deleteServiceInstance(request)) - .assertNext(response -> { - InOrder repoOrder = inOrder(serviceInstanceStateRepository); - repoOrder.verify(serviceInstanceStateRepository) - .saveState(eq("foo"), eq(OperationState.IN_PROGRESS), - eq("delete service instance started")); - repoOrder.verify(serviceInstanceStateRepository) - .saveState(eq("foo"), eq(OperationState.FAILED), eq("delete foo error")); - repoOrder.verifyNoMoreInteractions(); - - InOrder deleteOrder = inOrder(deleteServiceInstanceWorkflow1, deleteServiceInstanceWorkflow2); - deleteOrder.verify(deleteServiceInstanceWorkflow2).buildResponse(eq(request), - any(DeleteServiceInstanceResponseBuilder.class)); - deleteOrder.verify(deleteServiceInstanceWorkflow1).buildResponse(eq(request), - any(DeleteServiceInstanceResponseBuilder.class)); - deleteOrder.verify(deleteServiceInstanceWorkflow2).delete(request, responseBuilder.build()); - deleteOrder.verify(deleteServiceInstanceWorkflow1).delete(request, responseBuilder.build()); - deleteOrder.verifyNoMoreInteractions(); - - assertThat(response).isNotNull(); - }) - .verifyComplete(); - } - - @Test - void deleteServiceInstanceWithResponseError() { - DeleteServiceInstanceRequest request = DeleteServiceInstanceRequest.builder() - .serviceInstanceId("foo") - .build(); - - DeleteServiceInstanceResponseBuilder responseBuilder = DeleteServiceInstanceResponse.builder(); - - given(deleteServiceInstanceWorkflow1.accept(request)) - .willReturn(Mono.just(true)); - given( - deleteServiceInstanceWorkflow1 - .buildResponse(eq(request), any(DeleteServiceInstanceResponseBuilder.class))) - .willReturn(Mono.error(new ServiceBrokerException("delete foo error"))); - - given(deleteServiceInstanceWorkflow2.accept(request)) - .willReturn(Mono.just(true)); - given( - deleteServiceInstanceWorkflow2 - .buildResponse(eq(request), any(DeleteServiceInstanceResponseBuilder.class))) - .willReturn(Mono.just(responseBuilder)); - - StepVerifier.create(workflowServiceInstanceService.deleteServiceInstance(request)) - .expectErrorSatisfies(e -> assertThat(e) - .isInstanceOf(ServiceBrokerException.class) - .hasMessage("delete foo error")) - .verify(); - } - - @Test - void deleteServiceInstanceWithNoAcceptsDoesNothing() { - given(serviceInstanceStateRepository.saveState(anyString(), any(OperationState.class), anyString())) - .willReturn( - Mono.just( - new ServiceInstanceState(OperationState.IN_PROGRESS, "delete service instance started", - new Timestamp(Instant.now().minusSeconds(60).toEpochMilli())))) - .willReturn( - Mono.just( - new ServiceInstanceState(OperationState.SUCCEEDED, "delete service instance completed", - new Timestamp(Instant.now().minusSeconds(30).toEpochMilli())))); - - DeleteServiceInstanceRequest request = DeleteServiceInstanceRequest.builder() - .serviceInstanceId("foo") - .build(); - - given(deleteServiceInstanceWorkflow1.accept(request)) - .willReturn(Mono.just(false)); - - given(deleteServiceInstanceWorkflow2.accept(request)) - .willReturn(Mono.just(false)); - - StepVerifier.create(workflowServiceInstanceService.deleteServiceInstance(request)) - .assertNext(response -> { - InOrder repoOrder = inOrder(serviceInstanceStateRepository); - repoOrder.verify(serviceInstanceStateRepository) - .saveState(eq("foo"), eq(OperationState.IN_PROGRESS), - eq("delete service instance started")); - repoOrder.verify(serviceInstanceStateRepository) - .saveState(eq("foo"), eq(OperationState.SUCCEEDED), - eq("delete service instance completed")); - repoOrder.verifyNoMoreInteractions(); - - then(createServiceInstanceWorkflow1).shouldHaveNoMoreInteractions(); - then(createServiceInstanceWorkflow2).shouldHaveNoMoreInteractions(); - - assertThat(response).isNotNull(); - }) - .verifyComplete(); - } - - @Test - void updateServiceInstance() { - given(serviceInstanceStateRepository.saveState(anyString(), any(OperationState.class), anyString())) - .willReturn( - Mono.just( - new ServiceInstanceState(OperationState.IN_PROGRESS, "update service instance started", - new Timestamp(Instant.now().minusSeconds(60).toEpochMilli())))) - .willReturn( - Mono.just( - new ServiceInstanceState(OperationState.SUCCEEDED, "update service instance completed", - new Timestamp(Instant.now().minusSeconds(30).toEpochMilli())))); - - UpdateServiceInstanceRequest request = UpdateServiceInstanceRequest.builder() - .serviceInstanceId("foo") - .build(); - - UpdateServiceInstanceResponseBuilder responseBuilder = UpdateServiceInstanceResponse.builder(); - UpdateServiceInstanceResponse builtResponse = UpdateServiceInstanceResponse.builder() - .async(true) - .dashboardUrl("https://dashboard.example.local") - .operation("working2") - .build(); - - TestPublisher lowerOrderFlow = TestPublisher.create(); - TestPublisher higherOrderFlow = TestPublisher.create(); - - given(updateServiceInstanceWorkflow1.accept(request)) - .willReturn(Mono.just(true)); - given( - updateServiceInstanceWorkflow1 - .buildResponse(eq(request), any(UpdateServiceInstanceResponseBuilder.class))) - .willReturn(Mono.just(responseBuilder - .async(true) - .operation("working1"))); - given(updateServiceInstanceWorkflow1.update(eq(request), eq(builtResponse))) - .willReturn(lowerOrderFlow.mono()); - - given(updateServiceInstanceWorkflow2.accept(request)) - .willReturn(Mono.just(true)); - given( - updateServiceInstanceWorkflow2 - .buildResponse(eq(request), any(UpdateServiceInstanceResponseBuilder.class))) - .willReturn(Mono.just(responseBuilder - .dashboardUrl("https://dashboard.example.local") - .operation("working2"))); - given(updateServiceInstanceWorkflow2.update(eq(request), eq(builtResponse))) - .willReturn(higherOrderFlow.mono()); - - StepVerifier.create(workflowServiceInstanceService.updateServiceInstance(request)) - .assertNext(response -> { - InOrder repoOrder = inOrder(serviceInstanceStateRepository); - repoOrder.verify(serviceInstanceStateRepository) - .saveState(eq("foo"), eq(OperationState.IN_PROGRESS), - eq("update service instance started")); - repoOrder.verify(serviceInstanceStateRepository) - .saveState(eq("foo"), eq(OperationState.SUCCEEDED), - eq("update service instance completed")); - repoOrder.verifyNoMoreInteractions(); - - lowerOrderFlow.complete(); - lowerOrderFlow.assertWasNotRequested(); - - higherOrderFlow.complete(); - lowerOrderFlow.assertWasRequested(); - - InOrder updateOrder = inOrder(updateServiceInstanceWorkflow1, updateServiceInstanceWorkflow2); - updateOrder.verify(updateServiceInstanceWorkflow2).buildResponse(eq(request), - any(UpdateServiceInstanceResponseBuilder.class)); - updateOrder.verify(updateServiceInstanceWorkflow1).buildResponse(eq(request), - any(UpdateServiceInstanceResponseBuilder.class)); - updateOrder.verify(updateServiceInstanceWorkflow2).update(request, builtResponse); - updateOrder.verify(updateServiceInstanceWorkflow1).update(request, builtResponse); - updateOrder.verifyNoMoreInteractions(); - - assertThat(response).isNotNull(); - assertThat(response.isAsync()).isTrue(); - assertThat(response.getDashboardUrl()).isEqualTo("https://dashboard.example.local"); - assertThat(response.getOperation()).isEqualTo("working2"); - }) - .verifyComplete(); - } - - @Test - void updateServiceInstanceWithAsyncError() { - given(serviceInstanceStateRepository.saveState(anyString(), any(OperationState.class), anyString())) - .willReturn( - Mono.just( - new ServiceInstanceState(OperationState.IN_PROGRESS, "update service instance started", - new Timestamp(Instant.now().minusSeconds(60).toEpochMilli())))) - .willReturn(Mono.just(new ServiceInstanceState(OperationState.FAILED, "update service instance failed", - new Timestamp(Instant.now().minusSeconds(30).toEpochMilli())))); - - UpdateServiceInstanceRequest request = UpdateServiceInstanceRequest.builder() - .serviceInstanceId("foo") - .build(); - - UpdateServiceInstanceResponseBuilder responseBuilder = UpdateServiceInstanceResponse.builder(); - - given(updateServiceInstanceWorkflow1.accept(request)) - .willReturn(Mono.just(true)); - given(updateServiceInstanceWorkflow1.update(request, responseBuilder.build())) - .willReturn(Mono.error(new RuntimeException("update foo error"))); - given( - updateServiceInstanceWorkflow1 - .buildResponse(eq(request), any(UpdateServiceInstanceResponseBuilder.class))) - .willReturn(Mono.just(responseBuilder)); - - given(updateServiceInstanceWorkflow2.accept(request)) - .willReturn(Mono.just(true)); - given(updateServiceInstanceWorkflow2.update(request, responseBuilder.build())) - .willReturn(Mono.empty()); - given( - updateServiceInstanceWorkflow2 - .buildResponse(eq(request), any(UpdateServiceInstanceResponseBuilder.class))) - .willReturn(Mono.just(responseBuilder)); - - StepVerifier.create(workflowServiceInstanceService.updateServiceInstance(request)) - .assertNext(response -> { - InOrder repoOrder = inOrder(serviceInstanceStateRepository); - repoOrder.verify(serviceInstanceStateRepository) - .saveState(eq("foo"), eq(OperationState.IN_PROGRESS), - eq("update service instance started")); - repoOrder.verify(serviceInstanceStateRepository) - .saveState(eq("foo"), eq(OperationState.FAILED), eq("update foo error")); - repoOrder.verifyNoMoreInteractions(); - - InOrder updateOrder = inOrder(updateServiceInstanceWorkflow1, updateServiceInstanceWorkflow2); - updateOrder.verify(updateServiceInstanceWorkflow2).buildResponse(eq(request), - any(UpdateServiceInstanceResponseBuilder.class)); - updateOrder.verify(updateServiceInstanceWorkflow1).buildResponse(eq(request), - any(UpdateServiceInstanceResponseBuilder.class)); - updateOrder.verify(updateServiceInstanceWorkflow2).update(request, responseBuilder.build()); - updateOrder.verify(updateServiceInstanceWorkflow1).update(request, responseBuilder.build()); - updateOrder.verifyNoMoreInteractions(); - - assertThat(response).isNotNull(); - }) - .verifyComplete(); - } - - @Test - void updateServiceInstanceWithResponseError() { - UpdateServiceInstanceRequest request = UpdateServiceInstanceRequest.builder() - .serviceInstanceId("foo") - .build(); - - UpdateServiceInstanceResponseBuilder responseBuilder = UpdateServiceInstanceResponse.builder(); - - given(updateServiceInstanceWorkflow1.accept(request)) - .willReturn(Mono.just(true)); - given( - updateServiceInstanceWorkflow1 - .buildResponse(eq(request), any(UpdateServiceInstanceResponseBuilder.class))) - .willReturn(Mono.error(new ServiceBrokerException("update foo error"))); - - given(updateServiceInstanceWorkflow2.accept(request)) - .willReturn(Mono.just(true)); - given( - updateServiceInstanceWorkflow2 - .buildResponse(eq(request), any(UpdateServiceInstanceResponseBuilder.class))) - .willReturn(Mono.just(responseBuilder)); - - StepVerifier.create(workflowServiceInstanceService.updateServiceInstance(request)) - .expectErrorSatisfies(e -> assertThat(e) - .isInstanceOf(ServiceBrokerException.class) - .hasMessage("update foo error")) - .verify(); - } - - @Test - void updateServiceInstanceWithNoAcceptsDoesNothing() { - given(serviceInstanceStateRepository.saveState(anyString(), any(OperationState.class), anyString())) - .willReturn( - Mono.just( - new ServiceInstanceState(OperationState.IN_PROGRESS, "update service instance started", - new Timestamp(Instant.now().minusSeconds(60).toEpochMilli())))) - .willReturn( - Mono.just( - new ServiceInstanceState(OperationState.SUCCEEDED, "update service instance completed", - new Timestamp(Instant.now().minusSeconds(30).toEpochMilli())))); - - UpdateServiceInstanceRequest request = UpdateServiceInstanceRequest.builder() - .serviceInstanceId("foo") - .build(); - - given(updateServiceInstanceWorkflow1.accept(request)) - .willReturn(Mono.just(false)); - - given(updateServiceInstanceWorkflow2.accept(request)) - .willReturn(Mono.just(false)); - - StepVerifier.create(workflowServiceInstanceService.updateServiceInstance(request)) - .assertNext(response -> { - InOrder repoOrder = inOrder(serviceInstanceStateRepository); - repoOrder.verify(serviceInstanceStateRepository) - .saveState(eq("foo"), eq(OperationState.IN_PROGRESS), - eq("update service instance started")); - repoOrder.verify(serviceInstanceStateRepository) - .saveState(eq("foo"), eq(OperationState.SUCCEEDED), - eq("update service instance completed")); - repoOrder.verifyNoMoreInteractions(); - - then(updateServiceInstanceWorkflow1).shouldHaveNoMoreInteractions(); - then(updateServiceInstanceWorkflow2).shouldHaveNoMoreInteractions(); - - assertThat(response).isNotNull(); - }) - .verifyComplete(); - } - - @Order(Ordered.HIGHEST_PRECEDENCE) - private interface HighOrderCreateServiceInstanceWorkflow extends CreateServiceInstanceWorkflow { - } - - @Order - private interface LowOrderCreateServiceInstanceWorkflow extends CreateServiceInstanceWorkflow { - } - - @Order(Ordered.HIGHEST_PRECEDENCE) - private interface HighOrderDeleteServiceInstanceWorkflow extends DeleteServiceInstanceWorkflow { - } - - @Order - private interface LowOrderDeleteServiceInstanceWorkflow extends DeleteServiceInstanceWorkflow { - } - - @Order(Ordered.HIGHEST_PRECEDENCE) - private interface HighOrderUpdateServiceInstanceWorkflow extends UpdateServiceInstanceWorkflow { - } - - @Order - private interface LowOrderUpdateServiceInstanceWorkflow extends UpdateServiceInstanceWorkflow { - } - -} diff --git a/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/service/WorkflowServiceInstanceServiceTests.java b/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/service/WorkflowServiceInstanceServiceTests.java new file mode 100644 index 0000000..42b309a --- /dev/null +++ b/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/service/WorkflowServiceInstanceServiceTests.java @@ -0,0 +1,626 @@ +/* + * Copyright 2016-2020 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.cloud.appbroker.service; + +import java.sql.Timestamp; +import java.time.Instant; +import java.util.Arrays; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InOrder; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; +import reactor.test.publisher.TestPublisher; + +import org.springframework.cloud.appbroker.state.ServiceInstanceState; +import org.springframework.cloud.appbroker.state.ServiceInstanceStateRepository; +import org.springframework.cloud.servicebroker.exception.ServiceBrokerException; +import org.springframework.cloud.servicebroker.model.instance.CreateServiceInstanceRequest; +import org.springframework.cloud.servicebroker.model.instance.CreateServiceInstanceResponse; +import org.springframework.cloud.servicebroker.model.instance.CreateServiceInstanceResponse.CreateServiceInstanceResponseBuilder; +import org.springframework.cloud.servicebroker.model.instance.DeleteServiceInstanceRequest; +import org.springframework.cloud.servicebroker.model.instance.DeleteServiceInstanceResponse; +import org.springframework.cloud.servicebroker.model.instance.DeleteServiceInstanceResponse.DeleteServiceInstanceResponseBuilder; +import org.springframework.cloud.servicebroker.model.instance.OperationState; +import org.springframework.cloud.servicebroker.model.instance.UpdateServiceInstanceRequest; +import org.springframework.cloud.servicebroker.model.instance.UpdateServiceInstanceResponse; +import org.springframework.cloud.servicebroker.model.instance.UpdateServiceInstanceResponse.UpdateServiceInstanceResponseBuilder; +import org.springframework.core.Ordered; +import org.springframework.core.annotation.Order; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.BDDMockito.given; +import static org.mockito.BDDMockito.then; +import static org.mockito.Mockito.inOrder; + +@ExtendWith(MockitoExtension.class) +class WorkflowServiceInstanceServiceTests { + + @Mock + private ServiceInstanceStateRepository serviceInstanceStateRepository; + + @Mock + private LowOrderCreateServiceInstanceWorkflow createServiceInstanceWorkflow1; + + @Mock + private HighOrderCreateServiceInstanceWorkflow createServiceInstanceWorkflow2; + + @Mock + private LowOrderDeleteServiceInstanceWorkflow deleteServiceInstanceWorkflow1; + + @Mock + private HighOrderDeleteServiceInstanceWorkflow deleteServiceInstanceWorkflow2; + + @Mock + private LowOrderUpdateServiceInstanceWorkflow updateServiceInstanceWorkflow1; + + @Mock + private HighOrderUpdateServiceInstanceWorkflow updateServiceInstanceWorkflow2; + + private WorkflowServiceInstanceService workflowServiceInstanceService; + + @BeforeEach + void setUp() { + this.workflowServiceInstanceService = new WorkflowServiceInstanceService(this.serviceInstanceStateRepository, + Arrays.asList(this.createServiceInstanceWorkflow1, this.createServiceInstanceWorkflow2), + Arrays.asList(this.deleteServiceInstanceWorkflow1, this.deleteServiceInstanceWorkflow2), + Arrays.asList(this.updateServiceInstanceWorkflow1, this.updateServiceInstanceWorkflow2)); + } + + @Test + void createServiceInstance() { + given(this.serviceInstanceStateRepository.saveState(anyString(), any(OperationState.class), anyString())) + .willReturn(Mono.just(new ServiceInstanceState(OperationState.IN_PROGRESS, + "create service instance started", new Timestamp(Instant.now().minusSeconds(60).toEpochMilli())))) + .willReturn( + Mono.just(new ServiceInstanceState(OperationState.SUCCEEDED, "create service instance completed", + new Timestamp(Instant.now().minusSeconds(300).toEpochMilli())))); + + CreateServiceInstanceRequest request = CreateServiceInstanceRequest.builder().serviceInstanceId("foo").build(); + + CreateServiceInstanceResponseBuilder responseBuilder = CreateServiceInstanceResponse.builder(); + CreateServiceInstanceResponse builtResponse = CreateServiceInstanceResponse.builder() + .async(true) + .dashboardUrl("https://dashboard.example.local") + .operation("working2") + .build(); + + TestPublisher lowerOrderFlow = TestPublisher.create(); + TestPublisher higherOrderFlow = TestPublisher.create(); + + given(this.createServiceInstanceWorkflow1.accept(request)).willReturn(Mono.just(true)); + given(this.createServiceInstanceWorkflow1.create(eq(request), eq(builtResponse))) + .willReturn(lowerOrderFlow.mono()); + given(this.createServiceInstanceWorkflow1.buildResponse(eq(request), + any(CreateServiceInstanceResponseBuilder.class))) + .willReturn(Mono.just(responseBuilder.async(true).operation("working1"))); + + given(this.createServiceInstanceWorkflow2.accept(request)).willReturn(Mono.just(true)); + given(this.createServiceInstanceWorkflow2.create(eq(request), eq(builtResponse))) + .willReturn(higherOrderFlow.mono()); + given(this.createServiceInstanceWorkflow2 + .buildResponse(eq(request), any(CreateServiceInstanceResponseBuilder.class))).willReturn( + Mono.just(responseBuilder.dashboardUrl("https://dashboard.example.local").operation("working2"))); + + StepVerifier.create(this.workflowServiceInstanceService.createServiceInstance(request)) + .assertNext((response) -> { + InOrder repoOrder = inOrder(this.serviceInstanceStateRepository); + repoOrder.verify(this.serviceInstanceStateRepository) + .saveState(eq("foo"), eq(OperationState.IN_PROGRESS), eq("create service instance started")); + repoOrder.verify(this.serviceInstanceStateRepository) + .saveState(eq("foo"), eq(OperationState.SUCCEEDED), eq("create service instance completed")); + repoOrder.verifyNoMoreInteractions(); + + lowerOrderFlow.complete(); + lowerOrderFlow.assertWasNotRequested(); + + higherOrderFlow.complete(); + lowerOrderFlow.assertWasRequested(); + + InOrder createOrder = inOrder(this.createServiceInstanceWorkflow1, this.createServiceInstanceWorkflow2); + createOrder.verify(this.createServiceInstanceWorkflow2) + .buildResponse(eq(request), any(CreateServiceInstanceResponseBuilder.class)); + createOrder.verify(this.createServiceInstanceWorkflow1) + .buildResponse(eq(request), any(CreateServiceInstanceResponseBuilder.class)); + createOrder.verify(this.createServiceInstanceWorkflow2).create(request, responseBuilder.build()); + createOrder.verify(this.createServiceInstanceWorkflow1).create(request, responseBuilder.build()); + createOrder.verifyNoMoreInteractions(); + + assertThat(response).isNotNull(); + assertThat(response.isAsync()).isTrue(); + assertThat(response.getDashboardUrl()).isEqualTo("https://dashboard.example.local"); + assertThat(response.getOperation()).isEqualTo("working2"); + }) + .verifyComplete(); + } + + @Test + void createServiceInstanceWithAsyncError() { + given(this.serviceInstanceStateRepository.saveState(anyString(), any(OperationState.class), anyString())) + .willReturn(Mono.just(new ServiceInstanceState(OperationState.IN_PROGRESS, + "create service instance started", new Timestamp(Instant.now().minusSeconds(60).toEpochMilli())))) + .willReturn(Mono.just(new ServiceInstanceState(OperationState.FAILED, "create service instance failed", + new Timestamp(Instant.now().minusSeconds(30).toEpochMilli())))); + + CreateServiceInstanceRequest request = CreateServiceInstanceRequest.builder().serviceInstanceId("foo").build(); + + CreateServiceInstanceResponseBuilder responseBuilder = CreateServiceInstanceResponse.builder(); + + given(this.createServiceInstanceWorkflow1.accept(request)).willReturn(Mono.just(true)); + given(this.createServiceInstanceWorkflow1.create(request, responseBuilder.build())) + .willReturn(Mono.error(new RuntimeException("create foo error"))); + given(this.createServiceInstanceWorkflow1.buildResponse(eq(request), + any(CreateServiceInstanceResponseBuilder.class))) + .willReturn(Mono.just(responseBuilder)); + + given(this.createServiceInstanceWorkflow2.accept(request)).willReturn(Mono.just(true)); + given(this.createServiceInstanceWorkflow2.create(request, responseBuilder.build())).willReturn(Mono.empty()); + given(this.createServiceInstanceWorkflow2.buildResponse(eq(request), + any(CreateServiceInstanceResponseBuilder.class))) + .willReturn(Mono.just(responseBuilder)); + + StepVerifier.create(this.workflowServiceInstanceService.createServiceInstance(request)) + .assertNext((response) -> { + InOrder repoOrder = inOrder(this.serviceInstanceStateRepository); + repoOrder.verify(this.serviceInstanceStateRepository) + .saveState(eq("foo"), eq(OperationState.IN_PROGRESS), eq("create service instance started")); + repoOrder.verify(this.serviceInstanceStateRepository) + .saveState(eq("foo"), eq(OperationState.FAILED), eq("create foo error")); + repoOrder.verifyNoMoreInteractions(); + + InOrder createOrder = inOrder(this.createServiceInstanceWorkflow1, this.createServiceInstanceWorkflow2); + createOrder.verify(this.createServiceInstanceWorkflow2) + .buildResponse(eq(request), any(CreateServiceInstanceResponseBuilder.class)); + createOrder.verify(this.createServiceInstanceWorkflow1) + .buildResponse(eq(request), any(CreateServiceInstanceResponseBuilder.class)); + createOrder.verify(this.createServiceInstanceWorkflow2).create(request, responseBuilder.build()); + createOrder.verify(this.createServiceInstanceWorkflow1).create(request, responseBuilder.build()); + createOrder.verifyNoMoreInteractions(); + + assertThat(response).isNotNull(); + }) + .verifyComplete(); + } + + @Test + void createServiceInstanceWithResponseError() { + CreateServiceInstanceRequest request = CreateServiceInstanceRequest.builder().serviceInstanceId("foo").build(); + + CreateServiceInstanceResponseBuilder responseBuilder = CreateServiceInstanceResponse.builder(); + + given(this.createServiceInstanceWorkflow1.accept(request)).willReturn(Mono.just(true)); + given(this.createServiceInstanceWorkflow1.buildResponse(eq(request), + any(CreateServiceInstanceResponseBuilder.class))) + .willReturn(Mono.error(new ServiceBrokerException("create foo error"))); + + given(this.createServiceInstanceWorkflow2.accept(request)).willReturn(Mono.just(true)); + given(this.createServiceInstanceWorkflow2.buildResponse(eq(request), + any(CreateServiceInstanceResponseBuilder.class))) + .willReturn(Mono.just(responseBuilder)); + + StepVerifier.create(this.workflowServiceInstanceService.createServiceInstance(request)) + .expectErrorSatisfies( + (e) -> assertThat(e).isInstanceOf(ServiceBrokerException.class).hasMessage("create foo error")) + .verify(); + } + + @Test + void createServiceInstanceWithNoAcceptsDoesNothing() { + given(this.serviceInstanceStateRepository.saveState(anyString(), any(OperationState.class), anyString())) + .willReturn(Mono.just(new ServiceInstanceState(OperationState.IN_PROGRESS, + "create service instance started", new Timestamp(Instant.now().minusSeconds(60).toEpochMilli())))) + .willReturn( + Mono.just(new ServiceInstanceState(OperationState.SUCCEEDED, "create service instance completed", + new Timestamp(Instant.now().minusSeconds(30).toEpochMilli())))); + + CreateServiceInstanceRequest request = CreateServiceInstanceRequest.builder().serviceInstanceId("foo").build(); + + given(this.createServiceInstanceWorkflow1.accept(request)).willReturn(Mono.just(false)); + + given(this.createServiceInstanceWorkflow2.accept(request)).willReturn(Mono.just(false)); + + StepVerifier.create(this.workflowServiceInstanceService.createServiceInstance(request)) + .assertNext((response) -> { + InOrder repoOrder = inOrder(this.serviceInstanceStateRepository); + repoOrder.verify(this.serviceInstanceStateRepository) + .saveState(eq("foo"), eq(OperationState.IN_PROGRESS), eq("create service instance started")); + repoOrder.verify(this.serviceInstanceStateRepository) + .saveState(eq("foo"), eq(OperationState.SUCCEEDED), eq("create service instance completed")); + repoOrder.verifyNoMoreInteractions(); + + then(this.createServiceInstanceWorkflow1).shouldHaveNoMoreInteractions(); + then(this.createServiceInstanceWorkflow2).shouldHaveNoMoreInteractions(); + + assertThat(response).isNotNull(); + }) + .verifyComplete(); + } + + @Test + void deleteServiceInstance() { + given(this.serviceInstanceStateRepository.saveState(anyString(), any(OperationState.class), anyString())) + .willReturn(Mono.just(new ServiceInstanceState(OperationState.IN_PROGRESS, + "delete service instance started", new Timestamp(Instant.now().minusSeconds(60).toEpochMilli())))) + .willReturn( + Mono.just(new ServiceInstanceState(OperationState.SUCCEEDED, "delete service instance completed", + new Timestamp(Instant.now().minusSeconds(30).toEpochMilli())))); + + DeleteServiceInstanceRequest request = DeleteServiceInstanceRequest.builder().serviceInstanceId("foo").build(); + + DeleteServiceInstanceResponseBuilder responseBuilder = DeleteServiceInstanceResponse.builder(); + DeleteServiceInstanceResponse builtResponse = DeleteServiceInstanceResponse.builder() + .async(true) + .operation("working2") + .build(); + + TestPublisher lowerOrderFlow = TestPublisher.create(); + TestPublisher higherOrderFlow = TestPublisher.create(); + + given(this.deleteServiceInstanceWorkflow1.accept(request)).willReturn(Mono.just(true)); + given(this.deleteServiceInstanceWorkflow1.buildResponse(eq(request), + any(DeleteServiceInstanceResponseBuilder.class))) + .willReturn(Mono.just(responseBuilder.async(true).operation("working1"))); + given(this.deleteServiceInstanceWorkflow1.delete(eq(request), eq(builtResponse))) + .willReturn(lowerOrderFlow.mono()); + + given(this.deleteServiceInstanceWorkflow2.accept(request)).willReturn(Mono.just(true)); + given(this.deleteServiceInstanceWorkflow2.buildResponse(eq(request), + any(DeleteServiceInstanceResponseBuilder.class))) + .willReturn(Mono.just(responseBuilder.operation("working2"))); + given(this.deleteServiceInstanceWorkflow2.delete(eq(request), eq(builtResponse))) + .willReturn(higherOrderFlow.mono()); + + StepVerifier.create(this.workflowServiceInstanceService.deleteServiceInstance(request)) + .assertNext((response) -> { + InOrder repoOrder = inOrder(this.serviceInstanceStateRepository); + repoOrder.verify(this.serviceInstanceStateRepository) + .saveState(eq("foo"), eq(OperationState.IN_PROGRESS), eq("delete service instance started")); + repoOrder.verify(this.serviceInstanceStateRepository) + .saveState(eq("foo"), eq(OperationState.SUCCEEDED), eq("delete service instance completed")); + repoOrder.verifyNoMoreInteractions(); + + lowerOrderFlow.complete(); + lowerOrderFlow.assertWasNotRequested(); + + higherOrderFlow.complete(); + lowerOrderFlow.assertWasRequested(); + + InOrder deleteOrder = inOrder(this.deleteServiceInstanceWorkflow1, this.deleteServiceInstanceWorkflow2); + deleteOrder.verify(this.deleteServiceInstanceWorkflow2) + .buildResponse(eq(request), any(DeleteServiceInstanceResponseBuilder.class)); + deleteOrder.verify(this.deleteServiceInstanceWorkflow1) + .buildResponse(eq(request), any(DeleteServiceInstanceResponseBuilder.class)); + deleteOrder.verify(this.deleteServiceInstanceWorkflow2).delete(request, responseBuilder.build()); + deleteOrder.verify(this.deleteServiceInstanceWorkflow1).delete(request, responseBuilder.build()); + deleteOrder.verifyNoMoreInteractions(); + + assertThat(response).isNotNull(); + assertThat(response.isAsync()).isTrue(); + assertThat(response.getOperation()).isEqualTo("working2"); + }) + .verifyComplete(); + } + + @Test + void deleteServiceInstanceWithAsyncError() { + given(this.serviceInstanceStateRepository.saveState(anyString(), any(OperationState.class), anyString())) + .willReturn(Mono.just(new ServiceInstanceState(OperationState.IN_PROGRESS, + "delete service instance started", new Timestamp(Instant.now().minusSeconds(60).toEpochMilli())))) + .willReturn(Mono.just(new ServiceInstanceState(OperationState.FAILED, "delete service instance failed", + new Timestamp(Instant.now().minusSeconds(30).toEpochMilli())))); + + DeleteServiceInstanceRequest request = DeleteServiceInstanceRequest.builder().serviceInstanceId("foo").build(); + + DeleteServiceInstanceResponseBuilder responseBuilder = DeleteServiceInstanceResponse.builder(); + + given(this.deleteServiceInstanceWorkflow1.accept(request)).willReturn(Mono.just(true)); + given(this.deleteServiceInstanceWorkflow1.delete(request, responseBuilder.build())) + .willReturn(Mono.error(new RuntimeException("delete foo error"))); + given(this.deleteServiceInstanceWorkflow1.buildResponse(eq(request), + any(DeleteServiceInstanceResponseBuilder.class))) + .willReturn(Mono.just(responseBuilder)); + + given(this.deleteServiceInstanceWorkflow2.accept(request)).willReturn(Mono.just(true)); + given(this.deleteServiceInstanceWorkflow2.delete(request, responseBuilder.build())).willReturn(Mono.empty()); + given(this.deleteServiceInstanceWorkflow2.buildResponse(eq(request), + any(DeleteServiceInstanceResponseBuilder.class))) + .willReturn(Mono.just(responseBuilder)); + + StepVerifier.create(this.workflowServiceInstanceService.deleteServiceInstance(request)) + .assertNext((response) -> { + InOrder repoOrder = inOrder(this.serviceInstanceStateRepository); + repoOrder.verify(this.serviceInstanceStateRepository) + .saveState(eq("foo"), eq(OperationState.IN_PROGRESS), eq("delete service instance started")); + repoOrder.verify(this.serviceInstanceStateRepository) + .saveState(eq("foo"), eq(OperationState.FAILED), eq("delete foo error")); + repoOrder.verifyNoMoreInteractions(); + + InOrder deleteOrder = inOrder(this.deleteServiceInstanceWorkflow1, this.deleteServiceInstanceWorkflow2); + deleteOrder.verify(this.deleteServiceInstanceWorkflow2) + .buildResponse(eq(request), any(DeleteServiceInstanceResponseBuilder.class)); + deleteOrder.verify(this.deleteServiceInstanceWorkflow1) + .buildResponse(eq(request), any(DeleteServiceInstanceResponseBuilder.class)); + deleteOrder.verify(this.deleteServiceInstanceWorkflow2).delete(request, responseBuilder.build()); + deleteOrder.verify(this.deleteServiceInstanceWorkflow1).delete(request, responseBuilder.build()); + deleteOrder.verifyNoMoreInteractions(); + + assertThat(response).isNotNull(); + }) + .verifyComplete(); + } + + @Test + void deleteServiceInstanceWithResponseError() { + DeleteServiceInstanceRequest request = DeleteServiceInstanceRequest.builder().serviceInstanceId("foo").build(); + + DeleteServiceInstanceResponseBuilder responseBuilder = DeleteServiceInstanceResponse.builder(); + + given(this.deleteServiceInstanceWorkflow1.accept(request)).willReturn(Mono.just(true)); + given(this.deleteServiceInstanceWorkflow1.buildResponse(eq(request), + any(DeleteServiceInstanceResponseBuilder.class))) + .willReturn(Mono.error(new ServiceBrokerException("delete foo error"))); + + given(this.deleteServiceInstanceWorkflow2.accept(request)).willReturn(Mono.just(true)); + given(this.deleteServiceInstanceWorkflow2.buildResponse(eq(request), + any(DeleteServiceInstanceResponseBuilder.class))) + .willReturn(Mono.just(responseBuilder)); + + StepVerifier.create(this.workflowServiceInstanceService.deleteServiceInstance(request)) + .expectErrorSatisfies( + (e) -> assertThat(e).isInstanceOf(ServiceBrokerException.class).hasMessage("delete foo error")) + .verify(); + } + + @Test + void deleteServiceInstanceWithNoAcceptsDoesNothing() { + given(this.serviceInstanceStateRepository.saveState(anyString(), any(OperationState.class), anyString())) + .willReturn(Mono.just(new ServiceInstanceState(OperationState.IN_PROGRESS, + "delete service instance started", new Timestamp(Instant.now().minusSeconds(60).toEpochMilli())))) + .willReturn( + Mono.just(new ServiceInstanceState(OperationState.SUCCEEDED, "delete service instance completed", + new Timestamp(Instant.now().minusSeconds(30).toEpochMilli())))); + + DeleteServiceInstanceRequest request = DeleteServiceInstanceRequest.builder().serviceInstanceId("foo").build(); + + given(this.deleteServiceInstanceWorkflow1.accept(request)).willReturn(Mono.just(false)); + + given(this.deleteServiceInstanceWorkflow2.accept(request)).willReturn(Mono.just(false)); + + StepVerifier.create(this.workflowServiceInstanceService.deleteServiceInstance(request)) + .assertNext((response) -> { + InOrder repoOrder = inOrder(this.serviceInstanceStateRepository); + repoOrder.verify(this.serviceInstanceStateRepository) + .saveState(eq("foo"), eq(OperationState.IN_PROGRESS), eq("delete service instance started")); + repoOrder.verify(this.serviceInstanceStateRepository) + .saveState(eq("foo"), eq(OperationState.SUCCEEDED), eq("delete service instance completed")); + repoOrder.verifyNoMoreInteractions(); + + then(this.createServiceInstanceWorkflow1).shouldHaveNoMoreInteractions(); + then(this.createServiceInstanceWorkflow2).shouldHaveNoMoreInteractions(); + + assertThat(response).isNotNull(); + }) + .verifyComplete(); + } + + @Test + void updateServiceInstance() { + given(this.serviceInstanceStateRepository.saveState(anyString(), any(OperationState.class), anyString())) + .willReturn(Mono.just(new ServiceInstanceState(OperationState.IN_PROGRESS, + "update service instance started", new Timestamp(Instant.now().minusSeconds(60).toEpochMilli())))) + .willReturn( + Mono.just(new ServiceInstanceState(OperationState.SUCCEEDED, "update service instance completed", + new Timestamp(Instant.now().minusSeconds(30).toEpochMilli())))); + + UpdateServiceInstanceRequest request = UpdateServiceInstanceRequest.builder().serviceInstanceId("foo").build(); + + UpdateServiceInstanceResponseBuilder responseBuilder = UpdateServiceInstanceResponse.builder(); + UpdateServiceInstanceResponse builtResponse = UpdateServiceInstanceResponse.builder() + .async(true) + .dashboardUrl("https://dashboard.example.local") + .operation("working2") + .build(); + + TestPublisher lowerOrderFlow = TestPublisher.create(); + TestPublisher higherOrderFlow = TestPublisher.create(); + + given(this.updateServiceInstanceWorkflow1.accept(request)).willReturn(Mono.just(true)); + given(this.updateServiceInstanceWorkflow1.buildResponse(eq(request), + any(UpdateServiceInstanceResponseBuilder.class))) + .willReturn(Mono.just(responseBuilder.async(true).operation("working1"))); + given(this.updateServiceInstanceWorkflow1.update(eq(request), eq(builtResponse))) + .willReturn(lowerOrderFlow.mono()); + + given(this.updateServiceInstanceWorkflow2.accept(request)).willReturn(Mono.just(true)); + given(this.updateServiceInstanceWorkflow2 + .buildResponse(eq(request), any(UpdateServiceInstanceResponseBuilder.class))).willReturn( + Mono.just(responseBuilder.dashboardUrl("https://dashboard.example.local").operation("working2"))); + given(this.updateServiceInstanceWorkflow2.update(eq(request), eq(builtResponse))) + .willReturn(higherOrderFlow.mono()); + + StepVerifier.create(this.workflowServiceInstanceService.updateServiceInstance(request)) + .assertNext((response) -> { + InOrder repoOrder = inOrder(this.serviceInstanceStateRepository); + repoOrder.verify(this.serviceInstanceStateRepository) + .saveState(eq("foo"), eq(OperationState.IN_PROGRESS), eq("update service instance started")); + repoOrder.verify(this.serviceInstanceStateRepository) + .saveState(eq("foo"), eq(OperationState.SUCCEEDED), eq("update service instance completed")); + repoOrder.verifyNoMoreInteractions(); + + lowerOrderFlow.complete(); + lowerOrderFlow.assertWasNotRequested(); + + higherOrderFlow.complete(); + lowerOrderFlow.assertWasRequested(); + + InOrder updateOrder = inOrder(this.updateServiceInstanceWorkflow1, this.updateServiceInstanceWorkflow2); + updateOrder.verify(this.updateServiceInstanceWorkflow2) + .buildResponse(eq(request), any(UpdateServiceInstanceResponseBuilder.class)); + updateOrder.verify(this.updateServiceInstanceWorkflow1) + .buildResponse(eq(request), any(UpdateServiceInstanceResponseBuilder.class)); + updateOrder.verify(this.updateServiceInstanceWorkflow2).update(request, builtResponse); + updateOrder.verify(this.updateServiceInstanceWorkflow1).update(request, builtResponse); + updateOrder.verifyNoMoreInteractions(); + + assertThat(response).isNotNull(); + assertThat(response.isAsync()).isTrue(); + assertThat(response.getDashboardUrl()).isEqualTo("https://dashboard.example.local"); + assertThat(response.getOperation()).isEqualTo("working2"); + }) + .verifyComplete(); + } + + @Test + void updateServiceInstanceWithAsyncError() { + given(this.serviceInstanceStateRepository.saveState(anyString(), any(OperationState.class), anyString())) + .willReturn(Mono.just(new ServiceInstanceState(OperationState.IN_PROGRESS, + "update service instance started", new Timestamp(Instant.now().minusSeconds(60).toEpochMilli())))) + .willReturn(Mono.just(new ServiceInstanceState(OperationState.FAILED, "update service instance failed", + new Timestamp(Instant.now().minusSeconds(30).toEpochMilli())))); + + UpdateServiceInstanceRequest request = UpdateServiceInstanceRequest.builder().serviceInstanceId("foo").build(); + + UpdateServiceInstanceResponseBuilder responseBuilder = UpdateServiceInstanceResponse.builder(); + + given(this.updateServiceInstanceWorkflow1.accept(request)).willReturn(Mono.just(true)); + given(this.updateServiceInstanceWorkflow1.update(request, responseBuilder.build())) + .willReturn(Mono.error(new RuntimeException("update foo error"))); + given(this.updateServiceInstanceWorkflow1.buildResponse(eq(request), + any(UpdateServiceInstanceResponseBuilder.class))) + .willReturn(Mono.just(responseBuilder)); + + given(this.updateServiceInstanceWorkflow2.accept(request)).willReturn(Mono.just(true)); + given(this.updateServiceInstanceWorkflow2.update(request, responseBuilder.build())).willReturn(Mono.empty()); + given(this.updateServiceInstanceWorkflow2.buildResponse(eq(request), + any(UpdateServiceInstanceResponseBuilder.class))) + .willReturn(Mono.just(responseBuilder)); + + StepVerifier.create(this.workflowServiceInstanceService.updateServiceInstance(request)) + .assertNext((response) -> { + InOrder repoOrder = inOrder(this.serviceInstanceStateRepository); + repoOrder.verify(this.serviceInstanceStateRepository) + .saveState(eq("foo"), eq(OperationState.IN_PROGRESS), eq("update service instance started")); + repoOrder.verify(this.serviceInstanceStateRepository) + .saveState(eq("foo"), eq(OperationState.FAILED), eq("update foo error")); + repoOrder.verifyNoMoreInteractions(); + + InOrder updateOrder = inOrder(this.updateServiceInstanceWorkflow1, this.updateServiceInstanceWorkflow2); + updateOrder.verify(this.updateServiceInstanceWorkflow2) + .buildResponse(eq(request), any(UpdateServiceInstanceResponseBuilder.class)); + updateOrder.verify(this.updateServiceInstanceWorkflow1) + .buildResponse(eq(request), any(UpdateServiceInstanceResponseBuilder.class)); + updateOrder.verify(this.updateServiceInstanceWorkflow2).update(request, responseBuilder.build()); + updateOrder.verify(this.updateServiceInstanceWorkflow1).update(request, responseBuilder.build()); + updateOrder.verifyNoMoreInteractions(); + + assertThat(response).isNotNull(); + }) + .verifyComplete(); + } + + @Test + void updateServiceInstanceWithResponseError() { + UpdateServiceInstanceRequest request = UpdateServiceInstanceRequest.builder().serviceInstanceId("foo").build(); + + UpdateServiceInstanceResponseBuilder responseBuilder = UpdateServiceInstanceResponse.builder(); + + given(this.updateServiceInstanceWorkflow1.accept(request)).willReturn(Mono.just(true)); + given(this.updateServiceInstanceWorkflow1.buildResponse(eq(request), + any(UpdateServiceInstanceResponseBuilder.class))) + .willReturn(Mono.error(new ServiceBrokerException("update foo error"))); + + given(this.updateServiceInstanceWorkflow2.accept(request)).willReturn(Mono.just(true)); + given(this.updateServiceInstanceWorkflow2.buildResponse(eq(request), + any(UpdateServiceInstanceResponseBuilder.class))) + .willReturn(Mono.just(responseBuilder)); + + StepVerifier.create(this.workflowServiceInstanceService.updateServiceInstance(request)) + .expectErrorSatisfies( + (e) -> assertThat(e).isInstanceOf(ServiceBrokerException.class).hasMessage("update foo error")) + .verify(); + } + + @Test + void updateServiceInstanceWithNoAcceptsDoesNothing() { + given(this.serviceInstanceStateRepository.saveState(anyString(), any(OperationState.class), anyString())) + .willReturn(Mono.just(new ServiceInstanceState(OperationState.IN_PROGRESS, + "update service instance started", new Timestamp(Instant.now().minusSeconds(60).toEpochMilli())))) + .willReturn( + Mono.just(new ServiceInstanceState(OperationState.SUCCEEDED, "update service instance completed", + new Timestamp(Instant.now().minusSeconds(30).toEpochMilli())))); + + UpdateServiceInstanceRequest request = UpdateServiceInstanceRequest.builder().serviceInstanceId("foo").build(); + + given(this.updateServiceInstanceWorkflow1.accept(request)).willReturn(Mono.just(false)); + + given(this.updateServiceInstanceWorkflow2.accept(request)).willReturn(Mono.just(false)); + + StepVerifier.create(this.workflowServiceInstanceService.updateServiceInstance(request)) + .assertNext((response) -> { + InOrder repoOrder = inOrder(this.serviceInstanceStateRepository); + repoOrder.verify(this.serviceInstanceStateRepository) + .saveState(eq("foo"), eq(OperationState.IN_PROGRESS), eq("update service instance started")); + repoOrder.verify(this.serviceInstanceStateRepository) + .saveState(eq("foo"), eq(OperationState.SUCCEEDED), eq("update service instance completed")); + repoOrder.verifyNoMoreInteractions(); + + then(this.updateServiceInstanceWorkflow1).shouldHaveNoMoreInteractions(); + then(this.updateServiceInstanceWorkflow2).shouldHaveNoMoreInteractions(); + + assertThat(response).isNotNull(); + }) + .verifyComplete(); + } + + @Order(Ordered.HIGHEST_PRECEDENCE) + private interface HighOrderCreateServiceInstanceWorkflow extends CreateServiceInstanceWorkflow { + + } + + @Order + private interface LowOrderCreateServiceInstanceWorkflow extends CreateServiceInstanceWorkflow { + + } + + @Order(Ordered.HIGHEST_PRECEDENCE) + private interface HighOrderDeleteServiceInstanceWorkflow extends DeleteServiceInstanceWorkflow { + + } + + @Order + private interface LowOrderDeleteServiceInstanceWorkflow extends DeleteServiceInstanceWorkflow { + + } + + @Order(Ordered.HIGHEST_PRECEDENCE) + private interface HighOrderUpdateServiceInstanceWorkflow extends UpdateServiceInstanceWorkflow { + + } + + @Order + private interface LowOrderUpdateServiceInstanceWorkflow extends UpdateServiceInstanceWorkflow { + + } + +} diff --git a/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/service/WorkflowServiceInstanceSyncBindingServiceTest.java b/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/service/WorkflowServiceInstanceSyncBindingServiceTests.java similarity index 80% rename from spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/service/WorkflowServiceInstanceSyncBindingServiceTest.java rename to spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/service/WorkflowServiceInstanceSyncBindingServiceTests.java index 55b8580..bfcd9fd 100644 --- a/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/service/WorkflowServiceInstanceSyncBindingServiceTest.java +++ b/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/service/WorkflowServiceInstanceSyncBindingServiceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2016-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,7 +44,7 @@ import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.given; @ExtendWith(MockitoExtension.class) -class WorkflowServiceInstanceSyncBindingServiceTest { +class WorkflowServiceInstanceSyncBindingServiceTests { @Mock private ServiceInstanceBindingStateRepository stateRepository; @@ -53,13 +53,13 @@ class WorkflowServiceInstanceSyncBindingServiceTest { @BeforeEach void setUp() { - given(stateRepository.saveState(anyString(), anyString(), any(OperationState.class), anyString())) - .willReturn(Mono.just( - new ServiceInstanceState(OperationState.IN_PROGRESS, "create service instance binding started", - new Timestamp(Instant.now().minusSeconds(60).toEpochMilli())))) - .willReturn(Mono.just( - new ServiceInstanceState(OperationState.SUCCEEDED, "create service instance binding completed", - new Timestamp(Instant.now().minusSeconds(30).toEpochMilli())))); + given(this.stateRepository.saveState(anyString(), anyString(), any(OperationState.class), anyString())) + .willReturn(Mono + .just(new ServiceInstanceState(OperationState.IN_PROGRESS, "create service instance binding started", + new Timestamp(Instant.now().minusSeconds(60).toEpochMilli())))) + .willReturn(Mono + .just(new ServiceInstanceState(OperationState.SUCCEEDED, "create service instance binding completed", + new Timestamp(Instant.now().minusSeconds(30).toEpochMilli())))); } @@ -68,22 +68,20 @@ class WorkflowServiceInstanceSyncBindingServiceTest { CreateServiceInstanceBindingRequest request = CreateServiceInstanceBindingRequest.builder() .serviceInstanceId("foo-service") .bindingId("foo-binding") - .bindResource(BindResource.builder() - .appGuid("foo-guid") - .build()) + .bindResource(BindResource.builder().appGuid("foo-guid").build()) .build(); TestPublisher publisher = TestPublisher.create(); CreateServiceInstanceAppBindingWorkflow test = new CreateServiceInstanceAppBindingWorkflow() { @Override public Mono create(CreateServiceInstanceBindingRequest request, - CreateServiceInstanceAppBindingResponse response) { + CreateServiceInstanceAppBindingResponse response) { return publisher.mono(); } }; this.workflowServiceInstanceBindingService = new WorkflowServiceInstanceBindingService(this.stateRepository, - Collections.singletonList(test), Collections.emptyList(), Collections.emptyList()); + Collections.singletonList(test), Collections.emptyList(), Collections.emptyList()); StepVerifier.create(this.workflowServiceInstanceBindingService.createServiceInstanceBinding(request)) .expectSubscription() @@ -105,13 +103,13 @@ class WorkflowServiceInstanceSyncBindingServiceTest { DeleteServiceInstanceBindingWorkflow test = new DeleteServiceInstanceBindingWorkflow() { @Override public Mono delete(DeleteServiceInstanceBindingRequest request, - DeleteServiceInstanceBindingResponse response) { + DeleteServiceInstanceBindingResponse response) { return publisher.mono(); } }; this.workflowServiceInstanceBindingService = new WorkflowServiceInstanceBindingService(this.stateRepository, - Collections.emptyList(), Collections.emptyList(), Collections.singletonList(test)); + Collections.emptyList(), Collections.emptyList(), Collections.singletonList(test)); StepVerifier.create(this.workflowServiceInstanceBindingService.deleteServiceInstanceBinding(request)) .expectSubscription() @@ -122,6 +120,4 @@ class WorkflowServiceInstanceSyncBindingServiceTest { .verify(); } - - } diff --git a/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/state/InMemoryServiceInstanceBindingStateRepositoryTest.java b/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/state/InMemoryServiceInstanceBindingStateRepositoryTests.java similarity index 57% rename from spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/state/InMemoryServiceInstanceBindingStateRepositoryTest.java rename to spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/state/InMemoryServiceInstanceBindingStateRepositoryTests.java index dd207ad..bf6f7bd 100644 --- a/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/state/InMemoryServiceInstanceBindingStateRepositoryTest.java +++ b/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/state/InMemoryServiceInstanceBindingStateRepositoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,7 +28,7 @@ import org.springframework.cloud.servicebroker.model.instance.OperationState; import static org.assertj.core.api.Assertions.assertThat; -class InMemoryServiceInstanceBindingStateRepositoryTest { +class InMemoryServiceInstanceBindingStateRepositoryTests { private InMemoryServiceInstanceBindingStateRepository stateRepository; @@ -40,22 +40,19 @@ class InMemoryServiceInstanceBindingStateRepositoryTest { @Test void saveAndGet() { StepVerifier - .create(stateRepository.saveState("foo-service", "foo-binding", - OperationState.IN_PROGRESS, "bar")) - .assertNext(serviceInstanceState -> { + .create(this.stateRepository.saveState("foo-service", "foo-binding", OperationState.IN_PROGRESS, "bar")) + .assertNext((serviceInstanceState) -> { assertThat(serviceInstanceState.getOperationState()).isEqualTo(OperationState.IN_PROGRESS); assertThat(serviceInstanceState.getDescription()).isEqualTo("bar"); - assertThat(serviceInstanceState.getLastUpdated()) - .isInSameMinuteWindowAs(new Date()); + assertThat(serviceInstanceState.getLastUpdated()).isInSameMinuteWindowAs(new Date()); }) .verifyComplete(); - StepVerifier.create(stateRepository.getState("foo-service", "foo-binding")) - .assertNext(serviceInstanceState -> { + StepVerifier.create(this.stateRepository.getState("foo-service", "foo-binding")) + .assertNext((serviceInstanceState) -> { assertThat(serviceInstanceState.getOperationState()).isEqualTo(OperationState.IN_PROGRESS); assertThat(serviceInstanceState.getDescription()).isEqualTo("bar"); - assertThat(serviceInstanceState.getLastUpdated()) - .isInSameMinuteWindowAs(new Date()); + assertThat(serviceInstanceState.getLastUpdated()).isInSameMinuteWindowAs(new Date()); }) .verifyComplete(); } @@ -63,26 +60,23 @@ class InMemoryServiceInstanceBindingStateRepositoryTest { @Test void saveAndRemove() { StepVerifier - .create(stateRepository.saveState("foo-service", "foo-binding", - OperationState.IN_PROGRESS, "bar")) - .assertNext(serviceInstanceState -> { + .create(this.stateRepository.saveState("foo-service", "foo-binding", OperationState.IN_PROGRESS, "bar")) + .assertNext((serviceInstanceState) -> { assertThat(serviceInstanceState.getOperationState()).isEqualTo(OperationState.IN_PROGRESS); assertThat(serviceInstanceState.getDescription()).isEqualTo("bar"); - assertThat(serviceInstanceState.getLastUpdated()) - .isInSameMinuteWindowAs(new Date()); + assertThat(serviceInstanceState.getLastUpdated()).isInSameMinuteWindowAs(new Date()); }) .verifyComplete(); - StepVerifier.create(stateRepository.removeState("foo-service", "foo-binding")) - .assertNext(serviceInstanceState -> { + StepVerifier.create(this.stateRepository.removeState("foo-service", "foo-binding")) + .assertNext((serviceInstanceState) -> { assertThat(serviceInstanceState.getOperationState()).isEqualTo(OperationState.IN_PROGRESS); assertThat(serviceInstanceState.getDescription()).isEqualTo("bar"); - assertThat(serviceInstanceState.getLastUpdated()) - .isInSameMinuteWindowAs(new Date()); + assertThat(serviceInstanceState.getLastUpdated()).isInSameMinuteWindowAs(new Date()); }) .verifyComplete(); - StepVerifier.create(stateRepository.getState("foo-service", "foo-binding")) + StepVerifier.create(this.stateRepository.getState("foo-service", "foo-binding")) .expectError(IllegalArgumentException.class) .verify(); } @@ -90,81 +84,70 @@ class InMemoryServiceInstanceBindingStateRepositoryTest { @Test void updateState() { StepVerifier - .create(stateRepository.saveState("foo-service", "foo-binding", - OperationState.IN_PROGRESS, "bar")) - .assertNext(serviceInstanceState -> { + .create(this.stateRepository.saveState("foo-service", "foo-binding", OperationState.IN_PROGRESS, "bar")) + .assertNext((serviceInstanceState) -> { assertThat(serviceInstanceState.getOperationState()).isEqualTo(OperationState.IN_PROGRESS); assertThat(serviceInstanceState.getDescription()).isEqualTo("bar"); - assertThat(serviceInstanceState.getLastUpdated()) - .isInSameMinuteWindowAs(new Date()); + assertThat(serviceInstanceState.getLastUpdated()).isInSameMinuteWindowAs(new Date()); }) .verifyComplete(); - StepVerifier.create(stateRepository.getState("foo-service", "foo-binding")) - .assertNext(serviceInstanceState -> { + StepVerifier.create(this.stateRepository.getState("foo-service", "foo-binding")) + .assertNext((serviceInstanceState) -> { assertThat(serviceInstanceState.getOperationState()).isEqualTo(OperationState.IN_PROGRESS); assertThat(serviceInstanceState.getDescription()).isEqualTo("bar"); - assertThat(serviceInstanceState.getLastUpdated()) - .isInSameMinuteWindowAs(new Date()); + assertThat(serviceInstanceState.getLastUpdated()).isInSameMinuteWindowAs(new Date()); }) .verifyComplete(); StepVerifier - .create(stateRepository.saveState("foo-service", "foo-binding", - OperationState.SUCCEEDED, "bar")) - .assertNext(serviceInstanceState -> { + .create(this.stateRepository.saveState("foo-service", "foo-binding", OperationState.SUCCEEDED, "bar")) + .assertNext((serviceInstanceState) -> { assertThat(serviceInstanceState.getOperationState()).isEqualTo(OperationState.SUCCEEDED); assertThat(serviceInstanceState.getDescription()).isEqualTo("bar"); - assertThat(serviceInstanceState.getLastUpdated()) - .isInSameMinuteWindowAs(new Date()); + assertThat(serviceInstanceState.getLastUpdated()).isInSameMinuteWindowAs(new Date()); }) .verifyComplete(); - StepVerifier.create(stateRepository.getState("foo-service", "foo-binding")) - .assertNext(serviceInstanceState -> { + StepVerifier.create(this.stateRepository.getState("foo-service", "foo-binding")) + .assertNext((serviceInstanceState) -> { assertThat(serviceInstanceState.getOperationState()).isEqualTo(OperationState.SUCCEEDED); assertThat(serviceInstanceState.getDescription()).isEqualTo("bar"); - assertThat(serviceInstanceState.getLastUpdated()) - .isInSameMinuteWindowAs(new Date()); + assertThat(serviceInstanceState.getLastUpdated()).isInSameMinuteWindowAs(new Date()); }) .verifyComplete(); } @Test void getWithNullBindingKey() { - StepVerifier.create(stateRepository.getState(null, null)) + StepVerifier.create(this.stateRepository.getState(null, null)) .expectError(IllegalArgumentException.class) .verify(); } @Test void getWithUnknownBindingKey() { - StepVerifier.create(stateRepository.getState("foo-service", "foo-binding")) + StepVerifier.create(this.stateRepository.getState("foo-service", "foo-binding")) .expectError(IllegalArgumentException.class) .verify(); } @Test void removeWithUnknownBindingKey() { - StepVerifier.create(stateRepository.removeState("foo-service", "foo-binding")) + StepVerifier.create(this.stateRepository.removeState("foo-service", "foo-binding")) .expectError(IllegalArgumentException.class) .verify(); } @Test void ensureConcurrency() { - StepVerifier.create( - Flux.range(0, 100_000) + StepVerifier + .create(Flux.range(0, 100_000) .parallel(25) .runOn(Schedulers.newParallel("parallel-test", 25)) - .flatMap(value -> - stateRepository - .saveState( - "foo-service" + value, - "foo-binding" + value, - OperationState.IN_PROGRESS, - "bar") - .then(stateRepository.removeState("foo-service" + value, "foo-binding" + value)))) + .flatMap((value) -> this.stateRepository + .saveState("foo-service" + value, "foo-binding" + value, OperationState.IN_PROGRESS, "bar") + .then(this.stateRepository.removeState("foo-service" + value, "foo-binding" + value)))) .expectNextCount(100_000) .verifyComplete(); } diff --git a/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/state/InMemoryServiceInstanceStateRepositoryTest.java b/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/state/InMemoryServiceInstanceStateRepositoryTest.java deleted file mode 100644 index ebbddff..0000000 --- a/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/state/InMemoryServiceInstanceStateRepositoryTest.java +++ /dev/null @@ -1,154 +0,0 @@ -/* - * Copyright 2002-2020 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.appbroker.state; - -import java.util.Date; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import reactor.core.publisher.Flux; -import reactor.core.scheduler.Schedulers; -import reactor.test.StepVerifier; - -import org.springframework.cloud.servicebroker.model.instance.OperationState; - -import static org.assertj.core.api.Assertions.assertThat; - -class InMemoryServiceInstanceStateRepositoryTest { - - private InMemoryServiceInstanceStateRepository stateRepository; - - @BeforeEach - void setUp() { - this.stateRepository = new InMemoryServiceInstanceStateRepository(); - } - - @Test - void saveAndGet() { - StepVerifier.create(stateRepository.saveState("foo", OperationState.IN_PROGRESS, "bar")) - .assertNext(serviceInstanceState -> { - assertThat(serviceInstanceState.getOperationState()).isEqualTo(OperationState.IN_PROGRESS); - assertThat(serviceInstanceState.getDescription()).isEqualTo("bar"); - assertThat(serviceInstanceState.getLastUpdated()) - .isCloseTo(new Date(), 1000L); - }) - .verifyComplete(); - - StepVerifier.create(stateRepository.getState("foo")) - .assertNext(serviceInstanceState -> { - assertThat(serviceInstanceState.getOperationState()).isEqualTo(OperationState.IN_PROGRESS); - assertThat(serviceInstanceState.getDescription()).isEqualTo("bar"); - assertThat(serviceInstanceState.getLastUpdated()) - .isCloseTo(new Date(), 1000L); - }) - .verifyComplete(); - } - - @Test - void saveAndRemove() { - StepVerifier.create(stateRepository.saveState("foo", OperationState.IN_PROGRESS, "bar")) - .assertNext(serviceInstanceState -> { - assertThat(serviceInstanceState.getOperationState()).isEqualTo(OperationState.IN_PROGRESS); - assertThat(serviceInstanceState.getDescription()).isEqualTo("bar"); - assertThat(serviceInstanceState.getLastUpdated()).isInSameMinuteWindowAs(new Date()); - }) - .verifyComplete(); - - StepVerifier.create(stateRepository.removeState("foo")) - .assertNext(serviceInstanceState -> { - assertThat(serviceInstanceState.getOperationState()).isEqualTo(OperationState.IN_PROGRESS); - assertThat(serviceInstanceState.getDescription()).isEqualTo("bar"); - assertThat(serviceInstanceState.getLastUpdated()) - .isCloseTo(new Date(), 1000L); - }) - .verifyComplete(); - - StepVerifier.create(stateRepository.getState("foo")) - .expectError(IllegalArgumentException.class) - .verify(); - } - - @Test - void updateState() { - StepVerifier - .create(stateRepository.saveState("foo-service", OperationState.IN_PROGRESS, "bar")) - .assertNext(serviceInstanceState -> { - assertThat(serviceInstanceState.getOperationState()).isEqualTo(OperationState.IN_PROGRESS); - assertThat(serviceInstanceState.getDescription()).isEqualTo("bar"); - assertThat(serviceInstanceState.getLastUpdated()) - .isCloseTo(new Date(), 1000L); - }) - .verifyComplete(); - - StepVerifier.create(stateRepository.getState("foo-service")) - .assertNext(serviceInstanceState -> { - assertThat(serviceInstanceState.getOperationState()).isEqualTo(OperationState.IN_PROGRESS); - assertThat(serviceInstanceState.getDescription()).isEqualTo("bar"); - assertThat(serviceInstanceState.getLastUpdated()) - .isCloseTo(new Date(), 1000L); - }) - .verifyComplete(); - - StepVerifier - .create(stateRepository.saveState("foo-service", OperationState.SUCCEEDED, "bar")) - .assertNext(serviceInstanceState -> { - assertThat(serviceInstanceState.getOperationState()).isEqualTo(OperationState.SUCCEEDED); - assertThat(serviceInstanceState.getDescription()).isEqualTo("bar"); - assertThat(serviceInstanceState.getLastUpdated()) - .isCloseTo(new Date(), 1000L); - }) - .verifyComplete(); - - StepVerifier.create(stateRepository.getState("foo-service")) - .assertNext(serviceInstanceState -> { - assertThat(serviceInstanceState.getOperationState()).isEqualTo(OperationState.SUCCEEDED); - assertThat(serviceInstanceState.getDescription()).isEqualTo("bar"); - assertThat(serviceInstanceState.getLastUpdated()) - .isCloseTo(new Date(), 1000L); - }) - .verifyComplete(); - } - - @Test - void getWithUnknownServiceInstanceId() { - StepVerifier.create(stateRepository.getState("foo")) - .expectError(IllegalArgumentException.class) - .verify(); - } - - @Test - void removeWithUnknownServiceInstanceId() { - StepVerifier.create(stateRepository.removeState("foo")) - .expectError(IllegalArgumentException.class) - .verify(); - } - - @Test - void ensureConcurrency() { - StepVerifier.create( - Flux.range(0, 100_000) - .parallel(25) - .runOn(Schedulers.newParallel("parallel-test", 25)) - .flatMap(value -> - stateRepository - .saveState("foo" + value, OperationState.IN_PROGRESS, "bar") - .then(stateRepository.removeState("foo" + value)))) - .expectNextCount(100_000) - .verifyComplete(); - } - -} diff --git a/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/state/InMemoryServiceInstanceStateRepositoryTests.java b/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/state/InMemoryServiceInstanceStateRepositoryTests.java new file mode 100644 index 0000000..139dc81 --- /dev/null +++ b/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/state/InMemoryServiceInstanceStateRepositoryTests.java @@ -0,0 +1,131 @@ +/* + * Copyright 2016-2020 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.cloud.appbroker.state; + +import java.util.Date; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Flux; +import reactor.core.scheduler.Schedulers; +import reactor.test.StepVerifier; + +import org.springframework.cloud.servicebroker.model.instance.OperationState; + +import static org.assertj.core.api.Assertions.assertThat; + +class InMemoryServiceInstanceStateRepositoryTests { + + private InMemoryServiceInstanceStateRepository stateRepository; + + @BeforeEach + void setUp() { + this.stateRepository = new InMemoryServiceInstanceStateRepository(); + } + + @Test + void saveAndGet() { + StepVerifier.create(this.stateRepository.saveState("foo", OperationState.IN_PROGRESS, "bar")) + .assertNext((serviceInstanceState) -> { + assertThat(serviceInstanceState.getOperationState()).isEqualTo(OperationState.IN_PROGRESS); + assertThat(serviceInstanceState.getDescription()).isEqualTo("bar"); + assertThat(serviceInstanceState.getLastUpdated()).isCloseTo(new Date(), 1000L); + }) + .verifyComplete(); + + StepVerifier.create(this.stateRepository.getState("foo")).assertNext((serviceInstanceState) -> { + assertThat(serviceInstanceState.getOperationState()).isEqualTo(OperationState.IN_PROGRESS); + assertThat(serviceInstanceState.getDescription()).isEqualTo("bar"); + assertThat(serviceInstanceState.getLastUpdated()).isCloseTo(new Date(), 1000L); + }).verifyComplete(); + } + + @Test + void saveAndRemove() { + StepVerifier.create(this.stateRepository.saveState("foo", OperationState.IN_PROGRESS, "bar")) + .assertNext((serviceInstanceState) -> { + assertThat(serviceInstanceState.getOperationState()).isEqualTo(OperationState.IN_PROGRESS); + assertThat(serviceInstanceState.getDescription()).isEqualTo("bar"); + assertThat(serviceInstanceState.getLastUpdated()).isInSameMinuteWindowAs(new Date()); + }) + .verifyComplete(); + + StepVerifier.create(this.stateRepository.removeState("foo")).assertNext((serviceInstanceState) -> { + assertThat(serviceInstanceState.getOperationState()).isEqualTo(OperationState.IN_PROGRESS); + assertThat(serviceInstanceState.getDescription()).isEqualTo("bar"); + assertThat(serviceInstanceState.getLastUpdated()).isCloseTo(new Date(), 1000L); + }).verifyComplete(); + + StepVerifier.create(this.stateRepository.getState("foo")).expectError(IllegalArgumentException.class).verify(); + } + + @Test + void updateState() { + StepVerifier.create(this.stateRepository.saveState("foo-service", OperationState.IN_PROGRESS, "bar")) + .assertNext((serviceInstanceState) -> { + assertThat(serviceInstanceState.getOperationState()).isEqualTo(OperationState.IN_PROGRESS); + assertThat(serviceInstanceState.getDescription()).isEqualTo("bar"); + assertThat(serviceInstanceState.getLastUpdated()).isCloseTo(new Date(), 1000L); + }) + .verifyComplete(); + + StepVerifier.create(this.stateRepository.getState("foo-service")).assertNext((serviceInstanceState) -> { + assertThat(serviceInstanceState.getOperationState()).isEqualTo(OperationState.IN_PROGRESS); + assertThat(serviceInstanceState.getDescription()).isEqualTo("bar"); + assertThat(serviceInstanceState.getLastUpdated()).isCloseTo(new Date(), 1000L); + }).verifyComplete(); + + StepVerifier.create(this.stateRepository.saveState("foo-service", OperationState.SUCCEEDED, "bar")) + .assertNext((serviceInstanceState) -> { + assertThat(serviceInstanceState.getOperationState()).isEqualTo(OperationState.SUCCEEDED); + assertThat(serviceInstanceState.getDescription()).isEqualTo("bar"); + assertThat(serviceInstanceState.getLastUpdated()).isCloseTo(new Date(), 1000L); + }) + .verifyComplete(); + + StepVerifier.create(this.stateRepository.getState("foo-service")).assertNext((serviceInstanceState) -> { + assertThat(serviceInstanceState.getOperationState()).isEqualTo(OperationState.SUCCEEDED); + assertThat(serviceInstanceState.getDescription()).isEqualTo("bar"); + assertThat(serviceInstanceState.getLastUpdated()).isCloseTo(new Date(), 1000L); + }).verifyComplete(); + } + + @Test + void getWithUnknownServiceInstanceId() { + StepVerifier.create(this.stateRepository.getState("foo")).expectError(IllegalArgumentException.class).verify(); + } + + @Test + void removeWithUnknownServiceInstanceId() { + StepVerifier.create(this.stateRepository.removeState("foo")) + .expectError(IllegalArgumentException.class) + .verify(); + } + + @Test + void ensureConcurrency() { + StepVerifier + .create(Flux.range(0, 100_000) + .parallel(25) + .runOn(Schedulers.newParallel("parallel-test", 25)) + .flatMap((value) -> this.stateRepository.saveState("foo" + value, OperationState.IN_PROGRESS, "bar") + .then(this.stateRepository.removeState("foo" + value)))) + .expectNextCount(100_000) + .verifyComplete(); + } + +} diff --git a/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/workflow/instance/AppDeploymentCreateServiceInstanceWorkflowTest.java b/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/workflow/instance/AppDeploymentCreateServiceInstanceWorkflowTests.java similarity index 61% rename from spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/workflow/instance/AppDeploymentCreateServiceInstanceWorkflowTest.java rename to spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/workflow/instance/AppDeploymentCreateServiceInstanceWorkflowTests.java index d7d0008..8814255 100644 --- a/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/workflow/instance/AppDeploymentCreateServiceInstanceWorkflowTest.java +++ b/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/workflow/instance/AppDeploymentCreateServiceInstanceWorkflowTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,7 @@ package org.springframework.cloud.appbroker.workflow.instance; +import java.util.Collections; import java.util.HashMap; import java.util.Map; @@ -46,14 +47,13 @@ import org.springframework.cloud.servicebroker.model.catalog.ServiceDefinition; import org.springframework.cloud.servicebroker.model.instance.CreateServiceInstanceRequest; import org.springframework.cloud.servicebroker.model.instance.CreateServiceInstanceResponse; -import static java.util.Collections.singletonMap; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; @ExtendWith(MockitoExtension.class) -class AppDeploymentCreateServiceInstanceWorkflowTest { +class AppDeploymentCreateServiceInstanceWorkflowTests { @Mock private BackingAppDeploymentService appDeploymentService; @@ -80,75 +80,55 @@ class AppDeploymentCreateServiceInstanceWorkflowTest { @BeforeEach void setUp() { - backingApps = BackingApplications - .builder() - .backingApplication(BackingApplication - .builder() - .name("app1") - .path("https://myfiles/app1.jar") - .build()) - .backingApplication(BackingApplication - .builder() - .name("app2") - .path("https://myfiles/app2.jar") - .build()) + this.backingApps = BackingApplications.builder() + .backingApplication(BackingApplication.builder().name("app1").path("https://myfiles/app1.jar").build()) + .backingApplication(BackingApplication.builder().name("app2").path("https://myfiles/app2.jar").build()) .build(); - backingServices = BackingServices - .builder() - .backingService(BackingService - .builder() + this.backingServices = BackingServices.builder() + .backingService(BackingService.builder() .name("my-service") .plan("a-plan") .serviceInstanceName("my-service-instance") .build()) .build(); - targetSpec = TargetSpec.builder() - .name("TargetSpace") - .build(); + this.targetSpec = TargetSpec.builder().name("TargetSpace").build(); - BrokeredServices brokeredServices = BrokeredServices - .builder() - .service(BrokeredService - .builder() + BrokeredServices brokeredServices = BrokeredServices.builder() + .service(BrokeredService.builder() .serviceName("service1") .planName("plan1") - .apps(backingApps) - .services(backingServices) - .target(targetSpec) + .apps(this.backingApps) + .services(this.backingServices) + .target(this.targetSpec) .build()) .build(); - createServiceInstanceWorkflow = new AppDeploymentCreateServiceInstanceWorkflow( - brokeredServices, - appDeploymentService, - servicesProvisionService, - appsParametersTransformationService, - servicesParametersTransformationService, - targetService); + this.createServiceInstanceWorkflow = new AppDeploymentCreateServiceInstanceWorkflow(brokeredServices, + this.appDeploymentService, this.servicesProvisionService, this.appsParametersTransformationService, + this.servicesParametersTransformationService, this.targetService); } @Test - @SuppressWarnings({"unchecked", "UnassignedFluxMonoInstance"}) + @SuppressWarnings({ "unchecked", "UnassignedFluxMonoInstance" }) void createServiceInstanceSucceeds() { CreateServiceInstanceRequest request = buildRequest("service1", "plan1"); CreateServiceInstanceResponse response = CreateServiceInstanceResponse.builder().build(); setupMocks(request); - StepVerifier - .create(createServiceInstanceWorkflow.create(request, response)) + StepVerifier.create(this.createServiceInstanceWorkflow.create(request, response)) .expectNext() .expectNext() .verifyComplete(); - verify(appDeploymentService).deploy(backingApps, request.getServiceInstanceId()); - verify(servicesProvisionService).createServiceInstance(backingServices); + verify(this.appDeploymentService).deploy(this.backingApps, request.getServiceInstanceId()); + verify(this.servicesProvisionService).createServiceInstance(this.backingServices); final String expectedServiceId = "service-instance-id"; - verify(targetService).addToBackingServices(backingServices, targetSpec, expectedServiceId); - verify(targetService).addToBackingApplications(backingApps, targetSpec, expectedServiceId); + verify(this.targetService).addToBackingServices(this.backingServices, this.targetSpec, expectedServiceId); + verify(this.targetService).addToBackingApplications(this.backingApps, this.targetSpec, expectedServiceId); verifyNoMoreInteractionsWithServices(); } @@ -156,27 +136,24 @@ class AppDeploymentCreateServiceInstanceWorkflowTest { @Test @SuppressWarnings("UnassignedFluxMonoInstance") void createServiceInstanceWithParametersSucceeds() { - Map parameters = singletonMap("ENV_VAR_1", "value from parameters"); + Map parameters = Collections.singletonMap("ENV_VAR_1", "value from parameters"); CreateServiceInstanceRequest request = buildRequest("service1", "plan1", parameters); CreateServiceInstanceResponse response = CreateServiceInstanceResponse.builder().build(); setupMocks(request); - StepVerifier - .create(createServiceInstanceWorkflow.create(request, response)) + StepVerifier.create(this.createServiceInstanceWorkflow.create(request, response)) .expectNext() .expectNext() .verifyComplete(); - verify(appDeploymentService).deploy(backingApps, request.getServiceInstanceId()); - verify(servicesProvisionService).createServiceInstance(backingServices); + verify(this.appDeploymentService).deploy(this.backingApps, request.getServiceInstanceId()); + verify(this.servicesProvisionService).createServiceInstance(this.backingServices); - verify(appsParametersTransformationService) - .transformParameters(backingApps, parameters); + verify(this.appsParametersTransformationService).transformParameters(this.backingApps, parameters); - verify(servicesParametersTransformationService) - .transformParameters(backingServices, parameters); + verify(this.servicesParametersTransformationService).transformParameters(this.backingServices, parameters); verifyNoMoreInteractionsWithServices(); } @@ -186,32 +163,30 @@ class AppDeploymentCreateServiceInstanceWorkflowTest { CreateServiceInstanceRequest request = buildRequest("unsupported-service", "plan1"); CreateServiceInstanceResponse response = CreateServiceInstanceResponse.builder().build(); - StepVerifier - .create(createServiceInstanceWorkflow.create(request, response)) - .verifyComplete(); + StepVerifier.create(this.createServiceInstanceWorkflow.create(request, response)).verifyComplete(); verifyNoMoreInteractionsWithServices(); } private void setupMocks(CreateServiceInstanceRequest request) { - given(this.appDeploymentService.deploy(eq(backingApps), eq(request.getServiceInstanceId()))) + given(this.appDeploymentService.deploy(eq(this.backingApps), eq(request.getServiceInstanceId()))) .willReturn(Flux.just("app1", "app2")); - given(this.servicesProvisionService.createServiceInstance(eq(backingServices))) + given(this.servicesProvisionService.createServiceInstance(eq(this.backingServices))) .willReturn(Flux.just("my-service-instance")); - given( - this.appsParametersTransformationService.transformParameters(eq(backingApps), eq(request.getParameters()))) - .willReturn(Mono.just(backingApps)); - given(this.servicesParametersTransformationService - .transformParameters(eq(backingServices), eq(request.getParameters()))) - .willReturn(Mono.just(backingServices)); + given(this.appsParametersTransformationService.transformParameters(eq(this.backingApps), + eq(request.getParameters()))) + .willReturn(Mono.just(this.backingApps)); + given(this.servicesParametersTransformationService.transformParameters(eq(this.backingServices), + eq(request.getParameters()))) + .willReturn(Mono.just(this.backingServices)); - given(this.targetService - .addToBackingApplications(eq(backingApps), eq(targetSpec), eq(request.getServiceInstanceId()))) - .willReturn(Mono.just(backingApps)); - given(this.targetService - .addToBackingServices(eq(backingServices), eq(targetSpec), eq(request.getServiceInstanceId()))) - .willReturn(Mono.just(backingServices)); + given(this.targetService.addToBackingApplications(eq(this.backingApps), eq(this.targetSpec), + eq(request.getServiceInstanceId()))) + .willReturn(Mono.just(this.backingApps)); + given(this.targetService.addToBackingServices(eq(this.backingServices), eq(this.targetSpec), + eq(request.getServiceInstanceId()))) + .willReturn(Mono.just(this.backingServices)); } private void verifyNoMoreInteractionsWithServices() { @@ -227,26 +202,18 @@ class AppDeploymentCreateServiceInstanceWorkflowTest { } private CreateServiceInstanceRequest buildRequest(String serviceName, String planName, - Map parameters) { - return CreateServiceInstanceRequest - .builder() + Map parameters) { + return CreateServiceInstanceRequest.builder() .serviceInstanceId("service-instance-id") .serviceDefinitionId(serviceName + "-id") .planId(planName + "-id") - .serviceDefinition(ServiceDefinition - .builder() + .serviceDefinition(ServiceDefinition.builder() .id(serviceName + "-id") .name(serviceName) - .plans(Plan.builder() - .id(planName + "-id") - .name(planName) - .build()) + .plans(Plan.builder().id(planName + "-id").name(planName).build()) .build()) - .plan(Plan.builder() - .id(planName + "-id") - .name(planName) - .build()) - .parameters(parameters == null ? new HashMap<>() : parameters) + .plan(Plan.builder().id(planName + "-id").name(planName).build()) + .parameters((parameters != null) ? parameters : new HashMap<>()) .build(); } diff --git a/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/workflow/instance/AppDeploymentDeleteServiceInstanceWorkflowTest.java b/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/workflow/instance/AppDeploymentDeleteServiceInstanceWorkflowTests.java similarity index 69% rename from spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/workflow/instance/AppDeploymentDeleteServiceInstanceWorkflowTest.java rename to spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/workflow/instance/AppDeploymentDeleteServiceInstanceWorkflowTests.java index 2193743..2b931f7 100644 --- a/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/workflow/instance/AppDeploymentDeleteServiceInstanceWorkflowTest.java +++ b/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/workflow/instance/AppDeploymentDeleteServiceInstanceWorkflowTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2021 the original author or authors. + * Copyright 2016-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,6 +17,7 @@ package org.springframework.cloud.appbroker.workflow.instance; import java.util.Arrays; +import java.util.Collections; import java.util.Map; import org.junit.jupiter.api.BeforeEach; @@ -49,9 +50,6 @@ import org.springframework.cloud.servicebroker.model.catalog.ServiceDefinition; import org.springframework.cloud.servicebroker.model.instance.DeleteServiceInstanceRequest; import org.springframework.cloud.servicebroker.model.instance.DeleteServiceInstanceResponse; -import static java.util.Collections.emptyList; -import static java.util.Collections.singletonList; -import static java.util.Collections.singletonMap; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.ArgumentMatchers.eq; @@ -60,7 +58,7 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; @ExtendWith(MockitoExtension.class) -class AppDeploymentDeleteServiceInstanceWorkflowTest { +class AppDeploymentDeleteServiceInstanceWorkflowTests { @Mock private BackingAppDeploymentService backingAppDeploymentService; @@ -89,34 +87,21 @@ class AppDeploymentDeleteServiceInstanceWorkflowTest { @BeforeEach void setUp() { - backingApps = BackingApplications - .builder() - .backingApplication(BackingApplication - .builder() - .name("app1") - .path("https://myfiles/app1.jar") - .build()) - .backingApplication(BackingApplication - .builder() - .name("app2") - .path("https://myfiles/app2.jar") - .build()) + this.backingApps = BackingApplications.builder() + .backingApplication(BackingApplication.builder().name("app1").path("https://myfiles/app1.jar").build()) + .backingApplication(BackingApplication.builder().name("app2").path("https://myfiles/app2.jar").build()) .build(); - this.backingServices = BackingServices - .builder() - .backingService(BackingService - .builder() + this.backingServices = BackingServices.builder() + .backingService(BackingService.builder() .name("my-service") .plan("a-plan") .serviceInstanceName("my-service-instance") .build()) .build(); - this.backingServices2 = BackingServices - .builder() - .backingService(BackingService - .builder() + this.backingServices2 = BackingServices.builder() + .backingService(BackingService.builder() .name("my-service2") .plan("a-plan2") .serviceInstanceName("my-service-instance2") @@ -124,44 +109,34 @@ class AppDeploymentDeleteServiceInstanceWorkflowTest { .build()) .build(); - targetSpec = TargetSpec.builder() - .name("TargetSpace") - .build(); + this.targetSpec = TargetSpec.builder().name("TargetSpace").build(); - BrokeredServices brokeredServices = BrokeredServices - .builder() - .service(BrokeredService - .builder() + BrokeredServices brokeredServices = BrokeredServices.builder() + .service(BrokeredService.builder() .serviceName("service1") .planName("plan1") - .apps(backingApps) - .services(backingServices) - .target(targetSpec) + .apps(this.backingApps) + .services(this.backingServices) + .target(this.targetSpec) .build()) .service(BrokeredService.builder() .serviceName("service2") .planName("plan2") - .services(backingServices) - .target(targetSpec) + .services(this.backingServices) + .target(this.targetSpec) .build()) .service(BrokeredService.builder() .serviceName("service3") .planName("plan3") - .apps(backingApps) - .services(backingServices2) - .target(targetSpec) + .apps(this.backingApps) + .services(this.backingServices2) + .target(this.targetSpec) .build()) .build(); - deleteServiceInstanceWorkflow = - new AppDeploymentDeleteServiceInstanceWorkflow( - brokeredServices, - backingAppDeploymentService, - backingAppManagementService, - backingServicesProvisionService, - backingSpaceManagementService, - targetService - ); + this.deleteServiceInstanceWorkflow = new AppDeploymentDeleteServiceInstanceWorkflow(brokeredServices, + this.backingAppDeploymentService, this.backingAppManagementService, + this.backingServicesProvisionService, this.backingSpaceManagementService, this.targetService); } @Test @@ -169,21 +144,23 @@ class AppDeploymentDeleteServiceInstanceWorkflowTest { DeleteServiceInstanceRequest request = buildRequest("service1", "plan1"); DeleteServiceInstanceResponse response = DeleteServiceInstanceResponse.builder().build(); - given(this.backingAppDeploymentService.undeploy(eq(backingApps))) + given(this.backingAppDeploymentService.undeploy(eq(this.backingApps))) .willReturn(Flux.just("undeployed1", "undeployed2")); // configured backing services - given(this.targetService.addToBackingServices(eq(backingServices), eq(targetSpec), eq("service-instance-id"))) - .willReturn(Mono.just(backingServices)); + given(this.targetService.addToBackingServices(eq(this.backingServices), eq(this.targetSpec), + eq("service-instance-id"))) + .willReturn(Mono.just(this.backingServices)); // services bound to deployed apps given(this.backingAppManagementService.getDeployedBackingApplications(request.getServiceInstanceId(), - request.getServiceDefinition().getName(), request.getPlan().getName())) + request.getServiceDefinition().getName(), request.getPlan().getName())) .willReturn(Mono.just(getExistingBackingAppsWithService("my-service-instance"))); - given(this.targetService.addToBackingApplications(eq(backingApps), eq(targetSpec), eq("service-instance-id"))) - .willReturn(Mono.just(backingApps)); + given(this.targetService.addToBackingApplications(eq(this.backingApps), eq(this.targetSpec), + eq("service-instance-id"))) + .willReturn(Mono.just(this.backingApps)); - given(this.backingServicesProvisionService.deleteServiceInstance(argThat(backingServices -> { + given(this.backingServicesProvisionService.deleteServiceInstance(argThat((backingServices) -> { boolean nameMatch = "my-service-instance".equals(backingServices.get(0).getServiceInstanceName()); boolean sizeMatch = backingServices.size() == 1; return sizeMatch && nameMatch; @@ -191,12 +168,10 @@ class AppDeploymentDeleteServiceInstanceWorkflowTest { given(this.backingSpaceManagementService.deleteTargetSpaces(any())).willReturn(Flux.empty()); - StepVerifier - .create(deleteServiceInstanceWorkflow.delete(request, response)) - .verifyComplete(); + StepVerifier.create(this.deleteServiceInstanceWorkflow.delete(request, response)).verifyComplete(); verify(this.backingServicesProvisionService, Mockito.times(1)).deleteServiceInstance(any()); - verify(this.backingSpaceManagementService).deleteTargetSpaces(eq(emptyList())); + verify(this.backingSpaceManagementService).deleteTargetSpaces(eq(Collections.emptyList())); verifyNoMoreInteractionsWithServices(); } @@ -208,20 +183,24 @@ class AppDeploymentDeleteServiceInstanceWorkflowTest { String space2 = "CustomSpace2"; // configured backing services - BackingServices servicesWithTarget = BackingServices.builder().backingServices(backingServices).build(); + BackingServices servicesWithTarget = BackingServices.builder().backingServices(this.backingServices).build(); servicesWithTarget.get(0).setProperties(getPropertiesWithSpace(space1)); - given(this.targetService.addToBackingServices(eq(backingServices), eq(targetSpec), eq("service-instance-id"))) + given(this.targetService.addToBackingServices(eq(this.backingServices), eq(this.targetSpec), + eq("service-instance-id"))) .willReturn(Mono.just(servicesWithTarget)); // configured backing apps - BackingApplications appsWithTarget = BackingApplications.builder().backingApplications(backingApps).build(); + BackingApplications appsWithTarget = BackingApplications.builder() + .backingApplications(this.backingApps) + .build(); appsWithTarget.get(0).setProperties(getPropertiesWithSpace(space2)); - given(this.targetService.addToBackingApplications(eq(backingApps), eq(targetSpec), eq("service-instance-id"))) + given(this.targetService.addToBackingApplications(eq(this.backingApps), eq(this.targetSpec), + eq("service-instance-id"))) .willReturn(Mono.just(appsWithTarget)); // services bound to deployed apps given(this.backingAppManagementService.getDeployedBackingApplications(request.getServiceInstanceId(), - request.getServiceDefinition().getName(), request.getPlan().getName())) + request.getServiceDefinition().getName(), request.getPlan().getName())) .willReturn(Mono.just(getExistingBackingAppsWithService("my-service-instance"))); // delete in action @@ -231,9 +210,7 @@ class AppDeploymentDeleteServiceInstanceWorkflowTest { .willReturn(Flux.just("my-service-instance")); given(this.backingSpaceManagementService.deleteTargetSpaces(any())).willReturn(Flux.just("space-name")); - StepVerifier - .create(deleteServiceInstanceWorkflow.delete(request, response)) - .verifyComplete(); + StepVerifier.create(this.deleteServiceInstanceWorkflow.delete(request, response)).verifyComplete(); verify(this.backingServicesProvisionService, Mockito.times(1)).deleteServiceInstance(any()); verify(this.backingSpaceManagementService).deleteTargetSpaces(Arrays.asList(space1, space2)); @@ -245,35 +222,37 @@ class AppDeploymentDeleteServiceInstanceWorkflowTest { DeleteServiceInstanceRequest request = buildRequest("service3", "plan3"); DeleteServiceInstanceResponse response = DeleteServiceInstanceResponse.builder().build(); - given(this.backingAppDeploymentService.undeploy(eq(backingApps))) + given(this.backingAppDeploymentService.undeploy(eq(this.backingApps))) .willReturn(Flux.just("undeployed1", "undeployed2")); // configured backing services - given(this.targetService.addToBackingServices(eq(backingServices2), eq(targetSpec), eq("service-instance-id"))) - .willReturn(Mono.just(backingServices2)); + given(this.targetService.addToBackingServices(eq(this.backingServices2), eq(this.targetSpec), + eq("service-instance-id"))) + .willReturn(Mono.just(this.backingServices2)); // different bound services given(this.backingAppManagementService.getDeployedBackingApplications(request.getServiceInstanceId(), - request.getServiceDefinition().getName(), request.getPlan().getName())) + request.getServiceDefinition().getName(), request.getPlan().getName())) .willReturn(Mono.just(getExistingBackingAppsWithService("different-service-instance"))); - given(this.targetService.addToBackingApplications(eq(backingApps), eq(targetSpec), eq("service-instance-id"))) - .willReturn(Mono.just(backingApps)); + given(this.targetService.addToBackingApplications(eq(this.backingApps), eq(this.targetSpec), + eq("service-instance-id"))) + .willReturn(Mono.just(this.backingApps)); - given(this.backingServicesProvisionService.deleteServiceInstance(argThat(backingServices -> { + given(this.backingServicesProvisionService.deleteServiceInstance(argThat((backingServices) -> { boolean nameMatch0 = "my-service-instance2".equals(backingServices.get(0).getServiceInstanceName()); - boolean spaceMatch0 = "my-space2".equals(backingServices.get(0).getProperties() - .get(DeploymentProperties.TARGET_PROPERTY_KEY)); + boolean spaceMatch0 = "my-space2" + .equals(backingServices.get(0).getProperties().get(DeploymentProperties.TARGET_PROPERTY_KEY)); boolean nameMatch1 = "different-service-instance".equals(backingServices.get(1).getServiceInstanceName()); - boolean spaceMatch1 = "TargetSpace".equals(backingServices.get(1).getProperties() - .get(DeploymentProperties.TARGET_PROPERTY_KEY)); + boolean spaceMatch1 = "TargetSpace" + .equals(backingServices.get(1).getProperties().get(DeploymentProperties.TARGET_PROPERTY_KEY)); boolean sizeMatch = backingServices.size() == 2; return sizeMatch && (nameMatch0 && spaceMatch0 || nameMatch1 && spaceMatch1); }))).willReturn(Flux.just("different-service-instance")); - given(this.backingSpaceManagementService.deleteTargetSpaces(eq(singletonList("my-space2")))) + given(this.backingSpaceManagementService.deleteTargetSpaces(eq(Collections.singletonList("my-space2")))) .willReturn(Flux.just("space-name")); - StepVerifier.create(deleteServiceInstanceWorkflow.delete(request, response)) + StepVerifier.create(this.deleteServiceInstanceWorkflow.delete(request, response)) .expectNext() .expectNext() .verifyComplete(); @@ -288,14 +267,12 @@ class AppDeploymentDeleteServiceInstanceWorkflowTest { DeleteServiceInstanceResponse response = DeleteServiceInstanceResponse.builder().build(); given(this.backingAppManagementService.getDeployedBackingApplications(request.getServiceInstanceId(), - request.getServiceDefinition().getName(), request.getPlan().getName())) + request.getServiceDefinition().getName(), request.getPlan().getName())) .willReturn(Mono.empty()); given(this.backingSpaceManagementService.deleteTargetSpaces(any())).willReturn(Flux.empty()); - StepVerifier - .create(deleteServiceInstanceWorkflow.delete(request, response)) - .verifyComplete(); + StepVerifier.create(this.deleteServiceInstanceWorkflow.delete(request, response)).verifyComplete(); verifyNoMoreInteractionsWithServices(); } @@ -306,15 +283,16 @@ class AppDeploymentDeleteServiceInstanceWorkflowTest { DeleteServiceInstanceResponse response = DeleteServiceInstanceResponse.builder().build(); // configured backing services - given(this.targetService.addToBackingServices(eq(backingServices), eq(targetSpec), eq("service-instance-id"))) - .willReturn(Mono.just(backingServices)); + given(this.targetService.addToBackingServices(eq(this.backingServices), eq(this.targetSpec), + eq("service-instance-id"))) + .willReturn(Mono.just(this.backingServices)); // no backing apps given(this.backingAppManagementService.getDeployedBackingApplications(request.getServiceInstanceId(), - request.getServiceDefinition().getName(), request.getPlan().getName())) + request.getServiceDefinition().getName(), request.getPlan().getName())) .willReturn(Mono.empty()); - given(this.backingServicesProvisionService.deleteServiceInstance(argThat(backingServices -> { + given(this.backingServicesProvisionService.deleteServiceInstance(argThat((backingServices) -> { boolean nameMatch = "my-service-instance".equals(backingServices.get(0).getServiceInstanceName()); boolean sizeMatch = backingServices.size() == 1; return sizeMatch && nameMatch; @@ -322,7 +300,7 @@ class AppDeploymentDeleteServiceInstanceWorkflowTest { given(this.backingSpaceManagementService.deleteTargetSpaces(any())).willReturn(Flux.empty()); - StepVerifier.create(deleteServiceInstanceWorkflow.delete(request, response)) + StepVerifier.create(this.deleteServiceInstanceWorkflow.delete(request, response)) .expectNext() .expectNext() .verifyComplete(); @@ -339,48 +317,32 @@ class AppDeploymentDeleteServiceInstanceWorkflowTest { } private Map getPropertiesWithSpace(String customSpace) { - return singletonMap(DeploymentProperties.TARGET_PROPERTY_KEY, customSpace); + return Collections.singletonMap(DeploymentProperties.TARGET_PROPERTY_KEY, customSpace); } private DeleteServiceInstanceRequest buildRequest(String serviceName, String planName) { - return DeleteServiceInstanceRequest - .builder() + return DeleteServiceInstanceRequest.builder() .serviceDefinitionId(serviceName + "-id") .serviceInstanceId("service-instance-id") .planId(planName + "-id") .serviceDefinition(ServiceDefinition.builder() .id(serviceName + "-id") .name(serviceName) - .plans(Plan.builder() - .id(planName + "-id") - .name(planName) - .build()) - .build()) - .plan(Plan.builder() - .id(planName + "-id") - .name(planName) + .plans(Plan.builder().id(planName + "-id").name(planName).build()) .build()) + .plan(Plan.builder().id(planName + "-id").name(planName).build()) .build(); } private BackingApplications getExistingBackingAppsWithService(String serviceInstanceName) { - return BackingApplications - .builder() - .backingApplication(BackingApplication - .builder() + return BackingApplications.builder() + .backingApplication(BackingApplication.builder() .name("app1") - .services(ServicesSpec - .builder() - .serviceInstanceName(serviceInstanceName) - .build()) + .services(ServicesSpec.builder().serviceInstanceName(serviceInstanceName).build()) .build()) - .backingApplication(BackingApplication - .builder() + .backingApplication(BackingApplication.builder() .name("app2") - .services(ServicesSpec - .builder() - .serviceInstanceName(serviceInstanceName) - .build()) + .services(ServicesSpec.builder().serviceInstanceName(serviceInstanceName).build()) .build()) .build(); } diff --git a/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/workflow/instance/AppDeploymentInstanceWorkflowTest.java b/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/workflow/instance/AppDeploymentInstanceWorkflowTests.java similarity index 67% rename from spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/workflow/instance/AppDeploymentInstanceWorkflowTest.java rename to spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/workflow/instance/AppDeploymentInstanceWorkflowTests.java index 1ad0412..63fa075 100644 --- a/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/workflow/instance/AppDeploymentInstanceWorkflowTest.java +++ b/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/workflow/instance/AppDeploymentInstanceWorkflowTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,7 +31,7 @@ import org.springframework.cloud.servicebroker.model.catalog.ServiceDefinition; import static org.assertj.core.api.Assertions.assertThat; -class AppDeploymentInstanceWorkflowTest { +class AppDeploymentInstanceWorkflowTests { private BackingApplications backingApps; @@ -39,27 +39,16 @@ class AppDeploymentInstanceWorkflowTest { @BeforeEach void setUp() { - backingApps = BackingApplications.builder() - .backingApplication(BackingApplication.builder() - .name("app1") - .path("https://myfiles/app.jar") - .build()) + this.backingApps = BackingApplications.builder() + .backingApplication(BackingApplication.builder().name("app1").path("https://myfiles/app.jar").build()) .build(); BackingServices backingServices = BackingServices.builder() - .backingService(BackingService.builder() - .name("service1") - .plan("plan1") - .build() - ) + .backingService(BackingService.builder().name("service1").plan("plan1").build()) .build(); BrokeredServices brokeredServices = BrokeredServices.builder() - .service(BrokeredService.builder() - .serviceName("service1") - .planName("plan1") - .apps(backingApps) - .build()) + .service(BrokeredService.builder().serviceName("service1").planName("plan1").apps(this.backingApps).build()) .service(BrokeredService.builder() .serviceName("service2_without_backing_app") .planName("plan1") @@ -71,52 +60,47 @@ class AppDeploymentInstanceWorkflowTest { .build()) .build(); - workflow = new AppDeploymentInstanceWorkflow(brokeredServices); + this.workflow = new AppDeploymentInstanceWorkflow(brokeredServices); } @Test void acceptWithMatchingService() { ServiceDefinition serviceDefinition = buildServiceDefinition("service1", "plan1"); - StepVerifier - .create(workflow.accept(serviceDefinition, serviceDefinition.getPlans().get(0))) - .expectNextMatches(value -> value) + StepVerifier.create(this.workflow.accept(serviceDefinition, serviceDefinition.getPlans().get(0))) + .expectNextMatches((value) -> value) .verifyComplete(); } @Test void acceptWithMatchingServiceAndNoBackingApplication() { ServiceDefinition serviceDefinition = buildServiceDefinition("service2_without_backing_app", "plan1"); - StepVerifier - .create(workflow.accept(serviceDefinition, serviceDefinition.getPlans().get(0))) - .expectNextMatches(value -> value) + StepVerifier.create(this.workflow.accept(serviceDefinition, serviceDefinition.getPlans().get(0))) + .expectNextMatches((value) -> value) .verifyComplete(); } @Test void doNotAcceptWithMatchingServiceWithoutBackingServiceNorBackingApplication() { ServiceDefinition serviceDefinition = buildServiceDefinition("service3_without_backing_app_nor_service", - "plan1"); - StepVerifier - .create(workflow.accept(serviceDefinition, serviceDefinition.getPlans().get(0))) - .expectNextMatches(value -> !value) + "plan1"); + StepVerifier.create(this.workflow.accept(serviceDefinition, serviceDefinition.getPlans().get(0))) + .expectNextMatches((value) -> !value) .verifyComplete(); } @Test void doNotAcceptWithUnsupportedService() { ServiceDefinition serviceDefinition = buildServiceDefinition("unknown-service", "plan1"); - StepVerifier - .create(workflow.accept(serviceDefinition, serviceDefinition.getPlans().get(0))) - .expectNextMatches(value -> !value) + StepVerifier.create(this.workflow.accept(serviceDefinition, serviceDefinition.getPlans().get(0))) + .expectNextMatches((value) -> !value) .verifyComplete(); } @Test void doNotAcceptWithUnsupportedPlan() { ServiceDefinition serviceDefinition = buildServiceDefinition("service1", "unknown-plan"); - StepVerifier - .create(workflow.accept(serviceDefinition, serviceDefinition.getPlans().get(0))) - .expectNextMatches(value -> !value) + StepVerifier.create(this.workflow.accept(serviceDefinition, serviceDefinition.getPlans().get(0))) + .expectNextMatches((value) -> !value) .verifyComplete(); } @@ -124,11 +108,9 @@ class AppDeploymentInstanceWorkflowTest { void getBackingAppForServiceSucceeds() { ServiceDefinition serviceDefinition = buildServiceDefinition("service1", "plan1"); StepVerifier - .create(workflow - .getBackingApplicationsForService(serviceDefinition, serviceDefinition.getPlans().get(0))) - .assertNext(actual -> assertThat(actual) - .isEqualTo(backingApps) - .isNotSameAs(backingApps)) + .create(this.workflow.getBackingApplicationsForService(serviceDefinition, + serviceDefinition.getPlans().get(0))) + .assertNext((actual) -> assertThat(actual).isEqualTo(this.backingApps).isNotSameAs(this.backingApps)) .verifyComplete(); } @@ -136,8 +118,8 @@ class AppDeploymentInstanceWorkflowTest { void getBackingAppForServiceWithUnknownServiceIdDoesNothing() { ServiceDefinition serviceDefinition = buildServiceDefinition("unknown-service", "plan1"); StepVerifier - .create(workflow - .getBackingApplicationsForService(serviceDefinition, serviceDefinition.getPlans().get(0))) + .create(this.workflow.getBackingApplicationsForService(serviceDefinition, + serviceDefinition.getPlans().get(0))) .verifyComplete(); } @@ -145,8 +127,8 @@ class AppDeploymentInstanceWorkflowTest { void getBackingAppForServiceWithUnknownPlanIdDoesNothing() { ServiceDefinition serviceDefinition = buildServiceDefinition("service1", "unknown-plan"); StepVerifier - .create(workflow - .getBackingApplicationsForService(serviceDefinition, serviceDefinition.getPlans().get(0))) + .create(this.workflow.getBackingApplicationsForService(serviceDefinition, + serviceDefinition.getPlans().get(0))) .verifyComplete(); } @@ -154,10 +136,7 @@ class AppDeploymentInstanceWorkflowTest { return ServiceDefinition.builder() .id(serviceName + "-id") .name(serviceName) - .plans(Plan.builder() - .id(planName + "-id") - .name(planName) - .build()) + .plans(Plan.builder().id(planName + "-id").name(planName).build()) .build(); } diff --git a/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/workflow/instance/AppDeploymentUpdateServiceInstanceWorkflowTest.java b/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/workflow/instance/AppDeploymentUpdateServiceInstanceWorkflowTests.java similarity index 65% rename from spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/workflow/instance/AppDeploymentUpdateServiceInstanceWorkflowTest.java rename to spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/workflow/instance/AppDeploymentUpdateServiceInstanceWorkflowTests.java index f0abb6b..e7d67f2 100644 --- a/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/workflow/instance/AppDeploymentUpdateServiceInstanceWorkflowTest.java +++ b/spring-cloud-app-broker-core/src/test/java/org/springframework/cloud/appbroker/workflow/instance/AppDeploymentUpdateServiceInstanceWorkflowTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2021 the original author or authors. + * Copyright 2016-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,7 +49,6 @@ import org.springframework.cloud.servicebroker.model.catalog.ServiceDefinition; import org.springframework.cloud.servicebroker.model.instance.UpdateServiceInstanceRequest; import org.springframework.cloud.servicebroker.model.instance.UpdateServiceInstanceResponse; -import static java.util.Collections.singletonMap; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; @@ -58,7 +57,7 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; @ExtendWith(MockitoExtension.class) -class AppDeploymentUpdateServiceInstanceWorkflowTest { +class AppDeploymentUpdateServiceInstanceWorkflowTests { @Mock private BackingAppDeploymentService appDeploymentService; @@ -88,54 +87,39 @@ class AppDeploymentUpdateServiceInstanceWorkflowTest { @BeforeEach void setUp() { - backingApps = BackingApplications - .builder() - .backingApplication(BackingApplication.builder() - .name("app1") - .path("https://myfiles/app1.jar") - .build()) - .backingApplication(BackingApplication.builder() - .name("app2") - .path("https://myfiles/app2.jar") - .build()) + this.backingApps = BackingApplications.builder() + .backingApplication(BackingApplication.builder().name("app1").path("https://myfiles/app1.jar").build()) + .backingApplication(BackingApplication.builder().name("app2").path("https://myfiles/app2.jar").build()) .build(); - backingServices = BackingServices - .builder() - .backingService(BackingService - .builder() + this.backingServices = BackingServices.builder() + .backingService(BackingService.builder() .name("my-service") .plan("a-plan") .serviceInstanceName("my-service-instance") .build()) .build(); - targetSpec = TargetSpec.builder() - .name("TargetSpace") - .build(); + this.targetSpec = TargetSpec.builder().name("TargetSpace").build(); BrokeredServices brokeredServices = BrokeredServices.builder() .service(BrokeredService.builder() .serviceName("service1") .planName("plan1") - .apps(backingApps) - .services(backingServices) - .target(targetSpec) + .apps(this.backingApps) + .services(this.backingServices) + .target(this.targetSpec) .build()) .build(); - updateServiceInstanceWorkflow = new AppDeploymentUpdateServiceInstanceWorkflow( - brokeredServices, - appDeploymentService, - backingAppManagementService, - servicesProvisionService, - appsParametersTransformationService, - servicesParametersTransformationService, - targetService); + this.updateServiceInstanceWorkflow = new AppDeploymentUpdateServiceInstanceWorkflow(brokeredServices, + this.appDeploymentService, this.backingAppManagementService, this.servicesProvisionService, + this.appsParametersTransformationService, this.servicesParametersTransformationService, + this.targetService); } @Test - @SuppressWarnings({"UnassignedFluxMonoInstance"}) + @SuppressWarnings({ "UnassignedFluxMonoInstance" }) void updateServiceInstanceSucceeds() { UpdateServiceInstanceRequest request = buildRequest("service1", "plan1"); UpdateServiceInstanceResponse response = UpdateServiceInstanceResponse.builder().build(); @@ -143,20 +127,20 @@ class AppDeploymentUpdateServiceInstanceWorkflowTest { setupMocks(request); mockNoChangeInBackingServices(request); - StepVerifier - .create(updateServiceInstanceWorkflow.update(request, response)) + StepVerifier.create(this.updateServiceInstanceWorkflow.update(request, response)) .expectNext() .expectNext() .verifyComplete(); - InOrder updateStepOrder = inOrder(appDeploymentService, servicesProvisionService); - updateStepOrder.verify(appDeploymentService).prepareForUpdate(backingApps, request.getServiceInstanceId()); - updateStepOrder.verify(servicesProvisionService).updateServiceInstance(backingServices); - updateStepOrder.verify(appDeploymentService).update(backingApps, request.getServiceInstanceId()); + InOrder updateStepOrder = inOrder(this.appDeploymentService, this.servicesProvisionService); + updateStepOrder.verify(this.appDeploymentService) + .prepareForUpdate(this.backingApps, request.getServiceInstanceId()); + updateStepOrder.verify(this.servicesProvisionService).updateServiceInstance(this.backingServices); + updateStepOrder.verify(this.appDeploymentService).update(this.backingApps, request.getServiceInstanceId()); final String expectedServiceId = "service-instance-id"; - verify(targetService).addToBackingServices(backingServices, targetSpec, expectedServiceId); - verify(targetService).addToBackingApplications(backingApps, targetSpec, expectedServiceId); + verify(this.targetService).addToBackingServices(this.backingServices, this.targetSpec, expectedServiceId); + verify(this.targetService).addToBackingApplications(this.backingApps, this.targetSpec, expectedServiceId); verifyNoMoreInteractionsWithServices(); } @@ -164,14 +148,13 @@ class AppDeploymentUpdateServiceInstanceWorkflowTest { @Test void updateServiceInstanceWithParametersSucceeds() { UpdateServiceInstanceRequest request = buildRequest("service1", "plan1", - singletonMap("ENV_VAR_1", "value from parameters")); + Collections.singletonMap("ENV_VAR_1", "value from parameters")); UpdateServiceInstanceResponse response = UpdateServiceInstanceResponse.builder().build(); setupMocks(request); mockNoChangeInBackingServices(request); - StepVerifier - .create(updateServiceInstanceWorkflow.update(request, response)) + StepVerifier.create(this.updateServiceInstanceWorkflow.update(request, response)) .expectNext() .expectNext() .verifyComplete(); @@ -180,34 +163,30 @@ class AppDeploymentUpdateServiceInstanceWorkflowTest { } @Test - @SuppressWarnings({"UnassignedFluxMonoInstance"}) + @SuppressWarnings({ "UnassignedFluxMonoInstance" }) void updateServiceInstanceWithNewBackingServiceSucceeds() { UpdateServiceInstanceRequest request = buildRequest("service1", "plan1"); UpdateServiceInstanceResponse response = UpdateServiceInstanceResponse.builder().build(); setupMocks(request); given(this.backingAppManagementService.getDeployedBackingApplications(request.getServiceInstanceId(), - request.getServiceDefinition().getName(), request.getPlan().getName())) + request.getServiceDefinition().getName(), request.getPlan().getName())) .willReturn(Mono.just(getExistingBackingAppsWithService("existing-service-instance"))); - given(this.servicesProvisionService.createServiceInstance(any())) - .willReturn(Flux.just("my-service-instance")); + given(this.servicesProvisionService.createServiceInstance(any())).willReturn(Flux.just("my-service-instance")); given(this.servicesProvisionService.deleteServiceInstance(any())) .willReturn(Flux.just("existing-service-instance")); given(this.servicesProvisionService.updateServiceInstance(eq(Collections.emptyList()))) .willReturn(Flux.empty()); - StepVerifier - .create(updateServiceInstanceWorkflow.update(request, response)) + StepVerifier.create(this.updateServiceInstanceWorkflow.update(request, response)) .expectNext() .expectNext() .verifyComplete(); - verify(servicesProvisionService).createServiceInstance(backingServices); - verify(servicesProvisionService).deleteServiceInstance(BackingServices - .builder() - .backingService(BackingService - .builder() - .properties(singletonMap("target", "customTarget")) + verify(this.servicesProvisionService).createServiceInstance(this.backingServices); + verify(this.servicesProvisionService).deleteServiceInstance(BackingServices.builder() + .backingService(BackingService.builder() + .properties(Collections.singletonMap("target", "customTarget")) .serviceInstanceName("existing-service-instance") .build()) .build()); @@ -220,43 +199,40 @@ class AppDeploymentUpdateServiceInstanceWorkflowTest { UpdateServiceInstanceRequest request = buildRequest("unsupported-service", "plan1"); UpdateServiceInstanceResponse response = UpdateServiceInstanceResponse.builder().build(); - StepVerifier - .create(updateServiceInstanceWorkflow.update(request, response)) - .verifyComplete(); + StepVerifier.create(this.updateServiceInstanceWorkflow.update(request, response)).verifyComplete(); verifyNoMoreInteractionsWithServices(); } private void setupMocks(UpdateServiceInstanceRequest request) { - given(this.appDeploymentService.prepareForUpdate(eq(backingApps), eq(request.getServiceInstanceId()))) + given(this.appDeploymentService.prepareForUpdate(eq(this.backingApps), eq(request.getServiceInstanceId()))) .willReturn(Flux.just("app1", "app2")); - given(this.appDeploymentService.update(eq(backingApps), eq(request.getServiceInstanceId()))) + given(this.appDeploymentService.update(eq(this.backingApps), eq(request.getServiceInstanceId()))) .willReturn(Flux.just("app1", "app2")); - given( - this.appsParametersTransformationService.transformParameters(eq(backingApps), eq(request.getParameters()))) - .willReturn(Mono.just(backingApps)); - given(this.servicesParametersTransformationService - .transformParameters(eq(backingServices), eq(request.getParameters()))) - .willReturn(Mono.just(backingServices)); + given(this.appsParametersTransformationService.transformParameters(eq(this.backingApps), + eq(request.getParameters()))) + .willReturn(Mono.just(this.backingApps)); + given(this.servicesParametersTransformationService.transformParameters(eq(this.backingServices), + eq(request.getParameters()))) + .willReturn(Mono.just(this.backingServices)); - given(this.targetService.addToBackingApplications(eq(backingApps), eq(targetSpec), eq("service-instance-id"))) - .willReturn(Mono.just(backingApps)); - given(this.targetService - .addToBackingServices(eq(backingServices), eq(targetSpec), eq(request.getServiceInstanceId()))) - .willReturn(Mono.just(backingServices)); + given(this.targetService.addToBackingApplications(eq(this.backingApps), eq(this.targetSpec), + eq("service-instance-id"))) + .willReturn(Mono.just(this.backingApps)); + given(this.targetService.addToBackingServices(eq(this.backingServices), eq(this.targetSpec), + eq(request.getServiceInstanceId()))) + .willReturn(Mono.just(this.backingServices)); } private void mockNoChangeInBackingServices(UpdateServiceInstanceRequest request) { - given(this.servicesProvisionService.updateServiceInstance(eq(backingServices))) + given(this.servicesProvisionService.updateServiceInstance(eq(this.backingServices))) .willReturn(Flux.just("my-service-instance")); - given(this.servicesProvisionService.createServiceInstance(any())) - .willReturn(Flux.empty()); - given(this.servicesProvisionService.deleteServiceInstance(any())) - .willReturn(Flux.empty()); + given(this.servicesProvisionService.createServiceInstance(any())).willReturn(Flux.empty()); + given(this.servicesProvisionService.deleteServiceInstance(any())).willReturn(Flux.empty()); given(this.backingAppManagementService.getDeployedBackingApplications(request.getServiceInstanceId(), - request.getServiceDefinition().getName(), request.getPlan().getName())) + request.getServiceDefinition().getName(), request.getPlan().getName())) .willReturn(Mono.just(getExistingBackingAppsWithService("my-service-instance"))); } @@ -273,25 +249,18 @@ class AppDeploymentUpdateServiceInstanceWorkflowTest { } private UpdateServiceInstanceRequest buildRequest(String serviceName, String planName, - Map parameters) { - return UpdateServiceInstanceRequest - .builder() + Map parameters) { + return UpdateServiceInstanceRequest.builder() .serviceInstanceId("service-instance-id") .serviceDefinitionId(serviceName + "-id") .planId(planName + "-id") .serviceDefinition(ServiceDefinition.builder() .id(serviceName + "-id") .name(serviceName) - .plans(Plan.builder() - .id(planName + "-id") - .name(planName) - .build()) + .plans(Plan.builder().id(planName + "-id").name(planName).build()) .build()) - .plan(Plan.builder() - .id(planName + "-id") - .name(planName) - .build()) - .parameters(parameters == null ? new HashMap<>() : parameters) + .plan(Plan.builder().id(planName + "-id").name(planName).build()) + .parameters((parameters != null) ? parameters : new HashMap<>()) .build(); } @@ -299,25 +268,16 @@ class AppDeploymentUpdateServiceInstanceWorkflowTest { Map properties = new HashMap<>(); properties.put("target", "customTarget"); properties.put("not-important-property", "not-important-value"); - return BackingApplications - .builder() - .backingApplication(BackingApplication - .builder() + return BackingApplications.builder() + .backingApplication(BackingApplication.builder() .name("app1") .properties(properties) - .services(ServicesSpec - .builder() - .serviceInstanceName(serviceInstanceName) - .build()) + .services(ServicesSpec.builder().serviceInstanceName(serviceInstanceName).build()) .build()) - .backingApplication(BackingApplication - .builder() + .backingApplication(BackingApplication.builder() .name("app2") .properties(properties) - .services(ServicesSpec - .builder() - .serviceInstanceName(serviceInstanceName) - .build()) + .services(ServicesSpec.builder().serviceInstanceName(serviceInstanceName).build()) .build()) .build(); } diff --git a/spring-cloud-app-broker-deployer-cloudfoundry/build.gradle b/spring-cloud-app-broker-deployer-cloudfoundry/build.gradle index 52b943f..be5bbae 100644 --- a/spring-cloud-app-broker-deployer-cloudfoundry/build.gradle +++ b/spring-cloud-app-broker-deployer-cloudfoundry/build.gradle @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-cloud-app-broker-deployer-cloudfoundry/src/main/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryAppDeployer.java b/spring-cloud-app-broker-deployer-cloudfoundry/src/main/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryAppDeployer.java index 8893449..2ce0dc2 100644 --- a/spring-cloud-app-broker-deployer-cloudfoundry/src/main/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryAppDeployer.java +++ b/spring-cloud-app-broker-deployer-cloudfoundry/src/main/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryAppDeployer.java @@ -164,11 +164,8 @@ public class CloudFoundryAppDeployer implements AppDeployer, ResourceLoaderAware private ResourceLoader resourceLoader; public CloudFoundryAppDeployer(CloudFoundryDeploymentProperties deploymentProperties, - CloudFoundryOperations operations, - CloudFoundryClient client, - CloudFoundryOperationsUtils operationsUtils, - CloudFoundryTargetProperties targetProperties, - ResourceLoader resourceLoader) { + CloudFoundryOperations operations, CloudFoundryClient client, CloudFoundryOperationsUtils operationsUtils, + CloudFoundryTargetProperties targetProperties, ResourceLoader resourceLoader) { this.defaultDeploymentProperties = deploymentProperties; this.operations = operations; this.client = client; @@ -186,44 +183,43 @@ public class CloudFoundryAppDeployer implements AppDeployer, ResourceLoaderAware public Mono get(GetApplicationRequest request) { final String appName = request.getName(); - return operationsUtils.getOperations(request.getProperties()) - .flatMap(cfOperations -> cfOperations.applications() - .get(org.cloudfoundry.operations.applications.GetApplicationRequest.builder() - .name(appName) - .build()) - .doOnRequest(l -> { + return this.operationsUtils.getOperations(request.getProperties()) + .flatMap((cfOperations) -> cfOperations.applications() + .get(org.cloudfoundry.operations.applications.GetApplicationRequest.builder().name(appName).build()) + .doOnRequest((l) -> { LOG.info("Getting application. appName={}", appName); LOG.debug(REQUEST_LOG_TEMPLATE, request); }) - .doOnSuccess(response -> { + .doOnSuccess((response) -> { LOG.info("Success getting application. appName={}", appName); LOG.debug(RESPONSE_LOG_TEMPLATE, response); }) - .doOnError(e -> LOG.error(String.format("Error getting application. appName=%s, " + ERROR_LOG_TEMPLATE, - appName, e.getMessage()), e)) + .doOnError( + (e) -> LOG.error(String.format("Error getting application. appName=%s, " + ERROR_LOG_TEMPLATE, + appName, e.getMessage()), e)) .map(ApplicationDetail::getId) - .flatMap(id -> client.applicationsV2().summary(SummaryApplicationRequest.builder() - .applicationId(id) - .build()))) - .flatMap(summary -> Flux.fromIterable(summary.getServices()) + .flatMap((id) -> this.client.applicationsV2() + .summary(SummaryApplicationRequest.builder().applicationId(id).build()))) + .flatMap((summary) -> Flux.fromIterable(summary.getServices()) .map(org.cloudfoundry.client.v2.serviceinstances.ServiceInstance::getName) .collectList() - .map(services -> GetApplicationResponse.builder() + .map((services) -> GetApplicationResponse.builder() .id(summary.getId()) .name(summary.getName()) .services(services) .environment(summary.getEnvironmentJsons()) .build())) - .doOnRequest(l -> { + .doOnRequest((l) -> { LOG.info("Getting application summary. appName={}", appName); LOG.debug(REQUEST_LOG_TEMPLATE, request); }) - .doOnSuccess(response -> { + .doOnSuccess((response) -> { LOG.info("Success getting application summary. appName={}", appName); LOG.debug(RESPONSE_LOG_TEMPLATE, response); }) - .doOnError(e -> LOG.error(String.format("Error getting application summary. appName=%s, " + - ERROR_LOG_TEMPLATE, appName, e.getMessage()), e)); + .doOnError((e) -> LOG + .error(String.format("Error getting application summary. appName=%s, " + ERROR_LOG_TEMPLATE, appName, + e.getMessage()), e)); } @Override @@ -233,37 +229,31 @@ public class CloudFoundryAppDeployer implements AppDeployer, ResourceLoaderAware Map deploymentProperties = request.getProperties(); if (LOG.isTraceEnabled()) { - LOG.trace("Deploying application: request={}, resource={}", - appName, appResource); + LOG.trace("Deploying application: request={}, resource={}", appName, appResource); } return pushApplication(request, deploymentProperties, appResource) .timeout(Duration.ofSeconds(this.defaultDeploymentProperties.getApiTimeout())) - .doOnSuccess(item -> LOG.info("Successfully deployed {}", appName)) - .doOnError(e -> { + .doOnSuccess((item) -> LOG.info("Successfully deployed {}", appName)) + .doOnError((e) -> { if (httpStatusNotFoundPredicate().test(e)) { - LOG.error(String.format("Unable to deploy application. It may have been destroyed before " + - "start completed. " + ERROR_LOG_TEMPLATE, e.getMessage()), e); + LOG.error(String.format("Unable to deploy application. It may have been destroyed before " + + "start completed. " + ERROR_LOG_TEMPLATE, e.getMessage()), e); } else { logError(String.format("Error deploying application. appName=%s", appName)).accept(e); } }) - .thenReturn(DeployApplicationResponse.builder() - .name(appName) - .build()); + .thenReturn(DeployApplicationResponse.builder().name(appName).build()); } @Override public Mono preUpdate(UpdateApplicationRequest request) { final String appName = request.getName(); - return get(GetApplicationRequest.builder() - .name(appName) - .properties(request.getProperties()) - .build()) + return get(GetApplicationRequest.builder().name(appName).properties(request.getProperties()).build()) .map(GetApplicationResponse::getId) - .flatMap(applicationId -> updateApplication(request, applicationId)) + .flatMap((applicationId) -> updateApplication(request, applicationId)) .thenReturn(UpdateApplicationResponse.builder().name(appName).build()); } @@ -271,12 +261,9 @@ public class CloudFoundryAppDeployer implements AppDeployer, ResourceLoaderAware public Mono update(UpdateApplicationRequest request) { final String appName = request.getName(); - return get(GetApplicationRequest.builder() - .name(appName) - .properties(request.getProperties()) - .build()) - .flatMap(response -> bindNewServices(response, request.getServices(), request.getProperties())) - .flatMap(applicationId -> { + return get(GetApplicationRequest.builder().name(appName).properties(request.getProperties()).build()) + .flatMap((response) -> bindNewServices(response, request.getServices(), request.getProperties())) + .flatMap((applicationId) -> { if (request.getProperties().containsKey("routes")) { return associateRoutes(applicationId, request.getProperties()); } @@ -284,41 +271,41 @@ public class CloudFoundryAppDeployer implements AppDeployer, ResourceLoaderAware return associateHostName(applicationId, request.getProperties()); } }) - .flatMap(applicationId -> updateApplication(request, applicationId)) - .flatMap(applicationId -> Mono.zip(Mono.just(applicationId), - upgradeApplicationIfRequired(request, applicationId))) - .flatMap(tuple2 -> { + .flatMap((applicationId) -> updateApplication(request, applicationId)) + .flatMap((applicationId) -> Mono.zip(Mono.just(applicationId), + upgradeApplicationIfRequired(request, applicationId))) + .flatMap((tuple2) -> { String appId = tuple2.getT1(); String packageId = tuple2.getT2(); return Mono.zip(Mono.just(appId), createBuildForPackage(packageId)); }) - .flatMap(tuple2 -> { + .flatMap((tuple2) -> { String appId = tuple2.getT1(); String buildId = tuple2.getT2(); return Mono.zip(Mono.just(appId), waitForBuildStaged(buildId)); }) - .map(tuple2 -> tuple2.mapT2((t2) -> t2.getDroplet().getId())) - .flatMap(tuple2 -> { + .map((tuple2) -> tuple2.mapT2((t2) -> t2.getDroplet().getId())) + .flatMap((tuple2) -> { String appId = tuple2.getT1(); String dropletId = tuple2.getT2(); return createDeployment(dropletId, appId); }) .map(CreateDeploymentResponse::getId) .flatMap(this::waitForDeploymentDeployed) - .doOnRequest(l -> { + .doOnRequest((l) -> { LOG.info("Updating application. appName={}", appName); LOG.debug(REQUEST_LOG_TEMPLATE, request); }) - .doOnSuccess(response -> { + .doOnSuccess((response) -> { LOG.info("Success updating application. appName={}", appName); LOG.debug(RESPONSE_LOG_TEMPLATE, response); }) - .doOnError(e -> LOG.error(String.format("Error updating application. appName=%s", appName), e)) + .doOnError((e) -> LOG.error(String.format("Error updating application. appName=%s", appName), e)) .thenReturn(UpdateApplicationResponse.builder().name(appName).build()); } private Mono bindNewServices(GetApplicationResponse deployedApp, List services, - Map properties) { + Map properties) { String id = deployedApp.getId(); List boundServices = deployedApp.getServices(); List servicesToBind = new ArrayList<>(services); @@ -329,18 +316,20 @@ public class CloudFoundryAppDeployer implements AppDeployer, ResourceLoaderAware } String appName = deployedApp.getName(); - return operationsUtils.getOperations(properties) - .flatMapMany(cfOperations -> Flux.fromIterable(servicesToBind) - .flatMap(service -> cfOperations.services().bind(BindServiceInstanceRequest.builder() - .applicationName(appName) - .serviceInstanceName(service) - .build()) - .doOnRequest( - l -> LOG.info("Binding application to service. appName={}, serviceName={}", appName, service)) - .doOnNext(v -> LOG.info("Success binding application to service. appName={}, service={}", appName, - service)) - .doOnError(e -> LOG.error(String.format("Error binding application to service. appName=%s, " + - "service=%s", appName, service), e)))) + return this.operationsUtils.getOperations(properties) + .flatMapMany((cfOperations) -> Flux.fromIterable(servicesToBind) + .flatMap((service) -> cfOperations.services() + .bind(BindServiceInstanceRequest.builder() + .applicationName(appName) + .serviceInstanceName(service) + .build()) + .doOnRequest((l) -> LOG.info("Binding application to service. appName={}, serviceName={}", appName, + service)) + .doOnNext((v) -> LOG.info("Success binding application to service. appName={}, service={}", appName, + service)) + .doOnError((e) -> LOG.error(String + .format("Error binding application to service. appName=%s, " + "service=%s", appName, service), + e)))) .then() .thenReturn(id); } @@ -353,60 +342,61 @@ public class CloudFoundryAppDeployer implements AppDeployer, ResourceLoaderAware return Mono.just(applicationId); } - return operationsUtils.getOperations(properties) - .map(cfOperations -> cfOperations.domains().list()) + return this.operationsUtils.getOperations(properties) + .map((cfOperations) -> cfOperations.domains().list()) .flatMap(Flux::collectList) - .map(allDomains -> Stream.concat(Stream.of(domain), domains.stream()) - .map(d -> getDomainId(d, allDomains)) + .map((allDomains) -> Stream.concat(Stream.of(domain), domains.stream()) + .map((d) -> getDomainId(d, allDomains)) .collect(Collectors.toSet())) .zipWith(getSpaceId(properties)) - .flatMapMany(domainIdsWithSpaceId -> { + .flatMapMany((domainIdsWithSpaceId) -> { Set uniqueDomainIds = domainIdsWithSpaceId.getT1(); String spaceId = domainIdsWithSpaceId.getT2(); return Flux.fromIterable(uniqueDomainIds) - .flatMap(domainId -> associateHostForDomain(applicationId, host, domainId, spaceId)); + .flatMap((domainId) -> associateHostForDomain(applicationId, host, domainId, spaceId)); }) .then(Mono.just(applicationId)); } private Mono associateRoutes(String applicationId, Map properties) { List routes = Arrays.stream(properties.get("routes").split(",")) - .map(uri -> uri.split("\\.", 2)) + .map((uri) -> uri.split("\\.", 2)) .collect(Collectors.toList()); return Mono.just(routes) - .zipWith(operationsUtils.getOperations(properties) - .map(cfOperations -> cfOperations.domains().list()) - .flatMap(domains -> domains.collectMap(Domain::getName))) + .zipWith(this.operationsUtils.getOperations(properties) + .map((cfOperations) -> cfOperations.domains().list()) + .flatMap((domains) -> domains.collectMap(Domain::getName))) .zipWith(getSpaceId(properties)) - .flatMapMany(routesDomainsAndSpace -> { + .flatMapMany((routesDomainsAndSpace) -> { List routesComponents = routesDomainsAndSpace.getT1().getT1(); Map domainsByName = routesDomainsAndSpace.getT1().getT2(); String spaceId = routesDomainsAndSpace.getT2(); - return Flux.fromStream(routesComponents.stream() - .map(route -> new String[] {route[0], domainsByName.get(route[1]).getId()})) - .flatMap( - hostAndDomainId -> associateHostForDomain(applicationId, hostAndDomainId[0], hostAndDomainId[1], - spaceId)); + return Flux + .fromStream(routesComponents.stream() + .map((route) -> new String[] { route[0], domainsByName.get(route[1]).getId() })) + .flatMap((hostAndDomainId) -> associateHostForDomain(applicationId, hostAndDomainId[0], + hostAndDomainId[1], spaceId)); }) .then(Mono.just(applicationId)); } private Mono associateHostForDomain(String applicationId, String host, String domainId, String spaceId) { - return client.routes() + return this.client.routes() .create(org.cloudfoundry.client.v2.routes.CreateRouteRequest.builder() .domainId(domainId) .spaceId(spaceId) .host(host) .build()) - .map(response -> response.getMetadata().getId()) - .doOnError(error -> LOG.info("Host was already associated. host={}", host)) - .onErrorResume(e -> Mono.empty()) - .flatMap(routeId -> client.applicationsV2().associateRoute(AssociateApplicationRouteRequest.builder() - .applicationId(applicationId) - .routeId(routeId) - .build())) + .map((response) -> response.getMetadata().getId()) + .doOnError((error) -> LOG.info("Host was already associated. host={}", host)) + .onErrorResume((e) -> Mono.empty()) + .flatMap((routeId) -> this.client.applicationsV2() + .associateRoute(AssociateApplicationRouteRequest.builder() + .applicationId(applicationId) + .routeId(routeId) + .build())) .then(); } @@ -416,15 +406,9 @@ public class CloudFoundryAppDeployer implements AppDeployer, ResourceLoaderAware space = properties.get(DeploymentProperties.TARGET_PROPERTY_KEY); } else { - space = targetProperties.getDefaultSpace(); + space = this.targetProperties.getDefaultSpace(); } - return operations - .spaces() - .get(GetSpaceRequest - .builder() - .name(space) - .build()) - .map(SpaceDetail::getId); + return this.operations.spaces().get(GetSpaceRequest.builder().name(space).build()).map(SpaceDetail::getId); } private String getDomainId(String domain, List domains) { @@ -433,7 +417,7 @@ public class CloudFoundryAppDeployer implements AppDeployer, ResourceLoaderAware } return domains.stream() - .filter(d -> d.getName().equals(domain)) + .filter((d) -> d.getName().equals(domain)) .findFirst() .orElseThrow(() -> new RuntimeException("Non existing domain")) .getId(); @@ -441,27 +425,25 @@ public class CloudFoundryAppDeployer implements AppDeployer, ResourceLoaderAware private String getDefaultDomainId(List domains) { return domains.stream() - .filter(d -> !"internal".equals(d.getType())) - .findFirst().orElseThrow(RuntimeException::new) + .filter((d) -> !"internal".equals(d.getType())) + .findFirst() + .orElseThrow(RuntimeException::new) .getId(); } private Mono waitForDeploymentDeployed(String deploymentId) { - return this.client - .deploymentsV3() - .get(GetDeploymentRequest - .builder() - .deploymentId(deploymentId) - .build()) + return this.client.deploymentsV3() + .get(GetDeploymentRequest.builder().deploymentId(deploymentId).build()) .filter(this::deploymentFinished) .repeatWhenEmpty(getExponentialBackOff(getDeploymentTimeout())) - .doOnRequest(l -> LOG.debug("Waiting for deployment to complete. deploymentId={}", deploymentId)) - .doOnSuccess(response -> { + .doOnRequest((l) -> LOG.debug("Waiting for deployment to complete. deploymentId={}", deploymentId)) + .doOnSuccess((response) -> { LOG.info("Success waiting for deployment to complete. deploymentId={}", deploymentId); LOG.debug(RESPONSE_LOG_TEMPLATE, response); }) - .doOnError(e -> LOG.error(String.format("Error waiting for deployment to complete. deploymentId=%s, " + - ERROR_LOG_TEMPLATE, deploymentId, e.getMessage()), e)); + .doOnError((e) -> LOG + .error(String.format("Error waiting for deployment to complete. deploymentId=%s, " + ERROR_LOG_TEMPLATE, + deploymentId, e.getMessage()), e)); } @SuppressWarnings("deprecation") @@ -471,113 +453,102 @@ public class CloudFoundryAppDeployer implements AppDeployer, ResourceLoaderAware } return p.getStatus().getValue().equals(DeploymentStatusValue.FINALIZED) - && p.getStatus().getReason().equals(DeploymentStatusReason.DEPLOYED); + && p.getStatus().getReason().equals(DeploymentStatusReason.DEPLOYED); } private Mono createDeployment(String dropletId, String applicationId) { - return this.client - .deploymentsV3() - .create(CreateDeploymentRequest - .builder() - .droplet(Relationship - .builder() - .id(dropletId).build()).relationships(DeploymentRelationships - .builder() - .app(ToOneRelationship - .builder() - .data(Relationship.builder().id(applicationId).build()) - .build() - ).build()) + return this.client.deploymentsV3() + .create(CreateDeploymentRequest.builder() + .droplet(Relationship.builder().id(dropletId).build()) + .relationships(DeploymentRelationships.builder() + .app(ToOneRelationship.builder().data(Relationship.builder().id(applicationId).build()).build()) + .build()) .build()) - .doOnRequest(l -> LOG.debug("Creating deployment for application. applicationId={}", applicationId)) - .doOnSuccess(response -> { + .doOnRequest((l) -> LOG.debug("Creating deployment for application. applicationId={}", applicationId)) + .doOnSuccess((response) -> { LOG.info("Success creating deployment for application. applicationId={}", applicationId); LOG.debug(RESPONSE_LOG_TEMPLATE, response); }) - .doOnError(e -> LOG.error(String.format("Error creating deployment for application. applicationId=%s, " + - ERROR_LOG_TEMPLATE, applicationId, e.getMessage()), e)); + .doOnError((e) -> LOG.error( + String.format("Error creating deployment for application. applicationId=%s, " + ERROR_LOG_TEMPLATE, + applicationId, e.getMessage()), + e)); } private Mono waitForBuildStaged(String buildId) { - return this.client.builds().get(GetBuildRequest.builder() - .buildId(buildId) - .build()) - .filter(p -> p.getState().equals(BuildState.STAGED)) + return this.client.builds() + .get(GetBuildRequest.builder().buildId(buildId).build()) + .filter((p) -> p.getState().equals(BuildState.STAGED)) .repeatWhenEmpty(getExponentialBackOff(getStagingTimeout())) - .doOnRequest(l -> LOG.debug("Waiting for build to stage. buildId={}", buildId)) - .doOnSuccess(response -> { + .doOnRequest((l) -> LOG.debug("Waiting for build to stage. buildId={}", buildId)) + .doOnSuccess((response) -> { LOG.info("Success waiting for build to stage. buildId={}", buildId); LOG.debug(RESPONSE_LOG_TEMPLATE, response); }) - .doOnError(e -> LOG.error(String.format("Error waiting for build to stage. buildId=%s, " + - ERROR_LOG_TEMPLATE, buildId, e.getMessage()), e)); + .doOnError((e) -> LOG.error(String + .format("Error waiting for build to stage. buildId=%s, " + ERROR_LOG_TEMPLATE, buildId, e.getMessage()), + e)); } private Mono createBuildForPackage(String packageId) { - return this.client - .builds() - .create(CreateBuildRequest - .builder() - .getPackage(Relationship.builder().id(packageId).build()) - .build()) + return this.client.builds() + .create(CreateBuildRequest.builder().getPackage(Relationship.builder().id(packageId).build()).build()) .map(CreateBuildResponse::getId) - .doOnRequest(l -> LOG.debug("Creating build for package. packageId={}", packageId)) - .doOnSuccess(response -> { + .doOnRequest((l) -> LOG.debug("Creating build for package. packageId={}", packageId)) + .doOnSuccess((response) -> { LOG.info("Success creating build for package. packageId={}", packageId); LOG.debug(RESPONSE_LOG_TEMPLATE, response); }) - .doOnError(e -> LOG.error(String.format("Error creating build package. packageId=%s, " + - ERROR_LOG_TEMPLATE, packageId, e.getMessage()), e)); + .doOnError( + (e) -> LOG.error(String.format("Error creating build package. packageId=%s, " + ERROR_LOG_TEMPLATE, + packageId, e.getMessage()), e)); } private Mono waitForPackageReady(String packageId) { - return this.client - .packages() + return this.client.packages() .get(GetPackageRequest.builder().packageId(packageId).build()) - .filter(p -> p.getState().equals(PackageState.READY)) + .filter((p) -> p.getState().equals(PackageState.READY)) .repeatWhenEmpty(getExponentialBackOff(DEFAULT_PLATFORM_OPERATION_DURATION)) - .doOnRequest(l -> LOG.debug("Waiting for package ready. packageId={}", packageId)) - .doOnSuccess(response -> { + .doOnRequest((l) -> LOG.debug("Waiting for package ready. packageId={}", packageId)) + .doOnSuccess((response) -> { LOG.info("Success waiting for package ready. packageId={}", packageId); LOG.debug(RESPONSE_LOG_TEMPLATE, response); }) - .doOnError(e -> LOG.error(String.format("Error waiting for package ready. packageId=%s, " + - ERROR_LOG_TEMPLATE, packageId, e.getMessage()), e)); + .doOnError((e) -> LOG + .error(String.format("Error waiting for package ready. packageId=%s, " + ERROR_LOG_TEMPLATE, packageId, + e.getMessage()), e)); } private Mono uploadPackage(UpdateApplicationRequest request, String packageId) { try { - return this.client - .packages() - .upload(UploadPackageRequest - .builder() + return this.client.packages() + .upload(UploadPackageRequest.builder() .packageId(packageId) .bits(Paths.get(getAppResource(request.getPath()).getURI())) .build()) - .doOnRequest(l -> { + .doOnRequest((l) -> { LOG.info("Uploading package. packageId={}", packageId); LOG.debug(REQUEST_LOG_TEMPLATE, request); }) - .doOnSuccess(response -> { + .doOnSuccess((response) -> { LOG.info("Success uploading package. packageId={}", packageId); LOG.debug(RESPONSE_LOG_TEMPLATE, response); }) - .doOnError(e -> LOG.error(String.format("Error uploading package. packageId=%s, " + ERROR_LOG_TEMPLATE, - packageId, e.getMessage()), e)); + .doOnError( + (e) -> LOG.error(String.format("Error uploading package. packageId=%s, " + ERROR_LOG_TEMPLATE, + packageId, e.getMessage()), e)); } - catch (IOException e) { - throw Exceptions.propagate(e); + catch (IOException ex) { + throw Exceptions.propagate(ex); } } private Mono upgradeApplicationIfRequired(UpdateApplicationRequest request, String applicationId) { if (request.getProperties().containsKey("upgrade")) { - return createPackageForApplication(applicationId) - .map(CreatePackageResponse::getId) - .flatMap(packageId -> uploadPackage(request, packageId)) + return createPackageForApplication(applicationId).map(CreatePackageResponse::getId) + .flatMap((packageId) -> uploadPackage(request, packageId)) .map(UploadPackageResponse::getId) - .flatMap(packageId -> waitForPackageReady(packageId) - .map(Package::getId)); + .flatMap((packageId) -> waitForPackageReady(packageId).map(Package::getId)); } return getPackageForApplication(applicationId); @@ -585,112 +556,100 @@ public class CloudFoundryAppDeployer implements AppDeployer, ResourceLoaderAware private Mono updateApplication(UpdateApplicationRequest request, String applicationId) { final Map environmentVariables = getApplicationEnvironment(request.getProperties(), - request.getEnvironment(), request.getServiceInstanceId()); + request.getEnvironment(), request.getServiceInstanceId()); Map properties = request.getProperties(); - return updateStackIfPresent(request, applicationId) - .then(this.client.applicationsV2() - .update(org.cloudfoundry.client.v2.applications.UpdateApplicationRequest.builder() - .applicationId(applicationId) - .instances(instances(properties)) - .diskQuota(diskQuota(properties)) - .memory(memory(properties)) - .putAllEnvironmentJsons(environmentVariables) - .build()) - .doOnRequest(l -> LOG.debug("Updating environment. applicationId={}", applicationId)) - .doOnSuccess(response -> { - LOG.info("Success updating environment. applicationId={}", applicationId); - LOG.debug(RESPONSE_LOG_TEMPLATE, response); - }) - .doOnError(e -> LOG.error(String.format("Error updating environment. applicationId=%s, " + - ERROR_LOG_TEMPLATE, applicationId, e.getMessage()), e))) + return updateStackIfPresent(request, applicationId).then(this.client.applicationsV2() + .update(org.cloudfoundry.client.v2.applications.UpdateApplicationRequest.builder() + .applicationId(applicationId) + .instances(instances(properties)) + .diskQuota(diskQuota(properties)) + .memory(memory(properties)) + .putAllEnvironmentJsons(environmentVariables) + .build()) + .doOnRequest((l) -> LOG.debug("Updating environment. applicationId={}", applicationId)) + .doOnSuccess((response) -> { + LOG.info("Success updating environment. applicationId={}", applicationId); + LOG.debug(RESPONSE_LOG_TEMPLATE, response); + }) + .doOnError((e) -> LOG + .error(String.format("Error updating environment. applicationId=%s, " + ERROR_LOG_TEMPLATE, + applicationId, e.getMessage()), e))) .thenReturn(applicationId); } private Mono updateStackIfPresent(UpdateApplicationRequest request, String applicationId) { - if (!request.getProperties().containsKey("upgrade") || - !StringUtils.hasText(this.defaultDeploymentProperties.getStack())) { + if (!request.getProperties().containsKey("upgrade") + || !StringUtils.hasText(this.defaultDeploymentProperties.getStack())) { return Mono.just(applicationId); } String stackName = this.defaultDeploymentProperties.getStack(); - return this.client.applicationsV3(). - update(org.cloudfoundry.client.v3.applications.UpdateApplicationRequest.builder() + return this.client.applicationsV3() + .update(org.cloudfoundry.client.v3.applications.UpdateApplicationRequest.builder() .applicationId(applicationId) .lifecycle(Lifecycle.builder() .type(LifecycleType.BUILDPACK) - .data(BuildpackData.builder() - .stack(stackName) - .build()) + .data(BuildpackData.builder().stack(stackName).build()) .build()) .build()) .thenReturn(applicationId); } private Mono getPackageForApplication(String applicationId) { - return this.client - .applicationsV3() - .listPackages(ListApplicationPackagesRequest - .builder() + return this.client.applicationsV3() + .listPackages(ListApplicationPackagesRequest.builder() .applicationId(applicationId) .state(PackageState.READY) .build()) - .doOnRequest(l -> LOG.debug("Getting application package. applicationId={}", applicationId)) - .doOnSuccess(response -> { + .doOnRequest((l) -> LOG.debug("Getting application package. applicationId={}", applicationId)) + .doOnSuccess((response) -> { LOG.info("Success getting application package. applicationId={}", applicationId); LOG.debug(RESPONSE_LOG_TEMPLATE, response); }) - .doOnError(e -> LOG.error(String.format("Error getting application package. applicationId=%s, " + - ERROR_LOG_TEMPLATE, applicationId, e.getMessage()), e)) + .doOnError((e) -> LOG + .error(String.format("Error getting application package. applicationId=%s, " + ERROR_LOG_TEMPLATE, + applicationId, e.getMessage()), e)) .map(ListApplicationPackagesResponse::getResources) .map(this::getLastUpdatedPackageId); } private String getLastUpdatedPackageId(List packageResources) { - return packageResources - .stream() + return packageResources.stream() .min((h1, h2) -> Instant.parse(h2.getUpdatedAt()).compareTo(Instant.parse(h1.getUpdatedAt()))) .orElse(packageResources.get(0)) .getId(); } private Mono createPackageForApplication(String applicationId) { - return this.client - .packages() - .create(CreatePackageRequest - .builder() - .relationships(PackageRelationships - .builder() - .application(ToOneRelationship - .builder() - .data(Relationship - .builder() - .id(applicationId) - .build()) - .build()) + return this.client.packages() + .create(CreatePackageRequest.builder() + .relationships(PackageRelationships.builder() + .application( + ToOneRelationship.builder().data(Relationship.builder().id(applicationId).build()).build()) .build()) .type(PackageType.BITS) .build()) - .doOnRequest(l -> LOG.debug("Creating package. applicationId={}", applicationId)) - .doOnSuccess(response -> { + .doOnRequest((l) -> LOG.debug("Creating package. applicationId={}", applicationId)) + .doOnSuccess((response) -> { LOG.info("Success creating package. applicationId={}", applicationId); LOG.debug(RESPONSE_LOG_TEMPLATE, response); }) - .doOnError(e -> LOG.error(String.format("Error creating package. applicationId=%s, " + ERROR_LOG_TEMPLATE, - applicationId, e.getMessage()), e)); + .doOnError((e) -> LOG.error(String.format("Error creating package. applicationId=%s, " + ERROR_LOG_TEMPLATE, + applicationId, e.getMessage()), e)); } private Duration getStagingTimeout() { - if (targetProperties.getStagingTimeout() == null) { + if (this.targetProperties.getStagingTimeout() == null) { return DEFAULT_PLATFORM_OPERATION_DURATION; } - return Duration.ofMinutes(targetProperties.getStagingTimeout()); + return Duration.ofMinutes(this.targetProperties.getStagingTimeout()); } private Duration getDeploymentTimeout() { - if (targetProperties.getDeploymentTimeout() == null) { + if (this.targetProperties.getDeploymentTimeout() == null) { return DEFAULT_PLATFORM_OPERATION_DURATION; } - return Duration.ofMinutes(targetProperties.getDeploymentTimeout()); + return Duration.ofMinutes(this.targetProperties.getDeploymentTimeout()); } private Function, Publisher> getExponentialBackOff(Duration timeout) { @@ -698,18 +657,17 @@ public class CloudFoundryAppDeployer implements AppDeployer, ResourceLoaderAware } private Mono pushApplication(DeployApplicationRequest request, Map deploymentProperties, - Resource appResource) { + Resource appResource) { ApplicationManifest manifest = buildAppManifest(request, deploymentProperties, appResource); LOG.debug("Pushing app manifest. manifest={}", manifest.toString()); - PushApplicationManifestRequest applicationManifestRequest = - PushApplicationManifestRequest.builder() - .manifest(manifest) - .stagingTimeout(this.defaultDeploymentProperties.getStagingTimeout()) - .startupTimeout(this.defaultDeploymentProperties.getStartupTimeout()) - .noStart(!start(deploymentProperties)) - .build(); + PushApplicationManifestRequest applicationManifestRequest = PushApplicationManifestRequest.builder() + .manifest(manifest) + .stagingTimeout(this.defaultDeploymentProperties.getStagingTimeout()) + .startupTimeout(this.defaultDeploymentProperties.getStartupTimeout()) + .noStart(!start(deploymentProperties)) + .build(); Mono requestPushApplication; if (deploymentProperties.containsKey(DeploymentProperties.TARGET_PROPERTY_KEY)) { @@ -721,19 +679,18 @@ public class CloudFoundryAppDeployer implements AppDeployer, ResourceLoaderAware } return requestPushApplication - .doOnSuccess(v -> LOG.info("Success pushing app manifest. appName={}", request.getName())) - .doOnError(e -> LOG.error(String.format("Error pushing app manifest. appName=%s, " + ERROR_LOG_TEMPLATE, - request.getName(), e.getMessage()), e)); + .doOnSuccess((v) -> LOG.info("Success pushing app manifest. appName={}", request.getName())) + .doOnError((e) -> LOG.error(String.format("Error pushing app manifest. appName=%s, " + ERROR_LOG_TEMPLATE, + request.getName(), e.getMessage()), e)); } private ApplicationManifest buildAppManifest(DeployApplicationRequest request, - Map deploymentProperties, - Resource appResource) { + Map deploymentProperties, Resource appResource) { ApplicationManifest.Builder manifest = ApplicationManifest.builder() .name(request.getName()) .path(getApplication(appResource)) - .environmentVariables(getEnvironmentVariables(deploymentProperties, - request.getEnvironment(), request.getServiceInstanceId())) + .environmentVariables(getEnvironmentVariables(deploymentProperties, request.getEnvironment(), + request.getServiceInstanceId())) .services(request.getServices()) .instances(instances(deploymentProperties)) .memory(memory(deploymentProperties)) @@ -755,7 +712,7 @@ public class CloudFoundryAppDeployer implements AppDeployer, ResourceLoaderAware } else { Set routes = routes(deploymentProperties).stream() - .map(r -> Route.builder().route(r).build()) + .map((r) -> Route.builder().route(r).build()) .collect(Collectors.toSet()); manifest.routes(routes); } @@ -775,70 +732,67 @@ public class CloudFoundryAppDeployer implements AppDeployer, ResourceLoaderAware } private Mono pushManifest(PushApplicationManifestRequest request) { - return this.operations.applications() - .pushManifest(request); + return this.operations.applications().pushManifest(request); } private Mono pushManifestInSpace(PushApplicationManifestRequest request, String spaceName) { - return createSpace(spaceName) - .then(operationsUtils.getOperationsForSpace(spaceName)) - .flatMap(cfOperations -> cfOperations.applications().pushManifest(request)); + return createSpace(spaceName).then(this.operationsUtils.getOperationsForSpace(spaceName)) + .flatMap((cfOperations) -> cfOperations.applications().pushManifest(request)); } private Mono createSpace(String spaceName) { - return getSpaceId(spaceName) - .switchIfEmpty(Mono.justOrEmpty(targetProperties.getDefaultOrg()) - .flatMap(orgName -> getOrganizationId(orgName) - .flatMap(orgId -> client.spaces().create(CreateSpaceRequest.builder() - .organizationId(orgId) - .name(spaceName) - .build()) - .doOnSuccess(response -> { - LOG.info("Success creating space. spaceName={}", spaceName); - LOG.debug(RESPONSE_LOG_TEMPLATE, response); - }) - .doOnError(e -> LOG.error(String.format("Error creating space. spaceName=%s, " + - ERROR_LOG_TEMPLATE, spaceName, e.getMessage()), e)) - .onErrorResume(e -> Mono.empty()) - .map(response -> response.getMetadata().getId()) - .flatMap(spaceId -> addSpaceDeveloperRoleForCurrentUser(orgName, spaceName, spaceId) - .thenReturn(spaceId))))); + return getSpaceId(spaceName).switchIfEmpty(Mono.justOrEmpty(this.targetProperties.getDefaultOrg()) + .flatMap((orgName) -> getOrganizationId(orgName).flatMap((orgId) -> this.client.spaces() + .create(CreateSpaceRequest.builder().organizationId(orgId).name(spaceName).build()) + .doOnSuccess((response) -> { + LOG.info("Success creating space. spaceName={}", spaceName); + LOG.debug(RESPONSE_LOG_TEMPLATE, response); + }) + .doOnError((e) -> LOG.error(String.format("Error creating space. spaceName=%s, " + ERROR_LOG_TEMPLATE, + spaceName, e.getMessage()), e)) + .onErrorResume((e) -> Mono.empty()) + .map((response) -> response.getMetadata().getId()) + .flatMap((spaceId) -> addSpaceDeveloperRoleForCurrentUser(orgName, spaceName, spaceId) + .thenReturn(spaceId))))); } private Mono addSpaceDeveloperRoleForCurrentUser(String orgName, String spaceName, String spaceId) { return Mono.defer(() -> { - if (StringUtils.hasText(targetProperties.getClientId())) { - return client.spaces().associateDeveloper(AssociateSpaceDeveloperRequest.builder() - .spaceId(spaceId) - .developerId(targetProperties.getClientId()) - .build()) - .doOnSuccess(response -> { + if (StringUtils.hasText(this.targetProperties.getClientId())) { + return this.client.spaces() + .associateDeveloper(AssociateSpaceDeveloperRequest.builder() + .spaceId(spaceId) + .developerId(this.targetProperties.getClientId()) + .build()) + .doOnSuccess((response) -> { LOG.info("Setting space developer role. spaceName={}", spaceName); LOG.debug(RESPONSE_LOG_TEMPLATE, response); }) - .doOnError(e -> LOG.error(String.format("Error setting space developer role. spaceName=%s, " + - ERROR_LOG_TEMPLATE, spaceName, e.getMessage()), e)) + .doOnError((e) -> LOG + .error(String.format("Error setting space developer role. spaceName=%s, " + ERROR_LOG_TEMPLATE, + spaceName, e.getMessage()), e)) .then(); } - else if (StringUtils.hasText(targetProperties.getUsername())) { - return operations.userAdmin().setSpaceRole(SetSpaceRoleRequest.builder() - .spaceRole(SpaceRole.DEVELOPER) - .organizationName(orgName) - .spaceName(spaceName) - .username(targetProperties.getUsername()) - .build()) - .doOnSuccess(v -> LOG.info("Seting space developer role. spaceName={}", spaceName)) - .doOnError(e -> LOG.error(String.format("Error setting space developer role. spaceName=%s, " + - ERROR_LOG_TEMPLATE, spaceName, e.getMessage()), e)); + else if (StringUtils.hasText(this.targetProperties.getUsername())) { + return this.operations.userAdmin() + .setSpaceRole(SetSpaceRoleRequest.builder() + .spaceRole(SpaceRole.DEVELOPER) + .organizationName(orgName) + .spaceName(spaceName) + .username(this.targetProperties.getUsername()) + .build()) + .doOnSuccess((v) -> LOG.info("Seting space developer role. spaceName={}", spaceName)) + .doOnError((e) -> LOG + .error(String.format("Error setting space developer role. spaceName=%s, " + ERROR_LOG_TEMPLATE, + spaceName, e.getMessage()), e)); } return Mono.empty(); }); } private Mono getOrganizationId(String orgName) { - return operations.organizations().get(OrganizationInfoRequest.builder() - .name(orgName) - .build()) + return this.operations.organizations() + .get(OrganizationInfoRequest.builder().name(orgName).build()) .map(OrganizationDetail::getId); } @@ -858,13 +812,10 @@ public class CloudFoundryAppDeployer implements AppDeployer, ResourceLoaderAware requestDeleteApplication = deleteApplication(appName); } - return requestDeleteApplication - .timeout(Duration.ofSeconds(this.defaultDeploymentProperties.getApiTimeout())) - .doOnSuccess(v -> LOG.info("Success undeploying application. appName={}", appName)) + return requestDeleteApplication.timeout(Duration.ofSeconds(this.defaultDeploymentProperties.getApiTimeout())) + .doOnSuccess((v) -> LOG.info("Success undeploying application. appName={}", appName)) .doOnError(logError(String.format("Error undeploying application. appName=%s", appName))) - .then(Mono.just(UndeployApplicationResponse.builder() - .name(appName) - .build())); + .then(Mono.just(UndeployApplicationResponse.builder().name(appName).build())); } private Mono deleteApplication(String name) { @@ -877,52 +828,49 @@ public class CloudFoundryAppDeployer implements AppDeployer, ResourceLoaderAware private Mono deleteApplicationInSpace(String name, String spaceName) { return getSpaceId(spaceName) - .doOnError(e -> LOG.error(String.format("Unable to get space name. spaceName=%s, " + ERROR_LOG_TEMPLATE, - spaceName, e.getMessage()), e)) - .then(operationsUtils.getOperationsForSpace(spaceName)) - .flatMap(cfOperations -> cfOperations.applications().delete(DeleteApplicationRequest.builder() - .deleteRoutes(this.defaultDeploymentProperties.isDeleteRoutes()) - .name(name) - .build()) - .doOnError(e -> LOG.error(String.format("Error deleting application. appName=%s, " + ERROR_LOG_TEMPLATE, - name, e.getMessage()), e))) - .onErrorResume(e -> Mono.empty()); + .doOnError((e) -> LOG.error(String.format("Unable to get space name. spaceName=%s, " + ERROR_LOG_TEMPLATE, + spaceName, e.getMessage()), e)) + .then(this.operationsUtils.getOperationsForSpace(spaceName)) + .flatMap((cfOperations) -> cfOperations.applications() + .delete(DeleteApplicationRequest.builder() + .deleteRoutes(this.defaultDeploymentProperties.isDeleteRoutes()) + .name(name) + .build()) + .doOnError((e) -> LOG.error(String + .format("Error deleting application. appName=%s, " + ERROR_LOG_TEMPLATE, name, e.getMessage()), e))) + .onErrorResume((e) -> Mono.empty()); } @Override public Mono deleteBackingSpace(DeleteBackingSpaceRequest request) { String spaceName = request.getName(); return getSpaceId(spaceName) - .doOnError(e -> LOG.error(String.format("Unable to get space name. spaceName=%s, " + ERROR_LOG_TEMPLATE, - spaceName, e.getMessage()), e)) - .onErrorResume(e -> Mono.empty()) - .flatMap(spaceId -> this.client.spaces() - .delete(DeleteSpaceRequest.builder() - .spaceId(spaceId) - .recursive(true) - .build())) - .doOnError(e -> LOG.error(String.format("Error deleting space. spaceName=%s, " + ERROR_LOG_TEMPLATE, - spaceName, e.getMessage()), e)) + .doOnError((e) -> LOG.error(String.format("Unable to get space name. spaceName=%s, " + ERROR_LOG_TEMPLATE, + spaceName, e.getMessage()), e)) + .onErrorResume((e) -> Mono.empty()) + .flatMap((spaceId) -> this.client.spaces() + .delete(DeleteSpaceRequest.builder().spaceId(spaceId).recursive(true).build())) + .doOnError((e) -> LOG.error(String.format("Error deleting space. spaceName=%s, " + ERROR_LOG_TEMPLATE, + spaceName, e.getMessage()), e)) .thenReturn(DeleteBackingSpaceResponse.builder().name(spaceName).build()); } private Mono getSpaceId(String spaceName) { - return Mono.justOrEmpty(targetProperties.getDefaultOrg()) - .flatMap(orgName -> getOrganizationId(orgName) - .flatMap(orgId -> PaginationUtils.requestClientV2Resources(page -> client.organizations() + return Mono.justOrEmpty(this.targetProperties.getDefaultOrg()) + .flatMap((orgName) -> getOrganizationId(orgName).flatMap((orgId) -> PaginationUtils + .requestClientV2Resources((page) -> this.client.organizations() .listSpaces(ListOrganizationSpacesRequest.builder() .name(spaceName) .organizationId(orgId) .page(page) .build())) - .filter(resource -> resource.getEntity().getName().equals(spaceName)) - .map(resource -> resource.getMetadata().getId()) - .next())); + .filter((resource) -> resource.getEntity().getName().equals(spaceName)) + .map((resource) -> resource.getMetadata().getId()) + .next())); } - private Map getEnvironmentVariables(Map properties, - Map environment, - String serviceInstanceId) { + private Map getEnvironmentVariables(Map properties, Map environment, + String serviceInstanceId) { Map envVariables = getApplicationEnvironment(properties, environment, serviceInstanceId); String javaOpts = javaOpts(properties); @@ -934,8 +882,7 @@ public class CloudFoundryAppDeployer implements AppDeployer, ResourceLoaderAware } private Map getApplicationEnvironment(Map properties, - Map environment, - String serviceInstanceId) { + Map environment, String serviceInstanceId) { Map applicationEnvironment = sanitizeApplicationEnvironment(environment); if (serviceInstanceId != null) { @@ -948,8 +895,8 @@ public class CloudFoundryAppDeployer implements AppDeployer, ResourceLoaderAware applicationEnvironment = new HashMap<>(1); applicationEnvironment.put("SPRING_APPLICATION_JSON", jsonEnvironment); } - catch (JsonProcessingException e) { - throw new IllegalArgumentException("Error writing environment to SPRING_APPLICATION_JSON", e); + catch (JsonProcessingException ex) { + throw new IllegalArgumentException("Error writing environment to SPRING_APPLICATION_JSON", ex); } } @@ -959,11 +906,12 @@ public class CloudFoundryAppDeployer implements AppDeployer, ResourceLoaderAware private Map sanitizeApplicationEnvironment(Map environment) { Map applicationEnvironment = new HashMap<>(environment); - // Remove server.port as CF assigns a port for us, and we don't want to override that + // Remove server.port as CF assigns a port for us, and we don't want to override + // that Optional.ofNullable(applicationEnvironment.remove("server.port")) - .ifPresent(port -> LOG.warn("Ignoring 'server.port={}', " + - "as Cloud Foundry will assign a local dynamic port. " + - "Route to the app will use port 80.", port)); + .ifPresent((port) -> LOG.warn("Ignoring 'server.port={}', " + + "as Cloud Foundry will assign a local dynamic port. " + "Route to the app will use port 80.", + port)); return applicationEnvironment; } @@ -983,7 +931,7 @@ public class CloudFoundryAppDeployer implements AppDeployer, ResourceLoaderAware Set domains = new HashSet<>(); domains.addAll(this.defaultDeploymentProperties.getDomains()); domains.addAll( - StringUtils.commaDelimitedListToSet(properties.get(CloudFoundryDeploymentProperties.DOMAINS_PROPERTY))); + StringUtils.commaDelimitedListToSet(properties.get(CloudFoundryDeploymentProperties.DOMAINS_PROPERTY))); return domains; } @@ -997,10 +945,11 @@ public class CloudFoundryAppDeployer implements AppDeployer, ResourceLoaderAware try { return ApplicationHealthCheck.from(raw); } - catch (IllegalArgumentException e) { + catch (IllegalArgumentException ex) { throw new IllegalArgumentException( - String.format("Unsupported health-check value '%s'. Available values are %s", raw, - StringUtils.arrayToCommaDelimitedString(ApplicationHealthCheck.values())), e); + String.format("Unsupported health-check value '%s'. Available values are %s", raw, + StringUtils.arrayToCommaDelimitedString(ApplicationHealthCheck.values())), + ex); } } @@ -1018,9 +967,9 @@ public class CloudFoundryAppDeployer implements AppDeployer, ResourceLoaderAware private Duration apiPollingTimeout(Map properties) { return Duration.ofSeconds( - Optional.ofNullable(properties.get(CloudFoundryDeploymentProperties.API_POLLING_TIMEOUT_PROPERTY_KEY)) - .map(Long::parseLong) - .orElse(this.defaultDeploymentProperties.getApiPollingTimeout())); + Optional.ofNullable(properties.get(CloudFoundryDeploymentProperties.API_POLLING_TIMEOUT_PROPERTY_KEY)) + .map(Long::parseLong) + .orElse(this.defaultDeploymentProperties.getApiPollingTimeout())); } private Integer instances(Map properties) { @@ -1038,7 +987,7 @@ public class CloudFoundryAppDeployer implements AppDeployer, ResourceLoaderAware String routePath = properties.get(CloudFoundryDeploymentProperties.ROUTE_PATH_PROPERTY); if (StringUtils.hasText(routePath) && routePath.charAt(0) != '/') { throw new IllegalArgumentException( - "Cloud Foundry routes must start with \"/\". Route passed = [" + routePath + "]."); + "Cloud Foundry routes must start with \"/\". Route passed = [" + routePath + "]."); } return routePath; } @@ -1047,7 +996,7 @@ public class CloudFoundryAppDeployer implements AppDeployer, ResourceLoaderAware Set routes = new HashSet<>(); routes.addAll(this.defaultDeploymentProperties.getRoutes()); routes.addAll( - StringUtils.commaDelimitedListToSet(properties.get(CloudFoundryDeploymentProperties.ROUTES_PROPERTY))); + StringUtils.commaDelimitedListToSet(properties.get(CloudFoundryDeploymentProperties.ROUTES_PROPERTY))); return routes; } @@ -1060,13 +1009,13 @@ public class CloudFoundryAppDeployer implements AppDeployer, ResourceLoaderAware private Integer memory(Map properties) { return Optional.ofNullable(properties.get(DeploymentProperties.MEMORY_PROPERTY_KEY)) .map(ByteSizeUtils::parseToMebibytes) - .orElse(ByteSizeUtils.parseToMebibytes(defaultDeploymentProperties.getMemory())); + .orElse(ByteSizeUtils.parseToMebibytes(this.defaultDeploymentProperties.getMemory())); } private Integer diskQuota(Map properties) { return Optional.ofNullable(properties.get(DeploymentProperties.DISK_PROPERTY_KEY)) .map(ByteSizeUtils::parseToMebibytes) - .orElse(ByteSizeUtils.parseToMebibytes(defaultDeploymentProperties.getDisk())); + .orElse(ByteSizeUtils.parseToMebibytes(this.defaultDeploymentProperties.getDisk())); } private String buildpack(Map properties) { @@ -1096,14 +1045,15 @@ public class CloudFoundryAppDeployer implements AppDeployer, ResourceLoaderAware } private Predicate httpStatusNotFoundPredicate() { - return t -> t instanceof AbstractCloudFoundryException && - ((AbstractCloudFoundryException) t).getStatusCode() == HttpStatus.NOT_FOUND.value(); + return (t) -> t instanceof AbstractCloudFoundryException + && ((AbstractCloudFoundryException) t).getStatusCode() == HttpStatus.NOT_FOUND.value(); } /** - * Return a Docker image identifier if the application Resource is for a Docker image, or {@literal null} - * otherwise. - * + * Return a Docker image identifier if the application Resource is for a Docker image, + * or {@literal null} otherwise. + * @param resource the resource + * @return docker image identifier * @see #getApplication(Resource) */ private String getDockerImage(Resource resource) { @@ -1116,19 +1066,20 @@ public class CloudFoundryAppDeployer implements AppDeployer, ResourceLoaderAware return null; } } - catch (IOException e) { - throw Exceptions.propagate(e); + catch (IOException ex) { + throw Exceptions.propagate(ex); } } private Resource getAppResource(String path) { - return resourceLoader.getResource(path); + return this.resourceLoader.getResource(path); } /** - * Return a Path to the application Resource or {@literal null} if the request is for a Docker image. - * + * Return a Path to the application Resource or {@literal null} if the request is for + * a Docker image. * @param resource the resource representing the app bits + * @return path to the application resource * @see #getDockerImage(Resource) */ private Path getApplication(Resource resource) { @@ -1140,8 +1091,8 @@ public class CloudFoundryAppDeployer implements AppDeployer, ResourceLoaderAware return resource.getFile().toPath(); } } - catch (IOException e) { - throw Exceptions.propagate(e); + catch (IOException ex) { + throw Exceptions.propagate(ex); } } @@ -1150,18 +1101,18 @@ public class CloudFoundryAppDeployer implements AppDeployer, ResourceLoaderAware return Mono.defer(() -> { if (StringUtils.hasText(request.getServiceInstanceId())) { return getServiceInstance(request.getServiceInstanceId()) - .flatMap(serviceInstanceEntity -> getSpace(serviceInstanceEntity.getSpaceId()) - .flatMap(spaceEntity -> getServiceInstance(serviceInstanceEntity.getName(), spaceEntity))); + .flatMap((serviceInstanceEntity) -> getSpace(serviceInstanceEntity.getSpaceId()) + .flatMap((spaceEntity) -> getServiceInstance(serviceInstanceEntity.getName(), spaceEntity))); } else { - return operationsUtils.getOperations(request.getProperties()) - .flatMap(cfOperations -> cfOperations.services() + return this.operationsUtils.getOperations(request.getProperties()) + .flatMap((cfOperations) -> cfOperations.services() .getInstance(org.cloudfoundry.operations.services.GetServiceInstanceRequest.builder() .name(request.getName()) .build())); } }) - .map(serviceInstance -> GetServiceInstanceResponse.builder() + .map((serviceInstance) -> GetServiceInstanceResponse.builder() .name(serviceInstance.getName()) .service(serviceInstance.getService()) .plan(serviceInstance.getPlan()) @@ -1169,17 +1120,15 @@ public class CloudFoundryAppDeployer implements AppDeployer, ResourceLoaderAware } private Mono getServiceInstance(String name, SpaceEntity spaceEntity) { - return getOrganization(spaceEntity.getOrganizationId()) - .flatMap(organizationEntity -> - operationsUtils.getOperationsForOrgAndSpace(organizationEntity.getName(), spaceEntity.getName()) - .flatMap(cfOperations -> cfOperations.services() - .getInstance(org.cloudfoundry.operations.services.GetServiceInstanceRequest.builder() - .name(name) - .build()))); + return getOrganization(spaceEntity.getOrganizationId()).flatMap((organizationEntity) -> this.operationsUtils + .getOperationsForOrgAndSpace(organizationEntity.getName(), spaceEntity.getName()) + .flatMap((cfOperations) -> cfOperations.services() + .getInstance( + org.cloudfoundry.operations.services.GetServiceInstanceRequest.builder().name(name).build()))); } private Mono getServiceInstance(String serviceInstanceId) { - return client.serviceInstances() + return this.client.serviceInstances() .get(org.cloudfoundry.client.v2.serviceinstances.GetServiceInstanceRequest.builder() .serviceInstanceId(serviceInstanceId) .build()) @@ -1187,46 +1136,40 @@ public class CloudFoundryAppDeployer implements AppDeployer, ResourceLoaderAware } private Mono getSpace(String spaceId) { - return client.spaces().get(org.cloudfoundry.client.v2.spaces.GetSpaceRequest.builder() - .spaceId(spaceId) - .build()) + return this.client.spaces() + .get(org.cloudfoundry.client.v2.spaces.GetSpaceRequest.builder().spaceId(spaceId).build()) .map(ResourceUtils::getEntity); } private Mono getOrganization(String organizationId) { - return client.organizations() + return this.client.organizations() .get(GetOrganizationRequest.builder().organizationId(organizationId).build()) .map(GetOrganizationResponse::getEntity); } @Override public Mono createServiceInstance(CreateServiceInstanceRequest request) { - org.cloudfoundry.operations.services.CreateServiceInstanceRequest createServiceInstanceRequest = - org.cloudfoundry.operations.services.CreateServiceInstanceRequest - .builder() - .serviceInstanceName(request.getServiceInstanceName()) - .serviceName(request.getName()) - .planName(request.getPlan()) - .parameters(request.getParameters()) - .completionTimeout(apiPollingTimeout(request.getProperties())) - .build(); + org.cloudfoundry.operations.services.CreateServiceInstanceRequest createServiceInstanceRequest = org.cloudfoundry.operations.services.CreateServiceInstanceRequest + .builder() + .serviceInstanceName(request.getServiceInstanceName()) + .serviceName(request.getName()) + .planName(request.getPlan()) + .parameters(request.getParameters()) + .completionTimeout(apiPollingTimeout(request.getProperties())) + .build(); - Mono createServiceInstanceResponseMono = - Mono.just(CreateServiceInstanceResponse.builder() - .name(request.getServiceInstanceName()) - .build()); + Mono createServiceInstanceResponseMono = Mono + .just(CreateServiceInstanceResponse.builder().name(request.getServiceInstanceName()).build()); if (request.getProperties().containsKey(DeploymentProperties.TARGET_PROPERTY_KEY)) { return createSpace(request.getProperties().get(DeploymentProperties.TARGET_PROPERTY_KEY)) - .then( - operationsUtils.getOperations(request.getProperties()) - .flatMap(cfOperations -> cfOperations.services() - .createInstance(createServiceInstanceRequest) - .then(createServiceInstanceResponseMono))); + .then(this.operationsUtils.getOperations(request.getProperties()) + .flatMap((cfOperations) -> cfOperations.services() + .createInstance(createServiceInstanceRequest) + .then(createServiceInstanceResponseMono))); } else { - return operations - .services() + return this.operations.services() .createInstance(createServiceInstanceRequest) .then(createServiceInstanceResponseMono); } @@ -1234,8 +1177,8 @@ public class CloudFoundryAppDeployer implements AppDeployer, ResourceLoaderAware @Override public Mono updateServiceInstance(UpdateServiceInstanceRequest request) { - return operationsUtils.getOperations(request.getProperties()) - .flatMap(cfOperations -> rebindServiceInstanceIfNecessary(request, cfOperations) + return this.operationsUtils.getOperations(request.getProperties()) + .flatMap((cfOperations) -> rebindServiceInstanceIfNecessary(request, cfOperations) .then(updateServiceInstanceIfNecessary(request, cfOperations))); } @@ -1246,85 +1189,84 @@ public class CloudFoundryAppDeployer implements AppDeployer, ResourceLoaderAware Mono requestDeleteServiceInstance; if (deploymentProperties.containsKey(DeploymentProperties.TARGET_PROPERTY_KEY)) { - requestDeleteServiceInstance = operationsUtils.getOperations(deploymentProperties) - .flatMap(cfOperations -> unbindServiceInstance(serviceInstanceName, cfOperations) + requestDeleteServiceInstance = this.operationsUtils.getOperations(deploymentProperties) + .flatMap((cfOperations) -> unbindServiceInstance(serviceInstanceName, cfOperations) .then(deleteServiceInstance(serviceInstanceName, cfOperations, deploymentProperties))); } else { - requestDeleteServiceInstance = unbindServiceInstance(serviceInstanceName, operations) - .then(deleteServiceInstance(serviceInstanceName, operations, deploymentProperties)); + requestDeleteServiceInstance = unbindServiceInstance(serviceInstanceName, this.operations) + .then(deleteServiceInstance(serviceInstanceName, this.operations, deploymentProperties)); } return requestDeleteServiceInstance - .doOnSuccess(v -> LOG.info("Success deleting service instance. serviceInstanceName={}", - serviceInstanceName)) - .doOnError(logError(String.format("Error deleting service instance. serviceInstanceName=%s", - serviceInstanceName))) - .thenReturn(DeleteServiceInstanceResponse.builder() - .name(serviceInstanceName) - .build()); + .doOnSuccess( + (v) -> LOG.info("Success deleting service instance. serviceInstanceName={}", serviceInstanceName)) + .doOnError(logError( + String.format("Error deleting service instance. serviceInstanceName=%s", serviceInstanceName))) + .thenReturn(DeleteServiceInstanceResponse.builder().name(serviceInstanceName).build()); } - private Mono deleteServiceInstance(String serviceInstanceName, - CloudFoundryOperations cloudFoundryOperations, - Map deploymentProperties) { - return cloudFoundryOperations.services().deleteInstance( - org.cloudfoundry.operations.services.DeleteServiceInstanceRequest.builder() + private Mono deleteServiceInstance(String serviceInstanceName, CloudFoundryOperations cloudFoundryOperations, + Map deploymentProperties) { + return cloudFoundryOperations.services() + .deleteInstance(org.cloudfoundry.operations.services.DeleteServiceInstanceRequest.builder() .name(serviceInstanceName) .completionTimeout(apiPollingTimeout(deploymentProperties)) .build()) - .doOnError(e -> LOG.error(String.format("Error deleting service instance. serviceInstanceName=%s, " + - ERROR_LOG_TEMPLATE, serviceInstanceName, e.getMessage()), e)) - .onErrorResume(e -> Mono.empty()); + .doOnError((e) -> LOG + .error(String.format("Error deleting service instance. serviceInstanceName=%s, " + ERROR_LOG_TEMPLATE, + serviceInstanceName, e.getMessage()), e)) + .onErrorResume((e) -> Mono.empty()); } private Mono unbindServiceInstance(String serviceInstanceName, - CloudFoundryOperations cloudFoundryOperations) { + CloudFoundryOperations cloudFoundryOperations) { return cloudFoundryOperations.services() .getInstance(org.cloudfoundry.operations.services.GetServiceInstanceRequest.builder() .name(serviceInstanceName) .build()) - .doOnError(e -> LOG.error(String.format("Error getting service instance. serviceInstanceName=%s, " + - ERROR_LOG_TEMPLATE, serviceInstanceName, e.getMessage()), e)) - .onErrorResume(e -> Mono.empty()) + .doOnError((e) -> LOG + .error(String.format("Error getting service instance. serviceInstanceName=%s, " + ERROR_LOG_TEMPLATE, + serviceInstanceName, e.getMessage()), e)) + .onErrorResume((e) -> Mono.empty()) .map(ServiceInstance::getApplications) - .flatMap(applications -> Flux.fromIterable(applications) - .flatMap(application -> cloudFoundryOperations.services().unbind( - UnbindServiceInstanceRequest.builder() + .flatMap((applications) -> Flux.fromIterable(applications) + .flatMap((application) -> cloudFoundryOperations.services() + .unbind(UnbindServiceInstanceRequest.builder() .applicationName(application) .serviceInstanceName(serviceInstanceName) - .build()) - ) - .doOnError(e -> LOG.error(String.format("Error unbinding service instance. serviceInstanceName=%s, " + - ERROR_LOG_TEMPLATE, serviceInstanceName, e.getMessage()), e)) - .onErrorResume(e -> Mono.empty()) + .build())) + .doOnError((e) -> LOG.error( + String.format("Error unbinding service instance. serviceInstanceName=%s, " + ERROR_LOG_TEMPLATE, + serviceInstanceName, e.getMessage()), + e)) + .onErrorResume((e) -> Mono.empty()) .then(Mono.empty())); } private Mono rebindServiceInstance(String serviceInstanceName, - CloudFoundryOperations cloudFoundryOperations) { + CloudFoundryOperations cloudFoundryOperations) { return cloudFoundryOperations.services() .getInstance(org.cloudfoundry.operations.services.GetServiceInstanceRequest.builder() .name(serviceInstanceName) .build()) .map(ServiceInstance::getApplications) - .flatMap(applications -> Flux.fromIterable(applications) - .flatMap(application -> cloudFoundryOperations.services().unbind( - UnbindServiceInstanceRequest.builder() + .flatMap((applications) -> Flux.fromIterable(applications) + .flatMap((application) -> cloudFoundryOperations.services() + .unbind(UnbindServiceInstanceRequest.builder() .applicationName(application) .serviceInstanceName(serviceInstanceName) .build()) - .then(cloudFoundryOperations.services().bind( - BindServiceInstanceRequest.builder() + .then(cloudFoundryOperations.services() + .bind(BindServiceInstanceRequest.builder() .applicationName(application) .serviceInstanceName(serviceInstanceName) - .build())) - ) + .build()))) .then(Mono.empty())); } private Mono rebindServiceInstanceIfNecessary(UpdateServiceInstanceRequest request, - CloudFoundryOperations cloudFoundryOperations) { + CloudFoundryOperations cloudFoundryOperations) { if (request.isRebindOnUpdate()) { return rebindServiceInstance(request.getServiceInstanceName(), cloudFoundryOperations); } @@ -1332,8 +1274,9 @@ public class CloudFoundryAppDeployer implements AppDeployer, ResourceLoaderAware } private Mono updateServiceInstanceIfNecessary(UpdateServiceInstanceRequest request, - CloudFoundryOperations cloudFoundryOperations) { - // service instances can be updated with a change to the plan, name, or parameters; + CloudFoundryOperations cloudFoundryOperations) { + // service instances can be updated with a change to the plan, name, or + // parameters; // of these only parameter changes are supported, so don't update if the // backing service instance has no parameters if (request.getParameters() == null || request.getParameters().isEmpty()) { @@ -1342,27 +1285,27 @@ public class CloudFoundryAppDeployer implements AppDeployer, ResourceLoaderAware final String serviceInstanceName = request.getServiceInstanceName(); - return cloudFoundryOperations.services().updateInstance( - org.cloudfoundry.operations.services.UpdateServiceInstanceRequest.builder() + return cloudFoundryOperations.services() + .updateInstance(org.cloudfoundry.operations.services.UpdateServiceInstanceRequest.builder() .serviceInstanceName(serviceInstanceName) .completionTimeout(apiPollingTimeout(request.getProperties())) .parameters(request.getParameters()) .build()) - .then(Mono.just(UpdateServiceInstanceResponse.builder() - .name(serviceInstanceName) - .build())); + .then(Mono.just(UpdateServiceInstanceResponse.builder().name(serviceInstanceName).build())); } /** - * Return a function usable in {@literal doOnError} constructs that will unwrap unrecognized Cloud Foundry - * Exceptions and log the text payload. + * Return a function usable in {@literal doOnError} constructs that will unwrap + * unrecognized Cloud Foundry Exceptions and log the text payload. + * @param msg the message + * @return throwable */ private Consumer logError(String msg) { - return e -> { + return (e) -> { if (e instanceof UnknownCloudFoundryException) { if (LOG.isErrorEnabled()) { LOG.error(msg + "\nUnknownCloudFoundryException encountered, whose payload follows:\n" - + ((UnknownCloudFoundryException) e).getPayload(), e); + + ((UnknownCloudFoundryException) e).getPayload(), e); } } else { diff --git a/spring-cloud-app-broker-deployer-cloudfoundry/src/main/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryAppManager.java b/spring-cloud-app-broker-deployer-cloudfoundry/src/main/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryAppManager.java index f52d28c..2ccb3e6 100644 --- a/spring-cloud-app-broker-deployer-cloudfoundry/src/main/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryAppManager.java +++ b/spring-cloud-app-broker-deployer-cloudfoundry/src/main/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryAppManager.java @@ -1,11 +1,11 @@ /* - * Copyright 2002-2020 the original author or authors + * Copyright 2002-2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * https://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -41,23 +41,23 @@ public class CloudFoundryAppManager implements AppManager { @Override public Mono start(StartApplicationRequest request) { return Mono.justOrEmpty(request) - .flatMap(req -> operationsUtils.getOperations(req.getProperties()) - .flatMap(cfOperations -> Mono.justOrEmpty(req.getName()) - .flatMap(appName -> cfOperations.applications().start( - org.cloudfoundry.operations.applications.StartApplicationRequest.builder() + .flatMap((req) -> this.operationsUtils.getOperations(req.getProperties()) + .flatMap((cfOperations) -> Mono.justOrEmpty(req.getName()) + .flatMap((appName) -> cfOperations.applications() + .start(org.cloudfoundry.operations.applications.StartApplicationRequest.builder() .name(appName) .build()) - .doOnRequest(l -> { + .doOnRequest((l) -> { LOG.info("Starting application. appName={}", appName); LOG.debug(REQUEST_LOG_TEMPLATE, request); }) - .doOnSuccess(v -> { + .doOnSuccess((v) -> { LOG.info("Success starting application. appName={}", appName); LOG.debug(REQUEST_LOG_TEMPLATE, request); }) - .doOnError(e -> { + .doOnError((e) -> { LOG.error(String.format("Error starting application. appName=%s, error=%s", appName, - e.getMessage()), e); + e.getMessage()), e); LOG.debug(REQUEST_LOG_TEMPLATE, request); })))); } @@ -65,23 +65,23 @@ public class CloudFoundryAppManager implements AppManager { @Override public Mono stop(StopApplicationRequest request) { return Mono.justOrEmpty(request) - .flatMap(req -> operationsUtils.getOperations(req.getProperties()) - .flatMap(cfOperations -> Mono.justOrEmpty(req.getName()) - .flatMap(appName -> cfOperations.applications().stop( - org.cloudfoundry.operations.applications.StopApplicationRequest.builder() + .flatMap((req) -> this.operationsUtils.getOperations(req.getProperties()) + .flatMap((cfOperations) -> Mono.justOrEmpty(req.getName()) + .flatMap((appName) -> cfOperations.applications() + .stop(org.cloudfoundry.operations.applications.StopApplicationRequest.builder() .name(appName) .build()) - .doOnRequest(l -> { + .doOnRequest((l) -> { LOG.info("Stopping application. appName={}", appName); LOG.debug(REQUEST_LOG_TEMPLATE, request); }) - .doOnSuccess(v -> { + .doOnSuccess((v) -> { LOG.info("Success stopping application. appName={}", appName); LOG.debug(REQUEST_LOG_TEMPLATE, request); }) - .doOnError(e -> { + .doOnError((e) -> { LOG.error(String.format("Error stopping application. appName=%s, error=%s", appName, - e.getMessage()), e); + e.getMessage()), e); LOG.debug(REQUEST_LOG_TEMPLATE, request); })))); } @@ -89,23 +89,23 @@ public class CloudFoundryAppManager implements AppManager { @Override public Mono restart(RestartApplicationRequest request) { return Mono.justOrEmpty(request) - .flatMap(req -> operationsUtils.getOperations(req.getProperties()) - .flatMap(cfOperations -> Mono.justOrEmpty(req.getName()) - .flatMap(appName -> cfOperations.applications().restart( - org.cloudfoundry.operations.applications.RestartApplicationRequest.builder() + .flatMap((req) -> this.operationsUtils.getOperations(req.getProperties()) + .flatMap((cfOperations) -> Mono.justOrEmpty(req.getName()) + .flatMap((appName) -> cfOperations.applications() + .restart(org.cloudfoundry.operations.applications.RestartApplicationRequest.builder() .name(appName) .build()) - .doOnRequest(l -> { + .doOnRequest((l) -> { LOG.info("Restarting application. appName={}", appName); LOG.debug(REQUEST_LOG_TEMPLATE, request); }) - .doOnSuccess(v -> { + .doOnSuccess((v) -> { LOG.info("Success restarting application. appName={}", appName); LOG.debug(REQUEST_LOG_TEMPLATE, request); }) - .doOnError(e -> { + .doOnError((e) -> { LOG.error(String.format("Error restarting application. appName=%s, error=%s", appName, - e.getMessage()), e); + e.getMessage()), e); LOG.debug(REQUEST_LOG_TEMPLATE, request); })))); } @@ -113,23 +113,23 @@ public class CloudFoundryAppManager implements AppManager { @Override public Mono restage(RestageApplicationRequest request) { return Mono.justOrEmpty(request) - .flatMap(req -> operationsUtils.getOperations(req.getProperties()) - .flatMap(cfOperations -> Mono.justOrEmpty(req.getName()) - .flatMap(appName -> cfOperations.applications().restage( - org.cloudfoundry.operations.applications.RestageApplicationRequest.builder() + .flatMap((req) -> this.operationsUtils.getOperations(req.getProperties()) + .flatMap((cfOperations) -> Mono.justOrEmpty(req.getName()) + .flatMap((appName) -> cfOperations.applications() + .restage(org.cloudfoundry.operations.applications.RestageApplicationRequest.builder() .name(appName) .build()) - .doOnRequest(l -> { + .doOnRequest((l) -> { LOG.info("Restaging application. appName={}", appName); LOG.debug(REQUEST_LOG_TEMPLATE, request); }) - .doOnSuccess(v -> { + .doOnSuccess((v) -> { LOG.info("Success restaging application. appName={}", appName); LOG.debug(REQUEST_LOG_TEMPLATE, request); }) - .doOnError(e -> { + .doOnError((e) -> { LOG.error(String.format("Error restaging application. appName=%s, error=%s", appName, - e.getMessage()), e); + e.getMessage()), e); LOG.debug(REQUEST_LOG_TEMPLATE, request); })))); } diff --git a/spring-cloud-app-broker-deployer-cloudfoundry/src/main/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryDeploymentProperties.java b/spring-cloud-app-broker-deployer-cloudfoundry/src/main/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryDeploymentProperties.java index 77761f6..49d7c5d 100644 --- a/spring-cloud-app-broker-deployer-cloudfoundry/src/main/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryDeploymentProperties.java +++ b/spring-cloud-app-broker-deployer-cloudfoundry/src/main/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryDeploymentProperties.java @@ -25,8 +25,8 @@ import org.cloudfoundry.operations.applications.ApplicationHealthCheck; import org.springframework.cloud.appbroker.deployer.deployer.DeploymentProperties; /** - * Holds configuration properties for specifying what resources and services an app deployed to a Cloud Foundry runtime - * will get. + * Holds configuration properties for specifying what resources and services an app + * deployed to a Cloud Foundry runtime will get. * * @author Eric Bottard * @author Greg Turnquist @@ -36,17 +36,17 @@ import org.springframework.cloud.appbroker.deployer.deployer.DeploymentPropertie public class CloudFoundryDeploymentProperties extends DeploymentProperties { /** - * Key for storing the health check deployment property + * Key for storing the health check deployment property. */ protected static final String HEALTHCHECK_PROPERTY_KEY = "health-check"; /** - * Key for storing the health check endpoint deployment property + * Key for storing the health check endpoint deployment property. */ protected static final String HEALTHCHECK_HTTP_ENDPOINT_PROPERTY_KEY = "health-check-http-endpoint"; /** - * Key for storing the health check timeout deployment property + * Key for storing the health check timeout deployment property. */ protected static final String HEALTHCHECK_TIMEOUT_PROPERTY_KEY = "health-check-timeout"; @@ -56,53 +56,53 @@ public class CloudFoundryDeploymentProperties extends DeploymentProperties { protected static final String API_POLLING_TIMEOUT_PROPERTY_KEY = "api-polling-timeout"; /** - * Key for storing the route path deployment property + * Key for storing the route path deployment property. */ protected static final String ROUTE_PATH_PROPERTY = "route-path"; /** - * Key for storing the routes deployment property + * Key for storing the routes deployment property. */ protected static final String ROUTES_PROPERTY = "routes"; /** - * Key for storing a property describing whether routes are defined + * Key for storing a property describing whether routes are defined. */ protected static final String NO_ROUTE_PROPERTY = "no-route"; /** - * Key for storing the domain deployment property + * Key for storing the domain deployment property. */ protected static final String DOMAIN_PROPERTY = "domain"; /** - * Key for storing the domains deployment property + * Key for storing the domains deployment property. */ protected static final String DOMAINS_PROPERTY = "domains"; /** - * Key for storing the buildpack deployment property + * Key for storing the buildpack deployment property. */ protected static final String BUILDPACK_PROPERTY_KEY = "buildpack"; /** - * Key for storing the buildpacks deployment property + * Key for storing the buildpacks deployment property. */ protected static final String BUILDPACKS_PROPERTY_KEY = "buildpacks"; /** - * Key for storing the stack deployment property + * Key for storing the stack deployment property. */ protected static final String STACK_PROPERTY_KEY = "stack"; /** - * Key for storing JAVA_OPTS deployment property + * Key for storing JAVA_OPTS deployment property. */ protected static final String JAVA_OPTS_PROPERTY_KEY = "javaOpts"; /** - * The default value for the {@link #apiPollingTimeout} property. - * Useful in unit tests to assert default value when not assigned specifically. + * The default value for the {@link #apiPollingTimeout} property. Useful in unit tests + * to assert default value when not assigned specifically. */ public static final long DEFAULT_API_POLLING_TIMEOUT_SECONDS = Duration.ofMinutes(5).getSeconds(); @@ -117,7 +117,8 @@ public class CloudFoundryDeploymentProperties extends DeploymentProperties { private Set domains = new HashSet<>(); /** - * The routes that the application should be bound to. Mutually exclusive with host and domain. + * The routes that the application should be bound to. Mutually exclusive with host + * and domain. */ private Set routes = new HashSet<>(); @@ -137,17 +138,18 @@ public class CloudFoundryDeploymentProperties extends DeploymentProperties { private String stack; /** - * The type of health check to perform on deployed application, if not overridden per-app. Defaults to PORT + * The type of health check to perform on deployed application, if not overridden + * per-app. Defaults to PORT */ private ApplicationHealthCheck healthCheck; /** - * The path that the http health check will use, defaults to @{code /health} + * The path that the http health check will use, defaults to @{code /health}. */ private String healthCheckHttpEndpoint; /** - * The timeout value for health checks in seconds. Defaults to 120 seconds. + * The timeout value for health checks in seconds. Defaults to 120 seconds. */ private Integer healthCheckTimeout; @@ -162,12 +164,13 @@ public class CloudFoundryDeploymentProperties extends DeploymentProperties { private long apiTimeout = 360L; /** - * Timeout for polled async CF API calls, in seconds. Named "completionTimeout" in cf-java-client + * Timeout for polled async CF API calls, in seconds. Named "completionTimeout" in + * cf-java-client */ private long apiPollingTimeout = DEFAULT_API_POLLING_TIMEOUT_SECONDS; /** - * Timeout for name API operations in milliseconds + * Timeout for name API operations in milliseconds. */ private long statusTimeout = 5_000L; @@ -189,7 +192,7 @@ public class CloudFoundryDeploymentProperties extends DeploymentProperties { private String javaOpts; public String getBuildpack() { - return buildpack; + return this.buildpack; } public void setBuildpack(String buildpack) { @@ -197,7 +200,7 @@ public class CloudFoundryDeploymentProperties extends DeploymentProperties { } public String getBuildpacks() { - return buildpacks; + return this.buildpacks; } public void setBuildpacks(String buildpacks) { @@ -205,7 +208,7 @@ public class CloudFoundryDeploymentProperties extends DeploymentProperties { } public String getStack() { - return stack; + return this.stack; } public void setStack(String stack) { @@ -213,7 +216,7 @@ public class CloudFoundryDeploymentProperties extends DeploymentProperties { } public boolean isEnableRandomAppNamePrefix() { - return enableRandomAppNamePrefix; + return this.enableRandomAppNamePrefix; } public void setEnableRandomAppNamePrefix(boolean enableRandomAppNamePrefix) { @@ -221,7 +224,7 @@ public class CloudFoundryDeploymentProperties extends DeploymentProperties { } public long getApiTimeout() { - return apiTimeout; + return this.apiTimeout; } public void setApiTimeout(long apiTimeout) { @@ -229,7 +232,7 @@ public class CloudFoundryDeploymentProperties extends DeploymentProperties { } public ApplicationHealthCheck getHealthCheck() { - return healthCheck; + return this.healthCheck; } public void setHealthCheck(ApplicationHealthCheck healthCheck) { @@ -237,7 +240,7 @@ public class CloudFoundryDeploymentProperties extends DeploymentProperties { } public String getHealthCheckHttpEndpoint() { - return healthCheckHttpEndpoint; + return this.healthCheckHttpEndpoint; } public void setHealthCheckHttpEndpoint(String healthCheckHttpEndpoint) { @@ -245,7 +248,7 @@ public class CloudFoundryDeploymentProperties extends DeploymentProperties { } public Integer getHealthCheckTimeout() { - return healthCheckTimeout; + return this.healthCheckTimeout; } public void setHealthCheckTimeout(Integer healthCheckTimeout) { @@ -253,7 +256,7 @@ public class CloudFoundryDeploymentProperties extends DeploymentProperties { } public String getDomain() { - return domain; + return this.domain; } public void setDomain(String domain) { @@ -261,7 +264,7 @@ public class CloudFoundryDeploymentProperties extends DeploymentProperties { } public Set getDomains() { - return domains; + return this.domains; } public void setDomains(Set domains) { @@ -269,7 +272,7 @@ public class CloudFoundryDeploymentProperties extends DeploymentProperties { } public Set getRoutes() { - return routes; + return this.routes; } public void setRoutes(Set routes) { @@ -277,7 +280,7 @@ public class CloudFoundryDeploymentProperties extends DeploymentProperties { } public Duration getStagingTimeout() { - return stagingTimeout; + return this.stagingTimeout; } public void setStagingTimeout(Duration stagingTimeout) { @@ -285,7 +288,7 @@ public class CloudFoundryDeploymentProperties extends DeploymentProperties { } public Duration getStartupTimeout() { - return startupTimeout; + return this.startupTimeout; } public void setStartupTimeout(Duration startupTimeout) { @@ -293,7 +296,7 @@ public class CloudFoundryDeploymentProperties extends DeploymentProperties { } public long getStatusTimeout() { - return statusTimeout; + return this.statusTimeout; } public void setStatusTimeout(long statusTimeout) { @@ -301,7 +304,7 @@ public class CloudFoundryDeploymentProperties extends DeploymentProperties { } public boolean isDeleteRoutes() { - return deleteRoutes; + return this.deleteRoutes; } public void setDeleteRoutes(boolean deleteRoutes) { @@ -309,7 +312,7 @@ public class CloudFoundryDeploymentProperties extends DeploymentProperties { } public String getJavaOpts() { - return javaOpts; + return this.javaOpts; } public void setJavaOpts(String javaOpts) { @@ -317,12 +320,11 @@ public class CloudFoundryDeploymentProperties extends DeploymentProperties { } public long getApiPollingTimeout() { - return apiPollingTimeout; + return this.apiPollingTimeout; } public void setApiPollingTimeout(long apiPollingTimeout) { this.apiPollingTimeout = apiPollingTimeout; } - } diff --git a/spring-cloud-app-broker-deployer-cloudfoundry/src/main/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryOAuth2Client.java b/spring-cloud-app-broker-deployer-cloudfoundry/src/main/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryOAuth2Client.java index 1b368aa..1b972d6 100644 --- a/spring-cloud-app-broker-deployer-cloudfoundry/src/main/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryOAuth2Client.java +++ b/spring-cloud-app-broker-deployer-cloudfoundry/src/main/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryOAuth2Client.java @@ -44,16 +44,12 @@ public class CloudFoundryOAuth2Client implements OAuth2Client { @Override public Mono createClient(CreateOAuth2ClientRequest request) { - return uaaClient.clients() - .create(mapCreateRequest(request)) - .map(this::mapCreateResponse); + return this.uaaClient.clients().create(mapCreateRequest(request)).map(this::mapCreateResponse); } @Override public Mono deleteClient(DeleteOAuth2ClientRequest request) { - return uaaClient.clients() - .delete(mapDeleteRequest(request)) - .map(this::mapDeleteResponse); + return this.uaaClient.clients().delete(mapDeleteRequest(request)).map(this::mapDeleteResponse); } private CreateClientRequest mapCreateRequest(CreateOAuth2ClientRequest request) { @@ -102,9 +98,7 @@ public class CloudFoundryOAuth2Client implements OAuth2Client { return null; } - return grantTypes.stream() - .map(GrantType::from) - .collect(Collectors.toList()); + return grantTypes.stream().map(GrantType::from).collect(Collectors.toList()); } private List mapGrantTypeToString(List grantTypes) { @@ -112,9 +106,7 @@ public class CloudFoundryOAuth2Client implements OAuth2Client { return null; } - return grantTypes.stream() - .map(GrantType::getValue) - .collect(Collectors.toList()); + return grantTypes.stream().map(GrantType::getValue).collect(Collectors.toList()); } } diff --git a/spring-cloud-app-broker-deployer-cloudfoundry/src/main/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryOperationsUtils.java b/spring-cloud-app-broker-deployer-cloudfoundry/src/main/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryOperationsUtils.java index 72e3bdf..d47d98f 100644 --- a/spring-cloud-app-broker-deployer-cloudfoundry/src/main/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryOperationsUtils.java +++ b/spring-cloud-app-broker-deployer-cloudfoundry/src/main/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryOperationsUtils.java @@ -1,11 +1,11 @@ /* - * Copyright 2002-2020 the original author or authors + * Copyright 2002-2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * https://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -35,8 +35,8 @@ public class CloudFoundryOperationsUtils { protected Mono getOperations(Map properties) { return Mono.defer(() -> { - if (!CollectionUtils.isEmpty(properties) && properties.containsKey( - DeploymentProperties.TARGET_PROPERTY_KEY)) { + if (!CollectionUtils.isEmpty(properties) + && properties.containsKey(DeploymentProperties.TARGET_PROPERTY_KEY)) { return getOperationsForSpace(properties.get(DeploymentProperties.TARGET_PROPERTY_KEY)); } return Mono.just(this.operations); @@ -46,16 +46,13 @@ public class CloudFoundryOperationsUtils { protected Mono getOperationsForSpace(String space) { return Mono.just(this.operations) .cast(DefaultCloudFoundryOperations.class) - .map(cfOperations -> DefaultCloudFoundryOperations.builder() - .from(cfOperations) - .space(space) - .build()); + .map((cfOperations) -> DefaultCloudFoundryOperations.builder().from(cfOperations).space(space).build()); } protected Mono getOperationsForOrgAndSpace(String organization, String space) { return Mono.just(this.operations) .cast(DefaultCloudFoundryOperations.class) - .map(cfOperations -> DefaultCloudFoundryOperations.builder() + .map((cfOperations) -> DefaultCloudFoundryOperations.builder() .from(cfOperations) .organization(organization) .space(space) diff --git a/spring-cloud-app-broker-deployer-cloudfoundry/src/main/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryTargetProperties.java b/spring-cloud-app-broker-deployer-cloudfoundry/src/main/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryTargetProperties.java index 45205e1..80255ef 100644 --- a/spring-cloud-app-broker-deployer-cloudfoundry/src/main/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryTargetProperties.java +++ b/spring-cloud-app-broker-deployer-cloudfoundry/src/main/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryTargetProperties.java @@ -49,7 +49,7 @@ public class CloudFoundryTargetProperties { private Long stagingTimeout; public String getApiHost() { - return apiHost; + return this.apiHost; } public void setApiHost(String apiHost) { @@ -57,7 +57,7 @@ public class CloudFoundryTargetProperties { } public Integer getApiPort() { - return apiPort; + return this.apiPort; } public void setApiPort(int apiPort) { @@ -65,7 +65,7 @@ public class CloudFoundryTargetProperties { } public String getDefaultOrg() { - return defaultOrg; + return this.defaultOrg; } public void setDefaultOrg(String defaultOrg) { @@ -73,7 +73,7 @@ public class CloudFoundryTargetProperties { } public String getDefaultSpace() { - return defaultSpace; + return this.defaultSpace; } public void setDefaultSpace(String defaultSpace) { @@ -81,7 +81,7 @@ public class CloudFoundryTargetProperties { } public String getUsername() { - return username; + return this.username; } public void setUsername(String username) { @@ -89,7 +89,7 @@ public class CloudFoundryTargetProperties { } public String getPassword() { - return password; + return this.password; } public void setPassword(String password) { @@ -97,7 +97,7 @@ public class CloudFoundryTargetProperties { } public String getClientId() { - return clientId; + return this.clientId; } public void setClientId(String clientId) { @@ -105,7 +105,7 @@ public class CloudFoundryTargetProperties { } public String getClientSecret() { - return clientSecret; + return this.clientSecret; } public void setClientSecret(String clientSecret) { @@ -113,7 +113,7 @@ public class CloudFoundryTargetProperties { } public String getIdentityZoneSubdomain() { - return identityZoneSubdomain; + return this.identityZoneSubdomain; } public void setIdentityZoneSubdomain(String identityZoneSubdomain) { @@ -121,7 +121,7 @@ public class CloudFoundryTargetProperties { } public boolean isSecure() { - return secure; + return this.secure; } public void setSecure(boolean secure) { @@ -129,7 +129,7 @@ public class CloudFoundryTargetProperties { } public boolean isSkipSslValidation() { - return skipSslValidation; + return this.skipSslValidation; } public void setSkipSslValidation(boolean skipSslValidation) { @@ -141,7 +141,7 @@ public class CloudFoundryTargetProperties { } public Long getDeploymentTimeout() { - return deploymentTimeout; + return this.deploymentTimeout; } public void setDeploymentTimeout(Long deploymentTimeout) { @@ -149,7 +149,7 @@ public class CloudFoundryTargetProperties { } public Long getStagingTimeout() { - return stagingTimeout; + return this.stagingTimeout; } public void setStagingTimeout(Long stagingTimeout) { @@ -158,7 +158,7 @@ public class CloudFoundryTargetProperties { private static String parseApiHost(String api) { final URI uri = URI.create(api); - return uri.getHost() == null ? api : uri.getHost(); + return (uri.getHost() == null) ? api : uri.getHost(); } } diff --git a/spring-cloud-app-broker-deployer-cloudfoundry/src/main/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/package-info.java b/spring-cloud-app-broker-deployer-cloudfoundry/src/main/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/package-info.java new file mode 100644 index 0000000..1a2839a --- /dev/null +++ b/spring-cloud-app-broker-deployer-cloudfoundry/src/main/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/package-info.java @@ -0,0 +1,20 @@ +/* + * Copyright 2016-2024 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * CloudFoundry deployer. + */ +package org.springframework.cloud.appbroker.deployer.cloudfoundry; diff --git a/spring-cloud-app-broker-deployer-cloudfoundry/src/main/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/workflow/package-info.java b/spring-cloud-app-broker-deployer-cloudfoundry/src/main/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/workflow/package-info.java new file mode 100644 index 0000000..4d30525 --- /dev/null +++ b/spring-cloud-app-broker-deployer-cloudfoundry/src/main/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/workflow/package-info.java @@ -0,0 +1,20 @@ +/* + * Copyright 2016-2024 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * CloudFoundry deployer workflow. + */ +package org.springframework.cloud.appbroker.deployer.cloudfoundry.workflow; diff --git a/spring-cloud-app-broker-deployer-cloudfoundry/src/test/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryAppDeployerDeleteSpaceTest.java b/spring-cloud-app-broker-deployer-cloudfoundry/src/test/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryAppDeployerDeleteSpaceTests.java similarity index 56% rename from spring-cloud-app-broker-deployer-cloudfoundry/src/test/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryAppDeployerDeleteSpaceTest.java rename to spring-cloud-app-broker-deployer-cloudfoundry/src/test/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryAppDeployerDeleteSpaceTests.java index 5790321..62d5e36 100644 --- a/spring-cloud-app-broker-deployer-cloudfoundry/src/test/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryAppDeployerDeleteSpaceTest.java +++ b/spring-cloud-app-broker-deployer-cloudfoundry/src/test/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryAppDeployerDeleteSpaceTests.java @@ -44,7 +44,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; @ExtendWith(MockitoExtension.class) -class CloudFoundryAppDeployerDeleteSpaceTest { +class CloudFoundryAppDeployerDeleteSpaceTests { private AppDeployer appDeployer; @@ -77,103 +77,66 @@ class CloudFoundryAppDeployerDeleteSpaceTest { targetProperties.setDefaultOrg("default-org"); targetProperties.setDefaultSpace("default-space"); - given(cloudFoundryOperations.organizations()).willReturn(operationsOrganizations); - given(cloudFoundryClient.organizations()).willReturn(clientOrganizations); + given(this.cloudFoundryOperations.organizations()).willReturn(this.operationsOrganizations); + given(this.cloudFoundryClient.organizations()).willReturn(this.clientOrganizations); - given(operationsOrganizations - .get( - OrganizationInfoRequest - .builder() - .name("default-org") - .build())) - .willReturn(Mono.just( - OrganizationDetail - .builder() - .id("default-org-id") - .name("default-org") - .quota(OrganizationQuota - .builder() - .id("quota-id") - .instanceMemoryLimit(0) - .organizationId("default-org-id") - .name("quota") - .paidServicePlans(false) - .totalMemoryLimit(0) - .totalRoutes(0) - .totalServiceInstances(0) - .build()) - .build())); + given(this.operationsOrganizations.get(OrganizationInfoRequest.builder().name("default-org").build())) + .willReturn(Mono.just(OrganizationDetail.builder() + .id("default-org-id") + .name("default-org") + .quota(OrganizationQuota.builder() + .id("quota-id") + .instanceMemoryLimit(0) + .organizationId("default-org-id") + .name("quota") + .paidServicePlans(false) + .totalMemoryLimit(0) + .totalRoutes(0) + .totalServiceInstances(0) + .build()) + .build())); - appDeployer = new CloudFoundryAppDeployer(deploymentProperties, cloudFoundryOperations, cloudFoundryClient, - operationsUtils, targetProperties, resourceLoader); + this.appDeployer = new CloudFoundryAppDeployer(deploymentProperties, this.cloudFoundryOperations, + this.cloudFoundryClient, this.operationsUtils, targetProperties, this.resourceLoader); } @Test void deleteSpaceIfExists() { - given(clientOrganizations - .listSpaces(ListOrganizationSpacesRequest - .builder() - .name("test-space-name") - .organizationId("default-org-id") - .page(1) - .build())) - .willReturn(Mono.just(ListOrganizationSpacesResponse - .builder() - .resource(SpaceResource - .builder() - .entity(SpaceEntity - .builder() - .name("test-space-name") - .build()) - .metadata(Metadata - .builder() - .id("test-space-id") - .build()) + given(this.clientOrganizations.listSpaces(ListOrganizationSpacesRequest.builder() + .name("test-space-name") + .organizationId("default-org-id") + .page(1) + .build())) + .willReturn(Mono.just(ListOrganizationSpacesResponse.builder() + .resource(SpaceResource.builder() + .entity(SpaceEntity.builder().name("test-space-name").build()) + .metadata(Metadata.builder().id("test-space-id").build()) .build()) .build())); - given(cloudFoundryClient.spaces()).willReturn(clientSpaces); - given(clientSpaces - .delete(DeleteSpaceRequest - .builder() - .spaceId("test-space-id") - .recursive(true) - .build())) + given(this.cloudFoundryClient.spaces()).willReturn(this.clientSpaces); + given(this.clientSpaces.delete(DeleteSpaceRequest.builder().spaceId("test-space-id").recursive(true).build())) .willReturn(Mono.empty()); - DeleteBackingSpaceRequest request = - DeleteBackingSpaceRequest.builder() - .name("test-space-name") - .build(); + DeleteBackingSpaceRequest request = DeleteBackingSpaceRequest.builder().name("test-space-name").build(); - StepVerifier.create( - appDeployer.deleteBackingSpace(request)) - .assertNext(response -> assertThat(response.getName()).isEqualTo("test-space-name")) + StepVerifier.create(this.appDeployer.deleteBackingSpace(request)) + .assertNext((response) -> assertThat(response.getName()).isEqualTo("test-space-name")) .verifyComplete(); } @Test void doNothingIfSpaceDoesNotExist() { - given(clientOrganizations - .listSpaces(ListOrganizationSpacesRequest - .builder() - .name("test-space-name") - .organizationId("default-org-id") - .page(1) - .build())) - .willReturn(Mono.just(ListOrganizationSpacesResponse - .builder() - .resources() - .build())); + given(this.clientOrganizations.listSpaces(ListOrganizationSpacesRequest.builder() + .name("test-space-name") + .organizationId("default-org-id") + .page(1) + .build())).willReturn(Mono.just(ListOrganizationSpacesResponse.builder().resources().build())); - DeleteBackingSpaceRequest request = - DeleteBackingSpaceRequest.builder() - .name("test-space-name") - .build(); + DeleteBackingSpaceRequest request = DeleteBackingSpaceRequest.builder().name("test-space-name").build(); - StepVerifier.create( - appDeployer.deleteBackingSpace(request)) - .assertNext(response -> assertThat(response.getName()).isEqualTo("test-space-name")) + StepVerifier.create(this.appDeployer.deleteBackingSpace(request)) + .assertNext((response) -> assertThat(response.getName()).isEqualTo("test-space-name")) .verifyComplete(); } diff --git a/spring-cloud-app-broker-deployer-cloudfoundry/src/test/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryAppDeployerTest.java b/spring-cloud-app-broker-deployer-cloudfoundry/src/test/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryAppDeployerTests.java similarity index 51% rename from spring-cloud-app-broker-deployer-cloudfoundry/src/test/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryAppDeployerTest.java rename to spring-cloud-app-broker-deployer-cloudfoundry/src/test/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryAppDeployerTests.java index ce38c72..409788e 100644 --- a/spring-cloud-app-broker-deployer-cloudfoundry/src/test/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryAppDeployerTest.java +++ b/spring-cloud-app-broker-deployer-cloudfoundry/src/test/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryAppDeployerTests.java @@ -78,9 +78,6 @@ import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.ResourceLoader; import org.springframework.util.CollectionUtils; -import static java.util.Collections.emptyMap; -import static java.util.Collections.singleton; -import static java.util.Collections.singletonMap; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyMap; @@ -88,13 +85,11 @@ import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.then; -import static org.springframework.cloud.appbroker.deployer.cloudfoundry.CloudFoundryDeploymentProperties.DEFAULT_API_POLLING_TIMEOUT_SECONDS; -import static org.springframework.cloud.appbroker.deployer.deployer.DeploymentProperties.TARGET_PROPERTY_KEY; @SuppressWarnings("UnassignedFluxMonoInstance") @ExtendWith(MockitoExtension.class) @MockitoSettings(strictness = Strictness.LENIENT) -class CloudFoundryAppDeployerTest { +class CloudFoundryAppDeployerTests { private static final String APP_NAME = "test-app"; @@ -102,7 +97,8 @@ class CloudFoundryAppDeployerTest { private static final String SERVICE_INSTANCE_ID = "service-instance-id"; - private static final long DEFAULT_COMPLETION_DURATION = Duration.ofSeconds(DEFAULT_API_POLLING_TIMEOUT_SECONDS) + private static final long DEFAULT_COMPLETION_DURATION = Duration + .ofSeconds(CloudFoundryDeploymentProperties.DEFAULT_API_POLLING_TIMEOUT_SECONDS) .getSeconds(); private static final int EXPECTED_MANIFESTS = 1; @@ -149,30 +145,31 @@ class CloudFoundryAppDeployerTest { @BeforeEach void setUp() { - deploymentProperties = new CloudFoundryDeploymentProperties(); + this.deploymentProperties = new CloudFoundryDeploymentProperties(); CloudFoundryTargetProperties targetProperties = new CloudFoundryTargetProperties(); targetProperties.setDefaultOrg("default-org"); targetProperties.setDefaultSpace("default-space"); - given(operationsApplications.pushManifest(any())).willReturn(Mono.empty()); - given(resourceLoader.getResource(APP_PATH)).willReturn(new FileSystemResource(APP_PATH)); + given(this.operationsApplications.pushManifest(any())).willReturn(Mono.empty()); + given(this.resourceLoader.getResource(APP_PATH)).willReturn(new FileSystemResource(APP_PATH)); - given(cloudFoundryOperations.spaces()).willReturn(operationsSpaces); - given(cloudFoundryOperations.applications()).willReturn(operationsApplications); - given(cloudFoundryOperations.services()).willReturn(operationsServices); - given(cloudFoundryOperations.organizations()).willReturn(operationsOrganizations); - given(cloudFoundryClient.serviceInstances()).willReturn(clientServiceInstances); - given(cloudFoundryClient.spaces()).willReturn(clientSpaces); - given(cloudFoundryClient.organizations()).willReturn(clientOrganizations); - given(cloudFoundryClient.applicationsV2()).willReturn(clientApplications); - given(operationsUtils.getOperations(anyMap())).willReturn(Mono.just(cloudFoundryOperations)); - given(operationsUtils.getOperationsForSpace(anyString())).willReturn(Mono.just(cloudFoundryOperations)); - given(operationsUtils.getOperationsForOrgAndSpace(anyString(), anyString())) - .willReturn(Mono.just(cloudFoundryOperations)); + given(this.cloudFoundryOperations.spaces()).willReturn(this.operationsSpaces); + given(this.cloudFoundryOperations.applications()).willReturn(this.operationsApplications); + given(this.cloudFoundryOperations.services()).willReturn(this.operationsServices); + given(this.cloudFoundryOperations.organizations()).willReturn(this.operationsOrganizations); + given(this.cloudFoundryClient.serviceInstances()).willReturn(this.clientServiceInstances); + given(this.cloudFoundryClient.spaces()).willReturn(this.clientSpaces); + given(this.cloudFoundryClient.organizations()).willReturn(this.clientOrganizations); + given(this.cloudFoundryClient.applicationsV2()).willReturn(this.clientApplications); + given(this.operationsUtils.getOperations(anyMap())).willReturn(Mono.just(this.cloudFoundryOperations)); + given(this.operationsUtils.getOperationsForSpace(anyString())) + .willReturn(Mono.just(this.cloudFoundryOperations)); + given(this.operationsUtils.getOperationsForOrgAndSpace(anyString(), anyString())) + .willReturn(Mono.just(this.cloudFoundryOperations)); - appDeployer = new CloudFoundryAppDeployer(deploymentProperties, cloudFoundryOperations, cloudFoundryClient, - operationsUtils, targetProperties, resourceLoader); + this.appDeployer = new CloudFoundryAppDeployer(this.deploymentProperties, this.cloudFoundryOperations, + this.cloudFoundryClient, this.operationsUtils, targetProperties, this.resourceLoader); } @Test @@ -183,17 +180,16 @@ class CloudFoundryAppDeployerTest { .serviceInstanceId(SERVICE_INSTANCE_ID) .build(); - StepVerifier.create(appDeployer.deploy(request)) - .assertNext(response -> assertThat(response.getName()).isEqualTo(APP_NAME)) + StepVerifier.create(this.appDeployer.deploy(request)) + .assertNext((response) -> assertThat(response.getName()).isEqualTo(APP_NAME)) .verifyComplete(); - ApplicationManifest expectedManifest = baseManifestWithSpringAppJson() - .name(APP_NAME) + ApplicationManifest expectedManifest = baseManifestWithSpringAppJson().name(APP_NAME) .path(new File(APP_PATH).toPath()) .buildpacks("") // Empty list means to discover the buildpack .build(); - then(operationsApplications).should().pushManifest(argThat(matchesManifest(expectedManifest))); + then(this.operationsApplications).should().pushManifest(argThat(matchesManifest(expectedManifest))); } @Test @@ -214,12 +210,11 @@ class CloudFoundryAppDeployerTest { .property(CloudFoundryDeploymentProperties.NO_ROUTE_PROPERTY, "true") .build(); - StepVerifier.create(appDeployer.deploy(request)) - .assertNext(response -> assertThat(response.getName()).isEqualTo(APP_NAME)) + StepVerifier.create(this.appDeployer.deploy(request)) + .assertNext((response) -> assertThat(response.getName()).isEqualTo(APP_NAME)) .verifyComplete(); - ApplicationManifest expectedManifest = baseManifestWithSpringAppJson() - .name(APP_NAME) + ApplicationManifest expectedManifest = baseManifestWithSpringAppJson().name(APP_NAME) .path(new File(APP_PATH).toPath()) .instances(3) .memory(2048) @@ -233,19 +228,19 @@ class CloudFoundryAppDeployerTest { .noRoute(true) .build(); - then(operationsApplications).should().pushManifest(argThat(matchesManifest(expectedManifest))); + then(this.operationsApplications).should().pushManifest(argThat(matchesManifest(expectedManifest))); } @Test void deployAppWithDefaultProperties() { - deploymentProperties.setCount(3); - deploymentProperties.setMemory("2G"); - deploymentProperties.setDisk("3G"); - deploymentProperties.setBuildpack("buildpack"); - deploymentProperties.setHealthCheck(ApplicationHealthCheck.HTTP); - deploymentProperties.setHealthCheckHttpEndpoint("/healthcheck"); - deploymentProperties.setDomains(singleton("domain")); - deploymentProperties.setHost("host"); + this.deploymentProperties.setCount(3); + this.deploymentProperties.setMemory("2G"); + this.deploymentProperties.setDisk("3G"); + this.deploymentProperties.setBuildpack("buildpack"); + this.deploymentProperties.setHealthCheck(ApplicationHealthCheck.HTTP); + this.deploymentProperties.setHealthCheckHttpEndpoint("/healthcheck"); + this.deploymentProperties.setDomains(Collections.singleton("domain")); + this.deploymentProperties.setHost("host"); DeployApplicationRequest request = DeployApplicationRequest.builder() .name(APP_NAME) @@ -253,12 +248,11 @@ class CloudFoundryAppDeployerTest { .serviceInstanceId(SERVICE_INSTANCE_ID) .build(); - StepVerifier.create(appDeployer.deploy(request)) - .assertNext(response -> assertThat(response.getName()).isEqualTo(APP_NAME)) + StepVerifier.create(this.appDeployer.deploy(request)) + .assertNext((response) -> assertThat(response.getName()).isEqualTo(APP_NAME)) .verifyComplete(); - ApplicationManifest expectedManifest = baseManifestWithSpringAppJson() - .name(APP_NAME) + ApplicationManifest expectedManifest = baseManifestWithSpringAppJson().name(APP_NAME) .path(new File(APP_PATH).toPath()) .instances(3) .memory(2048) @@ -270,19 +264,19 @@ class CloudFoundryAppDeployerTest { .host("host") .build(); - then(operationsApplications).should().pushManifest(argThat(matchesManifest(expectedManifest))); + then(this.operationsApplications).should().pushManifest(argThat(matchesManifest(expectedManifest))); } @Test void deployAppWithRequestOverridingDefaultProperties() { - deploymentProperties.setCount(3); - deploymentProperties.setMemory("2G"); - deploymentProperties.setDisk("3G"); - deploymentProperties.setBuildpack("buildpack1"); - deploymentProperties.setHealthCheck(ApplicationHealthCheck.HTTP); - deploymentProperties.setHealthCheckHttpEndpoint("/healthcheck1"); - deploymentProperties.setDomains(singleton("domain1")); - deploymentProperties.setHost("host1"); + this.deploymentProperties.setCount(3); + this.deploymentProperties.setMemory("2G"); + this.deploymentProperties.setDisk("3G"); + this.deploymentProperties.setBuildpack("buildpack1"); + this.deploymentProperties.setHealthCheck(ApplicationHealthCheck.HTTP); + this.deploymentProperties.setHealthCheckHttpEndpoint("/healthcheck1"); + this.deploymentProperties.setDomains(Collections.singleton("domain1")); + this.deploymentProperties.setHost("host1"); DeployApplicationRequest request = DeployApplicationRequest.builder() .name(APP_NAME) @@ -300,12 +294,11 @@ class CloudFoundryAppDeployerTest { .property(CloudFoundryDeploymentProperties.STACK_PROPERTY_KEY, "customstack") .build(); - StepVerifier.create(appDeployer.deploy(request)) - .assertNext(response -> assertThat(response.getName()).isEqualTo(APP_NAME)) + StepVerifier.create(this.appDeployer.deploy(request)) + .assertNext((response) -> assertThat(response.getName()).isEqualTo(APP_NAME)) .verifyComplete(); - ApplicationManifest expectedManifest = baseManifestWithSpringAppJson() - .name(APP_NAME) + ApplicationManifest expectedManifest = baseManifestWithSpringAppJson().name(APP_NAME) .path(new File(APP_PATH).toPath()) .instances(5) .memory(4096) @@ -319,20 +312,19 @@ class CloudFoundryAppDeployerTest { .noRoute(true) .build(); - then(operationsApplications).should() - .pushManifest(argThat(matchesManifest(expectedManifest))); + then(this.operationsApplications).should().pushManifest(argThat(matchesManifest(expectedManifest))); } @Test void deployAppWithBothDomainAndDomainsProperties() { - deploymentProperties.setCount(3); - deploymentProperties.setMemory("2G"); - deploymentProperties.setDisk("3G"); - deploymentProperties.setBuildpack("buildpack1"); - deploymentProperties.setHealthCheck(ApplicationHealthCheck.HTTP); - deploymentProperties.setHealthCheckHttpEndpoint("/healthcheck1"); - deploymentProperties.setHost("host1"); - deploymentProperties.setDomains(singleton("default-domain")); + this.deploymentProperties.setCount(3); + this.deploymentProperties.setMemory("2G"); + this.deploymentProperties.setDisk("3G"); + this.deploymentProperties.setBuildpack("buildpack1"); + this.deploymentProperties.setHealthCheck(ApplicationHealthCheck.HTTP); + this.deploymentProperties.setHealthCheckHttpEndpoint("/healthcheck1"); + this.deploymentProperties.setHost("host1"); + this.deploymentProperties.setDomains(Collections.singleton("default-domain")); DeployApplicationRequest request = DeployApplicationRequest.builder() .name(APP_NAME) @@ -350,12 +342,11 @@ class CloudFoundryAppDeployerTest { .property(CloudFoundryDeploymentProperties.NO_ROUTE_PROPERTY, "true") .build(); - StepVerifier.create(appDeployer.deploy(request)) - .assertNext(response -> assertThat(response.getName()).isEqualTo(APP_NAME)) + StepVerifier.create(this.appDeployer.deploy(request)) + .assertNext((response) -> assertThat(response.getName()).isEqualTo(APP_NAME)) .verifyComplete(); - ApplicationManifest expectedManifest = baseManifestWithSpringAppJson() - .name(APP_NAME) + ApplicationManifest expectedManifest = baseManifestWithSpringAppJson().name(APP_NAME) .path(new File(APP_PATH).toPath()) .instances(5) .memory(4096) @@ -368,20 +359,20 @@ class CloudFoundryAppDeployerTest { .noRoute(true) .build(); - then(operationsApplications).should().pushManifest(argThat(matchesManifest(expectedManifest))); + then(this.operationsApplications).should().pushManifest(argThat(matchesManifest(expectedManifest))); } @Test void deployAppWithRoutesAndMutuallyExclusiveProperties() { - deploymentProperties.setCount(3); - deploymentProperties.setMemory("2G"); - deploymentProperties.setDisk("3G"); - deploymentProperties.setBuildpack("buildpack1"); - deploymentProperties.setHealthCheck(ApplicationHealthCheck.HTTP); - deploymentProperties.setHealthCheckHttpEndpoint("/healthcheck1"); - deploymentProperties.setHost("host1"); - deploymentProperties.setDomain("domain1"); - deploymentProperties.setDomains(singleton("domain2")); + this.deploymentProperties.setCount(3); + this.deploymentProperties.setMemory("2G"); + this.deploymentProperties.setDisk("3G"); + this.deploymentProperties.setBuildpack("buildpack1"); + this.deploymentProperties.setHealthCheck(ApplicationHealthCheck.HTTP); + this.deploymentProperties.setHealthCheckHttpEndpoint("/healthcheck1"); + this.deploymentProperties.setHost("host1"); + this.deploymentProperties.setDomain("domain1"); + this.deploymentProperties.setDomains(Collections.singleton("domain2")); DeployApplicationRequest request = DeployApplicationRequest.builder() .name(APP_NAME) @@ -398,12 +389,11 @@ class CloudFoundryAppDeployerTest { .property(CloudFoundryDeploymentProperties.ROUTES_PROPERTY, "route.domain3") .build(); - StepVerifier.create(appDeployer.deploy(request)) - .assertNext(response -> assertThat(response.getName()).isEqualTo(APP_NAME)) - .verifyComplete(); + StepVerifier.create(this.appDeployer.deploy(request)) + .assertNext((response) -> assertThat(response.getName()).isEqualTo(APP_NAME)) + .verifyComplete(); - ApplicationManifest expectedManifest = baseManifestWithSpringAppJson() - .name(APP_NAME) + ApplicationManifest expectedManifest = baseManifestWithSpringAppJson().name(APP_NAME) .path(new File(APP_PATH).toPath()) .instances(5) .memory(4096) @@ -414,12 +404,12 @@ class CloudFoundryAppDeployerTest { .routes(Route.builder().route("route.domain3").build()) .build(); - then(operationsApplications).should().pushManifest(argThat(matchesManifest(expectedManifest))); + then(this.operationsApplications).should().pushManifest(argThat(matchesManifest(expectedManifest))); } @Test void deployAppWithEnvironmentUsingSpringAppJson() { - deploymentProperties.setUseSpringApplicationJson(true); + this.deploymentProperties.setUseSpringApplicationJson(true); DeployApplicationRequest request = DeployApplicationRequest.builder() .name(APP_NAME) @@ -430,24 +420,24 @@ class CloudFoundryAppDeployerTest { .environment("ENV_VAR_2", "value2") .build(); - StepVerifier.create(appDeployer.deploy(request)) - .assertNext(response -> assertThat(response.getName()).isEqualTo(APP_NAME)) + StepVerifier.create(this.appDeployer.deploy(request)) + .assertNext((response) -> assertThat(response.getName()).isEqualTo(APP_NAME)) .verifyComplete(); ApplicationManifest expectedManifest = baseManifestWithSpringAppJson( - "\"ENV_VAR_2\":\"value2\",\"ENV_VAR_1\":\"value1\"") + "\"ENV_VAR_2\":\"value2\",\"ENV_VAR_1\":\"value1\"") .name(APP_NAME) .path(new File(APP_PATH).toPath()) .buildpacks("") .environmentVariable("JAVA_OPTS", "-Xms512m -Xmx1024m") .build(); - then(operationsApplications).should().pushManifest(argThat(matchesManifest(expectedManifest))); + then(this.operationsApplications).should().pushManifest(argThat(matchesManifest(expectedManifest))); } @Test void deployAppWithEnvironmentNotUsingSpringAppJson() { - deploymentProperties.setUseSpringApplicationJson(false); + this.deploymentProperties.setUseSpringApplicationJson(false); DeployApplicationRequest request = DeployApplicationRequest.builder() .name(APP_NAME) @@ -458,12 +448,11 @@ class CloudFoundryAppDeployerTest { .environment("ENV_VAR_2", "value2") .build(); - StepVerifier.create(appDeployer.deploy(request)) - .assertNext(response -> assertThat(response.getName()).isEqualTo(APP_NAME)) + StepVerifier.create(this.appDeployer.deploy(request)) + .assertNext((response) -> assertThat(response.getName()).isEqualTo(APP_NAME)) .verifyComplete(); - ApplicationManifest expectedManifest = baseManifest() - .name(APP_NAME) + ApplicationManifest expectedManifest = baseManifest().name(APP_NAME) .path(new File(APP_PATH).toPath()) .buildpack("") .environmentVariable("JAVA_OPTS", "-Xms512m -Xmx1024m") @@ -472,7 +461,7 @@ class CloudFoundryAppDeployerTest { .environmentVariable("ENV_VAR_2", "value2") .build(); - then(operationsApplications).should().pushManifest(argThat(matchesManifest(expectedManifest))); + then(this.operationsApplications).should().pushManifest(argThat(matchesManifest(expectedManifest))); } @Test @@ -484,11 +473,11 @@ class CloudFoundryAppDeployerTest { .serviceInstanceId(SERVICE_INSTANCE_ID) .build(); - StepVerifier.create(appDeployer.deploy(request)) - .assertNext(response -> assertThat(response.getName()).isEqualTo(APP_NAME)) + StepVerifier.create(this.appDeployer.deploy(request)) + .assertNext((response) -> assertThat(response.getName()).isEqualTo(APP_NAME)) .verifyComplete(); - then(operationsApplications).should().pushManifest(argThat(PushApplicationManifestRequest::getNoStart)); + then(this.operationsApplications).should().pushManifest(argThat(PushApplicationManifestRequest::getNoStart)); } @Test @@ -499,18 +488,18 @@ class CloudFoundryAppDeployerTest { .serviceInstanceId(SERVICE_INSTANCE_ID) .build(); - StepVerifier.create(appDeployer.deploy(request)) - .assertNext(response -> assertThat(response.getName()).isEqualTo(APP_NAME)) + StepVerifier.create(this.appDeployer.deploy(request)) + .assertNext((response) -> assertThat(response.getName()).isEqualTo(APP_NAME)) .verifyComplete(); - then(operationsApplications).should().pushManifest(argThat(r -> !r.getNoStart())); + then(this.operationsApplications).should().pushManifest(argThat((r) -> !r.getNoStart())); } @Test void preUpdateAppUpdatesApplicationEnvironment() { final String appId = "app-id"; - given(operationsApplications.get(argThat(request -> APP_NAME.equals(request.getName())))) + given(this.operationsApplications.get(argThat((request) -> APP_NAME.equals(request.getName())))) .willReturn(Mono.just(ApplicationDetail.builder() .id(appId) .name(APP_NAME) @@ -522,13 +511,12 @@ class CloudFoundryAppDeployerTest { .stack("cflinuxfs4") .build())); - given(clientApplications.summary(argThat(request -> appId.equals(request.getApplicationId())))) - .willReturn(Mono.just(SummaryApplicationResponse.builder() - .id(appId) - .services(Collections.emptyList()) - .build())); + given(this.clientApplications.summary(argThat((request) -> appId.equals(request.getApplicationId())))) + .willReturn(Mono + .just(SummaryApplicationResponse.builder().id(appId).services(Collections.emptyList()).build())); - given(clientApplications.update(any(org.cloudfoundry.client.v2.applications.UpdateApplicationRequest.class))) + given(this.clientApplications + .update(any(org.cloudfoundry.client.v2.applications.UpdateApplicationRequest.class))) .willReturn(Mono.just(UpdateApplicationResponse.builder().build())); UpdateApplicationRequest request = UpdateApplicationRequest.builder() @@ -536,27 +524,29 @@ class CloudFoundryAppDeployerTest { .environment("env-key", "env-value") .build(); - StepVerifier.create(appDeployer.preUpdate(request)) - .assertNext(response -> assertThat(response.getName()).isEqualTo(APP_NAME)) + StepVerifier.create(this.appDeployer.preUpdate(request)) + .assertNext((response) -> assertThat(response.getName()).isEqualTo(APP_NAME)) .verifyComplete(); - Map expectedEnvironment = - singletonMap("SPRING_APPLICATION_JSON", "{\"env-key\":\"env-value\"}"); + Map expectedEnvironment = Collections.singletonMap("SPRING_APPLICATION_JSON", + "{\"env-key\":\"env-value\"}"); - then(clientApplications).should().update(argThat(applicationUpdateRequest -> - applicationUpdateRequest.getEnvironmentJsons().equals(expectedEnvironment))); + then(this.clientApplications).should() + .update(argThat((applicationUpdateRequest) -> applicationUpdateRequest.getEnvironmentJsons() + .equals(expectedEnvironment))); } @Test void deleteServiceInstanceShouldUnbindServices() { - given(operationsServices.deleteInstance( - org.cloudfoundry.operations.services.DeleteServiceInstanceRequest.builder() + given(this.operationsServices + .deleteInstance(org.cloudfoundry.operations.services.DeleteServiceInstanceRequest.builder() .name("service-instance-name") .completionTimeout(Duration.ofSeconds(DEFAULT_COMPLETION_DURATION)) .build())) .willReturn(Mono.empty()); - given(operationsServices.getInstance(GetServiceInstanceRequest.builder().name("service-instance-name").build())) + given(this.operationsServices + .getInstance(GetServiceInstanceRequest.builder().name("service-instance-name").build())) .willReturn(Mono.just(ServiceInstance.builder() .id("siid") .type(ServiceInstanceType.MANAGED) @@ -564,41 +554,38 @@ class CloudFoundryAppDeployerTest { .applications("app1", "app2") .build())); - given(operationsServices.unbind(UnbindServiceInstanceRequest.builder() + given(this.operationsServices.unbind(UnbindServiceInstanceRequest.builder() .serviceInstanceName("service-instance-name") .applicationName("app1") - .build())) - .willReturn(Mono.empty()); + .build())).willReturn(Mono.empty()); - given(operationsServices.unbind(UnbindServiceInstanceRequest.builder() + given(this.operationsServices.unbind(UnbindServiceInstanceRequest.builder() .serviceInstanceName("service-instance-name") .applicationName("app2") - .build())) - .willReturn(Mono.empty()); + .build())).willReturn(Mono.empty()); - DeleteServiceInstanceRequest request = - DeleteServiceInstanceRequest.builder() - .serviceInstanceName("service-instance-name") - .properties(emptyMap()) - .build(); + DeleteServiceInstanceRequest request = DeleteServiceInstanceRequest.builder() + .serviceInstanceName("service-instance-name") + .properties(Collections.emptyMap()) + .build(); - StepVerifier.create( - appDeployer.deleteServiceInstance(request)) - .assertNext(response -> assertThat(response.getName()).isEqualTo("service-instance-name")) + StepVerifier.create(this.appDeployer.deleteServiceInstance(request)) + .assertNext((response) -> assertThat(response.getName()).isEqualTo("service-instance-name")) .verifyComplete(); } @Test void deleteServiceInstanceWithTarget() { - given(operationsServices.deleteInstance( - org.cloudfoundry.operations.services.DeleteServiceInstanceRequest.builder() + given(this.operationsServices + .deleteInstance(org.cloudfoundry.operations.services.DeleteServiceInstanceRequest.builder() .name("service-instance-name") .completionTimeout(Duration.ofSeconds(DEFAULT_COMPLETION_DURATION)) .build())) .willReturn(Mono.empty()); - given(operationsServices.getInstance(GetServiceInstanceRequest.builder().name("service-instance-name").build())) + given(this.operationsServices + .getInstance(GetServiceInstanceRequest.builder().name("service-instance-name").build())) .willReturn(Mono.just(ServiceInstance.builder() .id("siid") .type(ServiceInstanceType.MANAGED) @@ -606,169 +593,142 @@ class CloudFoundryAppDeployerTest { .applications("app1", "app2") .build())); - given(operationsServices.unbind(UnbindServiceInstanceRequest.builder() + given(this.operationsServices.unbind(UnbindServiceInstanceRequest.builder() .serviceInstanceName("service-instance-name") .applicationName("app1") - .build())) - .willReturn(Mono.empty()); + .build())).willReturn(Mono.empty()); - given(operationsServices.unbind(UnbindServiceInstanceRequest.builder() + given(this.operationsServices.unbind(UnbindServiceInstanceRequest.builder() .serviceInstanceName("service-instance-name") .applicationName("app2") - .build())) - .willReturn(Mono.empty()); + .build())).willReturn(Mono.empty()); - DeleteServiceInstanceRequest request = - DeleteServiceInstanceRequest.builder() - .serviceInstanceName("service-instance-name") - .properties(emptyMap()) - .properties(singletonMap(TARGET_PROPERTY_KEY, "service-instance-id")) - .build(); + DeleteServiceInstanceRequest request = DeleteServiceInstanceRequest.builder() + .serviceInstanceName("service-instance-name") + .properties(Collections.emptyMap()) + .properties(Collections.singletonMap(DeploymentProperties.TARGET_PROPERTY_KEY, "service-instance-id")) + .build(); - StepVerifier.create( - appDeployer.deleteServiceInstance(request)) - .assertNext(response -> assertThat(response.getName()).isEqualTo("service-instance-name")) + StepVerifier.create(this.appDeployer.deleteServiceInstance(request)) + .assertNext((response) -> assertThat(response.getName()).isEqualTo("service-instance-name")) .verifyComplete(); } @Test void createServiceInstance() { - given(operationsServices.createInstance( - org.cloudfoundry.operations.services.CreateServiceInstanceRequest.builder() + given(this.operationsServices + .createInstance(org.cloudfoundry.operations.services.CreateServiceInstanceRequest.builder() .serviceInstanceName("service-instance-name") .serviceName("db-service") .planName("standard") - .completionTimeout(Duration.ofSeconds(100)) //expect per app configured duration to be received and not + .completionTimeout(Duration.ofSeconds(100)) // expect per app configured + // duration to be received and + // not // CloudFoundryDeployment default - .parameters(emptyMap()) + .parameters(Collections.emptyMap()) .build())) .willReturn(Mono.empty()); - Map userProvidedTimeoutForBrokeredApp = - singletonMap(CloudFoundryDeploymentProperties.API_POLLING_TIMEOUT_PROPERTY_KEY, "100"); - CreateServiceInstanceRequest request = - CreateServiceInstanceRequest.builder() - .serviceInstanceName("service-instance-name") - .name("db-service") - .plan("standard") - .properties(userProvidedTimeoutForBrokeredApp) - .parameters(emptyMap()) - .build(); + Map userProvidedTimeoutForBrokeredApp = Collections + .singletonMap(CloudFoundryDeploymentProperties.API_POLLING_TIMEOUT_PROPERTY_KEY, "100"); + CreateServiceInstanceRequest request = CreateServiceInstanceRequest.builder() + .serviceInstanceName("service-instance-name") + .name("db-service") + .plan("standard") + .properties(userProvidedTimeoutForBrokeredApp) + .parameters(Collections.emptyMap()) + .build(); - StepVerifier.create( - appDeployer.createServiceInstance(request)) - .assertNext(response -> assertThat(response.getName()).isEqualTo("service-instance-name")) + StepVerifier.create(this.appDeployer.createServiceInstance(request)) + .assertNext((response) -> assertThat(response.getName()).isEqualTo("service-instance-name")) .verifyComplete(); } @Test void createServiceInstanceWithTarget() { - given(operationsOrganizations - .get( - OrganizationInfoRequest - .builder() - .name("default-org") - .build())) - .willReturn(Mono.just( - OrganizationDetail - .builder() - .id("default-org-id") - .name("default-org") - .quota(OrganizationQuota - .builder() - .id("quota-id") - .instanceMemoryLimit(0) - .organizationId("default-org-id") - .name("quota") - .paidServicePlans(false) - .totalMemoryLimit(0) - .totalRoutes(0) - .totalServiceInstances(0) - .build()) - .build())); + given(this.operationsOrganizations.get(OrganizationInfoRequest.builder().name("default-org").build())) + .willReturn(Mono.just(OrganizationDetail.builder() + .id("default-org-id") + .name("default-org") + .quota(OrganizationQuota.builder() + .id("quota-id") + .instanceMemoryLimit(0) + .organizationId("default-org-id") + .name("quota") + .paidServicePlans(false) + .totalMemoryLimit(0) + .totalRoutes(0) + .totalServiceInstances(0) + .build()) + .build())); - given(clientOrganizations - .listSpaces(ListOrganizationSpacesRequest - .builder() - .name("service-instance-id") - .organizationId("default-org-id") - .page(1) - .build())) + given(this.clientOrganizations.listSpaces(ListOrganizationSpacesRequest.builder() + .name("service-instance-id") + .organizationId("default-org-id") + .page(1) + .build())).willReturn(Mono.empty()); + + given(this.clientSpaces + .create(CreateSpaceRequest.builder().organizationId("default-org-id").name("service-instance-id").build())) .willReturn(Mono.empty()); - given(clientSpaces - .create(CreateSpaceRequest - .builder() - .organizationId("default-org-id") - .name("service-instance-id") - .build())) - .willReturn(Mono.empty()); - - given(operationsServices - .createInstance( - org.cloudfoundry.operations.services.CreateServiceInstanceRequest - .builder() - .serviceInstanceName("service-instance-name") - .serviceName("db-service") - .planName("standard") - .completionTimeout(Duration.ofSeconds(DEFAULT_COMPLETION_DURATION)) - .parameters(emptyMap()) - .build())) - .willReturn(Mono.empty()); - - CreateServiceInstanceRequest request = - CreateServiceInstanceRequest - .builder() + given(this.operationsServices + .createInstance(org.cloudfoundry.operations.services.CreateServiceInstanceRequest.builder() .serviceInstanceName("service-instance-name") - .name("db-service") - .plan("standard") - .parameters(emptyMap()) - .properties(singletonMap(TARGET_PROPERTY_KEY, "service-instance-id")) - .build(); + .serviceName("db-service") + .planName("standard") + .completionTimeout(Duration.ofSeconds(DEFAULT_COMPLETION_DURATION)) + .parameters(Collections.emptyMap()) + .build())) + .willReturn(Mono.empty()); - StepVerifier.create( - appDeployer.createServiceInstance(request)) - .assertNext(response -> assertThat(response.getName()).isEqualTo("service-instance-name")) + CreateServiceInstanceRequest request = CreateServiceInstanceRequest.builder() + .serviceInstanceName("service-instance-name") + .name("db-service") + .plan("standard") + .parameters(Collections.emptyMap()) + .properties(Collections.singletonMap(DeploymentProperties.TARGET_PROPERTY_KEY, "service-instance-id")) + .build(); + + StepVerifier.create(this.appDeployer.createServiceInstance(request)) + .assertNext((response) -> assertThat(response.getName()).isEqualTo("service-instance-name")) .verifyComplete(); } @Test void updateServiceInstanceUpdatesWithParameters() { - Map parameters = singletonMap("param1", "value"); + Map parameters = Collections.singletonMap("param1", "value"); - given(operationsServices.updateInstance( - org.cloudfoundry.operations.services.UpdateServiceInstanceRequest.builder() + given(this.operationsServices + .updateInstance(org.cloudfoundry.operations.services.UpdateServiceInstanceRequest.builder() .serviceInstanceName("service-instance-name") .parameters(parameters) .completionTimeout(Duration.ofSeconds(DEFAULT_COMPLETION_DURATION)) .build())) .willReturn(Mono.empty()); - UpdateServiceInstanceRequest request = - UpdateServiceInstanceRequest.builder() - .serviceInstanceName("service-instance-name") - .parameters(parameters) - .build(); + UpdateServiceInstanceRequest request = UpdateServiceInstanceRequest.builder() + .serviceInstanceName("service-instance-name") + .parameters(parameters) + .build(); - StepVerifier.create( - appDeployer.updateServiceInstance(request)) - .assertNext(response -> assertThat(response.getName()).isEqualTo("service-instance-name")) + StepVerifier.create(this.appDeployer.updateServiceInstance(request)) + .assertNext((response) -> assertThat(response.getName()).isEqualTo("service-instance-name")) .verifyComplete(); } @Test void updateServiceInstanceRebindsWhenRequired() { - given(operationsServices.updateInstance( - org.cloudfoundry.operations.services.UpdateServiceInstanceRequest.builder() + given(this.operationsServices + .updateInstance(org.cloudfoundry.operations.services.UpdateServiceInstanceRequest.builder() .serviceInstanceName("service-instance-name") - .parameters(emptyMap()) + .parameters(Collections.emptyMap()) .completionTimeout(Duration.ofSeconds(DEFAULT_COMPLETION_DURATION)) .build())) .willReturn(Mono.empty()); - given(operationsServices.getInstance(GetServiceInstanceRequest.builder() - .name("service-instance-name") - .build())) + given(this.operationsServices + .getInstance(GetServiceInstanceRequest.builder().name("service-instance-name").build())) .willReturn(Mono.just(ServiceInstance.builder() .name("service-instance-name") .id("service-instance-guid") @@ -776,65 +736,55 @@ class CloudFoundryAppDeployerTest { .applications("app1", "app2") .build())); - given(operationsServices.unbind(UnbindServiceInstanceRequest.builder() + given(this.operationsServices.unbind(UnbindServiceInstanceRequest.builder() .applicationName("app1") .serviceInstanceName("service-instance-name") - .build())) - .willReturn(Mono.empty()); + .build())).willReturn(Mono.empty()); - given(operationsServices.unbind(UnbindServiceInstanceRequest.builder() + given(this.operationsServices.unbind(UnbindServiceInstanceRequest.builder() .applicationName("app2") .serviceInstanceName("service-instance-name") - .build())) - .willReturn(Mono.empty()); + .build())).willReturn(Mono.empty()); - given(operationsServices.bind(BindServiceInstanceRequest.builder() + given(this.operationsServices.bind(BindServiceInstanceRequest.builder() .applicationName("app1") .serviceInstanceName("service-instance-name") - .build())) - .willReturn(Mono.empty()); + .build())).willReturn(Mono.empty()); - given(operationsServices.bind(BindServiceInstanceRequest.builder() + given(this.operationsServices.bind(BindServiceInstanceRequest.builder() .applicationName("app2") .serviceInstanceName("service-instance-name") - .build())) - .willReturn(Mono.empty()); + .build())).willReturn(Mono.empty()); - UpdateServiceInstanceRequest request = - UpdateServiceInstanceRequest.builder() - .serviceInstanceName("service-instance-name") - .parameters(emptyMap()) - .rebindOnUpdate(true) - .build(); + UpdateServiceInstanceRequest request = UpdateServiceInstanceRequest.builder() + .serviceInstanceName("service-instance-name") + .parameters(Collections.emptyMap()) + .rebindOnUpdate(true) + .build(); - StepVerifier.create( - appDeployer.updateServiceInstance(request)) - .verifyComplete(); + StepVerifier.create(this.appDeployer.updateServiceInstance(request)).verifyComplete(); } @Test void updateServiceInstanceDoesNothingWithoutParameters() { - given(operationsServices.updateInstance( - org.cloudfoundry.operations.services.UpdateServiceInstanceRequest.builder() + given(this.operationsServices + .updateInstance(org.cloudfoundry.operations.services.UpdateServiceInstanceRequest.builder() .serviceInstanceName("service-instance-name") - .parameters(emptyMap()) + .parameters(Collections.emptyMap()) .build())) .willReturn(Mono.empty()); - UpdateServiceInstanceRequest request = - UpdateServiceInstanceRequest.builder() - .serviceInstanceName("service-instance-name") - .parameters(emptyMap()) - .build(); + UpdateServiceInstanceRequest request = UpdateServiceInstanceRequest.builder() + .serviceInstanceName("service-instance-name") + .parameters(Collections.emptyMap()) + .build(); - StepVerifier.create( - appDeployer.updateServiceInstance(request)) - .verifyComplete(); + StepVerifier.create(this.appDeployer.updateServiceInstance(request)).verifyComplete(); } @Test void getServiceInstanceById() { - given(operationsServices.getInstance(any(GetServiceInstanceRequest.class))) + given(this.operationsServices.getInstance(any(GetServiceInstanceRequest.class))) .willReturn(Mono.just(ServiceInstance.builder() .id("foo-service-instance-id") .name("my-foo-service") @@ -843,68 +793,55 @@ class CloudFoundryAppDeployerTest { .type(ServiceInstanceType.MANAGED) .build())); - given(clientServiceInstances + given(this.clientServiceInstances .get(any(org.cloudfoundry.client.v2.serviceinstances.GetServiceInstanceRequest.class))) .willReturn(Mono.just(GetServiceInstanceResponse.builder() - .entity(ServiceInstanceEntity.builder() - .name("my-foo-service") - .spaceId("foo-space-id") - .build()) + .entity(ServiceInstanceEntity.builder().name("my-foo-service").spaceId("foo-space-id").build()) .build())); - given(clientSpaces.get(GetSpaceRequest.builder() - .spaceId("foo-space-id") - .build())) + given(this.clientSpaces.get(GetSpaceRequest.builder().spaceId("foo-space-id").build())) .willReturn(Mono.just(GetSpaceResponse.builder() - .entity(SpaceEntity.builder() - .name("foo-space") - .organizationId("foo-organization-id") - .build()) + .entity(SpaceEntity.builder().name("foo-space").organizationId("foo-organization-id").build()) .build())); - given(clientOrganizations.get(GetOrganizationRequest.builder() - .organizationId("foo-organization-id") - .build())) + given(this.clientOrganizations + .get(GetOrganizationRequest.builder().organizationId("foo-organization-id").build())) .willReturn(Mono.just(GetOrganizationResponse.builder() - .entity(OrganizationEntity.builder() - .name("foo-organization") - .build()) + .entity(OrganizationEntity.builder().name("foo-organization").build()) .build())); - org.springframework.cloud.appbroker.deployer.deployer.GetServiceInstanceRequest request = - org.springframework.cloud.appbroker.deployer.deployer.GetServiceInstanceRequest - .builder() - .serviceInstanceId("foo-service-instance-id") - .properties(emptyMap()) - .build(); + org.springframework.cloud.appbroker.deployer.deployer.GetServiceInstanceRequest request = org.springframework.cloud.appbroker.deployer.deployer.GetServiceInstanceRequest + .builder() + .serviceInstanceId("foo-service-instance-id") + .properties(Collections.emptyMap()) + .build(); - StepVerifier.create(appDeployer.getServiceInstance(request)) - .assertNext(response -> { - assertThat(response.getName()).isEqualTo("my-foo-service"); - assertThat(response.getService()).isEqualTo("foo-service"); - assertThat(response.getPlan()).isEqualTo("foo-plan"); - }) - .verifyComplete(); + StepVerifier.create(this.appDeployer.getServiceInstance(request)).assertNext((response) -> { + assertThat(response.getName()).isEqualTo("my-foo-service"); + assertThat(response.getService()).isEqualTo("foo-service"); + assertThat(response.getPlan()).isEqualTo("foo-plan"); + }).verifyComplete(); - then(operationsUtils).should() + then(this.operationsUtils).should() .getOperationsForOrgAndSpace(argThat("foo-organization"::equals), argThat("foo-space"::equals)); - then(cloudFoundryClient).should().serviceInstances(); - then(clientServiceInstances).should() - .get(argThat(req -> "foo-service-instance-id".equals(req.getServiceInstanceId()))); - then(cloudFoundryClient).should().spaces(); - then(cloudFoundryClient).should().organizations(); - then(clientSpaces).should().get(argThat(req -> "foo-space-id".equals(req.getSpaceId()))); - then(clientOrganizations).should().get(argThat(req -> "foo-organization-id".equals(req.getOrganizationId()))); - then(cloudFoundryOperations).should().services(); - then(operationsServices).should().getInstance(argThat(req -> "my-foo-service".equals(req.getName()))); - then(cloudFoundryClient).shouldHaveNoMoreInteractions(); - then(cloudFoundryOperations).shouldHaveNoMoreInteractions(); - then(operationsUtils).shouldHaveNoMoreInteractions(); + then(this.cloudFoundryClient).should().serviceInstances(); + then(this.clientServiceInstances).should() + .get(argThat((req) -> "foo-service-instance-id".equals(req.getServiceInstanceId()))); + then(this.cloudFoundryClient).should().spaces(); + then(this.cloudFoundryClient).should().organizations(); + then(this.clientSpaces).should().get(argThat((req) -> "foo-space-id".equals(req.getSpaceId()))); + then(this.clientOrganizations).should() + .get(argThat((req) -> "foo-organization-id".equals(req.getOrganizationId()))); + then(this.cloudFoundryOperations).should().services(); + then(this.operationsServices).should().getInstance(argThat((req) -> "my-foo-service".equals(req.getName()))); + then(this.cloudFoundryClient).shouldHaveNoMoreInteractions(); + then(this.cloudFoundryOperations).shouldHaveNoMoreInteractions(); + then(this.operationsUtils).shouldHaveNoMoreInteractions(); } @Test void getServiceInstanceByName() { - given(operationsServices.getInstance(any(GetServiceInstanceRequest.class))) + given(this.operationsServices.getInstance(any(GetServiceInstanceRequest.class))) .willReturn(Mono.just(ServiceInstance.builder() .id("foo-service-instance-id") .name("my-foo-service") @@ -913,31 +850,28 @@ class CloudFoundryAppDeployerTest { .type(ServiceInstanceType.MANAGED) .build())); - org.springframework.cloud.appbroker.deployer.deployer.GetServiceInstanceRequest request = - org.springframework.cloud.appbroker.deployer.deployer.GetServiceInstanceRequest + org.springframework.cloud.appbroker.deployer.deployer.GetServiceInstanceRequest request = org.springframework.cloud.appbroker.deployer.deployer.GetServiceInstanceRequest .builder() .name("my-foo-service") .build(); - StepVerifier.create(appDeployer.getServiceInstance(request)) - .assertNext(response -> { - assertThat(response.getName()).isEqualTo("my-foo-service"); - assertThat(response.getService()).isEqualTo("foo-service"); - assertThat(response.getPlan()).isEqualTo("foo-plan"); - }) - .verifyComplete(); + StepVerifier.create(this.appDeployer.getServiceInstance(request)).assertNext((response) -> { + assertThat(response.getName()).isEqualTo("my-foo-service"); + assertThat(response.getService()).isEqualTo("foo-service"); + assertThat(response.getPlan()).isEqualTo("foo-plan"); + }).verifyComplete(); - then(operationsUtils).should().getOperations(argThat(CollectionUtils::isEmpty)); - then(cloudFoundryOperations).should().services(); - then(operationsServices).should().getInstance(argThat(req -> "my-foo-service".equals(req.getName()))); - then(cloudFoundryClient).shouldHaveNoInteractions(); - then(cloudFoundryOperations).shouldHaveNoMoreInteractions(); - then(operationsUtils).shouldHaveNoMoreInteractions(); + then(this.operationsUtils).should().getOperations(argThat(CollectionUtils::isEmpty)); + then(this.cloudFoundryOperations).should().services(); + then(this.operationsServices).should().getInstance(argThat((req) -> "my-foo-service".equals(req.getName()))); + then(this.cloudFoundryClient).shouldHaveNoInteractions(); + then(this.cloudFoundryOperations).shouldHaveNoMoreInteractions(); + then(this.operationsUtils).shouldHaveNoMoreInteractions(); } @Test void getServiceInstanceByNameAndSpace() { - given(operationsServices.getInstance(any(GetServiceInstanceRequest.class))) + given(this.operationsServices.getInstance(any(GetServiceInstanceRequest.class))) .willReturn(Mono.just(ServiceInstance.builder() .id("foo-service-instance-id") .name("my-foo-service") @@ -946,40 +880,44 @@ class CloudFoundryAppDeployerTest { .type(ServiceInstanceType.MANAGED) .build())); - org.springframework.cloud.appbroker.deployer.deployer.GetServiceInstanceRequest request = - org.springframework.cloud.appbroker.deployer.deployer.GetServiceInstanceRequest + org.springframework.cloud.appbroker.deployer.deployer.GetServiceInstanceRequest request = org.springframework.cloud.appbroker.deployer.deployer.GetServiceInstanceRequest .builder() .name("my-foo-service") - .properties(singletonMap(TARGET_PROPERTY_KEY, "foo-space")) + .properties(Collections.singletonMap(DeploymentProperties.TARGET_PROPERTY_KEY, "foo-space")) .build(); - StepVerifier.create(appDeployer.getServiceInstance(request)) - .assertNext(response -> { - assertThat(response.getName()).isEqualTo("my-foo-service"); - assertThat(response.getService()).isEqualTo("foo-service"); - assertThat(response.getPlan()).isEqualTo("foo-plan"); - }) - .verifyComplete(); + StepVerifier.create(this.appDeployer.getServiceInstance(request)).assertNext((response) -> { + assertThat(response.getName()).isEqualTo("my-foo-service"); + assertThat(response.getService()).isEqualTo("foo-service"); + assertThat(response.getPlan()).isEqualTo("foo-plan"); + }).verifyComplete(); - then(operationsUtils).should().getOperations( - argThat(argument -> "foo-space".equals(argument.get(TARGET_PROPERTY_KEY)))); - then(cloudFoundryOperations).should().services(); - then(operationsServices).should().getInstance(argThat(req -> "my-foo-service".equals(req.getName()))); - then(cloudFoundryClient).shouldHaveNoInteractions(); - then(cloudFoundryOperations).shouldHaveNoMoreInteractions(); - then(operationsUtils).shouldHaveNoMoreInteractions(); + then(this.operationsUtils).should() + .getOperations( + argThat((argument) -> "foo-space".equals(argument.get(DeploymentProperties.TARGET_PROPERTY_KEY)))); + then(this.cloudFoundryOperations).should().services(); + then(this.operationsServices).should().getInstance(argThat((req) -> "my-foo-service".equals(req.getName()))); + then(this.cloudFoundryClient).shouldHaveNoInteractions(); + then(this.cloudFoundryOperations).shouldHaveNoMoreInteractions(); + then(this.operationsUtils).shouldHaveNoMoreInteractions(); } @Test void getDeployedAppByName() { - given(operationsApplications.get(any(org.cloudfoundry.operations.applications.GetApplicationRequest.class))) + given(this.operationsApplications + .get(any(org.cloudfoundry.operations.applications.GetApplicationRequest.class))) .willReturn(Mono.just(ApplicationDetail.builder() .id("foo-id") .name("foo-name") // fields below are required by builder but we don't care - .stack("").diskQuota(1).instances(1).memoryLimit(1).requestedState("").runningInstances(1) // + .stack("") + .diskQuota(1) + .instances(1) + .memoryLimit(1) + .requestedState("") + .runningInstances(1) // .build())); - given(clientApplications.summary(any(SummaryApplicationRequest.class))) + given(this.clientApplications.summary(any(SummaryApplicationRequest.class))) .willReturn(Mono.just(SummaryApplicationResponse.builder() .id("foo-id") .name("foo-name") @@ -992,36 +930,43 @@ class CloudFoundryAppDeployerTest { .environmentJson("foo-key", "foo-value") .build())); - StepVerifier.create(appDeployer.get(GetApplicationRequest.builder().name("foo-name").build())) - .assertNext(response -> { + StepVerifier.create(this.appDeployer.get(GetApplicationRequest.builder().name("foo-name").build())) + .assertNext((response) -> { assertThat(response.getName()).isEqualTo("foo-name"); assertThat(response.getServices()).hasSize(2); assertThat(response.getServices().get(0)).isEqualTo("foo-service-1"); assertThat(response.getServices().get(1)).isEqualTo("foo-service-2"); - assertThat(response.getEnvironment()).isEqualTo(singletonMap("foo-key", "foo-value")); + assertThat(response.getEnvironment()).isEqualTo(Collections.singletonMap("foo-key", "foo-value")); }) .verifyComplete(); - then(operationsUtils).should().getOperations(argThat(CollectionUtils::isEmpty)); - then(cloudFoundryOperations).should().applications(); - then(operationsApplications).should().get(argThat(request -> "foo-name".equals(request.getName()))); - then(clientApplications).should().summary(argThat(request -> "foo-id".equals(request.getApplicationId()))); - then(operationsApplications).shouldHaveNoMoreInteractions(); - then(clientApplications).shouldHaveNoMoreInteractions(); - then(cloudFoundryOperations).shouldHaveNoMoreInteractions(); - then(operationsUtils).shouldHaveNoMoreInteractions(); + then(this.operationsUtils).should().getOperations(argThat(CollectionUtils::isEmpty)); + then(this.cloudFoundryOperations).should().applications(); + then(this.operationsApplications).should().get(argThat((request) -> "foo-name".equals(request.getName()))); + then(this.clientApplications).should() + .summary(argThat((request) -> "foo-id".equals(request.getApplicationId()))); + then(this.operationsApplications).shouldHaveNoMoreInteractions(); + then(this.clientApplications).shouldHaveNoMoreInteractions(); + then(this.cloudFoundryOperations).shouldHaveNoMoreInteractions(); + then(this.operationsUtils).shouldHaveNoMoreInteractions(); } @Test void getDeployedAppByNameAndSpace() { - given(operationsApplications.get(any(org.cloudfoundry.operations.applications.GetApplicationRequest.class))) + given(this.operationsApplications + .get(any(org.cloudfoundry.operations.applications.GetApplicationRequest.class))) .willReturn(Mono.just(ApplicationDetail.builder() .id("foo-id") .name("foo-name") // fields below are required by builder but we don't care - .stack("").diskQuota(1).instances(1).memoryLimit(1).requestedState("").runningInstances(1) // + .stack("") + .diskQuota(1) + .instances(1) + .memoryLimit(1) + .requestedState("") + .runningInstances(1) // .build())); - given(clientApplications.summary(any(SummaryApplicationRequest.class))) + given(this.clientApplications.summary(any(SummaryApplicationRequest.class))) .willReturn(Mono.just(SummaryApplicationResponse.builder() .id("foo-id") .name("foo-name") @@ -1036,45 +981,43 @@ class CloudFoundryAppDeployerTest { GetApplicationRequest request = GetApplicationRequest.builder() .name("foo-name") - .properties(singletonMap(TARGET_PROPERTY_KEY, "foo-space")) + .properties(Collections.singletonMap(DeploymentProperties.TARGET_PROPERTY_KEY, "foo-space")) .build(); - StepVerifier.create(appDeployer.get(request)) - .assertNext(response -> { - assertThat(response.getName()).isEqualTo("foo-name"); - assertThat(response.getServices()).hasSize(2); - assertThat(response.getServices().get(0)).isEqualTo("foo-service-1"); - assertThat(response.getServices().get(1)).isEqualTo("foo-service-2"); - assertThat(response.getEnvironment()).isEqualTo(singletonMap("foo-key", "foo-value")); - }) - .verifyComplete(); + StepVerifier.create(this.appDeployer.get(request)).assertNext((response) -> { + assertThat(response.getName()).isEqualTo("foo-name"); + assertThat(response.getServices()).hasSize(2); + assertThat(response.getServices().get(0)).isEqualTo("foo-service-1"); + assertThat(response.getServices().get(1)).isEqualTo("foo-service-2"); + assertThat(response.getEnvironment()).isEqualTo(Collections.singletonMap("foo-key", "foo-value")); + }).verifyComplete(); - then(operationsUtils).should().getOperations( - argThat(argument -> "foo-space".equals(argument.get(TARGET_PROPERTY_KEY)))); - then(cloudFoundryOperations).should().applications(); - then(operationsApplications).should().get(argThat(req -> "foo-name".equals(req.getName()))); - then(clientApplications).should().summary(argThat(req -> "foo-id".equals(req.getApplicationId()))); - then(operationsApplications).shouldHaveNoMoreInteractions(); - then(clientApplications).shouldHaveNoMoreInteractions(); - then(cloudFoundryOperations).shouldHaveNoMoreInteractions(); - then(operationsUtils).shouldHaveNoMoreInteractions(); + then(this.operationsUtils).should() + .getOperations( + argThat((argument) -> "foo-space".equals(argument.get(DeploymentProperties.TARGET_PROPERTY_KEY)))); + then(this.cloudFoundryOperations).should().applications(); + then(this.operationsApplications).should().get(argThat((req) -> "foo-name".equals(req.getName()))); + then(this.clientApplications).should().summary(argThat((req) -> "foo-id".equals(req.getApplicationId()))); + then(this.operationsApplications).shouldHaveNoMoreInteractions(); + then(this.clientApplications).shouldHaveNoMoreInteractions(); + then(this.cloudFoundryOperations).shouldHaveNoMoreInteractions(); + then(this.operationsUtils).shouldHaveNoMoreInteractions(); } private ApplicationManifest.Builder baseManifest() { - return ApplicationManifest.builder() - .services(new ArrayList<>()); + return ApplicationManifest.builder().services(new ArrayList<>()); } private ApplicationManifest.Builder baseManifestWithSpringAppJson() { return ApplicationManifest.builder() .environmentVariable("SPRING_APPLICATION_JSON", - "{\"spring.cloud.appbroker.service-instance-id\":\"" + SERVICE_INSTANCE_ID + "\"}") + "{\"spring.cloud.appbroker.service-instance-id\":\"" + SERVICE_INSTANCE_ID + "\"}") .services(new ArrayList<>()); } private ApplicationManifest.Builder baseManifestWithSpringAppJson(String json) { return ApplicationManifest.builder() .environmentVariable("SPRING_APPLICATION_JSON", - "{" + json + ",\"spring.cloud.appbroker.service-instance-id\":\"" + SERVICE_INSTANCE_ID + "\"}") + "{" + json + ",\"spring.cloud.appbroker.service-instance-id\":\"" + SERVICE_INSTANCE_ID + "\"}") .services(new ArrayList<>()); } diff --git a/spring-cloud-app-broker-deployer-cloudfoundry/src/test/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryAppDeployerUpdateApplicationTest.java b/spring-cloud-app-broker-deployer-cloudfoundry/src/test/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryAppDeployerUpdateApplicationTests.java similarity index 50% rename from spring-cloud-app-broker-deployer-cloudfoundry/src/test/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryAppDeployerUpdateApplicationTest.java rename to spring-cloud-app-broker-deployer-cloudfoundry/src/test/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryAppDeployerUpdateApplicationTests.java index 61e4528..034a8d6 100644 --- a/spring-cloud-app-broker-deployer-cloudfoundry/src/test/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryAppDeployerUpdateApplicationTest.java +++ b/spring-cloud-app-broker-deployer-cloudfoundry/src/test/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryAppDeployerUpdateApplicationTests.java @@ -84,11 +84,11 @@ import reactor.core.publisher.Mono; import reactor.test.StepVerifier; import org.springframework.cloud.appbroker.deployer.deployer.AppDeployer; +import org.springframework.cloud.appbroker.deployer.deployer.DeploymentProperties; import org.springframework.cloud.appbroker.deployer.deployer.UpdateApplicationRequest; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.ResourceLoader; -import static java.util.Collections.singletonMap; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyMap; @@ -97,11 +97,10 @@ import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.then; import static org.mockito.Mockito.times; -import static org.springframework.cloud.appbroker.deployer.deployer.DeploymentProperties.TARGET_PROPERTY_KEY; @ExtendWith(MockitoExtension.class) @MockitoSettings(strictness = Strictness.LENIENT) -class CloudFoundryAppDeployerUpdateApplicationTest { +class CloudFoundryAppDeployerUpdateApplicationTests { private static final String APP_ID = "app-id"; @@ -160,72 +159,67 @@ class CloudFoundryAppDeployerUpdateApplicationTest { CloudFoundryTargetProperties targetProperties = new CloudFoundryTargetProperties(); targetProperties.setDefaultSpace("default-space"); - given(operationsApplications.pushManifest(any())).willReturn(Mono.empty()); - given(resourceLoader.getResource(APP_PATH)).willReturn(new FileSystemResource(APP_PATH)); + given(this.operationsApplications.pushManifest(any())).willReturn(Mono.empty()); + given(this.resourceLoader.getResource(APP_PATH)).willReturn(new FileSystemResource(APP_PATH)); - given(cloudFoundryOperations.services()).willReturn(operationsServices); - given(cloudFoundryOperations.applications()).willReturn(operationsApplications); - given(cloudFoundryOperations.domains()).willReturn(domains); - given(cloudFoundryOperations.spaces()).willReturn(spaces); - given(cloudFoundryClient.applicationsV2()).willReturn(applicationsV2); - given(cloudFoundryClient.applicationsV3()).willReturn(applicationsV3); - given(cloudFoundryClient.packages()).willReturn(packages); - given(cloudFoundryClient.builds()).willReturn(builds); - given(cloudFoundryClient.deploymentsV3()).willReturn(deploymentsV3); - given(cloudFoundryClient.routes()).willReturn(routes); - given(operationsUtils.getOperations(anyMap())).willReturn(Mono.just(cloudFoundryOperations)); - given(operationsUtils.getOperationsForSpace(anyString())).willReturn(Mono.just(cloudFoundryOperations)); + given(this.cloudFoundryOperations.services()).willReturn(this.operationsServices); + given(this.cloudFoundryOperations.applications()).willReturn(this.operationsApplications); + given(this.cloudFoundryOperations.domains()).willReturn(this.domains); + given(this.cloudFoundryOperations.spaces()).willReturn(this.spaces); + given(this.cloudFoundryClient.applicationsV2()).willReturn(this.applicationsV2); + given(this.cloudFoundryClient.applicationsV3()).willReturn(this.applicationsV3); + given(this.cloudFoundryClient.packages()).willReturn(this.packages); + given(this.cloudFoundryClient.builds()).willReturn(this.builds); + given(this.cloudFoundryClient.deploymentsV3()).willReturn(this.deploymentsV3); + given(this.cloudFoundryClient.routes()).willReturn(this.routes); + given(this.operationsUtils.getOperations(anyMap())).willReturn(Mono.just(this.cloudFoundryOperations)); + given(this.operationsUtils.getOperationsForSpace(anyString())) + .willReturn(Mono.just(this.cloudFoundryOperations)); - appDeployer = new CloudFoundryAppDeployer(deploymentProperties, - cloudFoundryOperations, cloudFoundryClient, operationsUtils, targetProperties, resourceLoader); + this.appDeployer = new CloudFoundryAppDeployer(deploymentProperties, this.cloudFoundryOperations, + this.cloudFoundryClient, this.operationsUtils, targetProperties, this.resourceLoader); - given(operationsApplications.get(any())) - .willReturn(Mono.just(createApplicationDetail())); + given(this.operationsApplications.get(any())).willReturn(Mono.just(createApplicationDetail())); - given(applicationsV2.summary(any(SummaryApplicationRequest.class))) + given(this.applicationsV2.summary(any(SummaryApplicationRequest.class))) .willReturn(Mono.just(SummaryApplicationResponse.builder() .id(APP_ID) .name(APP_NAME) .services(Collections.emptyList()) .build())); - given(packages.create(any())) - .willReturn(Mono.just(CreatePackageResponse.builder() - .data(BitsData.builder().build()) - .state(PackageState.READY) - .type(PackageType.BITS) - .createdAt("DATETIME") - .id("package-id") - .build())); + given(this.packages.create(any())).willReturn(Mono.just(CreatePackageResponse.builder() + .data(BitsData.builder().build()) + .state(PackageState.READY) + .type(PackageType.BITS) + .createdAt("DATETIME") + .id("package-id") + .build())); - given(packages.upload(any())) - .willReturn(Mono.just(UploadPackageResponse.builder() - .data(BitsData.builder().build()) - .state(PackageState.READY) - .type(PackageType.BITS) - .createdAt("2019-07-05T10:37:47Z") - .createdAt("2019-07-05T10:37:47Z") - .id("package-id") - .build())); + given(this.packages.upload(any())).willReturn(Mono.just(UploadPackageResponse.builder() + .data(BitsData.builder().build()) + .state(PackageState.READY) + .type(PackageType.BITS) + .createdAt("2019-07-05T10:37:47Z") + .createdAt("2019-07-05T10:37:47Z") + .id("package-id") + .build())); + given(this.packages.get(any())).willReturn(Mono.just(GetPackageResponse.builder() + .data(BitsData.builder().build()) + .state(PackageState.READY) + .type(PackageType.BITS) + .createdAt("DATETIME") + .id("package-id") + .build())); - given(packages.get(any())) - .willReturn(Mono.just(GetPackageResponse.builder() - .data(BitsData.builder().build()) - .state(PackageState.READY) - .type(PackageType.BITS) - .createdAt("DATETIME") - .id("package-id") - .build())); - - given(applicationsV3.listPackages(any())) - .willReturn(Mono.just(ListApplicationPackagesResponse.builder() - .resource(createPackage("2019-07-05T10:37:47Z", "package-id-1")) - .resource(createPackage("2019-07-05T12:37:47Z", "package-id-2")) - .resource(createPackage("2019-07-06T10:37:47Z", "package-id-3")) - .resource(createPackage("2019-07-06T11:37:47Z", "package-id-4")) - .build())); - given(applicationsV3.update(any())) + given(this.applicationsV3.listPackages(any())).willReturn(Mono.just(ListApplicationPackagesResponse.builder() + .resource(createPackage("2019-07-05T10:37:47Z", "package-id-1")) + .resource(createPackage("2019-07-05T12:37:47Z", "package-id-2")) + .resource(createPackage("2019-07-06T10:37:47Z", "package-id-3")) + .resource(createPackage("2019-07-06T11:37:47Z", "package-id-4")) + .build())); + given(this.applicationsV3.update(any())) .willReturn(Mono.just(org.cloudfoundry.client.v3.applications.UpdateApplicationResponse.builder() .createdAt("2019-07-06T11:37:47Z") .id("id") @@ -234,127 +228,112 @@ class CloudFoundryAppDeployerUpdateApplicationTest { .state(ApplicationState.STARTED) .build())); - given(builds.create(any())) - .willReturn(Mono.just(CreateBuildResponse.builder() - .state(BuildState.STAGING) - .createdBy(CreatedBy.builder().id("create-by-id").email("an-email").name("creator").build()) - .inputPackage(Relationship.builder().id("package-id").build()) - .lifecycle(createLifecycle()) - .createdAt("DATETIME") - .id("build-id") - .build())); - given(builds.get(any())) - .willReturn(Mono.just(GetBuildResponse.builder() - .state(BuildState.STAGED) - .createdBy(CreatedBy.builder().id("create-by-id").email("an-email").name("creator").build()) - .inputPackage(Relationship.builder().id("package-id").build()) - .lifecycle(createLifecycle()) - .droplet(Droplet.builder().id("droplet-id").build()) - .createdAt("DATETIME") - .id("build-id") - .build())); + given(this.builds.create(any())).willReturn(Mono.just(CreateBuildResponse.builder() + .state(BuildState.STAGING) + .createdBy(CreatedBy.builder().id("create-by-id").email("an-email").name("creator").build()) + .inputPackage(Relationship.builder().id("package-id").build()) + .lifecycle(createLifecycle()) + .createdAt("DATETIME") + .id("build-id") + .build())); + given(this.builds.get(any())).willReturn(Mono.just(GetBuildResponse.builder() + .state(BuildState.STAGED) + .createdBy(CreatedBy.builder().id("create-by-id").email("an-email").name("creator").build()) + .inputPackage(Relationship.builder().id("package-id").build()) + .lifecycle(createLifecycle()) + .droplet(Droplet.builder().id("droplet-id").build()) + .createdAt("DATETIME") + .id("build-id") + .build())); - given(deploymentsV3.create(any())) - .willReturn(Mono.just(CreateDeploymentResponse.builder() - .state(DeploymentState.DEPLOYED) - .createdAt("DATETIME") - .id("deployment-id") - .build())); - given(deploymentsV3.get(any())) - .willReturn(Mono.just(GetDeploymentResponse.builder() - .state(DeploymentState.DEPLOYED) - .status(org.cloudfoundry.client.v3.deployments.Status.builder().value(DeploymentStatusValue.FINALIZED).reason( - DeploymentStatusReason.DEPLOYED).build()) - .createdAt("DATETIME") - .id("deployment-id") - .build())); + given(this.deploymentsV3.create(any())).willReturn(Mono.just(CreateDeploymentResponse.builder() + .state(DeploymentState.DEPLOYED) + .createdAt("DATETIME") + .id("deployment-id") + .build())); + given(this.deploymentsV3.get(any())).willReturn(Mono.just(GetDeploymentResponse.builder() + .state(DeploymentState.DEPLOYED) + .status(org.cloudfoundry.client.v3.deployments.Status.builder() + .value(DeploymentStatusValue.FINALIZED) + .reason(DeploymentStatusReason.DEPLOYED) + .build()) + .createdAt("DATETIME") + .id("deployment-id") + .build())); } @Test void updateApp() { - given(applicationsV2.update(any())) - .willReturn(Mono.just(UpdateApplicationResponse.builder() - .build())); + given(this.applicationsV2.update(any())).willReturn(Mono.just(UpdateApplicationResponse.builder().build())); - UpdateApplicationRequest request = UpdateApplicationRequest.builder() - .name(APP_NAME) - .path(APP_PATH) - .build(); + UpdateApplicationRequest request = UpdateApplicationRequest.builder().name(APP_NAME).path(APP_PATH).build(); - StepVerifier.create(appDeployer.update(request)) - .assertNext(response -> assertThat(response.getName()).isEqualTo(APP_NAME)) + StepVerifier.create(this.appDeployer.update(request)) + .assertNext((response) -> assertThat(response.getName()).isEqualTo(APP_NAME)) .verifyComplete(); } @Test void updateAppWhenDeploymentObjectHasNotState() { - given(deploymentsV3.get(any())) - .willReturn(Mono.just(GetDeploymentResponse.builder() - .status(org.cloudfoundry.client.v3.deployments.Status.builder().value(DeploymentStatusValue.FINALIZED).reason( - DeploymentStatusReason.DEPLOYED).build()) - .createdAt("DATETIME") - .id("deployment-id") - .build())); + given(this.deploymentsV3.get(any())).willReturn(Mono.just(GetDeploymentResponse.builder() + .status(org.cloudfoundry.client.v3.deployments.Status.builder() + .value(DeploymentStatusValue.FINALIZED) + .reason(DeploymentStatusReason.DEPLOYED) + .build()) + .createdAt("DATETIME") + .id("deployment-id") + .build())); - given(applicationsV2.update(any())) - .willReturn(Mono.just(UpdateApplicationResponse.builder() - .build())); + given(this.applicationsV2.update(any())).willReturn(Mono.just(UpdateApplicationResponse.builder().build())); - UpdateApplicationRequest request = UpdateApplicationRequest.builder() - .name(APP_NAME) - .path(APP_PATH) - .build(); + UpdateApplicationRequest request = UpdateApplicationRequest.builder().name(APP_NAME).path(APP_PATH).build(); - StepVerifier.create(appDeployer.update(request)) - .assertNext(response -> assertThat(response.getName()).isEqualTo(APP_NAME)) + StepVerifier.create(this.appDeployer.update(request)) + .assertNext((response) -> assertThat(response.getName()).isEqualTo(APP_NAME)) .verifyComplete(); } @Test void updateAppWithTarget() { - given(applicationsV2.update(any())) - .willReturn(Mono.just(UpdateApplicationResponse.builder() - .build())); + given(this.applicationsV2.update(any())).willReturn(Mono.just(UpdateApplicationResponse.builder().build())); - Map properties = singletonMap(TARGET_PROPERTY_KEY, "service-instance-id"); + Map properties = Collections.singletonMap(DeploymentProperties.TARGET_PROPERTY_KEY, + "service-instance-id"); UpdateApplicationRequest request = UpdateApplicationRequest.builder() .name(APP_NAME) .path(APP_PATH) .properties(properties) .build(); - StepVerifier.create(appDeployer.update(request)) - .assertNext(response -> assertThat(response.getName()).isEqualTo(APP_NAME)) + StepVerifier.create(this.appDeployer.update(request)) + .assertNext((response) -> assertThat(response.getName()).isEqualTo(APP_NAME)) .verifyComplete(); - then(operationsUtils).should().getOperations(properties); - then(operationsUtils).shouldHaveNoMoreInteractions(); + then(this.operationsUtils).should().getOperations(properties); + then(this.operationsUtils).shouldHaveNoMoreInteractions(); } @Test void updateAppProperties() { - ArgumentCaptor updateApplicationRequestCaptor = - ArgumentCaptor.forClass(org.cloudfoundry.client.v2.applications.UpdateApplicationRequest.class); + ArgumentCaptor updateApplicationRequestCaptor = ArgumentCaptor + .forClass(org.cloudfoundry.client.v2.applications.UpdateApplicationRequest.class); - given(applicationsV2.update(updateApplicationRequestCaptor.capture())) - .willReturn(Mono.just(UpdateApplicationResponse.builder() - .build())); + given(this.applicationsV2.update(updateApplicationRequestCaptor.capture())) + .willReturn(Mono.just(UpdateApplicationResponse.builder().build())); Map properties = new HashMap<>(); properties.put("count", "2"); properties.put("disk", "2G"); properties.put("memory", "1G"); - UpdateApplicationRequest request = - UpdateApplicationRequest - .builder() - .name(APP_NAME) - .path(APP_PATH) - .properties(properties) - .build(); + UpdateApplicationRequest request = UpdateApplicationRequest.builder() + .name(APP_NAME) + .path(APP_PATH) + .properties(properties) + .build(); - StepVerifier.create(appDeployer.update(request)) - .assertNext(response -> assertThat(response.getName()).isEqualTo(APP_NAME)) + StepVerifier.create(this.appDeployer.update(request)) + .assertNext((response) -> assertThat(response.getName()).isEqualTo(APP_NAME)) .verifyComplete(); org.cloudfoundry.client.v2.applications.UpdateApplicationRequest updateApplicationRequest = updateApplicationRequestCaptor @@ -366,23 +345,20 @@ class CloudFoundryAppDeployerUpdateApplicationTest { @Test void updateAppEnvironment() { - ArgumentCaptor updateApplicationRequestCaptor = - ArgumentCaptor.forClass(org.cloudfoundry.client.v2.applications.UpdateApplicationRequest.class); + ArgumentCaptor updateApplicationRequestCaptor = ArgumentCaptor + .forClass(org.cloudfoundry.client.v2.applications.UpdateApplicationRequest.class); - given(applicationsV2.update(updateApplicationRequestCaptor.capture())) - .willReturn(Mono.just(UpdateApplicationResponse.builder() - .build())); + given(this.applicationsV2.update(updateApplicationRequestCaptor.capture())) + .willReturn(Mono.just(UpdateApplicationResponse.builder().build())); - UpdateApplicationRequest request = - UpdateApplicationRequest - .builder() - .name(APP_NAME) - .path(APP_PATH) - .environment("ENV_VAR", "test-env") - .build(); + UpdateApplicationRequest request = UpdateApplicationRequest.builder() + .name(APP_NAME) + .path(APP_PATH) + .environment("ENV_VAR", "test-env") + .build(); - StepVerifier.create(appDeployer.update(request)) - .assertNext(response -> assertThat(response.getName()).isEqualTo(APP_NAME)) + StepVerifier.create(this.appDeployer.update(request)) + .assertNext((response) -> assertThat(response.getName()).isEqualTo(APP_NAME)) .verifyComplete(); assertThat(updateApplicationRequestCaptor.getValue().getEnvironmentJsons().get("SPRING_APPLICATION_JSON")) @@ -391,10 +367,10 @@ class CloudFoundryAppDeployerUpdateApplicationTest { @Test void updateAppWithUpgrade() { - ArgumentCaptor updateApplicationRequestCaptor = - ArgumentCaptor.forClass(org.cloudfoundry.client.v2.applications.UpdateApplicationRequest.class); + ArgumentCaptor updateApplicationRequestCaptor = ArgumentCaptor + .forClass(org.cloudfoundry.client.v2.applications.UpdateApplicationRequest.class); - given(applicationsV2.update(any())).willReturn(Mono.just(UpdateApplicationResponse.builder().build())); + given(this.applicationsV2.update(any())).willReturn(Mono.just(UpdateApplicationResponse.builder().build())); UpdateApplicationRequest request = UpdateApplicationRequest.builder() .name(APP_NAME) @@ -403,33 +379,27 @@ class CloudFoundryAppDeployerUpdateApplicationTest { .environment("TEST_KEY", "TEST_VALUE") .build(); - StepVerifier.create(appDeployer.update(request)) - .assertNext(response -> assertThat(response.getName()).isEqualTo(APP_NAME)) + StepVerifier.create(this.appDeployer.update(request)) + .assertNext((response) -> assertThat(response.getName()).isEqualTo(APP_NAME)) .verifyComplete(); - then(applicationsV2).should().summary(any(SummaryApplicationRequest.class)); - then(applicationsV2).should().update(updateApplicationRequestCaptor.capture()); + then(this.applicationsV2).should().summary(any(SummaryApplicationRequest.class)); + then(this.applicationsV2).should().update(updateApplicationRequestCaptor.capture()); assertThat(updateApplicationRequestCaptor.getValue().getEnvironmentJsons().get("SPRING_APPLICATION_JSON")) .isEqualTo("{\"TEST_KEY\":\"TEST_VALUE\"}"); - then(applicationsV2).shouldHaveNoMoreInteractions(); + then(this.applicationsV2).shouldHaveNoMoreInteractions(); } @Test void updateAppWithNoNewServices() { - given(applicationsV2.summary(any(SummaryApplicationRequest.class))) + given(this.applicationsV2.summary(any(SummaryApplicationRequest.class))) .willReturn(Mono.just(SummaryApplicationResponse.builder() .id(APP_ID) .name(APP_NAME) - .service(ServiceInstance.builder() - .name("service-1") - .build()) - .service(ServiceInstance.builder() - .name("service-2") - .build()) - .build())); - given(applicationsV2.update(any())) - .willReturn(Mono.just(UpdateApplicationResponse.builder() + .service(ServiceInstance.builder().name("service-1").build()) + .service(ServiceInstance.builder().name("service-2").build()) .build())); + given(this.applicationsV2.update(any())).willReturn(Mono.just(UpdateApplicationResponse.builder().build())); UpdateApplicationRequest request = UpdateApplicationRequest.builder() .name(APP_NAME) @@ -438,23 +408,20 @@ class CloudFoundryAppDeployerUpdateApplicationTest { .service("service-2") .build(); - StepVerifier.create(appDeployer.update(request)) - .assertNext(response -> assertThat(response.getName()).isEqualTo(APP_NAME)) + StepVerifier.create(this.appDeployer.update(request)) + .assertNext((response) -> assertThat(response.getName()).isEqualTo(APP_NAME)) .verifyComplete(); - then(applicationsV2).should().summary(SummaryApplicationRequest.builder().applicationId(APP_ID).build()); - then(applicationsV2).should().update(argThat(arg -> APP_ID.equals(arg.getApplicationId()))); - then(operationsServices).shouldHaveNoMoreInteractions(); - then(applicationsV2).shouldHaveNoMoreInteractions(); + then(this.applicationsV2).should().summary(SummaryApplicationRequest.builder().applicationId(APP_ID).build()); + then(this.applicationsV2).should().update(argThat((arg) -> APP_ID.equals(arg.getApplicationId()))); + then(this.operationsServices).shouldHaveNoMoreInteractions(); + then(this.applicationsV2).shouldHaveNoMoreInteractions(); } @Test void updateAppWithNewServices() { - given(operationsServices.bind(any(BindServiceInstanceRequest.class))) - .willReturn(Mono.empty()); - given(applicationsV2.update(any())) - .willReturn(Mono.just(UpdateApplicationResponse.builder() - .build())); + given(this.operationsServices.bind(any(BindServiceInstanceRequest.class))).willReturn(Mono.empty()); + given(this.applicationsV2.update(any())).willReturn(Mono.just(UpdateApplicationResponse.builder().build())); UpdateApplicationRequest request = UpdateApplicationRequest.builder() .name(APP_NAME) @@ -463,21 +430,25 @@ class CloudFoundryAppDeployerUpdateApplicationTest { .service("service-2") .build(); - StepVerifier.create(appDeployer.update(request)) - .assertNext(response -> assertThat(response.getName()).isEqualTo(APP_NAME)) + StepVerifier.create(this.appDeployer.update(request)) + .assertNext((response) -> assertThat(response.getName()).isEqualTo(APP_NAME)) .verifyComplete(); - then(applicationsV2).should().summary(SummaryApplicationRequest.builder().applicationId(APP_ID).build()); - then(operationsServices).should() - .bind(BindServiceInstanceRequest.builder().serviceInstanceName("service-1").applicationName(APP_NAME) + then(this.applicationsV2).should().summary(SummaryApplicationRequest.builder().applicationId(APP_ID).build()); + then(this.operationsServices).should() + .bind(BindServiceInstanceRequest.builder() + .serviceInstanceName("service-1") + .applicationName(APP_NAME) .build()); - then(operationsServices).should() - .bind(BindServiceInstanceRequest.builder().serviceInstanceName("service-2").applicationName(APP_NAME) + then(this.operationsServices).should() + .bind(BindServiceInstanceRequest.builder() + .serviceInstanceName("service-2") + .applicationName(APP_NAME) .build()); - then(applicationsV2).should().update(argThat(arg -> APP_ID.equals(arg.getApplicationId()))); + then(this.applicationsV2).should().update(argThat((arg) -> APP_ID.equals(arg.getApplicationId()))); - then(operationsServices).shouldHaveNoMoreInteractions(); - then(applicationsV2).shouldHaveNoMoreInteractions(); + then(this.operationsServices).shouldHaveNoMoreInteractions(); + then(this.applicationsV2).shouldHaveNoMoreInteractions(); } @Test @@ -494,27 +465,25 @@ class CloudFoundryAppDeployerUpdateApplicationTest { .properties(properties) .build(); - StepVerifier.create(appDeployer.update(request)) - .assertNext(response -> assertThat(response.getName()).isEqualTo(APP_NAME)) + StepVerifier.create(this.appDeployer.update(request)) + .assertNext((response) -> assertThat(response.getName()).isEqualTo(APP_NAME)) .verifyComplete(); - - then(routes).should().create(CreateRouteRequest.builder() - .domainId("myDomainComId") - .spaceId("space-id") - .host("my.host") - .build()); - then(applicationsV2).should().associateRoute(AssociateApplicationRouteRequest.builder() - .applicationId(APP_ID) - .routeId("myDomainComId-route") - .build()); + then(this.routes).should() + .create(CreateRouteRequest.builder().domainId("myDomainComId").spaceId("space-id").host("my.host").build()); + then(this.applicationsV2).should() + .associateRoute(AssociateApplicationRouteRequest.builder() + .applicationId(APP_ID) + .routeId("myDomainComId-route") + .build()); } @Test void updateAppWithHostDomainAndDomains() { mockDomainsAndRoutesUpdate(); - given(domains.list()).willReturn(Flux.fromStream(IntStream.range(1, 4) - .mapToObj(i -> Domain.builder().name("domain" + i).id("domain" + i + "-id").status(Status.OWNED).build()))); + given(this.domains.list()).willReturn(Flux.fromStream(IntStream.range(1, 4) + .mapToObj( + (i) -> Domain.builder().name("domain" + i).id("domain" + i + "-id").status(Status.OWNED).build()))); Map properties = new HashMap<>(); properties.put("host", "foo"); @@ -525,13 +494,13 @@ class CloudFoundryAppDeployerUpdateApplicationTest { .properties(properties) .build(); - StepVerifier.create( - appDeployer.update(request)) - .assertNext(response -> assertThat(response.getName()).isEqualTo(APP_NAME)) - .verifyComplete(); + StepVerifier.create(this.appDeployer.update(request)) + .assertNext((response) -> assertThat(response.getName()).isEqualTo(APP_NAME)) + .verifyComplete(); - ArgumentCaptor createRouteRequestArgumentCaptor = ArgumentCaptor.forClass(CreateRouteRequest.class); - then(routes).should(times(3)).create(createRouteRequestArgumentCaptor.capture()); + ArgumentCaptor createRouteRequestArgumentCaptor = ArgumentCaptor + .forClass(CreateRouteRequest.class); + then(this.routes).should(times(3)).create(createRouteRequestArgumentCaptor.capture()); List routeRequests = createRouteRequestArgumentCaptor.getAllValues(); SoftAssertions softAssertions = new SoftAssertions(); @@ -548,23 +517,24 @@ class CloudFoundryAppDeployerUpdateApplicationTest { void updateAppWithRoutes() { mockDomainsAndRoutesUpdate(); - given(domains.list()).willReturn(Flux.fromStream(IntStream.range(1, 4) - .mapToObj(i -> Domain.builder().name("domain" + i).id("domain" + i + "-id").status(Status.OWNED).build()))); + given(this.domains.list()).willReturn(Flux.fromStream(IntStream.range(1, 4) + .mapToObj( + (i) -> Domain.builder().name("domain" + i).id("domain" + i + "-id").status(Status.OWNED).build()))); - Map properties = singletonMap("routes", "foo.domain1,bar.domain2"); + Map properties = Collections.singletonMap("routes", "foo.domain1,bar.domain2"); UpdateApplicationRequest request = UpdateApplicationRequest.builder() .name(APP_NAME) .properties(properties) .build(); - StepVerifier.create( - appDeployer.update(request)) - .assertNext(response -> assertThat(response.getName()).isEqualTo(APP_NAME)) - .verifyComplete(); + StepVerifier.create(this.appDeployer.update(request)) + .assertNext((response) -> assertThat(response.getName()).isEqualTo(APP_NAME)) + .verifyComplete(); - ArgumentCaptor createRouteRequestArgumentCaptor = ArgumentCaptor.forClass(CreateRouteRequest.class); - then(routes).should(times(2)).create(createRouteRequestArgumentCaptor.capture()); + ArgumentCaptor createRouteRequestArgumentCaptor = ArgumentCaptor + .forClass(CreateRouteRequest.class); + then(this.routes).should(times(2)).create(createRouteRequestArgumentCaptor.capture()); List routeRequests = createRouteRequestArgumentCaptor.getAllValues(); SoftAssertions softAssertions = new SoftAssertions(); @@ -590,8 +560,8 @@ class CloudFoundryAppDeployerUpdateApplicationTest { .properties(properties) .build(); - StepVerifier.create(appDeployer.update(request)) - .assertNext(response -> assertThat(response.getName()).isEqualTo(APP_NAME)) + StepVerifier.create(this.appDeployer.update(request)) + .assertNext((response) -> assertThat(response.getName()).isEqualTo(APP_NAME)) .verifyComplete(); verifyRouteCreatedAndMapped("myDomainComId", "my.host", "space-id", APP_ID); @@ -613,8 +583,8 @@ class CloudFoundryAppDeployerUpdateApplicationTest { .properties(properties) .build(); - StepVerifier.create(appDeployer.update(request)) - .assertNext(response -> assertThat(response.getName()).isEqualTo(APP_NAME)) + StepVerifier.create(this.appDeployer.update(request)) + .assertNext((response) -> assertThat(response.getName()).isEqualTo(APP_NAME)) .verifyComplete(); verifyRouteCreatedAndMapped("myDomainInternalId", "my.host", "space-id", APP_ID); @@ -634,45 +604,34 @@ class CloudFoundryAppDeployerUpdateApplicationTest { .properties(properties) .build(); - StepVerifier.create(appDeployer.update(request)) - .assertNext(response -> assertThat(response.getName()).isEqualTo(APP_NAME)) + StepVerifier.create(this.appDeployer.update(request)) + .assertNext((response) -> assertThat(response.getName()).isEqualTo(APP_NAME)) .verifyComplete(); - then(routes).should().create(CreateRouteRequest.builder() - .domainId("myDomainDefaultId") - .spaceId("space-id") - .host("my.host") - .build()); - then(applicationsV2).should().associateRoute(AssociateApplicationRouteRequest.builder() - .applicationId(APP_ID) - .routeId("myDomainDefaultId-route") - .build()); + then(this.routes).should() + .create(CreateRouteRequest.builder() + .domainId("myDomainDefaultId") + .spaceId("space-id") + .host("my.host") + .build()); + then(this.applicationsV2).should() + .associateRoute(AssociateApplicationRouteRequest.builder() + .applicationId(APP_ID) + .routeId("myDomainDefaultId-route") + .build()); } @Test void updateAppWithDomainAndNoHost() { - given(applicationsV2.update(any())) - .willReturn(Mono.just( - UpdateApplicationResponse.builder().build())); + given(this.applicationsV2.update(any())).willReturn(Mono.just(UpdateApplicationResponse.builder().build())); - given(domains.list()) - .willReturn(getDomains()); + given(this.domains.list()).willReturn(getDomains()); - given(spaces.get(any())) - .willReturn(Mono.just(SpaceDetail.builder() - .id("space-id") - .name("space-name") - .organization("org-name") - .build())); - given(routes.create(any())) - .willReturn(Mono.just(CreateRouteResponse.builder() - .metadata(Metadata - .builder() - .id("route-id") - .build()) - .build())); - given(applicationsV2.associateRoute(any())) - .willReturn(Mono.empty()); + given(this.spaces.get(any())).willReturn( + Mono.just(SpaceDetail.builder().id("space-id").name("space-name").organization("org-name").build())); + given(this.routes.create(any())).willReturn( + Mono.just(CreateRouteResponse.builder().metadata(Metadata.builder().id("route-id").build()).build())); + given(this.applicationsV2.associateRoute(any())).willReturn(Mono.empty()); Map properties = new HashMap<>(); properties.put("domain", "my.domain.com"); @@ -683,82 +642,55 @@ class CloudFoundryAppDeployerUpdateApplicationTest { .properties(properties) .build(); - StepVerifier.create(appDeployer.update(request)) - .assertNext(response -> assertThat(response.getName()).isEqualTo(APP_NAME)) + StepVerifier.create(this.appDeployer.update(request)) + .assertNext((response) -> assertThat(response.getName()).isEqualTo(APP_NAME)) .verifyComplete(); - - then(routes).should().create(CreateRouteRequest.builder() - .domainId("myDomainComId") - .spaceId("space-id") - .host(null) - .build()); - then(applicationsV2).should().associateRoute(AssociateApplicationRouteRequest - .builder() - .applicationId(APP_ID) - .routeId("route-id") - .build()); + then(this.routes).should() + .create(CreateRouteRequest.builder().domainId("myDomainComId").spaceId("space-id").host(null).build()); + then(this.applicationsV2).should() + .associateRoute( + AssociateApplicationRouteRequest.builder().applicationId(APP_ID).routeId("route-id").build()); } @Test void updateAppWithNotExistingDomain() { - given(applicationsV2.update(any())) - .willReturn(Mono.just(UpdateApplicationResponse.builder() - .build())); + given(this.applicationsV2.update(any())).willReturn(Mono.just(UpdateApplicationResponse.builder().build())); - given(domains.list()) - .willReturn(getDomains()); + given(this.domains.list()).willReturn(getDomains()); - given(spaces.get(any())) - .willReturn(Mono.just(SpaceDetail.builder() - .id("space-id") - .name("space-name") - .organization("org-name") - .build())); + given(this.spaces.get(any())).willReturn( + Mono.just(SpaceDetail.builder().id("space-id").name("space-name").organization("org-name").build())); Map properties = new HashMap<>(); properties.put("host", "my.host"); properties.put("domain", "non.existing.domain.com"); - UpdateApplicationRequest request = - UpdateApplicationRequest - .builder() - .name(APP_NAME) - .path(APP_PATH) - .properties(properties) - .build(); + UpdateApplicationRequest request = UpdateApplicationRequest.builder() + .name(APP_NAME) + .path(APP_PATH) + .properties(properties) + .build(); - StepVerifier.create(appDeployer.update(request)) - .expectError(RuntimeException.class) - .verify(); + StepVerifier.create(this.appDeployer.update(request)).expectError(RuntimeException.class).verify(); - then(routes).shouldHaveNoInteractions(); + then(this.routes).shouldHaveNoInteractions(); } private Flux getDomains() { return Flux.just( - Domain.builder() - .id("myDomainInternalId") - .name("my.domain.internal.com") - .status(Status.SHARED) - .type("internal") - .build(), - Domain.builder() - .id("myDomainDefaultId") - .name("my.domain.default.com") - .status(Status.SHARED) - .build(), - Domain.builder() - .id("myDomainComId") - .name("my.domain.com") - .status(Status.OWNED) - .build() - ); + Domain.builder() + .id("myDomainInternalId") + .name("my.domain.internal.com") + .status(Status.SHARED) + .type("internal") + .build(), + Domain.builder().id("myDomainDefaultId").name("my.domain.default.com").status(Status.SHARED).build(), + Domain.builder().id("myDomainComId").name("my.domain.com").status(Status.OWNED).build()); } private ApplicationDetail createApplicationDetail() { - return ApplicationDetail - .builder() + return ApplicationDetail.builder() .id(APP_ID) .stack("") .diskQuota(512) @@ -771,8 +703,7 @@ class CloudFoundryAppDeployerUpdateApplicationTest { } private PackageResource createPackage(String dateTime, String id) { - return PackageResource - .builder() + return PackageResource.builder() .data(BitsData.builder().build()) .state(PackageState.READY) .type(PackageType.BITS) @@ -783,16 +714,14 @@ class CloudFoundryAppDeployerUpdateApplicationTest { } private void verifyRouteCreatedAndMapped(String domainId, String host, String spaceId, String appId) { - then(routes).should().create(CreateRouteRequest.builder() - .domainId(domainId) - .spaceId(spaceId) - .host(host) - .build()); + then(this.routes).should() + .create(CreateRouteRequest.builder().domainId(domainId).spaceId(spaceId).host(host).build()); - then(applicationsV2).should().associateRoute(AssociateApplicationRouteRequest.builder() - .applicationId(appId) - .routeId(getRouteIdForDomain(domainId)) - .build()); + then(this.applicationsV2).should() + .associateRoute(AssociateApplicationRouteRequest.builder() + .applicationId(appId) + .routeId(getRouteIdForDomain(domainId)) + .build()); } private String getRouteIdForDomain(String domainId) { @@ -800,27 +729,17 @@ class CloudFoundryAppDeployerUpdateApplicationTest { } private void mockDomainsAndRoutesUpdate() { - given(applicationsV2.update(any())) - .willReturn(Mono.just(UpdateApplicationResponse.builder() - .build())); - given(spaces.get(any())).willReturn( - Mono.just( - SpaceDetail.builder() - .id("space-id") - .name("space-name") - .organization("org-name") - .build())); - given(domains.list()).willReturn(getDomains()); - given(routes.create(any())).willAnswer(invocation -> { + given(this.applicationsV2.update(any())).willReturn(Mono.just(UpdateApplicationResponse.builder().build())); + given(this.spaces.get(any())).willReturn( + Mono.just(SpaceDetail.builder().id("space-id").name("space-name").organization("org-name").build())); + given(this.domains.list()).willReturn(getDomains()); + given(this.routes.create(any())).willAnswer((invocation) -> { CreateRouteRequest createRouteRequest = invocation.getArgument(0); return Mono.just(CreateRouteResponse.builder() - .metadata(Metadata - .builder() - .id(getRouteIdForDomain(createRouteRequest.getDomainId())) - .build()).build()); + .metadata(Metadata.builder().id(getRouteIdForDomain(createRouteRequest.getDomainId())).build()) + .build()); }); - given(applicationsV2.associateRoute(any())) - .willReturn(Mono.empty()); + given(this.applicationsV2.associateRoute(any())).willReturn(Mono.empty()); } private static Lifecycle createLifecycle() { diff --git a/spring-cloud-app-broker-deployer-cloudfoundry/src/test/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryAppManagerTest.java b/spring-cloud-app-broker-deployer-cloudfoundry/src/test/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryAppManagerTest.java deleted file mode 100644 index 0fa1010..0000000 --- a/spring-cloud-app-broker-deployer-cloudfoundry/src/test/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryAppManagerTest.java +++ /dev/null @@ -1,230 +0,0 @@ -/* - * Copyright 2002-2020 the original author or authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cloud.appbroker.deployer.cloudfoundry; - -import org.cloudfoundry.operations.CloudFoundryOperations; -import org.cloudfoundry.operations.applications.Applications; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; -import reactor.core.publisher.Mono; -import reactor.test.StepVerifier; - -import org.springframework.cloud.appbroker.deployer.manager.RestageApplicationRequest; -import org.springframework.cloud.appbroker.deployer.manager.RestartApplicationRequest; -import org.springframework.cloud.appbroker.deployer.manager.StartApplicationRequest; -import org.springframework.cloud.appbroker.deployer.manager.StopApplicationRequest; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyMap; -import static org.mockito.ArgumentMatchers.argThat; -import static org.mockito.BDDMockito.given; -import static org.mockito.BDDMockito.then; - -@ExtendWith(MockitoExtension.class) -class CloudFoundryAppManagerTest { - - private CloudFoundryAppManager appManager; - - @Mock - private Applications operationsApplications; - - @Mock - private CloudFoundryOperations operations; - - @Mock - private CloudFoundryOperationsUtils operationsUtils; - - @BeforeEach - void setUp() { - this.appManager = new CloudFoundryAppManager(operationsUtils); - } - - @Test - void startNullApplication() { - StepVerifier.create(appManager.start(null)) - .verifyComplete(); - - then(operationsApplications).shouldHaveNoInteractions(); - then(operations).shouldHaveNoMoreInteractions(); - } - - @Test - void startApplication() { - setupStubs(); - - given(operationsApplications.start(any(org.cloudfoundry.operations.applications.StartApplicationRequest.class))) - .willReturn(Mono.empty()); - - StartApplicationRequest request = StartApplicationRequest.builder() - .name("my-foo-app") - .build(); - - StepVerifier.create(appManager.start(request)) - .verifyComplete(); - - then(operationsApplications).should().start(argThat(req -> "my-foo-app".equals(req.getName()))); - then(operations).shouldHaveNoMoreInteractions(); - } - - @Test - void startApplicationWithEmptyName() { - given(operationsUtils.getOperations(anyMap())).willReturn(Mono.just(operations)); - - StartApplicationRequest request = StartApplicationRequest.builder() - .build(); - - StepVerifier.create(appManager.start(request)) - .verifyComplete(); - - then(operationsApplications).shouldHaveNoInteractions(); - then(operations).shouldHaveNoMoreInteractions(); - } - - @Test - void stopNullApplication() { - StepVerifier.create(appManager.stop(null)) - .verifyComplete(); - - then(operationsApplications).shouldHaveNoInteractions(); - then(operations).shouldHaveNoMoreInteractions(); - } - - @Test - void stopApplication() { - setupStubs(); - - given(operationsApplications.stop(any(org.cloudfoundry.operations.applications.StopApplicationRequest.class))) - .willReturn(Mono.empty()); - - StopApplicationRequest request = StopApplicationRequest.builder() - .name("my-foo-app") - .build(); - - StepVerifier.create(appManager.stop(request)) - .verifyComplete(); - - then(operationsApplications).should().stop(argThat(req -> "my-foo-app".equals(req.getName()))); - then(operations).shouldHaveNoMoreInteractions(); - } - - @Test - void stopApplicationWithEmptyName() { - given(operationsUtils.getOperations(anyMap())).willReturn(Mono.just(operations)); - - StopApplicationRequest request = StopApplicationRequest.builder() - .build(); - - StepVerifier.create(appManager.stop(request)) - .verifyComplete(); - - then(operationsApplications).shouldHaveNoInteractions(); - then(operations).shouldHaveNoMoreInteractions(); - } - - @Test - void restartNullApplication() { - StepVerifier.create(appManager.restart(null)) - .verifyComplete(); - - then(operationsApplications).shouldHaveNoInteractions(); - then(operations).shouldHaveNoMoreInteractions(); - } - - @Test - void restartApplication() { - setupStubs(); - - given(operationsApplications - .restart(any(org.cloudfoundry.operations.applications.RestartApplicationRequest.class))) - .willReturn(Mono.empty()); - - RestartApplicationRequest request = RestartApplicationRequest.builder() - .name("my-foo-app") - .build(); - - StepVerifier.create(appManager.restart(request)) - .verifyComplete(); - - then(operationsApplications).should().restart(argThat(req -> "my-foo-app".equals(req.getName()))); - then(operations).shouldHaveNoMoreInteractions(); - } - - @Test - void restartApplicationWithEmptyName() { - given(operationsUtils.getOperations(anyMap())).willReturn(Mono.just(operations)); - - RestartApplicationRequest request = RestartApplicationRequest.builder() - .build(); - - StepVerifier.create(appManager.restart(request)) - .verifyComplete(); - - then(operationsApplications).shouldHaveNoInteractions(); - then(operations).shouldHaveNoMoreInteractions(); - } - - @Test - void restageNullApplication() { - StepVerifier.create(appManager.restage(null)) - .verifyComplete(); - - then(operationsApplications).shouldHaveNoInteractions(); - then(operations).shouldHaveNoMoreInteractions(); - } - - @Test - void restageApplication() { - setupStubs(); - - given(operationsApplications - .restage(any(org.cloudfoundry.operations.applications.RestageApplicationRequest.class))) - .willReturn(Mono.empty()); - - RestageApplicationRequest request = RestageApplicationRequest.builder() - .name("my-foo-app") - .build(); - - StepVerifier.create(appManager.restage(request)) - .verifyComplete(); - - then(operationsApplications).should().restage(argThat(req -> "my-foo-app".equals(req.getName()))); - then(operations).shouldHaveNoMoreInteractions(); - } - - @Test - void restageApplicationWithEmptyName() { - given(operationsUtils.getOperations(anyMap())).willReturn(Mono.just(operations)); - - RestageApplicationRequest request = RestageApplicationRequest.builder() - .build(); - - StepVerifier.create(appManager.restage(request)) - .verifyComplete(); - - then(operationsApplications).shouldHaveNoInteractions(); - then(operations).shouldHaveNoMoreInteractions(); - } - - private void setupStubs() { - given(operations.applications()).willReturn(operationsApplications); - given(operationsUtils.getOperations(anyMap())).willReturn(Mono.just(operations)); - } - -} diff --git a/spring-cloud-app-broker-deployer-cloudfoundry/src/test/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryAppManagerTests.java b/spring-cloud-app-broker-deployer-cloudfoundry/src/test/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryAppManagerTests.java new file mode 100644 index 0000000..af53a70 --- /dev/null +++ b/spring-cloud-app-broker-deployer-cloudfoundry/src/test/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryAppManagerTests.java @@ -0,0 +1,207 @@ +/* + * Copyright 2002-2020 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.cloud.appbroker.deployer.cloudfoundry; + +import org.cloudfoundry.operations.CloudFoundryOperations; +import org.cloudfoundry.operations.applications.Applications; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +import org.springframework.cloud.appbroker.deployer.manager.RestageApplicationRequest; +import org.springframework.cloud.appbroker.deployer.manager.RestartApplicationRequest; +import org.springframework.cloud.appbroker.deployer.manager.StartApplicationRequest; +import org.springframework.cloud.appbroker.deployer.manager.StopApplicationRequest; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.BDDMockito.given; +import static org.mockito.BDDMockito.then; + +@ExtendWith(MockitoExtension.class) +class CloudFoundryAppManagerTests { + + private CloudFoundryAppManager appManager; + + @Mock + private Applications operationsApplications; + + @Mock + private CloudFoundryOperations operations; + + @Mock + private CloudFoundryOperationsUtils operationsUtils; + + @BeforeEach + void setUp() { + this.appManager = new CloudFoundryAppManager(this.operationsUtils); + } + + @Test + void startNullApplication() { + StepVerifier.create(this.appManager.start(null)).verifyComplete(); + + then(this.operationsApplications).shouldHaveNoInteractions(); + then(this.operations).shouldHaveNoMoreInteractions(); + } + + @Test + void startApplication() { + setupStubs(); + + given(this.operationsApplications + .start(any(org.cloudfoundry.operations.applications.StartApplicationRequest.class))) + .willReturn(Mono.empty()); + + StartApplicationRequest request = StartApplicationRequest.builder().name("my-foo-app").build(); + + StepVerifier.create(this.appManager.start(request)).verifyComplete(); + + then(this.operationsApplications).should().start(argThat((req) -> "my-foo-app".equals(req.getName()))); + then(this.operations).shouldHaveNoMoreInteractions(); + } + + @Test + void startApplicationWithEmptyName() { + given(this.operationsUtils.getOperations(anyMap())).willReturn(Mono.just(this.operations)); + + StartApplicationRequest request = StartApplicationRequest.builder().build(); + + StepVerifier.create(this.appManager.start(request)).verifyComplete(); + + then(this.operationsApplications).shouldHaveNoInteractions(); + then(this.operations).shouldHaveNoMoreInteractions(); + } + + @Test + void stopNullApplication() { + StepVerifier.create(this.appManager.stop(null)).verifyComplete(); + + then(this.operationsApplications).shouldHaveNoInteractions(); + then(this.operations).shouldHaveNoMoreInteractions(); + } + + @Test + void stopApplication() { + setupStubs(); + + given(this.operationsApplications + .stop(any(org.cloudfoundry.operations.applications.StopApplicationRequest.class))).willReturn(Mono.empty()); + + StopApplicationRequest request = StopApplicationRequest.builder().name("my-foo-app").build(); + + StepVerifier.create(this.appManager.stop(request)).verifyComplete(); + + then(this.operationsApplications).should().stop(argThat((req) -> "my-foo-app".equals(req.getName()))); + then(this.operations).shouldHaveNoMoreInteractions(); + } + + @Test + void stopApplicationWithEmptyName() { + given(this.operationsUtils.getOperations(anyMap())).willReturn(Mono.just(this.operations)); + + StopApplicationRequest request = StopApplicationRequest.builder().build(); + + StepVerifier.create(this.appManager.stop(request)).verifyComplete(); + + then(this.operationsApplications).shouldHaveNoInteractions(); + then(this.operations).shouldHaveNoMoreInteractions(); + } + + @Test + void restartNullApplication() { + StepVerifier.create(this.appManager.restart(null)).verifyComplete(); + + then(this.operationsApplications).shouldHaveNoInteractions(); + then(this.operations).shouldHaveNoMoreInteractions(); + } + + @Test + void restartApplication() { + setupStubs(); + + given(this.operationsApplications + .restart(any(org.cloudfoundry.operations.applications.RestartApplicationRequest.class))) + .willReturn(Mono.empty()); + + RestartApplicationRequest request = RestartApplicationRequest.builder().name("my-foo-app").build(); + + StepVerifier.create(this.appManager.restart(request)).verifyComplete(); + + then(this.operationsApplications).should().restart(argThat((req) -> "my-foo-app".equals(req.getName()))); + then(this.operations).shouldHaveNoMoreInteractions(); + } + + @Test + void restartApplicationWithEmptyName() { + given(this.operationsUtils.getOperations(anyMap())).willReturn(Mono.just(this.operations)); + + RestartApplicationRequest request = RestartApplicationRequest.builder().build(); + + StepVerifier.create(this.appManager.restart(request)).verifyComplete(); + + then(this.operationsApplications).shouldHaveNoInteractions(); + then(this.operations).shouldHaveNoMoreInteractions(); + } + + @Test + void restageNullApplication() { + StepVerifier.create(this.appManager.restage(null)).verifyComplete(); + + then(this.operationsApplications).shouldHaveNoInteractions(); + then(this.operations).shouldHaveNoMoreInteractions(); + } + + @Test + void restageApplication() { + setupStubs(); + + given(this.operationsApplications + .restage(any(org.cloudfoundry.operations.applications.RestageApplicationRequest.class))) + .willReturn(Mono.empty()); + + RestageApplicationRequest request = RestageApplicationRequest.builder().name("my-foo-app").build(); + + StepVerifier.create(this.appManager.restage(request)).verifyComplete(); + + then(this.operationsApplications).should().restage(argThat((req) -> "my-foo-app".equals(req.getName()))); + then(this.operations).shouldHaveNoMoreInteractions(); + } + + @Test + void restageApplicationWithEmptyName() { + given(this.operationsUtils.getOperations(anyMap())).willReturn(Mono.just(this.operations)); + + RestageApplicationRequest request = RestageApplicationRequest.builder().build(); + + StepVerifier.create(this.appManager.restage(request)).verifyComplete(); + + then(this.operationsApplications).shouldHaveNoInteractions(); + then(this.operations).shouldHaveNoMoreInteractions(); + } + + private void setupStubs() { + given(this.operations.applications()).willReturn(this.operationsApplications); + given(this.operationsUtils.getOperations(anyMap())).willReturn(Mono.just(this.operations)); + } + +} diff --git a/spring-cloud-app-broker-deployer-cloudfoundry/src/test/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryOAuth2ClientTest.java b/spring-cloud-app-broker-deployer-cloudfoundry/src/test/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryOAuth2ClientTests.java similarity index 73% rename from spring-cloud-app-broker-deployer-cloudfoundry/src/test/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryOAuth2ClientTest.java rename to spring-cloud-app-broker-deployer-cloudfoundry/src/test/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryOAuth2ClientTests.java index e80aa8c..a3fedd6 100644 --- a/spring-cloud-app-broker-deployer-cloudfoundry/src/test/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryOAuth2ClientTest.java +++ b/spring-cloud-app-broker-deployer-cloudfoundry/src/test/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryOAuth2ClientTests.java @@ -40,7 +40,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; @ExtendWith(MockitoExtension.class) -class CloudFoundryOAuth2ClientTest { +class CloudFoundryOAuth2ClientTests { @Mock private UaaClient uaaClient; @@ -52,9 +52,9 @@ class CloudFoundryOAuth2ClientTest { @BeforeEach void setUp() { - given(uaaClient.clients()).willReturn(clients); + given(this.uaaClient.clients()).willReturn(this.clients); - oAuth2Client = new CloudFoundryOAuth2Client(uaaClient); + this.oAuth2Client = new CloudFoundryOAuth2Client(this.uaaClient); } @Test @@ -65,8 +65,8 @@ class CloudFoundryOAuth2ClientTest { .name("test-name") .scopes("auth1", "auth2") .authorities("auth1", "auth2") - .authorizedGrantTypes(GrantType.CLIENT_CREDENTIALS, GrantType.AUTHORIZATION_CODE, - GrantType.PASSWORD, GrantType.IMPLICIT, GrantType.REFRESH_TOKEN) + .authorizedGrantTypes(GrantType.CLIENT_CREDENTIALS, GrantType.AUTHORIZATION_CODE, GrantType.PASSWORD, + GrantType.IMPLICIT, GrantType.REFRESH_TOKEN) .identityZoneSubdomain("subdomain") .identityZoneId("zoneId") .build(); @@ -76,12 +76,11 @@ class CloudFoundryOAuth2ClientTest { .name("test-name") .scopes("auth1", "auth2") .authorities("auth1", "auth2") - .authorizedGrantTypes(GrantType.CLIENT_CREDENTIALS, GrantType.AUTHORIZATION_CODE, - GrantType.PASSWORD, GrantType.IMPLICIT, GrantType.REFRESH_TOKEN) + .authorizedGrantTypes(GrantType.CLIENT_CREDENTIALS, GrantType.AUTHORIZATION_CODE, GrantType.PASSWORD, + GrantType.IMPLICIT, GrantType.REFRESH_TOKEN) .build(); - given(clients.create(clientsRequest)) - .willReturn(Mono.just(clientsResponse)); + given(this.clients.create(clientsRequest)).willReturn(Mono.just(clientsResponse)); CreateOAuth2ClientRequest request = CreateOAuth2ClientRequest.builder() .clientId("test-client") @@ -94,10 +93,9 @@ class CloudFoundryOAuth2ClientTest { .identityZoneId("zoneId") .build(); - StepVerifier.create(oAuth2Client.createClient(request)) - .assertNext(response -> assertResponse(response.getClientId(), response.getClientName(), - response.getScopes(), response.getAuthorities(), - response.getGrantTypes())) + StepVerifier.create(this.oAuth2Client.createClient(request)) + .assertNext((response) -> assertResponse(response.getClientId(), response.getClientName(), + response.getScopes(), response.getAuthorities(), response.getGrantTypes())) .verifyComplete(); } @@ -114,12 +112,11 @@ class CloudFoundryOAuth2ClientTest { .name("test-name") .scopes("auth1", "auth2") .authorities("auth1", "auth2") - .authorizedGrantTypes(GrantType.CLIENT_CREDENTIALS, GrantType.AUTHORIZATION_CODE, - GrantType.PASSWORD, GrantType.IMPLICIT, GrantType.REFRESH_TOKEN) + .authorizedGrantTypes(GrantType.CLIENT_CREDENTIALS, GrantType.AUTHORIZATION_CODE, GrantType.PASSWORD, + GrantType.IMPLICIT, GrantType.REFRESH_TOKEN) .build(); - given(clients.delete(clientsRequest)) - .willReturn(Mono.just(clientsResponse)); + given(this.clients.delete(clientsRequest)).willReturn(Mono.just(clientsResponse)); DeleteOAuth2ClientRequest request = DeleteOAuth2ClientRequest.builder() .clientId("test-client") @@ -127,22 +124,20 @@ class CloudFoundryOAuth2ClientTest { .identityZoneId("zoneId") .build(); - StepVerifier.create(oAuth2Client.deleteClient(request)) - .assertNext(response -> assertResponse(response.getClientId(), response.getClientName(), - response.getScopes(), response.getAuthorities(), - response.getGrantTypes())) + StepVerifier.create(this.oAuth2Client.deleteClient(request)) + .assertNext((response) -> assertResponse(response.getClientId(), response.getClientName(), + response.getScopes(), response.getAuthorities(), response.getGrantTypes())) .verifyComplete(); } - private void assertResponse(String clientId, String name, - List scopes, List authorities, - List authorizedGrantTypes) { + private void assertResponse(String clientId, String name, List scopes, List authorities, + List authorizedGrantTypes) { assertThat(clientId).isEqualTo("test-client"); assertThat(name).isEqualTo("test-name"); assertThat(scopes).contains("auth1", "auth2"); assertThat(authorities).contains("auth1", "auth2"); - assertThat(authorizedGrantTypes).contains( - "client_credentials", "authorization_code", "password", "implicit", "refresh_token"); + assertThat(authorizedGrantTypes).contains("client_credentials", "authorization_code", "password", "implicit", + "refresh_token"); } } diff --git a/spring-cloud-app-broker-deployer-cloudfoundry/src/test/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryOperationsUtilsTest.java b/spring-cloud-app-broker-deployer-cloudfoundry/src/test/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryOperationsUtilsTests.java similarity index 67% rename from spring-cloud-app-broker-deployer-cloudfoundry/src/test/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryOperationsUtilsTest.java rename to spring-cloud-app-broker-deployer-cloudfoundry/src/test/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryOperationsUtilsTests.java index 0bbda2d..b04c66e 100644 --- a/spring-cloud-app-broker-deployer-cloudfoundry/src/test/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryOperationsUtilsTest.java +++ b/spring-cloud-app-broker-deployer-cloudfoundry/src/test/java/org/springframework/cloud/appbroker/deployer/cloudfoundry/CloudFoundryOperationsUtilsTests.java @@ -1,11 +1,11 @@ /* - * Copyright 2002-2020 the original author or authors + * Copyright 2002-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * https://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -29,7 +29,7 @@ import org.springframework.test.util.ReflectionTestUtils; import static org.assertj.core.api.Assertions.assertThat; -class CloudFoundryOperationsUtilsTest { +class CloudFoundryOperationsUtilsTests { private CloudFoundryOperationsUtils operationsUtils; @@ -38,21 +38,22 @@ class CloudFoundryOperationsUtilsTest { @BeforeEach void setUp() { this.operations = DefaultCloudFoundryOperations.builder().build(); - this.operationsUtils = new CloudFoundryOperationsUtils(operations); + this.operationsUtils = new CloudFoundryOperationsUtils(this.operations); } @Test void getOperationsWithEmptyProperties() { - StepVerifier.create(operationsUtils.getOperations(Collections.emptyMap())) - .expectNext(operations) + StepVerifier.create(this.operationsUtils.getOperations(Collections.emptyMap())) + .expectNext(this.operations) .verifyComplete(); } @Test void getOperationsWithProperties() { - StepVerifier.create(operationsUtils - .getOperations(Collections.singletonMap(DeploymentProperties.TARGET_PROPERTY_KEY, "foo-space1"))) - .assertNext(ops -> { + StepVerifier + .create(this.operationsUtils + .getOperations(Collections.singletonMap(DeploymentProperties.TARGET_PROPERTY_KEY, "foo-space1"))) + .assertNext((ops) -> { String space = (String) ReflectionTestUtils.getField(ops, "space"); assertThat(space).isEqualTo("foo-space1"); }) @@ -61,12 +62,10 @@ class CloudFoundryOperationsUtilsTest { @Test void getOperationsForSpace() { - StepVerifier.create(operationsUtils.getOperationsForSpace("foo-space2")) - .assertNext(ops -> { - String space = (String) ReflectionTestUtils.getField(ops, "space"); - assertThat(space).isEqualTo("foo-space2"); - }) - .verifyComplete(); + StepVerifier.create(this.operationsUtils.getOperationsForSpace("foo-space2")).assertNext((ops) -> { + String space = (String) ReflectionTestUtils.getField(ops, "space"); + assertThat(space).isEqualTo("foo-space2"); + }).verifyComplete(); } } diff --git a/spring-cloud-app-broker-deployer/build.gradle b/spring-cloud-app-broker-deployer/build.gradle index 3dc72fb..31195e2 100644 --- a/spring-cloud-app-broker-deployer/build.gradle +++ b/spring-cloud-app-broker-deployer/build.gradle @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/CreateServiceInstanceRequest.java b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/CreateServiceInstanceRequest.java index a5611ca..358b27f 100644 --- a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/CreateServiceInstanceRequest.java +++ b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/CreateServiceInstanceRequest.java @@ -33,11 +33,8 @@ public class CreateServiceInstanceRequest { private final Map properties; - protected CreateServiceInstanceRequest(String serviceInstanceName, - String name, - String plan, - Map parameters, - Map properties) { + protected CreateServiceInstanceRequest(String serviceInstanceName, String name, String plan, + Map parameters, Map properties) { this.serviceInstanceName = serviceInstanceName; this.name = name; this.plan = plan; @@ -50,23 +47,23 @@ public class CreateServiceInstanceRequest { } public String getServiceInstanceName() { - return serviceInstanceName; + return this.serviceInstanceName; } public String getName() { - return name; + return this.name; } public String getPlan() { - return plan; + return this.plan; } public Map getParameters() { - return parameters; + return this.parameters; } public Map getProperties() { - return properties; + return this.properties; } public static final class CreateServiceInstanceRequestBuilder { @@ -121,7 +118,8 @@ public class CreateServiceInstanceRequest { } public CreateServiceInstanceRequest build() { - return new CreateServiceInstanceRequest(serviceInstanceName, name, plan, parameters, properties); + return new CreateServiceInstanceRequest(this.serviceInstanceName, this.name, this.plan, this.parameters, + this.properties); } } diff --git a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/CreateServiceInstanceResponse.java b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/CreateServiceInstanceResponse.java index 8eeedbc..f6ac2cb 100644 --- a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/CreateServiceInstanceResponse.java +++ b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/CreateServiceInstanceResponse.java @@ -29,7 +29,7 @@ public class CreateServiceInstanceResponse { } public String getName() { - return name; + return this.name; } public static final class CreateServiceInstanceResponseBuilder { @@ -45,7 +45,7 @@ public class CreateServiceInstanceResponse { } public CreateServiceInstanceResponse build() { - return new CreateServiceInstanceResponse(name); + return new CreateServiceInstanceResponse(this.name); } } diff --git a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/DeleteBackingSpaceRequest.java b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/DeleteBackingSpaceRequest.java index 845f476..add935d 100644 --- a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/DeleteBackingSpaceRequest.java +++ b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/DeleteBackingSpaceRequest.java @@ -29,7 +29,7 @@ public class DeleteBackingSpaceRequest { } public String getName() { - return name; + return this.name; } public static final class DeleteBackingSpaceRequestBuilder { @@ -45,7 +45,7 @@ public class DeleteBackingSpaceRequest { } public DeleteBackingSpaceRequest build() { - return new DeleteBackingSpaceRequest(name); + return new DeleteBackingSpaceRequest(this.name); } } diff --git a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/DeleteBackingSpaceResponse.java b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/DeleteBackingSpaceResponse.java index e610a6c..9064143 100644 --- a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/DeleteBackingSpaceResponse.java +++ b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/DeleteBackingSpaceResponse.java @@ -29,7 +29,7 @@ public class DeleteBackingSpaceResponse { } public String getName() { - return name; + return this.name; } public static final class DeleteBackingSpaceResponseBuilder { @@ -45,7 +45,7 @@ public class DeleteBackingSpaceResponse { } public DeleteBackingSpaceResponse build() { - return new DeleteBackingSpaceResponse(name); + return new DeleteBackingSpaceResponse(this.name); } } diff --git a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/DeleteServiceInstanceRequest.java b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/DeleteServiceInstanceRequest.java index 8bbb816..4e7f2df 100644 --- a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/DeleteServiceInstanceRequest.java +++ b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/DeleteServiceInstanceRequest.java @@ -37,11 +37,11 @@ public class DeleteServiceInstanceRequest { } public String getServiceInstanceName() { - return serviceInstanceName; + return this.serviceInstanceName; } public Map getProperties() { - return properties; + return this.properties; } public static final class DeleteServiceInstanceRequestBuilder { @@ -66,7 +66,7 @@ public class DeleteServiceInstanceRequest { } public DeleteServiceInstanceRequest build() { - return new DeleteServiceInstanceRequest(serviceInstanceName, properties); + return new DeleteServiceInstanceRequest(this.serviceInstanceName, this.properties); } } diff --git a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/DeleteServiceInstanceResponse.java b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/DeleteServiceInstanceResponse.java index 385e5b3..2bf3dc7 100644 --- a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/DeleteServiceInstanceResponse.java +++ b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/DeleteServiceInstanceResponse.java @@ -29,7 +29,7 @@ public class DeleteServiceInstanceResponse { } public String getName() { - return name; + return this.name; } public static final class DeleteServiceInstanceResponseBuilder { @@ -45,7 +45,7 @@ public class DeleteServiceInstanceResponse { } public DeleteServiceInstanceResponse build() { - return new DeleteServiceInstanceResponse(name); + return new DeleteServiceInstanceResponse(this.name); } } diff --git a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/DeployApplicationRequest.java b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/DeployApplicationRequest.java index a5f5b73..51621d8 100644 --- a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/DeployApplicationRequest.java +++ b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/DeployApplicationRequest.java @@ -38,8 +38,7 @@ public class DeployApplicationRequest { private final String serviceInstanceId; protected DeployApplicationRequest(String name, String path, Map properties, - Map environment, List services, - String serviceInstanceId) { + Map environment, List services, String serviceInstanceId) { this.name = name; this.path = path; this.properties = properties; @@ -49,27 +48,27 @@ public class DeployApplicationRequest { } public String getName() { - return name; + return this.name; } public String getPath() { - return path; + return this.path; } public Map getProperties() { - return properties; + return this.properties; } public Map getEnvironment() { - return environment; + return this.environment; } public List getServices() { - return services; + return this.services; } public String getServiceInstanceId() { - return serviceInstanceId; + return this.serviceInstanceId; } public static DeployApplicationRequestBuilder builder() { @@ -151,7 +150,8 @@ public class DeployApplicationRequest { } public DeployApplicationRequest build() { - return new DeployApplicationRequest(name, path, properties, environment, services, serviceInstanceId); + return new DeployApplicationRequest(this.name, this.path, this.properties, this.environment, this.services, + this.serviceInstanceId); } } diff --git a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/DeployApplicationResponse.java b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/DeployApplicationResponse.java index e585d88..6792c46 100644 --- a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/DeployApplicationResponse.java +++ b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/DeployApplicationResponse.java @@ -29,7 +29,7 @@ public class DeployApplicationResponse { } public String getName() { - return name; + return this.name; } public static final class DeployApplicationResponseBuilder { @@ -45,7 +45,7 @@ public class DeployApplicationResponse { } public DeployApplicationResponse build() { - return new DeployApplicationResponse(name); + return new DeployApplicationResponse(this.name); } } diff --git a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/DeploymentProperties.java b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/DeploymentProperties.java index 93aa79a..561993f 100644 --- a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/DeploymentProperties.java +++ b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/DeploymentProperties.java @@ -19,30 +19,38 @@ package org.springframework.cloud.appbroker.deployer.deployer; public class DeploymentProperties { /** - * The deployment property for the count (number of app instances). If not provided, a deployer should assume 1 - * instance. + * The deployment property for the count (number of app instances). If not provided, a + * deployer should assume 1 instance. */ public static final String COUNT_PROPERTY_KEY = "count"; /** - * The deployment property for the memory setting for the container that will run the app. The memory is specified - * in Mebibytes, by default, with optional case-insensitive - * trailing unit 'm' and 'g' being supported, for mebi- and giga- respectively. + * The deployment property for the memory setting for the container that will run the + * app. The memory is specified in + * Mebibytes, by default, with + * optional case-insensitive trailing unit 'm' and 'g' being supported, for mebi- and + * giga- respectively. *

- * 1 MiB = 2^20 bytes = 1024*1024 bytes vs. the decimal based 1MB = 10^6 bytes = 1000*1000 bytes, + * 1 MiB = 2^20 bytes = 1024*1024 bytes vs. the decimal based 1MB = 10^6 bytes = + * 1000*1000 bytes, *

- * Implementations are expected to translate this value to the target platform as faithfully as possible. + * Implementations are expected to translate this value to the target platform as + * faithfully as possible. */ public static final String MEMORY_PROPERTY_KEY = "memory"; /** - * The deployment property for the disk setting for the container that will run the app. The memory is specified in - * Mebibytes, by default, with optional case-insensitive - * trailing unit 'm' and 'g' being supported, for mebi- and giga- respectively. + * The deployment property for the disk setting for the container that will run the + * app. The memory is specified in + * Mebibytes, by default, with + * optional case-insensitive trailing unit 'm' and 'g' being supported, for mebi- and + * giga- respectively. *

- * 1 MiB = 2^20 bytes = 1024*1024 bytes vs. the decimal based 1MB = 10^6 bytes = 1000*1000 bytes, + * 1 MiB = 2^20 bytes = 1024*1024 bytes vs. the decimal based 1MB = 10^6 bytes = + * 1000*1000 bytes, *

- * Implementations are expected to translate this value to the target platform as faithfully as possible. + * Implementations are expected to translate this value to the target platform as + * faithfully as possible. */ public static final String DISK_PROPERTY_KEY = "disk"; @@ -52,20 +60,20 @@ public class DeploymentProperties { public static final String HOST_PROPERTY_KEY = "host"; /** - * The deployment property for the location where the app will be deployed. The location will vary between - * implementations. + * The deployment property for the location where the app will be deployed. The + * location will vary between implementations. */ public static final String TARGET_PROPERTY_KEY = "target"; /** - * The deployment property indicating whether the application should be automatically started after deployment. - * Defaults to true. + * The deployment property indicating whether the application should be automatically + * started after deployment. Defaults to true. */ public static final String START_PROPERTY_KEY = "start"; /** - * The deployment property indicating whether the application should use the {@literal SPRING_APPLICATION_JSON} - * environment variable + * The deployment property indicating whether the application should use the + * {@literal SPRING_APPLICATION_JSON} environment variable. */ public static final String USE_SPRING_APPLICATION_JSON_KEY = "use-spring-application-json"; @@ -80,7 +88,7 @@ public class DeploymentProperties { private boolean useSpringApplicationJson = true; public String getMemory() { - return memory; + return this.memory; } public void setMemory(String memory) { @@ -88,7 +96,7 @@ public class DeploymentProperties { } public String getDisk() { - return disk; + return this.disk; } public void setDisk(String disk) { @@ -96,7 +104,7 @@ public class DeploymentProperties { } public Integer getCount() { - return count; + return this.count; } public void setCount(int count) { @@ -104,7 +112,7 @@ public class DeploymentProperties { } public String getHost() { - return host; + return this.host; } public void setHost(String host) { @@ -112,7 +120,7 @@ public class DeploymentProperties { } public boolean isUseSpringApplicationJson() { - return useSpringApplicationJson; + return this.useSpringApplicationJson; } public void setUseSpringApplicationJson(boolean useSpringApplicationJson) { diff --git a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/GetApplicationRequest.java b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/GetApplicationRequest.java index fa0e1cb..e16ad79 100644 --- a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/GetApplicationRequest.java +++ b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/GetApplicationRequest.java @@ -1,11 +1,11 @@ /* - * Copyright 2002-2020 the original author or authors + * Copyright 2002-2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * https://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -37,11 +37,11 @@ public class GetApplicationRequest { } public String getName() { - return name; + return this.name; } public Map getProperties() { - return properties; + return this.properties; } public static final class GetDeployedAppRequestBuilder { @@ -66,7 +66,7 @@ public class GetApplicationRequest { } public GetApplicationRequest build() { - return new GetApplicationRequest(name, properties); + return new GetApplicationRequest(this.name, this.properties); } } diff --git a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/GetApplicationResponse.java b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/GetApplicationResponse.java index 804c58e..c4a3f95 100644 --- a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/GetApplicationResponse.java +++ b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/GetApplicationResponse.java @@ -1,11 +1,11 @@ /* - * Copyright 2002-2020 the original author or authors + * Copyright 2002-2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * https://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -41,19 +41,19 @@ public class GetApplicationResponse { } public String getId() { - return id; + return this.id; } public String getName() { - return name; + return this.name; } public Map getEnvironment() { - return environment; + return this.environment; } public List getServices() { - return services; + return this.services; } public static GetApplicationResponseBuilder builder() { @@ -112,7 +112,7 @@ public class GetApplicationResponse { } public GetApplicationResponse build() { - return new GetApplicationResponse(id, name, environment, services); + return new GetApplicationResponse(this.id, this.name, this.environment, this.services); } } diff --git a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/GetServiceInstanceRequest.java b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/GetServiceInstanceRequest.java index b7345a2..6cce2a4 100644 --- a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/GetServiceInstanceRequest.java +++ b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/GetServiceInstanceRequest.java @@ -1,11 +1,11 @@ /* - * Copyright 2002-2020 the original author or authors + * Copyright 2002-2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * https://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -40,15 +40,15 @@ public class GetServiceInstanceRequest { } public String getName() { - return name; + return this.name; } public String getServiceInstanceId() { - return serviceInstanceId; + return this.serviceInstanceId; } public Map getProperties() { - return properties; + return this.properties; } public static final class GetServiceInstanceRequestBuilder { @@ -80,7 +80,7 @@ public class GetServiceInstanceRequest { } public GetServiceInstanceRequest build() { - return new GetServiceInstanceRequest(name, serviceInstanceId, properties); + return new GetServiceInstanceRequest(this.name, this.serviceInstanceId, this.properties); } } diff --git a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/GetServiceInstanceResponse.java b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/GetServiceInstanceResponse.java index e768909..058818d 100644 --- a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/GetServiceInstanceResponse.java +++ b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/GetServiceInstanceResponse.java @@ -1,11 +1,11 @@ /* - * Copyright 2002-2020 the original author or authors + * Copyright 2002-2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * https://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -35,15 +35,15 @@ public class GetServiceInstanceResponse { } public String getName() { - return name; + return this.name; } public String getService() { - return service; + return this.service; } public String getPlan() { - return plan; + return this.plan; } public static final class CreateServiceInstanceRequestBuilder { @@ -73,7 +73,7 @@ public class GetServiceInstanceResponse { } public GetServiceInstanceResponse build() { - return new GetServiceInstanceResponse(name, service, plan); + return new GetServiceInstanceResponse(this.name, this.service, this.plan); } } diff --git a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/UndeployApplicationRequest.java b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/UndeployApplicationRequest.java index f2e0615..59f9f46 100644 --- a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/UndeployApplicationRequest.java +++ b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/UndeployApplicationRequest.java @@ -37,11 +37,11 @@ public class UndeployApplicationRequest { } public String getName() { - return name; + return this.name; } public Map getProperties() { - return properties; + return this.properties; } public static final class UndeployApplicationRequestBuilder { @@ -66,7 +66,7 @@ public class UndeployApplicationRequest { } public UndeployApplicationRequest build() { - return new UndeployApplicationRequest(name, properties); + return new UndeployApplicationRequest(this.name, this.properties); } } diff --git a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/UndeployApplicationResponse.java b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/UndeployApplicationResponse.java index 9de32af..b608a0d 100644 --- a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/UndeployApplicationResponse.java +++ b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/UndeployApplicationResponse.java @@ -45,7 +45,7 @@ public class UndeployApplicationResponse { } public UndeployApplicationResponse build() { - return new UndeployApplicationResponse(name); + return new UndeployApplicationResponse(this.name); } } diff --git a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/UpdateApplicationRequest.java b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/UpdateApplicationRequest.java index 758f5df..41465cf 100644 --- a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/UpdateApplicationRequest.java +++ b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/UpdateApplicationRequest.java @@ -38,8 +38,7 @@ public class UpdateApplicationRequest { private final String serviceInstanceId; protected UpdateApplicationRequest(String name, String path, Map properties, - Map environment, List services, - String serviceInstanceId) { + Map environment, List services, String serviceInstanceId) { this.name = name; this.path = path; this.properties = properties; @@ -49,27 +48,27 @@ public class UpdateApplicationRequest { } public String getName() { - return name; + return this.name; } public String getPath() { - return path; + return this.path; } public Map getProperties() { - return properties; + return this.properties; } public Map getEnvironment() { - return environment; + return this.environment; } public List getServices() { - return services; + return this.services; } public String getServiceInstanceId() { - return serviceInstanceId; + return this.serviceInstanceId; } public static UpdateApplicationRequestBuilder builder() { @@ -151,7 +150,8 @@ public class UpdateApplicationRequest { } public UpdateApplicationRequest build() { - return new UpdateApplicationRequest(name, path, properties, environment, services, serviceInstanceId); + return new UpdateApplicationRequest(this.name, this.path, this.properties, this.environment, this.services, + this.serviceInstanceId); } } diff --git a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/UpdateApplicationResponse.java b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/UpdateApplicationResponse.java index 9dc34d7..0c9dad8 100644 --- a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/UpdateApplicationResponse.java +++ b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/UpdateApplicationResponse.java @@ -29,7 +29,7 @@ public class UpdateApplicationResponse { } public String getName() { - return name; + return this.name; } public static final class DeployApplicationResponseBuilder { @@ -45,7 +45,7 @@ public class UpdateApplicationResponse { } public UpdateApplicationResponse build() { - return new UpdateApplicationResponse(name); + return new UpdateApplicationResponse(this.name); } } diff --git a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/UpdateServiceInstanceRequest.java b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/UpdateServiceInstanceRequest.java index 5153a16..70ecc72 100644 --- a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/UpdateServiceInstanceRequest.java +++ b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/UpdateServiceInstanceRequest.java @@ -31,10 +31,8 @@ public class UpdateServiceInstanceRequest { private final boolean rebindOnUpdate; - protected UpdateServiceInstanceRequest(String serviceInstanceName, - Map parameters, - Map properties, - boolean rebindOnUpdate) { + protected UpdateServiceInstanceRequest(String serviceInstanceName, Map parameters, + Map properties, boolean rebindOnUpdate) { this.serviceInstanceName = serviceInstanceName; this.parameters = parameters; this.properties = properties; @@ -46,19 +44,19 @@ public class UpdateServiceInstanceRequest { } public String getServiceInstanceName() { - return serviceInstanceName; + return this.serviceInstanceName; } public Map getParameters() { - return parameters; + return this.parameters; } public Map getProperties() { - return properties; + return this.properties; } public boolean isRebindOnUpdate() { - return rebindOnUpdate; + return this.rebindOnUpdate; } public static final class UpdateServiceInstanceRequestBuilder { @@ -106,7 +104,8 @@ public class UpdateServiceInstanceRequest { } public UpdateServiceInstanceRequest build() { - return new UpdateServiceInstanceRequest(serviceInstanceName, parameters, properties, rebindOnUpdate); + return new UpdateServiceInstanceRequest(this.serviceInstanceName, this.parameters, this.properties, + this.rebindOnUpdate); } } diff --git a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/UpdateServiceInstanceResponse.java b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/UpdateServiceInstanceResponse.java index 598b7b8..bd0f73d 100644 --- a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/UpdateServiceInstanceResponse.java +++ b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/UpdateServiceInstanceResponse.java @@ -29,7 +29,7 @@ public class UpdateServiceInstanceResponse { } public String getName() { - return name; + return this.name; } public static final class UpdateServiceInstanceResponseBuilder { @@ -45,7 +45,7 @@ public class UpdateServiceInstanceResponse { } public UpdateServiceInstanceResponse build() { - return new UpdateServiceInstanceResponse(name); + return new UpdateServiceInstanceResponse(this.name); } } diff --git a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/package-info.java b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/package-info.java new file mode 100644 index 0000000..9f593c7 --- /dev/null +++ b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/package-info.java @@ -0,0 +1,20 @@ +/* + * Copyright 2002-2024 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * AppBroker Deployer. + */ +package org.springframework.cloud.appbroker.deployer.deployer; diff --git a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/util/ByteSizeUtils.java b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/util/ByteSizeUtils.java index 8a3339d..829f4e2 100644 --- a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/util/ByteSizeUtils.java +++ b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/util/ByteSizeUtils.java @@ -28,15 +28,18 @@ import org.springframework.util.StringUtils; */ public final class ByteSizeUtils { - private static final Pattern SIZE_PATTERN = Pattern - .compile("(?\\d+)(?([mg])?)", Pattern.CASE_INSENSITIVE); + private static final Pattern SIZE_PATTERN = Pattern.compile("(?\\d+)(?([mg])?)", + Pattern.CASE_INSENSITIVE); private ByteSizeUtils() { } /** - * Return the number of mebibytes (1024*1024) denoted by the given text, where an optional case-insensitive unit of - * 'm' or 'g' can be used to mean mebi- or gebi- bytes, respectively. Lack of unit assumes mebibytes. + * Return the number of mebibytes (1024*1024) denoted by the given text, where an + * optional case-insensitive unit of 'm' or 'g' can be used to mean mebi- or gebi- + * bytes, respectively. Lack of unit assumes mebibytes. + * @param text the text to parse + * @return the number of mebibytes */ public static Integer parseToMebibytes(String text) { if (!StringUtils.hasText(text)) { @@ -45,8 +48,9 @@ public final class ByteSizeUtils { Matcher matcher = SIZE_PATTERN.matcher(text); if (!matcher.matches()) { - throw new IllegalArgumentException(String.format("Could not parse '%s' as a byte size." + - " Expected a number with optional 'm' or 'g' suffix", text)); + throw new IllegalArgumentException(String.format( + "Could not parse '%s' as a byte size." + " Expected a number with optional 'm' or 'g' suffix", + text)); } int size = Integer.parseInt(matcher.group("amount")); if ("g".equalsIgnoreCase(matcher.group("unit"))) { diff --git a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/util/package-info.java b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/util/package-info.java new file mode 100644 index 0000000..642c105 --- /dev/null +++ b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/deployer/util/package-info.java @@ -0,0 +1,20 @@ +/* + * Copyright 2002-2024 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * AppBroker Deployer Utilities. + */ +package org.springframework.cloud.appbroker.deployer.deployer.util; diff --git a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/manager/AppManager.java b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/manager/AppManager.java index 863796c..ddeb42a 100644 --- a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/manager/AppManager.java +++ b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/manager/AppManager.java @@ -1,11 +1,11 @@ /* - * Copyright 2002-2020 the original author or authors + * Copyright 2002-2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * https://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/manager/RestageApplicationRequest.java b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/manager/RestageApplicationRequest.java index 3bfaa56..57b8aa1 100644 --- a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/manager/RestageApplicationRequest.java +++ b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/manager/RestageApplicationRequest.java @@ -1,11 +1,11 @@ /* - * Copyright 2002-2020 the original author or authors + * Copyright 2002-2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * https://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -33,11 +33,11 @@ public class RestageApplicationRequest { } public String getName() { - return name; + return this.name; } public Map getProperties() { - return properties; + return this.properties; } public static RestageApplicationRequestBuilder builder() { @@ -66,7 +66,7 @@ public class RestageApplicationRequest { } public RestageApplicationRequest build() { - return new RestageApplicationRequest(name, properties); + return new RestageApplicationRequest(this.name, this.properties); } } diff --git a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/manager/RestartApplicationRequest.java b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/manager/RestartApplicationRequest.java index b9cbb89..0c228fd 100644 --- a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/manager/RestartApplicationRequest.java +++ b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/manager/RestartApplicationRequest.java @@ -1,11 +1,11 @@ /* - * Copyright 2002-2020 the original author or authors + * Copyright 2002-2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * https://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -33,11 +33,11 @@ public class RestartApplicationRequest { } public String getName() { - return name; + return this.name; } public Map getProperties() { - return properties; + return this.properties; } public static RestartApplicationRequestBuilder builder() { @@ -66,7 +66,7 @@ public class RestartApplicationRequest { } public RestartApplicationRequest build() { - return new RestartApplicationRequest(name, properties); + return new RestartApplicationRequest(this.name, this.properties); } } diff --git a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/manager/StartApplicationRequest.java b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/manager/StartApplicationRequest.java index daa4b33..b18121c 100644 --- a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/manager/StartApplicationRequest.java +++ b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/manager/StartApplicationRequest.java @@ -1,11 +1,11 @@ /* - * Copyright 2002-2020 the original author or authors + * Copyright 2002-2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * https://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -33,11 +33,11 @@ public class StartApplicationRequest { } public String getName() { - return name; + return this.name; } public Map getProperties() { - return properties; + return this.properties; } public static StartApplicationRequestBuilder builder() { @@ -66,7 +66,7 @@ public class StartApplicationRequest { } public StartApplicationRequest build() { - return new StartApplicationRequest(name, properties); + return new StartApplicationRequest(this.name, this.properties); } } diff --git a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/manager/StopApplicationRequest.java b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/manager/StopApplicationRequest.java index 63f9f7f..7d0388f 100644 --- a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/manager/StopApplicationRequest.java +++ b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/manager/StopApplicationRequest.java @@ -1,11 +1,11 @@ /* - * Copyright 2002-2020 the original author or authors + * Copyright 2002-2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * https://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -33,11 +33,11 @@ public class StopApplicationRequest { } public String getName() { - return name; + return this.name; } public Map getProperties() { - return properties; + return this.properties; } public static StopApplicationRequestBuilder builder() { @@ -66,7 +66,7 @@ public class StopApplicationRequest { } public StopApplicationRequest build() { - return new StopApplicationRequest(name, properties); + return new StopApplicationRequest(this.name, this.properties); } } diff --git a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/manager/package-info.java b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/manager/package-info.java new file mode 100644 index 0000000..4819b44 --- /dev/null +++ b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/manager/package-info.java @@ -0,0 +1,20 @@ +/* + * Copyright 2002-2024 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * AppBroker Deployer Manager. + */ +package org.springframework.cloud.appbroker.deployer.manager; diff --git a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/oauth2/CreateOAuth2ClientRequest.java b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/oauth2/CreateOAuth2ClientRequest.java index 23ddb65..32b425e 100644 --- a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/oauth2/CreateOAuth2ClientRequest.java +++ b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/oauth2/CreateOAuth2ClientRequest.java @@ -41,9 +41,8 @@ public class CreateOAuth2ClientRequest { private final String identityZoneId; - protected CreateOAuth2ClientRequest(String clientId, String clientSecret, String clientName, - List scopes, List authorities, List grantTypes, - String identityZoneSubdomain, String identityZoneId) { + protected CreateOAuth2ClientRequest(String clientId, String clientSecret, String clientName, List scopes, + List authorities, List grantTypes, String identityZoneSubdomain, String identityZoneId) { this.clientId = clientId; this.clientSecret = clientSecret; this.clientName = clientName; @@ -55,35 +54,35 @@ public class CreateOAuth2ClientRequest { } public String getClientId() { - return clientId; + return this.clientId; } public String getClientSecret() { - return clientSecret; + return this.clientSecret; } public String getClientName() { - return clientName; + return this.clientName; } public List getScopes() { - return scopes; + return this.scopes; } public List getAuthorities() { - return authorities; + return this.authorities; } public List getGrantTypes() { - return grantTypes; + return this.grantTypes; } public String getIdentityZoneSubdomain() { - return identityZoneSubdomain; + return this.identityZoneSubdomain; } public String getIdentityZoneId() { - return identityZoneId; + return this.identityZoneId; } public static CreateOAuth2ClientRequestBuilder builder() { @@ -99,34 +98,26 @@ public class CreateOAuth2ClientRequest { return false; } CreateOAuth2ClientRequest that = (CreateOAuth2ClientRequest) o; - return Objects.equals(clientId, that.clientId) && - Objects.equals(clientSecret, that.clientSecret) && - Objects.equals(clientName, that.clientName) && - Objects.equals(scopes, that.scopes) && - Objects.equals(authorities, that.authorities) && - Objects.equals(grantTypes, that.grantTypes) && - Objects.equals(identityZoneSubdomain, that.identityZoneSubdomain) && - Objects.equals(identityZoneId, that.identityZoneId); + return Objects.equals(this.clientId, that.clientId) && Objects.equals(this.clientSecret, that.clientSecret) + && Objects.equals(this.clientName, that.clientName) && Objects.equals(this.scopes, that.scopes) + && Objects.equals(this.authorities, that.authorities) + && Objects.equals(this.grantTypes, that.grantTypes) + && Objects.equals(this.identityZoneSubdomain, that.identityZoneSubdomain) + && Objects.equals(this.identityZoneId, that.identityZoneId); } @Override public int hashCode() { - return Objects.hash(clientId, clientSecret, clientName, scopes, authorities, - grantTypes, identityZoneSubdomain, identityZoneId); + return Objects.hash(this.clientId, this.clientSecret, this.clientName, this.scopes, this.authorities, + this.grantTypes, this.identityZoneSubdomain, this.identityZoneId); } @Override public String toString() { - return "CreateOAuth2ClientRequest{" + - "clientId='" + clientId + '\'' + - ", clientSecret='" + clientSecret + '\'' + - ", clientName='" + clientName + '\'' + - ", scopes=" + scopes + - ", authorities=" + authorities + - ", grantTypes=" + grantTypes + - ", identityZoneSubdomain='" + identityZoneSubdomain + '\'' + - ", identityZoneId='" + identityZoneId + '\'' + - '}'; + return "CreateOAuth2ClientRequest{" + "clientId='" + this.clientId + '\'' + ", clientSecret='" + + this.clientSecret + '\'' + ", clientName='" + this.clientName + '\'' + ", scopes=" + this.scopes + + ", authorities=" + this.authorities + ", grantTypes=" + this.grantTypes + ", identityZoneSubdomain='" + + this.identityZoneSubdomain + '\'' + ", identityZoneId='" + this.identityZoneId + '\'' + '}'; } public static final class CreateOAuth2ClientRequestBuilder { @@ -212,9 +203,8 @@ public class CreateOAuth2ClientRequest { } public CreateOAuth2ClientRequest build() { - return new CreateOAuth2ClientRequest(clientId, clientSecret, clientName, - scopes, authorities, grantTypes, - identityZoneSubdomain, identityZoneId); + return new CreateOAuth2ClientRequest(this.clientId, this.clientSecret, this.clientName, this.scopes, + this.authorities, this.grantTypes, this.identityZoneSubdomain, this.identityZoneId); } } diff --git a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/oauth2/CreateOAuth2ClientResponse.java b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/oauth2/CreateOAuth2ClientResponse.java index 8d25849..8970778 100644 --- a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/oauth2/CreateOAuth2ClientResponse.java +++ b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/oauth2/CreateOAuth2ClientResponse.java @@ -34,9 +34,8 @@ public class CreateOAuth2ClientResponse { private final List grantTypes; - protected CreateOAuth2ClientResponse(String clientId, String clientName, - List scopes, List authorities, - List grantTypes) { + protected CreateOAuth2ClientResponse(String clientId, String clientName, List scopes, + List authorities, List grantTypes) { this.clientId = clientId; this.clientName = clientName; @@ -46,23 +45,23 @@ public class CreateOAuth2ClientResponse { } public String getClientId() { - return clientId; + return this.clientId; } public String getClientName() { - return clientName; + return this.clientName; } public List getScopes() { - return scopes; + return this.scopes; } public List getAuthorities() { - return authorities; + return this.authorities; } public List getGrantTypes() { - return grantTypes; + return this.grantTypes; } public static CreateOAuth2ClientResponseBuilder builder() { @@ -78,27 +77,21 @@ public class CreateOAuth2ClientResponse { return false; } CreateOAuth2ClientResponse that = (CreateOAuth2ClientResponse) o; - return Objects.equals(clientId, that.clientId) && - Objects.equals(clientName, that.clientName) && - Objects.equals(scopes, that.scopes) && - Objects.equals(authorities, that.authorities) && - Objects.equals(grantTypes, that.grantTypes); + return Objects.equals(this.clientId, that.clientId) && Objects.equals(this.clientName, that.clientName) + && Objects.equals(this.scopes, that.scopes) && Objects.equals(this.authorities, that.authorities) + && Objects.equals(this.grantTypes, that.grantTypes); } @Override public int hashCode() { - return Objects.hash(clientId, clientName, scopes, authorities, grantTypes); + return Objects.hash(this.clientId, this.clientName, this.scopes, this.authorities, this.grantTypes); } @Override public String toString() { - return "CreateOAuth2ClientResponse{" + - "clientId='" + clientId + '\'' + - ", clientName='" + clientName + '\'' + - ", scopes=" + scopes + - ", authorities=" + authorities + - ", grantTypes=" + grantTypes + - '}'; + return "CreateOAuth2ClientResponse{" + "clientId='" + this.clientId + '\'' + ", clientName='" + this.clientName + + '\'' + ", scopes=" + this.scopes + ", authorities=" + this.authorities + ", grantTypes=" + + this.grantTypes + '}'; } public static final class CreateOAuth2ClientResponseBuilder { @@ -148,7 +141,8 @@ public class CreateOAuth2ClientResponse { } public CreateOAuth2ClientResponse build() { - return new CreateOAuth2ClientResponse(clientId, clientName, scopes, authorities, grantTypes); + return new CreateOAuth2ClientResponse(this.clientId, this.clientName, this.scopes, this.authorities, + this.grantTypes); } } diff --git a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/oauth2/DeleteOAuth2ClientRequest.java b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/oauth2/DeleteOAuth2ClientRequest.java index 2f7729f..f80ebd9 100644 --- a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/oauth2/DeleteOAuth2ClientRequest.java +++ b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/oauth2/DeleteOAuth2ClientRequest.java @@ -33,15 +33,15 @@ public class DeleteOAuth2ClientRequest { } public String getClientId() { - return clientId; + return this.clientId; } public String getIdentityZoneSubdomain() { - return identityZoneSubdomain; + return this.identityZoneSubdomain; } public String getIdentityZoneId() { - return identityZoneId; + return this.identityZoneId; } public static DeleteOAuth2ClientRequestBuilder builder() { @@ -57,23 +57,20 @@ public class DeleteOAuth2ClientRequest { return false; } DeleteOAuth2ClientRequest that = (DeleteOAuth2ClientRequest) o; - return Objects.equals(clientId, that.clientId) && - Objects.equals(identityZoneSubdomain, that.identityZoneSubdomain) && - Objects.equals(identityZoneId, that.identityZoneId); + return Objects.equals(this.clientId, that.clientId) + && Objects.equals(this.identityZoneSubdomain, that.identityZoneSubdomain) + && Objects.equals(this.identityZoneId, that.identityZoneId); } @Override public int hashCode() { - return Objects.hash(clientId, identityZoneSubdomain, identityZoneId); + return Objects.hash(this.clientId, this.identityZoneSubdomain, this.identityZoneId); } @Override public String toString() { - return "DeleteOAuth2ClientRequest{" + - "clientId='" + clientId + '\'' + - ", identityZoneSubdomain='" + identityZoneSubdomain + '\'' + - ", identityZoneId='" + identityZoneId + '\'' + - '}'; + return "DeleteOAuth2ClientRequest{" + "clientId='" + this.clientId + '\'' + ", identityZoneSubdomain='" + + this.identityZoneSubdomain + '\'' + ", identityZoneId='" + this.identityZoneId + '\'' + '}'; } public static final class DeleteOAuth2ClientRequestBuilder { @@ -103,7 +100,7 @@ public class DeleteOAuth2ClientRequest { } public DeleteOAuth2ClientRequest build() { - return new DeleteOAuth2ClientRequest(clientId, identityZoneSubdomain, identityZoneId); + return new DeleteOAuth2ClientRequest(this.clientId, this.identityZoneSubdomain, this.identityZoneId); } } diff --git a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/oauth2/DeleteOAuth2ClientResponse.java b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/oauth2/DeleteOAuth2ClientResponse.java index 3bafb65..337e06a 100644 --- a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/oauth2/DeleteOAuth2ClientResponse.java +++ b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/oauth2/DeleteOAuth2ClientResponse.java @@ -34,9 +34,8 @@ public class DeleteOAuth2ClientResponse { private final List grantTypes; - protected DeleteOAuth2ClientResponse(String clientId, String clientName, - List scopes, List authorities, - List grantTypes) { + protected DeleteOAuth2ClientResponse(String clientId, String clientName, List scopes, + List authorities, List grantTypes) { this.clientId = clientId; this.clientName = clientName; this.scopes = scopes; @@ -45,23 +44,23 @@ public class DeleteOAuth2ClientResponse { } public String getClientId() { - return clientId; + return this.clientId; } public String getClientName() { - return clientName; + return this.clientName; } public List getScopes() { - return scopes; + return this.scopes; } public List getAuthorities() { - return authorities; + return this.authorities; } public List getGrantTypes() { - return grantTypes; + return this.grantTypes; } public static DeleteOAuth2ClientResponseBuilder builder() { @@ -77,27 +76,21 @@ public class DeleteOAuth2ClientResponse { return false; } DeleteOAuth2ClientResponse that = (DeleteOAuth2ClientResponse) o; - return Objects.equals(clientId, that.clientId) && - Objects.equals(clientName, that.clientName) && - Objects.equals(scopes, that.scopes) && - Objects.equals(authorities, that.authorities) && - Objects.equals(grantTypes, that.grantTypes); + return Objects.equals(this.clientId, that.clientId) && Objects.equals(this.clientName, that.clientName) + && Objects.equals(this.scopes, that.scopes) && Objects.equals(this.authorities, that.authorities) + && Objects.equals(this.grantTypes, that.grantTypes); } @Override public int hashCode() { - return Objects.hash(clientId, clientName, scopes, authorities, grantTypes); + return Objects.hash(this.clientId, this.clientName, this.scopes, this.authorities, this.grantTypes); } @Override public String toString() { - return "DeleteOAuth2ClientResponse{" + - "clientId='" + clientId + '\'' + - ", clientName='" + clientName + '\'' + - ", scopes=" + scopes + - ", authorities=" + authorities + - ", grantTypes=" + grantTypes + - '}'; + return "DeleteOAuth2ClientResponse{" + "clientId='" + this.clientId + '\'' + ", clientName='" + this.clientName + + '\'' + ", scopes=" + this.scopes + ", authorities=" + this.authorities + ", grantTypes=" + + this.grantTypes + '}'; } public static final class DeleteOAuth2ClientResponseBuilder { @@ -147,7 +140,8 @@ public class DeleteOAuth2ClientResponse { } public DeleteOAuth2ClientResponse build() { - return new DeleteOAuth2ClientResponse(clientId, clientName, scopes, authorities, grantTypes); + return new DeleteOAuth2ClientResponse(this.clientId, this.clientName, this.scopes, this.authorities, + this.grantTypes); } } diff --git a/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/oauth2/package-info.java b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/oauth2/package-info.java new file mode 100644 index 0000000..543ee61 --- /dev/null +++ b/spring-cloud-app-broker-deployer/src/main/java/org/springframework/cloud/appbroker/deployer/oauth2/package-info.java @@ -0,0 +1,20 @@ +/* + * Copyright 2002-2024 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * AppBroker Deployer OAuth2. + */ +package org.springframework.cloud.appbroker.deployer.oauth2; diff --git a/spring-cloud-app-broker-deployer/src/test/java/org/springframework/cloud/appbroker/deployer/deployer/GetServiceInstanceRequestTest.java b/spring-cloud-app-broker-deployer/src/test/java/org/springframework/cloud/appbroker/deployer/deployer/GetServiceInstanceRequestTests.java similarity index 84% rename from spring-cloud-app-broker-deployer/src/test/java/org/springframework/cloud/appbroker/deployer/deployer/GetServiceInstanceRequestTest.java rename to spring-cloud-app-broker-deployer/src/test/java/org/springframework/cloud/appbroker/deployer/deployer/GetServiceInstanceRequestTests.java index e46b1ec..9b1049f 100644 --- a/spring-cloud-app-broker-deployer/src/test/java/org/springframework/cloud/appbroker/deployer/deployer/GetServiceInstanceRequestTest.java +++ b/spring-cloud-app-broker-deployer/src/test/java/org/springframework/cloud/appbroker/deployer/deployer/GetServiceInstanceRequestTests.java @@ -1,11 +1,11 @@ /* - * Copyright 2002-2020 the original author or authors + * Copyright 2002-2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * https://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -18,17 +18,16 @@ package org.springframework.cloud.appbroker.deployer.deployer; import java.util.Collections; +import org.assertj.core.data.MapEntry; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.data.MapEntry.entry; -class GetServiceInstanceRequestTest { +class GetServiceInstanceRequestTests { @Test void builderWithNoValues() { - GetServiceInstanceRequest request = GetServiceInstanceRequest.builder() - .build(); + GetServiceInstanceRequest request = GetServiceInstanceRequest.builder().build(); assertThat(request).isNotNull(); assertThat(request.getName()).isNull(); assertThat(request.getServiceInstanceId()).isNull(); @@ -45,14 +44,12 @@ class GetServiceInstanceRequestTest { assertThat(request).isNotNull(); assertThat(request.getName()).isEqualTo("foo-name"); assertThat(request.getServiceInstanceId()).isEqualTo("foo-id"); - assertThat(request.getProperties()).containsOnly(entry("foo", "bar")); + assertThat(request.getProperties()).containsOnly(MapEntry.entry("foo", "bar")); } @Test void builderAcceptsNullProperties() { - GetServiceInstanceRequest request = GetServiceInstanceRequest.builder() - .properties(null) - .build(); + GetServiceInstanceRequest request = GetServiceInstanceRequest.builder().properties(null).build(); assertThat(request).isNotNull(); assertThat(request.getProperties()).isEmpty(); } diff --git a/spring-cloud-app-broker-deployer/src/test/java/org/springframework/cloud/appbroker/deployer/manager/RestageApplicationRequestTest.java b/spring-cloud-app-broker-deployer/src/test/java/org/springframework/cloud/appbroker/deployer/deployer/manager/RestageApplicationRequestTests.java similarity index 77% rename from spring-cloud-app-broker-deployer/src/test/java/org/springframework/cloud/appbroker/deployer/manager/RestageApplicationRequestTest.java rename to spring-cloud-app-broker-deployer/src/test/java/org/springframework/cloud/appbroker/deployer/deployer/manager/RestageApplicationRequestTests.java index bef40d5..ffd5c5b 100644 --- a/spring-cloud-app-broker-deployer/src/test/java/org/springframework/cloud/appbroker/deployer/manager/RestageApplicationRequestTest.java +++ b/spring-cloud-app-broker-deployer/src/test/java/org/springframework/cloud/appbroker/deployer/deployer/manager/RestageApplicationRequestTests.java @@ -1,11 +1,11 @@ /* - * Copyright 2002-2020 the original author or authors + * Copyright 2002-2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * https://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -14,21 +14,22 @@ * limitations under the License. */ -package org.springframework.cloud.appbroker.deployer.manager; +package org.springframework.cloud.appbroker.deployer.deployer.manager; import java.util.Collections; +import org.assertj.core.data.MapEntry; import org.junit.jupiter.api.Test; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.data.MapEntry.entry; +import org.springframework.cloud.appbroker.deployer.manager.RestageApplicationRequest; -class RestageApplicationRequestTest { +import static org.assertj.core.api.Assertions.assertThat; + +class RestageApplicationRequestTests { @Test void builderWithNoValues() { - RestageApplicationRequest request = RestageApplicationRequest.builder() - .build(); + RestageApplicationRequest request = RestageApplicationRequest.builder().build(); assertThat(request).isNotNull(); assertThat(request.getName()).isNull(); assertThat(request.getProperties()).isEmpty(); @@ -42,15 +43,12 @@ class RestageApplicationRequestTest { .build(); assertThat(request).isNotNull(); assertThat(request.getName()).isEqualTo("foo"); - assertThat(request.getProperties()).containsOnly(entry("foo", "bar")); + assertThat(request.getProperties()).containsOnly(MapEntry.entry("foo", "bar")); } @Test void builderAcceptsNullProperties() { - RestageApplicationRequest request = RestageApplicationRequest.builder() - .name("foo") - .properties(null) - .build(); + RestageApplicationRequest request = RestageApplicationRequest.builder().name("foo").properties(null).build(); assertThat(request).isNotNull(); assertThat(request.getName()).isEqualTo("foo"); assertThat(request.getProperties()).isEmpty(); diff --git a/spring-cloud-app-broker-deployer/src/test/java/org/springframework/cloud/appbroker/deployer/manager/RestartApplicationRequestTest.java b/spring-cloud-app-broker-deployer/src/test/java/org/springframework/cloud/appbroker/deployer/deployer/manager/RestartApplicationRequestTests.java similarity index 77% rename from spring-cloud-app-broker-deployer/src/test/java/org/springframework/cloud/appbroker/deployer/manager/RestartApplicationRequestTest.java rename to spring-cloud-app-broker-deployer/src/test/java/org/springframework/cloud/appbroker/deployer/deployer/manager/RestartApplicationRequestTests.java index a9566e9..bd3584b 100644 --- a/spring-cloud-app-broker-deployer/src/test/java/org/springframework/cloud/appbroker/deployer/manager/RestartApplicationRequestTest.java +++ b/spring-cloud-app-broker-deployer/src/test/java/org/springframework/cloud/appbroker/deployer/deployer/manager/RestartApplicationRequestTests.java @@ -1,11 +1,11 @@ /* - * Copyright 2002-2020 the original author or authors + * Copyright 2002-2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * https://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -14,21 +14,22 @@ * limitations under the License. */ -package org.springframework.cloud.appbroker.deployer.manager; +package org.springframework.cloud.appbroker.deployer.deployer.manager; import java.util.Collections; +import org.assertj.core.data.MapEntry; import org.junit.jupiter.api.Test; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.data.MapEntry.entry; +import org.springframework.cloud.appbroker.deployer.manager.RestartApplicationRequest; -class RestartApplicationRequestTest { +import static org.assertj.core.api.Assertions.assertThat; + +class RestartApplicationRequestTests { @Test void builderWithNoValues() { - RestartApplicationRequest request = RestartApplicationRequest.builder() - .build(); + RestartApplicationRequest request = RestartApplicationRequest.builder().build(); assertThat(request).isNotNull(); assertThat(request.getName()).isNull(); assertThat(request.getProperties()).isEmpty(); @@ -42,15 +43,12 @@ class RestartApplicationRequestTest { .build(); assertThat(request).isNotNull(); assertThat(request.getName()).isEqualTo("foo"); - assertThat(request.getProperties()).containsOnly(entry("foo", "bar")); + assertThat(request.getProperties()).containsOnly(MapEntry.entry("foo", "bar")); } @Test void builderAcceptsNullProperties() { - RestartApplicationRequest request = RestartApplicationRequest.builder() - .name("foo") - .properties(null) - .build(); + RestartApplicationRequest request = RestartApplicationRequest.builder().name("foo").properties(null).build(); assertThat(request).isNotNull(); assertThat(request.getName()).isEqualTo("foo"); assertThat(request.getProperties()).isEmpty(); diff --git a/spring-cloud-app-broker-deployer/src/test/java/org/springframework/cloud/appbroker/deployer/manager/StartApplicationRequestTest.java b/spring-cloud-app-broker-deployer/src/test/java/org/springframework/cloud/appbroker/deployer/deployer/manager/StartApplicationRequestTests.java similarity index 78% rename from spring-cloud-app-broker-deployer/src/test/java/org/springframework/cloud/appbroker/deployer/manager/StartApplicationRequestTest.java rename to spring-cloud-app-broker-deployer/src/test/java/org/springframework/cloud/appbroker/deployer/deployer/manager/StartApplicationRequestTests.java index 7cf5375..ea642fb 100644 --- a/spring-cloud-app-broker-deployer/src/test/java/org/springframework/cloud/appbroker/deployer/manager/StartApplicationRequestTest.java +++ b/spring-cloud-app-broker-deployer/src/test/java/org/springframework/cloud/appbroker/deployer/deployer/manager/StartApplicationRequestTests.java @@ -1,11 +1,11 @@ /* - * Copyright 2002-2020 the original author or authors + * Copyright 2002-2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * https://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -14,21 +14,22 @@ * limitations under the License. */ -package org.springframework.cloud.appbroker.deployer.manager; +package org.springframework.cloud.appbroker.deployer.deployer.manager; import java.util.Collections; +import org.assertj.core.data.MapEntry; import org.junit.jupiter.api.Test; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.data.MapEntry.entry; +import org.springframework.cloud.appbroker.deployer.manager.StartApplicationRequest; -class StartApplicationRequestTest { +import static org.assertj.core.api.Assertions.assertThat; + +class StartApplicationRequestTests { @Test void builderWithNoValues() { - StartApplicationRequest request = StartApplicationRequest.builder() - .build(); + StartApplicationRequest request = StartApplicationRequest.builder().build(); assertThat(request).isNotNull(); assertThat(request.getName()).isNull(); assertThat(request.getProperties()).isEmpty(); @@ -42,15 +43,12 @@ class StartApplicationRequestTest { .build(); assertThat(request).isNotNull(); assertThat(request.getName()).isEqualTo("foo"); - assertThat(request.getProperties()).containsOnly(entry("foo", "bar")); + assertThat(request.getProperties()).containsOnly(MapEntry.entry("foo", "bar")); } @Test void builderAcceptsNullProperties() { - StartApplicationRequest request = StartApplicationRequest.builder() - .name("foo") - .properties(null) - .build(); + StartApplicationRequest request = StartApplicationRequest.builder().name("foo").properties(null).build(); assertThat(request).isNotNull(); assertThat(request.getName()).isEqualTo("foo"); assertThat(request.getProperties()).isEmpty(); diff --git a/spring-cloud-app-broker-deployer/src/test/java/org/springframework/cloud/appbroker/deployer/manager/StopApplicationRequestTest.java b/spring-cloud-app-broker-deployer/src/test/java/org/springframework/cloud/appbroker/deployer/deployer/manager/StopApplicationRequestTests.java similarity index 78% rename from spring-cloud-app-broker-deployer/src/test/java/org/springframework/cloud/appbroker/deployer/manager/StopApplicationRequestTest.java rename to spring-cloud-app-broker-deployer/src/test/java/org/springframework/cloud/appbroker/deployer/deployer/manager/StopApplicationRequestTests.java index 4759f1d..85ae06d 100644 --- a/spring-cloud-app-broker-deployer/src/test/java/org/springframework/cloud/appbroker/deployer/manager/StopApplicationRequestTest.java +++ b/spring-cloud-app-broker-deployer/src/test/java/org/springframework/cloud/appbroker/deployer/deployer/manager/StopApplicationRequestTests.java @@ -1,11 +1,11 @@ /* - * Copyright 2002-2020 the original author or authors + * Copyright 2002-2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * https://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -14,21 +14,22 @@ * limitations under the License. */ -package org.springframework.cloud.appbroker.deployer.manager; +package org.springframework.cloud.appbroker.deployer.deployer.manager; import java.util.Collections; +import org.assertj.core.data.MapEntry; import org.junit.jupiter.api.Test; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.data.MapEntry.entry; +import org.springframework.cloud.appbroker.deployer.manager.StopApplicationRequest; -class StopApplicationRequestTest { +import static org.assertj.core.api.Assertions.assertThat; + +class StopApplicationRequestTests { @Test void builderWithNoValues() { - StopApplicationRequest request = StopApplicationRequest.builder() - .build(); + StopApplicationRequest request = StopApplicationRequest.builder().build(); assertThat(request).isNotNull(); assertThat(request.getName()).isNull(); assertThat(request.getProperties()).isEmpty(); @@ -42,15 +43,12 @@ class StopApplicationRequestTest { .build(); assertThat(request).isNotNull(); assertThat(request.getName()).isEqualTo("foo"); - assertThat(request.getProperties()).containsOnly(entry("foo", "bar")); + assertThat(request.getProperties()).containsOnly(MapEntry.entry("foo", "bar")); } @Test void builderAcceptsNullProperties() { - StopApplicationRequest request = StopApplicationRequest.builder() - .name("foo") - .properties(null) - .build(); + StopApplicationRequest request = StopApplicationRequest.builder().name("foo").properties(null).build(); assertThat(request).isNotNull(); assertThat(request.getName()).isEqualTo("foo"); assertThat(request.getProperties()).isEmpty(); diff --git a/spring-cloud-app-broker-docs/build.gradle b/spring-cloud-app-broker-docs/build.gradle index 9542a44..d896d70 100644 --- a/spring-cloud-app-broker-docs/build.gradle +++ b/spring-cloud-app-broker-docs/build.gradle @@ -1,5 +1,5 @@ /* - * Copyright 2002-2024 the original author or authors. + * Copyright 2016-2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-cloud-app-broker-integration-tests/build.gradle b/spring-cloud-app-broker-integration-tests/build.gradle index a00cb40..61c6ad9 100644 --- a/spring-cloud-app-broker-integration-tests/build.gradle +++ b/spring-cloud-app-broker-integration-tests/build.gradle @@ -1,7 +1,7 @@ import org.springframework.boot.gradle.plugin.SpringBootPlugin /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-cloud-app-broker-integration-tests/src/main/java/org/springframework/cloud/appbroker/integration/AppBrokerApplication.java b/spring-cloud-app-broker-integration-tests/src/main/java/org/springframework/cloud/appbroker/integration/AppBrokerApplication.java index a77c73a..404b59f 100644 --- a/spring-cloud-app-broker-integration-tests/src/main/java/org/springframework/cloud/appbroker/integration/AppBrokerApplication.java +++ b/spring-cloud-app-broker-integration-tests/src/main/java/org/springframework/cloud/appbroker/integration/AppBrokerApplication.java @@ -20,14 +20,15 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** - * A Spring Boot application for running integration tests + * A Spring Boot application for running integration tests. + * + * @author Scott Frederick */ @SpringBootApplication public class AppBrokerApplication { /** - * main application entry point - * + * main application entry point. * @param args the args */ public static void main(String[] args) { diff --git a/spring-cloud-app-broker-integration-tests/src/main/java/org/springframework/cloud/appbroker/integration/package-info.java b/spring-cloud-app-broker-integration-tests/src/main/java/org/springframework/cloud/appbroker/integration/package-info.java new file mode 100644 index 0000000..1e436b0 --- /dev/null +++ b/spring-cloud-app-broker-integration-tests/src/main/java/org/springframework/cloud/appbroker/integration/package-info.java @@ -0,0 +1,20 @@ +/* + * Copyright 2002-2024 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Integration test application. + */ +package org.springframework.cloud.appbroker.integration; diff --git a/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/ApplicationTest.java b/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/ApplicationTests.java similarity index 82% rename from spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/ApplicationTest.java rename to spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/ApplicationTests.java index bfd0e9c..788a22a 100644 --- a/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/ApplicationTest.java +++ b/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/ApplicationTests.java @@ -32,9 +32,9 @@ import org.springframework.test.context.junit.jupiter.SpringExtension; import static org.assertj.core.api.Assertions.assertThat; @ExtendWith(SpringExtension.class) -@SpringBootTest(classes = {AppBrokerApplication.class}) -@ActiveProfiles({"openservicebroker-catalog", "appbroker-cf"}) -class ApplicationTest { +@SpringBootTest(classes = { AppBrokerApplication.class }) +@ActiveProfiles({ "openservicebroker-catalog", "appbroker-cf" }) +class ApplicationTests { @Autowired(required = false) private CatalogController catalogController; @@ -53,11 +53,11 @@ class ApplicationTest { @Test void applicationInitialized() { - assertThat(catalogController).isNotNull(); - assertThat(cloudFoundryOperations).isNotNull(); - assertThat(appDeployer).isNotNull(); - assertThat(deploymentService).isNotNull(); - assertThat(serviceInstanceService).isNotNull(); + assertThat(this.catalogController).isNotNull(); + assertThat(this.cloudFoundryOperations).isNotNull(); + assertThat(this.appDeployer).isNotNull(); + assertThat(this.deploymentService).isNotNull(); + assertThat(this.serviceInstanceService).isNotNull(); } } diff --git a/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CatalogComponentTest.java b/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CatalogComponentTests.java similarity index 88% rename from spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CatalogComponentTest.java rename to spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CatalogComponentTests.java index 06802ff..6037eca 100644 --- a/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CatalogComponentTest.java +++ b/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CatalogComponentTests.java @@ -33,11 +33,9 @@ import static org.springframework.cloud.appbroker.integration.fixtures.CloudCont import static org.springframework.cloud.appbroker.integration.fixtures.CloudControllerStubFixture.serviceGuid; @ExtendWith(SpringExtension.class) -@SpringBootTest( - webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, - classes = {AppBrokerApplication.class}) -@ActiveProfiles({"openservicebroker-catalog", "appbroker-cf"}) -class CatalogComponentTest { +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = { AppBrokerApplication.class }) +@ActiveProfiles({ "openservicebroker-catalog", "appbroker-cf" }) +class CatalogComponentTests { private String baseUrl; @@ -46,13 +44,12 @@ class CatalogComponentTest { @BeforeEach void setUp() { - baseUrl = "http://localhost:" + port; + this.baseUrl = "http://localhost:" + this.port; } @Test void shouldRetrieveCatalog() { - given() - .get(baseUrl + "/v2/catalog") + given().get(this.baseUrl + "/v2/catalog") .then() .statusCode(HttpStatus.OK.value()) .body("services[0].name", equalTo("example")) @@ -71,4 +68,3 @@ class CatalogComponentTest { } } - diff --git a/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceComponentTest.java b/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceComponentTests.java similarity index 58% rename from spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceComponentTest.java rename to spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceComponentTests.java index 410d372..496cd52 100644 --- a/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceComponentTest.java +++ b/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceComponentTests.java @@ -30,19 +30,17 @@ import static io.restassured.RestAssured.given; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; -import static org.springframework.cloud.appbroker.integration.CreateInstanceComponentTest.APP_NAME_1; -import static org.springframework.cloud.appbroker.integration.CreateInstanceComponentTest.APP_NAME_2; +import static org.springframework.cloud.appbroker.integration.CreateInstanceComponentTests.APP_NAME_1; +import static org.springframework.cloud.appbroker.integration.CreateInstanceComponentTests.APP_NAME_2; -@TestPropertySource(properties = { - "spring.cloud.appbroker.services[0].service-name=example", - "spring.cloud.appbroker.services[0].plan-name=standard", - "spring.cloud.appbroker.services[0].apps[0].path=classpath:demo.jar", - "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME_1, - "spring.cloud.appbroker.services[0].apps[1].path=classpath:demo.jar", - "spring.cloud.appbroker.services[0].apps[1].name=" + APP_NAME_2, - "spring.cloud.appbroker.services[0].apps[1].properties.use-spring-application-json=false" -}) -class CreateInstanceComponentTest extends WiremockComponentTest { +@TestPropertySource(properties = { "spring.cloud.appbroker.services[0].service-name=example", + "spring.cloud.appbroker.services[0].plan-name=standard", + "spring.cloud.appbroker.services[0].apps[0].path=classpath:demo.jar", + "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME_1, + "spring.cloud.appbroker.services[0].apps[1].path=classpath:demo.jar", + "spring.cloud.appbroker.services[0].apps[1].name=" + APP_NAME_2, + "spring.cloud.appbroker.services[0].apps[1].properties.use-spring-application-json=false" }) +class CreateInstanceComponentTests extends WiremockComponentTests { protected static final String APP_NAME_1 = "first-app"; @@ -58,32 +56,30 @@ class CreateInstanceComponentTest extends WiremockComponentTest { @Test void pushAppsWhenTheyDoNotExist() { - cloudControllerFixture.stubFindSpaceV3(); - cloudControllerFixture.stubAppDoesNotExist(APP_NAME_1); - cloudControllerFixture.stubPushApp(APP_NAME_1, - matchingJsonPath("$.environment_json[?(@.SPRING_APPLICATION_JSON =~ " + - "/.*spring.cloud.appbroker.service-instance-id.*:.*" + SERVICE_INSTANCE_ID + ".*/)]")); - cloudControllerFixture.stubAppDoesNotExist(APP_NAME_2); - cloudControllerFixture.stubPushApp(APP_NAME_2, - matchingJsonPath("$.environment_json[?(@.['spring.cloud.appbroker.service-instance-id'] =~ " + - "/" + SERVICE_INSTANCE_ID + "/)]")); + this.cloudControllerFixture.stubFindSpaceV3(); + this.cloudControllerFixture.stubAppDoesNotExist(APP_NAME_1); + this.cloudControllerFixture.stubPushApp(APP_NAME_1, + matchingJsonPath("$.environment_json[?(@.SPRING_APPLICATION_JSON =~ " + + "/.*spring.cloud.appbroker.service-instance-id.*:.*" + SERVICE_INSTANCE_ID + ".*/)]")); + this.cloudControllerFixture.stubAppDoesNotExist(APP_NAME_2); + this.cloudControllerFixture.stubPushApp(APP_NAME_2, + matchingJsonPath("$.environment_json[?(@.['spring.cloud.appbroker.service-instance-id'] =~ " + "/" + + SERVICE_INSTANCE_ID + "/)]")); // when a service instance is created - given(brokerFixture.serviceInstanceRequest()) - .when() - .put(brokerFixture.createServiceInstanceUrl(), SERVICE_INSTANCE_ID) + given(this.brokerFixture.serviceInstanceRequest()).when() + .put(this.brokerFixture.createServiceInstanceUrl(), SERVICE_INSTANCE_ID) .then() .statusCode(HttpStatus.ACCEPTED.value()); // when the "last_operation" API is polled - given(brokerFixture.serviceInstanceRequest()) - .when() - .get(brokerFixture.getLastInstanceOperationUrl(), SERVICE_INSTANCE_ID) + given(this.brokerFixture.serviceInstanceRequest()).when() + .get(this.brokerFixture.getLastInstanceOperationUrl(), SERVICE_INSTANCE_ID) .then() .statusCode(HttpStatus.OK.value()) .body("state", is(equalTo(OperationState.IN_PROGRESS.toString()))); - String state = brokerFixture.waitForAsyncOperationComplete(SERVICE_INSTANCE_ID); + String state = this.brokerFixture.waitForAsyncOperationComplete(SERVICE_INSTANCE_ID); assertThat(state).isEqualTo(OperationState.SUCCEEDED.toString()); } diff --git a/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithCustomParametersMappingComponentTest.java b/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithCustomParametersMappingComponentTests.java similarity index 71% rename from spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithCustomParametersMappingComponentTest.java rename to spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithCustomParametersMappingComponentTests.java index fd9522c..9eac62f 100644 --- a/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithCustomParametersMappingComponentTest.java +++ b/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithCustomParametersMappingComponentTests.java @@ -46,20 +46,18 @@ import static io.restassured.RestAssured.given; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; -import static org.springframework.cloud.appbroker.integration.CreateInstanceWithCustomParametersMappingComponentTest.APP_NAME; +import static org.springframework.cloud.appbroker.integration.CreateInstanceWithCustomParametersMappingComponentTests.APP_NAME; -@TestPropertySource(properties = { - "spring.cloud.appbroker.services[0].service-name=example", - "spring.cloud.appbroker.services[0].plan-name=standard", - "spring.cloud.appbroker.services[0].apps[0].path=classpath:demo.jar", - "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME, - "spring.cloud.appbroker.services[0].apps[0].parameters-transformers[0].name=CustomMapping" -}) -@ContextConfiguration(classes = CreateInstanceWithCustomParametersMappingComponentTest.CustomConfig.class) -class CreateInstanceWithCustomParametersMappingComponentTest extends WiremockComponentTest { +@TestPropertySource(properties = { "spring.cloud.appbroker.services[0].service-name=example", + "spring.cloud.appbroker.services[0].plan-name=standard", + "spring.cloud.appbroker.services[0].apps[0].path=classpath:demo.jar", + "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME, + "spring.cloud.appbroker.services[0].apps[0].parameters-transformers[0].name=CustomMapping" }) +@ContextConfiguration(classes = CreateInstanceWithCustomParametersMappingComponentTests.CustomConfig.class) +class CreateInstanceWithCustomParametersMappingComponentTests extends WiremockComponentTests { - private static final Logger LOG = - LoggerFactory.getLogger(CreateInstanceWithCustomParametersMappingComponentTest.class); + private static final Logger LOG = LoggerFactory + .getLogger(CreateInstanceWithCustomParametersMappingComponentTests.class); protected static final String APP_NAME = "app-with-request-create-params"; @@ -71,34 +69,31 @@ class CreateInstanceWithCustomParametersMappingComponentTest extends WiremockCom @Test void pushAppWithParametersTransformedUsingCustomTransformer() { - cloudControllerFixture.stubFindSpaceV3(); - cloudControllerFixture.stubAppDoesNotExist(APP_NAME); - cloudControllerFixture.stubPushApp(APP_NAME, - matchingJsonPath( + this.cloudControllerFixture.stubFindSpaceV3(); + this.cloudControllerFixture.stubAppDoesNotExist(APP_NAME); + this.cloudControllerFixture.stubPushApp(APP_NAME, matchingJsonPath( "$.environment_json[?(@.SPRING_APPLICATION_JSON =~ /.*otherNestedKey.*:.*otherKey.*:.*keyValue.*/)]"), - matchingJsonPath( - "$.environment_json[?(@.SPRING_APPLICATION_JSON =~ /.*otherNestedKey.*:.*otherLabel.*:.*labelValue.*/)]")); + matchingJsonPath( + "$.environment_json[?(@.SPRING_APPLICATION_JSON =~ /.*otherNestedKey.*:.*otherLabel.*:.*labelValue.*/)]")); // given a set of parameters Map params = new HashMap<>(); params.put("firstKey", "{\"label\":\"labelValue\",\"secondKey\":\"keyValue\"}"); // when a service instance is created - given(brokerFixture.serviceInstanceRequest(params)) - .when() - .put(brokerFixture.createServiceInstanceUrl(), "instance-id") + given(this.brokerFixture.serviceInstanceRequest(params)).when() + .put(this.brokerFixture.createServiceInstanceUrl(), "instance-id") .then() .statusCode(HttpStatus.ACCEPTED.value()); // when the "last_operation" API is polled - given(brokerFixture.serviceInstanceRequest()) - .when() - .get(brokerFixture.getLastInstanceOperationUrl(), "instance-id") + given(this.brokerFixture.serviceInstanceRequest()).when() + .get(this.brokerFixture.getLastInstanceOperationUrl(), "instance-id") .then() .statusCode(HttpStatus.OK.value()) .body("state", is(equalTo(OperationState.IN_PROGRESS.toString()))); - String state = brokerFixture.waitForAsyncOperationComplete("instance-id"); + String state = this.brokerFixture.waitForAsyncOperationComplete("instance-id"); assertThat(state).isEqualTo(OperationState.SUCCEEDED.toString()); } @@ -111,7 +106,7 @@ class CreateInstanceWithCustomParametersMappingComponentTest extends WiremockCom } public final class CustomMappingParametersTransformerFactory - extends ParametersTransformerFactory { + extends ParametersTransformerFactory { private CustomMappingParametersTransformerFactory() { super(); @@ -123,7 +118,7 @@ class CreateInstanceWithCustomParametersMappingComponentTest extends WiremockCom } private Mono transform(BackingApplication backingApplication, - Map parameters) { + Map parameters) { backingApplication.setEnvironment(createEnvironmentMap(parameters)); return Mono.just(backingApplication); } @@ -132,14 +127,14 @@ class CreateInstanceWithCustomParametersMappingComponentTest extends WiremockCom ObjectMapper objectMapper = new ObjectMapper(); ObjectNode customOutputEnvironmentParameters = objectMapper.createObjectNode(); try { - CustomInputParameters customInputParameters = - objectMapper.readValue(parameters.get("firstKey").toString(), CustomInputParameters.class); + CustomInputParameters customInputParameters = objectMapper + .readValue(parameters.get("firstKey").toString(), CustomInputParameters.class); customOutputEnvironmentParameters.put("otherKey", customInputParameters.getSecondKey()); customOutputEnvironmentParameters.put("otherLabel", customInputParameters.getLabel()); } - catch (IOException e) { + catch (IOException ex) { if (LOG.isDebugEnabled()) { - LOG.debug("error reading parameters", e); + LOG.debug("error reading parameters", ex); } } return Collections.singletonMap("otherNestedKey", customOutputEnvironmentParameters); @@ -153,19 +148,19 @@ class CreateInstanceWithCustomParametersMappingComponentTest extends WiremockCom private String label; - public String getSecondKey() { - return secondKey; + String getSecondKey() { + return this.secondKey; } - public String getLabel() { - return label; + String getLabel() { + return this.label; } - public void setSecondKey(String secondKey) { + void setSecondKey(String secondKey) { this.secondKey = secondKey; } - public void setLabel(String label) { + void setLabel(String label) { this.label = label; } @@ -174,4 +169,3 @@ class CreateInstanceWithCustomParametersMappingComponentTest extends WiremockCom } } - diff --git a/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithCustomTargetComponentTest.java b/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithCustomTargetComponentTests.java similarity index 64% rename from spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithCustomTargetComponentTest.java rename to spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithCustomTargetComponentTests.java index 34b5436..2b41d65 100644 --- a/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithCustomTargetComponentTest.java +++ b/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithCustomTargetComponentTests.java @@ -38,25 +38,23 @@ import static io.restassured.RestAssured.given; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; -import static org.springframework.cloud.appbroker.integration.CreateInstanceWithCustomTargetComponentTest.APP_NAME; -import static org.springframework.cloud.appbroker.integration.CreateInstanceWithCustomTargetComponentTest.BACKING_SERVICE_NAME; -import static org.springframework.cloud.appbroker.integration.CreateInstanceWithCustomTargetComponentTest.BACKING_SI_NAME; +import static org.springframework.cloud.appbroker.integration.CreateInstanceWithCustomTargetComponentTests.APP_NAME; +import static org.springframework.cloud.appbroker.integration.CreateInstanceWithCustomTargetComponentTests.BACKING_SERVICE_NAME; +import static org.springframework.cloud.appbroker.integration.CreateInstanceWithCustomTargetComponentTests.BACKING_SI_NAME; -@TestPropertySource(properties = { - "spring.cloud.appbroker.services[0].service-name=example", - "spring.cloud.appbroker.services[0].plan-name=standard", - "spring.cloud.appbroker.services[0].apps[0].path=classpath:demo.jar", - "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME, - "spring.cloud.appbroker.services[0].apps[0].services[0].service-instance-name=" + BACKING_SI_NAME, +@TestPropertySource(properties = { "spring.cloud.appbroker.services[0].service-name=example", + "spring.cloud.appbroker.services[0].plan-name=standard", + "spring.cloud.appbroker.services[0].apps[0].path=classpath:demo.jar", + "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME, + "spring.cloud.appbroker.services[0].apps[0].services[0].service-instance-name=" + BACKING_SI_NAME, - "spring.cloud.appbroker.services[0].services[0].service-instance-name=" + BACKING_SI_NAME, - "spring.cloud.appbroker.services[0].services[0].name=" + BACKING_SERVICE_NAME, - "spring.cloud.appbroker.services[0].services[0].plan=standard", + "spring.cloud.appbroker.services[0].services[0].service-instance-name=" + BACKING_SI_NAME, + "spring.cloud.appbroker.services[0].services[0].name=" + BACKING_SERVICE_NAME, + "spring.cloud.appbroker.services[0].services[0].plan=standard", - "spring.cloud.appbroker.services[0].target.name=CustomSpaceTarget" -}) -@ContextConfiguration(classes = CreateInstanceWithCustomTargetComponentTest.CustomConfig.class) -class CreateInstanceWithCustomTargetComponentTest extends WiremockComponentTest { + "spring.cloud.appbroker.services[0].target.name=CustomSpaceTarget" }) +@ContextConfiguration(classes = CreateInstanceWithCustomTargetComponentTests.CustomConfig.class) +class CreateInstanceWithCustomTargetComponentTests extends WiremockComponentTests { protected static final String APP_NAME = "app-new-services-target"; @@ -78,36 +76,34 @@ class CreateInstanceWithCustomTargetComponentTest extends WiremockComponentTest String customSpace = "my-space"; String customSpaceGuid = "my-space-guid"; - cloudControllerFixture.stubFindTestOrg(); - cloudControllerFixture.stubFindSpaceV3(customSpace, customSpaceGuid); - cloudControllerFixture.stubCreateSpace(customSpace, customSpaceGuid); - cloudControllerFixture.stubAssociatePermissions(); - cloudControllerFixture.stubPushApp(APP_NAME); + this.cloudControllerFixture.stubFindTestOrg(); + this.cloudControllerFixture.stubFindSpaceV3(customSpace, customSpaceGuid); + this.cloudControllerFixture.stubCreateSpace(customSpace, customSpaceGuid); + this.cloudControllerFixture.stubAssociatePermissions(); + this.cloudControllerFixture.stubPushApp(APP_NAME); // given services are available in the marketplace - cloudControllerFixture.stubServiceExistsInSpace(BACKING_SERVICE_NAME, BACKING_PLAN_NAME, customSpaceGuid); + this.cloudControllerFixture.stubServiceExistsInSpace(BACKING_SERVICE_NAME, BACKING_PLAN_NAME, customSpaceGuid); // will create and bind the service instance - cloudControllerFixture.stubCreateServiceInstance(BACKING_SI_NAME); - cloudControllerFixture.stubCreateServiceBinding(APP_NAME, BACKING_SI_NAME); - cloudControllerFixture.stubServiceInstanceExistsInSpace(BACKING_SI_NAME, customSpaceGuid); + this.cloudControllerFixture.stubCreateServiceInstance(BACKING_SI_NAME); + this.cloudControllerFixture.stubCreateServiceBinding(APP_NAME, BACKING_SI_NAME); + this.cloudControllerFixture.stubServiceInstanceExistsInSpace(BACKING_SI_NAME, customSpaceGuid); // when a service instance is created - given(brokerFixture.serviceInstanceRequest()) - .when() - .put(brokerFixture.createServiceInstanceUrl(), serviceInstanceId) + given(this.brokerFixture.serviceInstanceRequest()).when() + .put(this.brokerFixture.createServiceInstanceUrl(), serviceInstanceId) .then() .statusCode(HttpStatus.ACCEPTED.value()); // when the "last_operation" API is polled - given(brokerFixture.serviceInstanceRequest()) - .when() - .get(brokerFixture.getLastInstanceOperationUrl(), serviceInstanceId) + given(this.brokerFixture.serviceInstanceRequest()).when() + .get(this.brokerFixture.getLastInstanceOperationUrl(), serviceInstanceId) .then() .statusCode(HttpStatus.OK.value()) .body("state", is(equalTo(OperationState.IN_PROGRESS.toString()))); - String state = brokerFixture.waitForAsyncOperationComplete(serviceInstanceId); + String state = this.brokerFixture.waitForAsyncOperationComplete(serviceInstanceId); assertThat(state).isEqualTo(OperationState.SUCCEEDED.toString()); } @@ -128,7 +124,7 @@ class CreateInstanceWithCustomTargetComponentTest extends WiremockComponentTest private final CustomSpaceService customSpaceService; - public CustomSpaceTarget(CustomSpaceService customSpaceService) { + CustomSpaceTarget(CustomSpaceService customSpaceService) { super(Config.class); this.customSpaceService = customSpaceService; } @@ -139,16 +135,14 @@ class CreateInstanceWithCustomTargetComponentTest extends WiremockComponentTest } private ArtifactDetails apply(Map properties, String name, String serviceInstanceId) { - String space = customSpaceService.retrieveSpaceName(); + String space = this.customSpaceService.retrieveSpaceName(); properties.put(DeploymentProperties.TARGET_PROPERTY_KEY, space); - return ArtifactDetails.builder() - .name(name) - .properties(properties) - .build(); + return ArtifactDetails.builder().name(name).properties(properties).build(); } public static class Config { + } } diff --git a/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithEnvironmentComponentTest.java b/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithEnvironmentComponentTests.java similarity index 52% rename from spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithEnvironmentComponentTest.java rename to spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithEnvironmentComponentTests.java index 279626d..62684b6 100644 --- a/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithEnvironmentComponentTest.java +++ b/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithEnvironmentComponentTests.java @@ -30,23 +30,21 @@ import static io.restassured.RestAssured.given; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; -import static org.springframework.cloud.appbroker.integration.CreateInstanceWithEnvironmentComponentTest.APP_NAME_1; -import static org.springframework.cloud.appbroker.integration.CreateInstanceWithEnvironmentComponentTest.APP_NAME_2; +import static org.springframework.cloud.appbroker.integration.CreateInstanceWithEnvironmentComponentTests.APP_NAME_1; +import static org.springframework.cloud.appbroker.integration.CreateInstanceWithEnvironmentComponentTests.APP_NAME_2; -@TestPropertySource(properties = { - "spring.cloud.appbroker.services[0].service-name=example", - "spring.cloud.appbroker.services[0].plan-name=standard", - "spring.cloud.appbroker.services[0].apps[0].path=classpath:demo.jar", - "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME_1, - "spring.cloud.appbroker.services[0].apps[0].environment.ENV_VAR_1=value1", - "spring.cloud.appbroker.services[0].apps[0].environment.ENV_VAR_2=true", - "spring.cloud.appbroker.services[0].apps[1].path=classpath:demo.jar", - "spring.cloud.appbroker.services[0].apps[1].name=" + APP_NAME_2, - "spring.cloud.appbroker.services[0].apps[1].properties.use-spring-application-json=false", - "spring.cloud.appbroker.services[0].apps[1].environment.ENV_VAR_3=value3", - "spring.cloud.appbroker.services[0].apps[1].environment.ENV_VAR_4=true" -}) -class CreateInstanceWithEnvironmentComponentTest extends WiremockComponentTest { +@TestPropertySource(properties = { "spring.cloud.appbroker.services[0].service-name=example", + "spring.cloud.appbroker.services[0].plan-name=standard", + "spring.cloud.appbroker.services[0].apps[0].path=classpath:demo.jar", + "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME_1, + "spring.cloud.appbroker.services[0].apps[0].environment.ENV_VAR_1=value1", + "spring.cloud.appbroker.services[0].apps[0].environment.ENV_VAR_2=true", + "spring.cloud.appbroker.services[0].apps[1].path=classpath:demo.jar", + "spring.cloud.appbroker.services[0].apps[1].name=" + APP_NAME_2, + "spring.cloud.appbroker.services[0].apps[1].properties.use-spring-application-json=false", + "spring.cloud.appbroker.services[0].apps[1].environment.ENV_VAR_3=value3", + "spring.cloud.appbroker.services[0].apps[1].environment.ENV_VAR_4=true" }) +class CreateInstanceWithEnvironmentComponentTests extends WiremockComponentTests { protected static final String APP_NAME_1 = "app-with-env1"; @@ -60,33 +58,31 @@ class CreateInstanceWithEnvironmentComponentTest extends WiremockComponentTest { @Test void pushAppWithEnvironmentVariables() { - cloudControllerFixture.stubFindSpaceV3(); - cloudControllerFixture.stubAppDoesNotExist(APP_NAME_1); - cloudControllerFixture.stubPushApp(APP_NAME_1, - matchingJsonPath("$.environment_json[?(@.SPRING_APPLICATION_JSON =~ /.*ENV_VAR_1.*:.*value1.*/)]"), - matchingJsonPath("$.environment_json[?(@.SPRING_APPLICATION_JSON =~ /.*ENV_VAR_2.*:.*true.*/)]")); + this.cloudControllerFixture.stubFindSpaceV3(); + this.cloudControllerFixture.stubAppDoesNotExist(APP_NAME_1); + this.cloudControllerFixture.stubPushApp(APP_NAME_1, + matchingJsonPath("$.environment_json[?(@.SPRING_APPLICATION_JSON =~ /.*ENV_VAR_1.*:.*value1.*/)]"), + matchingJsonPath("$.environment_json[?(@.SPRING_APPLICATION_JSON =~ /.*ENV_VAR_2.*:.*true.*/)]")); - cloudControllerFixture.stubAppDoesNotExist(APP_NAME_2); - cloudControllerFixture.stubPushApp(APP_NAME_2, - matchingJsonPath("$.environment_json[?(@.ENV_VAR_3 == 'value3')]"), - matchingJsonPath("$.environment_json[?(@.ENV_VAR_4 == 'true')]")); + this.cloudControllerFixture.stubAppDoesNotExist(APP_NAME_2); + this.cloudControllerFixture.stubPushApp(APP_NAME_2, + matchingJsonPath("$.environment_json[?(@.ENV_VAR_3 == 'value3')]"), + matchingJsonPath("$.environment_json[?(@.ENV_VAR_4 == 'true')]")); // when a service instance is created - given(brokerFixture.serviceInstanceRequest()) - .when() - .put(brokerFixture.createServiceInstanceUrl(), "instance-id") + given(this.brokerFixture.serviceInstanceRequest()).when() + .put(this.brokerFixture.createServiceInstanceUrl(), "instance-id") .then() .statusCode(HttpStatus.ACCEPTED.value()); // when the "last_operation" API is polled - given(brokerFixture.serviceInstanceRequest()) - .when() - .get(brokerFixture.getLastInstanceOperationUrl(), "instance-id") + given(this.brokerFixture.serviceInstanceRequest()).when() + .get(this.brokerFixture.getLastInstanceOperationUrl(), "instance-id") .then() .statusCode(HttpStatus.OK.value()) .body("state", is(equalTo(OperationState.IN_PROGRESS.toString()))); - String state = brokerFixture.waitForAsyncOperationComplete("instance-id"); + String state = this.brokerFixture.waitForAsyncOperationComplete("instance-id"); assertThat(state).isEqualTo(OperationState.SUCCEEDED.toString()); } diff --git a/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithExistingServicesComponentTest.java b/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithExistingServicesComponentTests.java similarity index 59% rename from spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithExistingServicesComponentTest.java rename to spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithExistingServicesComponentTests.java index 4890d5a..6cbfa7e 100644 --- a/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithExistingServicesComponentTest.java +++ b/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithExistingServicesComponentTests.java @@ -29,19 +29,17 @@ import static io.restassured.RestAssured.given; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; -import static org.springframework.cloud.appbroker.integration.CreateInstanceWithExistingServicesComponentTest.APP_NAME; -import static org.springframework.cloud.appbroker.integration.CreateInstanceWithExistingServicesComponentTest.BACKING_SI_1_NAME; -import static org.springframework.cloud.appbroker.integration.CreateInstanceWithExistingServicesComponentTest.BACKING_SI_2_NAME; +import static org.springframework.cloud.appbroker.integration.CreateInstanceWithExistingServicesComponentTests.APP_NAME; +import static org.springframework.cloud.appbroker.integration.CreateInstanceWithExistingServicesComponentTests.BACKING_SI_1_NAME; +import static org.springframework.cloud.appbroker.integration.CreateInstanceWithExistingServicesComponentTests.BACKING_SI_2_NAME; -@TestPropertySource(properties = { - "spring.cloud.appbroker.services[0].service-name=example", - "spring.cloud.appbroker.services[0].plan-name=standard", - "spring.cloud.appbroker.services[0].apps[0].path=classpath:demo.jar", - "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME, - "spring.cloud.appbroker.services[0].apps[0].services[0].service-instance-name=" + BACKING_SI_1_NAME, - "spring.cloud.appbroker.services[0].apps[0].services[1].service-instance-name=" + BACKING_SI_2_NAME -}) -class CreateInstanceWithExistingServicesComponentTest extends WiremockComponentTest { +@TestPropertySource(properties = { "spring.cloud.appbroker.services[0].service-name=example", + "spring.cloud.appbroker.services[0].plan-name=standard", + "spring.cloud.appbroker.services[0].apps[0].path=classpath:demo.jar", + "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME, + "spring.cloud.appbroker.services[0].apps[0].services[0].service-instance-name=" + BACKING_SI_1_NAME, + "spring.cloud.appbroker.services[0].apps[0].services[1].service-instance-name=" + BACKING_SI_2_NAME }) +class CreateInstanceWithExistingServicesComponentTests extends WiremockComponentTests { protected static final String APP_NAME = "app-with-services"; @@ -57,33 +55,31 @@ class CreateInstanceWithExistingServicesComponentTest extends WiremockComponentT @Test void pushAppWithServicesWhenServicesExist() { - cloudControllerFixture.stubFindSpaceV3(); - cloudControllerFixture.stubAppDoesNotExist(APP_NAME); - cloudControllerFixture.stubPushApp(APP_NAME); + this.cloudControllerFixture.stubFindSpaceV3(); + this.cloudControllerFixture.stubAppDoesNotExist(APP_NAME); + this.cloudControllerFixture.stubPushApp(APP_NAME); // given that service instances exist - cloudControllerFixture.stubServiceInstanceExists(BACKING_SI_1_NAME); - cloudControllerFixture.stubServiceInstanceExists(BACKING_SI_2_NAME); + this.cloudControllerFixture.stubServiceInstanceExists(BACKING_SI_1_NAME); + this.cloudControllerFixture.stubServiceInstanceExists(BACKING_SI_2_NAME); - cloudControllerFixture.stubCreateServiceBinding(APP_NAME, BACKING_SI_1_NAME); - cloudControllerFixture.stubCreateServiceBinding(APP_NAME, BACKING_SI_2_NAME); + this.cloudControllerFixture.stubCreateServiceBinding(APP_NAME, BACKING_SI_1_NAME); + this.cloudControllerFixture.stubCreateServiceBinding(APP_NAME, BACKING_SI_2_NAME); // when a service instance is created - given(brokerFixture.serviceInstanceRequest()) - .when() - .put(brokerFixture.createServiceInstanceUrl(), "instance-id") + given(this.brokerFixture.serviceInstanceRequest()).when() + .put(this.brokerFixture.createServiceInstanceUrl(), "instance-id") .then() .statusCode(HttpStatus.ACCEPTED.value()); // when the "last_operation" API is polled - given(brokerFixture.serviceInstanceRequest()) - .when() - .get(brokerFixture.getLastInstanceOperationUrl(), "instance-id") + given(this.brokerFixture.serviceInstanceRequest()).when() + .get(this.brokerFixture.getLastInstanceOperationUrl(), "instance-id") .then() .statusCode(HttpStatus.OK.value()) .body("state", is(equalTo(OperationState.IN_PROGRESS.toString()))); - String state = brokerFixture.waitForAsyncOperationComplete("instance-id"); + String state = this.brokerFixture.waitForAsyncOperationComplete("instance-id"); assertThat(state).isEqualTo(OperationState.SUCCEEDED.toString()); } diff --git a/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithOnlyABackingServiceComponentTest.java b/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithOnlyABackingServiceComponentTests.java similarity index 67% rename from spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithOnlyABackingServiceComponentTest.java rename to spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithOnlyABackingServiceComponentTests.java index 4f8d27b..de5b852 100644 --- a/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithOnlyABackingServiceComponentTest.java +++ b/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithOnlyABackingServiceComponentTests.java @@ -29,17 +29,15 @@ import static io.restassured.RestAssured.given; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; -import static org.springframework.cloud.appbroker.integration.CreateInstanceWithServicesComponentTest.BACKING_SERVICE_NAME; -import static org.springframework.cloud.appbroker.integration.CreateInstanceWithServicesComponentTest.BACKING_SI_NAME; +import static org.springframework.cloud.appbroker.integration.CreateInstanceWithServicesComponentTests.BACKING_SERVICE_NAME; +import static org.springframework.cloud.appbroker.integration.CreateInstanceWithServicesComponentTests.BACKING_SI_NAME; -@TestPropertySource(properties = { - "spring.cloud.appbroker.services[0].service-name=example", - "spring.cloud.appbroker.services[0].plan-name=standard", - "spring.cloud.appbroker.services[0].services[0].service-instance-name=" + BACKING_SI_NAME, - "spring.cloud.appbroker.services[0].services[0].name=" + BACKING_SERVICE_NAME, - "spring.cloud.appbroker.services[0].services[0].plan=standard" -}) -class CreateInstanceWithOnlyABackingServiceComponentTest extends WiremockComponentTest { +@TestPropertySource(properties = { "spring.cloud.appbroker.services[0].service-name=example", + "spring.cloud.appbroker.services[0].plan-name=standard", + "spring.cloud.appbroker.services[0].services[0].service-instance-name=" + BACKING_SI_NAME, + "spring.cloud.appbroker.services[0].services[0].name=" + BACKING_SERVICE_NAME, + "spring.cloud.appbroker.services[0].services[0].plan=standard" }) +class CreateInstanceWithOnlyABackingServiceComponentTests extends WiremockComponentTests { protected static final String APP_NAME = "app-with-new-services"; @@ -57,29 +55,27 @@ class CreateInstanceWithOnlyABackingServiceComponentTest extends WiremockCompone @Test void createsServicesWhenOnlyBackingServiceIsRequested() { - cloudControllerFixture.stubFindSpaceV3(); + this.cloudControllerFixture.stubFindSpaceV3(); // given services are available in the marketplace - cloudControllerFixture.stubServiceExists(BACKING_SERVICE_NAME, BACKING_PLAN_NAME); + this.cloudControllerFixture.stubServiceExists(BACKING_SERVICE_NAME, BACKING_PLAN_NAME); // will create the service instance - cloudControllerFixture.stubCreateServiceInstance(BACKING_SI_NAME); + this.cloudControllerFixture.stubCreateServiceInstance(BACKING_SI_NAME); // when a service instance is created - given(brokerFixture.serviceInstanceRequest()) - .when() - .put(brokerFixture.createServiceInstanceUrl(), "instance-id") + given(this.brokerFixture.serviceInstanceRequest()).when() + .put(this.brokerFixture.createServiceInstanceUrl(), "instance-id") .then() .statusCode(HttpStatus.ACCEPTED.value()); // when the "last_operation" API is polled - given(brokerFixture.serviceInstanceRequest()) - .when() - .get(brokerFixture.getLastInstanceOperationUrl(), "instance-id") + given(this.brokerFixture.serviceInstanceRequest()).when() + .get(this.brokerFixture.getLastInstanceOperationUrl(), "instance-id") .then() .statusCode(HttpStatus.OK.value()) .body("state", is(equalTo(OperationState.IN_PROGRESS.toString()))); - String state = brokerFixture.waitForAsyncOperationComplete("instance-id"); + String state = this.brokerFixture.waitForAsyncOperationComplete("instance-id"); assertThat(state).isEqualTo(OperationState.SUCCEEDED.toString()); } diff --git a/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithParametersMappingComponentTest.java b/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithParametersMappingComponentTests.java similarity index 54% rename from spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithParametersMappingComponentTest.java rename to spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithParametersMappingComponentTests.java index a2ad2bd..07ad71e 100644 --- a/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithParametersMappingComponentTest.java +++ b/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithParametersMappingComponentTests.java @@ -33,22 +33,20 @@ import static io.restassured.RestAssured.given; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; -import static org.springframework.cloud.appbroker.integration.CreateInstanceWithParametersMappingComponentTest.APP_NAME; +import static org.springframework.cloud.appbroker.integration.CreateInstanceWithParametersMappingComponentTests.APP_NAME; -@TestPropertySource(properties = { - "spring.cloud.appbroker.services[0].service-name=example", - "spring.cloud.appbroker.services[0].plan-name=standard", - "spring.cloud.appbroker.services[0].apps[0].path=classpath:demo.jar", - "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME, - "spring.cloud.appbroker.services[0].apps[0].environment.parameter1=config1", - "spring.cloud.appbroker.services[0].apps[0].environment.parameter2=false", - "spring.cloud.appbroker.services[0].apps[0].environment.parameter3=config3", - "spring.cloud.appbroker.services[0].apps[0].parameters-transformers[0].name=EnvironmentMapping", - "spring.cloud.appbroker.services[0].apps[0].parameters-transformers[0].args.include=parameter1,parameter2", - "spring.cloud.appbroker.services[0].apps[0].parameters-transformers[1].name=PropertyMapping", - "spring.cloud.appbroker.services[0].apps[0].parameters-transformers[1].args.include=count,memory" -}) -class CreateInstanceWithParametersMappingComponentTest extends WiremockComponentTest { +@TestPropertySource(properties = { "spring.cloud.appbroker.services[0].service-name=example", + "spring.cloud.appbroker.services[0].plan-name=standard", + "spring.cloud.appbroker.services[0].apps[0].path=classpath:demo.jar", + "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME, + "spring.cloud.appbroker.services[0].apps[0].environment.parameter1=config1", + "spring.cloud.appbroker.services[0].apps[0].environment.parameter2=false", + "spring.cloud.appbroker.services[0].apps[0].environment.parameter3=config3", + "spring.cloud.appbroker.services[0].apps[0].parameters-transformers[0].name=EnvironmentMapping", + "spring.cloud.appbroker.services[0].apps[0].parameters-transformers[0].args.include=parameter1,parameter2", + "spring.cloud.appbroker.services[0].apps[0].parameters-transformers[1].name=PropertyMapping", + "spring.cloud.appbroker.services[0].apps[0].parameters-transformers[1].args.include=count,memory" }) +class CreateInstanceWithParametersMappingComponentTests extends WiremockComponentTests { protected static final String APP_NAME = "app-with-env-create-params"; @@ -60,14 +58,13 @@ class CreateInstanceWithParametersMappingComponentTest extends WiremockComponent @Test void pushAppWithParametersTransformedToEnvironmentVariables() { - cloudControllerFixture.stubFindSpaceV3(); - cloudControllerFixture.stubAppDoesNotExist(APP_NAME); - cloudControllerFixture.stubPushApp(APP_NAME, - matchingJsonPath("$.environment_json[?(@.SPRING_APPLICATION_JSON =~ /.*parameter1.*:.*value1.*/)]"), - matchingJsonPath("$.environment_json[?(@.SPRING_APPLICATION_JSON =~ /.*parameter2.*:.*true.*/)]"), - matchingJsonPath("$.environment_json[?(@.SPRING_APPLICATION_JSON =~ /.*parameter3.*:.*config3.*/)]"), - matchingJsonPath("$.[?(@.instances == '2')]"), - matchingJsonPath("$.[?(@.memory == '2048')]")); + this.cloudControllerFixture.stubFindSpaceV3(); + this.cloudControllerFixture.stubAppDoesNotExist(APP_NAME); + this.cloudControllerFixture.stubPushApp(APP_NAME, + matchingJsonPath("$.environment_json[?(@.SPRING_APPLICATION_JSON =~ /.*parameter1.*:.*value1.*/)]"), + matchingJsonPath("$.environment_json[?(@.SPRING_APPLICATION_JSON =~ /.*parameter2.*:.*true.*/)]"), + matchingJsonPath("$.environment_json[?(@.SPRING_APPLICATION_JSON =~ /.*parameter3.*:.*config3.*/)]"), + matchingJsonPath("$.[?(@.instances == '2')]"), matchingJsonPath("$.[?(@.memory == '2048')]")); // given a set of parameters Map params = new HashMap<>(); @@ -78,21 +75,19 @@ class CreateInstanceWithParametersMappingComponentTest extends WiremockComponent params.put("memory", "2G"); // when a service instance is created - given(brokerFixture.serviceInstanceRequest(params)) - .when() - .put(brokerFixture.createServiceInstanceUrl(), "instance-id") + given(this.brokerFixture.serviceInstanceRequest(params)).when() + .put(this.brokerFixture.createServiceInstanceUrl(), "instance-id") .then() .statusCode(HttpStatus.ACCEPTED.value()); // when the "last_operation" API is polled - given(brokerFixture.serviceInstanceRequest()) - .when() - .get(brokerFixture.getLastInstanceOperationUrl(), "instance-id") + given(this.brokerFixture.serviceInstanceRequest()).when() + .get(this.brokerFixture.getLastInstanceOperationUrl(), "instance-id") .then() .statusCode(HttpStatus.OK.value()) .body("state", is(equalTo(OperationState.IN_PROGRESS.toString()))); - String state = brokerFixture.waitForAsyncOperationComplete("instance-id"); + String state = this.brokerFixture.waitForAsyncOperationComplete("instance-id"); assertThat(state).isEqualTo(OperationState.SUCCEEDED.toString()); } diff --git a/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithPropertiesComponentTest.java b/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithPropertiesComponentTests.java similarity index 53% rename from spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithPropertiesComponentTest.java rename to spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithPropertiesComponentTests.java index 20bdc6f..2b51a87 100644 --- a/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithPropertiesComponentTest.java +++ b/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithPropertiesComponentTests.java @@ -30,22 +30,20 @@ import static io.restassured.RestAssured.given; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; -import static org.springframework.cloud.appbroker.integration.CreateInstanceWithPropertiesComponentTest.APP_NAME; +import static org.springframework.cloud.appbroker.integration.CreateInstanceWithPropertiesComponentTests.APP_NAME; -@TestPropertySource(properties = { - "spring.cloud.appbroker.deployer.cloudfoundry.properties.memory=1G", - "spring.cloud.appbroker.deployer.cloudfoundry.properties.count=1", - "spring.cloud.appbroker.deployer.cloudfoundry.properties.health-check=http", - "spring.cloud.appbroker.deployer.cloudfoundry.properties.health-check-http-endpoint=/myhealth", - "spring.cloud.appbroker.services[0].service-name=example", - "spring.cloud.appbroker.services[0].plan-name=standard", - "spring.cloud.appbroker.services[0].apps[0].path=classpath:demo.jar", - "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME, - "spring.cloud.appbroker.services[0].apps[0].properties.memory=2G", - "spring.cloud.appbroker.services[0].apps[0].properties.count=2", - "spring.cloud.appbroker.services[0].apps[0].properties.health-check-timeout=180" -}) -class CreateInstanceWithPropertiesComponentTest extends WiremockComponentTest { +@TestPropertySource(properties = { "spring.cloud.appbroker.deployer.cloudfoundry.properties.memory=1G", + "spring.cloud.appbroker.deployer.cloudfoundry.properties.count=1", + "spring.cloud.appbroker.deployer.cloudfoundry.properties.health-check=http", + "spring.cloud.appbroker.deployer.cloudfoundry.properties.health-check-http-endpoint=/myhealth", + "spring.cloud.appbroker.services[0].service-name=example", + "spring.cloud.appbroker.services[0].plan-name=standard", + "spring.cloud.appbroker.services[0].apps[0].path=classpath:demo.jar", + "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME, + "spring.cloud.appbroker.services[0].apps[0].properties.memory=2G", + "spring.cloud.appbroker.services[0].apps[0].properties.count=2", + "spring.cloud.appbroker.services[0].apps[0].properties.health-check-timeout=180" }) +class CreateInstanceWithPropertiesComponentTests extends WiremockComponentTests { protected static final String APP_NAME = "app-with-properties"; @@ -57,31 +55,28 @@ class CreateInstanceWithPropertiesComponentTest extends WiremockComponentTest { @Test void pushAppWithProperties() { - cloudControllerFixture.stubFindSpaceV3(); - cloudControllerFixture.stubAppDoesNotExist(APP_NAME); - cloudControllerFixture.stubPushApp(APP_NAME, - matchingJsonPath("$.[?(@.memory == '2048')]"), - matchingJsonPath("$.[?(@.instances == '2')]"), - matchingJsonPath("$.[?(@.health_check_timeout == '180')]"), - matchingJsonPath("$.[?(@.health_check_type == 'http')]"), - matchingJsonPath("$.[?(@.health_check_http_endpoint == '/myhealth')]")); + this.cloudControllerFixture.stubFindSpaceV3(); + this.cloudControllerFixture.stubAppDoesNotExist(APP_NAME); + this.cloudControllerFixture.stubPushApp(APP_NAME, matchingJsonPath("$.[?(@.memory == '2048')]"), + matchingJsonPath("$.[?(@.instances == '2')]"), + matchingJsonPath("$.[?(@.health_check_timeout == '180')]"), + matchingJsonPath("$.[?(@.health_check_type == 'http')]"), + matchingJsonPath("$.[?(@.health_check_http_endpoint == '/myhealth')]")); // when a service instance is created - given(brokerFixture.serviceInstanceRequest()) - .when() - .put(brokerFixture.createServiceInstanceUrl(), "instance-id") + given(this.brokerFixture.serviceInstanceRequest()).when() + .put(this.brokerFixture.createServiceInstanceUrl(), "instance-id") .then() .statusCode(HttpStatus.ACCEPTED.value()); // when the "last_operation" API is polled - given(brokerFixture.serviceInstanceRequest()) - .when() - .get(brokerFixture.getLastInstanceOperationUrl(), "instance-id") + given(this.brokerFixture.serviceInstanceRequest()).when() + .get(this.brokerFixture.getLastInstanceOperationUrl(), "instance-id") .then() .statusCode(HttpStatus.OK.value()) .body("state", is(equalTo(OperationState.IN_PROGRESS.toString()))); - String state = brokerFixture.waitForAsyncOperationComplete("instance-id"); + String state = this.brokerFixture.waitForAsyncOperationComplete("instance-id"); assertThat(state).isEqualTo(OperationState.SUCCEEDED.toString()); } diff --git a/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithServiceInstanceGuidSuffixTargetComponentTest.java b/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithServiceInstanceGuidSuffixTargetComponentTests.java similarity index 56% rename from spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithServiceInstanceGuidSuffixTargetComponentTest.java rename to spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithServiceInstanceGuidSuffixTargetComponentTests.java index dcd5d6d..d75fe7a 100644 --- a/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithServiceInstanceGuidSuffixTargetComponentTest.java +++ b/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithServiceInstanceGuidSuffixTargetComponentTests.java @@ -29,24 +29,22 @@ import static io.restassured.RestAssured.given; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; -import static org.springframework.cloud.appbroker.integration.CreateInstanceWithServiceInstanceGuidSuffixTargetComponentTest.APP_NAME; -import static org.springframework.cloud.appbroker.integration.CreateInstanceWithServiceInstanceGuidSuffixTargetComponentTest.BACKING_SERVICE_NAME; -import static org.springframework.cloud.appbroker.integration.CreateInstanceWithServiceInstanceGuidSuffixTargetComponentTest.BACKING_SI_NAME; +import static org.springframework.cloud.appbroker.integration.CreateInstanceWithServiceInstanceGuidSuffixTargetComponentTests.APP_NAME; +import static org.springframework.cloud.appbroker.integration.CreateInstanceWithServiceInstanceGuidSuffixTargetComponentTests.BACKING_SERVICE_NAME; +import static org.springframework.cloud.appbroker.integration.CreateInstanceWithServiceInstanceGuidSuffixTargetComponentTests.BACKING_SI_NAME; -@TestPropertySource(properties = { - "spring.cloud.appbroker.services[0].service-name=example", - "spring.cloud.appbroker.services[0].plan-name=standard", - "spring.cloud.appbroker.services[0].apps[0].path=classpath:demo.jar", - "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME, - "spring.cloud.appbroker.services[0].apps[0].services[0].service-instance-name=" + BACKING_SI_NAME, +@TestPropertySource(properties = { "spring.cloud.appbroker.services[0].service-name=example", + "spring.cloud.appbroker.services[0].plan-name=standard", + "spring.cloud.appbroker.services[0].apps[0].path=classpath:demo.jar", + "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME, + "spring.cloud.appbroker.services[0].apps[0].services[0].service-instance-name=" + BACKING_SI_NAME, - "spring.cloud.appbroker.services[0].services[0].service-instance-name=" + BACKING_SI_NAME, - "spring.cloud.appbroker.services[0].services[0].name=" + BACKING_SERVICE_NAME, - "spring.cloud.appbroker.services[0].services[0].plan=standard", + "spring.cloud.appbroker.services[0].services[0].service-instance-name=" + BACKING_SI_NAME, + "spring.cloud.appbroker.services[0].services[0].name=" + BACKING_SERVICE_NAME, + "spring.cloud.appbroker.services[0].services[0].plan=standard", - "spring.cloud.appbroker.services[0].target.name=ServiceInstanceGuidSuffix" -}) -class CreateInstanceWithServiceInstanceGuidSuffixTargetComponentTest extends WiremockComponentTest { + "spring.cloud.appbroker.services[0].target.name=ServiceInstanceGuidSuffix" }) +class CreateInstanceWithServiceInstanceGuidSuffixTargetComponentTests extends WiremockComponentTests { protected static final String APP_NAME = "app-with-target"; @@ -68,35 +66,33 @@ class CreateInstanceWithServiceInstanceGuidSuffixTargetComponentTest extends Wir String applicationName = APP_NAME + "-" + serviceInstanceId; String backingServiceInstanceName = BACKING_SI_NAME + "-" + serviceInstanceId; - cloudControllerFixture.stubFindSpaceV3(); - cloudControllerFixture.stubAppDoesNotExist(applicationName); - cloudControllerFixture.stubPushApp(applicationName); + this.cloudControllerFixture.stubFindSpaceV3(); + this.cloudControllerFixture.stubAppDoesNotExist(applicationName); + this.cloudControllerFixture.stubPushApp(applicationName); // given services are available in the marketplace - cloudControllerFixture.stubServiceExists(BACKING_SERVICE_NAME, BACKING_PLAN_NAME); + this.cloudControllerFixture.stubServiceExists(BACKING_SERVICE_NAME, BACKING_PLAN_NAME); // will create and bind the service instance - cloudControllerFixture.stubCreateServiceInstance(backingServiceInstanceName); - cloudControllerFixture.stubCreateServiceBinding(applicationName, backingServiceInstanceName); - cloudControllerFixture.stubServiceInstanceExists(backingServiceInstanceName); + this.cloudControllerFixture.stubCreateServiceInstance(backingServiceInstanceName); + this.cloudControllerFixture.stubCreateServiceBinding(applicationName, backingServiceInstanceName); + this.cloudControllerFixture.stubServiceInstanceExists(backingServiceInstanceName); // when a service instance is created - given(brokerFixture.serviceInstanceRequest()) - .when() - .put(brokerFixture.createServiceInstanceUrl(), "instance-id") + given(this.brokerFixture.serviceInstanceRequest()).when() + .put(this.brokerFixture.createServiceInstanceUrl(), "instance-id") .then() .statusCode(HttpStatus.ACCEPTED.value()); // when the "last_operation" API is polled - given(brokerFixture.serviceInstanceRequest()) - .when() - .get(brokerFixture.getLastInstanceOperationUrl(), "instance-id") + given(this.brokerFixture.serviceInstanceRequest()).when() + .get(this.brokerFixture.getLastInstanceOperationUrl(), "instance-id") .then() .statusCode(HttpStatus.OK.value()) .body("state", is(equalTo(OperationState.IN_PROGRESS.toString()))); // then a new service instance was created - String state = brokerFixture.waitForAsyncOperationComplete("instance-id"); + String state = this.brokerFixture.waitForAsyncOperationComplete("instance-id"); assertThat(state).isEqualTo(OperationState.SUCCEEDED.toString()); // when a second service instance is created @@ -104,31 +100,28 @@ class CreateInstanceWithServiceInstanceGuidSuffixTargetComponentTest extends Wir String otherBackingServiceInstanceName = BACKING_SI_NAME + "-" + otherServiceInstanceId; String otherApplicationName = APP_NAME + "-" + otherServiceInstanceId; - cloudControllerFixture.stubAppDoesNotExist(otherApplicationName); - cloudControllerFixture.stubPushApp(otherApplicationName); + this.cloudControllerFixture.stubAppDoesNotExist(otherApplicationName); + this.cloudControllerFixture.stubPushApp(otherApplicationName); - cloudControllerFixture.stubCreateServiceInstance(otherBackingServiceInstanceName); - cloudControllerFixture.stubCreateServiceBinding(otherApplicationName, otherBackingServiceInstanceName); - cloudControllerFixture.stubServiceInstanceExists(otherBackingServiceInstanceName); + this.cloudControllerFixture.stubCreateServiceInstance(otherBackingServiceInstanceName); + this.cloudControllerFixture.stubCreateServiceBinding(otherApplicationName, otherBackingServiceInstanceName); + this.cloudControllerFixture.stubServiceInstanceExists(otherBackingServiceInstanceName); - given(brokerFixture.serviceInstanceRequest()) - .when() - .put(brokerFixture.createServiceInstanceUrl(), "other-instance-id") + given(this.brokerFixture.serviceInstanceRequest()).when() + .put(this.brokerFixture.createServiceInstanceUrl(), "other-instance-id") .then() .statusCode(HttpStatus.ACCEPTED.value()); // when the "last_operation" API is polled - given(brokerFixture.serviceInstanceRequest()) - .when() - .get(brokerFixture.getLastInstanceOperationUrl(), "other-instance-id") + given(this.brokerFixture.serviceInstanceRequest()).when() + .get(this.brokerFixture.getLastInstanceOperationUrl(), "other-instance-id") .then() .statusCode(HttpStatus.OK.value()) .body("state", is(equalTo(OperationState.IN_PROGRESS.toString()))); // then the second instance was created - String otherState = brokerFixture.waitForAsyncOperationComplete("other-instance-id"); + String otherState = this.brokerFixture.waitForAsyncOperationComplete("other-instance-id"); assertThat(otherState).isEqualTo(OperationState.SUCCEEDED.toString()); } } - diff --git a/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithServicesComponentTest.java b/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithServicesComponentTests.java similarity index 58% rename from spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithServicesComponentTest.java rename to spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithServicesComponentTests.java index b05fd41..c846bd2 100644 --- a/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithServicesComponentTest.java +++ b/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithServicesComponentTests.java @@ -29,21 +29,19 @@ import static io.restassured.RestAssured.given; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; -import static org.springframework.cloud.appbroker.integration.CreateInstanceWithServicesComponentTest.APP_NAME; -import static org.springframework.cloud.appbroker.integration.CreateInstanceWithServicesComponentTest.BACKING_SERVICE_NAME; -import static org.springframework.cloud.appbroker.integration.CreateInstanceWithServicesComponentTest.BACKING_SI_NAME; +import static org.springframework.cloud.appbroker.integration.CreateInstanceWithServicesComponentTests.APP_NAME; +import static org.springframework.cloud.appbroker.integration.CreateInstanceWithServicesComponentTests.BACKING_SERVICE_NAME; +import static org.springframework.cloud.appbroker.integration.CreateInstanceWithServicesComponentTests.BACKING_SI_NAME; -@TestPropertySource(properties = { - "spring.cloud.appbroker.services[0].service-name=example", - "spring.cloud.appbroker.services[0].plan-name=standard", - "spring.cloud.appbroker.services[0].apps[0].path=classpath:demo.jar", - "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME, - "spring.cloud.appbroker.services[0].apps[0].services[0].service-instance-name=" + BACKING_SI_NAME, - "spring.cloud.appbroker.services[0].services[0].service-instance-name=" + BACKING_SI_NAME, - "spring.cloud.appbroker.services[0].services[0].name=" + BACKING_SERVICE_NAME, - "spring.cloud.appbroker.services[0].services[0].plan=standard" -}) -class CreateInstanceWithServicesComponentTest extends WiremockComponentTest { +@TestPropertySource(properties = { "spring.cloud.appbroker.services[0].service-name=example", + "spring.cloud.appbroker.services[0].plan-name=standard", + "spring.cloud.appbroker.services[0].apps[0].path=classpath:demo.jar", + "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME, + "spring.cloud.appbroker.services[0].apps[0].services[0].service-instance-name=" + BACKING_SI_NAME, + "spring.cloud.appbroker.services[0].services[0].service-instance-name=" + BACKING_SI_NAME, + "spring.cloud.appbroker.services[0].services[0].name=" + BACKING_SERVICE_NAME, + "spring.cloud.appbroker.services[0].services[0].plan=standard" }) +class CreateInstanceWithServicesComponentTests extends WiremockComponentTests { protected static final String APP_NAME = "app-with-new-services"; @@ -61,34 +59,32 @@ class CreateInstanceWithServicesComponentTest extends WiremockComponentTest { @Test void pushAppWithServicesWhenServicesExist() { - cloudControllerFixture.stubFindSpaceV3(); - cloudControllerFixture.stubAppDoesNotExist(APP_NAME); - cloudControllerFixture.stubPushApp(APP_NAME); + this.cloudControllerFixture.stubFindSpaceV3(); + this.cloudControllerFixture.stubAppDoesNotExist(APP_NAME); + this.cloudControllerFixture.stubPushApp(APP_NAME); // given services are available in the marketplace - cloudControllerFixture.stubServiceExists(BACKING_SERVICE_NAME, BACKING_PLAN_NAME); + this.cloudControllerFixture.stubServiceExists(BACKING_SERVICE_NAME, BACKING_PLAN_NAME); // will create and bind the service instance - cloudControllerFixture.stubCreateServiceInstance(BACKING_SI_NAME); - cloudControllerFixture.stubCreateServiceBinding(APP_NAME, BACKING_SI_NAME); - cloudControllerFixture.stubServiceInstanceExists(BACKING_SI_NAME); + this.cloudControllerFixture.stubCreateServiceInstance(BACKING_SI_NAME); + this.cloudControllerFixture.stubCreateServiceBinding(APP_NAME, BACKING_SI_NAME); + this.cloudControllerFixture.stubServiceInstanceExists(BACKING_SI_NAME); // when a service instance is created - given(brokerFixture.serviceInstanceRequest()) - .when() - .put(brokerFixture.createServiceInstanceUrl(), "instance-id") + given(this.brokerFixture.serviceInstanceRequest()).when() + .put(this.brokerFixture.createServiceInstanceUrl(), "instance-id") .then() .statusCode(HttpStatus.ACCEPTED.value()); // when the "last_operation" API is polled - given(brokerFixture.serviceInstanceRequest()) - .when() - .get(brokerFixture.getLastInstanceOperationUrl(), "instance-id") + given(this.brokerFixture.serviceInstanceRequest()).when() + .get(this.brokerFixture.getLastInstanceOperationUrl(), "instance-id") .then() .statusCode(HttpStatus.OK.value()) .body("state", is(equalTo(OperationState.IN_PROGRESS.toString()))); - String state = brokerFixture.waitForAsyncOperationComplete("instance-id"); + String state = this.brokerFixture.waitForAsyncOperationComplete("instance-id"); assertThat(state).isEqualTo(OperationState.SUCCEEDED.toString()); } diff --git a/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithServicesParametersComponentTest.java b/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithServicesParametersComponentTests.java similarity index 59% rename from spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithServicesParametersComponentTest.java rename to spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithServicesParametersComponentTests.java index 204a86b..91b3e30 100644 --- a/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithServicesParametersComponentTest.java +++ b/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithServicesParametersComponentTests.java @@ -32,23 +32,21 @@ import static io.restassured.RestAssured.given; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; -import static org.springframework.cloud.appbroker.integration.CreateInstanceWithServicesParametersComponentTest.APP_NAME; -import static org.springframework.cloud.appbroker.integration.CreateInstanceWithServicesParametersComponentTest.BACKING_SERVICE_NAME; -import static org.springframework.cloud.appbroker.integration.CreateInstanceWithServicesParametersComponentTest.BACKING_SI_NAME; +import static org.springframework.cloud.appbroker.integration.CreateInstanceWithServicesParametersComponentTests.APP_NAME; +import static org.springframework.cloud.appbroker.integration.CreateInstanceWithServicesParametersComponentTests.BACKING_SERVICE_NAME; +import static org.springframework.cloud.appbroker.integration.CreateInstanceWithServicesParametersComponentTests.BACKING_SI_NAME; -@TestPropertySource(properties = { - "spring.cloud.appbroker.services[0].service-name=example", - "spring.cloud.appbroker.services[0].plan-name=standard", - "spring.cloud.appbroker.services[0].apps[0].path=classpath:demo.jar", - "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME, - "spring.cloud.appbroker.services[0].apps[0].services[0].service-instance-name=" + BACKING_SI_NAME, - "spring.cloud.appbroker.services[0].services[0].service-instance-name=" + BACKING_SI_NAME, - "spring.cloud.appbroker.services[0].services[0].name=" + BACKING_SERVICE_NAME, - "spring.cloud.appbroker.services[0].services[0].plan=standard", - "spring.cloud.appbroker.services[0].services[0].parameters-transformers[0].name=ParameterMapping", - "spring.cloud.appbroker.services[0].services[0].parameters-transformers[0].args.include=paramA,paramC" -}) -class CreateInstanceWithServicesParametersComponentTest extends WiremockComponentTest { +@TestPropertySource(properties = { "spring.cloud.appbroker.services[0].service-name=example", + "spring.cloud.appbroker.services[0].plan-name=standard", + "spring.cloud.appbroker.services[0].apps[0].path=classpath:demo.jar", + "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME, + "spring.cloud.appbroker.services[0].apps[0].services[0].service-instance-name=" + BACKING_SI_NAME, + "spring.cloud.appbroker.services[0].services[0].service-instance-name=" + BACKING_SI_NAME, + "spring.cloud.appbroker.services[0].services[0].name=" + BACKING_SERVICE_NAME, + "spring.cloud.appbroker.services[0].services[0].plan=standard", + "spring.cloud.appbroker.services[0].services[0].parameters-transformers[0].name=ParameterMapping", + "spring.cloud.appbroker.services[0].services[0].parameters-transformers[0].args.include=paramA,paramC" }) +class CreateInstanceWithServicesParametersComponentTests extends WiremockComponentTests { protected static final String APP_NAME = "app-services-param"; @@ -66,21 +64,22 @@ class CreateInstanceWithServicesParametersComponentTest extends WiremockComponen @Test void pushAppWithBackingServicesParameters() { - cloudControllerFixture.stubFindSpaceV3(); - cloudControllerFixture.stubAppDoesNotExist(APP_NAME); - cloudControllerFixture.stubPushApp(APP_NAME); + this.cloudControllerFixture.stubFindSpaceV3(); + this.cloudControllerFixture.stubAppDoesNotExist(APP_NAME); + this.cloudControllerFixture.stubPushApp(APP_NAME); // given services are available in the marketplace - cloudControllerFixture.stubServiceExists(BACKING_SERVICE_NAME, BACKING_PLAN_NAME); + this.cloudControllerFixture.stubServiceExists(BACKING_SERVICE_NAME, BACKING_PLAN_NAME); // will create with filtered parameters and bind the service instance HashMap expectedCreationParameters = new HashMap<>(); expectedCreationParameters.put("paramA", "valueA"); expectedCreationParameters.put("paramC", Collections.singletonMap("paramC1", "valueC1")); - cloudControllerFixture.stubCreateServiceInstanceWithParameters(BACKING_SI_NAME, expectedCreationParameters); - cloudControllerFixture.stubCreateServiceBinding(APP_NAME, BACKING_SI_NAME); - cloudControllerFixture.stubServiceInstanceExists(BACKING_SI_NAME); + this.cloudControllerFixture.stubCreateServiceInstanceWithParameters(BACKING_SI_NAME, + expectedCreationParameters); + this.cloudControllerFixture.stubCreateServiceBinding(APP_NAME, BACKING_SI_NAME); + this.cloudControllerFixture.stubServiceInstanceExists(BACKING_SI_NAME); // when a service instance is created with parameters HashMap creationParameters = new HashMap<>(); @@ -88,21 +87,19 @@ class CreateInstanceWithServicesParametersComponentTest extends WiremockComponen creationParameters.put("paramB", "valueB"); creationParameters.put("paramC", Collections.singletonMap("paramC1", "valueC1")); - given(brokerFixture.serviceInstanceRequest(creationParameters)) - .when() - .put(brokerFixture.createServiceInstanceUrl(), "instance-id") + given(this.brokerFixture.serviceInstanceRequest(creationParameters)).when() + .put(this.brokerFixture.createServiceInstanceUrl(), "instance-id") .then() .statusCode(HttpStatus.ACCEPTED.value()); // when the "last_operation" API is polled - given(brokerFixture.serviceInstanceRequest()) - .when() - .get(brokerFixture.getLastInstanceOperationUrl(), "instance-id") + given(this.brokerFixture.serviceInstanceRequest()).when() + .get(this.brokerFixture.getLastInstanceOperationUrl(), "instance-id") .then() .statusCode(HttpStatus.OK.value()) .body("state", is(equalTo(OperationState.IN_PROGRESS.toString()))); - String state = brokerFixture.waitForAsyncOperationComplete("instance-id"); + String state = this.brokerFixture.waitForAsyncOperationComplete("instance-id"); assertThat(state).isEqualTo(OperationState.SUCCEEDED.toString()); } diff --git a/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithSpacePerServiceInstanceTargetComponentTest.java b/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithSpacePerServiceInstanceTargetComponentTests.java similarity index 55% rename from spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithSpacePerServiceInstanceTargetComponentTest.java rename to spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithSpacePerServiceInstanceTargetComponentTests.java index 46ea2ad..625b5ab 100644 --- a/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithSpacePerServiceInstanceTargetComponentTest.java +++ b/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/CreateInstanceWithSpacePerServiceInstanceTargetComponentTests.java @@ -29,24 +29,22 @@ import static io.restassured.RestAssured.given; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; -import static org.springframework.cloud.appbroker.integration.CreateInstanceWithSpacePerServiceInstanceTargetComponentTest.APP_NAME; -import static org.springframework.cloud.appbroker.integration.CreateInstanceWithSpacePerServiceInstanceTargetComponentTest.BACKING_SERVICE_NAME; -import static org.springframework.cloud.appbroker.integration.CreateInstanceWithSpacePerServiceInstanceTargetComponentTest.BACKING_SI_NAME; +import static org.springframework.cloud.appbroker.integration.CreateInstanceWithSpacePerServiceInstanceTargetComponentTests.APP_NAME; +import static org.springframework.cloud.appbroker.integration.CreateInstanceWithSpacePerServiceInstanceTargetComponentTests.BACKING_SERVICE_NAME; +import static org.springframework.cloud.appbroker.integration.CreateInstanceWithSpacePerServiceInstanceTargetComponentTests.BACKING_SI_NAME; -@TestPropertySource(properties = { - "spring.cloud.appbroker.services[0].service-name=example", - "spring.cloud.appbroker.services[0].plan-name=standard", - "spring.cloud.appbroker.services[0].apps[0].path=classpath:demo.jar", - "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME, - "spring.cloud.appbroker.services[0].apps[0].services[0].service-instance-name=" + BACKING_SI_NAME, +@TestPropertySource(properties = { "spring.cloud.appbroker.services[0].service-name=example", + "spring.cloud.appbroker.services[0].plan-name=standard", + "spring.cloud.appbroker.services[0].apps[0].path=classpath:demo.jar", + "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME, + "spring.cloud.appbroker.services[0].apps[0].services[0].service-instance-name=" + BACKING_SI_NAME, - "spring.cloud.appbroker.services[0].services[0].service-instance-name=" + BACKING_SI_NAME, - "spring.cloud.appbroker.services[0].services[0].name=" + BACKING_SERVICE_NAME, - "spring.cloud.appbroker.services[0].services[0].plan=standard", + "spring.cloud.appbroker.services[0].services[0].service-instance-name=" + BACKING_SI_NAME, + "spring.cloud.appbroker.services[0].services[0].name=" + BACKING_SERVICE_NAME, + "spring.cloud.appbroker.services[0].services[0].plan=standard", - "spring.cloud.appbroker.services[0].target.name=SpacePerServiceInstance" -}) -class CreateInstanceWithSpacePerServiceInstanceTargetComponentTest extends WiremockComponentTest { + "spring.cloud.appbroker.services[0].target.name=SpacePerServiceInstance" }) +class CreateInstanceWithSpacePerServiceInstanceTargetComponentTests extends WiremockComponentTests { protected static final String APP_NAME = "app-new-services-target"; @@ -67,36 +65,34 @@ class CreateInstanceWithSpacePerServiceInstanceTargetComponentTest extends Wirem String serviceInstanceId = "instance-id"; String backingSpaceGuid = "my-space-guid"; - cloudControllerFixture.stubFindTestOrg(); - cloudControllerFixture.stubFindSpaceV3(serviceInstanceId, backingSpaceGuid); - cloudControllerFixture.stubCreateSpace(serviceInstanceId, backingSpaceGuid); - cloudControllerFixture.stubAssociatePermissions(); - cloudControllerFixture.stubPushAppWithHost(APP_NAME, APP_NAME + "-" + serviceInstanceId); + this.cloudControllerFixture.stubFindTestOrg(); + this.cloudControllerFixture.stubFindSpaceV3(serviceInstanceId, backingSpaceGuid); + this.cloudControllerFixture.stubCreateSpace(serviceInstanceId, backingSpaceGuid); + this.cloudControllerFixture.stubAssociatePermissions(); + this.cloudControllerFixture.stubPushAppWithHost(APP_NAME, APP_NAME + "-" + serviceInstanceId); // given services are available in the marketplace - cloudControllerFixture.stubServiceExistsInSpace(BACKING_SERVICE_NAME, BACKING_PLAN_NAME, backingSpaceGuid); + this.cloudControllerFixture.stubServiceExistsInSpace(BACKING_SERVICE_NAME, BACKING_PLAN_NAME, backingSpaceGuid); // will create and bind the service instance - cloudControllerFixture.stubCreateServiceInstance(BACKING_SI_NAME); - cloudControllerFixture.stubCreateServiceBinding(APP_NAME, BACKING_SI_NAME); - cloudControllerFixture.stubServiceInstanceExistsInSpace(BACKING_SI_NAME, backingSpaceGuid); + this.cloudControllerFixture.stubCreateServiceInstance(BACKING_SI_NAME); + this.cloudControllerFixture.stubCreateServiceBinding(APP_NAME, BACKING_SI_NAME); + this.cloudControllerFixture.stubServiceInstanceExistsInSpace(BACKING_SI_NAME, backingSpaceGuid); // when a service instance is created - given(brokerFixture.serviceInstanceRequest()) - .when() - .put(brokerFixture.createServiceInstanceUrl(), serviceInstanceId) + given(this.brokerFixture.serviceInstanceRequest()).when() + .put(this.brokerFixture.createServiceInstanceUrl(), serviceInstanceId) .then() .statusCode(HttpStatus.ACCEPTED.value()); // when the "last_operation" API is polled - given(brokerFixture.serviceInstanceRequest()) - .when() - .get(brokerFixture.getLastInstanceOperationUrl(), serviceInstanceId) + given(this.brokerFixture.serviceInstanceRequest()).when() + .get(this.brokerFixture.getLastInstanceOperationUrl(), serviceInstanceId) .then() .statusCode(HttpStatus.OK.value()) .body("state", is(equalTo(OperationState.IN_PROGRESS.toString()))); - String state = brokerFixture.waitForAsyncOperationComplete(serviceInstanceId); + String state = this.brokerFixture.waitForAsyncOperationComplete(serviceInstanceId); assertThat(state).isEqualTo(OperationState.SUCCEEDED.toString()); } diff --git a/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/DeleteInstanceComponentTest.java b/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/DeleteInstanceComponentTests.java similarity index 58% rename from spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/DeleteInstanceComponentTest.java rename to spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/DeleteInstanceComponentTests.java index bb91440..12f97d2 100644 --- a/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/DeleteInstanceComponentTest.java +++ b/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/DeleteInstanceComponentTests.java @@ -29,20 +29,18 @@ import static io.restassured.RestAssured.given; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; -import static org.springframework.cloud.appbroker.integration.DeleteInstanceComponentTest.APP_NAME_1; -import static org.springframework.cloud.appbroker.integration.DeleteInstanceComponentTest.APP_NAME_2; -import static org.springframework.cloud.appbroker.integration.DeleteInstanceComponentTest.PLAN_NAME; -import static org.springframework.cloud.appbroker.integration.DeleteInstanceComponentTest.SERVICE_NAME; +import static org.springframework.cloud.appbroker.integration.DeleteInstanceComponentTests.APP_NAME_1; +import static org.springframework.cloud.appbroker.integration.DeleteInstanceComponentTests.APP_NAME_2; +import static org.springframework.cloud.appbroker.integration.DeleteInstanceComponentTests.PLAN_NAME; +import static org.springframework.cloud.appbroker.integration.DeleteInstanceComponentTests.SERVICE_NAME; -@TestPropertySource(properties = { - "spring.cloud.appbroker.services[0].service-name=" + SERVICE_NAME, - "spring.cloud.appbroker.services[0].plan-name=" + PLAN_NAME, - "spring.cloud.appbroker.services[0].apps[0].path=classpath:demo.jar", - "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME_1, - "spring.cloud.appbroker.services[0].apps[1].path=classpath:demo.jar", - "spring.cloud.appbroker.services[0].apps[1].name=" + APP_NAME_2 -}) -class DeleteInstanceComponentTest extends WiremockComponentTest { +@TestPropertySource(properties = { "spring.cloud.appbroker.services[0].service-name=" + SERVICE_NAME, + "spring.cloud.appbroker.services[0].plan-name=" + PLAN_NAME, + "spring.cloud.appbroker.services[0].apps[0].path=classpath:demo.jar", + "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME_1, + "spring.cloud.appbroker.services[0].apps[1].path=classpath:demo.jar", + "spring.cloud.appbroker.services[0].apps[1].name=" + APP_NAME_2 }) +class DeleteInstanceComponentTests extends WiremockComponentTests { protected static final String APP_NAME_1 = "first-app"; @@ -60,56 +58,52 @@ class DeleteInstanceComponentTest extends WiremockComponentTest { @Test void deleteAppsWhenTheyExist() { - cloudControllerFixture.stubAppExistsV3(APP_NAME_1); - cloudControllerFixture.stubAppExistsV3(APP_NAME_2); + this.cloudControllerFixture.stubAppExistsV3(APP_NAME_1); + this.cloudControllerFixture.stubAppExistsV3(APP_NAME_2); - cloudControllerFixture.stubServiceBindingDoesNotExist(APP_NAME_1); - cloudControllerFixture.stubServiceBindingDoesNotExist(APP_NAME_2); + this.cloudControllerFixture.stubServiceBindingDoesNotExist(APP_NAME_1); + this.cloudControllerFixture.stubServiceBindingDoesNotExist(APP_NAME_2); - cloudControllerFixture.stubDeleteApp(APP_NAME_1); - cloudControllerFixture.stubDeleteApp(APP_NAME_2); + this.cloudControllerFixture.stubDeleteApp(APP_NAME_1); + this.cloudControllerFixture.stubDeleteApp(APP_NAME_2); // when the service instance is deleted - given(brokerFixture.serviceInstanceRequest()) - .when() - .delete(brokerFixture.deleteServiceInstanceUrl(), "instance-id") + given(this.brokerFixture.serviceInstanceRequest()).when() + .delete(this.brokerFixture.deleteServiceInstanceUrl(), "instance-id") .then() .statusCode(HttpStatus.ACCEPTED.value()); // when the "last_operation" API is polled - given(brokerFixture.serviceInstanceRequest()) - .when() - .get(brokerFixture.getLastInstanceOperationUrl(), "instance-id") + given(this.brokerFixture.serviceInstanceRequest()).when() + .get(this.brokerFixture.getLastInstanceOperationUrl(), "instance-id") .then() .statusCode(HttpStatus.OK.value()) .body("state", is(equalTo(OperationState.IN_PROGRESS.toString()))); - String state = brokerFixture.waitForAsyncOperationComplete("instance-id"); + String state = this.brokerFixture.waitForAsyncOperationComplete("instance-id"); assertThat(state).isEqualTo(OperationState.SUCCEEDED.toString()); } @Test void deleteAppsWhenTheyDoNotExist() { - cloudControllerFixture.stubFindSpaceV3(); - cloudControllerFixture.stubAppDoesNotExist(APP_NAME_1); - cloudControllerFixture.stubAppDoesNotExist(APP_NAME_2); + this.cloudControllerFixture.stubFindSpaceV3(); + this.cloudControllerFixture.stubAppDoesNotExist(APP_NAME_1); + this.cloudControllerFixture.stubAppDoesNotExist(APP_NAME_2); // when the service instance is deleted - given(brokerFixture.serviceInstanceRequest()) - .when() - .delete(brokerFixture.deleteServiceInstanceUrl(), "instance-id") + given(this.brokerFixture.serviceInstanceRequest()).when() + .delete(this.brokerFixture.deleteServiceInstanceUrl(), "instance-id") .then() .statusCode(HttpStatus.ACCEPTED.value()); // when the "last_operation" API is polled - given(brokerFixture.serviceInstanceRequest()) - .when() - .get(brokerFixture.getLastInstanceOperationUrl(), "instance-id") + given(this.brokerFixture.serviceInstanceRequest()).when() + .get(this.brokerFixture.getLastInstanceOperationUrl(), "instance-id") .then() .statusCode(HttpStatus.OK.value()) .body("state", is(equalTo(OperationState.IN_PROGRESS.toString()))); - String state = brokerFixture.waitForAsyncOperationComplete("instance-id"); + String state = this.brokerFixture.waitForAsyncOperationComplete("instance-id"); assertThat(state).isEqualTo(OperationState.SUCCEEDED.toString()); } diff --git a/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/DeleteInstanceWithAppsAndServicesComponentTest.java b/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/DeleteInstanceWithAppsAndServicesComponentTests.java similarity index 50% rename from spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/DeleteInstanceWithAppsAndServicesComponentTest.java rename to spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/DeleteInstanceWithAppsAndServicesComponentTests.java index f33780c..aa8806a 100644 --- a/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/DeleteInstanceWithAppsAndServicesComponentTest.java +++ b/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/DeleteInstanceWithAppsAndServicesComponentTests.java @@ -30,24 +30,22 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.either; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; -import static org.springframework.cloud.appbroker.integration.DeleteInstanceWithAppsAndServicesComponentTest.APP_NAME; -import static org.springframework.cloud.appbroker.integration.DeleteInstanceWithAppsAndServicesComponentTest.BACKING_PLAN_NAME; -import static org.springframework.cloud.appbroker.integration.DeleteInstanceWithAppsAndServicesComponentTest.BACKING_SERVICE_NAME; -import static org.springframework.cloud.appbroker.integration.DeleteInstanceWithAppsAndServicesComponentTest.BACKING_SI_NAME; -import static org.springframework.cloud.appbroker.integration.DeleteInstanceWithAppsAndServicesComponentTest.PLAN_NAME; -import static org.springframework.cloud.appbroker.integration.DeleteInstanceWithAppsAndServicesComponentTest.SERVICE_NAME; +import static org.springframework.cloud.appbroker.integration.DeleteInstanceWithAppsAndServicesComponentTests.APP_NAME; +import static org.springframework.cloud.appbroker.integration.DeleteInstanceWithAppsAndServicesComponentTests.BACKING_PLAN_NAME; +import static org.springframework.cloud.appbroker.integration.DeleteInstanceWithAppsAndServicesComponentTests.BACKING_SERVICE_NAME; +import static org.springframework.cloud.appbroker.integration.DeleteInstanceWithAppsAndServicesComponentTests.BACKING_SI_NAME; +import static org.springframework.cloud.appbroker.integration.DeleteInstanceWithAppsAndServicesComponentTests.PLAN_NAME; +import static org.springframework.cloud.appbroker.integration.DeleteInstanceWithAppsAndServicesComponentTests.SERVICE_NAME; -@TestPropertySource(properties = { - "spring.cloud.appbroker.services[0].service-name=" + SERVICE_NAME, - "spring.cloud.appbroker.services[0].plan-name=" + PLAN_NAME, - "spring.cloud.appbroker.services[0].apps[0].path=classpath:demo.jar", - "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME, - "spring.cloud.appbroker.services[0].apps[0].services[0].service-instance-name=" + BACKING_SI_NAME, - "spring.cloud.appbroker.services[0].services[0].service-instance-name=" + BACKING_SI_NAME, - "spring.cloud.appbroker.services[0].services[0].name=" + BACKING_SERVICE_NAME, - "spring.cloud.appbroker.services[0].services[0].plan=" + BACKING_PLAN_NAME -}) -class DeleteInstanceWithAppsAndServicesComponentTest extends WiremockComponentTest { +@TestPropertySource(properties = { "spring.cloud.appbroker.services[0].service-name=" + SERVICE_NAME, + "spring.cloud.appbroker.services[0].plan-name=" + PLAN_NAME, + "spring.cloud.appbroker.services[0].apps[0].path=classpath:demo.jar", + "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME, + "spring.cloud.appbroker.services[0].apps[0].services[0].service-instance-name=" + BACKING_SI_NAME, + "spring.cloud.appbroker.services[0].services[0].service-instance-name=" + BACKING_SI_NAME, + "spring.cloud.appbroker.services[0].services[0].name=" + BACKING_SERVICE_NAME, + "spring.cloud.appbroker.services[0].services[0].plan=" + BACKING_PLAN_NAME }) +class DeleteInstanceWithAppsAndServicesComponentTests extends WiremockComponentTests { protected static final String APP_NAME = "app-delete-with-services"; @@ -69,88 +67,82 @@ class DeleteInstanceWithAppsAndServicesComponentTest extends WiremockComponentTe @Test void deleteAppsAndServicesWhenTheyExist() { - cloudControllerFixture.stubFindSpaceV3(); - cloudControllerFixture.stubFindSpace(); - cloudControllerFixture.stubAppExistsWithBackingService(APP_NAME, BACKING_SI_NAME, - BACKING_SERVICE_NAME, BACKING_PLAN_NAME); - cloudControllerFixture.stubServiceBindingDoesNotExist(APP_NAME); - cloudControllerFixture.stubDeleteApp(APP_NAME); + this.cloudControllerFixture.stubFindSpaceV3(); + this.cloudControllerFixture.stubFindSpace(); + this.cloudControllerFixture.stubAppExistsWithBackingService(APP_NAME, BACKING_SI_NAME, BACKING_SERVICE_NAME, + BACKING_PLAN_NAME); + this.cloudControllerFixture.stubServiceBindingDoesNotExist(APP_NAME); + this.cloudControllerFixture.stubDeleteApp(APP_NAME); - cloudControllerFixture.stubGetBackingServiceInstance(BACKING_SI_NAME, BACKING_SERVICE_NAME, BACKING_PLAN_NAME); + this.cloudControllerFixture.stubGetBackingServiceInstance(BACKING_SI_NAME, BACKING_SERVICE_NAME, + BACKING_PLAN_NAME); - cloudControllerFixture.stubServiceBindingExists(APP_NAME, BACKING_SI_NAME); - cloudControllerFixture.stubDeleteServiceBinding(APP_NAME, BACKING_SI_NAME); - cloudControllerFixture.stubDeleteServiceInstance(BACKING_SI_NAME); + this.cloudControllerFixture.stubServiceBindingExists(APP_NAME, BACKING_SI_NAME); + this.cloudControllerFixture.stubDeleteServiceBinding(APP_NAME, BACKING_SI_NAME); + this.cloudControllerFixture.stubDeleteServiceInstance(BACKING_SI_NAME); // when the service instance is deleted - given(brokerFixture.serviceInstanceRequest()) - .when() - .delete(brokerFixture.deleteServiceInstanceUrl(), "instance-id") + given(this.brokerFixture.serviceInstanceRequest()).when() + .delete(this.brokerFixture.deleteServiceInstanceUrl(), "instance-id") .then() .statusCode(HttpStatus.ACCEPTED.value()); // when the "last_operation" API is polled - given(brokerFixture.serviceInstanceRequest()) - .when() - .get(brokerFixture.getLastInstanceOperationUrl(), "instance-id") + given(this.brokerFixture.serviceInstanceRequest()).when() + .get(this.brokerFixture.getLastInstanceOperationUrl(), "instance-id") .then() .statusCode(HttpStatus.OK.value()) .body("state", is(equalTo(OperationState.IN_PROGRESS.toString()))); - String state = brokerFixture.waitForAsyncOperationComplete("instance-id"); + String state = this.brokerFixture.waitForAsyncOperationComplete("instance-id"); assertThat(state).isEqualTo(OperationState.SUCCEEDED.toString()); } @Test void deleteAppsWhenTheyExistAndServicesWhenTheyDoNotExist() { - cloudControllerFixture.stubFindSpace(); - cloudControllerFixture.stubAppExists(APP_NAME); - cloudControllerFixture.stubServiceBindingDoesNotExist(APP_NAME); - cloudControllerFixture.stubDeleteApp(APP_NAME); + this.cloudControllerFixture.stubFindSpace(); + this.cloudControllerFixture.stubAppExists(APP_NAME); + this.cloudControllerFixture.stubServiceBindingDoesNotExist(APP_NAME); + this.cloudControllerFixture.stubDeleteApp(APP_NAME); // when the service instance is deleted - given(brokerFixture.serviceInstanceRequest()) - .when() - .delete(brokerFixture.deleteServiceInstanceUrl(), "instance-id") + given(this.brokerFixture.serviceInstanceRequest()).when() + .delete(this.brokerFixture.deleteServiceInstanceUrl(), "instance-id") .then() .statusCode(HttpStatus.ACCEPTED.value()); // when the "last_operation" API is polled - given(brokerFixture.serviceInstanceRequest()) - .when() - .get(brokerFixture.getLastInstanceOperationUrl(), "instance-id") + given(this.brokerFixture.serviceInstanceRequest()).when() + .get(this.brokerFixture.getLastInstanceOperationUrl(), "instance-id") .then() .statusCode(HttpStatus.OK.value()) .body("state", is(equalTo(OperationState.IN_PROGRESS.toString()))); - String state = brokerFixture.waitForAsyncOperationComplete("instance-id"); + String state = this.brokerFixture.waitForAsyncOperationComplete("instance-id"); assertThat(state).isEqualTo(OperationState.SUCCEEDED.toString()); } @Test void deleteAppsAndServicesWhenTheyDoNotExist() { - cloudControllerFixture.stubFindSpace(); - cloudControllerFixture.stubAppDoesNotExist(APP_NAME); + this.cloudControllerFixture.stubFindSpace(); + this.cloudControllerFixture.stubAppDoesNotExist(APP_NAME); // when the service instance is deleted - given(brokerFixture.serviceInstanceRequest()) - .when() - .delete(brokerFixture.deleteServiceInstanceUrl(), "instance-id") + given(this.brokerFixture.serviceInstanceRequest()).when() + .delete(this.brokerFixture.deleteServiceInstanceUrl(), "instance-id") .then() .statusCode(HttpStatus.ACCEPTED.value()); // when the "last_operation" API is polled - given(brokerFixture.serviceInstanceRequest()) - .when() - .get(brokerFixture.getLastInstanceOperationUrl(), "instance-id") + given(this.brokerFixture.serviceInstanceRequest()).when() + .get(this.brokerFixture.getLastInstanceOperationUrl(), "instance-id") .then() .statusCode(HttpStatus.OK.value()) - .body("state", - either(equalTo(OperationState.IN_PROGRESS.toString())) - // if the error occurs immediately it will return succeeded status - .or(equalTo(OperationState.SUCCEEDED.toString()))); + .body("state", either(equalTo(OperationState.IN_PROGRESS.toString())) + // if the error occurs immediately it will return succeeded status + .or(equalTo(OperationState.SUCCEEDED.toString()))); - String state = brokerFixture.waitForAsyncOperationComplete("instance-id"); + String state = this.brokerFixture.waitForAsyncOperationComplete("instance-id"); assertThat(state).isEqualTo(OperationState.SUCCEEDED.toString()); } diff --git a/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/DeleteInstanceWithServicesComponentTest.java b/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/DeleteInstanceWithServicesComponentTests.java similarity index 58% rename from spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/DeleteInstanceWithServicesComponentTest.java rename to spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/DeleteInstanceWithServicesComponentTests.java index 72d1e7e..10f069c 100644 --- a/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/DeleteInstanceWithServicesComponentTest.java +++ b/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/DeleteInstanceWithServicesComponentTests.java @@ -30,20 +30,18 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.either; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; -import static org.springframework.cloud.appbroker.integration.DeleteInstanceWithAppsAndServicesComponentTest.BACKING_PLAN_NAME; -import static org.springframework.cloud.appbroker.integration.DeleteInstanceWithAppsAndServicesComponentTest.BACKING_SERVICE_NAME; -import static org.springframework.cloud.appbroker.integration.DeleteInstanceWithAppsAndServicesComponentTest.BACKING_SI_NAME; -import static org.springframework.cloud.appbroker.integration.DeleteInstanceWithAppsAndServicesComponentTest.PLAN_NAME; -import static org.springframework.cloud.appbroker.integration.DeleteInstanceWithAppsAndServicesComponentTest.SERVICE_NAME; +import static org.springframework.cloud.appbroker.integration.DeleteInstanceWithAppsAndServicesComponentTests.BACKING_PLAN_NAME; +import static org.springframework.cloud.appbroker.integration.DeleteInstanceWithAppsAndServicesComponentTests.BACKING_SERVICE_NAME; +import static org.springframework.cloud.appbroker.integration.DeleteInstanceWithAppsAndServicesComponentTests.BACKING_SI_NAME; +import static org.springframework.cloud.appbroker.integration.DeleteInstanceWithAppsAndServicesComponentTests.PLAN_NAME; +import static org.springframework.cloud.appbroker.integration.DeleteInstanceWithAppsAndServicesComponentTests.SERVICE_NAME; -@TestPropertySource(properties = { - "spring.cloud.appbroker.services[0].service-name=" + SERVICE_NAME, - "spring.cloud.appbroker.services[0].plan-name=" + PLAN_NAME, - "spring.cloud.appbroker.services[0].services[0].service-instance-name=" + BACKING_SI_NAME, - "spring.cloud.appbroker.services[0].services[0].name=" + BACKING_SERVICE_NAME, - "spring.cloud.appbroker.services[0].services[0].plan=" + BACKING_PLAN_NAME -}) -class DeleteInstanceWithServicesComponentTest extends WiremockComponentTest { +@TestPropertySource(properties = { "spring.cloud.appbroker.services[0].service-name=" + SERVICE_NAME, + "spring.cloud.appbroker.services[0].plan-name=" + PLAN_NAME, + "spring.cloud.appbroker.services[0].services[0].service-instance-name=" + BACKING_SI_NAME, + "spring.cloud.appbroker.services[0].services[0].name=" + BACKING_SERVICE_NAME, + "spring.cloud.appbroker.services[0].services[0].plan=" + BACKING_PLAN_NAME }) +class DeleteInstanceWithServicesComponentTests extends WiremockComponentTests { protected static final String SERVICE_NAME = "example"; @@ -63,52 +61,48 @@ class DeleteInstanceWithServicesComponentTest extends WiremockComponentTest { @Test void deleteServicesWhenTheyExist() { - cloudControllerFixture.stubGetBackingServiceInstance(BACKING_SI_NAME, BACKING_SERVICE_NAME, BACKING_PLAN_NAME); + this.cloudControllerFixture.stubGetBackingServiceInstance(BACKING_SI_NAME, BACKING_SERVICE_NAME, + BACKING_PLAN_NAME); - cloudControllerFixture.stubServiceBindingsDoNotExist(BACKING_SI_NAME); - cloudControllerFixture.stubDeleteServiceInstance(BACKING_SI_NAME); + this.cloudControllerFixture.stubServiceBindingsDoNotExist(BACKING_SI_NAME); + this.cloudControllerFixture.stubDeleteServiceInstance(BACKING_SI_NAME); // when the service instance is deleted - given(brokerFixture.serviceInstanceRequest()) - .when() - .delete(brokerFixture.deleteServiceInstanceUrl(), "instance-id") + given(this.brokerFixture.serviceInstanceRequest()).when() + .delete(this.brokerFixture.deleteServiceInstanceUrl(), "instance-id") .then() .statusCode(HttpStatus.ACCEPTED.value()); // when the "last_operation" API is polled - given(brokerFixture.serviceInstanceRequest()) - .when() - .get(brokerFixture.getLastInstanceOperationUrl(), "instance-id") + given(this.brokerFixture.serviceInstanceRequest()).when() + .get(this.brokerFixture.getLastInstanceOperationUrl(), "instance-id") .then() .statusCode(HttpStatus.OK.value()) .body("state", is(equalTo(OperationState.IN_PROGRESS.toString()))); - String state = brokerFixture.waitForAsyncOperationComplete("instance-id"); + String state = this.brokerFixture.waitForAsyncOperationComplete("instance-id"); assertThat(state).isEqualTo(OperationState.SUCCEEDED.toString()); } @Test void deleteServicesWhenTheyDoNotExist() { - cloudControllerFixture.stubFindSpaceV3(); + this.cloudControllerFixture.stubFindSpaceV3(); // when the service instance is deleted - given(brokerFixture.serviceInstanceRequest()) - .when() - .delete(brokerFixture.deleteServiceInstanceUrl(), "instance-id") + given(this.brokerFixture.serviceInstanceRequest()).when() + .delete(this.brokerFixture.deleteServiceInstanceUrl(), "instance-id") .then() .statusCode(HttpStatus.ACCEPTED.value()); // when the "last_operation" API is polled - given(brokerFixture.serviceInstanceRequest()) - .when() - .get(brokerFixture.getLastInstanceOperationUrl(), "instance-id") + given(this.brokerFixture.serviceInstanceRequest()).when() + .get(this.brokerFixture.getLastInstanceOperationUrl(), "instance-id") .then() .statusCode(HttpStatus.OK.value()) - .body("state", - either(equalTo(OperationState.IN_PROGRESS.toString())) - // if the error occurs immediately it will return succeeded status - .or(equalTo(OperationState.SUCCEEDED.toString()))); + .body("state", either(equalTo(OperationState.IN_PROGRESS.toString())) + // if the error occurs immediately it will return succeeded status + .or(equalTo(OperationState.SUCCEEDED.toString()))); - String state = brokerFixture.waitForAsyncOperationComplete("instance-id"); + String state = this.brokerFixture.waitForAsyncOperationComplete("instance-id"); assertThat(state).isEqualTo(OperationState.SUCCEEDED.toString()); } diff --git a/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/UpdateInstanceComponentTest.java b/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/UpdateInstanceComponentTests.java similarity index 63% rename from spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/UpdateInstanceComponentTest.java rename to spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/UpdateInstanceComponentTests.java index 39a45f2..881c4c3 100644 --- a/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/UpdateInstanceComponentTest.java +++ b/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/UpdateInstanceComponentTests.java @@ -29,18 +29,16 @@ import static io.restassured.RestAssured.given; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; -import static org.springframework.cloud.appbroker.integration.UpdateInstanceComponentTest.APP_NAME_1; -import static org.springframework.cloud.appbroker.integration.UpdateInstanceComponentTest.APP_NAME_2; +import static org.springframework.cloud.appbroker.integration.UpdateInstanceComponentTests.APP_NAME_1; +import static org.springframework.cloud.appbroker.integration.UpdateInstanceComponentTests.APP_NAME_2; -@TestPropertySource(properties = { - "spring.cloud.appbroker.services[0].service-name=example", - "spring.cloud.appbroker.services[0].plan-name=standard", - "spring.cloud.appbroker.services[0].apps[0].path=classpath:demo.jar", - "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME_1, - "spring.cloud.appbroker.services[0].apps[1].path=classpath:demo.jar", - "spring.cloud.appbroker.services[0].apps[1].name=" + APP_NAME_2 -}) -class UpdateInstanceComponentTest extends WiremockComponentTest { +@TestPropertySource(properties = { "spring.cloud.appbroker.services[0].service-name=example", + "spring.cloud.appbroker.services[0].plan-name=standard", + "spring.cloud.appbroker.services[0].apps[0].path=classpath:demo.jar", + "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME_1, + "spring.cloud.appbroker.services[0].apps[1].path=classpath:demo.jar", + "spring.cloud.appbroker.services[0].apps[1].name=" + APP_NAME_2 }) +class UpdateInstanceComponentTests extends WiremockComponentTests { protected static final String APP_NAME_1 = "update-first-app"; @@ -54,28 +52,26 @@ class UpdateInstanceComponentTest extends WiremockComponentTest { @Test void updateAppsWhenTheyExist() { - cloudControllerFixture.stubFindSpaceV3(); - cloudControllerFixture.stubAppExists(APP_NAME_1); - cloudControllerFixture.stubUpdateApp(APP_NAME_1); - cloudControllerFixture.stubAppExists(APP_NAME_2); - cloudControllerFixture.stubUpdateApp(APP_NAME_2); + this.cloudControllerFixture.stubFindSpaceV3(); + this.cloudControllerFixture.stubAppExists(APP_NAME_1); + this.cloudControllerFixture.stubUpdateApp(APP_NAME_1); + this.cloudControllerFixture.stubAppExists(APP_NAME_2); + this.cloudControllerFixture.stubUpdateApp(APP_NAME_2); // when a service instance is created - given(brokerFixture.serviceInstanceRequest()) - .when() - .patch(brokerFixture.createServiceInstanceUrl(), "instance-id") + given(this.brokerFixture.serviceInstanceRequest()).when() + .patch(this.brokerFixture.createServiceInstanceUrl(), "instance-id") .then() .statusCode(HttpStatus.ACCEPTED.value()); // when the "last_operation" API is polled - given(brokerFixture.serviceInstanceRequest()) - .when() - .get(brokerFixture.getLastInstanceOperationUrl(), "instance-id") + given(this.brokerFixture.serviceInstanceRequest()).when() + .get(this.brokerFixture.getLastInstanceOperationUrl(), "instance-id") .then() .statusCode(HttpStatus.OK.value()) .body("state", is(equalTo(OperationState.IN_PROGRESS.toString()))); - String state = brokerFixture.waitForAsyncOperationComplete("instance-id"); + String state = this.brokerFixture.waitForAsyncOperationComplete("instance-id"); assertThat(state).isEqualTo(OperationState.SUCCEEDED.toString()); } diff --git a/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/UpdateInstanceWithNewServiceAndTargetComponentTest.java b/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/UpdateInstanceWithNewServiceAndTargetComponentTests.java similarity index 51% rename from spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/UpdateInstanceWithNewServiceAndTargetComponentTest.java rename to spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/UpdateInstanceWithNewServiceAndTargetComponentTests.java index c80bed2..b90cda0 100644 --- a/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/UpdateInstanceWithNewServiceAndTargetComponentTest.java +++ b/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/UpdateInstanceWithNewServiceAndTargetComponentTests.java @@ -29,26 +29,24 @@ import static io.restassured.RestAssured.given; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; -import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithNewServiceAndTargetComponentTest.APP_NAME; -import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithNewServiceAndTargetComponentTest.NEW_BACKING_PLAN_NAME; -import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithNewServiceAndTargetComponentTest.NEW_BACKING_SERVICE_NAME; -import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithNewServiceAndTargetComponentTest.NEW_BACKING_SI_NAME; -import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithNewServiceAndTargetComponentTest.PLAN_NAME; -import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithNewServiceAndTargetComponentTest.SERVICE_NAME; +import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithNewServiceAndTargetComponentTests.APP_NAME; +import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithNewServiceAndTargetComponentTests.NEW_BACKING_PLAN_NAME; +import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithNewServiceAndTargetComponentTests.NEW_BACKING_SERVICE_NAME; +import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithNewServiceAndTargetComponentTests.NEW_BACKING_SI_NAME; +import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithNewServiceAndTargetComponentTests.PLAN_NAME; +import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithNewServiceAndTargetComponentTests.SERVICE_NAME; -@TestPropertySource(properties = { - "spring.cloud.appbroker.services[0].service-name=" + SERVICE_NAME, - "spring.cloud.appbroker.services[0].plan-name=" + PLAN_NAME, - "spring.cloud.appbroker.services[0].apps[0].path=classpath:demo.jar", - "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME, - "spring.cloud.appbroker.services[0].apps[0].services[0].service-instance-name=" + NEW_BACKING_SI_NAME, - "spring.cloud.appbroker.services[0].services[0].service-instance-name=" + NEW_BACKING_SI_NAME, - "spring.cloud.appbroker.services[0].services[0].name=" + NEW_BACKING_SERVICE_NAME, - "spring.cloud.appbroker.services[0].services[0].plan=" + NEW_BACKING_PLAN_NAME, +@TestPropertySource(properties = { "spring.cloud.appbroker.services[0].service-name=" + SERVICE_NAME, + "spring.cloud.appbroker.services[0].plan-name=" + PLAN_NAME, + "spring.cloud.appbroker.services[0].apps[0].path=classpath:demo.jar", + "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME, + "spring.cloud.appbroker.services[0].apps[0].services[0].service-instance-name=" + NEW_BACKING_SI_NAME, + "spring.cloud.appbroker.services[0].services[0].service-instance-name=" + NEW_BACKING_SI_NAME, + "spring.cloud.appbroker.services[0].services[0].name=" + NEW_BACKING_SERVICE_NAME, + "spring.cloud.appbroker.services[0].services[0].plan=" + NEW_BACKING_PLAN_NAME, - "spring.cloud.appbroker.services[0].target.name=SpacePerServiceInstance" -}) -class UpdateInstanceWithNewServiceAndTargetComponentTest extends WiremockComponentTest { + "spring.cloud.appbroker.services[0].target.name=SpacePerServiceInstance" }) +class UpdateInstanceWithNewServiceAndTargetComponentTests extends WiremockComponentTests { protected static final String APP_NAME = "app-update-with-new-service-and-target"; @@ -79,43 +77,42 @@ class UpdateInstanceWithNewServiceAndTargetComponentTest extends WiremockCompone final String backingSpaceGuid = "instance-id-space-guid"; final String serviceInstanceId = "instance-id"; - cloudControllerFixture.stubFindTestOrg(); - cloudControllerFixture.stubFindSpace(serviceInstanceId, backingSpaceGuid); - cloudControllerFixture.stubFindSpaceV3(serviceInstanceId, backingSpaceGuid); - cloudControllerFixture.stubSpaceExists(serviceInstanceId, backingSpaceGuid); - cloudControllerFixture.stubAppExistsWithBackingService(APP_NAME, BACKING_SI_NAME, - BACKING_SERVICE_NAME, BACKING_PLAN_NAME, backingSpaceGuid); - cloudControllerFixture.stubUpdateAppWithTarget(APP_NAME, backingSpaceGuid); + this.cloudControllerFixture.stubFindTestOrg(); + this.cloudControllerFixture.stubFindSpace(serviceInstanceId, backingSpaceGuid); + this.cloudControllerFixture.stubFindSpaceV3(serviceInstanceId, backingSpaceGuid); + this.cloudControllerFixture.stubSpaceExists(serviceInstanceId, backingSpaceGuid); + this.cloudControllerFixture.stubAppExistsWithBackingService(APP_NAME, BACKING_SI_NAME, BACKING_SERVICE_NAME, + BACKING_PLAN_NAME, backingSpaceGuid); + this.cloudControllerFixture.stubUpdateAppWithTarget(APP_NAME, backingSpaceGuid); // will unbind and delete the existing service instance - cloudControllerFixture.stubGetBackingServiceInstanceFromSpace(BACKING_SI_NAME, BACKING_SERVICE_NAME, - BACKING_PLAN_NAME, backingSpaceGuid); - cloudControllerFixture.stubServiceBindingExists(APP_NAME, BACKING_SI_NAME); - cloudControllerFixture.stubDeleteServiceBinding(APP_NAME, BACKING_SI_NAME); - cloudControllerFixture.stubDeleteServiceInstance(BACKING_SI_NAME); + this.cloudControllerFixture.stubGetBackingServiceInstanceFromSpace(BACKING_SI_NAME, BACKING_SERVICE_NAME, + BACKING_PLAN_NAME, backingSpaceGuid); + this.cloudControllerFixture.stubServiceBindingExists(APP_NAME, BACKING_SI_NAME); + this.cloudControllerFixture.stubDeleteServiceBinding(APP_NAME, BACKING_SI_NAME); + this.cloudControllerFixture.stubDeleteServiceInstance(BACKING_SI_NAME); // will create and bind the service instance - cloudControllerFixture.stubServiceExistsInSpace(NEW_BACKING_SERVICE_NAME, NEW_BACKING_PLAN_NAME, backingSpaceGuid); - cloudControllerFixture.stubCreateServiceInstance(NEW_BACKING_SI_NAME); - cloudControllerFixture.stubCreateServiceBinding(APP_NAME, NEW_BACKING_SI_NAME); - cloudControllerFixture.stubServiceInstanceExistsInSpace(NEW_BACKING_SI_NAME, backingSpaceGuid); + this.cloudControllerFixture.stubServiceExistsInSpace(NEW_BACKING_SERVICE_NAME, NEW_BACKING_PLAN_NAME, + backingSpaceGuid); + this.cloudControllerFixture.stubCreateServiceInstance(NEW_BACKING_SI_NAME); + this.cloudControllerFixture.stubCreateServiceBinding(APP_NAME, NEW_BACKING_SI_NAME); + this.cloudControllerFixture.stubServiceInstanceExistsInSpace(NEW_BACKING_SI_NAME, backingSpaceGuid); // when a service instance is updated - given(brokerFixture.serviceInstanceRequest()) - .when() - .patch(brokerFixture.createServiceInstanceUrl(), serviceInstanceId) + given(this.brokerFixture.serviceInstanceRequest()).when() + .patch(this.brokerFixture.createServiceInstanceUrl(), serviceInstanceId) .then() .statusCode(HttpStatus.ACCEPTED.value()); // when the "last_operation" API is polled - given(brokerFixture.serviceInstanceRequest()) - .when() - .get(brokerFixture.getLastInstanceOperationUrl(), serviceInstanceId) + given(this.brokerFixture.serviceInstanceRequest()).when() + .get(this.brokerFixture.getLastInstanceOperationUrl(), serviceInstanceId) .then() .statusCode(HttpStatus.OK.value()) .body("state", is(equalTo(OperationState.IN_PROGRESS.toString()))); - String state = brokerFixture.waitForAsyncOperationComplete(serviceInstanceId); + String state = this.brokerFixture.waitForAsyncOperationComplete(serviceInstanceId); assertThat(state).isEqualTo(OperationState.SUCCEEDED.toString()); } diff --git a/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/UpdateInstanceWithNewServiceComponentTest.java b/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/UpdateInstanceWithNewServiceComponentTests.java similarity index 55% rename from spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/UpdateInstanceWithNewServiceComponentTest.java rename to spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/UpdateInstanceWithNewServiceComponentTests.java index 3fb80a8..5d17009 100644 --- a/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/UpdateInstanceWithNewServiceComponentTest.java +++ b/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/UpdateInstanceWithNewServiceComponentTests.java @@ -29,24 +29,22 @@ import static io.restassured.RestAssured.given; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; -import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithNewServiceComponentTest.APP_NAME; -import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithNewServiceComponentTest.NEW_BACKING_PLAN_NAME; -import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithNewServiceComponentTest.NEW_BACKING_SERVICE_NAME; -import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithNewServiceComponentTest.NEW_BACKING_SI_NAME; -import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithNewServiceComponentTest.PLAN_NAME; -import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithNewServiceComponentTest.SERVICE_NAME; +import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithNewServiceComponentTests.APP_NAME; +import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithNewServiceComponentTests.NEW_BACKING_PLAN_NAME; +import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithNewServiceComponentTests.NEW_BACKING_SERVICE_NAME; +import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithNewServiceComponentTests.NEW_BACKING_SI_NAME; +import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithNewServiceComponentTests.PLAN_NAME; +import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithNewServiceComponentTests.SERVICE_NAME; -@TestPropertySource(properties = { - "spring.cloud.appbroker.services[0].service-name=" + SERVICE_NAME, - "spring.cloud.appbroker.services[0].plan-name=" + PLAN_NAME, - "spring.cloud.appbroker.services[0].apps[0].path=classpath:demo.jar", - "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME, - "spring.cloud.appbroker.services[0].apps[0].services[0].service-instance-name=" + NEW_BACKING_SI_NAME, - "spring.cloud.appbroker.services[0].services[0].service-instance-name=" + NEW_BACKING_SI_NAME, - "spring.cloud.appbroker.services[0].services[0].name=" + NEW_BACKING_SERVICE_NAME, - "spring.cloud.appbroker.services[0].services[0].plan=" + NEW_BACKING_PLAN_NAME -}) -class UpdateInstanceWithNewServiceComponentTest extends WiremockComponentTest { +@TestPropertySource(properties = { "spring.cloud.appbroker.services[0].service-name=" + SERVICE_NAME, + "spring.cloud.appbroker.services[0].plan-name=" + PLAN_NAME, + "spring.cloud.appbroker.services[0].apps[0].path=classpath:demo.jar", + "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME, + "spring.cloud.appbroker.services[0].apps[0].services[0].service-instance-name=" + NEW_BACKING_SI_NAME, + "spring.cloud.appbroker.services[0].services[0].service-instance-name=" + NEW_BACKING_SI_NAME, + "spring.cloud.appbroker.services[0].services[0].name=" + NEW_BACKING_SERVICE_NAME, + "spring.cloud.appbroker.services[0].services[0].plan=" + NEW_BACKING_PLAN_NAME }) +class UpdateInstanceWithNewServiceComponentTests extends WiremockComponentTests { protected static final String APP_NAME = "app-update-with-new-service"; @@ -74,39 +72,38 @@ class UpdateInstanceWithNewServiceComponentTest extends WiremockComponentTest { @Test void updateAppWithNewService() { - cloudControllerFixture.stubFindSpaceV3(); - cloudControllerFixture.stubAppExistsWithBackingService(APP_NAME, BACKING_SI_NAME, - BACKING_SERVICE_NAME, BACKING_PLAN_NAME); - cloudControllerFixture.stubUpdateApp(APP_NAME); + this.cloudControllerFixture.stubFindSpaceV3(); + this.cloudControllerFixture.stubAppExistsWithBackingService(APP_NAME, BACKING_SI_NAME, BACKING_SERVICE_NAME, + BACKING_PLAN_NAME); + this.cloudControllerFixture.stubUpdateApp(APP_NAME); // will unbind and delete the existing service instance - cloudControllerFixture.stubGetBackingServiceInstance(BACKING_SI_NAME, BACKING_SERVICE_NAME, BACKING_PLAN_NAME); - cloudControllerFixture.stubServiceBindingExists(APP_NAME, BACKING_SI_NAME); - cloudControllerFixture.stubDeleteServiceBinding(APP_NAME, BACKING_SI_NAME); - cloudControllerFixture.stubDeleteServiceInstance(BACKING_SI_NAME); + this.cloudControllerFixture.stubGetBackingServiceInstance(BACKING_SI_NAME, BACKING_SERVICE_NAME, + BACKING_PLAN_NAME); + this.cloudControllerFixture.stubServiceBindingExists(APP_NAME, BACKING_SI_NAME); + this.cloudControllerFixture.stubDeleteServiceBinding(APP_NAME, BACKING_SI_NAME); + this.cloudControllerFixture.stubDeleteServiceInstance(BACKING_SI_NAME); // will create and bind the service instance - cloudControllerFixture.stubServiceExists(NEW_BACKING_SERVICE_NAME, NEW_BACKING_PLAN_NAME); - cloudControllerFixture.stubCreateServiceInstance(NEW_BACKING_SI_NAME); - cloudControllerFixture.stubCreateServiceBinding(APP_NAME, NEW_BACKING_SI_NAME); - cloudControllerFixture.stubServiceInstanceExists(NEW_BACKING_SI_NAME); + this.cloudControllerFixture.stubServiceExists(NEW_BACKING_SERVICE_NAME, NEW_BACKING_PLAN_NAME); + this.cloudControllerFixture.stubCreateServiceInstance(NEW_BACKING_SI_NAME); + this.cloudControllerFixture.stubCreateServiceBinding(APP_NAME, NEW_BACKING_SI_NAME); + this.cloudControllerFixture.stubServiceInstanceExists(NEW_BACKING_SI_NAME); // when a service instance is updated - given(brokerFixture.serviceInstanceRequest()) - .when() - .patch(brokerFixture.createServiceInstanceUrl(), "instance-id") + given(this.brokerFixture.serviceInstanceRequest()).when() + .patch(this.brokerFixture.createServiceInstanceUrl(), "instance-id") .then() .statusCode(HttpStatus.ACCEPTED.value()); // when the "last_operation" API is polled - given(brokerFixture.serviceInstanceRequest()) - .when() - .get(brokerFixture.getLastInstanceOperationUrl(), "instance-id") + given(this.brokerFixture.serviceInstanceRequest()).when() + .get(this.brokerFixture.getLastInstanceOperationUrl(), "instance-id") .then() .statusCode(HttpStatus.OK.value()) .body("state", is(equalTo(OperationState.IN_PROGRESS.toString()))); - String state = brokerFixture.waitForAsyncOperationComplete("instance-id"); + String state = this.brokerFixture.waitForAsyncOperationComplete("instance-id"); assertThat(state).isEqualTo(OperationState.SUCCEEDED.toString()); } diff --git a/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/UpdateInstanceWithServicesComponentTest.java b/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/UpdateInstanceWithServicesComponentTests.java similarity index 60% rename from spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/UpdateInstanceWithServicesComponentTest.java rename to spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/UpdateInstanceWithServicesComponentTests.java index e2f5eb4..5eb5176 100644 --- a/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/UpdateInstanceWithServicesComponentTest.java +++ b/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/UpdateInstanceWithServicesComponentTests.java @@ -29,24 +29,22 @@ import static io.restassured.RestAssured.given; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; -import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithServicesComponentTest.APP_NAME; -import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithServicesComponentTest.BACKING_PLAN_NAME; -import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithServicesComponentTest.BACKING_SERVICE_INSTANCE_NAME; -import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithServicesComponentTest.BACKING_SERVICE_NAME; -import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithServicesComponentTest.PLAN_NAME; -import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithServicesComponentTest.SERVICE_NAME; +import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithServicesComponentTests.APP_NAME; +import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithServicesComponentTests.BACKING_PLAN_NAME; +import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithServicesComponentTests.BACKING_SERVICE_INSTANCE_NAME; +import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithServicesComponentTests.BACKING_SERVICE_NAME; +import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithServicesComponentTests.PLAN_NAME; +import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithServicesComponentTests.SERVICE_NAME; -@TestPropertySource(properties = { - "spring.cloud.appbroker.services[0].service-name=" + SERVICE_NAME, - "spring.cloud.appbroker.services[0].plan-name=" + PLAN_NAME, - "spring.cloud.appbroker.services[0].apps[0].path=classpath:demo.jar", - "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME, - "spring.cloud.appbroker.services[0].apps[0].services[0].service-instance-name=" + BACKING_SERVICE_INSTANCE_NAME, - "spring.cloud.appbroker.services[0].services[0].service-instance-name=" + BACKING_SERVICE_INSTANCE_NAME, - "spring.cloud.appbroker.services[0].services[0].name=" + BACKING_SERVICE_NAME, - "spring.cloud.appbroker.services[0].services[0].plan=" + BACKING_PLAN_NAME -}) -class UpdateInstanceWithServicesComponentTest extends WiremockComponentTest { +@TestPropertySource(properties = { "spring.cloud.appbroker.services[0].service-name=" + SERVICE_NAME, + "spring.cloud.appbroker.services[0].plan-name=" + PLAN_NAME, + "spring.cloud.appbroker.services[0].apps[0].path=classpath:demo.jar", + "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME, + "spring.cloud.appbroker.services[0].apps[0].services[0].service-instance-name=" + BACKING_SERVICE_INSTANCE_NAME, + "spring.cloud.appbroker.services[0].services[0].service-instance-name=" + BACKING_SERVICE_INSTANCE_NAME, + "spring.cloud.appbroker.services[0].services[0].name=" + BACKING_SERVICE_NAME, + "spring.cloud.appbroker.services[0].services[0].plan=" + BACKING_PLAN_NAME }) +class UpdateInstanceWithServicesComponentTests extends WiremockComponentTests { protected static final String APP_NAME = "app-update-with-services"; @@ -68,27 +66,25 @@ class UpdateInstanceWithServicesComponentTest extends WiremockComponentTest { @Test void updateAppWithServices() { - cloudControllerFixture.stubFindSpaceV3(); - cloudControllerFixture.stubAppExistsWithBackingService(APP_NAME, BACKING_SERVICE_INSTANCE_NAME, - BACKING_SERVICE_NAME, BACKING_PLAN_NAME); - cloudControllerFixture.stubUpdateApp(APP_NAME); + this.cloudControllerFixture.stubFindSpaceV3(); + this.cloudControllerFixture.stubAppExistsWithBackingService(APP_NAME, BACKING_SERVICE_INSTANCE_NAME, + BACKING_SERVICE_NAME, BACKING_PLAN_NAME); + this.cloudControllerFixture.stubUpdateApp(APP_NAME); // when a service instance is updated - given(brokerFixture.serviceInstanceRequest()) - .when() - .patch(brokerFixture.createServiceInstanceUrl(), "instance-id") + given(this.brokerFixture.serviceInstanceRequest()).when() + .patch(this.brokerFixture.createServiceInstanceUrl(), "instance-id") .then() .statusCode(HttpStatus.ACCEPTED.value()); // when the "last_operation" API is polled - given(brokerFixture.serviceInstanceRequest()) - .when() - .get(brokerFixture.getLastInstanceOperationUrl(), "instance-id") + given(this.brokerFixture.serviceInstanceRequest()).when() + .get(this.brokerFixture.getLastInstanceOperationUrl(), "instance-id") .then() .statusCode(HttpStatus.OK.value()) .body("state", is(equalTo(OperationState.IN_PROGRESS.toString()))); - String state = brokerFixture.waitForAsyncOperationComplete("instance-id"); + String state = this.brokerFixture.waitForAsyncOperationComplete("instance-id"); assertThat(state).isEqualTo(OperationState.SUCCEEDED.toString()); } diff --git a/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/UpdateInstanceWithServicesHostAndDomainComponentTest.java b/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/UpdateInstanceWithServicesHostAndDomainComponentTests.java similarity index 64% rename from spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/UpdateInstanceWithServicesHostAndDomainComponentTest.java rename to spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/UpdateInstanceWithServicesHostAndDomainComponentTests.java index e39697e..076ddcb 100644 --- a/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/UpdateInstanceWithServicesHostAndDomainComponentTest.java +++ b/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/UpdateInstanceWithServicesHostAndDomainComponentTests.java @@ -31,17 +31,15 @@ import static io.restassured.RestAssured.given; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; -import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithServicesHostAndDomainComponentTest.APP_NAME; +import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithServicesHostAndDomainComponentTests.APP_NAME; -@TestPropertySource(properties = { - "spring.cloud.appbroker.services[0].service-name=example", - "spring.cloud.appbroker.services[0].plan-name=standard", - "spring.cloud.appbroker.services[0].apps[0].path=classpath:demo.jar", - "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME, - "spring.cloud.appbroker.services[0].apps[0].parameters-transformers[0].name=PropertyMapping", - "spring.cloud.appbroker.services[0].apps[0].parameters-transformers[0].args.include=host,domain" -}) -class UpdateInstanceWithServicesHostAndDomainComponentTest extends WiremockComponentTest { +@TestPropertySource(properties = { "spring.cloud.appbroker.services[0].service-name=example", + "spring.cloud.appbroker.services[0].plan-name=standard", + "spring.cloud.appbroker.services[0].apps[0].path=classpath:demo.jar", + "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME, + "spring.cloud.appbroker.services[0].apps[0].parameters-transformers[0].name=PropertyMapping", + "spring.cloud.appbroker.services[0].apps[0].parameters-transformers[0].args.include=host,domain" }) +class UpdateInstanceWithServicesHostAndDomainComponentTests extends WiremockComponentTests { protected static final String APP_NAME = "app-update-hostname-param"; @@ -53,31 +51,29 @@ class UpdateInstanceWithServicesHostAndDomainComponentTest extends WiremockCompo @Test void updateAppWithHostAndDomain() { - cloudControllerFixture.stubFindTestOrg(); - cloudControllerFixture.stubFindSpaceV3(); - cloudControllerFixture.stubAppExists(APP_NAME); - cloudControllerFixture.stubUpdateAppWithHostAndDomain(APP_NAME); + this.cloudControllerFixture.stubFindTestOrg(); + this.cloudControllerFixture.stubFindSpaceV3(); + this.cloudControllerFixture.stubAppExists(APP_NAME); + this.cloudControllerFixture.stubUpdateAppWithHostAndDomain(APP_NAME); HashMap expectedUpdateParams = new HashMap<>(); expectedUpdateParams.put("host", "myhost"); expectedUpdateParams.put("domain", "my.domain.com"); // when a service instance is updated with parameters - given(brokerFixture.serviceInstanceRequest(expectedUpdateParams)) - .when() - .patch(brokerFixture.createServiceInstanceUrl(), "instance-id") + given(this.brokerFixture.serviceInstanceRequest(expectedUpdateParams)).when() + .patch(this.brokerFixture.createServiceInstanceUrl(), "instance-id") .then() .statusCode(HttpStatus.ACCEPTED.value()); // when the "last_operation" API is polled - given(brokerFixture.serviceInstanceRequest()) - .when() - .get(brokerFixture.getLastInstanceOperationUrl(), "instance-id") + given(this.brokerFixture.serviceInstanceRequest()).when() + .get(this.brokerFixture.getLastInstanceOperationUrl(), "instance-id") .then() .statusCode(HttpStatus.OK.value()) .body("state", is(equalTo(OperationState.IN_PROGRESS.toString()))); - String state = brokerFixture.waitForAsyncOperationComplete("instance-id"); + String state = this.brokerFixture.waitForAsyncOperationComplete("instance-id"); assertThat(state).isEqualTo(OperationState.SUCCEEDED.toString()); } diff --git a/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/UpdateInstanceWithServicesParametersComponentTest.java b/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/UpdateInstanceWithServicesParametersComponentTests.java similarity index 59% rename from spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/UpdateInstanceWithServicesParametersComponentTest.java rename to spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/UpdateInstanceWithServicesParametersComponentTests.java index 9063ed9..e4549d6 100644 --- a/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/UpdateInstanceWithServicesParametersComponentTest.java +++ b/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/UpdateInstanceWithServicesParametersComponentTests.java @@ -32,26 +32,24 @@ import static io.restassured.RestAssured.given; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; -import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithServicesParametersComponentTest.APP_NAME; -import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithServicesParametersComponentTest.BACKING_PLAN_NAME; -import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithServicesParametersComponentTest.BACKING_SERVICE_NAME; -import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithServicesParametersComponentTest.BACKING_SI_NAME; -import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithServicesParametersComponentTest.PLAN_NAME; -import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithServicesParametersComponentTest.SERVICE_NAME; +import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithServicesParametersComponentTests.APP_NAME; +import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithServicesParametersComponentTests.BACKING_PLAN_NAME; +import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithServicesParametersComponentTests.BACKING_SERVICE_NAME; +import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithServicesParametersComponentTests.BACKING_SI_NAME; +import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithServicesParametersComponentTests.PLAN_NAME; +import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithServicesParametersComponentTests.SERVICE_NAME; -@TestPropertySource(properties = { - "spring.cloud.appbroker.services[0].service-name=" + SERVICE_NAME, - "spring.cloud.appbroker.services[0].plan-name=" + PLAN_NAME, - "spring.cloud.appbroker.services[0].apps[0].path=classpath:demo.jar", - "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME, - "spring.cloud.appbroker.services[0].apps[0].services[0].service-instance-name=" + BACKING_SI_NAME, - "spring.cloud.appbroker.services[0].services[0].service-instance-name=" + BACKING_SI_NAME, - "spring.cloud.appbroker.services[0].services[0].name=" + BACKING_SERVICE_NAME, - "spring.cloud.appbroker.services[0].services[0].plan=" + BACKING_PLAN_NAME, - "spring.cloud.appbroker.services[0].services[0].parameters-transformers[0].name=ParameterMapping", - "spring.cloud.appbroker.services[0].services[0].parameters-transformers[0].args.include=paramA,paramC" -}) -class UpdateInstanceWithServicesParametersComponentTest extends WiremockComponentTest { +@TestPropertySource(properties = { "spring.cloud.appbroker.services[0].service-name=" + SERVICE_NAME, + "spring.cloud.appbroker.services[0].plan-name=" + PLAN_NAME, + "spring.cloud.appbroker.services[0].apps[0].path=classpath:demo.jar", + "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME, + "spring.cloud.appbroker.services[0].apps[0].services[0].service-instance-name=" + BACKING_SI_NAME, + "spring.cloud.appbroker.services[0].services[0].service-instance-name=" + BACKING_SI_NAME, + "spring.cloud.appbroker.services[0].services[0].name=" + BACKING_SERVICE_NAME, + "spring.cloud.appbroker.services[0].services[0].plan=" + BACKING_PLAN_NAME, + "spring.cloud.appbroker.services[0].services[0].parameters-transformers[0].name=ParameterMapping", + "spring.cloud.appbroker.services[0].services[0].parameters-transformers[0].args.include=paramA,paramC" }) +class UpdateInstanceWithServicesParametersComponentTests extends WiremockComponentTests { protected static final String APP_NAME = "app-update-services-param"; @@ -73,18 +71,19 @@ class UpdateInstanceWithServicesParametersComponentTest extends WiremockComponen @Test void updateAppWithBackingServicesParameters() { - cloudControllerFixture.stubFindSpaceV3(); - cloudControllerFixture.stubAppExistsWithBackingService(APP_NAME, BACKING_SI_NAME, BACKING_SERVICE_NAME, - BACKING_PLAN_NAME); - cloudControllerFixture.stubUpdateApp(APP_NAME); + this.cloudControllerFixture.stubFindSpaceV3(); + this.cloudControllerFixture.stubAppExistsWithBackingService(APP_NAME, BACKING_SI_NAME, BACKING_SERVICE_NAME, + BACKING_PLAN_NAME); + this.cloudControllerFixture.stubUpdateApp(APP_NAME); // will update with filtered parameters and bind the service instance HashMap expectedCreationParameters = new HashMap<>(); expectedCreationParameters.put("paramA", "valueA"); expectedCreationParameters.put("paramC", Collections.singletonMap("paramC1", "valueC1")); - cloudControllerFixture.stubServiceInstanceExists(BACKING_SI_NAME, BACKING_SERVICE_NAME, BACKING_PLAN_NAME); - cloudControllerFixture.stubUpdateServiceInstanceWithParameters(BACKING_SI_NAME, expectedCreationParameters); + this.cloudControllerFixture.stubServiceInstanceExists(BACKING_SI_NAME, BACKING_SERVICE_NAME, BACKING_PLAN_NAME); + this.cloudControllerFixture.stubUpdateServiceInstanceWithParameters(BACKING_SI_NAME, + expectedCreationParameters); // when a service instance is created with parameters HashMap creationParameters = new HashMap<>(); @@ -92,21 +91,19 @@ class UpdateInstanceWithServicesParametersComponentTest extends WiremockComponen creationParameters.put("paramB", "valueB"); creationParameters.put("paramC", Collections.singletonMap("paramC1", "valueC1")); - given(brokerFixture.serviceInstanceRequest(creationParameters)) - .when() - .patch(brokerFixture.createServiceInstanceUrl(), "instance-id") + given(this.brokerFixture.serviceInstanceRequest(creationParameters)).when() + .patch(this.brokerFixture.createServiceInstanceUrl(), "instance-id") .then() .statusCode(HttpStatus.ACCEPTED.value()); // when the "last_operation" API is polled - given(brokerFixture.serviceInstanceRequest()) - .when() - .get(brokerFixture.getLastInstanceOperationUrl(), "instance-id") + given(this.brokerFixture.serviceInstanceRequest()).when() + .get(this.brokerFixture.getLastInstanceOperationUrl(), "instance-id") .then() .statusCode(HttpStatus.OK.value()) .body("state", is(equalTo(OperationState.IN_PROGRESS.toString()))); - String state = brokerFixture.waitForAsyncOperationComplete("instance-id"); + String state = this.brokerFixture.waitForAsyncOperationComplete("instance-id"); assertThat(state).isEqualTo(OperationState.SUCCEEDED.toString()); } diff --git a/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/UpdateInstanceWithServicesRebindComponentTest.java b/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/UpdateInstanceWithServicesRebindComponentTests.java similarity index 55% rename from spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/UpdateInstanceWithServicesRebindComponentTest.java rename to spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/UpdateInstanceWithServicesRebindComponentTests.java index 89d4439..9189c8c 100644 --- a/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/UpdateInstanceWithServicesRebindComponentTest.java +++ b/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/UpdateInstanceWithServicesRebindComponentTests.java @@ -29,25 +29,23 @@ import static io.restassured.RestAssured.given; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; -import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithServicesRebindComponentTest.APP_NAME; -import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithServicesRebindComponentTest.BACKING_PLAN_NAME; -import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithServicesRebindComponentTest.BACKING_SERVICE_NAME; -import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithServicesRebindComponentTest.BACKING_SI_NAME; -import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithServicesRebindComponentTest.PLAN_NAME; -import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithServicesRebindComponentTest.SERVICE_NAME; +import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithServicesRebindComponentTests.APP_NAME; +import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithServicesRebindComponentTests.BACKING_PLAN_NAME; +import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithServicesRebindComponentTests.BACKING_SERVICE_NAME; +import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithServicesRebindComponentTests.BACKING_SI_NAME; +import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithServicesRebindComponentTests.PLAN_NAME; +import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithServicesRebindComponentTests.SERVICE_NAME; -@TestPropertySource(properties = { - "spring.cloud.appbroker.services[0].service-name=" + SERVICE_NAME, - "spring.cloud.appbroker.services[0].plan-name=" + PLAN_NAME, - "spring.cloud.appbroker.services[0].apps[0].path=classpath:demo.jar", - "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME, - "spring.cloud.appbroker.services[0].apps[0].services[0].service-instance-name=" + BACKING_SI_NAME, - "spring.cloud.appbroker.services[0].services[0].service-instance-name=" + BACKING_SI_NAME, - "spring.cloud.appbroker.services[0].services[0].name=" + BACKING_SERVICE_NAME, - "spring.cloud.appbroker.services[0].services[0].plan=" + BACKING_PLAN_NAME, - "spring.cloud.appbroker.services[0].services[0].rebind-on-update=true" -}) -class UpdateInstanceWithServicesRebindComponentTest extends WiremockComponentTest { +@TestPropertySource(properties = { "spring.cloud.appbroker.services[0].service-name=" + SERVICE_NAME, + "spring.cloud.appbroker.services[0].plan-name=" + PLAN_NAME, + "spring.cloud.appbroker.services[0].apps[0].path=classpath:demo.jar", + "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME, + "spring.cloud.appbroker.services[0].apps[0].services[0].service-instance-name=" + BACKING_SI_NAME, + "spring.cloud.appbroker.services[0].services[0].service-instance-name=" + BACKING_SI_NAME, + "spring.cloud.appbroker.services[0].services[0].name=" + BACKING_SERVICE_NAME, + "spring.cloud.appbroker.services[0].services[0].plan=" + BACKING_PLAN_NAME, + "spring.cloud.appbroker.services[0].services[0].rebind-on-update=true" }) +class UpdateInstanceWithServicesRebindComponentTests extends WiremockComponentTests { protected static final String APP_NAME = "app-update-rebind-with-services"; @@ -69,32 +67,31 @@ class UpdateInstanceWithServicesRebindComponentTest extends WiremockComponentTes @Test void updateAppWithServices() { - cloudControllerFixture.stubFindSpaceV3(); - cloudControllerFixture.stubAppExistsWithBackingService(APP_NAME, BACKING_SI_NAME, BACKING_SERVICE_NAME, - BACKING_PLAN_NAME); - cloudControllerFixture.stubUpdateApp(APP_NAME); + this.cloudControllerFixture.stubFindSpaceV3(); + this.cloudControllerFixture.stubAppExistsWithBackingService(APP_NAME, BACKING_SI_NAME, BACKING_SERVICE_NAME, + BACKING_PLAN_NAME); + this.cloudControllerFixture.stubUpdateApp(APP_NAME); - cloudControllerFixture.stubGetBackingServiceInstance(BACKING_SI_NAME, BACKING_SERVICE_NAME, BACKING_PLAN_NAME); - cloudControllerFixture.stubServiceBindingExists(APP_NAME, BACKING_SI_NAME); - cloudControllerFixture.stubDeleteServiceBinding(APP_NAME, BACKING_SI_NAME); - cloudControllerFixture.stubCreateServiceBinding(APP_NAME, BACKING_SI_NAME); + this.cloudControllerFixture.stubGetBackingServiceInstance(BACKING_SI_NAME, BACKING_SERVICE_NAME, + BACKING_PLAN_NAME); + this.cloudControllerFixture.stubServiceBindingExists(APP_NAME, BACKING_SI_NAME); + this.cloudControllerFixture.stubDeleteServiceBinding(APP_NAME, BACKING_SI_NAME); + this.cloudControllerFixture.stubCreateServiceBinding(APP_NAME, BACKING_SI_NAME); // when a service instance is updated - given(brokerFixture.serviceInstanceRequest()) - .when() - .patch(brokerFixture.createServiceInstanceUrl(), "instance-id") + given(this.brokerFixture.serviceInstanceRequest()).when() + .patch(this.brokerFixture.createServiceInstanceUrl(), "instance-id") .then() .statusCode(HttpStatus.ACCEPTED.value()); // when the "last_operation" API is polled - given(brokerFixture.serviceInstanceRequest()) - .when() - .get(brokerFixture.getLastInstanceOperationUrl(), "instance-id") + given(this.brokerFixture.serviceInstanceRequest()).when() + .get(this.brokerFixture.getLastInstanceOperationUrl(), "instance-id") .then() .statusCode(HttpStatus.OK.value()) .body("state", is(equalTo(OperationState.IN_PROGRESS.toString()))); - String state = brokerFixture.waitForAsyncOperationComplete("instance-id"); + String state = this.brokerFixture.waitForAsyncOperationComplete("instance-id"); assertThat(state).isEqualTo(OperationState.SUCCEEDED.toString()); } diff --git a/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/UpdateInstanceWithUpgradeComponentTest.java b/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/UpdateInstanceWithUpgradeComponentTests.java similarity index 63% rename from spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/UpdateInstanceWithUpgradeComponentTest.java rename to spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/UpdateInstanceWithUpgradeComponentTests.java index 35c3998..6a405b5 100644 --- a/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/UpdateInstanceWithUpgradeComponentTest.java +++ b/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/UpdateInstanceWithUpgradeComponentTests.java @@ -31,18 +31,16 @@ import static io.restassured.RestAssured.given; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; -import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithUpgradeComponentTest.APP_NAME_1; +import static org.springframework.cloud.appbroker.integration.UpdateInstanceWithUpgradeComponentTests.APP_NAME_1; -@TestPropertySource(properties = { - "spring.cloud.appbroker.services[0].service-name=example", - "spring.cloud.appbroker.services[0].plan-name=standard", - "spring.cloud.appbroker.services[0].apps[0].path=classpath:demo.jar", - "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME_1, - "spring.cloud.appbroker.services[0].apps[0].environment.ENV_VAR=testEnv", - "spring.cloud.appbroker.services[0].apps[0].parameters-transformers[0].name=PropertyMapping", - "spring.cloud.appbroker.services[0].apps[0].parameters-transformers[0].args.include=upgrade" -}) -class UpdateInstanceWithUpgradeComponentTest extends WiremockComponentTest { +@TestPropertySource(properties = { "spring.cloud.appbroker.services[0].service-name=example", + "spring.cloud.appbroker.services[0].plan-name=standard", + "spring.cloud.appbroker.services[0].apps[0].path=classpath:demo.jar", + "spring.cloud.appbroker.services[0].apps[0].name=" + APP_NAME_1, + "spring.cloud.appbroker.services[0].apps[0].environment.ENV_VAR=testEnv", + "spring.cloud.appbroker.services[0].apps[0].parameters-transformers[0].name=PropertyMapping", + "spring.cloud.appbroker.services[0].apps[0].parameters-transformers[0].args.include=upgrade" }) +class UpdateInstanceWithUpgradeComponentTests extends WiremockComponentTests { protected static final String APP_NAME_1 = "upgrade-first-app"; @@ -54,28 +52,26 @@ class UpdateInstanceWithUpgradeComponentTest extends WiremockComponentTest { @Test void updateAppsWhenTheyExist() { - cloudControllerFixture.stubFindSpaceV3(); - cloudControllerFixture.stubAppExists(APP_NAME_1); - cloudControllerFixture.stubUpdateAppWithUpgrade(APP_NAME_1); + this.cloudControllerFixture.stubFindSpaceV3(); + this.cloudControllerFixture.stubAppExists(APP_NAME_1); + this.cloudControllerFixture.stubUpdateAppWithUpgrade(APP_NAME_1); // when a service instance is updated with upgrade flag HashMap upgradeParameter = new HashMap<>(); upgradeParameter.put("upgrade", true); - given(brokerFixture.serviceInstanceRequest(upgradeParameter)) - .when() - .patch(brokerFixture.createServiceInstanceUrl(), "instance-id") + given(this.brokerFixture.serviceInstanceRequest(upgradeParameter)).when() + .patch(this.brokerFixture.createServiceInstanceUrl(), "instance-id") .then() .statusCode(HttpStatus.ACCEPTED.value()); // when the "last_operation" API is polled - given(brokerFixture.serviceInstanceRequest()) - .when() - .get(brokerFixture.getLastInstanceOperationUrl(), "instance-id") + given(this.brokerFixture.serviceInstanceRequest()).when() + .get(this.brokerFixture.getLastInstanceOperationUrl(), "instance-id") .then() .statusCode(HttpStatus.OK.value()) .body("state", is(equalTo(OperationState.IN_PROGRESS.toString()))); - String state = brokerFixture.waitForAsyncOperationComplete("instance-id"); + String state = this.brokerFixture.waitForAsyncOperationComplete("instance-id"); assertThat(state).isEqualTo(OperationState.SUCCEEDED.toString()); } diff --git a/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/WiremockComponentTest.java b/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/WiremockComponentTests.java similarity index 63% rename from spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/WiremockComponentTest.java rename to spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/WiremockComponentTests.java index ae59f71..4754824 100644 --- a/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/WiremockComponentTest.java +++ b/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/WiremockComponentTests.java @@ -32,27 +32,20 @@ import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit.jupiter.SpringExtension; @ExtendWith(SpringExtension.class) -@SpringBootTest( - webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, - classes = {AppBrokerApplication.class, - WiremockServerFixture.class, - OpenServiceBrokerApiFixture.class, - CloudControllerStubFixture.class, - UaaStubFixture.class}, - properties = { - "spring.cloud.appbroker.deployer.cloudfoundry.api-host=localhost", - "spring.cloud.appbroker.deployer.cloudfoundry.api-port=8080", - "spring.cloud.appbroker.deployer.cloudfoundry.username=admin", - "spring.cloud.appbroker.deployer.cloudfoundry.password=adminpass", - "spring.cloud.appbroker.deployer.cloudfoundry.default-org=test", - "spring.cloud.appbroker.deployer.cloudfoundry.default-space=development", - "spring.cloud.appbroker.deployer.cloudfoundry.secure=false", - "spring.cloud.appbroker.deployer.cloudfoundry.properties.buildpack=example-buildpack" - } -) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, + classes = { AppBrokerApplication.class, WiremockServerFixture.class, OpenServiceBrokerApiFixture.class, + CloudControllerStubFixture.class, UaaStubFixture.class }, + properties = { "spring.cloud.appbroker.deployer.cloudfoundry.api-host=localhost", + "spring.cloud.appbroker.deployer.cloudfoundry.api-port=8080", + "spring.cloud.appbroker.deployer.cloudfoundry.username=admin", + "spring.cloud.appbroker.deployer.cloudfoundry.password=adminpass", + "spring.cloud.appbroker.deployer.cloudfoundry.default-org=test", + "spring.cloud.appbroker.deployer.cloudfoundry.default-space=development", + "spring.cloud.appbroker.deployer.cloudfoundry.secure=false", + "spring.cloud.appbroker.deployer.cloudfoundry.properties.buildpack=example-buildpack" }) @ActiveProfiles("openservicebroker-catalog") @TestInstance(TestInstance.Lifecycle.PER_CLASS) -class WiremockComponentTest { +class WiremockComponentTests { @Autowired private WiremockServerFixture wiremockFixture; @@ -65,20 +58,20 @@ class WiremockComponentTest { @AfterAll void tearDown() { - wiremockFixture.stopWiremock(); + this.wiremockFixture.stopWiremock(); } @BeforeEach void resetWiremock() { - wiremockFixture.resetWiremock(); + this.wiremockFixture.resetWiremock(); - uaaFixture.stubCommonUaaRequests(); - cloudFoundryFixture.stubCommonCloudControllerRequests(); + this.uaaFixture.stubCommonUaaRequests(); + this.cloudFoundryFixture.stubCommonCloudControllerRequests(); } @AfterEach void verifyStubs() { - wiremockFixture.verifyAllRequiredStubsUsed(); + this.wiremockFixture.verifyAllRequiredStubsUsed(); } } diff --git a/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/fixtures/CloudControllerStubFixture.java b/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/fixtures/CloudControllerStubFixture.java index 3e041d1..dc108bb 100644 --- a/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/fixtures/CloudControllerStubFixture.java +++ b/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/fixtures/CloudControllerStubFixture.java @@ -57,73 +57,44 @@ public class CloudControllerStubFixture extends WiremockStubFixture { } private void stubGetPlatformInfo() { - stubFor(get(urlEqualTo("/")) - .withMetadata(optionalStubMapping()) - .willReturn(ok() - .withBody(cc("get-root")))); + stubFor(get(urlEqualTo("/")).withMetadata(optionalStubMapping()).willReturn(ok().withBody(cc("get-root")))); - stubFor(get(urlEqualTo("/v2/info")) - .withMetadata(optionalStubMapping()) - .willReturn(ok() - .withBody(cc("get-info")))); + stubFor(get(urlEqualTo("/v2/info")).withMetadata(optionalStubMapping()) + .willReturn(ok().withBody(cc("get-info")))); } public void stubFindTestOrg() { - stubFor(get(urlPathEqualTo("/v2/organizations")) - .withMetadata(optionalStubMapping()) - .willReturn(ok() - .withBody(cc("list-organizations", - replace("@org-guid", TEST_ORG_GUID))))); + stubFor(get(urlPathEqualTo("/v2/organizations")).withMetadata(optionalStubMapping()) + .willReturn(ok().withBody(cc("list-organizations", replace("@org-guid", TEST_ORG_GUID))))); - stubFor(get(urlPathEqualTo("/v2/organizations/" + TEST_ORG_GUID)) - .withMetadata(optionalStubMapping()) - .willReturn(ok() - .withBody(cc("get-organization", - replace("@org-guid", TEST_ORG_GUID))))); + stubFor(get(urlPathEqualTo("/v2/organizations/" + TEST_ORG_GUID)).withMetadata(optionalStubMapping()) + .willReturn(ok().withBody(cc("get-organization", replace("@org-guid", TEST_ORG_GUID))))); } private void stubFindTestOrgV3() { - stubFor(get(urlPathEqualTo("/v3/organizations")) - .withMetadata(optionalStubMapping()) - .willReturn(ok() - .withBody(cc("list-organizations-v3", - replace("@org-guid", TEST_ORG_GUID))))); + stubFor(get(urlPathEqualTo("/v3/organizations")).withMetadata(optionalStubMapping()) + .willReturn(ok().withBody(cc("list-organizations-v3", replace("@org-guid", TEST_ORG_GUID))))); - stubFor(get(urlPathEqualTo("/v3/organizations/" + TEST_ORG_GUID)) - .withMetadata(optionalStubMapping()) - .willReturn(ok() - .withBody(cc("get-organization-v3", - replace("@org-guid", TEST_ORG_GUID))))); + stubFor(get(urlPathEqualTo("/v3/organizations/" + TEST_ORG_GUID)).withMetadata(optionalStubMapping()) + .willReturn(ok().withBody(cc("get-organization-v3", replace("@org-guid", TEST_ORG_GUID))))); } public void stubFindSpace(String spaceName, String spaceGuid) { - stubFor(get(urlPathEqualTo("/v2/spaces")) - .withQueryParam("q", equalTo("name:" + spaceName)) + stubFor(get(urlPathEqualTo("/v2/spaces")).withQueryParam("q", equalTo("name:" + spaceName)) .withMetadata(optionalStubMapping()) - .willReturn(ok() - .withBody(cc("list-spaces", - replace("@org-guid", TEST_ORG_GUID), - replace("@name", spaceName), + .willReturn(ok().withBody(cc("list-spaces", replace("@org-guid", TEST_ORG_GUID), + replace("@name", spaceName), replace("@space-guid", spaceGuid))))); + + stubFor(get(urlPathEqualTo("/v2/spaces/" + spaceGuid)).withMetadata(optionalStubMapping()) + .willReturn(ok().withBody(cc("get-space", replace("@name", "test"), replace("@org-guid", TEST_ORG_GUID), replace("@space-guid", spaceGuid))))); - stubFor(get(urlPathEqualTo("/v2/spaces/" + spaceGuid)) + stubFor(get(urlPathEqualTo("/v2/spaces/" + spaceGuid + "/apps")).withQueryParam("page", equalTo("1")) .withMetadata(optionalStubMapping()) - .willReturn(ok() - .withBody(cc("get-space", - replace("@name", "test"), - replace("@org-guid", TEST_ORG_GUID), - replace("@space-guid", spaceGuid))))); + .willReturn(ok().withBody(cc("empty-query-results")))); - stubFor(get(urlPathEqualTo("/v2/spaces/" + spaceGuid + "/apps")) - .withQueryParam("page", equalTo("1")) - .withMetadata(optionalStubMapping()) - .willReturn(ok() - .withBody(cc("empty-query-results")))); - - stubFor(get(urlPathEqualTo("/v2/spaces/" + spaceGuid + "/security_groups")) - .withMetadata(optionalStubMapping()) - .willReturn(ok() - .withBody(cc("get-space-security_groups")))); + stubFor(get(urlPathEqualTo("/v2/spaces/" + spaceGuid + "/security_groups")).withMetadata(optionalStubMapping()) + .willReturn(ok().withBody(cc("get-space-security_groups")))); } public void stubFindSpaceV3() { @@ -135,78 +106,53 @@ public class CloudControllerStubFixture extends WiremockStubFixture { } public void stubFindSpaceV3(String spaceName, String spaceGuid) { - stubFor(get(urlPathEqualTo("/v3/spaces")) - .withQueryParam("names", equalTo(spaceName)) + stubFor(get(urlPathEqualTo("/v3/spaces")).withQueryParam("names", equalTo(spaceName)) .withQueryParam("organization_guids", equalTo(TEST_ORG_GUID)) .withQueryParam("page", equalTo("1")) - .willReturn(ok() - .withBody(cc("list-spaces-v3", - replace("@org-guid", TEST_ORG_GUID), - replace("@name", spaceName), + .willReturn(ok().withBody(cc("list-spaces-v3", replace("@org-guid", TEST_ORG_GUID), + replace("@name", spaceName), replace("@space-guid", spaceGuid))))); + + stubFor(get(urlPathEqualTo("/v3/spaces/" + spaceGuid)).withMetadata(optionalStubMapping()) + .willReturn(ok().withBody(cc("get-space-v3", replace("@name", "test"), replace("@org-guid", TEST_ORG_GUID), replace("@space-guid", spaceGuid))))); - stubFor(get(urlPathEqualTo("/v3/spaces/" + spaceGuid)) + stubFor(get(urlPathEqualTo("/v3/spaces/" + spaceGuid + "/apps")).withQueryParam("page", equalTo("1")) .withMetadata(optionalStubMapping()) - .willReturn(ok() - .withBody(cc("get-space-v3", - replace("@name", "test"), - replace("@org-guid", TEST_ORG_GUID), - replace("@space-guid", spaceGuid))))); + .willReturn(ok().withBody(cc("empty-query-results")))); - stubFor(get(urlPathEqualTo("/v3/spaces/" + spaceGuid + "/apps")) - .withQueryParam("page", equalTo("1")) - .withMetadata(optionalStubMapping()) - .willReturn(ok() - .withBody(cc("empty-query-results")))); - - stubFor(get(urlPathEqualTo("/v3/spaces/" + spaceGuid + "/security_groups")) - .withMetadata(optionalStubMapping()) - .willReturn(ok() - .withBody(cc("get-space-security_groups")))); + stubFor(get(urlPathEqualTo("/v3/spaces/" + spaceGuid + "/security_groups")).withMetadata(optionalStubMapping()) + .willReturn(ok().withBody(cc("get-space-security_groups")))); } private void stubFindDomains() { - stubFor(get(urlPathEqualTo("/v2/shared_domains")) - .withMetadata(optionalStubMapping()) - .willReturn(ok() - .withBody(cc("list-shared-domains", - replace("@org-guid", TEST_ORG_GUID))))); + stubFor(get(urlPathEqualTo("/v2/shared_domains")).withMetadata(optionalStubMapping()) + .willReturn(ok().withBody(cc("list-shared-domains", replace("@org-guid", TEST_ORG_GUID))))); stubFor(get(urlPathEqualTo("/v2/organizations/" + TEST_ORG_GUID + "/private_domains")) .withMetadata(optionalStubMapping()) - .willReturn(ok() - .withBody(cc("empty-query-results")))); + .willReturn(ok().withBody(cc("empty-query-results")))); stubFor(get(urlPathEqualTo("/v2/organizations/" + TEST_ORG_GUID + "/spaces")) .withQueryParam("page", equalTo("1")) .withMetadata(optionalStubMapping()) - .willReturn(ok() - .withBody(cc("list-spaces", - replace("@org-guid", TEST_ORG_GUID), - replace("@space-guid", TEST_SPACE_GUID))))); + .willReturn(ok().withBody( + cc("list-spaces", replace("@org-guid", TEST_ORG_GUID), replace("@space-guid", TEST_SPACE_GUID))))); stubFor(get(urlPathEqualTo("/v2/organizations/" + TEST_ORG_GUID + "/space_quota_definitions")) .withQueryParam("page", equalTo("1")) .withMetadata(optionalStubMapping()) - .willReturn(ok() - .withBody(cc("list-organizations-quota", - replace("@org-guid", TEST_ORG_GUID))))); + .willReturn(ok().withBody(cc("list-organizations-quota", replace("@org-guid", TEST_ORG_GUID))))); stubFor(get(urlPathEqualTo("/v2/quota_definitions/" + TEST_QUOTA_DEFINITION_GUID)) .withMetadata(optionalStubMapping()) - .willReturn(ok() - .withBody(cc("get-organizations-quota", - replace("@org-guid", TEST_ORG_GUID))))); + .willReturn(ok().withBody(cc("get-organizations-quota", replace("@org-guid", TEST_ORG_GUID))))); } public void stubCreateSpace(final String spaceName, final String spaceGuid) { stubFor(post(urlPathEqualTo("/v2/spaces")) .withRequestBody(matchingJsonPath("$.[?(@.name == '" + spaceName + "')]")) .withRequestBody(matchingJsonPath("$.[?(@.organization_guid == '" + TEST_ORG_GUID + "')]")) - .willReturn(ok() - .withBody(cc("get-space", - replace("@name", spaceName), - replace("@space-guid", spaceGuid), + .willReturn(ok().withBody(cc("get-space", replace("@name", spaceName), replace("@space-guid", spaceGuid), replace("@org-guid", TEST_ORG_GUID))))); stubFindSpace(spaceName, spaceGuid); @@ -216,90 +162,57 @@ public class CloudControllerStubFixture extends WiremockStubFixture { stubFor(get(urlPathEqualTo("/v2/spaces/" + TEST_SPACE_GUID + "/apps")) .withQueryParam("q", equalTo("name:" + appName)) .withQueryParam("page", equalTo("1")) - .willReturn(ok() - .withBody(cc("empty-query-results")))); + .willReturn(ok().withBody(cc("empty-query-results")))); } public void stubAppExistsInSpace(final String appName, final String spaceGuid) { - stubFor(get(urlPathEqualTo("/v2/apps/" + appGuid(appName))) - .withMetadata(optionalStubMapping()) - .willReturn(ok() - .withBody(cc("get-app-STAGED", - replace("@name", appName))))); + stubFor(get(urlPathEqualTo("/v2/apps/" + appGuid(appName))).withMetadata(optionalStubMapping()) + .willReturn(ok().withBody(cc("get-app-STAGED", replace("@name", appName))))); - stubFor(get(urlPathEqualTo("/v2/spaces/" + spaceGuid + "/apps")) - .withQueryParam("q", equalTo("name:" + appName)) + stubFor(get(urlPathEqualTo("/v2/spaces/" + spaceGuid + "/apps")).withQueryParam("q", equalTo("name:" + appName)) .withQueryParam("page", equalTo("1")) - .willReturn(ok() - .withBody(cc("list-space-apps", - replace("@name", appName), - replace("@guid", appGuid(appName)), - replace("@space-guid", spaceGuid), - replace("@stack-guid", stackGuid(appName)))))); + .willReturn( + ok().withBody(cc("list-space-apps", replace("@name", appName), replace("@guid", appGuid(appName)), + replace("@space-guid", spaceGuid), replace("@stack-guid", stackGuid(appName)))))); stubFor(get(urlPathEqualTo("/v2/apps/" + appGuid(appName) + "/instances")) - .willReturn(ok() - .withBody(cc("get-app-instances")))); + .willReturn(ok().withBody(cc("get-app-instances")))); - stubFor(get(urlPathEqualTo("/v2/apps/" + appGuid(appName) + "/summary")) - .withMetadata(optionalStubMapping()) - .willReturn(ok() - .withBody(cc("get-app-summary", - replace("@name", appName), - replace("@guid", appGuid(appName)), - replace("@stack-guid", stackGuid(appName)), - replace("@route-guid", routeGuid(appName)))))); + stubFor(get(urlPathEqualTo("/v2/apps/" + appGuid(appName) + "/summary")).withMetadata(optionalStubMapping()) + .willReturn( + ok().withBody(cc("get-app-summary", replace("@name", appName), replace("@guid", appGuid(appName)), + replace("@stack-guid", stackGuid(appName)), replace("@route-guid", routeGuid(appName)))))); stubFor(get(urlPathEqualTo("/v2/apps/" + appGuid(appName) + "/stats")) - .willReturn(ok() - .withBody(cc("get-app-stats", - replace("@name", appName))))); + .willReturn(ok().withBody(cc("get-app-stats", replace("@name", appName))))); stubFor(get(urlPathEqualTo("/v2/stacks/" + stackGuid(appName))) - .willReturn(ok() - .withBody(cc("get-stack", - replace("@guid", stackGuid(appName)))))); + .willReturn(ok().withBody(cc("get-stack", replace("@guid", stackGuid(appName)))))); } public void stubAppExistsInSpaceV3(final String appName, final String spaceGuid) { - stubFor(get(urlPathEqualTo("/v3/apps/" + appGuid(appName))) - .withMetadata(optionalStubMapping()) - .willReturn(ok() - .withBody(cc("get-app-STAGED-v3", - replace("@name", appName))))); + stubFor(get(urlPathEqualTo("/v3/apps/" + appGuid(appName))).withMetadata(optionalStubMapping()) + .willReturn(ok().withBody(cc("get-app-STAGED-v3", replace("@name", appName))))); - stubFor(get(urlPathEqualTo("/v2/spaces/" + spaceGuid + "/apps")) - .withQueryParam("q", equalTo("name:" + appName)) + stubFor(get(urlPathEqualTo("/v2/spaces/" + spaceGuid + "/apps")).withQueryParam("q", equalTo("name:" + appName)) .withQueryParam("page", equalTo("1")) - .willReturn(ok() - .withBody(cc("list-space-apps", - replace("@name", appName), - replace("@guid", appGuid(appName)), - replace("@space-guid", spaceGuid), - replace("@stack-guid", stackGuid(appName)))))); + .willReturn( + ok().withBody(cc("list-space-apps", replace("@name", appName), replace("@guid", appGuid(appName)), + replace("@space-guid", spaceGuid), replace("@stack-guid", stackGuid(appName)))))); stubFor(get(urlPathEqualTo("/v2/apps/" + appGuid(appName) + "/instances")) - .willReturn(ok() - .withBody(cc("get-app-instances")))); + .willReturn(ok().withBody(cc("get-app-instances")))); - stubFor(get(urlPathEqualTo("/v2/apps/" + appGuid(appName) + "/summary")) - .withMetadata(optionalStubMapping()) - .willReturn(ok() - .withBody(cc("get-app-summary", - replace("@name", appName), - replace("@guid", appGuid(appName)), - replace("@stack-guid", stackGuid(appName)), - replace("@route-guid", routeGuid(appName)))))); + stubFor(get(urlPathEqualTo("/v2/apps/" + appGuid(appName) + "/summary")).withMetadata(optionalStubMapping()) + .willReturn( + ok().withBody(cc("get-app-summary", replace("@name", appName), replace("@guid", appGuid(appName)), + replace("@stack-guid", stackGuid(appName)), replace("@route-guid", routeGuid(appName)))))); stubFor(get(urlPathEqualTo("/v2/apps/" + appGuid(appName) + "/stats")) - .willReturn(ok() - .withBody(cc("get-app-stats", - replace("@name", appName))))); + .willReturn(ok().withBody(cc("get-app-stats", replace("@name", appName))))); stubFor(get(urlPathEqualTo("/v2/stacks/" + stackGuid(appName))) - .willReturn(ok() - .withBody(cc("get-stack", - replace("@guid", stackGuid(appName)))))); + .willReturn(ok().withBody(cc("get-stack", replace("@guid", stackGuid(appName)))))); } public void stubAppExists(final String appName) { @@ -311,23 +224,19 @@ public class CloudControllerStubFixture extends WiremockStubFixture { } public void stubAppExistsWithBackingService(final String appName, final String serviceInstanceName, - final String serviceName, final String planName) { + final String serviceName, final String planName) { stubAppExistsWithBackingService(appName, serviceInstanceName, serviceName, planName, TEST_SPACE_GUID); } public void stubAppExistsWithBackingService(final String appName, final String serviceInstanceName, - final String serviceName, final String planName, final String spaceGuid) { + final String serviceName, final String planName, final String spaceGuid) { stubAppExistsInSpace(appName, spaceGuid); stubFor(get(urlPathEqualTo("/v2/apps/" + appGuid(appName) + "/summary")) - .willReturn(ok() - .withBody(cc("get-app-summary-with-backing-service", - replace("@name", appName), + .willReturn(ok().withBody(cc("get-app-summary-with-backing-service", replace("@name", appName), replace("@service-instance-name", serviceInstanceName), - replace("@service-guid", serviceGuid(serviceName)), - replace("@plan-guid", planGuid(planName)), - replace("@guid", appGuid(appName)), - replace("@stack-guid", stackGuid(appName)), + replace("@service-guid", serviceGuid(serviceName)), replace("@plan-guid", planGuid(planName)), + replace("@guid", appGuid(appName)), replace("@stack-guid", stackGuid(appName)), replace("@route-guid", routeGuid(appName)))))); } @@ -368,12 +277,8 @@ public class CloudControllerStubFixture extends WiremockStubFixture { } private void stubGetV3App(String appName) { - stubFor(get(urlPathEqualTo("/v3/apps/" + appGuid(appName))) - .willReturn(ok() - .withBody(cc("get-v3-app-STARTED", - replace("@name", appName), - replace("@guid", appGuid(appName)) - )))); + stubFor(get(urlPathEqualTo("/v3/apps/" + appGuid(appName))).willReturn(ok() + .withBody(cc("get-v3-app-STARTED", replace("@name", appName), replace("@guid", appGuid(appName)))))); } private void stubAppAfterCreation(String appName, String host) { @@ -387,72 +292,49 @@ public class CloudControllerStubFixture extends WiremockStubFixture { stubFor(put(urlPathEqualTo("/v2/apps/" + appGuid(appName))) .withRequestBody(matchingJsonPath("$.[?(@.environment_json)]")) .willReturn(ok() - .withBody(cc("get-app-STARTED", - replace("@name", appName), - replace("@guid", appGuid(appName)))))); + .withBody(cc("get-app-STARTED", replace("@name", appName), replace("@guid", appGuid(appName)))))); } private void stubCreatePackage(String appName) { stubFor(post(urlPathEqualTo("/v3/packages")) - .withRequestBody( - matchingJsonPath("$.[?(@.relationships.app.data.guid == '" + appGuid(appName) + "')]")) - .willReturn(ok() - .withBody(cc("get-package-READY", - replace("@guid", packageGuid(appName)), + .withRequestBody(matchingJsonPath("$.[?(@.relationships.app.data.guid == '" + appGuid(appName) + "')]")) + .willReturn(ok().withBody(cc("get-package-READY", replace("@guid", packageGuid(appName)), replace("@app-guid", appGuid(appName)))))); stubFor(post(urlPathEqualTo("/v3/packages/" + packageGuid(appName) + "/upload")) - .willReturn(ok() - .withBody(cc("get-package-READY", - replace("@guid", packageGuid(appName)), + .willReturn(ok().withBody(cc("get-package-READY", replace("@guid", packageGuid(appName)), replace("@app-guid", appGuid(appName)))))); stubFor(get(urlPathEqualTo("/v3/packages/" + packageGuid(appName))) - .willReturn(ok() - .withBody(cc("get-package-READY", - replace("@guid", packageGuid(appName)), + .willReturn(ok().withBody(cc("get-package-READY", replace("@guid", packageGuid(appName)), replace("@app-guid", appGuid(appName)))))); } private void stubGetPackage(String appName) { stubFor(get(urlPathEqualTo("/v3/apps/" + appGuid(appName) + "/packages")) .withQueryParam("states", equalTo("READY")) - .willReturn(ok() - .withBody(cc("get-packages-READY", - replace("@package-guid", packageGuid(appName)))))); + .willReturn(ok().withBody(cc("get-packages-READY", replace("@package-guid", packageGuid(appName)))))); } private void stubCreateBuild(String appName) { stubFor(post(urlPathEqualTo("/v3/builds")) - .withRequestBody( - matchingJsonPath("$.[?(@.package.guid == '" + packageGuid(appName) + "')]")) - .willReturn(ok() - .withBody(cc("get-build-STAGED", - replace("@guid", buildGuid(appName)), - replace("@package-guid", packageGuid(appName)), - replace("@app-guid", appGuid(appName)))))); + .withRequestBody(matchingJsonPath("$.[?(@.package.guid == '" + packageGuid(appName) + "')]")) + .willReturn(ok().withBody(cc("get-build-STAGED", replace("@guid", buildGuid(appName)), + replace("@package-guid", packageGuid(appName)), replace("@app-guid", appGuid(appName)))))); stubFor(get(urlPathEqualTo("/v3/builds/" + buildGuid(appName))) - .willReturn(ok() - .withBody(cc("get-build-STAGED", - replace("@guid", buildGuid(appName)), - replace("@package-guid", packageGuid(appName)), - replace("@app-guid", appGuid(appName)))))); + .willReturn(ok().withBody(cc("get-build-STAGED", replace("@guid", buildGuid(appName)), + replace("@package-guid", packageGuid(appName)), replace("@app-guid", appGuid(appName)))))); } private void stubCreateDeployment(String appName) { stubFor(post(urlPathEqualTo("/v3/deployments")) - .withRequestBody( - matchingJsonPath("$.[?(@.relationships.app.data.guid == '" + appGuid(appName) + "')]")) - .willReturn(ok() - .withBody(cc("get-deployment-DEPLOYED", - replace("@guid", deploymentGuid(appName)), + .withRequestBody(matchingJsonPath("$.[?(@.relationships.app.data.guid == '" + appGuid(appName) + "')]")) + .willReturn(ok().withBody(cc("get-deployment-DEPLOYED", replace("@guid", deploymentGuid(appName)), replace("@app-guid", appGuid(appName)))))); stubFor(get(urlPathEqualTo("/v3/deployments/" + deploymentGuid(appName))) - .willReturn(ok() - .withBody(cc("get-deployment-DEPLOYED", - replace("@guid", deploymentGuid(appName)), + .willReturn(ok().withBody(cc("get-deployment-DEPLOYED", replace("@guid", deploymentGuid(appName)), replace("@app-guid", appGuid(appName)))))); } @@ -462,102 +344,70 @@ public class CloudControllerStubFixture extends WiremockStubFixture { for (ContentPattern appMetadataPattern : appMetadataPatterns) { mappingBuilder.withRequestBody(appMetadataPattern); } - stubFor(mappingBuilder - .willReturn(ok() - .withBody(cc("get-app-STOPPED", - replace("@name", appName), - replace("@guid", appGuid(appName)))))); + stubFor(mappingBuilder.willReturn( + ok().withBody(cc("get-app-STOPPED", replace("@name", appName), replace("@guid", appGuid(appName)))))); } private void stubMapRouteToApp(String appName, String host) { - stubFor(get(urlPathEqualTo("/v2/apps/" + appGuid(appName) + "/routes")) - .withQueryParam("page", equalTo("1")) - .willReturn(ok() - .withBody(cc("empty-query-results")))); + stubFor(get(urlPathEqualTo("/v2/apps/" + appGuid(appName) + "/routes")).withQueryParam("page", equalTo("1")) + .willReturn(ok().withBody(cc("empty-query-results")))); - stubFor(get(urlPathEqualTo("/v2/routes")) - .withQueryParam("q", equalTo("domain_guid:" + TEST_ORG_GUID)) + stubFor(get(urlPathEqualTo("/v2/routes")).withQueryParam("q", equalTo("domain_guid:" + TEST_ORG_GUID)) .withQueryParam("q", equalTo("host:" + host)) .withQueryParam("page", equalTo("1")) - .willReturn(ok() - .withBody(cc("empty-query-results")))); + .willReturn(ok().withBody(cc("empty-query-results")))); - stubFor(post(urlPathEqualTo("/v2/routes")) - .withRequestBody(matchingJsonPath("$.[?(@.host == '" + host + "')]")) + stubFor(post(urlPathEqualTo("/v2/routes")).withRequestBody(matchingJsonPath("$.[?(@.host == '" + host + "')]")) .willReturn(created() - .withBody(cc("list-routes", - replace("@name", appName), - replace("@guid", routeGuid(appName)))))); + .withBody(cc("list-routes", replace("@name", appName), replace("@guid", routeGuid(appName)))))); stubFor(put(urlPathEqualTo("/v2/apps/" + appGuid(appName) + "/routes/" + routeGuid(appName))) .willReturn(created() - .withBody(cc("get-app-STOPPED", - replace("@name", appName), - replace("@guid", appGuid(appName)))))); + .withBody(cc("get-app-STOPPED", replace("@name", appName), replace("@guid", appGuid(appName)))))); } private void stubUploadAppBits(String appName) { - stubFor(put(urlPathEqualTo("/v2/resource_match")) - .withMetadata(optionalStubMapping()) - .willReturn(ok() - .withBody("[]"))); + stubFor(put(urlPathEqualTo("/v2/resource_match")).withMetadata(optionalStubMapping()) + .willReturn(ok().withBody("[]"))); - stubFor(put(urlPathEqualTo("/v2/apps/" + appGuid(appName) + "/bits")) - .withQueryParam("async", equalTo("true")) - .willReturn(created() - .withBody(cc("put-app-bits", - replace("@guid", appName + "-JOB-GUID"))))); + stubFor(put(urlPathEqualTo("/v2/apps/" + appGuid(appName) + "/bits")).withQueryParam("async", equalTo("true")) + .willReturn(created().withBody(cc("put-app-bits", replace("@guid", appName + "-JOB-GUID"))))); } private void stubInitializeAppState(String appName) { stubFor(put(urlPathEqualTo("/v2/apps/" + appGuid(appName))) .withRequestBody(matchingJsonPath("$.[?(@.state == 'STOPPED')]")) .willReturn(created() - .withBody(cc("get-app-STOPPED", - replace("@name", appName), - replace("@guid", appGuid(appName)))))); + .withBody(cc("get-app-STOPPED", replace("@name", appName), replace("@guid", appGuid(appName)))))); stubFor(put(urlPathEqualTo("/v2/apps/" + appGuid(appName))) .withRequestBody(matchingJsonPath("$.[?(@.state == 'STARTED')]")) .willReturn(created() - .withBody(cc("get-app-STARTED", - replace("@name", appName), - replace("@guid", appGuid(appName)))))); + .withBody(cc("get-app-STARTED", replace("@name", appName), replace("@guid", appGuid(appName)))))); } private void stubCheckAppState(String appName) { stubFor(get(urlPathEqualTo("/v2/apps/" + appGuid(appName))) - .willReturn(ok() - .withBody(cc("get-app-STAGED", - replace("@name", appName))))); + .willReturn(ok().withBody(cc("get-app-STAGED", replace("@name", appName))))); stubFor(get(urlPathEqualTo("/v2/apps/" + appGuid(appName) + "/instances")) - .willReturn(ok() - .withBody(cc("get-app-instances")))); + .willReturn(ok().withBody(cc("get-app-instances")))); } private void stubCreateRouteInSpace(final String appName, final String spaceGuid) { - stubFor(get(urlPathEqualTo("/v2/private_domains")) - .withQueryParam("page", equalTo("1")) + stubFor(get(urlPathEqualTo("/v2/private_domains")).withQueryParam("page", equalTo("1")) .withMetadata(optionalStubMapping()) - .willReturn(ok() - .withBody(cc("empty-query-results")))); + .willReturn(ok().withBody(cc("empty-query-results")))); - stubFor(get(urlPathEqualTo("/v2/spaces/" + spaceGuid + "/services")) - .withQueryParam("page", equalTo("1")) - .willReturn(ok() - .withBody(cc("list-space-services") - .replace("@service-guid", "SERVICE-ID") - .replace("@service-name", "db-service")))); + stubFor(get(urlPathEqualTo("/v2/spaces/" + spaceGuid + "/services")).withQueryParam("page", equalTo("1")) + .willReturn(ok().withBody(cc("list-space-services").replace("@service-guid", "SERVICE-ID") + .replace("@service-name", "db-service")))); stubFor(post(urlPathEqualTo("/v2/routes")) - .willReturn(ok() - .withBody(cc("post-route") - .replace("@guid", routeGuid(appName))))); + .willReturn(ok().withBody(cc("post-route").replace("@guid", routeGuid(appName))))); stubFor(put(urlPathEqualTo("/v2/apps/" + appGuid(appName) + "/routes/" + routeGuid(appName))) - .willReturn(ok() - .withBody(cc("get-app-summary")))); + .willReturn(ok().withBody(cc("get-app-summary")))); } private void stubCreateRoute(final String appName) { @@ -566,12 +416,9 @@ public class CloudControllerStubFixture extends WiremockStubFixture { public void stubDeleteApp(String appName) { stubFor(delete(urlPathEqualTo("/v2/routes/" + appName + "-ROUTE-GUID")) - .willReturn(ok() - .withBody(cc("get-route", - replace("@guid", routeGuid(appName)))))); + .willReturn(ok().withBody(cc("get-route", replace("@guid", routeGuid(appName)))))); - stubFor(delete(urlPathEqualTo("/v2/apps/" + appGuid(appName))) - .willReturn(noContent())); + stubFor(delete(urlPathEqualTo("/v2/apps/" + appGuid(appName))).willReturn(noContent())); } public void stubServiceInstanceExists(String serviceInstanceName) { @@ -583,45 +430,40 @@ public class CloudControllerStubFixture extends WiremockStubFixture { } public void stubServiceInstanceExists(String serviceInstanceName, String serviceName, String planName) { - stubServiceInstanceExists(serviceInstanceGuid(serviceInstanceName), serviceInstanceName, serviceName, - planName, TEST_SPACE_GUID); + stubServiceInstanceExists(serviceInstanceGuid(serviceInstanceName), serviceInstanceName, serviceName, planName, + TEST_SPACE_GUID); } public void stubServiceInstanceExistsInSpace(String serviceInstanceName, String serviceName, String planName, - String spaceGuid) { - stubServiceInstanceExists(serviceInstanceGuid(serviceInstanceName), serviceInstanceName, serviceName, - planName, spaceGuid); + String spaceGuid) { + stubServiceInstanceExists(serviceInstanceGuid(serviceInstanceName), serviceInstanceName, serviceName, planName, + spaceGuid); } - private void stubServiceInstanceExists(String serviceInstanceId, String serviceInstanceName, - String serviceName, String planName, String spaceGuid) { + private void stubServiceInstanceExists(String serviceInstanceId, String serviceInstanceName, String serviceName, + String planName, String spaceGuid) { stubFor(get(urlPathEqualTo("/v2/spaces/" + spaceGuid + "/service_instances")) .withQueryParam("q", equalTo("name:" + serviceInstanceName)) .withQueryParam("page", equalTo("1")) .withQueryParam("return_user_provided_service_instances", equalTo("true")) - .willReturn(ok() - .withBody(cc("list-space-service_instances", - replace("@space-guid", spaceGuid), - replace("@service-guid", serviceGuid(serviceName)), - replace("@plan-guid", planGuid(planName)), - replace("@name", serviceInstanceName), - replace("@guid", serviceInstanceId))))); + .willReturn(ok().withBody(cc("list-space-service_instances", replace("@space-guid", spaceGuid), + replace("@service-guid", serviceGuid(serviceName)), replace("@plan-guid", planGuid(planName)), + replace("@name", serviceInstanceName), replace("@guid", serviceInstanceId))))); } public void stubServiceBindingsDoNotExist(String serviceInstanceName) { stubFor(get(urlPathEqualTo("/v2/service_bindings")) .withQueryParam("q", equalTo("service_instance_guid:" + serviceInstanceGuid(serviceInstanceName))) .withQueryParam("page", equalTo("1")) - .willReturn(ok() - .withBody(cc("empty-query-results")))); + .willReturn(ok().withBody(cc("empty-query-results")))); } public void stubGetBackingServiceInstance(String serviceInstanceName, String serviceName, String planName) { stubGetBackingServiceInstanceFromSpace(serviceInstanceName, serviceName, planName, TEST_SPACE_GUID); } - public void stubGetBackingServiceInstanceFromSpace(String serviceInstanceName, String serviceName, - String planName, String spaceGuid) { + public void stubGetBackingServiceInstanceFromSpace(String serviceInstanceName, String serviceName, String planName, + String spaceGuid) { String serviceInstanceId = serviceInstanceGuid(serviceInstanceName); stubServiceInstanceExists(serviceInstanceId, serviceInstanceName, serviceName, planName, spaceGuid); stubGetServiceAndGetPlan(serviceName, planName); @@ -631,20 +473,16 @@ public class CloudControllerStubFixture extends WiremockStubFixture { stubFor(get(urlPathEqualTo("/v2/spaces/" + spaceGuid + "/services")) .withQueryParam("q", equalTo("label:" + serviceName)) .withQueryParam("page", equalTo("1")) - .willReturn(ok() - .withBody(cc("list-space-services") - .replace("@service-guid", serviceGuid(serviceName)) - .replace("@plan-guid", planGuid(planName)) - .replace("@service-name", serviceName)))); + .willReturn(ok().withBody(cc("list-space-services").replace("@service-guid", serviceGuid(serviceName)) + .replace("@plan-guid", planGuid(planName)) + .replace("@service-name", serviceName)))); stubFor(get(urlPathEqualTo("/v2/service_plans")) .withQueryParam("q", equalTo("service_guid:" + serviceGuid(serviceName))) .withQueryParam("page", equalTo("1")) - .willReturn(ok() - .withBody(cc("list-service-plans") - .replace("@service-guid", serviceGuid(serviceName)) - .replace("@plan-name", planName) - .replace("@plan-guid", planGuid(planName))))); + .willReturn(ok().withBody(cc("list-service-plans").replace("@service-guid", serviceGuid(serviceName)) + .replace("@plan-name", planName) + .replace("@plan-guid", planGuid(planName))))); } public void stubServiceExists(String serviceName, String planName) { @@ -652,15 +490,13 @@ public class CloudControllerStubFixture extends WiremockStubFixture { } public void stubCreateServiceInstance(String serviceInstanceName) { - stubFor(post(urlPathEqualTo("/v2/service_instances")) - .withQueryParam("accepts_incomplete", equalTo("true")) + stubFor(post(urlPathEqualTo("/v2/service_instances")).withQueryParam("accepts_incomplete", equalTo("true")) .withRequestBody(matchingJsonPath("$.[?(@.name == '" + serviceInstanceName + "')]")) .willReturn(ok())); } public void stubCreateServiceInstanceWithParameters(String serviceInstanceName, Map params) { - stubFor(post(urlPathEqualTo("/v2/service_instances")) - .withQueryParam("accepts_incomplete", equalTo("true")) + stubFor(post(urlPathEqualTo("/v2/service_instances")).withQueryParam("accepts_incomplete", equalTo("true")) .withRequestBody(matchingJsonPath("$.[?(@.name == '" + serviceInstanceName + "')]")) .withRequestBody(matchingJsonPath("$.[?(@.parameters == " + new JSONObject(params) + ")]")) .willReturn(ok())); @@ -676,8 +512,7 @@ public class CloudControllerStubFixture extends WiremockStubFixture { public void stubDeleteServiceInstance(String serviceInstanceName) { String serviceInstanceGuid = serviceInstanceGuid(serviceInstanceName); - stubFor(delete(urlPathEqualTo("/v2/service_instances/" + serviceInstanceGuid)) - .willReturn(ok())); + stubFor(delete(urlPathEqualTo("/v2/service_instances/" + serviceInstanceGuid)).willReturn(ok())); } public void stubCreateServiceBinding(String appName, String serviceInstanceName) { @@ -687,11 +522,8 @@ public class CloudControllerStubFixture extends WiremockStubFixture { stubFor(post(urlPathEqualTo("/v2/service_bindings")) .withRequestBody(matchingJsonPath("$.[?(@.app_guid == '" + appGuid(appName) + "')]")) .withRequestBody(matchingJsonPath("$.[?(@.service_instance_guid == '" + serviceInstanceGuid + "')]")) - .willReturn(created() - .withBody(cc("get-service_binding", - replace("@guid", serviceBindingGuid), - replace("@app-guid", appGuid(appName)), - replace("@service-instance-guid", serviceInstanceGuid))))); + .willReturn(created().withBody(cc("get-service_binding", replace("@guid", serviceBindingGuid), + replace("@app-guid", appGuid(appName)), replace("@service-instance-guid", serviceInstanceGuid))))); } public void stubDeleteServiceBinding(String appName, String serviceInstanceName) { @@ -709,60 +541,44 @@ public class CloudControllerStubFixture extends WiremockStubFixture { stubFor(get(urlPathEqualTo("/v2/service_bindings")) .withQueryParam("q", equalTo("service_instance_guid:" + serviceInstanceGuid)) .withQueryParam("page", equalTo("1")) - .willReturn(ok() - .withBody(cc("list-service-bindings", - replace("@guid", serviceBindingGuid), - replace("@app-guid", appGuid(appName)), - replace("@service-instance-guid", serviceInstanceGuid))))); + .willReturn(ok().withBody(cc("list-service-bindings", replace("@guid", serviceBindingGuid), + replace("@app-guid", appGuid(appName)), replace("@service-instance-guid", serviceInstanceGuid))))); stubFor(get(urlPathEqualTo("/v2/apps/" + appGuid(appName) + "/service_bindings")) .withQueryParam("q", equalTo("service_instance_guid:" + serviceInstanceGuid)) .withQueryParam("page", equalTo("1")) - .willReturn(ok() - .withBody(cc("get-service_bindings", - replace("@service-binding-guid", serviceBindingGuid), - replace("@app-guid", appGuid(appName)), - replace("@service-instance-guid", serviceInstanceGuid))))); + .willReturn(ok().withBody(cc("get-service_bindings", replace("@service-binding-guid", serviceBindingGuid), + replace("@app-guid", appGuid(appName)), replace("@service-instance-guid", serviceInstanceGuid))))); } public void stubServiceBindingDoesNotExist(String appName) { stubFor(get(urlPathEqualTo("/v2/apps/" + appGuid(appName) + "/service_bindings")) - .willReturn(ok() - .withBody(cc("empty-query-results")))); + .willReturn(ok().withBody(cc("empty-query-results")))); } public void stubAssociatePermissions() { stubFor(get(urlPathEqualTo("/v2/config/feature_flags/set_roles_by_username")) - .willReturn(ok() - .withBody(cc("get-feature-flag-roles")))); + .willReturn(ok().withBody(cc("get-feature-flag-roles")))); - stubFor(put(urlPathEqualTo("/v2/organizations/" + TEST_ORG_GUID + "/users")) - .willReturn(ok())); + stubFor(put(urlPathEqualTo("/v2/organizations/" + TEST_ORG_GUID + "/users")).willReturn(ok())); } private void stubGetServiceAndGetPlan(String serviceName, String planName) { stubFor(get(urlPathEqualTo("/v2/service_plans/" + planGuid(planName))) - .willReturn(ok() - .withBody(cc("get-service-plan") - .replace("@service-guid", serviceGuid(serviceName)) - .replace("@plan-name", planName) - .replace("@plan-guid", planGuid(planName))))); + .willReturn(ok().withBody(cc("get-service-plan").replace("@service-guid", serviceGuid(serviceName)) + .replace("@plan-name", planName) + .replace("@plan-guid", planGuid(planName))))); stubFor(get(urlPathEqualTo("/v2/services/" + serviceGuid(serviceName))) - .willReturn(ok() - .withBody(cc("get-service") - .replace("@service-guid", serviceGuid(serviceName)) - .replace("@service-name", serviceName)))); + .willReturn(ok().withBody(cc("get-service").replace("@service-guid", serviceGuid(serviceName)) + .replace("@service-name", serviceName)))); } public void stubSpaceExists(final String spaceName, final String spaceGuid) { stubFor(get(urlPathEqualTo("/v2/organizations/" + TEST_ORG_GUID + "/spaces")) .withQueryParam("q", equalTo("name:" + spaceName)) - .willReturn(ok() - .withBody(cc("list-spaces", - replace("@org-guid", TEST_ORG_GUID), - replace("@space-guid", spaceGuid), - replace("@name", spaceName))))); + .willReturn(ok().withBody(cc("list-spaces", replace("@org-guid", TEST_ORG_GUID), + replace("@space-guid", spaceGuid), replace("@name", spaceName))))); } private String cc(String fileRoot, StringReplacementPair... replacements) { diff --git a/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/fixtures/OpenServiceBrokerApiFixture.java b/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/fixtures/OpenServiceBrokerApiFixture.java index cde5539..9b3b107 100644 --- a/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/fixtures/OpenServiceBrokerApiFixture.java +++ b/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/fixtures/OpenServiceBrokerApiFixture.java @@ -61,9 +61,8 @@ public class OpenServiceBrokerApiFixture implements ApplicationListener params) { String stringParams = new JSONObject(params).toString(); - return serviceBrokerSpecification() - .body("{" + - "\"service_id\": \"" + serviceDefinitionId + "\"," + - "\"plan_id\": \"" + planId + "\"," + - "\"organization_guid\": \"" + ORG_ID + "\"," + - "\"space_guid\": \"" + SPACE_ID + "\"," + - "\"parameters\": " + stringParams + - "}"); + return serviceBrokerSpecification().body("{" + "\"service_id\": \"" + this.serviceDefinitionId + "\"," + + "\"plan_id\": \"" + this.planId + "\"," + "\"organization_guid\": \"" + ORG_ID + "\"," + + "\"space_guid\": \"" + SPACE_ID + "\"," + "\"parameters\": " + stringParams + "}"); } public RequestSpecification serviceAppBindingRequest() { return serviceBrokerSpecification() - .body("{" + - "\"service_id\": \"" + serviceDefinitionId + "\"," + - "\"plan_id\": \"" + planId + "\"," + - "\"bind_resource\": {" + - "\"app_guid\": \"" + APP_ID + "\"" + - "}" + - "}"); + .body("{" + "\"service_id\": \"" + this.serviceDefinitionId + "\"," + "\"plan_id\": \"" + this.planId + + "\"," + "\"bind_resource\": {" + "\"app_guid\": \"" + APP_ID + "\"" + "}" + "}"); } public RequestSpecification serviceKeyRequest() { - return serviceBrokerSpecification() - .body("{" + - "\"service_id\": \"" + serviceDefinitionId + "\"," + - "\"plan_id\": \"" + planId + "\"," + - "\"bind_resource\": {" + - "\"credential_client_id\": \"" + SERVICE_KEY_CLIENT_ID + "\"" + - "}" + - "}"); + return serviceBrokerSpecification().body("{" + "\"service_id\": \"" + this.serviceDefinitionId + "\"," + + "\"plan_id\": \"" + this.planId + "\"," + "\"bind_resource\": {" + "\"credential_client_id\": \"" + + SERVICE_KEY_CLIENT_ID + "\"" + "}" + "}"); } private RequestSpecification serviceBrokerSpecification() { - return with() - .baseUri("http://localhost:" + port + "/v2") + return with().baseUri("http://localhost:" + this.port + "/v2") .accept(ContentType.JSON) .contentType(ContentType.JSON); } @@ -132,13 +110,16 @@ public class OpenServiceBrokerApiFixture implements ApplicationListener servedStubIds = wireMockServer.getServeEvents().getRequests().stream() - .filter(event -> event.getStubMapping() != null) - .map(event -> event.getStubMapping().getId()) + Set servedStubIds = wireMockServer.getServeEvents() + .getRequests() + .stream() + .filter((event) -> event.getStubMapping() != null) + .map((event) -> event.getStubMapping().getId()) .collect(Collectors.toSet()); - List unusedStubs = wireMockServer.listAllStubMappings().getMappings().stream() - .filter(stub -> !servedStubIds.contains(stub.getId())) + List unusedStubs = wireMockServer.listAllStubMappings() + .getMappings() + .stream() + .filter((stub) -> !servedStubIds.contains(stub.getId())) .filter(this::stubIsRequired) .collect(Collectors.toList()); diff --git a/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/fixtures/WiremockStubFixture.java b/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/fixtures/WiremockStubFixture.java index ab9e4f1..798d2d3 100644 --- a/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/fixtures/WiremockStubFixture.java +++ b/spring-cloud-app-broker-integration-tests/src/test/java/org/springframework/cloud/appbroker/integration/fixtures/WiremockStubFixture.java @@ -41,13 +41,11 @@ public class WiremockStubFixture { private ResourceLoader resourceLoader; protected WiremockStubFixture(int port) { - wireMock = WireMock.create() - .port(port) - .build(); + this.wireMock = WireMock.create().port(port).build(); } public ListStubMappingsResult getAllStubs() { - return wireMock.allStubMappings(); + return this.wireMock.allStubMappings(); } protected StubMapping stubFor(MappingBuilder mappingBuilder) { @@ -55,7 +53,7 @@ public class WiremockStubFixture { } protected StubMapping givenThat(MappingBuilder mappingBuilder) { - return wireMock.register(mappingBuilder); + return this.wireMock.register(mappingBuilder); } protected CloudControllerStubFixture.StringReplacementPair replace(String regex, String replacement) { @@ -68,21 +66,17 @@ public class WiremockStubFixture { private String readTestDataFile(String filePath) { try { - Resource resource = resourceLoader.getResource(filePath); + Resource resource = this.resourceLoader.getResource(filePath); InputStreamReader reader = new InputStreamReader(resource.getInputStream()); - return new BufferedReader(reader) - .lines() - .collect(Collectors.joining("\n")); + return new BufferedReader(reader).lines().collect(Collectors.joining("\n")); } - catch (IOException e) { - throw new RuntimeException("Error loading resource from location " + filePath, e); + catch (IOException ex) { + throw new RuntimeException("Error loading resource from location " + filePath, ex); } } protected Metadata optionalStubMapping() { - return Metadata.metadata() - .attr("optional", true) - .build(); + return Metadata.metadata().attr("optional", true).build(); } protected final class StringReplacementPair { @@ -97,11 +91,11 @@ public class WiremockStubFixture { } public String getRegex() { - return regex; + return this.regex; } public String getReplacement() { - return replacement; + return this.replacement; } } diff --git a/spring-cloud-app-broker-logging/build.gradle b/spring-cloud-app-broker-logging/build.gradle index 65f4351..1b8d807 100644 --- a/spring-cloud-app-broker-logging/build.gradle +++ b/spring-cloud-app-broker-logging/build.gradle @@ -1,5 +1,5 @@ /* - * Copyright 2002-2024 the original author or authors. + * Copyright 2016-2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/ApplicationIdsProvider.java b/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/ApplicationIdsProvider.java index 500260a..3f32246 100644 --- a/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/ApplicationIdsProvider.java +++ b/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/ApplicationIdsProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2024 the original author or authors. + * Copyright 2016-2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/LoggingUtils.java b/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/LoggingUtils.java index 379f80e..f612ccf 100644 --- a/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/LoggingUtils.java +++ b/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/LoggingUtils.java @@ -1,11 +1,11 @@ /* - * Copyright 2016-2024 the original author or authors + * Copyright 2016-2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * https://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -16,7 +16,6 @@ package org.springframework.cloud.appbroker.logging; - import java.util.Base64; import okio.ByteString; @@ -29,8 +28,7 @@ public final class LoggingUtils { } public static Envelope convertLogCacheEnvelopeToDropsonde(org.cloudfoundry.logcache.v1.Envelope envelope) { - final Envelope.Builder builder = new Envelope.Builder() - .eventType(Envelope.EventType.LogMessage) + final Envelope.Builder builder = new Envelope.Builder().eventType(Envelope.EventType.LogMessage) .tags(envelope.getTags()) .origin(getFromTags(envelope, "rep")) .timestamp(envelope.getTimestamp()) diff --git a/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/package-info.java b/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/package-info.java new file mode 100644 index 0000000..d8168f5 --- /dev/null +++ b/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/package-info.java @@ -0,0 +1,20 @@ +/* + * Copyright 2002-2024 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Logging. + */ +package org.springframework.cloud.appbroker.logging; diff --git a/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/recent/ApplicationRecentLogsProvider.java b/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/recent/ApplicationRecentLogsProvider.java index 954f536..d9041bf 100644 --- a/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/recent/ApplicationRecentLogsProvider.java +++ b/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/recent/ApplicationRecentLogsProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2024 the original author or authors. + * Copyright 2016-2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,20 +32,18 @@ public class ApplicationRecentLogsProvider implements RecentLogsProvider { private final ApplicationIdsProvider applicationIdsProvider; - public ApplicationRecentLogsProvider(LogCacheClient logCacheClient, - ApplicationIdsProvider applicationIdsProvider) { + public ApplicationRecentLogsProvider(LogCacheClient logCacheClient, ApplicationIdsProvider applicationIdsProvider) { this.logCacheClient = logCacheClient; this.applicationIdsProvider = applicationIdsProvider; } @Override public Flux getLogs(String serviceInstanceId) { - return this.applicationIdsProvider.getApplicationIds(serviceInstanceId) - .flatMap(this::recentLogs); + return this.applicationIdsProvider.getApplicationIds(serviceInstanceId).flatMap(this::recentLogs); } protected Flux recentLogs(String applicationId) { - return logCacheClient + return this.logCacheClient .read(ReadRequest.builder() .sourceId(applicationId) .descending(true) @@ -53,7 +51,7 @@ public class ApplicationRecentLogsProvider implements RecentLogsProvider { .limit(1000) .startTime(Instant.MIN.getEpochSecond()) .build()) - .flatMapMany(readResponse -> Flux.fromIterable(readResponse.getEnvelopes().getBatch())); + .flatMapMany((readResponse) -> Flux.fromIterable(readResponse.getEnvelopes().getBatch())); } } diff --git a/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/recent/RecentLogsProvider.java b/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/recent/RecentLogsProvider.java index cf908c7..d1d4f02 100644 --- a/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/recent/RecentLogsProvider.java +++ b/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/recent/RecentLogsProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2024 the original author or authors. + * Copyright 2016-2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/recent/endpoint/EncodingException.java b/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/recent/endpoint/EncodingException.java index 7d0adb1..fa96991 100644 --- a/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/recent/endpoint/EncodingException.java +++ b/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/recent/endpoint/EncodingException.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2024 the original author or authors. + * Copyright 2016-2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,7 +20,7 @@ class EncodingException extends RuntimeException { private static final long serialVersionUID = 1837485200518028161L; - public EncodingException(Throwable throwable) { + EncodingException(Throwable throwable) { super("Failed to encode: " + throwable.getMessage(), throwable); } diff --git a/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/recent/endpoint/LogMessageComparator.java b/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/recent/endpoint/LogMessageComparator.java index 08c07a7..a422866 100644 --- a/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/recent/endpoint/LogMessageComparator.java +++ b/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/recent/endpoint/LogMessageComparator.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2024 the original author or authors. + * Copyright 2016-2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/recent/endpoint/MultipartEncoder.java b/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/recent/endpoint/MultipartEncoder.java index a9ce3b4..c0d72ac 100644 --- a/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/recent/endpoint/MultipartEncoder.java +++ b/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/recent/endpoint/MultipartEncoder.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2024 the original author or authors. + * Copyright 2016-2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,51 +22,51 @@ import java.io.IOException; class MultipartEncoder implements Closeable { - private final byte[] bytesCRLF = {'\r', '\n'}; + private final byte[] bytesCRLF = { '\r', '\n' }; - private final byte[] bytesSEP = {'-', '-'}; + private final byte[] bytesSEP = { '-', '-' }; private final byte[] boundary; private final ByteArrayOutputStream out = new ByteArrayOutputStream(); - public MultipartEncoder(String boundary) { + MultipartEncoder(String boundary) { this.boundary = boundary.getBytes(); } - public void append(byte[] part) { + void append(byte[] part) { try { - out.write(bytesCRLF); - out.write(bytesSEP); - out.write(boundary); - out.write(bytesCRLF); - out.write(bytesCRLF); - out.write(part); + this.out.write(this.bytesCRLF); + this.out.write(this.bytesSEP); + this.out.write(this.boundary); + this.out.write(this.bytesCRLF); + this.out.write(this.bytesCRLF); + this.out.write(part); } - catch (IOException e) { - throw new EncodingException(e); + catch (IOException ex) { + throw new EncodingException(ex); } } - public byte[] terminateAndGetBytes() { + byte[] terminateAndGetBytes() { try { - out.write(bytesCRLF); - out.write(bytesSEP); - out.write(boundary); - out.write(bytesSEP); - out.write(bytesCRLF); - final byte[] bytes = out.toByteArray(); - out.close(); + this.out.write(this.bytesCRLF); + this.out.write(this.bytesSEP); + this.out.write(this.boundary); + this.out.write(this.bytesSEP); + this.out.write(this.bytesCRLF); + final byte[] bytes = this.out.toByteArray(); + this.out.close(); return bytes; } - catch (IOException e) { - throw new EncodingException(e); + catch (IOException ex) { + throw new EncodingException(ex); } } @Override public void close() throws IOException { - out.close(); + this.out.close(); } } diff --git a/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/recent/endpoint/RecentLogsController.java b/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/recent/endpoint/RecentLogsController.java index d219c79..d58c94b 100644 --- a/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/recent/endpoint/RecentLogsController.java +++ b/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/recent/endpoint/RecentLogsController.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2024 the original author or authors. + * Copyright 2016-2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,10 +47,10 @@ public class RecentLogsController { final String multipartBoundary = UUID.randomUUID().toString(); final HttpHeaders headers = new HttpHeaders(); headers.add(HttpHeaders.CONTENT_TYPE, "multipart/mixed; boundary=" + multipartBoundary); - return recentLogsProviders.getLogs(serviceInstanceId) + return this.recentLogsProviders.getLogs(serviceInstanceId) .collectList() - .doOnNext(envelopes -> envelopes.sort(LOG_MESSAGE_COMPARATOR)) - .map(envelopes -> { + .doOnNext((envelopes) -> envelopes.sort(LOG_MESSAGE_COMPARATOR)) + .map((envelopes) -> { final MultipartEncoder multipart = new MultipartEncoder(multipartBoundary); for (Envelope message : envelopes) { var dropsondeEvent = LoggingUtils.convertLogCacheEnvelopeToDropsonde(message); diff --git a/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/recent/endpoint/package-info.java b/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/recent/endpoint/package-info.java new file mode 100644 index 0000000..3afaa5a --- /dev/null +++ b/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/recent/endpoint/package-info.java @@ -0,0 +1,20 @@ +/* + * Copyright 2002-2024 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Recent log endpoints. + */ +package org.springframework.cloud.appbroker.logging.recent.endpoint; diff --git a/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/recent/package-info.java b/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/recent/package-info.java new file mode 100644 index 0000000..a2f74ab --- /dev/null +++ b/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/recent/package-info.java @@ -0,0 +1,20 @@ +/* + * Copyright 2002-2024 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Recent logs functionality. + */ +package org.springframework.cloud.appbroker.logging.recent; diff --git a/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/streaming/ApplicationLogStreamPublisher.java b/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/streaming/ApplicationLogStreamPublisher.java index 85406af..53063ed 100644 --- a/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/streaming/ApplicationLogStreamPublisher.java +++ b/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/streaming/ApplicationLogStreamPublisher.java @@ -40,8 +40,8 @@ public class ApplicationLogStreamPublisher implements ApplicationListener logStreamPublisher, - ApplicationEventPublisher publisher) { + LogStreamPublisher logStreamPublisher, + ApplicationEventPublisher publisher) { this.logStreamPublisher = logStreamPublisher; this.publisher = publisher; } @@ -65,7 +65,7 @@ public class ApplicationLogStreamPublisher implements ApplicationListener { + this.registry.compute(serviceInstanceId, (key, existingRegistration) -> { if (existingRegistration != null) { LOG.debug("Incrementing registration subscription count for {}", serviceInstanceId); existingRegistration.increment(); @@ -76,9 +76,8 @@ public class ApplicationLogStreamPublisher implements ApplicationListener publisher - .publishEvent(new ServiceInstanceLogEvent(this, serviceInstanceId, envelope))) + .doOnNext((envelope) -> this.publisher + .publishEvent(new ServiceInstanceLogEvent(this, serviceInstanceId, envelope))) .subscribe(); LOG.debug("Creating new registration for {}", serviceInstanceId); @@ -91,11 +90,11 @@ public class ApplicationLogStreamPublisher implements ApplicationListener { + this.registry.compute(serviceInstanceId, (key, registration) -> { if (registration == null) { if (LOG.isWarnEnabled()) { LOG.warn("Received deregister event for service instance {} but there no event handler registered", - serviceInstanceId); + serviceInstanceId); } return null; } @@ -112,7 +111,7 @@ public class ApplicationLogStreamPublisher implements ApplicationListenerloc-cache-cli + * Class to Stream LocCache Envelopes using the same pattern as the loc-cache-cli. + * + * @author Alberto C. Rios */ public class LogCacheStreamPublisher implements LogStreamPublisher { @@ -51,10 +53,8 @@ public class LogCacheStreamPublisher implements LogStreamPublisher { private final ApplicationIdsProvider applicationIdsProvider; - public LogCacheStreamPublisher( - CloudFoundryClient client, - LogCacheClient logCacheClient, - ApplicationIdsProvider applicationIdsProvider) { + public LogCacheStreamPublisher(CloudFoundryClient client, LogCacheClient logCacheClient, + ApplicationIdsProvider applicationIdsProvider) { this.client = client; this.logCacheClient = logCacheClient; this.applicationIdsProvider = applicationIdsProvider; @@ -62,45 +62,42 @@ public class LogCacheStreamPublisher implements LogStreamPublisher { @Override public Flux getLogStream(String serviceInstanceId) { - return this.applicationIdsProvider - .getApplicationIds(serviceInstanceId) - .doOnNext(id -> LOG.debug("Starting log streaming for app with ID {}", id)) + return this.applicationIdsProvider.getApplicationIds(serviceInstanceId) + .doOnNext((id) -> LOG.debug("Starting log streaming for app with ID {}", id)) .flatMap(this::createApplicationStreamer); } protected Flux createApplicationStreamer(String applicationId) { - return getApplicationName(applicationId) - .flatMapMany(appName -> { - long initialStartTime = Instant.now().minus(5, ChronoUnit.SECONDS).toEpochMilli() * 1_000_000L; - return readLogCache(applicationId, initialStartTime) - .flatMapMany(initialResponse -> { - AtomicLong lastTimestamp = getLastTimestamp(initialResponse, initialStartTime); - Flux initialLogs = convertEnvelopesToDropsonde(initialResponse); - Flux polledLogs = Flux.interval(Duration.ofSeconds(1)) - .flatMap(tick -> readLogCache(applicationId, lastTimestamp.get() + 1) - .flatMapMany(readResponse -> { - updateLastTimestampFromResponse(readResponse, lastTimestamp); - return convertEnvelopesToDropsonde(readResponse); - })) - .onErrorResume(error -> { - LOG.error("Error during log polling", error); - return Flux.empty(); - }); - - return Flux.merge(initialLogs, polledLogs) - .retryWhen(Retry.backoff(3, Duration.ofSeconds(5))) - .doOnError(error -> LOG.error("Streaming error", error)); + return getApplicationName(applicationId).flatMapMany((appName) -> { + long initialStartTime = Instant.now().minus(5, ChronoUnit.SECONDS).toEpochMilli() * 1_000_000L; + return readLogCache(applicationId, initialStartTime).flatMapMany((initialResponse) -> { + AtomicLong lastTimestamp = getLastTimestamp(initialResponse, initialStartTime); + Flux initialLogs = convertEnvelopesToDropsonde(initialResponse); + Flux polledLogs = Flux.interval(Duration.ofSeconds(1)) + .flatMap((tick) -> readLogCache(applicationId, lastTimestamp.get() + 1) + .flatMapMany((readResponse) -> { + updateLastTimestampFromResponse(readResponse, lastTimestamp); + return convertEnvelopesToDropsonde(readResponse); + })) + .onErrorResume((error) -> { + LOG.error("Error during log polling", error); + return Flux.empty(); }); + + return Flux.merge(initialLogs, polledLogs) + .retryWhen(Retry.backoff(3, Duration.ofSeconds(5))) + .doOnError((error) -> LOG.error("Streaming error", error)); }); + }); } private static AtomicLong getLastTimestamp(ReadResponse initialResponse, long initialStartTime) { - return new AtomicLong( - initialResponse.getEnvelopes().getBatch().stream() - .mapToLong(org.cloudfoundry.logcache.v1.Envelope::getTimestamp) - .max() - .orElse(initialStartTime) - ); + return new AtomicLong(initialResponse.getEnvelopes() + .getBatch() + .stream() + .mapToLong(org.cloudfoundry.logcache.v1.Envelope::getTimestamp) + .max() + .orElse(initialStartTime)); } private static Flux convertEnvelopesToDropsonde(ReadResponse readResponse) { @@ -109,24 +106,23 @@ public class LogCacheStreamPublisher implements LogStreamPublisher { } private Mono getApplicationName(String applicationId) { - return client.applicationsV2() - .get(GetApplicationRequest.builder() - .applicationId(applicationId) - .build()) - .map(response -> response.getEntity().getName()); + return this.client.applicationsV2() + .get(GetApplicationRequest.builder().applicationId(applicationId).build()) + .map((response) -> response.getEntity().getName()); } private Mono readLogCache(String applicationId, long lastTimestamp) { - return logCacheClient.read( - ReadRequest.builder() - .sourceId(applicationId) - .envelopeTypes(EnvelopeType.LOG) - .startTime(lastTimestamp) - .build()); + return this.logCacheClient.read(ReadRequest.builder() + .sourceId(applicationId) + .envelopeTypes(EnvelopeType.LOG) + .startTime(lastTimestamp) + .build()); } private static void updateLastTimestampFromResponse(ReadResponse readResponse, AtomicLong lastTimestamp) { - long maxTimestamp = readResponse.getEnvelopes().getBatch().stream() + long maxTimestamp = readResponse.getEnvelopes() + .getBatch() + .stream() .mapToLong(org.cloudfoundry.logcache.v1.Envelope::getTimestamp) .max() .orElse(lastTimestamp.get()); diff --git a/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/streaming/endpoint/StreamingLogWebSocketHandler.java b/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/streaming/endpoint/StreamingLogWebSocketHandler.java index 44d7248..e288ed2 100644 --- a/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/streaming/endpoint/StreamingLogWebSocketHandler.java +++ b/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/streaming/endpoint/StreamingLogWebSocketHandler.java @@ -53,22 +53,23 @@ public class StreamingLogWebSocketHandler implements WebSocketHandler, Applicati @Override public Mono handle(WebSocketSession session) { String serviceInstanceId = getServiceInstanceId(session); - LOG.info("Connection established [{}], service instance {}", - session.getHandshakeInfo().getRemoteAddress(), - serviceInstanceId); + LOG.info("Connection established [{}], service instance {}", session.getHandshakeInfo().getRemoteAddress(), + serviceInstanceId); - Sinks.Many envelopeSink = envelopeSinks - .computeIfAbsent(serviceInstanceId, s -> Sinks.many().multicast().onBackpressureBuffer()); + Sinks.Many envelopeSink = this.envelopeSinks.computeIfAbsent(serviceInstanceId, + (s) -> Sinks.many().multicast().onBackpressureBuffer()); - eventPublisher.publishEvent(new StartServiceInstanceLoggingEvent(this, serviceInstanceId)); + this.eventPublisher.publishEvent(new StartServiceInstanceLoggingEvent(this, serviceInstanceId)); LOG.info("Published event to start streaming logs for service instance with ID {}", serviceInstanceId); - return session.send(envelopeSink.asFlux() - .map(envelope -> session.binaryMessage( - dataBufferFactory -> dataBufferFactory.wrap(Envelope.ADAPTER.encode(envelope))))) - .doFinally(signalType -> afterConnectionClosed(session, serviceInstanceId)) - .doOnError(throwable -> LOG.error(String.format("Error handling logging stream for service instance %s", - serviceInstanceId), throwable)); + return session + .send(envelopeSink.asFlux() + .map((envelope) -> session + .binaryMessage((dataBufferFactory) -> dataBufferFactory.wrap(Envelope.ADAPTER.encode(envelope))))) + .doFinally((signalType) -> afterConnectionClosed(session, serviceInstanceId)) + .doOnError((throwable) -> LOG.error( + String.format("Error handling logging stream for service instance %s", serviceInstanceId), + throwable)); } @Override @@ -87,7 +88,7 @@ public class StreamingLogWebSocketHandler implements WebSocketHandler, Applicati LOG.warn("No sink found for {}, stopping log streaming", event.getServiceInstanceId()); } - eventPublisher.publishEvent(new StopServiceInstanceLoggingEvent(this, event.getServiceInstanceId())); + this.eventPublisher.publishEvent(new StopServiceInstanceLoggingEvent(this, event.getServiceInstanceId())); return; } @@ -100,11 +101,11 @@ public class StreamingLogWebSocketHandler implements WebSocketHandler, Applicati private void afterConnectionClosed(WebSocketSession webSocketSession, String serviceInstanceId) { LOG.info("Connection closed [{}], service instance {}", webSocketSession.getHandshakeInfo().getRemoteAddress(), - serviceInstanceId); + serviceInstanceId); - eventPublisher.publishEvent(new StopServiceInstanceLoggingEvent(this, serviceInstanceId)); + this.eventPublisher.publishEvent(new StopServiceInstanceLoggingEvent(this, serviceInstanceId)); - Sinks.Many sink = envelopeSinks.remove(serviceInstanceId); + Sinks.Many sink = this.envelopeSinks.remove(serviceInstanceId); if (sink != null) { sink.emitComplete(Sinks.EmitFailureHandler.FAIL_FAST); } diff --git a/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/streaming/endpoint/package-info.java b/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/streaming/endpoint/package-info.java new file mode 100644 index 0000000..584c658 --- /dev/null +++ b/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/streaming/endpoint/package-info.java @@ -0,0 +1,20 @@ +/* + * Copyright 2002-2024 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Streaming log endpoints. + */ +package org.springframework.cloud.appbroker.logging.streaming.endpoint; diff --git a/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/streaming/events/ServiceInstanceLogEvent.java b/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/streaming/events/ServiceInstanceLogEvent.java index 6d45079..9cf62ea 100644 --- a/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/streaming/events/ServiceInstanceLogEvent.java +++ b/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/streaming/events/ServiceInstanceLogEvent.java @@ -28,19 +28,18 @@ public class ServiceInstanceLogEvent extends ApplicationEvent { private final Envelope envelope; - public ServiceInstanceLogEvent(Object source, String serviceInstanceId, - Envelope envelope) { + public ServiceInstanceLogEvent(Object source, String serviceInstanceId, Envelope envelope) { super(source); this.serviceInstanceId = serviceInstanceId; this.envelope = envelope; } public String getServiceInstanceId() { - return serviceInstanceId; + return this.serviceInstanceId; } public Envelope getEnvelope() { - return envelope; + return this.envelope; } } diff --git a/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/streaming/events/ServiceInstanceLoggingEvent.java b/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/streaming/events/ServiceInstanceLoggingEvent.java index 4a45f3b..f8f417d 100644 --- a/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/streaming/events/ServiceInstanceLoggingEvent.java +++ b/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/streaming/events/ServiceInstanceLoggingEvent.java @@ -25,14 +25,15 @@ public class ServiceInstanceLoggingEvent extends ApplicationEvent { public enum Operation { /** - * Start publishing log stream for a given service instance id + * Start publishing log stream for a given service instance id. */ START, /** - * Stop publishing log stream for a given service instance id + * Stop publishing log stream for a given service instance id. */ STOP + } private final String serviceInstanceId; @@ -46,11 +47,11 @@ public class ServiceInstanceLoggingEvent extends ApplicationEvent { } public String getServiceInstanceId() { - return serviceInstanceId; + return this.serviceInstanceId; } public Operation getOperation() { - return operation; + return this.operation; } } diff --git a/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/streaming/events/package-info.java b/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/streaming/events/package-info.java new file mode 100644 index 0000000..56e3446 --- /dev/null +++ b/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/streaming/events/package-info.java @@ -0,0 +1,20 @@ +/* + * Copyright 2002-2024 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Streaming log events. + */ +package org.springframework.cloud.appbroker.logging.streaming.events; diff --git a/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/streaming/package-info.java b/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/streaming/package-info.java new file mode 100644 index 0000000..f2d42ab --- /dev/null +++ b/spring-cloud-app-broker-logging/src/main/java/org/springframework/cloud/appbroker/logging/streaming/package-info.java @@ -0,0 +1,20 @@ +/* + * Copyright 2002-2024 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Streaming logs. + */ +package org.springframework.cloud.appbroker.logging.streaming; diff --git a/spring-cloud-app-broker-logging/src/test/java/com/example/recentlog/RecentLogsTestApp.java b/spring-cloud-app-broker-logging/src/test/java/com/example/recentlog/RecentLogsTestApp.java index 95a3011..5f849f6 100644 --- a/spring-cloud-app-broker-logging/src/test/java/com/example/recentlog/RecentLogsTestApp.java +++ b/spring-cloud-app-broker-logging/src/test/java/com/example/recentlog/RecentLogsTestApp.java @@ -26,10 +26,7 @@ import org.springframework.cloud.servicebroker.autoconfigure.web.ServiceBrokerAu import org.springframework.cloud.servicebroker.autoconfigure.web.reactive.ServiceBrokerWebFluxAutoConfiguration; import org.springframework.context.annotation.Bean; -@SpringBootApplication(exclude = { - ServiceBrokerAutoConfiguration.class, - ServiceBrokerWebFluxAutoConfiguration.class -}) +@SpringBootApplication(exclude = { ServiceBrokerAutoConfiguration.class, ServiceBrokerWebFluxAutoConfiguration.class }) public class RecentLogsTestApp { static final String APP_ID = UUID.randomUUID().toString(); @@ -40,7 +37,7 @@ public class RecentLogsTestApp { @Bean ApplicationIdsProvider applicationIdsProvider() { - return serviceInstanceId -> Flux.just(APP_ID); + return (serviceInstanceId) -> Flux.just(APP_ID); } } diff --git a/spring-cloud-app-broker-logging/src/test/java/com/example/streaming/LogStreamingTestApp.java b/spring-cloud-app-broker-logging/src/test/java/com/example/streaming/LogStreamingTestApp.java index 9045caf..cafe0ea 100644 --- a/spring-cloud-app-broker-logging/src/test/java/com/example/streaming/LogStreamingTestApp.java +++ b/spring-cloud-app-broker-logging/src/test/java/com/example/streaming/LogStreamingTestApp.java @@ -28,15 +28,13 @@ import org.springframework.cloud.servicebroker.autoconfigure.web.reactive.Servic import org.springframework.context.annotation.Bean; import org.springframework.context.event.EventListener; -@SpringBootApplication(exclude = { - ServiceBrokerAutoConfiguration.class, - ServiceBrokerWebFluxAutoConfiguration.class -}) +@SpringBootApplication(exclude = { ServiceBrokerAutoConfiguration.class, ServiceBrokerWebFluxAutoConfiguration.class }) public class LogStreamingTestApp { private static final String APP_ID = UUID.randomUUID().toString(); private static boolean receivedStopEvent; + private static String receivedStopEventServiceInstanceId; public static String getAppId() { @@ -53,7 +51,7 @@ public class LogStreamingTestApp { @Bean ApplicationIdsProvider applicationIdsProvider() { - return serviceInstanceId -> Flux.just(APP_ID); + return (serviceInstanceId) -> Flux.just(APP_ID); } @EventListener diff --git a/spring-cloud-app-broker-logging/src/test/java/org/springframework/cloud/appbroker/logging/recent/ServiceInstanceRecentLogsTest.java b/spring-cloud-app-broker-logging/src/test/java/org/springframework/cloud/appbroker/logging/recent/ServiceInstanceRecentLogsTests.java similarity index 72% rename from spring-cloud-app-broker-logging/src/test/java/org/springframework/cloud/appbroker/logging/recent/ServiceInstanceRecentLogsTest.java rename to spring-cloud-app-broker-logging/src/test/java/org/springframework/cloud/appbroker/logging/recent/ServiceInstanceRecentLogsTests.java index fd4dbc3..4ab339f 100644 --- a/spring-cloud-app-broker-logging/src/test/java/org/springframework/cloud/appbroker/logging/recent/ServiceInstanceRecentLogsTest.java +++ b/spring-cloud-app-broker-logging/src/test/java/org/springframework/cloud/appbroker/logging/recent/ServiceInstanceRecentLogsTests.java @@ -47,7 +47,7 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = RecentLogsTestApp.class) -class ServiceInstanceRecentLogsTest { +class ServiceInstanceRecentLogsTests { @LocalServerPort private int port; @@ -64,40 +64,40 @@ class ServiceInstanceRecentLogsTest { @BeforeEach void setUp() { - expectedTestMessage = "test message " + UUID.randomUUID(); + this.expectedTestMessage = "test message " + UUID.randomUUID(); - Envelope testEnvelope = - Envelope.builder() - .timestamp(Instant.now().toEpochMilli()) - .log(Log.builder() - .payload(new String(Base64.getEncoder().encode(expectedTestMessage.getBytes()))) - .type(LogType.OUT) - .build()) - .build(); + Envelope testEnvelope = Envelope.builder() + .timestamp(Instant.now().toEpochMilli()) + .log(Log.builder() + .payload(new String(Base64.getEncoder().encode(this.expectedTestMessage.getBytes()))) + .type(LogType.OUT) + .build()) + .build(); - ReadResponse response = - ReadResponse.builder() - .envelopes(EnvelopeBatch.builder().batch(testEnvelope).build()) - .build(); + ReadResponse response = ReadResponse.builder() + .envelopes(EnvelopeBatch.builder().batch(testEnvelope).build()) + .build(); - given(logCacheClient.read(any(ReadRequest.class))) - .willReturn(Mono.just(response)); + given(this.logCacheClient.read(any(ReadRequest.class))).willReturn(Mono.just(response)); - given(cloudFoundryClient.applicationsV2() + given(this.cloudFoundryClient.applicationsV2() .get(GetApplicationRequest.builder().applicationId(RecentLogsTestApp.getAppId()).build())) - .willReturn(Mono.just( - GetApplicationResponse.builder().entity(ApplicationEntity.builder().name("test-app").build()).build())); + .willReturn(Mono.just(GetApplicationResponse.builder() + .entity(ApplicationEntity.builder().name("test-app").build()) + .build())); } @Test void shouldFetchLogs() { - WebTestClient client = WebTestClient.bindToServer().baseUrl("http://localhost:" + port).build(); + WebTestClient client = WebTestClient.bindToServer().baseUrl("http://localhost:" + this.port).build(); - client.get().uri("/logs/{serviceInstanceId}/recentlogs", SERVICE_INSTANCE_ID) + client.get() + .uri("/logs/{serviceInstanceId}/recentlogs", SERVICE_INSTANCE_ID) .exchange() - .expectStatus().isOk() + .expectStatus() + .isOk() .expectBody(String.class) - .value(Matchers.containsString(expectedTestMessage)); + .value(Matchers.containsString(this.expectedTestMessage)); } } diff --git a/spring-cloud-app-broker-logging/src/test/java/org/springframework/cloud/appbroker/logging/streaming/ServiceInstanceLogStreamingTest.java b/spring-cloud-app-broker-logging/src/test/java/org/springframework/cloud/appbroker/logging/streaming/ServiceInstanceLogStreamingTests.java similarity index 71% rename from spring-cloud-app-broker-logging/src/test/java/org/springframework/cloud/appbroker/logging/streaming/ServiceInstanceLogStreamingTest.java rename to spring-cloud-app-broker-logging/src/test/java/org/springframework/cloud/appbroker/logging/streaming/ServiceInstanceLogStreamingTests.java index ff08de4..c2f10e9 100644 --- a/spring-cloud-app-broker-logging/src/test/java/org/springframework/cloud/appbroker/logging/streaming/ServiceInstanceLogStreamingTest.java +++ b/spring-cloud-app-broker-logging/src/test/java/org/springframework/cloud/appbroker/logging/streaming/ServiceInstanceLogStreamingTests.java @@ -60,7 +60,7 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = LogStreamingTestApp.class) -class ServiceInstanceLogStreamingTest { +class ServiceInstanceLogStreamingTests { private static final String SERVICE_INSTANCE_ID = UUID.randomUUID().toString(); @@ -84,15 +84,14 @@ class ServiceInstanceLogStreamingTest { void setUp() { String expectedTestMessage = "test message " + UUID.randomUUID(); - Envelope testEnvelope = - Envelope.builder() - .timestamp(Instant.now().toEpochMilli()) - .log(Log.builder() - .payload(new String(Base64.getEncoder().encode(expectedTestMessage.getBytes()))) - .type(LogType.OUT) - .build()) - .build(); - expectedEnvelope = new org.cloudfoundry.dropsonde.events.Envelope.Builder() + Envelope testEnvelope = Envelope.builder() + .timestamp(Instant.now().toEpochMilli()) + .log(Log.builder() + .payload(new String(Base64.getEncoder().encode(expectedTestMessage.getBytes()))) + .type(LogType.OUT) + .build()) + .build(); + this.expectedEnvelope = new org.cloudfoundry.dropsonde.events.Envelope.Builder() .logMessage(new LogMessage.Builder() .message(ByteString.of(Base64.getEncoder().encode(expectedTestMessage.getBytes()))) .message_type(LogMessage.MessageType.OUT) @@ -101,28 +100,28 @@ class ServiceInstanceLogStreamingTest { .origin("") .eventType(org.cloudfoundry.dropsonde.events.Envelope.EventType.LogMessage) .build(); - actualEnvelope.set(testEnvelope); + this.actualEnvelope.set(testEnvelope); - ReadResponse response = - ReadResponse.builder() - .envelopes(EnvelopeBatch.builder().batch(testEnvelope).build()) - .build(); + ReadResponse response = ReadResponse.builder() + .envelopes(EnvelopeBatch.builder().batch(testEnvelope).build()) + .build(); - given(logCacheClient.read(any(ReadRequest.class))) - .willReturn(Mono.just(response)); + given(this.logCacheClient.read(any(ReadRequest.class))).willReturn(Mono.just(response)); - given(cloudFoundryClient.applicationsV2() + given(this.cloudFoundryClient.applicationsV2() .get(GetApplicationRequest.builder().applicationId(RecentLogsTestApp.getAppId()).build())) - .willReturn(Mono.just( - GetApplicationResponse.builder().entity(ApplicationEntity.builder().name("test-app").build()).build())); + .willReturn(Mono.just(GetApplicationResponse.builder() + .entity(ApplicationEntity.builder().name("test-app").build()) + .build())); } @Test void shouldPublishWebSocketEndpoint() { Disposable subscription = connectToLogsStreamEndpoint(); - await().untilAsserted(() -> assertThat(Base64.getDecoder().decode(actualEnvelope.get().getLog().getPayload())) - .isEqualTo(Base64.getDecoder().decode(expectedEnvelope.logMessage.message.toByteArray()))); + await() + .untilAsserted(() -> assertThat(Base64.getDecoder().decode(this.actualEnvelope.get().getLog().getPayload())) + .isEqualTo(Base64.getDecoder().decode(this.expectedEnvelope.logMessage.message.toByteArray()))); subscription.dispose(); } @@ -131,7 +130,7 @@ class ServiceInstanceLogStreamingTest { void shouldPublishEventOnDisconnect() { Disposable subscription = connectToLogsStreamEndpoint(); - await().untilAsserted(() -> assertThat(actualEnvelope.get()).isNotNull()); + await().untilAsserted(() -> assertThat(this.actualEnvelope.get()).isNotNull()); subscription.dispose(); @@ -140,36 +139,34 @@ class ServiceInstanceLogStreamingTest { @Test void shouldStopStreamingIfNoClient() { - // CLI plugin doesn't always handle disconnect gracefully, so sometimes it is possible that log stream is - // being published but there is no listener. In this case log streaming should be stopped. + // CLI plugin doesn't always handle disconnect gracefully, so sometimes it is + // possible that log stream is + // being published but there is no listener. In this case log streaming should be + // stopped. Disposable subscription = connectToLogsStreamEndpoint(); subscription.dispose(); - applicationEventPublisher.publishEvent( - new ServiceInstanceLogEvent(this, SERVICE_INSTANCE_ID, expectedEnvelope)); - await().untilAsserted( - () -> assertThat(LogStreamingTestApp.getReceivedStopEventServiceInstanceId()).isEqualTo( - SERVICE_INSTANCE_ID)); + this.applicationEventPublisher + .publishEvent(new ServiceInstanceLogEvent(this, SERVICE_INSTANCE_ID, this.expectedEnvelope)); + await().untilAsserted(() -> assertThat(LogStreamingTestApp.getReceivedStopEventServiceInstanceId()) + .isEqualTo(SERVICE_INSTANCE_ID)); } private Disposable connectToLogsStreamEndpoint() { - URI uri = URI.create("ws://localhost:" + port + "/logs/" + SERVICE_INSTANCE_ID + "/stream"); + URI uri = URI.create("ws://localhost:" + this.port + "/logs/" + SERVICE_INSTANCE_ID + "/stream"); WebSocketClient client = new ReactorNettyWebSocketClient(); return client.execute(uri, getWebSocketHandler()).subscribe(); } private WebSocketHandler getWebSocketHandler() { - return session -> session - .receive() - .doOnNext(message -> { - DataBuffer buffer = message.getPayload(); - actualEnvelope.set(Envelope.builder() - .log(Log.builder().payload(new String(Base64.getDecoder().decode(buffer.toString()))).build()) - .build()); - }) - .then(); + return (session) -> session.receive().doOnNext((message) -> { + DataBuffer buffer = message.getPayload(); + this.actualEnvelope.set(Envelope.builder() + .log(Log.builder().payload(new String(Base64.getDecoder().decode(buffer.toString()))).build()) + .build()); + }).then(); } } diff --git a/spring-cloud-starter-app-broker-cloudfoundry/build.gradle b/spring-cloud-starter-app-broker-cloudfoundry/build.gradle index 07b14d5..fbedc12 100644 --- a/spring-cloud-starter-app-broker-cloudfoundry/build.gradle +++ b/spring-cloud-starter-app-broker-cloudfoundry/build.gradle @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-cloud-starter-app-broker-logging/build.gradle b/spring-cloud-starter-app-broker-logging/build.gradle index 128b346..9837f8e 100644 --- a/spring-cloud-starter-app-broker-logging/build.gradle +++ b/spring-cloud-starter-app-broker-logging/build.gradle @@ -1,5 +1,5 @@ /* - * Copyright 2002-2024 the original author or authors. + * Copyright 2016-2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-cloud-starter-app-broker/build.gradle b/spring-cloud-starter-app-broker/build.gradle index ae093f2..3e8c08e 100644 --- a/spring-cloud-starter-app-broker/build.gradle +++ b/spring-cloud-starter-app-broker/build.gradle @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/checkstyle/checkstyle-suppressions.xml b/src/checkstyle/checkstyle-suppressions.xml deleted file mode 100644 index e33c5a2..0000000 --- a/src/checkstyle/checkstyle-suppressions.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - - - - - - - - diff --git a/src/checkstyle/checkstyle-test.xml b/src/checkstyle/checkstyle-test.xml new file mode 100644 index 0000000..5647f91 --- /dev/null +++ b/src/checkstyle/checkstyle-test.xml @@ -0,0 +1,24 @@ + + + + + + + + + diff --git a/src/checkstyle/checkstyle.xml b/src/checkstyle/checkstyle.xml index a5d6d19..0afe48b 100644 --- a/src/checkstyle/checkstyle.xml +++ b/src/checkstyle/checkstyle.xml @@ -1,6 +1,6 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + diff --git a/src/checkstyle/license.header b/src/checkstyle/license.header index e468828..d6d329c 100644 --- a/src/checkstyle/license.header +++ b/src/checkstyle/license.header @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2016-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License.