From ae314100f5340ab6fd7f49995ec2c6f478b9bc70 Mon Sep 17 00:00:00 2001 From: Marcin Grzejszczak Date: Fri, 1 Feb 2019 12:50:02 +0100 Subject: [PATCH] Applied checkstyle and turned it on by default --- .circleci/config.yml | 2 +- .editorconfig | 14 + .settings.xml | 128 +- docs/pom.xml | 4 +- eclipse/eclipse-code-formatter.xml | 1063 ++++++++++++----- eclipse/org.eclipse.jdt.ui.prefs | 2 +- pom.xml | 40 +- spring-cloud-commons-dependencies/pom.xml | 5 +- .../eclipse/eclipse-code-formatter.xml | 1043 +++++++++++----- spring-cloud-commons/pom.xml | 5 +- .../CommonsClientAutoConfiguration.java | 7 +- .../cloud/client/DefaultServiceInstance.java | 79 +- .../HostInfoEnvironmentPostProcessor.java | 17 + .../cloud/client/ServiceInstance.java | 4 +- .../cloud/client/SpringCloudApplication.java | 26 +- .../client/actuator/FeaturesEndpoint.java | 74 +- .../cloud/client/actuator/HasFeatures.java | 33 +- .../cloud/client/actuator/NamedFeature.java | 11 +- .../EnableCircuitBreakerImportSelector.java | 9 +- .../client/discovery/DiscoveryClient.java | 9 +- .../discovery/EnableDiscoveryClient.java | 2 + .../EnableDiscoveryClientImportSelector.java | 24 +- .../discovery/ManagementServerPortUtils.java | 47 +- .../composite/CompositeDiscoveryClient.java | 11 +- ...ositeDiscoveryClientAutoConfiguration.java | 29 +- .../discovery/event/HeartbeatEvent.java | 14 +- .../discovery/event/HeartbeatMonitor.java | 4 +- .../event/InstancePreRegisteredEvent.java | 8 +- .../event/InstanceRegisteredEvent.java | 1 + .../DiscoveryClientHealthIndicator.java | 25 +- ...coveryClientHealthIndicatorProperties.java | 28 +- .../DiscoveryCompositeHealthIndicator.java | 18 +- .../health/DiscoveryHealthIndicator.java | 1 + .../discovery/noop/NoopDiscoveryClient.java | 5 +- .../NoopDiscoveryClientAutoConfiguration.java | 47 +- .../simple/SimpleDiscoveryClient.java | 3 +- ...impleDiscoveryClientAutoConfiguration.java | 45 +- .../simple/SimpleDiscoveryProperties.java | 43 +- .../CloudHypermediaAutoConfiguration.java | 39 +- .../client/hypermedia/DiscoveredResource.java | 77 +- .../DynamicServiceInstanceProvider.java | 26 +- .../client/hypermedia/RemoteResource.java | 15 +- .../hypermedia/RemoteResourceRefresher.java | 32 +- .../hypermedia/ServiceInstanceProvider.java | 17 +- .../StaticServiceInstanceProvider.java | 20 +- .../hypermedia/TraversalDefinition.java | 5 +- .../AsyncLoadBalancerAutoConfiguration.java | 9 +- .../AsyncLoadBalancerInterceptor.java | 19 +- .../AsyncRestTemplateCustomizer.java | 5 +- ...ClientHttpResponseStatusCodeException.java | 31 +- .../loadbalancer/InterceptorRetryPolicy.java | 145 ++- .../client/loadbalancer/LoadBalanced.java | 5 +- .../LoadBalancedRecoveryCallback.java | 22 +- .../LoadBalancedRetryContext.java | 84 +- .../LoadBalancedRetryFactory.java | 8 +- .../loadbalancer/LoadBalancedRetryPolicy.java | 77 +- .../LoadBalancerAutoConfiguration.java | 67 +- .../loadbalancer/LoadBalancerClient.java | 23 +- .../loadbalancer/LoadBalancerInterceptor.java | 11 +- .../loadbalancer/LoadBalancerRequest.java | 8 +- .../LoadBalancerRequestFactory.java | 34 +- .../LoadBalancerRequestTransformer.java | 16 +- .../LoadBalancerRetryProperties.java | 36 +- .../loadbalancer/RestTemplateCustomizer.java | 18 + .../RetryLoadBalancerInterceptor.java | 67 +- .../RetryableStatusCodeException.java | 16 +- .../loadbalancer/ServiceInstanceChooser.java | 17 +- .../loadbalancer/ServiceRequestWrapper.java | 24 +- .../reactive/CompletionContext.java | 34 +- .../reactive/DefaultResponse.java | 3 +- .../loadbalancer/reactive/EmptyResponse.java | 3 +- .../LoadBalancerExchangeFilterFunction.java | 43 +- .../reactive/ReactiveLoadBalancer.java | 15 +- ...ReactiveLoadBalancerAutoConfiguration.java | 31 +- .../client/loadbalancer/reactive/Request.java | 25 +- .../loadbalancer/reactive/Response.java | 27 +- .../reactive/WebClientCustomizer.java | 6 +- .../AbstractAutoServiceRegistration.java | 43 +- .../AutoServiceRegistration.java | 17 + ...oServiceRegistrationAutoConfiguration.java | 22 +- .../AutoServiceRegistrationConfiguration.java | 17 + .../AutoServiceRegistrationProperties.java | 37 +- .../client/serviceregistry/Registration.java | 17 + .../serviceregistry/ServiceRegistry.java | 36 +- .../ServiceRegistryAutoConfiguration.java | 27 +- .../endpoint/ServiceRegistryEndpoint.java | 12 +- ...cheHttpClientConnectionManagerFactory.java | 43 +- .../httpclient/ApacheHttpClientFactory.java | 31 +- ...cheHttpClientConnectionManagerFactory.java | 46 +- .../DefaultApacheHttpClientFactory.java | 24 +- ...aultOkHttpClientConnectionPoolFactory.java | 28 +- .../DefaultOkHttpClientFactory.java | 30 +- .../httpclient/HttpClientConfiguration.java | 24 +- .../OkHttpClientConnectionPoolFactory.java | 25 +- .../httpclient/OkHttpClientFactory.java | 39 +- .../cloud/commons/util/IdUtils.java | 40 +- .../cloud/commons/util/InetUtils.java | 60 +- .../commons/util/InetUtilsProperties.java | 29 +- .../util/SpringFactoryImportSelector.java | 9 +- .../commons/util/UtilAutoConfiguration.java | 17 + .../CompatibilityNotMetException.java | 22 +- .../CompatibilityNotMetFailureAnalyzer.java | 30 +- .../configuration/CompatibilityPredicate.java | 23 +- .../configuration/CompatibilityVerifier.java | 24 +- ...ompatibilityVerifierAutoConfiguration.java | 30 +- .../CompatibilityVerifierProperties.java | 25 +- .../CompositeCompatibilityVerifier.java | 25 +- .../SpringBootVersionVerifier.java | 41 +- .../configuration/VerificationResult.java | 22 +- ...itional-spring-configuration-metadata.json | 102 +- .../main/resources/META-INF/spring.factories | 3 - .../springframework/cloud/AdhocTestSuite.java | 1 + .../CommonsClientAutoConfigurationTests.java | 17 +- ...HostInfoEnvironmentPostProcessorTests.java | 8 +- .../actuator/FeaturesEndpointTests.java | 13 +- .../AutoRegisterPropertyFalseTests.java | 16 +- ...DiscoveryClientAutoRegisterFalseTests.java | 12 +- ...bleDiscoveryClientImportSelectorTests.java | 10 +- ...EnableDiscoveryClientMissingImplTests.java | 4 + .../ManagementServerPortUtilsTests.java | 9 +- ...DiscoveryClientAutoConfigurationTests.java | 15 +- .../CompositeDiscoveryClientOrderTest.java | 6 +- .../CompositeDiscoveryClientTests.java | 14 +- .../CompositeDiscoveryClientTestsConfig.java | 5 +- .../DiscoveryClientHealthIndicatorTests.java | 47 +- ...iscoveryCompositeHealthIndicatorTests.java | 45 +- ...ryClientAutoConfigurationDefaultTests.java | 7 +- ...DiscoveryClientPropertiesMappingTests.java | 3 + .../simple/SimpleDiscoveryClientTests.java | 2 + ...ediaAutoConfigurationIntegrationTests.java | 21 +- .../DiscoveredResourceUnitTests.java | 60 +- ...namicServiceInstanceProviderUnitTests.java | 14 +- ...actLoadBalancerAutoConfigurationTests.java | 31 +- ...yncLoadBalancerAutoConfigurationTests.java | 47 +- ...ntHttpResponseStatusCodeExceptionTest.java | 16 +- .../InterceptorRetryPolicyTest.java | 163 +-- .../LoadBalancedRetryContextTest.java | 70 +- .../LoadBalancerAutoConfigurationTests.java | 6 +- ...ancerRequestFactoryConfigurationTests.java | 69 +- .../LoadBalancerRequestFactoryTests.java | 77 +- ...tryLoadBalancerAutoConfigurationTests.java | 16 +- .../RetryLoadBalancerInterceptorTest.java | 672 ++++++----- ...adBalancerExchangeFilterFunctionTests.java | 47 +- ...iveLoadBalancerAutoConfigurationTests.java | 28 +- ...oServiceRegistrationMgmtDisabledTests.java | 54 +- .../AbstractAutoServiceRegistrationTests.java | 95 +- ...iceRegistrationAutoConfigurationTests.java | 37 +- ...ServiceRegistryAutoConfigurationTests.java | 10 +- ...ceRegistryEndpointNoRegistrationTests.java | 20 +- .../ServiceRegistryEndpointTests.java | 26 +- ...omHttpClientBuilderConfigurationTests.java | 11 +- .../CustomHttpClientConfigurationTests.java | 39 +- ...OkHttpClientBuilderConfigurationTests.java | 11 +- ...tpClientConnectionManagerFactoryTests.java | 2 + .../DefaultApacheHttpClientFactoryTests.java | 12 +- .../DefaultHttpClientConfigurationTests.java | 30 +- ...OkHttpClientConnectionPoolFactoryTest.java | 12 +- .../DefaultOkHttpClientFactoryTest.java | 26 +- .../cloud/commons/util/IdUtilsTests.java | 17 +- .../cloud/commons/util/InetUtilsTests.java | 5 +- .../SpringFactoryImportSelectorTests.java | 6 +- ...ibilityVerifierAutoConfigurationTests.java | 9 +- ...erifierDisabledAutoConfigurationTests.java | 9 +- ...VerifierFailureAutoConfigurationTests.java | 13 +- .../CompatibilityVerifierTests.java | 25 +- .../SpringBootDependencyTests.java | 44 +- .../resources/application-encrypt.properties | 3 +- .../src/test/resources/application.properties | 8 +- .../resources/bootstrap-encrypt.properties | 2 +- .../resources/bootstrap-parent.properties | 2 +- .../src/test/resources/bootstrap.properties | 5 +- .../external-properties/bootstrap.properties | 2 +- .../src/test/resources/other.properties | 2 +- .../src/test/resources/plain.properties | 2 +- .../eclipse/eclipse-code-formatter.xml | 1043 +++++++++++----- .../pom.xml | 5 +- .../RefreshScopeIntegrationTests.java | 49 +- .../src/test/resources/application.properties | 8 +- .../src/test/resources/bootstrap.properties | 2 +- .../eclipse/eclipse-code-formatter.xml | 1043 +++++++++++----- spring-cloud-context/pom.xml | 5 +- ...onPropertiesRebinderAutoConfiguration.java | 14 +- ...LifecycleMvcEndpointAutoConfiguration.java | 3 +- .../RefreshAutoConfiguration.java | 59 +- .../RefreshEndpointAutoConfiguration.java | 10 +- ...eEnvironmentEndpointAutoConfiguration.java | 19 +- .../BootstrapApplicationListener.java | 84 +- .../bootstrap/BootstrapConfiguration.java | 27 +- .../bootstrap/BootstrapImportSelector.java | 51 +- .../BootstrapImportSelectorConfiguration.java | 8 +- .../LoggingSystemShutdownListener.java | 11 +- .../PropertySourceBootstrapConfiguration.java | 12 +- .../PropertySourceBootstrapProperties.java | 21 + .../config/PropertySourceLocator.java | 6 +- .../EncryptionBootstrapConfiguration.java | 40 +- ...ironmentDecryptApplicationInitializer.java | 35 +- .../bootstrap/encrypt/KeyProperties.java | 18 +- .../bootstrap/encrypt/RsaProperties.java | 13 +- .../config/annotation/RefreshScope.java | 7 +- .../context/encrypt/EncryptorFactory.java | 5 +- .../context/encrypt/KeyFormatException.java | 14 +- .../environment/EnvironmentChangeEvent.java | 7 +- .../environment/EnvironmentManager.java | 41 +- .../WritableEnvironmentEndpoint.java | 16 + ...itableEnvironmentEndpointWebExtension.java | 11 +- .../named/ClientFactoryObjectProvider.java | 30 +- .../context/named/NamedContextFactory.java | 44 +- .../ConfigurationPropertiesBeans.java | 26 +- .../ConfigurationPropertiesRebinder.java | 20 +- .../context/refresh/ContextRefresher.java | 21 +- .../context/restart/RestartEndpoint.java | 65 +- .../context/restart/RestartListener.java | 4 +- .../cloud/context/scope/GenericScope.java | 99 +- .../cloud/context/scope/ScopeCache.java | 19 +- .../context/scope/StandardScopeCache.java | 16 +- .../context/scope/refresh/RefreshScope.java | 32 +- .../refresh/RefreshScopeRefreshedEvent.java | 24 +- .../scope/thread/ThreadLocalScopeCache.java | 12 +- .../context/scope/thread/ThreadScope.java | 27 +- .../cloud/endpoint/RefreshEndpoint.java | 2 +- .../cloud/endpoint/event/RefreshEvent.java | 19 + .../endpoint/event/RefreshEventListener.java | 27 +- .../cloud/env/EnvironmentUtils.java | 24 +- .../health/RefreshScopeHealthIndicator.java | 3 +- .../cloud/logging/LoggingRebinder.java | 6 +- .../cloud/util/ProxyUtils.java | 9 +- ...itional-spring-configuration-metadata.json | 90 +- .../main/resources/META-INF/spring.factories | 2 - .../LifecycleMvcAutoConfigurationTests.java | 80 +- ...efreshAutoConfigurationClassPathTests.java | 22 +- ...shAutoConfigurationMoreClassPathTests.java | 28 +- .../RefreshAutoConfigurationTests.java | 18 +- ...bledAutoConfigurationIntegrationTests.java | 8 +- ...ringAutoConfigurationIntegrationTests.java | 3 +- ...gCustomPropertySourceIntegrationTests.java | 9 +- ...SpringApplicationJsonIntegrationTests.java | 11 +- .../BootstrapSourcesOrderingTests.java | 1 + .../MessageSourceConfigurationTests.java | 7 +- .../bootstrap/TestBootstrapConfiguration.java | 7 +- ...tHigherPriorityBootstrapConfiguration.java | 6 +- .../config/BootstrapConfigurationTests.java | 37 +- ...trapListenerHierarchyIntegrationTests.java | 18 +- ...EncryptionBootstrapConfigurationTests.java | 20 +- .../encrypt/EncryptionIntegrationTests.java | 6 +- .../encrypt/EncryptorFactoryTests.java | 8 +- ...entDecryptApplicationInitializerTests.java | 1 + .../bootstrap/encrypt/RsaDisabledTests.java | 22 +- .../EnvironmentManagerIntegrationTests.java | 39 +- .../environment/EnvironmentManagerTest.java | 2 +- .../named/NamedContextFactoryTests.java | 33 +- ...ionPropertiesRebinderIntegrationTests.java | 23 +- ...tiesRebinderLifecycleIntegrationTests.java | 5 + ...ropertiesRebinderListIntegrationTests.java | 13 +- ...opertiesRebinderProxyIntegrationTests.java | 22 +- ...sRebinderRefreshScopeIntegrationTests.java | 39 +- .../ContextRefresherIntegrationTests.java | 6 +- .../refresh/ContextRefresherTests.java | 25 +- .../restart/RestartIntegrationTests.java | 39 +- .../ImportRefreshScopeIntegrationTests.java | 8 +- .../MoreRefreshScopeIntegrationTests.java | 52 +- .../RefreshEndpointIntegrationTests.java | 28 +- .../refresh/RefreshScopeConcurrencyTests.java | 14 +- .../RefreshScopeConfigurationScaleTests.java | 31 +- .../RefreshScopeConfigurationTests.java | 78 +- .../refresh/RefreshScopeIntegrationTests.java | 49 +- .../RefreshScopeLazyIntegrationTests.java | 45 +- .../RefreshScopeNullBeanIntegrationTests.java | 16 +- .../refresh/RefreshScopePureScaleTests.java | 41 +- .../scope/refresh/RefreshScopeScaleTests.java | 23 +- .../RefreshScopeSerializationTests.java | 1 + .../RefreshScopeWebIntegrationTests.java | 34 +- .../cloud/endpoint/RefreshEndpointTests.java | 16 +- .../RefreshScopeHealthIndicatorTests.java | 31 +- .../cloud/logging/LoggingRebinderTests.java | 7 +- .../resources/application-config.properties | 2 +- .../resources/application-encrypt.properties | 2 +- .../resources/application-local.properties | 2 +- .../resources/application-override.properties | 2 +- .../src/test/resources/application.properties | 8 +- .../resources/bootstrap-config.properties | 4 +- .../resources/bootstrap-encrypt.properties | 2 +- .../resources/bootstrap-parent.properties | 2 +- .../resources/bootstrap-refresh.properties | 4 +- .../src/test/resources/bootstrap.properties | 4 +- .../src/test/resources/custom.properties | 2 +- .../external-properties/bootstrap.properties | 2 +- .../src/test/resources/local.properties | 2 +- .../src/test/resources/messages.properties | 2 +- .../src/test/resources/other.properties | 2 +- .../src/test/resources/plain.properties | 2 +- spring-cloud-loadbalancer/pom.xml | 5 +- .../annotation/LoadBalancerClient.java | 19 +- .../LoadBalancerClientConfiguration.java | 13 +- ...dBalancerClientConfigurationRegistrar.java | 68 +- .../LoadBalancerClientSpecification.java | 28 +- .../annotation/LoadBalancerClients.java | 14 +- .../config/LoadBalancerAutoConfiguration.java | 10 +- .../core/CachingServiceInstanceSupplier.java | 38 +- ...iscoveryClientServiceInstanceSupplier.java | 11 +- .../core/ReactorLoadBalancer.java | 16 +- .../core/RoundRobinLoadBalancer.java | 23 +- .../core/ServiceInstanceSupplier.java | 3 +- .../support/LoadBalancerClientFactory.java | 13 +- .../support/ServiceInstanceSuppliers.java | 23 +- .../support/SimpleObjectProvider.java | 9 +- .../loadbalancer/core/LoadBalancerTest.java | 46 +- .../src/test/resources/application.yml | 45 +- spring-cloud-starter/pom.xml | 5 +- .../eclipse/eclipse-code-formatter.xml | 1043 +++++++++++----- spring-cloud-test-support/pom.xml | 5 +- .../cloud/test/ClassPathExclusions.java | 25 +- .../cloud/test/ClassPathOverrides.java | 2 +- .../cloud/test/ModifiedClassPathRunner.java | 6 +- 313 files changed, 8658 insertions(+), 4416 deletions(-) create mode 100644 .editorconfig diff --git a/.circleci/config.yml b/.circleci/config.yml index 075b8c91..133de9bd 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -37,4 +37,4 @@ jobs: destination: artifacts - store_test_results: path: ~/junit/ - destination: testartifacts \ No newline at end of file + destination: testartifacts diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 00000000..0679d88a --- /dev/null +++ b/.editorconfig @@ -0,0 +1,14 @@ +# EditorConfig is awesome: http://EditorConfig.org + +# top-most EditorConfig file +root = true + +[*] +indent_style = tab +indent_size = 4 +end_of_line = lf +insert_final_newline = true + +[*.yml] +indent_style = space +indent_size = 2 diff --git a/.settings.xml b/.settings.xml index 6c355129..6f542c94 100644 --- a/.settings.xml +++ b/.settings.xml @@ -1,66 +1,68 @@ - - - repo.spring.io - ${env.CI_DEPLOY_USERNAME} - ${env.CI_DEPLOY_PASSWORD} - - - - - - spring - true - - - spring-snapshots - Spring Snapshots - http://repo.spring.io/libs-snapshot-local - - true - - - - spring-milestones - Spring Milestones - http://repo.spring.io/libs-milestone-local - - false - - - - spring-releases - Spring Releases - http://repo.spring.io/release - - false - - - - - - spring-snapshots - Spring Snapshots - http://repo.spring.io/libs-snapshot-local - - true - - - - spring-milestones - Spring Milestones - http://repo.spring.io/libs-milestone-local - - false - - - - - + + + repo.spring.io + ${env.CI_DEPLOY_USERNAME} + ${env.CI_DEPLOY_PASSWORD} + + + + + + spring + + true + + + + spring-snapshots + Spring Snapshots + http://repo.spring.io/libs-snapshot-local + + true + + + + spring-milestones + Spring Milestones + http://repo.spring.io/libs-milestone-local + + false + + + + spring-releases + Spring Releases + http://repo.spring.io/release + + false + + + + + + spring-snapshots + Spring Snapshots + http://repo.spring.io/libs-snapshot-local + + true + + + + spring-milestones + Spring Milestones + http://repo.spring.io/libs-milestone-local + + false + + + + + diff --git a/docs/pom.xml b/docs/pom.xml index ed2d92d4..410eb4b7 100644 --- a/docs/pom.xml +++ b/docs/pom.xml @@ -1,6 +1,6 @@ - 4.0.0 org.springframework.cloud diff --git a/eclipse/eclipse-code-formatter.xml b/eclipse/eclipse-code-formatter.xml index 2586a2a2..f44070cf 100644 --- a/eclipse/eclipse-code-formatter.xml +++ b/eclipse/eclipse-code-formatter.xml @@ -1,315 +1,804 @@ - - - - - - - - - - - - - + + + + + + + + + + + + + - - - - - - + + + + + + - - - - - - - - + + + + + + + + - - + + - - - - - - - + + + + + + + - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + - - - - - - + + + + + + - - - - - - - - - - - - - - + + + + + + + + + + + + + + - - + + - - - - - - - - + + + + + + + + - - - + + + - - - - - + + + + + - - - - - - + + + + + + - - - + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - + + + + - - + + - - + + diff --git a/eclipse/org.eclipse.jdt.ui.prefs b/eclipse/org.eclipse.jdt.ui.prefs index e7f77db5..28f88e08 100644 --- a/eclipse/org.eclipse.jdt.ui.prefs +++ b/eclipse/org.eclipse.jdt.ui.prefs @@ -70,7 +70,7 @@ org.eclipse.jdt.ui.keywordthis=false org.eclipse.jdt.ui.ondemandthreshold=9999 org.eclipse.jdt.ui.overrideannotation=true org.eclipse.jdt.ui.staticondemandthreshold=9999 -org.eclipse.jdt.ui.text.custom_code_templates= +org.eclipse.jdt.ui.text.custom_code_templates= sp_cleanup.add_default_serial_version_id=true sp_cleanup.add_generated_serial_version_id=false sp_cleanup.add_missing_annotations=true diff --git a/pom.xml b/pom.xml index 26f41946..23a2a0cf 100644 --- a/pom.xml +++ b/pom.xml @@ -1,5 +1,7 @@ - + 4.0.0 org.springframework.cloud spring-cloud-commons-parent @@ -16,12 +18,18 @@ https://github.com/spring-cloud/spring-cloud-commons - scm:git:git://github.com/spring-cloud/spring-cloud-commons.git - scm:git:ssh://git@github.com/spring-cloud/spring-cloud-commons.git + scm:git:git://github.com/spring-cloud/spring-cloud-commons.git + + + scm:git:ssh://git@github.com/spring-cloud/spring-cloud-commons.git + HEAD commons + true + true + @@ -33,17 +41,39 @@ .settings/org.eclipse.jdt.ui.prefs - ${maven.multiModuleProjectDirectory}/eclipse/org.eclipse.jdt.ui.prefs + + ${maven.multiModuleProjectDirectory}/eclipse/org.eclipse.jdt.ui.prefs + .settings/org.eclipse.jdt.core.prefs - ${maven.multiModuleProjectDirectory}/eclipse/org.eclipse.jdt.core.prefs + + ${maven.multiModuleProjectDirectory}/eclipse/org.eclipse.jdt.core.prefs + + + org.apache.maven.plugins + maven-checkstyle-plugin + + + io.spring.javaformat + spring-javaformat-maven-plugin + + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + + + + spring diff --git a/spring-cloud-commons-dependencies/pom.xml b/spring-cloud-commons-dependencies/pom.xml index 0b5fcce1..cd5f5b39 100644 --- a/spring-cloud-commons-dependencies/pom.xml +++ b/spring-cloud-commons-dependencies/pom.xml @@ -1,12 +1,13 @@ - 4.0.0 spring-cloud-dependencies-parent org.springframework.cloud 2.1.3.BUILD-SNAPSHOT - + spring-cloud-commons-dependencies 2.1.1.BUILD-SNAPSHOT diff --git a/spring-cloud-commons/eclipse/eclipse-code-formatter.xml b/spring-cloud-commons/eclipse/eclipse-code-formatter.xml index 4694d7f2..5cbf769b 100644 --- a/spring-cloud-commons/eclipse/eclipse-code-formatter.xml +++ b/spring-cloud-commons/eclipse/eclipse-code-formatter.xml @@ -1,295 +1,754 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spring-cloud-commons/pom.xml b/spring-cloud-commons/pom.xml index 88c7d288..12861fab 100644 --- a/spring-cloud-commons/pom.xml +++ b/spring-cloud-commons/pom.xml @@ -1,6 +1,7 @@ - + 4.0.0 diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/CommonsClientAutoConfiguration.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/CommonsClientAutoConfiguration.java index cffbbba0..0177ec26 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/CommonsClientAutoConfiguration.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/CommonsClientAutoConfiguration.java @@ -57,10 +57,12 @@ public class CommonsClientAutoConfiguration { @ConditionalOnBean(DiscoveryClient.class) @ConditionalOnProperty(value = "spring.cloud.discovery.enabled", matchIfMissing = true) protected static class DiscoveryLoadBalancerConfiguration { + @Bean @ConditionalOnProperty(value = "spring.cloud.discovery.client.health-indicator.enabled", matchIfMissing = true) public DiscoveryClientHealthIndicator discoveryClientHealthIndicator( - ObjectProvider discoveryClient, DiscoveryClientHealthIndicatorProperties properties) { + ObjectProvider discoveryClient, + DiscoveryClientHealthIndicatorProperties properties) { return new DiscoveryClientHealthIndicator(discoveryClient, properties); } @@ -77,12 +79,14 @@ public class CommonsClientAutoConfiguration { return HasFeatures.abstractFeatures(DiscoveryClient.class, LoadBalancerClient.class); } + } @Configuration @ConditionalOnClass(Endpoint.class) @ConditionalOnProperty(value = "spring.cloud.features.enabled", matchIfMissing = true) protected static class ActuatorConfiguration { + @Autowired(required = false) private List hasFeatures = new ArrayList<>(); @@ -91,6 +95,7 @@ public class CommonsClientAutoConfiguration { public FeaturesEndpoint featuresEndpoint() { return new FeaturesEndpoint(this.hasFeatures); } + } } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/DefaultServiceInstance.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/DefaultServiceInstance.java index 5facde91..0e27c8f0 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/DefaultServiceInstance.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/DefaultServiceInstance.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-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. @@ -16,7 +16,6 @@ package org.springframework.cloud.client; - import java.net.URI; import java.util.LinkedHashMap; import java.util.Map; @@ -50,8 +49,8 @@ public class DefaultServiceInstance implements ServiceInstance { * @param secure indicates whether or not the connection needs to be secure. * @param metadata a map containing metadata. */ - public DefaultServiceInstance(String instanceId, String serviceId, String host, int port, boolean secure, - Map metadata) { + public DefaultServiceInstance(String instanceId, String serviceId, String host, + int port, boolean secure, Map metadata) { this.instanceId = instanceId; this.serviceId = serviceId; this.host = host; @@ -67,7 +66,8 @@ public class DefaultServiceInstance implements ServiceInstance { * @param port the port on which the service is running. * @param secure indicates whether or not the connection needs to be secure. */ - public DefaultServiceInstance(String instanceId, String serviceId, String host, int port, boolean secure) { + public DefaultServiceInstance(String instanceId, String serviceId, String host, + int port, boolean secure) { this(instanceId, serviceId, host, port, secure, new LinkedHashMap<>()); } @@ -77,7 +77,7 @@ public class DefaultServiceInstance implements ServiceInstance { * @param port the port on which the service is running. * @param secure indicates whether or not the connection needs to be secure. * @param metadata a map containing metadata. - * @deprecated + * @deprecated - use other constructors */ @Deprecated public DefaultServiceInstance(String serviceId, String host, int port, boolean secure, @@ -90,7 +90,7 @@ public class DefaultServiceInstance implements ServiceInstance { * @param host the host where the service instance can be found. * @param port the port on which the service is running. * @param secure indicates whether or not the connection needs to be secure. - * @deprecated + * @deprecated - use other constructors */ @Deprecated public DefaultServiceInstance(String serviceId, String host, int port, @@ -98,16 +98,6 @@ public class DefaultServiceInstance implements ServiceInstance { this(serviceId, host, port, secure, new LinkedHashMap<>()); } - @Override - public URI getUri() { - return getUri(this); - } - - @Override - public Map getMetadata() { - return this.metadata; - } - /** * Creates a URI from the given ServiceInstance's host:port. * @param instance the ServiceInstance. @@ -120,58 +110,69 @@ public class DefaultServiceInstance implements ServiceInstance { return URI.create(uri); } + @Override + public URI getUri() { + return getUri(this); + } + + @Override + public Map getMetadata() { + return this.metadata; + } + @Override public String getInstanceId() { - return instanceId; + return this.instanceId; } @Override public String getServiceId() { - return serviceId; + return this.serviceId; } @Override public String getHost() { - return host; + return this.host; } @Override public int getPort() { - return port; + return this.port; } @Override public boolean isSecure() { - return secure; + return this.secure; } @Override public String toString() { - return "DefaultServiceInstance{" + - "instanceId='" + instanceId + '\'' + - ", serviceId='" + serviceId + '\'' + - ", host='" + host + '\'' + - ", port=" + port + - ", secure=" + secure + - ", metadata=" + metadata + - '}'; + return "DefaultServiceInstance{" + "instanceId='" + this.instanceId + '\'' + + ", serviceId='" + this.serviceId + '\'' + ", host='" + this.host + '\'' + + ", port=" + this.port + ", secure=" + this.secure + ", metadata=" + + this.metadata + '}'; } @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } DefaultServiceInstance that = (DefaultServiceInstance) o; - return port == that.port && - secure == that.secure && - Objects.equals(instanceId, that.instanceId) && - Objects.equals(serviceId, that.serviceId) && - Objects.equals(host, that.host) && - Objects.equals(metadata, that.metadata); + return this.port == that.port && this.secure == that.secure + && Objects.equals(this.instanceId, that.instanceId) + && Objects.equals(this.serviceId, that.serviceId) + && Objects.equals(this.host, that.host) + && Objects.equals(this.metadata, that.metadata); } @Override public int hashCode() { - return Objects.hash(instanceId, serviceId, host, port, secure, metadata); + return Objects.hash(this.instanceId, this.serviceId, this.host, this.port, + this.secure, this.metadata); } + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/HostInfoEnvironmentPostProcessor.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/HostInfoEnvironmentPostProcessor.java index 751c7ac4..9bdb7c7c 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/HostInfoEnvironmentPostProcessor.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/HostInfoEnvironmentPostProcessor.java @@ -1,3 +1,19 @@ +/* + * Copyright 2012-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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.client; import java.util.LinkedHashMap; @@ -50,4 +66,5 @@ public class HostInfoEnvironmentPostProcessor return utils.findFirstNonLoopbackHostInfo(); } } + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/ServiceInstance.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/ServiceInstance.java index 546143e8..64294149 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/ServiceInstance.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/ServiceInstance.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-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. @@ -21,6 +21,7 @@ import java.util.Map; /** * Represents an instance of a service in a discovery system. + * * @author Spencer Gibb * @author Tim Ysewyn */ @@ -69,4 +70,5 @@ public interface ServiceInstance { default String getScheme() { return null; } + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/SpringCloudApplication.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/SpringCloudApplication.java index a99b48b7..e3f4e57e 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/SpringCloudApplication.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/SpringCloudApplication.java @@ -1,11 +1,32 @@ +/* + * Copyright 2012-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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.client; +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; -import java.lang.annotation.*; - /** * @author Spencer Gibb */ @@ -17,4 +38,5 @@ import java.lang.annotation.*; @EnableDiscoveryClient @EnableCircuitBreaker public @interface SpringCloudApplication { + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/actuator/FeaturesEndpoint.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/actuator/FeaturesEndpoint.java index 44bcb158..31347219 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/actuator/FeaturesEndpoint.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/actuator/FeaturesEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2017 the original author or authors. + * Copyright 2012-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. @@ -26,15 +26,14 @@ import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; - /** * @author Spencer Gibb */ @Endpoint(id = "features") -public class FeaturesEndpoint - implements ApplicationContextAware { +public class FeaturesEndpoint implements ApplicationContextAware { private final List hasFeaturesList; + private ApplicationContext context; public FeaturesEndpoint(List hasFeaturesList) { @@ -90,26 +89,32 @@ public class FeaturesEndpoint } static class Features { + final List enabled = new ArrayList<>(); + final List disabled = new ArrayList<>(); public List getEnabled() { - return enabled; + return this.enabled; } public List getDisabled() { - return disabled; + return this.disabled; } + } - static class Feature { + final String type; + final String name; + final String version; + final String vendor; - public Feature(String name, String type, String version, String vendor) { + Feature(String name, String type, String version, String vendor) { this.type = type; this.name = name; this.version = version; @@ -117,51 +122,64 @@ public class FeaturesEndpoint } public String getType() { - return type; + return this.type; } public String getName() { - return name; + return this.name; } public String getVersion() { - return version; + return this.version; } public String getVendor() { - return vendor; + return this.vendor; } @Override public String toString() { - return "Feature{" + - "type='" + type + '\'' + - ", name='" + name + '\'' + - ", version='" + version + '\'' + - ", vendor='" + vendor + '\'' + - '}'; + return "Feature{" + "type='" + this.type + '\'' + ", name='" + this.name + + '\'' + ", version='" + this.version + '\'' + ", vendor='" + + this.vendor + '\'' + '}'; } @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } Feature feature = (Feature) o; - if (type != null ? !type.equals(feature.type) : feature.type != null) return false; - if (name != null ? !name.equals(feature.name) : feature.name != null) return false; - if (version != null ? !version.equals(feature.version) : feature.version != null) return false; - return vendor != null ? vendor.equals(feature.vendor) : feature.vendor == null; + if (this.type != null ? !this.type.equals(feature.type) + : feature.type != null) { + return false; + } + if (this.name != null ? !this.name.equals(feature.name) + : feature.name != null) { + return false; + } + if (this.version != null ? !this.version.equals(feature.version) + : feature.version != null) { + return false; + } + return this.vendor != null ? this.vendor.equals(feature.vendor) + : feature.vendor == null; } @Override public int hashCode() { - int result = type != null ? type.hashCode() : 0; - result = 31 * result + (name != null ? name.hashCode() : 0); - result = 31 * result + (version != null ? version.hashCode() : 0); - result = 31 * result + (vendor != null ? vendor.hashCode() : 0); + int result = this.type != null ? this.type.hashCode() : 0; + result = 31 * result + (this.name != null ? this.name.hashCode() : 0); + result = 31 * result + (this.version != null ? this.version.hashCode() : 0); + result = 31 * result + (this.vendor != null ? this.vendor.hashCode() : 0); return result; } + } + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/actuator/HasFeatures.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/actuator/HasFeatures.java index 7ccf972d..d9ce96ae 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/actuator/HasFeatures.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/actuator/HasFeatures.java @@ -1,3 +1,19 @@ +/* + * Copyright 2012-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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.client.actuator; import java.util.ArrayList; @@ -14,13 +30,19 @@ public class HasFeatures { private final List namedFeatures = new ArrayList<>(); + public HasFeatures(List> abstractFeatures, + List namedFeatures) { + this.abstractFeatures.addAll(abstractFeatures); + this.namedFeatures.addAll(namedFeatures); + } + public static HasFeatures abstractFeatures(Class... abstractFeatures) { return new HasFeatures(Arrays.asList(abstractFeatures), - Collections. emptyList()); + Collections.emptyList()); } public static HasFeatures namedFeatures(NamedFeature... namedFeatures) { - return new HasFeatures(Collections.> emptyList(), + return new HasFeatures(Collections.>emptyList(), Arrays.asList(namedFeatures)); } @@ -34,12 +56,6 @@ public class HasFeatures { new NamedFeature(name2, type2)); } - public HasFeatures(List> abstractFeatures, - List namedFeatures) { - this.abstractFeatures.addAll(abstractFeatures); - this.namedFeatures.addAll(namedFeatures); - } - public List> getAbstractFeatures() { return this.abstractFeatures; } @@ -47,4 +63,5 @@ public class HasFeatures { public List getNamedFeatures() { return this.namedFeatures; } + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/actuator/NamedFeature.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/actuator/NamedFeature.java index 572263e0..41a6bdd2 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/actuator/NamedFeature.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/actuator/NamedFeature.java @@ -1,5 +1,5 @@ /* - * Copyright 2017 the original author or authors. + * Copyright 2012-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. @@ -13,14 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.springframework.cloud.client.actuator; +package org.springframework.cloud.client.actuator; /** * @author Spencer Gibb */ public class NamedFeature { + private final String name; + private final Class type; public NamedFeature(String name, Class type) { @@ -29,10 +31,11 @@ public class NamedFeature { } public String getName() { - return name; + return this.name; } public Class getType() { - return type; + return this.type; } + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/circuitbreaker/EnableCircuitBreakerImportSelector.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/circuitbreaker/EnableCircuitBreakerImportSelector.java index 934ffb74..4db401b6 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/circuitbreaker/EnableCircuitBreakerImportSelector.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/circuitbreaker/EnableCircuitBreakerImportSelector.java @@ -22,16 +22,17 @@ import org.springframework.core.annotation.Order; /** * Imports a single circuit breaker implementation configuration. + * * @author Spencer Gibb */ @Order(Ordered.LOWEST_PRECEDENCE - 100) -public class EnableCircuitBreakerImportSelector extends - SpringFactoryImportSelector { +public class EnableCircuitBreakerImportSelector + extends SpringFactoryImportSelector { @Override protected boolean isEnabled() { - return getEnvironment().getProperty( - "spring.cloud.circuit.breaker.enabled", Boolean.class, Boolean.TRUE); + return getEnvironment().getProperty("spring.cloud.circuit.breaker.enabled", + Boolean.class, Boolean.TRUE); } } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/DiscoveryClient.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/DiscoveryClient.java index 6c0f00ab..2326a59a 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/DiscoveryClient.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/DiscoveryClient.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-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. @@ -30,18 +30,19 @@ import org.springframework.core.Ordered; */ public interface DiscoveryClient extends Ordered { + /** + * Default order of the discovery client. + */ int DEFAULT_ORDER = 0; /** * A human-readable description of the implementation, used in HealthIndicator. - * * @return The description. */ String description(); /** * Gets all ServiceInstances associated with a particular serviceId. - * * @param serviceId The serviceId to query. * @return A List of ServiceInstance. */ @@ -54,11 +55,11 @@ public interface DiscoveryClient extends Ordered { /** * Default implementation for getting order of discovery clients. - * * @return order */ @Override default int getOrder() { return DEFAULT_ORDER; } + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/EnableDiscoveryClient.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/EnableDiscoveryClient.java index efa96caa..373c1f6c 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/EnableDiscoveryClient.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/EnableDiscoveryClient.java @@ -38,6 +38,8 @@ public @interface EnableDiscoveryClient { /** * If true, the ServiceRegistry will automatically register the local server. + * @return - {@code true} if you want to automatically register. */ boolean autoRegister() default true; + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/EnableDiscoveryClientImportSelector.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/EnableDiscoveryClientImportSelector.java index b5d99298..2691eeb1 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/EnableDiscoveryClientImportSelector.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/EnableDiscoveryClientImportSelector.java @@ -16,6 +16,11 @@ package org.springframework.cloud.client.discovery; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.List; + import org.springframework.cloud.commons.util.SpringFactoryImportSelector; import org.springframework.core.Ordered; import org.springframework.core.annotation.AnnotationAttributes; @@ -25,11 +30,6 @@ import org.springframework.core.env.Environment; import org.springframework.core.env.MapPropertySource; import org.springframework.core.type.AnnotationMetadata; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.LinkedHashMap; -import java.util.List; - /** * @author Spencer Gibb */ @@ -48,12 +48,14 @@ public class EnableDiscoveryClientImportSelector if (autoRegister) { List importsList = new ArrayList<>(Arrays.asList(imports)); - importsList.add("org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration"); + importsList.add( + "org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration"); imports = importsList.toArray(new String[0]); - } else { + } + else { Environment env = getEnvironment(); - if(ConfigurableEnvironment.class.isInstance(env)) { - ConfigurableEnvironment configEnv = (ConfigurableEnvironment)env; + if (ConfigurableEnvironment.class.isInstance(env)) { + ConfigurableEnvironment configEnv = (ConfigurableEnvironment) env; LinkedHashMap map = new LinkedHashMap<>(); map.put("spring.cloud.service-registry.auto-registration.enabled", false); MapPropertySource propertySource = new MapPropertySource( @@ -68,8 +70,8 @@ public class EnableDiscoveryClientImportSelector @Override protected boolean isEnabled() { - return getEnvironment().getProperty( - "spring.cloud.discovery.enabled", Boolean.class, Boolean.TRUE); + return getEnvironment().getProperty("spring.cloud.discovery.enabled", + Boolean.class, Boolean.TRUE); } @Override diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/ManagementServerPortUtils.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/ManagementServerPortUtils.java index 4bdff639..551e7292 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/ManagementServerPortUtils.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/ManagementServerPortUtils.java @@ -23,23 +23,34 @@ import org.springframework.boot.autoconfigure.web.ServerProperties; import org.springframework.web.context.WebApplicationContext; /** - * FIXME: + * Utility class for management server ports. + * * @author Spencer Gibb */ -public class ManagementServerPortUtils { - /** for testing */ static final boolean hasActuator; +public final class ManagementServerPortUtils { + + // for testing + static final boolean hasActuator; + static { - boolean hasEndpointClass = hasClass("org.springframework.boot.actuate.endpoint.annotation.Endpoint"); - boolean hasManagementServerPropertiesClass = hasClass("org.springframework.boot.actuate.autoconfigure.web.server.ManagementServerProperties"); + boolean hasEndpointClass = hasClass( + "org.springframework.boot.actuate.endpoint.annotation.Endpoint"); + boolean hasManagementServerPropertiesClass = hasClass( + "org.springframework.boot.actuate.autoconfigure.web.server.ManagementServerProperties"); hasActuator = hasEndpointClass && hasManagementServerPropertiesClass; } + private ManagementServerPortUtils() { + throw new IllegalStateException("Can't instantiate a utility class"); + } + private static boolean hasClass(String className) { boolean hasClass; try { Class.forName(className); hasClass = true; - } catch (ClassNotFoundException e) { + } + catch (ClassNotFoundException e) { hasClass = false; } return hasClass; @@ -76,9 +87,26 @@ public class ManagementServerPortUtils { } // TODO: copied from EndpointWebMvcAutoConfiguration.ManagementServerPort - public static enum ManagementServerPort { - DISABLE, SAME, DIFFERENT; + /** + * Enumeration for management server ports. + */ + public enum ManagementServerPort { + + /** + * Disabled management server port. + */ + DISABLE, + + /** + * Add it. TODO: Add it + */ + SAME, + + /** + * Add it. TODO: Add it + */ + DIFFERENT; public static ManagementServerPort get(BeanFactory beanFactory) { if (!hasActuator) { @@ -113,8 +141,9 @@ public class ManagementServerPortUtils { return ((port == null) || (serverProperties.getPort() == null && port.equals(8080)) || (port != 0 && port.equals(serverProperties.getPort())) ? SAME - : DIFFERENT); + : DIFFERENT); } + } } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/composite/CompositeDiscoveryClient.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/composite/CompositeDiscoveryClient.java index 2df075d8..23b07bed 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/composite/CompositeDiscoveryClient.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/composite/CompositeDiscoveryClient.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2012-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. @@ -28,7 +28,7 @@ import org.springframework.core.annotation.AnnotationAwareOrderComparator; /** * A {@link DiscoveryClient} that is composed of other discovery clients and delegates * calls to each of them in order. - * + * * @author Biju Kunjummen * @author Olga Maciaszek-Sharma */ @@ -49,7 +49,7 @@ public class CompositeDiscoveryClient implements DiscoveryClient { @Override public List getInstances(String serviceId) { if (this.discoveryClients != null) { - for (DiscoveryClient discoveryClient : discoveryClients) { + for (DiscoveryClient discoveryClient : this.discoveryClients) { List instances = discoveryClient.getInstances(serviceId); if (instances != null && !instances.isEmpty()) { return instances; @@ -63,7 +63,7 @@ public class CompositeDiscoveryClient implements DiscoveryClient { public List getServices() { LinkedHashSet services = new LinkedHashSet<>(); if (this.discoveryClients != null) { - for (DiscoveryClient discoveryClient : discoveryClients) { + for (DiscoveryClient discoveryClient : this.discoveryClients) { List serviceForClient = discoveryClient.getServices(); if (serviceForClient != null) { services.addAll(serviceForClient); @@ -74,6 +74,7 @@ public class CompositeDiscoveryClient implements DiscoveryClient { } public List getDiscoveryClients() { - return discoveryClients; + return this.discoveryClients; } + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/composite/CompositeDiscoveryClientAutoConfiguration.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/composite/CompositeDiscoveryClientAutoConfiguration.java index cefc0337..a68c7212 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/composite/CompositeDiscoveryClientAutoConfiguration.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/composite/CompositeDiscoveryClientAutoConfiguration.java @@ -1,5 +1,23 @@ +/* + * Copyright 2012-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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.client.discovery.composite; +import java.util.List; + import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.cloud.client.discovery.simple.SimpleDiscoveryClientAutoConfiguration; @@ -7,22 +25,21 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; -import java.util.List; - /** * Auto-configuration for composite discovery client. - * + * * @author Biju Kunjummen */ @Configuration @AutoConfigureBefore(SimpleDiscoveryClientAutoConfiguration.class) public class CompositeDiscoveryClientAutoConfiguration { - + @Bean @Primary - public CompositeDiscoveryClient compositeDiscoveryClient(List discoveryClients) { + public CompositeDiscoveryClient compositeDiscoveryClient( + List discoveryClients) { return new CompositeDiscoveryClient(discoveryClients); } - + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/event/HeartbeatEvent.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/event/HeartbeatEvent.java index e0e6eac0..76233408 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/event/HeartbeatEvent.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/event/HeartbeatEvent.java @@ -19,9 +19,9 @@ package org.springframework.cloud.client.discovery.event; import org.springframework.context.ApplicationEvent; /** - * An event that a DiscoveryClient implementation can broadcast if it supports - * heartbeats from the discovery server. Provides listeners with a basic indication - * of a state change in the service catalog. + * An event that a DiscoveryClient implementation can broadcast if it supports heartbeats + * from the discovery server. Provides listeners with a basic indication of a state change + * in the service catalog. * * @author Spencer Gibb * @author Dave Syer @@ -34,7 +34,6 @@ public class HeartbeatEvent extends ApplicationEvent { /** * Creates a new event with a source (for example, a discovery client) and a value. * Neither parameter should be relied on to have specific content or format. - * * @param source The source of the event. * @param state The value indicating state of the catalog. */ @@ -46,10 +45,9 @@ public class HeartbeatEvent extends ApplicationEvent { /** * A value representing the state of the service catalog. The only requirement is that * it changes when the catalog is updated; it can be as simple as a version counter or - * a hash. Implementations can provide information to help users visualize - * what is going on in the catalog, but users should not rely on the content (since - * the implementation of the underlying discovery might change). - * + * a hash. Implementations can provide information to help users visualize what is + * going on in the catalog, but users should not rely on the content (since the + * implementation of the underlying discovery might change). * @return A value representing state of the service catalog. */ public Object getValue() { diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/event/HeartbeatMonitor.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/event/HeartbeatMonitor.java index cfcd0629..cba4287b 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/event/HeartbeatMonitor.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/event/HeartbeatMonitor.java @@ -19,8 +19,8 @@ package org.springframework.cloud.client.discovery.event; import java.util.concurrent.atomic.AtomicReference; /** - * Helper class for listeners to the {@link HeartbeatEvent}, providing a convenient way - * to determine if there has been a change in state. + * Helper class for listeners to the {@link HeartbeatEvent}, providing a convenient way to + * determine if there has been a change in state. * * @author Dave Syer */ diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/event/InstancePreRegisteredEvent.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/event/InstancePreRegisteredEvent.java index 6253c546..8cd95ff6 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/event/InstancePreRegisteredEvent.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/event/InstancePreRegisteredEvent.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-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. @@ -21,6 +21,7 @@ import org.springframework.context.ApplicationEvent; /** * An event to fire before a service is registered. + * * @author Ryan Baxter */ public class InstancePreRegisteredEvent extends ApplicationEvent { @@ -29,8 +30,8 @@ public class InstancePreRegisteredEvent extends ApplicationEvent { /** * Create a new pre registration event. - * * @param source the object on which the event initially occurred (never {@code null}) + * @param registration the registration meta data */ public InstancePreRegisteredEvent(Object source, Registration registration) { super(source); @@ -42,6 +43,7 @@ public class InstancePreRegisteredEvent extends ApplicationEvent { * @return the registration data */ public Registration getRegistration() { - return registration; + return this.registration; } + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/event/InstanceRegisteredEvent.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/event/InstanceRegisteredEvent.java index 6be79d95..17c444c4 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/event/InstanceRegisteredEvent.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/event/InstanceRegisteredEvent.java @@ -23,6 +23,7 @@ import org.springframework.context.ApplicationEvent; * discovery service. * * @author Spencer Gibb + * @param - type of configuration */ @SuppressWarnings("serial") public class InstanceRegisteredEvent extends ApplicationEvent { diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/health/DiscoveryClientHealthIndicator.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/health/DiscoveryClientHealthIndicator.java index 915ae195..71bbcf22 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/health/DiscoveryClientHealthIndicator.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/health/DiscoveryClientHealthIndicator.java @@ -21,6 +21,7 @@ import java.util.concurrent.atomic.AtomicBoolean; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.actuate.health.Health; import org.springframework.boot.actuate.health.Status; @@ -29,23 +30,24 @@ import org.springframework.cloud.client.discovery.event.InstanceRegisteredEvent; import org.springframework.context.ApplicationListener; import org.springframework.core.Ordered; - /** * @author Spencer Gibb */ public class DiscoveryClientHealthIndicator implements DiscoveryHealthIndicator, Ordered, ApplicationListener> { - private AtomicBoolean discoveryInitialized = new AtomicBoolean(false); - - private int order = Ordered.HIGHEST_PRECEDENCE; - private final ObjectProvider discoveryClient; + private final DiscoveryClientHealthIndicatorProperties properties; private final Log log = LogFactory.getLog(DiscoveryClientHealthIndicator.class); - public DiscoveryClientHealthIndicator(ObjectProvider discoveryClient, DiscoveryClientHealthIndicatorProperties properties) { + private AtomicBoolean discoveryInitialized = new AtomicBoolean(false); + + private int order = Ordered.HIGHEST_PRECEDENCE; + + public DiscoveryClientHealthIndicator(ObjectProvider discoveryClient, + DiscoveryClientHealthIndicatorProperties properties) { this.discoveryClient = discoveryClient; this.properties = properties; } @@ -53,7 +55,7 @@ public class DiscoveryClientHealthIndicator implements DiscoveryHealthIndicator, @Override public void onApplicationEvent(InstanceRegisteredEvent event) { if (this.discoveryInitialized.compareAndSet(false, true)) { - log.debug("Discovery Client has been initialized"); + this.log.debug("Discovery Client has been initialized"); } } @@ -65,12 +67,13 @@ public class DiscoveryClientHealthIndicator implements DiscoveryHealthIndicator, try { DiscoveryClient client = this.discoveryClient.getIfAvailable(); List services = client.getServices(); - String description = (this.properties.isIncludeDescription()) ? client.description() : ""; - builder.status(new Status("UP", description)) - .withDetail("services", services); + String description = (this.properties.isIncludeDescription()) + ? client.description() : ""; + builder.status(new Status("UP", description)).withDetail("services", + services); } catch (Exception e) { - log.error("Error", e); + this.log.error("Error", e); builder.down(e); } } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/health/DiscoveryClientHealthIndicatorProperties.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/health/DiscoveryClientHealthIndicatorProperties.java index 30efebc7..f886309c 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/health/DiscoveryClientHealthIndicatorProperties.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/health/DiscoveryClientHealthIndicatorProperties.java @@ -1,3 +1,19 @@ +/* + * Copyright 2012-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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.client.discovery.health; import org.springframework.boot.context.properties.ConfigurationProperties; @@ -13,7 +29,7 @@ public class DiscoveryClientHealthIndicatorProperties { private boolean includeDescription = false; public boolean isEnabled() { - return enabled; + return this.enabled; } public void setEnabled(boolean enabled) { @@ -21,7 +37,7 @@ public class DiscoveryClientHealthIndicatorProperties { } public boolean isIncludeDescription() { - return includeDescription; + return this.includeDescription; } public void setIncludeDescription(boolean includeDescription) { @@ -30,10 +46,12 @@ public class DiscoveryClientHealthIndicatorProperties { @Override public String toString() { - final StringBuffer sb = new StringBuffer("DiscoveryClientHealthIndicatorProperties{"); - sb.append("enabled=").append(enabled); - sb.append(", includeDescription=").append(includeDescription); + final StringBuffer sb = new StringBuffer( + "DiscoveryClientHealthIndicatorProperties{"); + sb.append("enabled=").append(this.enabled); + sb.append(", includeDescription=").append(this.includeDescription); sb.append('}'); return sb.toString(); } + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/health/DiscoveryCompositeHealthIndicator.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/health/DiscoveryCompositeHealthIndicator.java index 1626786e..b11ce78c 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/health/DiscoveryCompositeHealthIndicator.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/health/DiscoveryCompositeHealthIndicator.java @@ -26,11 +26,12 @@ import org.springframework.boot.actuate.health.HealthAggregator; import org.springframework.boot.actuate.health.HealthIndicator; /** - * Gathers all instances of DiscoveryHealthIndicator from a DiscoveryClient - * implementation and aggregates the statuses. + * Gathers all instances of DiscoveryHealthIndicator from a DiscoveryClient implementation + * and aggregates the statuses. + * * @author Spencer Gibb */ -//TODO: do we need this? Can they just be independent HealthIndicators? +// TODO: do we need this? Can they just be independent HealthIndicators? public class DiscoveryCompositeHealthIndicator extends CompositeHealthIndicator { private final ArrayList healthIndicators = new ArrayList<>(); @@ -42,15 +43,19 @@ public class DiscoveryCompositeHealthIndicator extends CompositeHealthIndicator for (DiscoveryHealthIndicator indicator : indicators) { Holder holder = new Holder(indicator); addHealthIndicator(indicator.getName(), holder); - healthIndicators.add(holder); + this.healthIndicators.add(holder); } } public ArrayList getHealthIndicators() { - return healthIndicators; + return this.healthIndicators; } + /** + * Holder for the Health Indicator. + */ public static class Holder implements HealthIndicator { + private DiscoveryHealthIndicator delegate; public Holder(DiscoveryHealthIndicator delegate) { @@ -63,8 +68,9 @@ public class DiscoveryCompositeHealthIndicator extends CompositeHealthIndicator } public DiscoveryHealthIndicator getDelegate() { - return delegate; + return this.delegate; } + } } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/health/DiscoveryHealthIndicator.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/health/DiscoveryHealthIndicator.java index cbf4287d..a68b4570 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/health/DiscoveryHealthIndicator.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/health/DiscoveryHealthIndicator.java @@ -20,6 +20,7 @@ import org.springframework.boot.actuate.health.Health; /** * A health indicator interface specific to a DiscoveryClient implementation. + * * @author Spencer Gibb */ public interface DiscoveryHealthIndicator { diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/noop/NoopDiscoveryClient.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/noop/NoopDiscoveryClient.java index 46170bce..9927d764 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/noop/NoopDiscoveryClient.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/noop/NoopDiscoveryClient.java @@ -25,8 +25,9 @@ import org.springframework.cloud.client.discovery.DiscoveryClient; /** * DiscoveryClient used when no implementations are found on the classpath. * - * @deprecated Use {@link org.springframework.cloud.client.discovery.simple.SimpleDiscoveryClient instead}. - * + * @deprecated Use + * {@link org.springframework.cloud.client.discovery.simple.SimpleDiscoveryClient + * instead}. * @author Dave Syer */ diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/noop/NoopDiscoveryClientAutoConfiguration.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/noop/NoopDiscoveryClientAutoConfiguration.java index 60dd0ff4..4a5d8bdb 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/noop/NoopDiscoveryClientAutoConfiguration.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/noop/NoopDiscoveryClientAutoConfiguration.java @@ -23,6 +23,7 @@ import javax.annotation.PostConstruct; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; @@ -39,10 +40,9 @@ import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.core.env.Environment; /** - * * @deprecated Use - * {@link org.springframework.cloud.client.discovery.simple.SimpleDiscoveryClientAutoConfiguration instead}. - * + * {@link org.springframework.cloud.client.discovery.simple.SimpleDiscoveryClientAutoConfiguration + * instead}. * @author Dave Syer */ @Configuration @@ -52,6 +52,8 @@ import org.springframework.core.env.Environment; public class NoopDiscoveryClientAutoConfiguration implements ApplicationListener { + private final Log log = LogFactory.getLog(NoopDiscoveryClientAutoConfiguration.class); + @Autowired(required = false) private ServerProperties server; @@ -66,8 +68,6 @@ public class NoopDiscoveryClientAutoConfiguration private DefaultServiceInstance serviceInstance; - private final Log log = LogFactory.getLog(NoopDiscoveryClientAutoConfiguration.class); - @PostConstruct public void init() { String host = "localhost"; @@ -75,7 +75,7 @@ public class NoopDiscoveryClientAutoConfiguration host = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { - log.warn("Cannot get host info: (" + e.getMessage() + ")"); + this.log.warn("Cannot get host info: (" + e.getMessage() + ")"); } int port = findPort(); this.serviceInstance = new DefaultServiceInstance( @@ -96,8 +96,8 @@ public class NoopDiscoveryClientAutoConfiguration } else { // Apparently spring-web is not on the classpath - if (log.isDebugEnabled()) { - log.debug( + if (this.log.isDebugEnabled()) { + this.log.debug( "Could not locate port in embedded container (spring-web not available)"); } } @@ -109,18 +109,21 @@ public class NoopDiscoveryClientAutoConfiguration this.context.publishEvent(new InstanceRegisteredEvent<>(this, this.environment)); } - private interface PortFinder { - Integer findPort(); - } - @Bean public DiscoveryClient discoveryClient() { return new NoopDiscoveryClient(this.serviceInstance); } + private interface PortFinder { + + Integer findPort(); + + } + @Configuration - @ConditionalOnClass(name = {"org.springframework.web.context.support.GenericWebApplicationContext", - "org.springframework.boot.context.embedded.EmbeddedWebApplicationContext"}) + @ConditionalOnClass(name = { + "org.springframework.web.context.support.GenericWebApplicationContext", + "org.springframework.boot.context.embedded.EmbeddedWebApplicationContext" }) protected static class Boot15PortFinderConfiguration { @Bean @@ -129,16 +132,18 @@ public class NoopDiscoveryClientAutoConfiguration @Override public Integer findPort() { // TODO: support reactive - /*if (context instanceof EmbeddedWebApplicationContext) { - EmbeddedServletContainer container = ((EmbeddedWebApplicationContext) context) - .getEmbeddedServletContainer(); - if (container != null) { - return container.getPort(); - } - }*/ + /* + * if (context instanceof EmbeddedWebApplicationContext) { + * EmbeddedServletContainer container = + * ((EmbeddedWebApplicationContext) context) + * .getEmbeddedServletContainer(); if (container != null) { return + * container.getPort(); } } + */ return null; } }; } + } + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/simple/SimpleDiscoveryClient.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/simple/SimpleDiscoveryClient.java index a6bae3dc..73b13139 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/simple/SimpleDiscoveryClient.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/simple/SimpleDiscoveryClient.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2012-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. @@ -64,4 +64,5 @@ public class SimpleDiscoveryClient implements DiscoveryClient { public int getOrder() { return this.simpleDiscoveryProperties.getOrder(); } + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/simple/SimpleDiscoveryClientAutoConfiguration.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/simple/SimpleDiscoveryClientAutoConfiguration.java index c7214636..25f5a8cd 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/simple/SimpleDiscoveryClientAutoConfiguration.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/simple/SimpleDiscoveryClientAutoConfiguration.java @@ -1,11 +1,27 @@ +/* + * Copyright 2012-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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.client.discovery.simple; +import java.net.URI; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.boot.autoconfigure.web.ServerProperties; -// import org.springframework.boot.context.embedded.EmbeddedServletContainer; -// import org.springframework.boot.context.embedded.EmbeddedWebApplicationContext; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.cloud.client.discovery.noop.NoopDiscoveryClientAutoConfiguration; import org.springframework.cloud.commons.util.InetUtils; @@ -14,9 +30,9 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; -import org.springframework.util.ClassUtils; -import java.net.URI; +// import org.springframework.boot.context.embedded.EmbeddedServletContainer; +// import org.springframework.boot.context.embedded.EmbeddedWebApplicationContext; /** * Spring Boot auto-configuration for simple properties-based discovery client. @@ -58,18 +74,15 @@ public class SimpleDiscoveryClientAutoConfiguration { } private int findPort() { - //FIXME: is what is the boot 2.0 equiv? - /*if (ClassUtils.isPresent( - "org.springframework.boot.context.embedded.EmbeddedWebApplicationContext", - null)) { - if (this.context instanceof EmbeddedWebApplicationContext) { - EmbeddedServletContainer container = ((EmbeddedWebApplicationContext) this.context) - .getEmbeddedServletContainer(); - if (container != null) { - return container.getPort(); - } - } - }*/ + // FIXME: is what is the boot 2.0 equiv? + /* + * if (ClassUtils.isPresent( + * "org.springframework.boot.context.embedded.EmbeddedWebApplicationContext", + * null)) { if (this.context instanceof EmbeddedWebApplicationContext) { + * EmbeddedServletContainer container = ((EmbeddedWebApplicationContext) + * this.context) .getEmbeddedServletContainer(); if (container != null) { return + * container.getPort(); } } } + */ if (this.server != null && this.server.getPort() != null && this.server.getPort() > 0) { return this.server.getPort(); diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/simple/SimpleDiscoveryProperties.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/simple/SimpleDiscoveryProperties.java index d920240c..aec63a26 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/simple/SimpleDiscoveryProperties.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/simple/SimpleDiscoveryProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2012-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. @@ -31,10 +31,9 @@ import org.springframework.cloud.client.discovery.DiscoveryClient; /** * Properties to hold the details of a * {@link org.springframework.cloud.client.discovery.DiscoveryClient} service instances - * for a given service. - * It also holds the user-configurable order that will be used to establish the - * precedence of this client in the list of clients - * used by {@link org.springframework.cloud.client.discovery.composite.CompositeDiscoveryClient}. + * for a given service. It also holds the user-configurable order that will be used to + * establish the precedence of this client in the list of clients used by + * {@link org.springframework.cloud.client.discovery.composite.CompositeDiscoveryClient}. * * @author Biju Kunjummen * @author Olga Maciaszek-Sharma @@ -43,6 +42,7 @@ import org.springframework.cloud.client.discovery.DiscoveryClient; @ConfigurationProperties(prefix = "spring.cloud.discovery.client.simple") public class SimpleDiscoveryProperties { + private Map> instances = new HashMap<>(); /** @@ -83,25 +83,34 @@ public class SimpleDiscoveryProperties { } } + /** + * Basic implementation of {@link ServiceInstance}. + */ public static class SimpleServiceInstance implements ServiceInstance { /** * The URI of the service instance. Will be parsed to extract the scheme, host, - * and port. + * and port. */ private URI uri; + private String host; + private int port; + private boolean secure; + /** * Metadata for the service instance. Can be used by discovery clients to modify * their behaviour per instance, e.g. when load balancing. */ private Map metadata = new LinkedHashMap<>(); + /** * The unique identifier or name for the service instance. */ private String instanceId; + /** * The identifier or name for the service. Multiple instances might share the same * service ID. @@ -115,16 +124,6 @@ public class SimpleDiscoveryProperties { setUri(uri); } - public void setUri(URI uri) { - this.uri = uri; - this.host = this.uri.getHost(); - this.port = this.uri.getPort(); - String scheme = this.uri.getScheme(); - if ("https".equals(scheme)) { - this.secure = true; - } - } - @Override public String getInstanceId() { return this.instanceId; @@ -163,9 +162,21 @@ public class SimpleDiscoveryProperties { return this.uri; } + public void setUri(URI uri) { + this.uri = uri; + this.host = this.uri.getHost(); + this.port = this.uri.getPort(); + String scheme = this.uri.getScheme(); + if ("https".equals(scheme)) { + this.secure = true; + } + } + @Override public Map getMetadata() { return this.metadata; } + } + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/hypermedia/CloudHypermediaAutoConfiguration.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/hypermedia/CloudHypermediaAutoConfiguration.java index de3887dc..743f3c63 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/hypermedia/CloudHypermediaAutoConfiguration.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/hypermedia/CloudHypermediaAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2017 the original author or authors. + * Copyright 2012-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. @@ -13,8 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.springframework.cloud.client.hypermedia; +package org.springframework.cloud.client.hypermedia; import java.util.Collections; import java.util.List; @@ -29,9 +29,10 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** - * Registers a default {@link RemoteResourceRefresher} if at least one {@link RemoteResource} is declared in the system. - * Applies verification timings defined in the application properties. - * + * Registers a default {@link RemoteResourceRefresher} if at least one + * {@link RemoteResource} is declared in the system. Applies verification timings defined + * in the application properties. + * * @author Oliver Gierke */ @Configuration @@ -39,36 +40,47 @@ import org.springframework.context.annotation.Configuration; @EnableConfigurationProperties(CloudHypermediaProperties.class) public class CloudHypermediaAutoConfiguration { - @Autowired(required = false) List discoveredResources = Collections.emptyList(); - @Autowired CloudHypermediaProperties properties; + @Autowired(required = false) + List discoveredResources = Collections.emptyList(); + + @Autowired + CloudHypermediaProperties properties; @Bean @ConditionalOnMissingBean public RemoteResourceRefresher discoveredResourceRefresher() { - return new RemoteResourceRefresher(discoveredResources, properties.getRefresh().getFixedDelay(), - properties.getRefresh().getInitialDelay()); + return new RemoteResourceRefresher(this.discoveredResources, + this.properties.getRefresh().getFixedDelay(), + this.properties.getRefresh().getInitialDelay()); } + /** + * Configuration for Cloud hypermedia. + */ @ConfigurationProperties(prefix = "spring.cloud.hypermedia") public static class CloudHypermediaProperties { private Refresh refresh = new Refresh(); public Refresh getRefresh() { - return refresh; + return this.refresh; } public void setRefresh(Refresh refresh) { this.refresh = refresh; } + /** + * Configuration for Cloud hypermedia refresh. + */ public static class Refresh { private int fixedDelay = 5000; + private int initialDelay = 10000; public int getFixedDelay() { - return fixedDelay; + return this.fixedDelay; } public void setFixedDelay(int fixedDelay) { @@ -76,12 +88,15 @@ public class CloudHypermediaAutoConfiguration { } public int getInitialDelay() { - return initialDelay; + return this.initialDelay; } public void setInitialDelay(int initialDelay) { this.initialDelay = initialDelay; } + } + } + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/hypermedia/DiscoveredResource.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/hypermedia/DiscoveredResource.java index a0a024c9..d0c45743 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/hypermedia/DiscoveredResource.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/hypermedia/DiscoveredResource.java @@ -1,5 +1,5 @@ /* - * Copyright 2015-2017 the original author or authors. + * Copyright 2012-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. @@ -13,12 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.client.hypermedia; import java.net.URI; import org.slf4j.Logger; import org.slf4j.LoggerFactory; + import org.springframework.cloud.client.ServiceInstance; import org.springframework.hateoas.Link; import org.springframework.hateoas.MediaTypes; @@ -29,51 +31,55 @@ import org.springframework.web.client.RestOperations; import org.springframework.web.client.RestTemplate; /** - * A REST resource that is defined by a service reference and a traversal operation within that service. + * A REST resource that is defined by a service reference and a traversal operation within + * that service. * * @author Oliver Gierke */ public class DiscoveredResource implements RemoteResource { private final ServiceInstanceProvider provider; - private final TraversalDefinition traversal; - - private RestOperations restOperations = new RestTemplate(); - private Link link = null; + private final TraversalDefinition traversal; private final Logger log = LoggerFactory.getLogger(DiscoveredResource.class); + private RestOperations restOperations = new RestTemplate(); - public DiscoveredResource(ServiceInstanceProvider provider, TraversalDefinition traversal) { + private Link link = null; + + public DiscoveredResource(ServiceInstanceProvider provider, + TraversalDefinition traversal) { this.provider = provider; this.traversal = traversal; } - /** - * Configures the {@link RestOperations} to use to execute the traversal and verifying HEAD calls. - * - * @param restOperations Can be {@literal null}; resorts to a default {@link RestTemplate} in that case. - */ - public void setRestOperations(RestOperations restOperations) { - this.restOperations = restOperations == null ? new RestTemplate() : restOperations; - } - public ServiceInstanceProvider getProvider() { - return provider; + return this.provider; } public TraversalDefinition getTraversal() { - return traversal; + return this.traversal; } public RestOperations getRestOperations() { - return restOperations; + return this.restOperations; + } + + /** + * Configures the {@link RestOperations} to use to execute the traversal and verifying + * HEAD calls. + * @param restOperations Can be {@literal null}; resorts to a default + * {@link RestTemplate} in that case. + */ + public void setRestOperations(RestOperations restOperations) { + this.restOperations = restOperations == null ? new RestTemplate() + : restOperations; } @Override public Link getLink() { - return link; + return this.link; } public void setLink(Link link) { @@ -84,14 +90,13 @@ public class DiscoveredResource implements RemoteResource { * Verifies the link to the current. */ public void verifyOrDiscover() { - this.link = link == null ? discoverLink() : verify(link); + this.link = this.link == null ? discoverLink() : verify(this.link); } /** * Verifies the given {@link Link} by issuing an HTTP HEAD request to the resource. - * * @param link Must not be {@literal null}. - * @return + * @return - link to the resource */ private Link verify(Link link) { @@ -101,15 +106,16 @@ public class DiscoveredResource implements RemoteResource { String uri = link.expand().getHref(); - log.debug("Verifying link pointing to {}…", uri); - restOperations.headForHeaders(uri); - log.debug("Successfully verified link!"); + this.log.debug("Verifying link pointing to {}…", uri); + this.restOperations.headForHeaders(uri); + this.log.debug("Successfully verified link!"); return link; - } catch (RestClientException o_O) { + } + catch (RestClientException o_O) { - log.debug("Verification failed, marking as outdated!"); + this.log.debug("Verification failed, marking as outdated!"); return null; } } @@ -118,7 +124,7 @@ public class DiscoveredResource implements RemoteResource { try { - ServiceInstance service = provider.getServiceInstance(); + ServiceInstance service = this.provider.getServiceInstance(); if (service == null) { return null; @@ -127,21 +133,24 @@ public class DiscoveredResource implements RemoteResource { URI uri = service.getUri(); String serviceId = service.getServiceId(); - log.debug("Discovered {} system at {}. Discovering resource…", serviceId, uri); + this.log.debug("Discovered {} system at {}. Discovering resource…", serviceId, + uri); Traverson traverson = new Traverson(uri, MediaTypes.HAL_JSON); - Link link = traversal.buildTraversal(traverson).asTemplatedLink(); + Link link = this.traversal.buildTraversal(traverson).asTemplatedLink(); - log.debug("Found link pointing to {}.", link.getHref()); + this.log.debug("Found link pointing to {}.", link.getHref()); return link; - } catch (RuntimeException o_O) { + } + catch (RuntimeException o_O) { this.link = null; - log.debug("Target system unavailable. Got: ", o_O.getMessage()); + this.log.debug("Target system unavailable. Got: ", o_O.getMessage()); return null; } } + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/hypermedia/DynamicServiceInstanceProvider.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/hypermedia/DynamicServiceInstanceProvider.java index ab25f970..22bfd9fb 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/hypermedia/DynamicServiceInstanceProvider.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/hypermedia/DynamicServiceInstanceProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2015-2017 the original author or authors. + * Copyright 2012-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. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.client.hypermedia; import java.util.List; @@ -21,14 +22,16 @@ import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.discovery.DiscoveryClient; /** - * {@link ServiceInstanceProvider} to work with a {@link DiscoveryClient} to look up a service by name. Picks the - * first one returned by the configured {@link DiscoveryClient}. - * + * {@link ServiceInstanceProvider} to work with a {@link DiscoveryClient} to look up a + * service by name. Picks the first one returned by the configured + * {@link DiscoveryClient}. + * * @author Oliver Gierke */ public class DynamicServiceInstanceProvider implements ServiceInstanceProvider { private final DiscoveryClient client; + private final String serviceName; public DynamicServiceInstanceProvider(DiscoveryClient client, String serviceName) { @@ -36,20 +39,23 @@ public class DynamicServiceInstanceProvider implements ServiceInstanceProvider { this.serviceName = serviceName; } - /* - * (non-Javadoc) - * @see example.customers.integration.ServiceInstanceProvider#getServiceInstance() - */ + /* + * (non-Javadoc) + * + * @see example.customers.integration.ServiceInstanceProvider#getServiceInstance() + */ @Override public ServiceInstance getServiceInstance() { try { - List instances = client.getInstances(serviceName); + List instances = this.client.getInstances(this.serviceName); return instances.isEmpty() ? null : instances.get(0); - } catch (RuntimeException o_O) { + } + catch (RuntimeException o_O) { return null; } } + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/hypermedia/RemoteResource.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/hypermedia/RemoteResource.java index c3e81ef2..084f05a2 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/hypermedia/RemoteResource.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/hypermedia/RemoteResource.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2012-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. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.client.hypermedia; import org.springframework.hateoas.Link; @@ -25,15 +26,17 @@ import org.springframework.hateoas.Link; public interface RemoteResource { /** - * Returns the {@link Link} to the resource if it is available, or {@literal null} - * if it is gone (i.e. it either is generally unavailable or can't be discovered). + * Returns the {@link Link} to the resource if it is available, or {@literal null} if + * it is gone (i.e. it either is generally unavailable or can't be discovered). + * @return a link to the resource. */ Link getLink(); /** - * Discovers the resource if it hasn't been discovered yet or has become - * unavailable. If a link has been discovered previously, it is verified and either - * confirmed or removed to indicate that it's not available anymore. + * Discovers the resource if it hasn't been discovered yet or has become unavailable. + * If a link has been discovered previously, it is verified and either confirmed or + * removed to indicate that it's not available anymore. */ void verifyOrDiscover(); + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/hypermedia/RemoteResourceRefresher.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/hypermedia/RemoteResourceRefresher.java index 09ca1acf..a2544a63 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/hypermedia/RemoteResourceRefresher.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/hypermedia/RemoteResourceRefresher.java @@ -1,5 +1,5 @@ /* - * Copyright 2017 the original author or authors. + * Copyright 2012-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. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.client.hypermedia; import java.util.List; @@ -22,39 +23,46 @@ import org.springframework.scheduling.config.IntervalTask; import org.springframework.scheduling.config.ScheduledTaskRegistrar; /** - * A {@link ScheduledTaskRegistrar} that verifies all {@link DiscoveredResource} instances in the system, based - * on the given timing configuration. - * + * A {@link ScheduledTaskRegistrar} that verifies all {@link DiscoveredResource} instances + * in the system, based on the given timing configuration. + * * @author Oliver Gierke */ public class RemoteResourceRefresher extends ContextLifecycleScheduledTaskRegistrar { private final List discoveredResources; - private final int fixedDelay, initialDelay; - public RemoteResourceRefresher(List discoveredResources, int fixedDelay, int initialDelay) { + private final int fixedDelay; + + private final int initialDelay; + + public RemoteResourceRefresher(List discoveredResources, + int fixedDelay, int initialDelay) { this.discoveredResources = discoveredResources; this.fixedDelay = fixedDelay; this.initialDelay = initialDelay; } - /* - * (non-Javadoc) - * @see org.springframework.scheduling.config.ContextLifecycleScheduledTaskRegistrar#afterPropertiesSet() - */ + /* + * (non-Javadoc) + * + * @see org.springframework.scheduling.config.ContextLifecycleScheduledTaskRegistrar# + * afterPropertiesSet() + */ @Override public void afterPropertiesSet() { - for (final RemoteResource resource : discoveredResources) { + for (final RemoteResource resource : this.discoveredResources) { addFixedDelayTask(new IntervalTask(new Runnable() { @Override public void run() { resource.verifyOrDiscover(); } - }, fixedDelay, initialDelay)); + }, this.fixedDelay, this.initialDelay)); } super.afterPropertiesSet(); } + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/hypermedia/ServiceInstanceProvider.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/hypermedia/ServiceInstanceProvider.java index 7eb59a00..3810e867 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/hypermedia/ServiceInstanceProvider.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/hypermedia/ServiceInstanceProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2012-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. @@ -13,22 +13,25 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.client.hypermedia; import org.springframework.cloud.client.ServiceInstance; /** - * A component that will provide a {@link ServiceInstance}, or can express the absence of one by - * returning {@literal null}. - * + * A component that will provide a {@link ServiceInstance}, or can express the absence of + * one by returning {@literal null}. + * * @author Oliver Gierke */ public interface ServiceInstanceProvider { /** - * Returns the service instance or {@literal null} if the service is currently unavailable. - * - * @return The service instance, or {@literal null} if the service is currently unavailable. + * Returns the service instance or {@literal null} if the service is currently + * unavailable. + * @return The service instance, or {@literal null} if the service is currently + * unavailable. */ ServiceInstance getServiceInstance(); + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/hypermedia/StaticServiceInstanceProvider.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/hypermedia/StaticServiceInstanceProvider.java index 1dc7715a..0fe8d7ed 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/hypermedia/StaticServiceInstanceProvider.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/hypermedia/StaticServiceInstanceProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2017 the original author or authors. + * Copyright 2012-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. @@ -13,13 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.client.hypermedia; import org.springframework.cloud.client.ServiceInstance; /** - * A {@link ServiceInstanceProvider} that will always return the configured {@link ServiceInstance}. - * + * A {@link ServiceInstanceProvider} that will always return the configured + * {@link ServiceInstance}. + * * @author Oliver Gierke */ public class StaticServiceInstanceProvider implements ServiceInstanceProvider { @@ -30,12 +32,14 @@ public class StaticServiceInstanceProvider implements ServiceInstanceProvider { this.instance = instance; } - /* - * (non-Javadoc) - * @see example.customers.integration.ServiceInstanceProvider#getServiceInstance() - */ + /* + * (non-Javadoc) + * + * @see example.customers.integration.ServiceInstanceProvider#getServiceInstance() + */ @Override public ServiceInstance getServiceInstance() { - return instance; + return this.instance; } + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/hypermedia/TraversalDefinition.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/hypermedia/TraversalDefinition.java index a4e68505..bba927dc 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/hypermedia/TraversalDefinition.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/hypermedia/TraversalDefinition.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2012-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. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.client.hypermedia; import org.springframework.hateoas.client.Traverson; @@ -27,6 +28,8 @@ public interface TraversalDefinition { /** * @param traverson The Traverson instance to run the traversal on. + * @return the builder for traversing */ TraversalBuilder buildTraversal(Traverson traverson); + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/AsyncLoadBalancerAutoConfiguration.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/AsyncLoadBalancerAutoConfiguration.java index ce0cf751..7ca8695b 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/AsyncLoadBalancerAutoConfiguration.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/AsyncLoadBalancerAutoConfiguration.java @@ -39,9 +39,9 @@ import org.springframework.web.client.AsyncRestTemplate; @ConditionalOnClass(AsyncRestTemplate.class) public class AsyncLoadBalancerAutoConfiguration { - @Configuration static class AsyncRestTemplateCustomizerConfig { + @LoadBalanced @Autowired(required = false) private List restTemplates = Collections.emptyList(); @@ -60,12 +60,15 @@ public class AsyncLoadBalancerAutoConfiguration { } }; } + } @Configuration static class LoadBalancerInterceptorConfig { + @Bean - public AsyncLoadBalancerInterceptor asyncLoadBalancerInterceptor(LoadBalancerClient loadBalancerClient) { + public AsyncLoadBalancerInterceptor asyncLoadBalancerInterceptor( + LoadBalancerClient loadBalancerClient) { return new AsyncLoadBalancerInterceptor(loadBalancerClient); } @@ -82,5 +85,7 @@ public class AsyncLoadBalancerAutoConfiguration { } }; } + } + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/AsyncLoadBalancerInterceptor.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/AsyncLoadBalancerInterceptor.java index f386d5ec..9f879428 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/AsyncLoadBalancerInterceptor.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/AsyncLoadBalancerInterceptor.java @@ -16,6 +16,9 @@ package org.springframework.cloud.client.loadbalancer; +import java.io.IOException; +import java.net.URI; + import org.springframework.cloud.client.ServiceInstance; import org.springframework.http.HttpRequest; import org.springframework.http.client.AsyncClientHttpRequestExecution; @@ -23,9 +26,6 @@ import org.springframework.http.client.AsyncClientHttpRequestInterceptor; import org.springframework.http.client.ClientHttpResponse; import org.springframework.util.concurrent.ListenableFuture; -import java.io.IOException; -import java.net.URI; - /** * @author Rob Worsnop */ @@ -38,21 +38,22 @@ public class AsyncLoadBalancerInterceptor implements AsyncClientHttpRequestInter } @Override - public ListenableFuture intercept(final HttpRequest request, final byte[] body, - final AsyncClientHttpRequestExecution execution) throws IOException { + public ListenableFuture intercept(final HttpRequest request, + final byte[] body, final AsyncClientHttpRequestExecution execution) + throws IOException { final URI originalUri = request.getURI(); String serviceName = originalUri.getHost(); return this.loadBalancer.execute(serviceName, new LoadBalancerRequest>() { @Override - public ListenableFuture apply(final ServiceInstance instance) - throws Exception { + public ListenableFuture apply( + final ServiceInstance instance) throws Exception { HttpRequest serviceRequest = new ServiceRequestWrapper(request, - instance, loadBalancer); + instance, AsyncLoadBalancerInterceptor.this.loadBalancer); return execution.executeAsync(serviceRequest, body); } }); } -} +} diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/AsyncRestTemplateCustomizer.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/AsyncRestTemplateCustomizer.java index 4ac6a90b..26b66718 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/AsyncRestTemplateCustomizer.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/AsyncRestTemplateCustomizer.java @@ -22,6 +22,7 @@ import org.springframework.web.client.AsyncRestTemplate; * @author Rob Worsnop */ public interface AsyncRestTemplateCustomizer { - void customize(AsyncRestTemplate restTemplate); -} + void customize(AsyncRestTemplate restTemplate); + +} diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/ClientHttpResponseStatusCodeException.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/ClientHttpResponseStatusCodeException.java index 93ff5435..b3d43ad7 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/ClientHttpResponseStatusCodeException.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/ClientHttpResponseStatusCodeException.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2018 the original author or authors. + * Copyright 2012-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. @@ -13,72 +13,81 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.client.loadbalancer; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; + import org.springframework.http.HttpHeaders; import org.springframework.http.client.AbstractClientHttpResponse; import org.springframework.http.client.ClientHttpResponse; /** * {@link RetryableStatusCodeException} that captures a {@link ClientHttpResponse}. + * * @author Ryan Baxter */ public class ClientHttpResponseStatusCodeException extends RetryableStatusCodeException { - private ClientHttpResponseWrapper response; + private final ClientHttpResponseWrapper response; /** * Constructor. * @param serviceId The service ID. * @param response The response object. - * @throws IOException Thrown if the {@link ClientHttpResponse} response code cannot be retrieved. + * @param body The response body. + * @throws IOException Thrown if the {@link ClientHttpResponse} response code cannot + * be retrieved. */ - public ClientHttpResponseStatusCodeException(String serviceId, ClientHttpResponse response, byte[] body) throws IOException { + public ClientHttpResponseStatusCodeException(String serviceId, + ClientHttpResponse response, byte[] body) throws IOException { super(serviceId, response.getRawStatusCode(), response, null); this.response = new ClientHttpResponseWrapper(response, body); } @Override public ClientHttpResponse getResponse() { - return response; + return this.response; } static class ClientHttpResponseWrapper extends AbstractClientHttpResponse { private ClientHttpResponse response; + private byte[] body; - public ClientHttpResponseWrapper(ClientHttpResponse response, byte[] body) { + ClientHttpResponseWrapper(ClientHttpResponse response, byte[] body) { this.response = response; this.body = body; } @Override public int getRawStatusCode() throws IOException { - return response.getRawStatusCode(); + return this.response.getRawStatusCode(); } @Override public String getStatusText() throws IOException { - return response.getStatusText(); + return this.response.getStatusText(); } @Override public void close() { - response.close(); + this.response.close(); } @Override public InputStream getBody() throws IOException { - return new ByteArrayInputStream(body); + return new ByteArrayInputStream(this.body); } @Override public HttpHeaders getHeaders() { - return response.getHeaders(); + return this.response.getHeaders(); } + } + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/InterceptorRetryPolicy.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/InterceptorRetryPolicy.java index 94e0e3fb..6f9cb996 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/InterceptorRetryPolicy.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/InterceptorRetryPolicy.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2016 the original author or authors. + * Copyright 2012-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. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.client.loadbalancer; import org.springframework.http.HttpRequest; @@ -20,83 +21,99 @@ import org.springframework.retry.RetryContext; import org.springframework.retry.RetryPolicy; /** - * {@link RetryPolicy} used by the {@link LoadBalancerClient} when retrying failed requests. + * {@link RetryPolicy} used by the {@link LoadBalancerClient} when retrying failed + * requests. + * * @author Ryan Baxter */ public class InterceptorRetryPolicy implements RetryPolicy { - private HttpRequest request; - private LoadBalancedRetryPolicy policy; - private ServiceInstanceChooser serviceInstanceChooser; - private String serviceName; + private HttpRequest request; - /** - * Creates a new retry policy. - * @param request The request that will be retried. - * @param policy The retry policy from the load balancer. - * @param serviceInstanceChooser The load balancer client. - * @param serviceName The name of the service. - */ - public InterceptorRetryPolicy(HttpRequest request, LoadBalancedRetryPolicy policy, - ServiceInstanceChooser serviceInstanceChooser, String serviceName) { - this.request = request; - this.policy = policy; - this.serviceInstanceChooser = serviceInstanceChooser; - this.serviceName = serviceName; - } + private LoadBalancedRetryPolicy policy; - @Override - public boolean canRetry(RetryContext context) { - LoadBalancedRetryContext lbContext = (LoadBalancedRetryContext)context; - if(lbContext.getRetryCount() == 0 && lbContext.getServiceInstance() == null) { - //We haven't even tried to make the request yet so return true so we do - lbContext.setServiceInstance(serviceInstanceChooser.choose(serviceName)); - return true; - } - return policy.canRetryNextServer(lbContext); - } + private ServiceInstanceChooser serviceInstanceChooser; - @Override - public RetryContext open(RetryContext parent) { - return new LoadBalancedRetryContext(parent, request); - } + private String serviceName; + /** + * Creates a new retry policy. + * @param request The request that will be retried. + * @param policy The retry policy from the load balancer. + * @param serviceInstanceChooser The load balancer client. + * @param serviceName The name of the service. + */ + public InterceptorRetryPolicy(HttpRequest request, LoadBalancedRetryPolicy policy, + ServiceInstanceChooser serviceInstanceChooser, String serviceName) { + this.request = request; + this.policy = policy; + this.serviceInstanceChooser = serviceInstanceChooser; + this.serviceName = serviceName; + } - @Override - public void close(RetryContext context) { - policy.close((LoadBalancedRetryContext)context); - } + @Override + public boolean canRetry(RetryContext context) { + LoadBalancedRetryContext lbContext = (LoadBalancedRetryContext) context; + if (lbContext.getRetryCount() == 0 && lbContext.getServiceInstance() == null) { + // We haven't even tried to make the request yet so return true so we do + lbContext.setServiceInstance( + this.serviceInstanceChooser.choose(this.serviceName)); + return true; + } + return this.policy.canRetryNextServer(lbContext); + } + @Override + public RetryContext open(RetryContext parent) { + return new LoadBalancedRetryContext(parent, this.request); + } - @Override - public void registerThrowable(RetryContext context, Throwable throwable) { - LoadBalancedRetryContext lbContext = (LoadBalancedRetryContext) context; - //this is important as it registers the last exception in the context and also increases the retry count - lbContext.registerThrowable(throwable); - //let the policy know about the exception as well - policy.registerThrowable(lbContext, throwable); - } + @Override + public void close(RetryContext context) { + this.policy.close((LoadBalancedRetryContext) context); + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + @Override + public void registerThrowable(RetryContext context, Throwable throwable) { + LoadBalancedRetryContext lbContext = (LoadBalancedRetryContext) context; + // this is important as it registers the last exception in the context and also + // increases the retry count + lbContext.registerThrowable(throwable); + // let the policy know about the exception as well + this.policy.registerThrowable(lbContext, throwable); + } - InterceptorRetryPolicy that = (InterceptorRetryPolicy) o; + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } - if (!request.equals(that.request)) return false; - if (!policy.equals(that.policy)) return false; - if (!serviceInstanceChooser.equals(that.serviceInstanceChooser)) return false; - return serviceName.equals(that.serviceName); + InterceptorRetryPolicy that = (InterceptorRetryPolicy) o; - } + if (!this.request.equals(that.request)) { + return false; + } + if (!this.policy.equals(that.policy)) { + return false; + } + if (!this.serviceInstanceChooser.equals(that.serviceInstanceChooser)) { + return false; + } + return this.serviceName.equals(that.serviceName); + + } + + @Override + public int hashCode() { + int result = this.request.hashCode(); + result = 31 * result + this.policy.hashCode(); + result = 31 * result + this.serviceInstanceChooser.hashCode(); + result = 31 * result + this.serviceName.hashCode(); + return result; + } - @Override - public int hashCode() { - int result = request.hashCode(); - result = 31 * result + policy.hashCode(); - result = 31 * result + serviceInstanceChooser.hashCode(); - result = 31 * result + serviceName.hashCode(); - return result; - } } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalanced.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalanced.java index 2d24c0e0..c7cb70fc 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalanced.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalanced.java @@ -16,8 +16,6 @@ package org.springframework.cloud.client.loadbalancer; -import org.springframework.beans.factory.annotation.Qualifier; - import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; @@ -25,6 +23,8 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import org.springframework.beans.factory.annotation.Qualifier; + /** * Annotation to mark a RestTemplate bean to be configured to use a LoadBalancerClient. * @author Spencer Gibb @@ -35,4 +35,5 @@ import java.lang.annotation.Target; @Inherited @Qualifier public @interface LoadBalanced { + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancedRecoveryCallback.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancedRecoveryCallback.java index 1427c657..6f5bd65a 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancedRecoveryCallback.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancedRecoveryCallback.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2012-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. @@ -13,18 +13,22 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.client.loadbalancer; +import java.net.URI; + import org.springframework.retry.RecoveryCallback; import org.springframework.retry.RetryContext; import org.springframework.retry.RetryException; -import java.net.URI; - /** - * An implementation of {@link RecoveryCallback} which relies on an implementation - * of {@link RetryableStatusCodeException} to contain the last response object from - * the request. + * An implementation of {@link RecoveryCallback} which relies on an implementation of + * {@link RetryableStatusCodeException} to contain the last response object from the + * request. + * + * @param - response type to return + * @param - response type from the HTTP client * @author LiYuan Lee */ public abstract class LoadBalancedRecoveryCallback implements RecoveryCallback { @@ -44,10 +48,12 @@ public abstract class LoadBalancedRecoveryCallback implements RecoveryCall if (lastThrowable instanceof RetryableStatusCodeException) { RetryableStatusCodeException ex = (RetryableStatusCodeException) lastThrowable; return createResponse((R) ex.getResponse(), ex.getUri()); - } else if (lastThrowable instanceof Exception){ - throw (Exception)lastThrowable; + } + else if (lastThrowable instanceof Exception) { + throw (Exception) lastThrowable; } } throw new RetryException("Could not recover", lastThrowable); } + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancedRetryContext.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancedRetryContext.java index 0ff06aa5..efd63c87 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancedRetryContext.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancedRetryContext.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2016 the original author or authors. + * Copyright 2012-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. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.client.loadbalancer; import org.springframework.cloud.client.ServiceInstance; @@ -22,52 +23,55 @@ import org.springframework.retry.context.RetryContextSupport; /** * {@link RetryContext} for load-balanced retries. + * * @author Ryan Baxter */ public class LoadBalancedRetryContext extends RetryContextSupport { - private HttpRequest request; - private ServiceInstance serviceInstance; + private HttpRequest request; - /** - * Creates a new load-balanced context. - * @param parent The parent context. - * @param request The request that is being load-balanced. - */ - public LoadBalancedRetryContext(RetryContext parent, HttpRequest request) { - super(parent); - this.request = request; - } + private ServiceInstance serviceInstance; - /** - * Gets the request that is being load-balanced. - * @return The request that is being load-balanced. - */ - public HttpRequest getRequest() { - return request; - } + /** + * Creates a new load-balanced context. + * @param parent The parent context. + * @param request The request that is being load-balanced. + */ + public LoadBalancedRetryContext(RetryContext parent, HttpRequest request) { + super(parent); + this.request = request; + } - /** - * Sets the request that is being load-balanced. - * @param request The request to be load balanced. - */ - public void setRequest(HttpRequest request) { - this.request = request; - } + /** + * Gets the request that is being load-balanced. + * @return The request that is being load-balanced. + */ + public HttpRequest getRequest() { + return this.request; + } - /** - * Gets the service instance used during the retry. - * @return The service instance used during the retry. - */ - public ServiceInstance getServiceInstance() { - return serviceInstance; - } + /** + * Sets the request that is being load-balanced. + * @param request The request to be load balanced. + */ + public void setRequest(HttpRequest request) { + this.request = request; + } + + /** + * Gets the service instance used during the retry. + * @return The service instance used during the retry. + */ + public ServiceInstance getServiceInstance() { + return this.serviceInstance; + } + + /** + * Sets the service instance to use during the retry. + * @param serviceInstance The service instance to use during the retry. + */ + public void setServiceInstance(ServiceInstance serviceInstance) { + this.serviceInstance = serviceInstance; + } - /** - * Sets the service instance to use during the retry. - * @param serviceInstance The service instance to use during the retry. - */ - public void setServiceInstance(ServiceInstance serviceInstance) { - this.serviceInstance = serviceInstance; - } } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancedRetryFactory.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancedRetryFactory.java index 87c86a04..a6a888b7 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancedRetryFactory.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancedRetryFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2012-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. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.client.loadbalancer; import org.springframework.retry.RetryListener; @@ -21,6 +22,7 @@ import org.springframework.retry.backoff.NoBackOffPolicy; /** * Factory class used to customize the retry functionality throughout Spring Cloud. + * * @author Ryan Baxter */ public interface LoadBalancedRetryFactory { @@ -31,7 +33,8 @@ public interface LoadBalancedRetryFactory { * @param serviceInstanceChooser Used to get the next server from a load balancer. * @return A retry policy for the service. */ - default LoadBalancedRetryPolicy createRetryPolicy(String service, ServiceInstanceChooser serviceInstanceChooser) { + default LoadBalancedRetryPolicy createRetryPolicy(String service, + ServiceInstanceChooser serviceInstanceChooser) { return null; } @@ -52,4 +55,5 @@ public interface LoadBalancedRetryFactory { default BackOffPolicy createBackOffPolicy(String service) { return new NoBackOffPolicy(); } + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancedRetryPolicy.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancedRetryPolicy.java index 7ec7726f..d4c9f063 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancedRetryPolicy.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancedRetryPolicy.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2016 the original author or authors. + * Copyright 2012-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. @@ -13,51 +13,56 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.client.loadbalancer; /** * Retry logic to use for the {@link LoadBalancerClient}. + * * @author Ryan Baxter */ public interface LoadBalancedRetryPolicy { - /** - * Return true to retry the failed request on the same server. - * This method may be called more than once when executing a single operation. - * @param context The context for the retry operation. - * @return True to retry the failed request on the same server; false otherwise. - */ - public boolean canRetrySameServer(LoadBalancedRetryContext context); + /** + * Return true to retry the failed request on the same server. This method may be + * called more than once when executing a single operation. + * @param context The context for the retry operation. + * @return True to retry the failed request on the same server; false otherwise. + */ + boolean canRetrySameServer(LoadBalancedRetryContext context); - /** - * Return true to retry the failed request on the next server from the load balancer. - * This method may be called more than once when executing a single operation. - * @param context The context for the retry operation. - * @return True to retry the failed request on the next server from the load balancer; false otherwise. - */ - public boolean canRetryNextServer(LoadBalancedRetryContext context); + /** + * Return true to retry the failed request on the next server from the load balancer. + * This method may be called more than once when executing a single operation. + * @param context The context for the retry operation. + * @return True to retry the failed request on the next server from the load balancer; + * false otherwise. + */ + boolean canRetryNextServer(LoadBalancedRetryContext context); - /** - * Called when the retry operation has ended. - * @param context The context for the retry operation. - */ - public abstract void close(LoadBalancedRetryContext context); + /** + * Called when the retry operation has ended. + * @param context The context for the retry operation. + */ + void close(LoadBalancedRetryContext context); - /** - * Called when the execution fails. - * @param context The context for the retry operation. - * @param throwable The throwable from the failed execution. - */ - public abstract void registerThrowable(LoadBalancedRetryContext context, Throwable throwable); + /** + * Called when the execution fails. + * @param context The context for the retry operation. + * @param throwable The throwable from the failed execution. + */ + void registerThrowable(LoadBalancedRetryContext context, Throwable throwable); + + /** + * If an exception is not thrown when making a request, this method will be called to + * see if the client would like to retry the request based on the status code + * returned. For example, in Cloud Foundry, the router will return a 404 + * when an app is not available. Since HTTP clients do not throw an exception when a + * 404 is returned, retryableStatusCode allows clients to + * force a retry. + * @param statusCode The HTTP status code. + * @return True if a retry should be attempted; false to just return the response. + */ + boolean retryableStatusCode(int statusCode); - /** - * If an exception is not thrown when making a request, this method will be called to see if the - * client would like to retry the request based on the status code returned. For example, in - * Cloud Foundry, the router will return a 404 when an app is not available. Since - * HTTP clients do not throw an exception when a 404 is returned, - * retryableStatusCode allows clients to force a retry. - * @param statusCode The HTTP status code. - * @return True if a retry should be attempted; false to just return the response. - */ - public boolean retryableStatusCode(int statusCode); } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancerAutoConfiguration.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancerAutoConfiguration.java index e74a6df1..f723e64a 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancerAutoConfiguration.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancerAutoConfiguration.java @@ -16,6 +16,10 @@ package org.springframework.cloud.client.loadbalancer; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.SmartInitializingSingleton; import org.springframework.beans.factory.annotation.Autowired; @@ -27,14 +31,9 @@ import org.springframework.boot.context.properties.EnableConfigurationProperties import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.client.ClientHttpRequestInterceptor; -import org.springframework.retry.backoff.BackOffPolicy; import org.springframework.retry.support.RetryTemplate; import org.springframework.web.client.RestTemplate; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - /** * Auto-configuration for Ribbon (client-side load balancing). * @@ -53,31 +52,32 @@ public class LoadBalancerAutoConfiguration { @Autowired(required = false) private List restTemplates = Collections.emptyList(); + @Autowired(required = false) + private List transformers = Collections.emptyList(); + @Bean public SmartInitializingSingleton loadBalancedRestTemplateInitializerDeprecated( final ObjectProvider> restTemplateCustomizers) { return () -> restTemplateCustomizers.ifAvailable(customizers -> { - for (RestTemplate restTemplate : LoadBalancerAutoConfiguration.this.restTemplates) { - for (RestTemplateCustomizer customizer : customizers) { - customizer.customize(restTemplate); - } - } - }); + for (RestTemplate restTemplate : LoadBalancerAutoConfiguration.this.restTemplates) { + for (RestTemplateCustomizer customizer : customizers) { + customizer.customize(restTemplate); + } + } + }); } - @Autowired(required = false) - private List transformers = Collections.emptyList(); - @Bean @ConditionalOnMissingBean public LoadBalancerRequestFactory loadBalancerRequestFactory( LoadBalancerClient loadBalancerClient) { - return new LoadBalancerRequestFactory(loadBalancerClient, transformers); + return new LoadBalancerRequestFactory(loadBalancerClient, this.transformers); } @Configuration @ConditionalOnMissingClass("org.springframework.retry.support.RetryTemplate") static class LoadBalancerInterceptorConfig { + @Bean public LoadBalancerInterceptor ribbonInterceptor( LoadBalancerClient loadBalancerClient, @@ -90,14 +90,18 @@ public class LoadBalancerAutoConfiguration { public RestTemplateCustomizer restTemplateCustomizer( final LoadBalancerInterceptor loadBalancerInterceptor) { return restTemplate -> { - List list = new ArrayList<>( - restTemplate.getInterceptors()); - list.add(loadBalancerInterceptor); - restTemplate.setInterceptors(list); - }; + List list = new ArrayList<>( + restTemplate.getInterceptors()); + list.add(loadBalancerInterceptor); + restTemplate.setInterceptors(list); + }; } + } + /** + * Auto configuration for retry mechanism. + */ @Configuration @ConditionalOnClass(RetryTemplate.class) public static class RetryAutoConfiguration { @@ -105,17 +109,24 @@ public class LoadBalancerAutoConfiguration { @Bean @ConditionalOnMissingBean public LoadBalancedRetryFactory loadBalancedRetryFactory() { - return new LoadBalancedRetryFactory() {}; + return new LoadBalancedRetryFactory() { + }; } + } + /** + * Auto configuration for retry intercepting mechanism. + */ @Configuration @ConditionalOnClass(RetryTemplate.class) public static class RetryInterceptorAutoConfiguration { + @Bean @ConditionalOnMissingBean public RetryLoadBalancerInterceptor ribbonInterceptor( - LoadBalancerClient loadBalancerClient, LoadBalancerRetryProperties properties, + LoadBalancerClient loadBalancerClient, + LoadBalancerRetryProperties properties, LoadBalancerRequestFactory requestFactory, LoadBalancedRetryFactory loadBalancedRetryFactory) { return new RetryLoadBalancerInterceptor(loadBalancerClient, properties, @@ -127,11 +138,13 @@ public class LoadBalancerAutoConfiguration { public RestTemplateCustomizer restTemplateCustomizer( final RetryLoadBalancerInterceptor loadBalancerInterceptor) { return restTemplate -> { - List list = new ArrayList<>( - restTemplate.getInterceptors()); - list.add(loadBalancerInterceptor); - restTemplate.setInterceptors(list); - }; + List list = new ArrayList<>( + restTemplate.getInterceptors()); + list.add(loadBalancerInterceptor); + restTemplate.setInterceptors(list); + }; } + } + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancerClient.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancerClient.java index 5b2913bd..9310e161 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancerClient.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancerClient.java @@ -16,13 +16,14 @@ package org.springframework.cloud.client.loadbalancer; -import org.springframework.cloud.client.ServiceInstance; - import java.io.IOException; import java.net.URI; +import org.springframework.cloud.client.ServiceInstance; + /** * Represents a client-side load balancer. + * * @author Spencer Gibb */ public interface LoadBalancerClient extends ServiceInstanceChooser { @@ -33,6 +34,8 @@ public interface LoadBalancerClient extends ServiceInstanceChooser { * @param serviceId The service ID to look up the LoadBalancer. * @param request Allows implementations to execute pre and post actions, such as * incrementing metrics. + * @param type of the response + * @throws IOException in case of IO issues. * @return The result of the LoadBalancerRequest callback on the selected * ServiceInstance. */ @@ -45,19 +48,23 @@ public interface LoadBalancerClient extends ServiceInstanceChooser { * @param serviceInstance The service to execute the request to. * @param request Allows implementations to execute pre and post actions, such as * incrementing metrics. + * @param type of the response + * @throws IOException in case of IO issues. * @return The result of the LoadBalancerRequest callback on the selected * ServiceInstance. */ - T execute(String serviceId, ServiceInstance serviceInstance, LoadBalancerRequest request) throws IOException; + T execute(String serviceId, ServiceInstance serviceInstance, + LoadBalancerRequest request) throws IOException; /** - * Creates a proper URI with a real host and port for systems to utilize. - * Some systems use a URI with the logical service name as the host, - * such as http://myservice/path/to/service. This will replace the - * service name with the host:port from the ServiceInstance. - * @param instance + * Creates a proper URI with a real host and port for systems to utilize. Some systems + * use a URI with the logical service name as the host, such as + * http://myservice/path/to/service. This will replace the service name with the + * host:port from the ServiceInstance. + * @param instance service instance to reconstruct the URI * @param original A URI with the host as a logical service name. * @return A reconstructed URI. */ URI reconstructURI(ServiceInstance instance, URI original); + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancerInterceptor.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancerInterceptor.java index 684b2309..5b1a54ff 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancerInterceptor.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancerInterceptor.java @@ -34,9 +34,11 @@ import org.springframework.util.Assert; public class LoadBalancerInterceptor implements ClientHttpRequestInterceptor { private LoadBalancerClient loadBalancer; + private LoadBalancerRequestFactory requestFactory; - public LoadBalancerInterceptor(LoadBalancerClient loadBalancer, LoadBalancerRequestFactory requestFactory) { + public LoadBalancerInterceptor(LoadBalancerClient loadBalancer, + LoadBalancerRequestFactory requestFactory) { this.loadBalancer = loadBalancer; this.requestFactory = requestFactory; } @@ -51,7 +53,10 @@ public class LoadBalancerInterceptor implements ClientHttpRequestInterceptor { final ClientHttpRequestExecution execution) throws IOException { final URI originalUri = request.getURI(); String serviceName = originalUri.getHost(); - Assert.state(serviceName != null, "Request URI does not contain a valid hostname: " + originalUri); - return this.loadBalancer.execute(serviceName, requestFactory.createRequest(request, body, execution)); + Assert.state(serviceName != null, + "Request URI does not contain a valid hostname: " + originalUri); + return this.loadBalancer.execute(serviceName, + this.requestFactory.createRequest(request, body, execution)); } + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancerRequest.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancerRequest.java index f085a450..84ba85fa 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancerRequest.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancerRequest.java @@ -19,12 +19,14 @@ package org.springframework.cloud.client.loadbalancer; import org.springframework.cloud.client.ServiceInstance; /** - * Simple interface used by LoadBalancerClient to apply metrics or pre and post - * actions around load balancer requests. + * Simple interface used by LoadBalancerClient to apply metrics or pre and post actions + * around load balancer requests. + * + * @param type of the response * @author Spencer Gibb */ public interface LoadBalancerRequest { - public T apply(ServiceInstance instance) throws Exception; + T apply(ServiceInstance instance) throws Exception; } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancerRequestFactory.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancerRequestFactory.java index c107b16b..1cf1cd2d 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancerRequestFactory.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancerRequestFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2017 the original author or authors. + * Copyright 2012-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. @@ -18,23 +18,22 @@ package org.springframework.cloud.client.loadbalancer; import java.util.List; -import org.springframework.cloud.client.ServiceInstance; import org.springframework.http.HttpRequest; import org.springframework.http.client.ClientHttpRequestExecution; import org.springframework.http.client.ClientHttpResponse; /** * Creates {@link LoadBalancerRequest}s for {@link LoadBalancerInterceptor} and - * {@link RetryLoadBalancerInterceptor}. Applies - * {@link LoadBalancerRequestTransformer}s to the intercepted - * {@link HttpRequest}. - * + * {@link RetryLoadBalancerInterceptor}. Applies {@link LoadBalancerRequestTransformer}s + * to the intercepted {@link HttpRequest}. + * * @author William Tran * */ public class LoadBalancerRequestFactory { private LoadBalancerClient loadBalancer; + private List transformers; public LoadBalancerRequestFactory(LoadBalancerClient loadBalancer, @@ -47,17 +46,20 @@ public class LoadBalancerRequestFactory { this.loadBalancer = loadBalancer; } - public LoadBalancerRequest createRequest(final HttpRequest request, - final byte[] body, final ClientHttpRequestExecution execution) { + public LoadBalancerRequest createRequest( + final HttpRequest request, final byte[] body, + final ClientHttpRequestExecution execution) { return instance -> { - HttpRequest serviceRequest = new ServiceRequestWrapper(request, instance, loadBalancer); - if (transformers != null) { - for (LoadBalancerRequestTransformer transformer : transformers) { - serviceRequest = transformer.transformRequest(serviceRequest, instance); - } - } - return execution.execute(serviceRequest, body); - }; + HttpRequest serviceRequest = new ServiceRequestWrapper(request, instance, + this.loadBalancer); + if (this.transformers != null) { + for (LoadBalancerRequestTransformer transformer : this.transformers) { + serviceRequest = transformer.transformRequest(serviceRequest, + instance); + } + } + return execution.execute(serviceRequest, body); + }; } } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancerRequestTransformer.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancerRequestTransformer.java index 27daf160..40245b4d 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancerRequestTransformer.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancerRequestTransformer.java @@ -1,5 +1,5 @@ /* - * Copyright 2017 the original author or authors. + * Copyright 2012-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. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.client.loadbalancer; import org.springframework.cloud.client.ServiceInstance; @@ -20,14 +21,19 @@ import org.springframework.core.annotation.Order; import org.springframework.http.HttpRequest; /** - * Allows applications to transform the load-balanced {@link HttpRequest} given - * the chosen {@link ServiceInstance}. - * + * Allows applications to transform the load-balanced {@link HttpRequest} given the chosen + * {@link ServiceInstance}. + * * @author Will Tran */ @Order(LoadBalancerRequestTransformer.DEFAULT_ORDER) public interface LoadBalancerRequestTransformer { - public static final int DEFAULT_ORDER = 0; + + /** + * Order for the load balancer request tranformer. + */ + int DEFAULT_ORDER = 0; HttpRequest transformRequest(HttpRequest request, ServiceInstance instance); + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancerRetryProperties.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancerRetryProperties.java index 9ee82b5d..fe56cfb3 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancerRetryProperties.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancerRetryProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2016 the original author or authors. + * Copyright 2012-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. @@ -13,31 +13,35 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.client.loadbalancer; import org.springframework.boot.context.properties.ConfigurationProperties; /** * Configuration properties for the {@link LoadBalancerClient}. + * * @author Ryan Baxter */ @ConfigurationProperties("spring.cloud.loadbalancer.retry") public class LoadBalancerRetryProperties { - private boolean enabled = true; - /** - * Returns true if the load balancer should retry failed requests. - * @return True if the load balancer should retry failed requests; false otherwise. - */ - public boolean isEnabled() { - return enabled; - } + private boolean enabled = true; + + /** + * Returns true if the load balancer should retry failed requests. + * @return True if the load balancer should retry failed requests; false otherwise. + */ + public boolean isEnabled() { + return this.enabled; + } + + /** + * Sets whether the load balancer should retry failed requests. + * @param enabled Whether the load balancer should retry failed requests. + */ + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } - /** - * Sets whether the load balancer should retry failed requests. - * @param enabled Whether the load balancer should retry failed requests. - */ - public void setEnabled(boolean enabled) { - this.enabled = enabled; - } } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/RestTemplateCustomizer.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/RestTemplateCustomizer.java index 8d92bc59..7c0773b6 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/RestTemplateCustomizer.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/RestTemplateCustomizer.java @@ -1,3 +1,19 @@ +/* + * Copyright 2013-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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.client.loadbalancer; import org.springframework.web.client.RestTemplate; @@ -6,5 +22,7 @@ import org.springframework.web.client.RestTemplate; * @author Spencer Gibb */ public interface RestTemplateCustomizer { + void customize(RestTemplate restTemplate); + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/RetryLoadBalancerInterceptor.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/RetryLoadBalancerInterceptor.java index 30b96bd1..5ace248e 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/RetryLoadBalancerInterceptor.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/RetryLoadBalancerInterceptor.java @@ -40,29 +40,33 @@ import org.springframework.util.StreamUtils; public class RetryLoadBalancerInterceptor implements ClientHttpRequestInterceptor { private LoadBalancerClient loadBalancer; + private LoadBalancerRetryProperties lbProperties; + private LoadBalancerRequestFactory requestFactory; + private LoadBalancedRetryFactory lbRetryFactory; public RetryLoadBalancerInterceptor(LoadBalancerClient loadBalancer, - LoadBalancerRetryProperties lbProperties, - LoadBalancerRequestFactory requestFactory, - LoadBalancedRetryFactory lbRetryFactory) { - this.loadBalancer = loadBalancer; - this.lbProperties = lbProperties; - this.requestFactory = requestFactory; - this.lbRetryFactory = lbRetryFactory; + LoadBalancerRetryProperties lbProperties, + LoadBalancerRequestFactory requestFactory, + LoadBalancedRetryFactory lbRetryFactory) { + this.loadBalancer = loadBalancer; + this.lbProperties = lbProperties; + this.requestFactory = requestFactory; + this.lbRetryFactory = lbRetryFactory; - } + } @Override public ClientHttpResponse intercept(final HttpRequest request, final byte[] body, - final ClientHttpRequestExecution execution) throws IOException { + final ClientHttpRequestExecution execution) throws IOException { final URI originalUri = request.getURI(); final String serviceName = originalUri.getHost(); - Assert.state(serviceName != null, "Request URI does not contain a valid hostname: " + originalUri); - final LoadBalancedRetryPolicy retryPolicy = lbRetryFactory.createRetryPolicy(serviceName, - loadBalancer); + Assert.state(serviceName != null, + "Request URI does not contain a valid hostname: " + originalUri); + final LoadBalancedRetryPolicy retryPolicy = this.lbRetryFactory + .createRetryPolicy(serviceName, this.loadBalancer); RetryTemplate template = createRetryTemplate(serviceName, request, retryPolicy); return template.execute(context -> { ServiceInstance serviceInstance = null; @@ -71,41 +75,48 @@ public class RetryLoadBalancerInterceptor implements ClientHttpRequestIntercepto serviceInstance = lbContext.getServiceInstance(); } if (serviceInstance == null) { - serviceInstance = loadBalancer.choose(serviceName); + serviceInstance = this.loadBalancer.choose(serviceName); } - ClientHttpResponse response = RetryLoadBalancerInterceptor.this.loadBalancer.execute( - serviceName, serviceInstance, - requestFactory.createRequest(request, body, execution)); + ClientHttpResponse response = RetryLoadBalancerInterceptor.this.loadBalancer + .execute(serviceName, serviceInstance, + this.requestFactory.createRequest(request, body, execution)); int statusCode = response.getRawStatusCode(); if (retryPolicy != null && retryPolicy.retryableStatusCode(statusCode)) { byte[] bodyCopy = StreamUtils.copyToByteArray(response.getBody()); response.close(); - throw new ClientHttpResponseStatusCodeException(serviceName, response, bodyCopy); + throw new ClientHttpResponseStatusCodeException(serviceName, response, + bodyCopy); } return response; }, new LoadBalancedRecoveryCallback() { - //This is a special case, where both parameters to LoadBalancedRecoveryCallback are - //the same. In most cases they would be different. + // This is a special case, where both parameters to + // LoadBalancedRecoveryCallback are + // the same. In most cases they would be different. @Override - protected ClientHttpResponse createResponse(ClientHttpResponse response, URI uri) { + protected ClientHttpResponse createResponse(ClientHttpResponse response, + URI uri) { return response; } }); } - private RetryTemplate createRetryTemplate(String serviceName, HttpRequest request, LoadBalancedRetryPolicy retryPolicy) { + private RetryTemplate createRetryTemplate(String serviceName, HttpRequest request, + LoadBalancedRetryPolicy retryPolicy) { RetryTemplate template = new RetryTemplate(); - BackOffPolicy backOffPolicy = lbRetryFactory.createBackOffPolicy(serviceName); - template.setBackOffPolicy(backOffPolicy == null ? new NoBackOffPolicy() : backOffPolicy); + BackOffPolicy backOffPolicy = this.lbRetryFactory + .createBackOffPolicy(serviceName); + template.setBackOffPolicy( + backOffPolicy == null ? new NoBackOffPolicy() : backOffPolicy); template.setThrowLastExceptionOnExhausted(true); - RetryListener[] retryListeners = lbRetryFactory.createRetryListeners(serviceName); + RetryListener[] retryListeners = this.lbRetryFactory + .createRetryListeners(serviceName); if (retryListeners != null && retryListeners.length != 0) { template.setListeners(retryListeners); } - template.setRetryPolicy( - !lbProperties.isEnabled() || retryPolicy == null ? new NeverRetryPolicy() - : new InterceptorRetryPolicy(request, retryPolicy, loadBalancer, - serviceName)); + template.setRetryPolicy(!this.lbProperties.isEnabled() || retryPolicy == null + ? new NeverRetryPolicy() : new InterceptorRetryPolicy(request, + retryPolicy, this.loadBalancer, serviceName)); return template; } + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/RetryableStatusCodeException.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/RetryableStatusCodeException.java index a2798c65..0a26fc15 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/RetryableStatusCodeException.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/RetryableStatusCodeException.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2018 the original author or authors. + * Copyright 2013-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. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.client.loadbalancer; import java.io.IOException; @@ -20,27 +21,30 @@ import java.net.URI; /** * Exception to be thrown when the status code is deemed to be retryable. + * * @author Ryan Baxter */ public class RetryableStatusCodeException extends IOException { private static final String MESSAGE = "Service %s returned a status code of %d"; - private Object response; + private final Object response; - private URI uri; + private final URI uri; - public RetryableStatusCodeException(String serviceId, int statusCode, Object response, URI uri) { + public RetryableStatusCodeException(String serviceId, int statusCode, Object response, + URI uri) { super(String.format(MESSAGE, serviceId, statusCode)); this.response = response; this.uri = uri; } public Object getResponse() { - return response; + return this.response; } public URI getUri() { - return uri; + return this.uri; } + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/ServiceInstanceChooser.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/ServiceInstanceChooser.java index 13710cda..d4a3006f 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/ServiceInstanceChooser.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/ServiceInstanceChooser.java @@ -19,17 +19,18 @@ package org.springframework.cloud.client.loadbalancer; import org.springframework.cloud.client.ServiceInstance; /** - * Implemented by classes which use a load balancer to choose a server to - * send a request to. + * Implemented by classes which use a load balancer to choose a server to send a request + * to. * * @author Ryan Baxter */ public interface ServiceInstanceChooser { - /** - * Chooses a ServiceInstance from the LoadBalancer for the specified service. - * @param serviceId The service ID to look up the LoadBalancer. - * @return A ServiceInstance that matches the serviceId. - */ - ServiceInstance choose(String serviceId); + /** + * Chooses a ServiceInstance from the LoadBalancer for the specified service. + * @param serviceId The service ID to look up the LoadBalancer. + * @return A ServiceInstance that matches the serviceId. + */ + ServiceInstance choose(String serviceId); + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/ServiceRequestWrapper.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/ServiceRequestWrapper.java index 37be07f5..9d951998 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/ServiceRequestWrapper.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/ServiceRequestWrapper.java @@ -1,3 +1,19 @@ +/* + * Copyright 2012-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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.client.loadbalancer; import java.net.URI; @@ -10,11 +26,13 @@ import org.springframework.http.client.support.HttpRequestWrapper; * @author Ryan Baxter */ public class ServiceRequestWrapper extends HttpRequestWrapper { + private final ServiceInstance instance; + private final LoadBalancerClient loadBalancer; public ServiceRequestWrapper(HttpRequest request, ServiceInstance instance, - LoadBalancerClient loadBalancer) { + LoadBalancerClient loadBalancer) { super(request); this.instance = instance; this.loadBalancer = loadBalancer; @@ -22,8 +40,8 @@ public class ServiceRequestWrapper extends HttpRequestWrapper { @Override public URI getURI() { - URI uri = this.loadBalancer.reconstructURI( - this.instance, getRequest().getURI()); + URI uri = this.loadBalancer.reconstructURI(this.instance, getRequest().getURI()); return uri; } + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/CompletionContext.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/CompletionContext.java index 23fa0899..3be4322f 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/CompletionContext.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/CompletionContext.java @@ -21,19 +21,11 @@ import org.springframework.core.style.ToStringCreator; /** * @author Spencer Gibb */ -//TODO: add metrics +// TODO: add metrics public class CompletionContext { - public enum Status { - /** Request was handled successfully */ - SUCCESSS, - /** Request reached the server but failed due to timeout or internal error */ - FAILED, - /** Request did not go off box and should not be counted for statistics */ - DISCARD, - } - private final Status status; + private final Throwable throwable; public CompletionContext(Status status) { @@ -46,19 +38,33 @@ public class CompletionContext { } public Status getStatus() { - return status; + return this.status; } public Throwable getThrowable() { - return throwable; + return this.throwable; } @Override public String toString() { ToStringCreator to = new ToStringCreator(this); - to.append("status", status); - to.append("throwable", throwable); + to.append("status", this.status); + to.append("throwable", this.throwable); return to.toString(); } + /** + * Request status state. + */ + public enum Status { + + /** Request was handled successfully. */ + SUCCESSS, + /** Request reached the server but failed due to timeout or internal error. */ + FAILED, + /** Request did not go off box and should not be counted for statistics. */ + DISCARD, + + } + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/DefaultResponse.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/DefaultResponse.java index 340a8d9e..b8d2439f 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/DefaultResponse.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/DefaultResponse.java @@ -41,6 +41,7 @@ public class DefaultResponse implements Response { @Override public void onComplete(CompletionContext completionContext) { - //TODO: implement + // TODO: implement } + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/EmptyResponse.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/EmptyResponse.java index ce5ea1ba..5821e36f 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/EmptyResponse.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/EmptyResponse.java @@ -35,6 +35,7 @@ public class EmptyResponse implements Response { @Override public void onComplete(CompletionContext completionContext) { - //TODO: implement + // TODO: implement } + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/LoadBalancerExchangeFilterFunction.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/LoadBalancerExchangeFilterFunction.java index db8f239b..bd026aa9 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/LoadBalancerExchangeFilterFunction.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/LoadBalancerExchangeFilterFunction.java @@ -1,9 +1,27 @@ +/* + * Copyright 2012-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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.client.loadbalancer.reactive; import java.net.URI; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import reactor.core.publisher.Mono; + import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.loadbalancer.LoadBalancerClient; import org.springframework.http.HttpStatus; @@ -12,8 +30,6 @@ import org.springframework.web.reactive.function.client.ClientResponse; import org.springframework.web.reactive.function.client.ExchangeFilterFunction; import org.springframework.web.reactive.function.client.ExchangeFunction; -import reactor.core.publisher.Mono; - /** * @author Spencer Gibb * @author Ryan Baxter @@ -33,25 +49,30 @@ public class LoadBalancerExchangeFilterFunction implements ExchangeFilterFunctio public Mono filter(ClientRequest request, ExchangeFunction next) { URI originalUrl = request.url(); String serviceId = originalUrl.getHost(); - if(serviceId == null) { - String msg = String.format("Request URI does not contain a valid hostname: %s", originalUrl.toString()); + if (serviceId == null) { + String msg = String.format( + "Request URI does not contain a valid hostname: %s", + originalUrl.toString()); logger.warn(msg); - return Mono.just(ClientResponse.create(HttpStatus.BAD_REQUEST).body(msg).build()); + return Mono.just( + ClientResponse.create(HttpStatus.BAD_REQUEST).body(msg).build()); } - //TODO: reactive lb client + // TODO: reactive lb client ServiceInstance instance = this.loadBalancerClient.choose(serviceId); - if(instance == null) { - String msg = String.format("Load balancer does not contain an instance for the service %s", serviceId); + if (instance == null) { + String msg = String.format( + "Load balancer does not contain an instance for the service %s", + serviceId); logger.warn(msg); - return Mono.just(ClientResponse.create(HttpStatus.SERVICE_UNAVAILABLE).body(msg).build()); + return Mono.just(ClientResponse.create(HttpStatus.SERVICE_UNAVAILABLE) + .body(msg).build()); } URI uri = this.loadBalancerClient.reconstructURI(instance, originalUrl); ClientRequest newRequest = ClientRequest.method(request.method(), uri) .headers(headers -> headers.addAll(request.headers())) .cookies(cookies -> cookies.addAll(request.cookies())) .attributes(attributes -> attributes.putAll(request.attributes())) - .body(request.body()) - .build(); + .body(request.body()).build(); return next.exchange(newRequest); } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/ReactiveLoadBalancer.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/ReactiveLoadBalancer.java index c3051856..61375a42 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/ReactiveLoadBalancer.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/ReactiveLoadBalancer.java @@ -19,20 +19,27 @@ package org.springframework.cloud.client.loadbalancer.reactive; import org.reactivestreams.Publisher; /** + * Reactive load balancer. + * + * @param type of the response * @author Spencer Gibb */ public interface ReactiveLoadBalancer { + /** + * Default implementation of a request. + */ Request REQUEST = new DefaultRequest(); /** - * Choose the next server based on the load balancing algorithm - * @param request - * @return + * Choose the next server based on the load balancing algorithm. + * @param request - incoming request + * @return publisher for the response */ Publisher> choose(Request request); - default Publisher> choose() { //conflicting name + default Publisher> choose() { // conflicting name return choose(REQUEST); } + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/ReactiveLoadBalancerAutoConfiguration.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/ReactiveLoadBalancerAutoConfiguration.java index be28a4a0..aeb5f1d3 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/ReactiveLoadBalancerAutoConfiguration.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/ReactiveLoadBalancerAutoConfiguration.java @@ -1,5 +1,24 @@ +/* + * Copyright 2012-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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.client.loadbalancer.reactive; +import java.util.Collections; +import java.util.List; + import org.springframework.beans.factory.SmartInitializingSingleton; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; @@ -10,9 +29,6 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.reactive.function.client.WebClient; -import java.util.Collections; -import java.util.List; - /** * @author Spencer Gibb */ @@ -26,7 +42,7 @@ public class ReactiveLoadBalancerAutoConfiguration { private List webClientBuilders = Collections.emptyList(); public List getBuilders() { - return webClientBuilders; + return this.webClientBuilders; } @Bean @@ -42,12 +58,15 @@ public class ReactiveLoadBalancerAutoConfiguration { } @Bean - public WebClientCustomizer loadbalanceClientWebClientCustomizer(LoadBalancerExchangeFilterFunction filterFunction) { + public WebClientCustomizer loadbalanceClientWebClientCustomizer( + LoadBalancerExchangeFilterFunction filterFunction) { return builder -> builder.filter(filterFunction); } @Bean - public LoadBalancerExchangeFilterFunction loadBalancerExchangeFilterFunction(LoadBalancerClient client) { + public LoadBalancerExchangeFilterFunction loadBalancerExchangeFilterFunction( + LoadBalancerClient client) { return new LoadBalancerExchangeFilterFunction(client); } + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/Request.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/Request.java index 309254af..ef4fe566 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/Request.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/Request.java @@ -1,5 +1,28 @@ +/* + * Copyright 2012-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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.client.loadbalancer.reactive; +/** + * Marker interface for a request. + * + * @author Spencer Gibb + */ public interface Request { - //TODO: define contents + + // TODO: define contents + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/Response.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/Response.java index 47c14ccc..ef2d6599 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/Response.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/Response.java @@ -1,16 +1,37 @@ +/* + * Copyright 2012-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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.client.loadbalancer.reactive; /** * Response created for each request. - */ + * + * @param type of the server + * @author Spencer Gibb + */ public interface Response { + boolean hasServer(); T getServer(); /** - * Notification that the request completed - * @param completionContext + * Notification that the request completed. + * @param completionContext - completion context */ void onComplete(CompletionContext completionContext); + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/WebClientCustomizer.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/WebClientCustomizer.java index 0bcb3083..ed026f41 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/WebClientCustomizer.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/WebClientCustomizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-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. @@ -23,7 +23,8 @@ import org.springframework.web.reactive.function.client.WebClient; * {@link org.springframework.web.reactive.function.client.WebClient.Builder * WebClient.Builder}. * - * See original {@link org.springframework.boot.web.reactive.function.client.WebClientCustomizer} + * See original + * {@link org.springframework.boot.web.reactive.function.client.WebClientCustomizer} * * @author Brian Clozel * @since 2.1.0 @@ -40,4 +41,3 @@ public interface WebClientCustomizer { void customize(WebClient.Builder webClientBuilder); } - diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/serviceregistry/AbstractAutoServiceRegistration.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/serviceregistry/AbstractAutoServiceRegistration.java index 9f7c8db0..b0fac704 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/serviceregistry/AbstractAutoServiceRegistration.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/serviceregistry/AbstractAutoServiceRegistration.java @@ -1,3 +1,19 @@ +/* + * Copyright 2012-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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.client.serviceregistry; import java.util.concurrent.atomic.AtomicBoolean; @@ -26,14 +42,17 @@ import org.springframework.core.env.Environment; * TODO: Document the lifecycle. * * @param Registration type passed to the {@link ServiceRegistry}. - * * @author Spencer Gibb */ public abstract class AbstractAutoServiceRegistration - implements AutoServiceRegistration, ApplicationContextAware, ApplicationListener { + implements AutoServiceRegistration, ApplicationContextAware, + ApplicationListener { + private static final Log logger = LogFactory .getLog(AbstractAutoServiceRegistration.class); + private final ServiceRegistry serviceRegistry; + private boolean autoStartup = true; private AtomicBoolean running = new AtomicBoolean(false); @@ -46,7 +65,6 @@ public abstract class AbstractAutoServiceRegistration private AtomicInteger port = new AtomicInteger(0); - private final ServiceRegistry serviceRegistry; private AutoServiceRegistrationProperties properties; @Deprecated @@ -54,13 +72,14 @@ public abstract class AbstractAutoServiceRegistration this.serviceRegistry = serviceRegistry; } - protected AbstractAutoServiceRegistration(ServiceRegistry serviceRegistry, AutoServiceRegistrationProperties properties) { + protected AbstractAutoServiceRegistration(ServiceRegistry serviceRegistry, + AutoServiceRegistrationProperties properties) { this.serviceRegistry = serviceRegistry; this.properties = properties; } protected ApplicationContext getContext() { - return context; + return this.context; } @Override @@ -73,8 +92,8 @@ public abstract class AbstractAutoServiceRegistration public void bind(WebServerInitializedEvent event) { ApplicationContext context = event.getApplicationContext(); if (context instanceof ConfigurableWebServerApplicationContext) { - if ("management".equals( - ((ConfigurableWebServerApplicationContext) context).getServerNamespace())) { + if ("management".equals(((ConfigurableWebServerApplicationContext) context) + .getServerNamespace())) { return; } } @@ -91,12 +110,12 @@ public abstract class AbstractAutoServiceRegistration @Deprecated protected Environment getEnvironment() { - return environment; + return this.environment; } @Deprecated protected AtomicInteger getPort() { - return port; + return this.port; } public boolean isAutoStartup() { @@ -114,7 +133,8 @@ public abstract class AbstractAutoServiceRegistration // only initialize if nonSecurePort is greater than 0 and it isn't already running // because of containerPortInitializer below if (!this.running.get()) { - this.context.publishEvent(new InstancePreRegisteredEvent(this, getRegistration())); + this.context.publishEvent( + new InstancePreRegisteredEvent(this, getRegistration())); register(); if (shouldRegisterManagement()) { registerManagement(); @@ -193,7 +213,7 @@ public abstract class AbstractAutoServiceRegistration } protected AtomicBoolean getRunning() { - return running; + return this.running; } public int getOrder() { @@ -255,4 +275,5 @@ public abstract class AbstractAutoServiceRegistration this.serviceRegistry.close(); } } + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/serviceregistry/AutoServiceRegistration.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/serviceregistry/AutoServiceRegistration.java index 3450804f..8b637e55 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/serviceregistry/AutoServiceRegistration.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/serviceregistry/AutoServiceRegistration.java @@ -1,7 +1,24 @@ +/* + * Copyright 2012-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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.client.serviceregistry; /** * @author Spencer Gibb */ public interface AutoServiceRegistration { + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/serviceregistry/AutoServiceRegistrationAutoConfiguration.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/serviceregistry/AutoServiceRegistrationAutoConfiguration.java index 88779d31..5ca4d71a 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/serviceregistry/AutoServiceRegistrationAutoConfiguration.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/serviceregistry/AutoServiceRegistrationAutoConfiguration.java @@ -1,3 +1,19 @@ +/* + * Copyright 2012-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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.client.serviceregistry; import javax.annotation.PostConstruct; @@ -23,8 +39,10 @@ public class AutoServiceRegistrationAutoConfiguration { @PostConstruct protected void init() { - if (autoServiceRegistration == null && this.properties.isFailFast()) { - throw new IllegalStateException("Auto Service Registration has been requested, but there is no AutoServiceRegistration bean"); + if (this.autoServiceRegistration == null && this.properties.isFailFast()) { + throw new IllegalStateException("Auto Service Registration has " + + "been requested, but there is no AutoServiceRegistration bean"); } } + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/serviceregistry/AutoServiceRegistrationConfiguration.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/serviceregistry/AutoServiceRegistrationConfiguration.java index c772069b..ef376946 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/serviceregistry/AutoServiceRegistrationConfiguration.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/serviceregistry/AutoServiceRegistrationConfiguration.java @@ -1,3 +1,19 @@ +/* + * Copyright 2012-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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.client.serviceregistry; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; @@ -11,4 +27,5 @@ import org.springframework.context.annotation.Configuration; @EnableConfigurationProperties(AutoServiceRegistrationProperties.class) @ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled", matchIfMissing = true) public class AutoServiceRegistrationConfiguration { + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/serviceregistry/AutoServiceRegistrationProperties.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/serviceregistry/AutoServiceRegistrationProperties.java index 695e8cc4..c77c4093 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/serviceregistry/AutoServiceRegistrationProperties.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/serviceregistry/AutoServiceRegistrationProperties.java @@ -1,3 +1,19 @@ +/* + * Copyright 2012-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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.client.serviceregistry; import org.springframework.boot.context.properties.ConfigurationProperties; @@ -14,11 +30,13 @@ public class AutoServiceRegistrationProperties { /** Whether to register the management as a service. Defaults to true. */ private boolean registerManagement = true; - /** Whether startup fails if there is no AutoServiceRegistration. Defaults to false. */ + /** + * Whether startup fails if there is no AutoServiceRegistration. Defaults to false. + */ private boolean failFast = false; public boolean isEnabled() { - return enabled; + return this.enabled; } public void setEnabled(boolean enabled) { @@ -26,23 +44,24 @@ public class AutoServiceRegistrationProperties { } public boolean isRegisterManagement() { - return registerManagement; - } - - @Deprecated - public boolean shouldRegisterManagement() { - return registerManagement; + return this.registerManagement; } public void setRegisterManagement(boolean registerManagement) { this.registerManagement = registerManagement; } + @Deprecated + public boolean shouldRegisterManagement() { + return this.registerManagement; + } + public boolean isFailFast() { - return failFast; + return this.failFast; } public void setFailFast(boolean failFast) { this.failFast = failFast; } + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/serviceregistry/Registration.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/serviceregistry/Registration.java index c1068011..842c291e 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/serviceregistry/Registration.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/serviceregistry/Registration.java @@ -1,3 +1,19 @@ +/* + * Copyright 2012-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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.client.serviceregistry; import org.springframework.cloud.client.ServiceInstance; @@ -9,4 +25,5 @@ import org.springframework.cloud.client.ServiceInstance; * @since 1.2.0 */ public interface Registration extends ServiceInstance { + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/serviceregistry/ServiceRegistry.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/serviceregistry/ServiceRegistry.java index 3641d1ae..e8b33186 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/serviceregistry/ServiceRegistry.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/serviceregistry/ServiceRegistry.java @@ -1,23 +1,40 @@ +/* + * Copyright 2012-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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.client.serviceregistry; /** * Contract to register and deregister instances with a Service Registry. * + * @param registration meta data * @author Spencer Gibb * @since 1.2.0 */ public interface ServiceRegistry { /** - * Registers the registration. A registration typically has information about - * an instance, such as its hostname and port. - * @param registration The registration. + * Registers the registration. A registration typically has information about an + * instance, such as its hostname and port. + * @param registration registration meta data */ void register(R registration); /** * Deregisters the registration. - * @param registration + * @param registration registration meta data */ void deregister(R registration); @@ -27,22 +44,21 @@ public interface ServiceRegistry { void close(); /** - * Sets the status of the registration. The status values are determined - * by the individual implementations. - * - * @see org.springframework.cloud.client.serviceregistry.endpoint.ServiceRegistryEndpoint + * Sets the status of the registration. The status values are determined by the + * individual implementations. * @param registration The registration to update. * @param status The status to set. + * @see org.springframework.cloud.client.serviceregistry.endpoint.ServiceRegistryEndpoint */ void setStatus(R registration, String status); /** * Gets the status of a particular registration. - * - * @see org.springframework.cloud.client.serviceregistry.endpoint.ServiceRegistryEndpoint * @param registration The registration to query. * @param The type of the status. * @return The status of the registration. + * @see org.springframework.cloud.client.serviceregistry.endpoint.ServiceRegistryEndpoint */ T getStatus(R registration); + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/serviceregistry/ServiceRegistryAutoConfiguration.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/serviceregistry/ServiceRegistryAutoConfiguration.java index a34edd73..0b424ac3 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/serviceregistry/ServiceRegistryAutoConfiguration.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/serviceregistry/ServiceRegistryAutoConfiguration.java @@ -1,3 +1,19 @@ +/* + * Copyright 2012-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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.client.serviceregistry; import org.springframework.beans.factory.annotation.Autowired; @@ -18,15 +34,20 @@ public class ServiceRegistryAutoConfiguration { @ConditionalOnBean(ServiceRegistry.class) @ConditionalOnClass(Endpoint.class) protected class ServiceRegistryEndpointConfiguration { + @Autowired(required = false) private Registration registration; @Bean @ConditionalOnEnabledEndpoint - public ServiceRegistryEndpoint serviceRegistryEndpoint(ServiceRegistry serviceRegistry) { - ServiceRegistryEndpoint endpoint = new ServiceRegistryEndpoint(serviceRegistry); - endpoint.setRegistration(registration); + public ServiceRegistryEndpoint serviceRegistryEndpoint( + ServiceRegistry serviceRegistry) { + ServiceRegistryEndpoint endpoint = new ServiceRegistryEndpoint( + serviceRegistry); + endpoint.setRegistration(this.registration); return endpoint; } + } + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/serviceregistry/endpoint/ServiceRegistryEndpoint.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/serviceregistry/endpoint/ServiceRegistryEndpoint.java index 07f48502..ca42c743 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/serviceregistry/endpoint/ServiceRegistryEndpoint.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/serviceregistry/endpoint/ServiceRegistryEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2016 the original author or authors. + * Copyright 2012-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. @@ -12,7 +12,6 @@ * WITHOUT 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.client.serviceregistry.endpoint; @@ -52,7 +51,8 @@ public class ServiceRegistryEndpoint { Assert.notNull(status, "status may not by null"); if (this.registration == null) { - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("no registration found"); + return ResponseEntity.status(HttpStatus.NOT_FOUND) + .body("no registration found"); } this.serviceRegistry.setStatus(this.registration, status); @@ -62,10 +62,12 @@ public class ServiceRegistryEndpoint { @ReadOperation public ResponseEntity getStatus() { if (this.registration == null) { - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("no registration found"); + return ResponseEntity.status(HttpStatus.NOT_FOUND) + .body("no registration found"); } - return ResponseEntity.ok().body(this.serviceRegistry.getStatus(this.registration)); + return ResponseEntity.ok() + .body(this.serviceRegistry.getStatus(this.registration)); } } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/httpclient/ApacheHttpClientConnectionManagerFactory.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/httpclient/ApacheHttpClientConnectionManagerFactory.java index 803e3ed8..236c9ef5 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/httpclient/ApacheHttpClientConnectionManagerFactory.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/httpclient/ApacheHttpClientConnectionManagerFactory.java @@ -1,19 +1,17 @@ /* + * Copyright 2012-2019 the original author or authors. * - * * Copyright 2013-2016 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 - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an "AS IS" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.commons.httpclient; @@ -25,11 +23,20 @@ import org.apache.http.conn.HttpClientConnectionManager; /** * Interface for creating an {@link HttpClientConnectionManager}. + * * @author Ryan Baxter */ public interface ApacheHttpClientConnectionManagerFactory { - public static final String HTTP_SCHEME = "http"; - public static final String HTTPS_SCHEME = "https"; + + /** + * Scheme for HTTP based communication. + */ + String HTTP_SCHEME = "http"; + + /** + * Scheme for HTTPS based communication. + */ + String HTTPS_SCHEME = "https"; /** * Creates a new {@link HttpClientConnectionManager}. @@ -38,10 +45,12 @@ public interface ApacheHttpClientConnectionManagerFactory { * @param maxConnectionsPerRoute The total number of connections per route. * @param timeToLive The time a connection is allowed to exist. * @param timeUnit The time unit for the time-to-live value. - * @param registryBuilder The {@link RegistryBuilder} to use in the connection manager. + * @param registryBuilder The {@link RegistryBuilder} to use in the connection + * manager. * @return A new {@link HttpClientConnectionManager}. */ - public HttpClientConnectionManager newConnectionManager(boolean disableSslValidation, + HttpClientConnectionManager newConnectionManager(boolean disableSslValidation, int maxTotalConnections, int maxConnectionsPerRoute, long timeToLive, TimeUnit timeUnit, RegistryBuilder registryBuilder); + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/httpclient/ApacheHttpClientFactory.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/httpclient/ApacheHttpClientFactory.java index e2bb3e4f..10efd771 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/httpclient/ApacheHttpClientFactory.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/httpclient/ApacheHttpClientFactory.java @@ -1,19 +1,17 @@ /* + * Copyright 2012-2019 the original author or authors. * - * * Copyright 2013-2016 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 - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an "AS IS" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.commons.httpclient; @@ -23,13 +21,16 @@ import org.apache.http.impl.client.HttpClientBuilder; /** * Factory for creating a new {@link CloseableHttpClient}. + * * @author Ryan Baxter */ public interface ApacheHttpClientFactory { /** - * Creates an {@link HttpClientBuilder} that can be used to create a new {@link CloseableHttpClient}. + * Creates an {@link HttpClientBuilder} that can be used to create a new + * {@link CloseableHttpClient}. * @return A {@link HttpClientBuilder}. */ - public HttpClientBuilder createBuilder(); + HttpClientBuilder createBuilder(); + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/httpclient/DefaultApacheHttpClientConnectionManagerFactory.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/httpclient/DefaultApacheHttpClientConnectionManagerFactory.java index 6ade938a..9630ce64 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/httpclient/DefaultApacheHttpClientConnectionManagerFactory.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/httpclient/DefaultApacheHttpClientConnectionManagerFactory.java @@ -1,3 +1,19 @@ +/* + * Copyright 2012-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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.commons.httpclient; import java.security.KeyManagementException; @@ -6,9 +22,12 @@ import java.security.SecureRandom; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.concurrent.TimeUnit; + import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; + +import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.config.Registry; import org.apache.http.config.RegistryBuilder; @@ -18,10 +37,10 @@ import org.apache.http.conn.socket.PlainConnectionSocketFactory; import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.apache.commons.logging.Log; /** * Default implementation of {@link ApacheHttpClientConnectionManagerFactory}. + * * @author Ryan Baxter * @author Michael Wirth */ @@ -42,17 +61,17 @@ public class DefaultApacheHttpClientConnectionManagerFactory int maxTotalConnections, int maxConnectionsPerRoute, long timeToLive, TimeUnit timeUnit, RegistryBuilder registryBuilder) { if (registryBuilder == null) { - registryBuilder = RegistryBuilder. create() + registryBuilder = RegistryBuilder.create() .register(HTTP_SCHEME, PlainConnectionSocketFactory.INSTANCE); } if (disableSslValidation) { try { final SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, - new TrustManager[] { new DisabledValidationTrustManager()}, - new SecureRandom()); + new TrustManager[] { new DisabledValidationTrustManager() }, + new SecureRandom()); registryBuilder.register(HTTPS_SCHEME, new SSLConnectionSocketFactory( - sslContext, NoopHostnameVerifier.INSTANCE)); + sslContext, NoopHostnameVerifier.INSTANCE)); } catch (NoSuchAlgorithmException e) { LOG.warn("Error creating SSLContext", e); @@ -60,8 +79,10 @@ public class DefaultApacheHttpClientConnectionManagerFactory catch (KeyManagementException e) { LOG.warn("Error creating SSLContext", e); } - } else { - registryBuilder.register("https", SSLConnectionSocketFactory.getSocketFactory()); + } + else { + registryBuilder.register("https", + SSLConnectionSocketFactory.getSocketFactory()); } final Registry registry = registryBuilder.build(); @@ -74,19 +95,22 @@ public class DefaultApacheHttpClientConnectionManagerFactory } class DisabledValidationTrustManager implements X509TrustManager { + @Override - public void checkClientTrusted(X509Certificate[] x509Certificates, - String s) throws CertificateException { + public void checkClientTrusted(X509Certificate[] x509Certificates, String s) + throws CertificateException { } @Override - public void checkServerTrusted(X509Certificate[] x509Certificates, - String s) throws CertificateException { + public void checkServerTrusted(X509Certificate[] x509Certificates, String s) + throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return null; } + } + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/httpclient/DefaultApacheHttpClientFactory.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/httpclient/DefaultApacheHttpClientFactory.java index a42a711d..791aaf85 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/httpclient/DefaultApacheHttpClientFactory.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/httpclient/DefaultApacheHttpClientFactory.java @@ -1,9 +1,26 @@ +/* + * Copyright 2012-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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.commons.httpclient; import org.apache.http.impl.client.HttpClientBuilder; /** * Default implementation of {@link ApacheHttpClientFactory}. + * * @author Ryan Baxter */ public class DefaultApacheHttpClientFactory implements ApacheHttpClientFactory { @@ -17,11 +34,12 @@ public class DefaultApacheHttpClientFactory implements ApacheHttpClientFactory { /** * A default {@link HttpClientBuilder}. The {@link HttpClientBuilder} returned will * have content compression disabled, have cookie management disabled, and use system - * properties. + * properties. */ @Override public HttpClientBuilder createBuilder() { - return this.builder.disableContentCompression() - .disableCookieManagement().useSystemProperties(); + return this.builder.disableContentCompression().disableCookieManagement() + .useSystemProperties(); } + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/httpclient/DefaultOkHttpClientConnectionPoolFactory.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/httpclient/DefaultOkHttpClientConnectionPoolFactory.java index 9c09dfcc..7f418bd4 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/httpclient/DefaultOkHttpClientConnectionPoolFactory.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/httpclient/DefaultOkHttpClientConnectionPoolFactory.java @@ -1,17 +1,37 @@ -package org.springframework.cloud.commons.httpclient; +/* + * Copyright 2012-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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ -import okhttp3.ConnectionPool; +package org.springframework.cloud.commons.httpclient; import java.util.concurrent.TimeUnit; +import okhttp3.ConnectionPool; + /** * Default implementation of {@link OkHttpClientConnectionPoolFactory}. + * * @author Ryan Baxter */ -public class DefaultOkHttpClientConnectionPoolFactory implements OkHttpClientConnectionPoolFactory { +public class DefaultOkHttpClientConnectionPoolFactory + implements OkHttpClientConnectionPoolFactory { @Override - public ConnectionPool create(int maxIdleConnections, long keepAliveDuration, TimeUnit timeUnit) { + public ConnectionPool create(int maxIdleConnections, long keepAliveDuration, + TimeUnit timeUnit) { return new ConnectionPool(maxIdleConnections, keepAliveDuration, timeUnit); } + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/httpclient/DefaultOkHttpClientFactory.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/httpclient/DefaultOkHttpClientFactory.java index a30234e2..574945fe 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/httpclient/DefaultOkHttpClientFactory.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/httpclient/DefaultOkHttpClientFactory.java @@ -1,18 +1,36 @@ -package org.springframework.cloud.commons.httpclient; +/* + * Copyright 2012-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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ -import okhttp3.OkHttpClient; +package org.springframework.cloud.commons.httpclient; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; + import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; + +import okhttp3.OkHttpClient; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Default implementation of {@link OkHttpClientFactory}. + * * @author Ryan Baxter */ public class DefaultOkHttpClientFactory implements OkHttpClientFactory { @@ -35,8 +53,9 @@ public class DefaultOkHttpClientFactory implements OkHttpClientFactory { SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, trustManagers, new java.security.SecureRandom()); SSLSocketFactory disabledSSLSocketFactory = sslContext.getSocketFactory(); - builder.sslSocketFactory(disabledSSLSocketFactory, disabledTrustManager); - builder.hostnameVerifier(new TrustAllHostnames()); + this.builder.sslSocketFactory(disabledSSLSocketFactory, + disabledTrustManager); + this.builder.hostnameVerifier(new TrustAllHostnames()); } catch (NoSuchAlgorithmException e) { LOG.warn("Error setting SSLSocketFactory in OKHttpClient", e); @@ -45,6 +64,7 @@ public class DefaultOkHttpClientFactory implements OkHttpClientFactory { LOG.warn("Error setting SSLSocketFactory in OKHttpClient", e); } } - return builder; + return this.builder; } + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/httpclient/HttpClientConfiguration.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/httpclient/HttpClientConfiguration.java index 3160203d..71803795 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/httpclient/HttpClientConfiguration.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/httpclient/HttpClientConfiguration.java @@ -1,9 +1,25 @@ +/* + * Copyright 2012-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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.commons.httpclient; import okhttp3.OkHttpClient; - import org.apache.http.client.HttpClient; import org.apache.http.impl.client.HttpClientBuilder; + import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; @@ -35,9 +51,11 @@ public class HttpClientConfiguration { @Bean @ConditionalOnMissingBean - public ApacheHttpClientFactory apacheHttpClientFactory(HttpClientBuilder builder) { + public ApacheHttpClientFactory apacheHttpClientFactory( + HttpClientBuilder builder) { return new DefaultApacheHttpClientFactory(builder); } + } @Configuration @@ -62,5 +80,7 @@ public class HttpClientConfiguration { public OkHttpClientFactory okHttpClientFactory(OkHttpClient.Builder builder) { return new DefaultOkHttpClientFactory(builder); } + } + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/httpclient/OkHttpClientConnectionPoolFactory.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/httpclient/OkHttpClientConnectionPoolFactory.java index 922e7c1d..b7a18f1c 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/httpclient/OkHttpClientConnectionPoolFactory.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/httpclient/OkHttpClientConnectionPoolFactory.java @@ -1,11 +1,28 @@ -package org.springframework.cloud.commons.httpclient; +/* + * Copyright 2012-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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ -import okhttp3.ConnectionPool; +package org.springframework.cloud.commons.httpclient; import java.util.concurrent.TimeUnit; +import okhttp3.ConnectionPool; + /** * Creates {@link ConnectionPool}s for {@link okhttp3.OkHttpClient}s. + * * @author Ryan Baxter */ public interface OkHttpClientConnectionPoolFactory { @@ -17,5 +34,7 @@ public interface OkHttpClientConnectionPoolFactory { * @param timeUnit The time unit for the keep-alive duration. * @return A new {@link ConnectionPool}. */ - public ConnectionPool create(int maxIdleConnections, long keepAliveDuration, TimeUnit timeUnit); + ConnectionPool create(int maxIdleConnections, long keepAliveDuration, + TimeUnit timeUnit); + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/httpclient/OkHttpClientFactory.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/httpclient/OkHttpClientFactory.java index 25652393..0bc852c1 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/httpclient/OkHttpClientFactory.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/httpclient/OkHttpClientFactory.java @@ -1,15 +1,33 @@ -package org.springframework.cloud.commons.httpclient; +/* + * Copyright 2012-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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ -import okhttp3.OkHttpClient; +package org.springframework.cloud.commons.httpclient; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; + import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLSession; import javax.net.ssl.X509TrustManager; +import okhttp3.OkHttpClient; + /** * Creates new {@link OkHttpClient}s. + * * @author Ryan Baxter */ public interface OkHttpClientFactory { @@ -19,33 +37,40 @@ public interface OkHttpClientFactory { * @param disableSslValidation Disables SSL validation * @return A new {@link OkHttpClient.Builder} */ - public OkHttpClient.Builder createBuilder(boolean disableSslValidation); + OkHttpClient.Builder createBuilder(boolean disableSslValidation); /** * A {@link X509TrustManager} that does not validate SSL certificates. */ - public static class DisableValidationTrustManager implements X509TrustManager { + class DisableValidationTrustManager implements X509TrustManager { @Override - public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {} + public void checkClientTrusted(X509Certificate[] x509Certificates, String s) + throws CertificateException { + } @Override - public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {} + public void checkServerTrusted(X509Certificate[] x509Certificates, String s) + throws CertificateException { + } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } + } /** * A {@link HostnameVerifier} that does not validate any hostnames. */ - public static class TrustAllHostnames implements HostnameVerifier { + class TrustAllHostnames implements HostnameVerifier { @Override public boolean verify(String s, SSLSession sslSession) { return true; } + } + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/util/IdUtils.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/util/IdUtils.java index dd8751ee..18d789f6 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/util/IdUtils.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/util/IdUtils.java @@ -1,3 +1,19 @@ +/* + * Copyright 2012-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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.commons.util; import org.springframework.core.env.PropertyResolver; @@ -6,15 +22,20 @@ import org.springframework.util.StringUtils; /** * @author Spencer Gibb */ -public class IdUtils { +public final class IdUtils { private static final String SEPARATOR = ":"; - public static String getDefaultInstanceId(PropertyResolver resolver) { - return getDefaultInstanceId(resolver, true); - } + private IdUtils() { + throw new IllegalStateException("Can't instantiate a utility class"); + } - public static String getDefaultInstanceId(PropertyResolver resolver, boolean includeHostname) { + public static String getDefaultInstanceId(PropertyResolver resolver) { + return getDefaultInstanceId(resolver, true); + } + + public static String getDefaultInstanceId(PropertyResolver resolver, + boolean includeHostname) { String vcapInstanceId = resolver.getProperty("vcap.application.instance_id"); if (StringUtils.hasText(vcapInstanceId)) { return vcapInstanceId; @@ -34,13 +55,16 @@ public class IdUtils { return combineParts(namePart, SEPARATOR, indexPart); } - public static String combineParts(String firstPart, String separator, String secondPart) { + public static String combineParts(String firstPart, String separator, + String secondPart) { String combined = null; if (firstPart != null && secondPart != null) { combined = firstPart + separator + secondPart; - } else if (firstPart != null) { + } + else if (firstPart != null) { combined = firstPart; - } else if (secondPart != null) { + } + else if (secondPart != null) { combined = secondPart; } return combined; diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/util/InetUtils.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/util/InetUtils.java index f35f450d..5ca01d55 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/util/InetUtils.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/util/InetUtils.java @@ -25,11 +25,9 @@ import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.util.Enumeration; import java.util.List; -import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; -import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import org.apache.commons.logging.Log; @@ -42,24 +40,24 @@ public class InetUtils implements Closeable { // TODO: maybe shutdown the thread pool if it isn't being used? private final ExecutorService executorService; + private final InetUtilsProperties properties; private final Log log = LogFactory.getLog(InetUtils.class); - + public InetUtils(final InetUtilsProperties properties) { this.properties = properties; - this.executorService = Executors - .newSingleThreadExecutor(r -> { - Thread thread = new Thread(r); - thread.setName(InetUtilsProperties.PREFIX); - thread.setDaemon(true); - return thread; - }); + this.executorService = Executors.newSingleThreadExecutor(r -> { + Thread thread = new Thread(r); + thread.setName(InetUtilsProperties.PREFIX); + thread.setDaemon(true); + return thread; + }); } @Override public void close() { - executorService.shutdown(); + this.executorService.shutdown(); } public HostInfo findFirstNonLoopbackHostInfo() { @@ -81,7 +79,7 @@ public class InetUtils implements Closeable { .getNetworkInterfaces(); nics.hasMoreElements();) { NetworkInterface ifc = nics.nextElement(); if (ifc.isUp()) { - log.trace("Testing interface: " + ifc.getDisplayName()); + this.log.trace("Testing interface: " + ifc.getDisplayName()); if (ifc.getIndex() < lowest || result == null) { lowest = ifc.getIndex(); } @@ -97,7 +95,7 @@ public class InetUtils implements Closeable { if (address instanceof Inet4Address && !address.isLoopbackAddress() && isPreferredAddress(address)) { - log.trace("Found non-loopback interface: " + this.log.trace("Found non-loopback interface: " + ifc.getDisplayName()); result = address; } @@ -108,7 +106,7 @@ public class InetUtils implements Closeable { } } catch (IOException ex) { - log.error("Cannot get first non-loopback address", ex); + this.log.error("Cannot get first non-loopback address", ex); } if (result != null) { @@ -119,18 +117,19 @@ public class InetUtils implements Closeable { return InetAddress.getLocalHost(); } catch (UnknownHostException e) { - log.warn("Unable to retrieve localhost"); + this.log.warn("Unable to retrieve localhost"); } return null; } - /** For testing. */ boolean isPreferredAddress(InetAddress address) { + // For testing. + boolean isPreferredAddress(InetAddress address) { if (this.properties.isUseOnlySiteLocalInterfaces()) { final boolean siteLocalAddress = address.isSiteLocalAddress(); if (!siteLocalAddress) { - log.trace("Ignoring address: " + address.getHostAddress()); + this.log.trace("Ignoring address: " + address.getHostAddress()); } return siteLocalAddress; } @@ -144,14 +143,15 @@ public class InetUtils implements Closeable { return true; } } - log.trace("Ignoring address: " + address.getHostAddress()); + this.log.trace("Ignoring address: " + address.getHostAddress()); return false; } - /** For testing. */ boolean ignoreInterface(String interfaceName) { + // For testing + boolean ignoreInterface(String interfaceName) { for (String regex : this.properties.getIgnoredInterfaces()) { if (interfaceName.matches(regex)) { - log.trace("Ignoring interface: " + interfaceName); + this.log.trace("Ignoring interface: " + interfaceName); return true; } } @@ -160,14 +160,14 @@ public class InetUtils implements Closeable { public HostInfo convertAddress(final InetAddress address) { HostInfo hostInfo = new HostInfo(); - Future result = executorService.submit(address::getHostName); + Future result = this.executorService.submit(address::getHostName); String hostname; try { hostname = result.get(this.properties.getTimeoutSeconds(), TimeUnit.SECONDS); } catch (Exception e) { - log.info("Cannot determine local hostname"); + this.log.info("Cannot determine local hostname"); hostname = "localhost"; } hostInfo.setHostname(hostname); @@ -175,9 +175,18 @@ public class InetUtils implements Closeable { return hostInfo; } + /** + * Host information pojo. + */ public static class HostInfo { + + /** + * Should override the host info. + */ public boolean override; + private String ipAddress; + private String hostname; public HostInfo(String hostname) { @@ -203,7 +212,7 @@ public class InetUtils implements Closeable { } public boolean isOverride() { - return override; + return this.override; } public void setOverride(boolean override) { @@ -211,7 +220,7 @@ public class InetUtils implements Closeable { } public String getIpAddress() { - return ipAddress; + return this.ipAddress; } public void setIpAddress(String ipAddress) { @@ -219,12 +228,13 @@ public class InetUtils implements Closeable { } public String getHostname() { - return hostname; + return this.hostname; } public void setHostname(String hostname) { this.hostname = hostname; } + } } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/util/InetUtilsProperties.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/util/InetUtilsProperties.java index aa0ca157..3982d76b 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/util/InetUtilsProperties.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/util/InetUtilsProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2017 the original author or authors. + * Copyright 2012-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. @@ -24,10 +24,16 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.properties.ConfigurationProperties; /** + * Properties for {@link InetUtils}. + * * @author Spencer Gibb */ @ConfigurationProperties(InetUtilsProperties.PREFIX) public class InetUtilsProperties { + + /** + * Prefix for the Inet Utils properties. + */ public static final String PREFIX = "spring.cloud.inetutils"; /** @@ -50,13 +56,13 @@ public class InetUtilsProperties { * List of Java regular expressions for network interfaces that will be ignored. */ private List ignoredInterfaces = new ArrayList<>(); - + /** - * Whether to use only interfaces with site local addresses. - * See {@link InetAddress#isSiteLocalAddress()} for more details. + * Whether to use only interfaces with site local addresses. See + * {@link InetAddress#isSiteLocalAddress()} for more details. */ private boolean useOnlySiteLocalInterfaces = false; - + /** * List of Java regular expressions for network addresses that will be preferred. */ @@ -67,7 +73,7 @@ public class InetUtilsProperties { } public String getDefaultHostname() { - return defaultHostname; + return this.defaultHostname; } public void setDefaultHostname(String defaultHostname) { @@ -75,7 +81,7 @@ public class InetUtilsProperties { } public String getDefaultIpAddress() { - return defaultIpAddress; + return this.defaultIpAddress; } public void setDefaultIpAddress(String defaultIpAddress) { @@ -83,7 +89,7 @@ public class InetUtilsProperties { } public int getTimeoutSeconds() { - return timeoutSeconds; + return this.timeoutSeconds; } public void setTimeoutSeconds(int timeoutSeconds) { @@ -91,7 +97,7 @@ public class InetUtilsProperties { } public List getIgnoredInterfaces() { - return ignoredInterfaces; + return this.ignoredInterfaces; } public void setIgnoredInterfaces(List ignoredInterfaces) { @@ -99,7 +105,7 @@ public class InetUtilsProperties { } public boolean isUseOnlySiteLocalInterfaces() { - return useOnlySiteLocalInterfaces; + return this.useOnlySiteLocalInterfaces; } public void setUseOnlySiteLocalInterfaces(boolean useOnlySiteLocalInterfaces) { @@ -107,10 +113,11 @@ public class InetUtilsProperties { } public List getPreferredNetworks() { - return preferredNetworks; + return this.preferredNetworks; } public void setPreferredNetworks(List preferredNetworks) { this.preferredNetworks = preferredNetworks; } + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/util/SpringFactoryImportSelector.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/util/SpringFactoryImportSelector.java index dcb887e8..cbf1040e 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/util/SpringFactoryImportSelector.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/util/SpringFactoryImportSelector.java @@ -22,6 +22,7 @@ import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + import org.springframework.beans.factory.BeanClassLoaderAware; import org.springframework.context.EnvironmentAware; import org.springframework.context.annotation.DeferredImportSelector; @@ -32,25 +33,25 @@ import org.springframework.core.io.support.SpringFactoriesLoader; import org.springframework.core.type.AnnotationMetadata; import org.springframework.util.Assert; - /** * Selects configurations to load, defined by the generic type T. Loads implementations * using {@link SpringFactoriesLoader}. * + * @param type of annotation class * @author Spencer Gibb * @author Dave Syer */ public abstract class SpringFactoryImportSelector implements DeferredImportSelector, BeanClassLoaderAware, EnvironmentAware { + private final Log log = LogFactory.getLog(SpringFactoryImportSelector.class); + private ClassLoader beanClassLoader; private Class annotationClass; private Environment environment; - private final Log log = LogFactory.getLog(SpringFactoryImportSelector.class); - @SuppressWarnings("unchecked") protected SpringFactoryImportSelector() { this.annotationClass = (Class) GenericTypeResolver @@ -80,7 +81,7 @@ public abstract class SpringFactoryImportSelector if (factories.size() > 1) { // there should only ever be one DiscoveryClient, but there might be more than // one factory - log.warn("More than one implementation " + "of @" + getSimpleName() + this.log.warn("More than one implementation " + "of @" + getSimpleName() + " (now relying on @Conditionals to pick one): " + factories); } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/util/UtilAutoConfiguration.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/util/UtilAutoConfiguration.java index 4532d875..f6712101 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/util/UtilAutoConfiguration.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/util/UtilAutoConfiguration.java @@ -1,3 +1,19 @@ +/* + * Copyright 2012-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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.commons.util; import org.springframework.boot.autoconfigure.AutoConfigureOrder; @@ -26,4 +42,5 @@ public class UtilAutoConfiguration { public InetUtils inetUtils(InetUtilsProperties properties) { return new InetUtils(properties); } + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/configuration/CompatibilityNotMetException.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/configuration/CompatibilityNotMetException.java index 6be61a3f..808afdf0 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/configuration/CompatibilityNotMetException.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/configuration/CompatibilityNotMetException.java @@ -1,29 +1,35 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2012-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. You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on - * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ + package org.springframework.cloud.configuration; import java.util.List; /** - * Exception thrown when the current setup is not compatible + * Exception thrown when the current setup is not compatible. * * @author Marcin Grzejszczak * @since 1.3.6 */ class CompatibilityNotMetException extends RuntimeException { + final List results; CompatibilityNotMetException(List results) { this.results = results; } + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/configuration/CompatibilityNotMetFailureAnalyzer.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/configuration/CompatibilityNotMetFailureAnalyzer.java index c4703e99..4ea78e46 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/configuration/CompatibilityNotMetFailureAnalyzer.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/configuration/CompatibilityNotMetFailureAnalyzer.java @@ -1,3 +1,19 @@ +/* + * Copyright 2012-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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.configuration; import java.util.List; @@ -6,21 +22,24 @@ import org.springframework.boot.diagnostics.AbstractFailureAnalyzer; import org.springframework.boot.diagnostics.FailureAnalysis; /** - * Analyzer for the {@link CompatibilityNotMetException}. Prints a list of found - * issues and actions that should be taken to fix them. + * Analyzer for the {@link CompatibilityNotMetException}. Prints a list of found issues + * and actions that should be taken to fix them. * * @author Marcin Grzejszczak * @since 1.3.6 */ -public final class CompatibilityNotMetFailureAnalyzer extends AbstractFailureAnalyzer { +public final class CompatibilityNotMetFailureAnalyzer + extends AbstractFailureAnalyzer { + @Override - protected FailureAnalysis analyze(Throwable rootFailure, CompatibilityNotMetException cause) { + protected FailureAnalysis analyze(Throwable rootFailure, + CompatibilityNotMetException cause) { return new FailureAnalysis(getDescription(cause), getAction(cause), cause); } private String getDescription(CompatibilityNotMetException ex) { return String.format("Your project setup is incompatible with our requirements " - + "due to following reasons:%s", descriptions(ex.results)); + + "due to following reasons:%s", descriptions(ex.results)); } private String descriptions(List results) { @@ -43,4 +62,5 @@ public final class CompatibilityNotMetFailureAnalyzer extends AbstractFailureAna } return builder.toString(); } + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/configuration/CompatibilityPredicate.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/configuration/CompatibilityPredicate.java index 5e564ed7..d180f5c3 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/configuration/CompatibilityPredicate.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/configuration/CompatibilityPredicate.java @@ -1,21 +1,28 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2012-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. You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on - * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ + package org.springframework.cloud.configuration; /** - * So that can be used for jdk 7 - otherwise we would use a predicate + * So that can be used for jdk 7 - otherwise we would use a predicate. + * * @author Marcin Grzejszczak */ interface CompatibilityPredicate { + boolean isCompatible(); + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/configuration/CompatibilityVerifier.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/configuration/CompatibilityVerifier.java index c6ae7b60..95e290f2 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/configuration/CompatibilityVerifier.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/configuration/CompatibilityVerifier.java @@ -1,24 +1,30 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2012-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. You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on - * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ + package org.springframework.cloud.configuration; /** - * Implementations will verify the compatibility and return a result that - * says whether the check is compatible or not for the current release train + * Implementations will verify the compatibility and return a result that says whether the + * check is compatible or not for the current release train. * * @author Marcin Grzejszczak * @since 1.3.6 */ interface CompatibilityVerifier { + VerificationResult verify(); + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/configuration/CompatibilityVerifierAutoConfiguration.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/configuration/CompatibilityVerifierAutoConfiguration.java index c31916d4..27553221 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/configuration/CompatibilityVerifierAutoConfiguration.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/configuration/CompatibilityVerifierAutoConfiguration.java @@ -1,15 +1,19 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2012-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. You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on - * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ + package org.springframework.cloud.configuration; import java.util.List; @@ -21,10 +25,9 @@ import org.springframework.boot.context.properties.EnableConfigurationProperties import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; - /** - * {@link EnableAutoConfiguration Auto-configuration} that fails the build fast for incompatible - * versions of dependencies (e.g. invalid version of Boot). + * {@link EnableAutoConfiguration Auto-configuration} that fails the build fast for + * incompatible versions of dependencies (e.g. invalid version of Boot). * * @author Marcin Grzejszczak * @since 1.3.6 @@ -36,8 +39,10 @@ import org.springframework.context.annotation.Configuration; public class CompatibilityVerifierAutoConfiguration { @Bean - CompositeCompatibilityVerifier compositeCompatibilityVerifier(List verifiers) { - CompositeCompatibilityVerifier verifier = new CompositeCompatibilityVerifier(verifiers); + CompositeCompatibilityVerifier compositeCompatibilityVerifier( + List verifiers) { + CompositeCompatibilityVerifier verifier = new CompositeCompatibilityVerifier( + verifiers); verifier.verifyDependencies(); return verifier; } @@ -49,4 +54,3 @@ public class CompatibilityVerifierAutoConfiguration { } } - diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/configuration/CompatibilityVerifierProperties.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/configuration/CompatibilityVerifierProperties.java index f1a55404..5087fbd3 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/configuration/CompatibilityVerifierProperties.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/configuration/CompatibilityVerifierProperties.java @@ -1,15 +1,19 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2012-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. You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on - * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ + package org.springframework.cloud.configuration; import java.util.Collections; @@ -29,9 +33,9 @@ public class CompatibilityVerifierProperties { private boolean enabled; /** - * Default accepted versions for the Spring Boot dependency. You can set {@code x} - * for the patch version if you don't want to specify a concrete value. - * Example: {@code 3.4.x} + * Default accepted versions for the Spring Boot dependency. You can set {@code x} for + * the patch version if you don't want to specify a concrete value. Example: + * {@code 3.4.x} */ private List compatibleBootVersions = Collections.singletonList("2.1.x"); @@ -50,4 +54,5 @@ public class CompatibilityVerifierProperties { public void setCompatibleBootVersions(List compatibleBootVersions) { this.compatibleBootVersions = compatibleBootVersions; } + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/configuration/CompositeCompatibilityVerifier.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/configuration/CompositeCompatibilityVerifier.java index 7a01fc6c..a046a07e 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/configuration/CompositeCompatibilityVerifier.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/configuration/CompositeCompatibilityVerifier.java @@ -1,15 +1,19 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2012-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. You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on - * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ + package org.springframework.cloud.configuration; import java.util.ArrayList; @@ -19,11 +23,13 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** - * Iterates over {@link CompatibilityVerifier} and prepares a report if exceptions were found + * Iterates over {@link CompatibilityVerifier} and prepares a report if exceptions were + * found. */ class CompositeCompatibilityVerifier { - private static final Log log = LogFactory.getLog(CompositeCompatibilityVerifier.class); + private static final Log log = LogFactory + .getLog(CompositeCompatibilityVerifier.class); private final List verifiers; @@ -52,4 +58,5 @@ class CompositeCompatibilityVerifier { } return errors; } + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/configuration/SpringBootVersionVerifier.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/configuration/SpringBootVersionVerifier.java index 38e46989..02854a78 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/configuration/SpringBootVersionVerifier.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/configuration/SpringBootVersionVerifier.java @@ -1,15 +1,19 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2012-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. You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on - * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ + package org.springframework.cloud.configuration; import java.util.HashMap; @@ -24,7 +28,7 @@ import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.util.StringUtils; /** - * Verifies if Spring Boot has proper version + * Verifies if Spring Boot has proper version. */ class SpringBootVersionVerifier implements CompatibilityVerifier { @@ -65,7 +69,8 @@ class SpringBootVersionVerifier implements CompatibilityVerifier { public boolean isCompatible() { try { // deprecated 1.5 - Class.forName("org.springframework.boot.context.config.ResourceNotFoundException"); + Class.forName( + "org.springframework.boot.context.config.ResourceNotFoundException"); return true; } catch (ClassNotFoundException e) { @@ -128,7 +133,6 @@ class SpringBootVersionVerifier implements CompatibilityVerifier { return false; } - } }; } @@ -136,29 +140,33 @@ class SpringBootVersionVerifier implements CompatibilityVerifier { private String errorDescription() { String versionFromManifest = getVersionFromManifest(); if (StringUtils.hasText(versionFromManifest)) { - return String.format("Spring Boot [%s] is not compatible with this Spring Cloud release train", versionFromManifest); + return String.format( + "Spring Boot [%s] is not compatible with this Spring Cloud release train", + versionFromManifest); } return "Spring Boot is not compatible with this Spring Cloud release train"; } private String action() { - return String.format("Change Spring Boot version to one of the following versions %s .\n" + return String.format( + "Change Spring Boot version to one of the following versions %s .\n" + "You can find the latest Spring Boot versions here [%s]. \n" + "If you want to learn more about the Spring Cloud Release train compatibility, you " + "can visit this page [%s] and check the [Release Trains] section.\n" + "If you want to disable this check, just set the property [spring.cloud.compatibility-verifier.enabled=false]", - this.acceptedVersions, "https://spring.io/projects/spring-boot#learn", "https://spring.io/projects/spring-cloud#overview"); + this.acceptedVersions, "https://spring.io/projects/spring-boot#learn", + "https://spring.io/projects/spring-cloud#overview"); } private boolean springBootVersionMatches() { - for (String acceptedVersion : acceptedVersions) { + for (String acceptedVersion : this.acceptedVersions) { if (bootVersionFromManifest(acceptedVersion)) { return true; } else { // 2.0, 2.1 - CompatibilityPredicate predicate = ACCEPTED_VERSIONS.get( - acceptedVersionWithoutX(acceptedVersion)); + CompatibilityPredicate predicate = this.ACCEPTED_VERSIONS + .get(acceptedVersionWithoutX(acceptedVersion)); if (predicate != null && predicate.isCompatible()) { if (log.isDebugEnabled()) { log.debug("Predicate [" + predicate + "] was matched"); @@ -176,4 +184,5 @@ class SpringBootVersionVerifier implements CompatibilityVerifier { } return acceptedVersion; } + } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/configuration/VerificationResult.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/configuration/VerificationResult.java index e3b53b3d..706f5a21 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/configuration/VerificationResult.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/configuration/VerificationResult.java @@ -1,15 +1,19 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2012-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. You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on - * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ + package org.springframework.cloud.configuration; import org.springframework.util.StringUtils; @@ -17,8 +21,10 @@ import org.springframework.util.StringUtils; /** * @author Marcin Grzejszczak */ -class VerificationResult { +final class VerificationResult { + final String description; + final String action; // if OK diff --git a/spring-cloud-commons/src/main/resources/META-INF/additional-spring-configuration-metadata.json b/spring-cloud-commons/src/main/resources/META-INF/additional-spring-configuration-metadata.json index bce10121..dd3b1a41 100644 --- a/spring-cloud-commons/src/main/resources/META-INF/additional-spring-configuration-metadata.json +++ b/spring-cloud-commons/src/main/resources/META-INF/additional-spring-configuration-metadata.json @@ -1,52 +1,52 @@ { - "properties": [ - { - "defaultValue": "true", - "name": "spring.cloud.refresh.enabled", - "description": "Enables autoconfiguration for the refresh scope and associated features.", - "type": "java.lang.Boolean" - }, - { - "defaultValue": true, - "name": "spring.cloud.httpclientfactories.apache.enabled", - "description": "Enables creation of Apache Http Client factory beans.", - "type": "java.lang.Boolean" - }, - { - "defaultValue": "true", - "name": "spring.cloud.httpclientfactories.ok.enabled", - "description": "Enables creation of OK Http Client factory beans.", - "type": "java.lang.Boolean" - }, - { - "defaultValue": true, - "name": "spring.cloud.util.enabled", - "description": "Enables creation of Spring Cloud utility beans.", - "type": "java.lang.Boolean" - }, - { - "defaultValue": true, - "name": "spring.cloud.features.enabled", - "description": "Enables the features endpoint.", - "type": "java.lang.Boolean" - }, - { - "defaultValue": true, - "name": "spring.cloud.discovery.enabled", - "description": "Enables discovery client health indicators.", - "type": "java.lang.Boolean" - }, - { - "defaultValue": true, - "name": "spring.cloud.discovery.client.composite-indicator.enabled", - "description": "Enables discovery client composite health indicator.", - "type": "java.lang.Boolean" - }, - { - "defaultValue": true, - "name": "management.endpoint.env.post.enabled", - "description": "Enables writable environment endpoint.", - "type": "java.lang.Boolean" - } - ] -} \ No newline at end of file + "properties": [ + { + "defaultValue": "true", + "name": "spring.cloud.refresh.enabled", + "description": "Enables autoconfiguration for the refresh scope and associated features.", + "type": "java.lang.Boolean" + }, + { + "defaultValue": true, + "name": "spring.cloud.httpclientfactories.apache.enabled", + "description": "Enables creation of Apache Http Client factory beans.", + "type": "java.lang.Boolean" + }, + { + "defaultValue": "true", + "name": "spring.cloud.httpclientfactories.ok.enabled", + "description": "Enables creation of OK Http Client factory beans.", + "type": "java.lang.Boolean" + }, + { + "defaultValue": true, + "name": "spring.cloud.util.enabled", + "description": "Enables creation of Spring Cloud utility beans.", + "type": "java.lang.Boolean" + }, + { + "defaultValue": true, + "name": "spring.cloud.features.enabled", + "description": "Enables the features endpoint.", + "type": "java.lang.Boolean" + }, + { + "defaultValue": true, + "name": "spring.cloud.discovery.enabled", + "description": "Enables discovery client health indicators.", + "type": "java.lang.Boolean" + }, + { + "defaultValue": true, + "name": "spring.cloud.discovery.client.composite-indicator.enabled", + "description": "Enables discovery client composite health indicator.", + "type": "java.lang.Boolean" + }, + { + "defaultValue": true, + "name": "management.endpoint.env.post.enabled", + "description": "Enables writable environment endpoint.", + "type": "java.lang.Boolean" + } + ] +} diff --git a/spring-cloud-commons/src/main/resources/META-INF/spring.factories b/spring-cloud-commons/src/main/resources/META-INF/spring.factories index 4b22aa70..a72ba300 100644 --- a/spring-cloud-commons/src/main/resources/META-INF/spring.factories +++ b/spring-cloud-commons/src/main/resources/META-INF/spring.factories @@ -13,12 +13,9 @@ org.springframework.cloud.commons.httpclient.HttpClientConfiguration,\ org.springframework.cloud.commons.util.UtilAutoConfiguration,\ org.springframework.cloud.configuration.CompatibilityVerifierAutoConfiguration,\ org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationAutoConfiguration - - # Environment Post Processors org.springframework.boot.env.EnvironmentPostProcessor=\ org.springframework.cloud.client.HostInfoEnvironmentPostProcessor - # Failure Analyzers org.springframework.boot.diagnostics.FailureAnalyzer=\ org.springframework.cloud.configuration.CompatibilityNotMetFailureAnalyzer \ No newline at end of file diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/AdhocTestSuite.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/AdhocTestSuite.java index 95ead569..40184994 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/AdhocTestSuite.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/AdhocTestSuite.java @@ -20,6 +20,7 @@ import org.junit.Ignore; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; + import org.springframework.cloud.client.discovery.EnableDiscoveryClientMissingImplTests; import org.springframework.cloud.client.hypermedia.CloudHypermediaAutoConfigurationIntegrationTests; diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/CommonsClientAutoConfigurationTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/CommonsClientAutoConfigurationTests.java index c390a3c2..870cd91a 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/CommonsClientAutoConfigurationTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/CommonsClientAutoConfigurationTests.java @@ -1,6 +1,7 @@ package org.springframework.cloud.client; import org.junit.Test; + import org.springframework.beans.BeansException; import org.springframework.boot.WebApplicationType; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; @@ -41,10 +42,16 @@ public class CommonsClientAutoConfigurationTests { @Test public void disableAll() { - try (ConfigurableApplicationContext ctxt = init("spring.cloud.discovery.enabled=false")) { + try (ConfigurableApplicationContext ctxt = init( + "spring.cloud.discovery.enabled=false")) { assertBeanNonExistant(ctxt, DiscoveryClientHealthIndicator.class); assertBeanNonExistant(ctxt, DiscoveryCompositeHealthIndicator.class); - assertThat(ctxt.getBean(FeaturesEndpoint.class), is(notNullValue())); // features actuator is independent of discovery + assertThat(ctxt.getBean(FeaturesEndpoint.class), is(notNullValue())); // features + // actuator + // is + // independent + // of + // discovery assertBeanNonExistant(ctxt, HasFeatures.class); } } @@ -82,13 +89,15 @@ public class CommonsClientAutoConfigurationTests { } protected ConfigurableApplicationContext init(String... pairs) { - return new SpringApplicationBuilder().web(WebApplicationType.NONE).sources(Config.class) - .properties(pairs).run(); + return new SpringApplicationBuilder().web(WebApplicationType.NONE) + .sources(Config.class).properties(pairs).run(); } @Configuration @EnableAutoConfiguration @Import(NoopDiscoveryClientAutoConfiguration.class) protected static class Config { + } + } diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/HostInfoEnvironmentPostProcessorTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/HostInfoEnvironmentPostProcessorTests.java index 6ebd7cae..9b5ee38b 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/HostInfoEnvironmentPostProcessorTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/HostInfoEnvironmentPostProcessorTests.java @@ -17,6 +17,7 @@ package org.springframework.cloud.client; import org.junit.Test; + import org.springframework.boot.SpringApplication; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.StandardEnvironment; @@ -29,19 +30,18 @@ import static org.junit.Assert.assertNotNull; public class HostInfoEnvironmentPostProcessorTests { private HostInfoEnvironmentPostProcessor processor = new HostInfoEnvironmentPostProcessor(); + private ConfigurableEnvironment environment = new StandardEnvironment(); @Test public void hostname() { - this.processor.postProcessEnvironment(this.environment, - new SpringApplication()); + this.processor.postProcessEnvironment(this.environment, new SpringApplication()); assertNotNull(this.environment.getProperty("spring.cloud.client.hostname")); } @Test public void ipAddress() { - this.processor.postProcessEnvironment(this.environment, - new SpringApplication()); + this.processor.postProcessEnvironment(this.environment, new SpringApplication()); String address = this.environment.getProperty("spring.cloud.client.ip-address"); assertNotNull(address); } diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/actuator/FeaturesEndpointTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/actuator/FeaturesEndpointTests.java index d151df81..1c99921e 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/actuator/FeaturesEndpointTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/actuator/FeaturesEndpointTests.java @@ -6,6 +6,7 @@ import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration; import org.springframework.boot.context.properties.EnableConfigurationProperties; @@ -15,7 +16,6 @@ import org.springframework.context.annotation.Configuration; import static org.assertj.core.api.Assertions.assertThat; - /** * @author Spencer Gibb */ @@ -43,8 +43,8 @@ public class FeaturesEndpointTests { FeaturesEndpoint.Features features = this.context.getBean(FeaturesEndpoint.class) .features(); assertThat(features).isNotNull(); - assertThat(features.getEnabled()).hasSize(2) - .contains(newFeature("foo", Foo.class), newFeature("Baz Feature", Baz.class)); + assertThat(features.getEnabled()).hasSize(2).contains( + newFeature("foo", Foo.class), newFeature("Baz Feature", Baz.class)); assertThat(features.getDisabled()).hasSize(1).contains("Bar"); } @@ -54,6 +54,7 @@ public class FeaturesEndpointTests { @Configuration public static class FeaturesConfig { + @Bean Foo foo() { return new Foo(); @@ -73,6 +74,7 @@ public class FeaturesEndpointTests { @Configuration @EnableConfigurationProperties public static class Config { + @Autowired(required = false) private List hasFeatures = new ArrayList<>(); @@ -80,14 +82,19 @@ public class FeaturesEndpointTests { public FeaturesEndpoint cloudEndpoint() { return new FeaturesEndpoint(this.hasFeatures); } + } public static class Foo { + } public static class Bar { + } public static class Baz { + } + } diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/AutoRegisterPropertyFalseTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/AutoRegisterPropertyFalseTests.java index 35c57634..dec344be 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/AutoRegisterPropertyFalseTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/AutoRegisterPropertyFalseTests.java @@ -2,6 +2,7 @@ package org.springframework.cloud.client.discovery; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; @@ -19,8 +20,10 @@ import static org.junit.Assert.assertNull; * @author Ryan Baxter */ @RunWith(SpringRunner.class) -@SpringBootTest(properties = {"spring.cloud.service-registry.auto-registration.enabled: false"}) +@SpringBootTest(properties = { + "spring.cloud.service-registry.auto-registration.enabled: false" }) public class AutoRegisterPropertyFalseTests { + @Autowired(required = false) AutoServiceRegistrationAutoConfiguration autoConfiguration; @@ -35,15 +38,16 @@ public class AutoRegisterPropertyFalseTests { @Test public void veryifyBeans() { - assertNull(autoConfiguration); - assertNull(autoServiceRegistration); - assertNull(autoServiceRegistrationProperties); - assertFalse(autoRegisterProperty); + assertNull(this.autoConfiguration); + assertNull(this.autoServiceRegistration); + assertNull(this.autoServiceRegistrationProperties); + assertFalse(this.autoRegisterProperty); } - @EnableAutoConfiguration @Configuration public static class App { + } + } diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/EnableDiscoveryClientAutoRegisterFalseTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/EnableDiscoveryClientAutoRegisterFalseTests.java index 906be22c..149eee17 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/EnableDiscoveryClientAutoRegisterFalseTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/EnableDiscoveryClientAutoRegisterFalseTests.java @@ -2,6 +2,7 @@ package org.springframework.cloud.client.discovery; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; @@ -36,16 +37,17 @@ public class EnableDiscoveryClientAutoRegisterFalseTests { @Test public void veryifyBeans() { - assertNull(autoConfiguration); - assertNull(autoServiceRegistration); - assertNull(autoServiceRegistrationProperties); - assertFalse(autoRegisterProperty); + assertNull(this.autoConfiguration); + assertNull(this.autoServiceRegistration); + assertNull(this.autoServiceRegistrationProperties); + assertFalse(this.autoRegisterProperty); } - @EnableAutoConfiguration @Configuration @EnableDiscoveryClient(autoRegister = false) public static class App { + } + } diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/EnableDiscoveryClientImportSelectorTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/EnableDiscoveryClientImportSelectorTests.java index 6c2e360c..e2deba4b 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/EnableDiscoveryClientImportSelectorTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/EnableDiscoveryClientImportSelectorTests.java @@ -4,6 +4,7 @@ import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; + import org.springframework.core.annotation.AnnotationAttributes; import org.springframework.core.type.AnnotationMetadata; import org.springframework.mock.env.MockEnvironment; @@ -39,7 +40,9 @@ public class EnableDiscoveryClientImportSelectorTests { public void autoRegistrationIsEnabled() { configureAnnotation(true); String[] imports = this.importSelector.selectImports(this.annotationMetadata); - assertTrue(environment.getProperty("spring.cloud.service-registry.auto-registration.enabled", Boolean.class, true)); + assertTrue(this.environment.getProperty( + "spring.cloud.service-registry.auto-registration.enabled", Boolean.class, + true)); assertThat(imports).hasSize(1); } @@ -47,7 +50,9 @@ public class EnableDiscoveryClientImportSelectorTests { public void autoRegistrationIsDisabled() { configureAnnotation(false); String[] imports = this.importSelector.selectImports(this.annotationMetadata); - assertFalse(environment.getProperty("spring.cloud.service-registry.auto-registration.enabled", Boolean.class)); + assertFalse(this.environment.getProperty( + "spring.cloud.service-registry.auto-registration.enabled", + Boolean.class)); assertThat(imports).isEmpty(); } @@ -59,4 +64,5 @@ public class EnableDiscoveryClientImportSelectorTests { given(this.annotationAttributes.getBoolean("autoRegister")) .willReturn(autoRegistration); } + } diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/EnableDiscoveryClientMissingImplTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/EnableDiscoveryClientMissingImplTests.java index 7bfb1796..e1a0c60f 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/EnableDiscoveryClientMissingImplTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/EnableDiscoveryClientMissingImplTests.java @@ -1,6 +1,7 @@ package org.springframework.cloud.client.discovery; import org.junit.Test; + import org.springframework.boot.WebApplicationType; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.builder.SpringApplicationBuilder; @@ -13,6 +14,7 @@ import static org.junit.Assert.assertTrue; /** * Tests that if @EnableDiscoveryClient is used, but there is no * implementation on the classpath, then fail + * * @author Spencer Gibb */ public class EnableDiscoveryClientMissingImplTests { @@ -35,5 +37,7 @@ public class EnableDiscoveryClientMissingImplTests { // this will fail with @EnableDiscoveryClient and no implementation (nothing in // spring.factories) public static class App { + } + } diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/ManagementServerPortUtilsTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/ManagementServerPortUtilsTests.java index e4a0b7a8..ae81c40f 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/ManagementServerPortUtilsTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/ManagementServerPortUtilsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-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,5 +44,8 @@ public class ManagementServerPortUtilsTests { @SpringBootConfiguration @EnableAutoConfiguration - protected static class TestApp {} -} \ No newline at end of file + protected static class TestApp { + + } + +} diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/composite/CompositeDiscoveryClientAutoConfigurationTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/composite/CompositeDiscoveryClientAutoConfigurationTests.java index 4832c33f..b6172230 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/composite/CompositeDiscoveryClientAutoConfigurationTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/composite/CompositeDiscoveryClientAutoConfigurationTests.java @@ -1,7 +1,10 @@ package org.springframework.cloud.client.discovery.composite; +import java.util.List; + import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; @@ -12,13 +15,11 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.junit4.SpringRunner; -import java.util.List; - import static org.assertj.core.api.Assertions.assertThat; /** * Composite Discovery Client should be the one found by default. - * + * * @author Biju Kunjummen */ @@ -31,8 +32,8 @@ public class CompositeDiscoveryClientAutoConfigurationTests { @Test public void compositeDiscoveryClientShouldBeTheDefault() { - assertThat(discoveryClient).isInstanceOf(CompositeDiscoveryClient.class); - CompositeDiscoveryClient compositeDiscoveryClient = (CompositeDiscoveryClient) discoveryClient; + assertThat(this.discoveryClient).isInstanceOf(CompositeDiscoveryClient.class); + CompositeDiscoveryClient compositeDiscoveryClient = (CompositeDiscoveryClient) this.discoveryClient; assertThat(compositeDiscoveryClient.getDiscoveryClients()).hasSize(2); assertThat(compositeDiscoveryClient.getDiscoveryClients().get(0).description()) .isEqualTo("A custom discovery client"); @@ -40,7 +41,7 @@ public class CompositeDiscoveryClientAutoConfigurationTests { @Test public void simpleDiscoveryClientShouldBeHaveTheLowestPrecedence() { - CompositeDiscoveryClient compositeDiscoveryClient = (CompositeDiscoveryClient) discoveryClient; + CompositeDiscoveryClient compositeDiscoveryClient = (CompositeDiscoveryClient) this.discoveryClient; assertThat(compositeDiscoveryClient.getDiscoveryClients().get(0).description()) .isEqualTo("A custom discovery client"); assertThat(compositeDiscoveryClient.getDiscoveryClients().get(1)) @@ -70,5 +71,7 @@ public class CompositeDiscoveryClientAutoConfigurationTests { } }; } + } + } diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/composite/CompositeDiscoveryClientOrderTest.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/composite/CompositeDiscoveryClientOrderTest.java index f9f925e3..1128e3a5 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/composite/CompositeDiscoveryClientOrderTest.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/composite/CompositeDiscoveryClientOrderTest.java @@ -34,13 +34,14 @@ import static org.springframework.cloud.client.discovery.composite.CompositeDisc import static org.springframework.cloud.client.discovery.composite.CompositeDiscoveryClientTestsConfig.FOURTH_DISCOVERY_CLIENT; /** - * Tests for the support of ordered {@link DiscoveryClient} instances in {@link CompositeDiscoveryClient} + * Tests for the support of ordered {@link DiscoveryClient} instances in + * {@link CompositeDiscoveryClient} * * @author Olga Maciaszek-Sharma */ @RunWith(SpringRunner.class) @SpringBootTest(properties = "spring.cloud.discovery.client.simple.order:2", classes = { - CompositeDiscoveryClientTestsConfig.class}) + CompositeDiscoveryClientTestsConfig.class }) public class CompositeDiscoveryClientOrderTest { @Autowired @@ -73,4 +74,5 @@ public class CompositeDiscoveryClientOrderTest { assertThat(serviceInstances).hasSize(1); assertThat(serviceInstances.get(0).getPort()).isEqualTo(123); } + } diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/composite/CompositeDiscoveryClientTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/composite/CompositeDiscoveryClientTests.java index f0eca3bf..d4e9c6e6 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/composite/CompositeDiscoveryClientTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/composite/CompositeDiscoveryClientTests.java @@ -37,13 +37,12 @@ import static org.springframework.cloud.client.discovery.composite.CompositeDisc */ @RunWith(SpringRunner.class) -@SpringBootTest(properties = { - "spring.application.name=service0", +@SpringBootTest(properties = { "spring.application.name=service0", "spring.cloud.discovery.client.simple.instances.service1[0].uri=http://s1-1:8080", "spring.cloud.discovery.client.simple.instances.service1[1].uri=https://s1-2:8443", "spring.cloud.discovery.client.simple.instances.service2[0].uri=https://s2-1:8080", - "spring.cloud.discovery.client.simple.instances.service2[1].uri=https://s2-2:443",}, classes = { - CompositeDiscoveryClientTestsConfig.class}) + "spring.cloud.discovery.client.simple.instances.service2[1].uri=https://s2-2:443", }, classes = { + CompositeDiscoveryClientTestsConfig.class }) public class CompositeDiscoveryClientTests { @Autowired @@ -64,12 +63,14 @@ public class CompositeDiscoveryClientTests { @Test public void getServicesShouldAggregateAllServiceNames() { - assertThat(this.discoveryClient.getServices()).containsOnlyOnce("service1", "service2", "custom"); + assertThat(this.discoveryClient.getServices()).containsOnlyOnce("service1", + "service2", "custom"); } @Test public void getDescriptionShouldBeComposite() { - assertThat(this.discoveryClient.description()).isEqualTo("Composite Discovery Client"); + assertThat(this.discoveryClient.description()) + .isEqualTo("Composite Discovery Client"); } @Test @@ -82,4 +83,5 @@ public class CompositeDiscoveryClientTests { public void getInstancesByUnknownServiceIdShouldReturnAnEmptyList() { assertThat(this.discoveryClient.getInstances("unknown")).hasSize(0); } + } diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/composite/CompositeDiscoveryClientTestsConfig.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/composite/CompositeDiscoveryClientTestsConfig.java index 443830bc..e91d1970 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/composite/CompositeDiscoveryClientTestsConfig.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/composite/CompositeDiscoveryClientTestsConfig.java @@ -68,8 +68,8 @@ public class CompositeDiscoveryClientTestsConfig { @Override public List getInstances(String serviceId) { if (serviceId.equals(CUSTOM_SERVICE_ID)) { - ServiceInstance s1 = new DefaultServiceInstance("customInstance", CUSTOM_SERVICE_ID, - "host", 123, false); + ServiceInstance s1 = new DefaultServiceInstance("customInstance", + CUSTOM_SERVICE_ID, "host", 123, false); return singletonList(s1); } return Collections.emptyList(); @@ -86,4 +86,5 @@ public class CompositeDiscoveryClientTestsConfig { } }; } + } diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/health/DiscoveryClientHealthIndicatorTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/health/DiscoveryClientHealthIndicatorTests.java index 32dcb636..aeabeaf1 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/health/DiscoveryClientHealthIndicatorTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/health/DiscoveryClientHealthIndicatorTests.java @@ -20,6 +20,7 @@ import java.util.Arrays; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.health.Health; import org.springframework.boot.actuate.health.HealthAggregator; @@ -53,9 +54,33 @@ public class DiscoveryClientHealthIndicatorTests { @Autowired private DiscoveryClientHealthIndicator clientHealthIndicator; + @Test + public void testHealthIndicatorDescriptionDisabled() { + assertNotNull("healthIndicator was null", this.healthIndicator); + Health health = this.healthIndicator.health(); + assertHealth(health, Status.UNKNOWN); + + this.clientHealthIndicator + .onApplicationEvent(new InstanceRegisteredEvent<>(this, null)); + + health = this.healthIndicator.health(); + Status status = assertHealth(health, Status.UP); + assertEquals("status description was wrong", "TestDiscoveryClient", + status.getDescription()); + } + + private Status assertHealth(Health health, Status expected) { + assertNotNull("health was null", health); + Status status = health.getStatus(); + assertNotNull("status was null", status); + assertEquals("status code was wrong", expected.getCode(), status.getCode()); + return status; + } + @Configuration @EnableConfigurationProperties public static class Config { + @Bean public HealthAggregator healthAggregator() { return new OrderedHealthAggregator(); @@ -83,27 +108,7 @@ public class DiscoveryClientHealthIndicatorTests { } }; } + } - @Test - public void testHealthIndicatorDescriptionDisabled() { - assertNotNull("healthIndicator was null", this.healthIndicator); - Health health = this.healthIndicator.health(); - assertHealth(health, Status.UNKNOWN); - - clientHealthIndicator.onApplicationEvent(new InstanceRegisteredEvent<>(this, null)); - - health = this.healthIndicator.health(); - Status status = assertHealth(health, Status.UP); - assertEquals("status description was wrong", "TestDiscoveryClient", - status.getDescription()); - } - - private Status assertHealth(Health health, Status expected) { - assertNotNull("health was null", health); - Status status = health.getStatus(); - assertNotNull("status was null", status); - assertEquals("status code was wrong", expected.getCode(), status.getCode()); - return status; - } } diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/health/DiscoveryCompositeHealthIndicatorTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/health/DiscoveryCompositeHealthIndicatorTests.java index 676b2886..575637fe 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/health/DiscoveryCompositeHealthIndicatorTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/health/DiscoveryCompositeHealthIndicatorTests.java @@ -20,6 +20,7 @@ import java.util.Arrays; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.health.Health; import org.springframework.boot.actuate.health.HealthAggregator; @@ -52,8 +53,31 @@ public class DiscoveryCompositeHealthIndicatorTests { @Autowired private DiscoveryClientHealthIndicator clientHealthIndicator; + @Test + public void testHealthIndicator() { + assertNotNull("healthIndicator was null", this.healthIndicator); + Health health = this.healthIndicator.health(); + assertHealth(health, Status.UNKNOWN); + + this.clientHealthIndicator + .onApplicationEvent(new InstanceRegisteredEvent<>(this, null)); + + health = this.healthIndicator.health(); + Status status = assertHealth(health, Status.UP); + assertEquals("status description was wrong", "", status.getDescription()); + } + + protected Status assertHealth(Health health, Status expected) { + assertNotNull("health was null", health); + Status status = health.getStatus(); + assertNotNull("status was null", status); + assertEquals("status code was wrong", expected.getCode(), status.getCode()); + return status; + } + @Configuration public static class Config { + @Bean public HealthAggregator healthAggregator() { return new OrderedHealthAggregator(); @@ -81,28 +105,7 @@ public class DiscoveryCompositeHealthIndicatorTests { } }; } - } - @Test - public void testHealthIndicator() { - assertNotNull("healthIndicator was null", this.healthIndicator); - Health health = this.healthIndicator.health(); - assertHealth(health, Status.UNKNOWN); - - clientHealthIndicator.onApplicationEvent(new InstanceRegisteredEvent<>(this, null)); - - health = this.healthIndicator.health(); - Status status = assertHealth(health, Status.UP); - assertEquals("status description was wrong", "", - status.getDescription()); - } - - protected Status assertHealth(Health health, Status expected) { - assertNotNull("health was null", health); - Status status = health.getStatus(); - assertNotNull("status was null", status); - assertEquals("status code was wrong", expected.getCode(), status.getCode()); - return status; } } diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/simple/DiscoveryClientAutoConfigurationDefaultTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/simple/DiscoveryClientAutoConfigurationDefaultTests.java index bb6732ec..eb3cf684 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/simple/DiscoveryClientAutoConfigurationDefaultTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/simple/DiscoveryClientAutoConfigurationDefaultTests.java @@ -2,6 +2,7 @@ package org.springframework.cloud.client.discovery.simple; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; @@ -14,7 +15,7 @@ import static org.assertj.core.api.Assertions.assertThat; /** * DiscoveryClient implementation defaults to {@link CompositeDiscoveryClient} - * + * * @author Biju Kunjummen */ @RunWith(SpringRunner.class) @@ -26,11 +27,13 @@ public class DiscoveryClientAutoConfigurationDefaultTests { @Test public void simpleDiscoveryClientShouldBeTheDefault() { - assertThat(discoveryClient).isInstanceOf(CompositeDiscoveryClient.class); + assertThat(this.discoveryClient).isInstanceOf(CompositeDiscoveryClient.class); } @EnableAutoConfiguration @Configuration public static class Config { + } + } diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/simple/SimpleDiscoveryClientPropertiesMappingTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/simple/SimpleDiscoveryClientPropertiesMappingTests.java index c42c7bb2..385ad837 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/simple/SimpleDiscoveryClientPropertiesMappingTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/simple/SimpleDiscoveryClientPropertiesMappingTests.java @@ -4,6 +4,7 @@ import java.net.URI; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; @@ -85,5 +86,7 @@ public class SimpleDiscoveryClientPropertiesMappingTests { @Configuration @EnableAutoConfiguration public static class SampleConfig { + } + } diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/simple/SimpleDiscoveryClientTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/simple/SimpleDiscoveryClientTests.java index eb29c205..bbb5e18a 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/simple/SimpleDiscoveryClientTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/simple/SimpleDiscoveryClientTests.java @@ -8,6 +8,7 @@ import java.util.Map; import org.junit.Before; import org.junit.Test; + import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.discovery.simple.SimpleDiscoveryProperties.SimpleServiceInstance; @@ -47,4 +48,5 @@ public class SimpleDiscoveryClientTests { assertThat(instances.get(0).isSecure()).isEqualTo(false); assertThat(instances.get(0).getMetadata()).isNotNull(); } + } diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/hypermedia/CloudHypermediaAutoConfigurationIntegrationTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/hypermedia/CloudHypermediaAutoConfigurationIntegrationTests.java index 7df82999..2b9906eb 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/hypermedia/CloudHypermediaAutoConfigurationIntegrationTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/hypermedia/CloudHypermediaAutoConfigurationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2015-2018 the original author or authors. + * Copyright 2015-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. @@ -16,6 +16,7 @@ package org.springframework.cloud.client.hypermedia; import org.junit.Test; + import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.cloud.client.DefaultServiceInstance; @@ -38,6 +39,12 @@ import static org.junit.Assert.assertThat; */ public class CloudHypermediaAutoConfigurationIntegrationTests { + private static ConfigurableApplicationContext getApplicationContext( + Class configuration) { + return new SpringApplicationBuilder(configuration).properties("server.port=0") + .run(); + } + @Test public void picksUpHypermediaProperties() { @@ -86,15 +93,10 @@ public class CloudHypermediaAutoConfigurationIntegrationTests { } } - private static ConfigurableApplicationContext getApplicationContext( - Class configuration) { - return new SpringApplicationBuilder(configuration).properties("server.port=0") - .run(); - } - @Configuration @EnableAutoConfiguration static class Config { + } @Configuration @@ -105,8 +107,11 @@ public class CloudHypermediaAutoConfigurationIntegrationTests { public RemoteResource resource() { ServiceInstanceProvider provider = new StaticServiceInstanceProvider( - new DefaultServiceInstance("instance", "service", "localhost", 80, false)); + new DefaultServiceInstance("instance", "service", "localhost", 80, + false)); return new DiscoveredResource(provider, traverson -> traverson.follow("rel")); } + } + } diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/hypermedia/DiscoveredResourceUnitTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/hypermedia/DiscoveredResourceUnitTests.java index e580dd1b..5a51931e 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/hypermedia/DiscoveredResourceUnitTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/hypermedia/DiscoveredResourceUnitTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2015-2018 the original author or authors. + * Copyright 2015-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. @@ -21,6 +21,7 @@ import org.junit.runner.RunWith; import org.mockito.Matchers; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; + import org.springframework.cloud.client.DefaultServiceInstance; import org.springframework.hateoas.Link; import org.springframework.hateoas.client.Traverson; @@ -45,24 +46,32 @@ import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class DiscoveredResourceUnitTests { - @Mock ServiceInstanceProvider provider; - @Mock TraversalDefinition traversal; - @Mock TraversalBuilder builder; - @Mock RestOperations operations; + @Mock + ServiceInstanceProvider provider; + + @Mock + TraversalDefinition traversal; + + @Mock + TraversalBuilder builder; + + @Mock + RestOperations operations; DiscoveredResource resource; @Before public void setUp() { - when(traversal.buildTraversal(Matchers.any(Traverson.class))).thenReturn(builder); + when(this.traversal.buildTraversal(Matchers.any(Traverson.class))) + .thenReturn(this.builder); - this.resource = new DiscoveredResource(provider, traversal); - this.resource.setRestOperations(operations); + this.resource = new DiscoveredResource(this.provider, this.traversal); + this.resource.setRestOperations(this.operations); } @Test public void isUndiscoveredByDefault() { - assertThat(resource.getLink(), is(nullValue())); + assertThat(this.resource.getLink(), is(nullValue())); } @Test @@ -70,14 +79,15 @@ public class DiscoveredResourceUnitTests { Link link = new Link("target", "rel"); - when(provider.getServiceInstance()).thenReturn(new DefaultServiceInstance("instance", "service", "localhost", 8080, false)); - when(builder.asTemplatedLink()).thenReturn(link); + when(this.provider.getServiceInstance()).thenReturn(new DefaultServiceInstance( + "instance", "service", "localhost", 8080, false)); + when(this.builder.asTemplatedLink()).thenReturn(link); - resource.verifyOrDiscover(); + this.resource.verifyOrDiscover(); - assertThat(resource.getLink(), is(link)); - verify(provider, times(1)).getServiceInstance(); - verify(traversal, times(1)).buildTraversal(Matchers.any(Traverson.class)); + assertThat(this.resource.getLink(), is(link)); + verify(this.provider, times(1)).getServiceInstance(); + verify(this.traversal, times(1)).buildTraversal(Matchers.any(Traverson.class)); } @Test @@ -85,10 +95,10 @@ public class DiscoveredResourceUnitTests { verificationTriggersDiscovery(); - resource.verifyOrDiscover(); + this.resource.verifyOrDiscover(); - assertThat(resource.getLink(), is(notNullValue())); - verify(operations, times(1)).headForHeaders(anyString()); + assertThat(this.resource.getLink(), is(notNullValue())); + verify(this.operations, times(1)).headForHeaders(anyString()); } @Test @@ -96,19 +106,21 @@ public class DiscoveredResourceUnitTests { verificationTriggersDiscovery(); - doThrow(RestClientException.class).when(operations).headForHeaders(anyString()); - resource.verifyOrDiscover(); + doThrow(RestClientException.class).when(this.operations) + .headForHeaders(anyString()); + this.resource.verifyOrDiscover(); - assertThat(resource.getLink(), is(nullValue())); + assertThat(this.resource.getLink(), is(nullValue())); } @Test public void failedDiscoveryTraversalCausesLinkToStayNull() { - doThrow(RuntimeException.class).when(provider).getServiceInstance(); + doThrow(RuntimeException.class).when(this.provider).getServiceInstance(); - resource.verifyOrDiscover(); + this.resource.verifyOrDiscover(); - assertThat(resource.getLink(), is(nullValue())); + assertThat(this.resource.getLink(), is(nullValue())); } + } diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/hypermedia/DynamicServiceInstanceProviderUnitTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/hypermedia/DynamicServiceInstanceProviderUnitTests.java index 405e1c3f..1b15e510 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/hypermedia/DynamicServiceInstanceProviderUnitTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/hypermedia/DynamicServiceInstanceProviderUnitTests.java @@ -21,6 +21,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; + import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.discovery.DiscoveryClient; @@ -37,11 +38,13 @@ import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class DynamicServiceInstanceProviderUnitTests { - @Mock DiscoveryClient client; + @Mock + DiscoveryClient client; @Test public void returnsNoServiceInCaseNoneIsAvailable() { - assertThat(new DynamicServiceInstanceProvider(client, "service").getServiceInstance(), is(nullValue())); + assertThat(new DynamicServiceInstanceProvider(this.client, "service") + .getServiceInstance(), is(nullValue())); } @Test @@ -50,8 +53,11 @@ public class DynamicServiceInstanceProviderUnitTests { ServiceInstance first = mock(ServiceInstance.class); ServiceInstance second = mock(ServiceInstance.class); - when(client.getInstances(anyString())).thenReturn(Arrays.asList(first, second)); + when(this.client.getInstances(anyString())) + .thenReturn(Arrays.asList(first, second)); - assertThat(new DynamicServiceInstanceProvider(client, "service").getServiceInstance(), is(first)); + assertThat(new DynamicServiceInstanceProvider(this.client, "service") + .getServiceInstance(), is(first)); } + } diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/AbstractLoadBalancerAutoConfigurationTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/AbstractLoadBalancerAutoConfigurationTests.java index 69a4817b..8baa06ce 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/AbstractLoadBalancerAutoConfigurationTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/AbstractLoadBalancerAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 the original author or authors. + * Copyright 2017-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. @@ -16,20 +16,14 @@ package org.springframework.cloud.client.loadbalancer; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.empty; -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; - import java.io.IOException; import java.net.URI; import java.util.Collection; import java.util.Map; import java.util.Random; - import org.junit.Test; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.WebApplicationType; import org.springframework.boot.builder.SpringApplicationBuilder; @@ -41,6 +35,12 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.web.client.RestTemplate; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.empty; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; + /** * @author Ryan Baxter * @author Tim Ysewyn @@ -101,6 +101,7 @@ public abstract class AbstractLoadBalancerAutoConfigurationTests { LoadBalancerClient loadBalancerClient() { return new NoopLoadBalancerClient(); } + } @Configuration @@ -125,17 +126,20 @@ public abstract class AbstractLoadBalancerAutoConfigurationTests { @Configuration protected static class Two { + @Autowired RestTemplate nonLoadBalanced; @Autowired @LoadBalanced RestTemplate loadBalanced; + } } private static class NoopLoadBalancerClient implements LoadBalancerClient { + private final Random random = new Random(); @Override @@ -148,16 +152,19 @@ public abstract class AbstractLoadBalancerAutoConfigurationTests { public T execute(String serviceId, LoadBalancerRequest request) { try { return request.apply(choose(serviceId)); - } catch (Exception e) { + } + catch (Exception e) { throw new RuntimeException(e); } } @Override - public T execute(String serviceId, ServiceInstance serviceInstance, LoadBalancerRequest request) throws IOException { + public T execute(String serviceId, ServiceInstance serviceInstance, + LoadBalancerRequest request) throws IOException { try { return request.apply(choose(serviceId)); - } catch (Exception e) { + } + catch (Exception e) { throw new RuntimeException(e); } } @@ -166,5 +173,7 @@ public abstract class AbstractLoadBalancerAutoConfigurationTests { public URI reconstructURI(ServiceInstance instance, URI original) { return DefaultServiceInstance.getUri(instance); } + } + } diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/AsyncLoadBalancerAutoConfigurationTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/AsyncLoadBalancerAutoConfigurationTests.java index 51e14498..dd9b1f9f 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/AsyncLoadBalancerAutoConfigurationTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/AsyncLoadBalancerAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 the original author or authors. + * Copyright 2017-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. @@ -16,8 +16,16 @@ package org.springframework.cloud.client.loadbalancer; +import java.io.IOException; +import java.net.URI; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Random; + import org.hamcrest.MatcherAssert; import org.junit.Test; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.WebApplicationType; import org.springframework.boot.builder.SpringApplicationBuilder; @@ -30,19 +38,11 @@ import org.springframework.context.annotation.Primary; import org.springframework.http.client.AsyncClientHttpRequestInterceptor; import org.springframework.web.client.AsyncRestTemplate; -import java.io.IOException; -import java.net.URI; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.Random; - -import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.empty; - +import static org.hamcrest.Matchers.notNullValue; /** * @author Rob Worsnop @@ -65,10 +65,12 @@ public class AsyncLoadBalancerAutoConfigurationTests { } private void assertLoadBalanced(AsyncRestTemplate restTemplate) { - List interceptors = restTemplate.getInterceptors(); + List interceptors = restTemplate + .getInterceptors(); MatcherAssert.assertThat(interceptors, hasSize(1)); AsyncClientHttpRequestInterceptor interceptor = interceptors.get(0); - MatcherAssert.assertThat(interceptor, is(instanceOf(AsyncLoadBalancerInterceptor.class))); + MatcherAssert.assertThat(interceptor, + is(instanceOf(AsyncLoadBalancerInterceptor.class))); } @Test @@ -111,7 +113,10 @@ public class AsyncLoadBalancerAutoConfigurationTests { } @Bean - LoadBalancedRetryFactory loadBalancedRetryFactory() {return new LoadBalancedRetryFactory(){};} + LoadBalancedRetryFactory loadBalancedRetryFactory() { + return new LoadBalancedRetryFactory() { + }; + } } @@ -137,17 +142,20 @@ public class AsyncLoadBalancerAutoConfigurationTests { @Configuration protected static class Two { + @Autowired AsyncRestTemplate nonLoadBalanced; @Autowired @LoadBalanced AsyncRestTemplate loadBalanced; + } } private static class NoopLoadBalancerClient implements LoadBalancerClient { + private final Random random = new Random(); @Override @@ -160,16 +168,19 @@ public class AsyncLoadBalancerAutoConfigurationTests { public T execute(String serviceId, LoadBalancerRequest request) { try { return request.apply(choose(serviceId)); - } catch (Exception e) { + } + catch (Exception e) { throw new RuntimeException(e); } } @Override - public T execute(String serviceId, ServiceInstance serviceInstance, LoadBalancerRequest request) throws IOException { + public T execute(String serviceId, ServiceInstance serviceInstance, + LoadBalancerRequest request) throws IOException { try { return request.apply(choose(serviceId)); - } catch (Exception e) { + } + catch (Exception e) { throw new RuntimeException(e); } } @@ -178,5 +189,7 @@ public class AsyncLoadBalancerAutoConfigurationTests { public URI reconstructURI(ServiceInstance instance, URI original) { return DefaultServiceInstance.getUri(instance); } + } + } diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/ClientHttpResponseStatusCodeExceptionTest.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/ClientHttpResponseStatusCodeExceptionTest.java index 61155168..532d2f8a 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/ClientHttpResponseStatusCodeExceptionTest.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/ClientHttpResponseStatusCodeExceptionTest.java @@ -3,16 +3,17 @@ package org.springframework.cloud.client.loadbalancer; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; + import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.runners.MockitoJUnitRunner; + import org.springframework.http.HttpHeaders; import org.springframework.http.client.AbstractClientHttpResponse; import org.springframework.http.client.ClientHttpResponse; import org.springframework.util.StreamUtils; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertFalse; /** @@ -25,13 +26,14 @@ public class ClientHttpResponseStatusCodeExceptionTest { public void testCreation() throws Exception { MyClientHttpResponse response = new MyClientHttpResponse(); assertFalse(response.isClosed()); - ClientHttpResponseStatusCodeException exp = new ClientHttpResponseStatusCodeException("service", - response, response.getStatusText().getBytes()); + ClientHttpResponseStatusCodeException exp = new ClientHttpResponseStatusCodeException( + "service", response, response.getStatusText().getBytes()); ClientHttpResponse expResponse = exp.getResponse(); assertEquals(response.getRawStatusCode(), expResponse.getRawStatusCode()); assertEquals(response.getStatusText(), expResponse.getStatusText()); assertEquals(response.getHeaders(), expResponse.getHeaders()); - assertEquals(response.getStatusText(), new String(StreamUtils.copyToByteArray(expResponse.getBody()))); + assertEquals(response.getStatusText(), + new String(StreamUtils.copyToByteArray(expResponse.getBody()))); } class MyClientHttpResponse extends AbstractClientHttpResponse { @@ -54,7 +56,7 @@ public class ClientHttpResponseStatusCodeExceptionTest { } public boolean isClosed() { - return closed; + return this.closed; } @Override @@ -68,5 +70,7 @@ public class ClientHttpResponseStatusCodeExceptionTest { headers.add("foo", "bar"); return headers; } + } -} \ No newline at end of file + +} diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/InterceptorRetryPolicyTest.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/InterceptorRetryPolicyTest.java index 81cc6755..c95854b6 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/InterceptorRetryPolicyTest.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/InterceptorRetryPolicyTest.java @@ -6,6 +6,7 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.runners.MockitoJUnitRunner; + import org.springframework.cloud.client.ServiceInstance; import org.springframework.http.HttpRequest; import org.springframework.retry.RetryContext; @@ -24,88 +25,102 @@ import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class InterceptorRetryPolicyTest { - private HttpRequest request; - private LoadBalancedRetryPolicy policy; - private ServiceInstanceChooser serviceInstanceChooser; - private String serviceName; + private HttpRequest request; - @Before - public void setup() { - request = mock(HttpRequest.class); - policy = mock(LoadBalancedRetryPolicy.class); - serviceInstanceChooser = mock(ServiceInstanceChooser.class); - serviceName = "foo"; - } + private LoadBalancedRetryPolicy policy; - @After - public void teardown() { - request = null; - policy = null; - serviceInstanceChooser = null; - serviceName = null; - } + private ServiceInstanceChooser serviceInstanceChooser; - @Test - public void canRetryBeforeExecution() throws Exception { - InterceptorRetryPolicy interceptorRetryPolicy = new InterceptorRetryPolicy(request, policy, serviceInstanceChooser, serviceName); - LoadBalancedRetryContext context = mock(LoadBalancedRetryContext.class); - when(context.getRetryCount()).thenReturn(0); - ServiceInstance serviceInstance = mock(ServiceInstance.class); - when(serviceInstanceChooser.choose(eq(serviceName))).thenReturn(serviceInstance); - assertThat(interceptorRetryPolicy.canRetry(context), is(true)); - verify(context, times(1)).setServiceInstance(eq(serviceInstance)); + private String serviceName; - } + @Before + public void setup() { + this.request = mock(HttpRequest.class); + this.policy = mock(LoadBalancedRetryPolicy.class); + this.serviceInstanceChooser = mock(ServiceInstanceChooser.class); + this.serviceName = "foo"; + } - @Test - public void canRetryNextServer() throws Exception { - InterceptorRetryPolicy interceptorRetryPolicy = new InterceptorRetryPolicy(request, policy, serviceInstanceChooser, serviceName); - LoadBalancedRetryContext context = mock(LoadBalancedRetryContext.class); - when(context.getRetryCount()).thenReturn(1); - when(policy.canRetryNextServer(eq(context))).thenReturn(true); - assertThat(interceptorRetryPolicy.canRetry(context), is(true)); - } + @After + public void teardown() { + this.request = null; + this.policy = null; + this.serviceInstanceChooser = null; + this.serviceName = null; + } - @Test - public void cannotRetry() throws Exception { - InterceptorRetryPolicy interceptorRetryPolicy = new InterceptorRetryPolicy(request, policy, serviceInstanceChooser, serviceName); - LoadBalancedRetryContext context = mock(LoadBalancedRetryContext.class); - when(context.getRetryCount()).thenReturn(1); - assertThat(interceptorRetryPolicy.canRetry(context), is(false)); - } + @Test + public void canRetryBeforeExecution() throws Exception { + InterceptorRetryPolicy interceptorRetryPolicy = new InterceptorRetryPolicy( + this.request, this.policy, this.serviceInstanceChooser, this.serviceName); + LoadBalancedRetryContext context = mock(LoadBalancedRetryContext.class); + when(context.getRetryCount()).thenReturn(0); + ServiceInstance serviceInstance = mock(ServiceInstance.class); + when(this.serviceInstanceChooser.choose(eq(this.serviceName))) + .thenReturn(serviceInstance); + assertThat(interceptorRetryPolicy.canRetry(context), is(true)); + verify(context, times(1)).setServiceInstance(eq(serviceInstance)); - @Test - public void open() throws Exception { - InterceptorRetryPolicy interceptorRetryPolicy = new InterceptorRetryPolicy(request, policy, serviceInstanceChooser, serviceName); - RetryContext context = interceptorRetryPolicy.open(null); - assertThat(context, IsInstanceOf.instanceOf(LoadBalancedRetryContext.class)); - } + } - @Test - public void close() throws Exception { - InterceptorRetryPolicy interceptorRetryPolicy = new InterceptorRetryPolicy(request, policy, serviceInstanceChooser, serviceName); - LoadBalancedRetryContext context = mock(LoadBalancedRetryContext.class); - interceptorRetryPolicy.close(context); - verify(policy, times(1)).close(eq(context)); - } + @Test + public void canRetryNextServer() throws Exception { + InterceptorRetryPolicy interceptorRetryPolicy = new InterceptorRetryPolicy( + this.request, this.policy, this.serviceInstanceChooser, this.serviceName); + LoadBalancedRetryContext context = mock(LoadBalancedRetryContext.class); + when(context.getRetryCount()).thenReturn(1); + when(this.policy.canRetryNextServer(eq(context))).thenReturn(true); + assertThat(interceptorRetryPolicy.canRetry(context), is(true)); + } - @Test - public void registerThrowable() throws Exception { - InterceptorRetryPolicy interceptorRetryPolicy = new InterceptorRetryPolicy(request, policy, serviceInstanceChooser, serviceName); - LoadBalancedRetryContext context = mock(LoadBalancedRetryContext.class); - Throwable thrown = new Exception(); - interceptorRetryPolicy.registerThrowable(context, thrown); - verify(context, times(1)).registerThrowable(eq(thrown)); - verify(policy, times(1)).registerThrowable(eq(context), eq(thrown)); - } + @Test + public void cannotRetry() throws Exception { + InterceptorRetryPolicy interceptorRetryPolicy = new InterceptorRetryPolicy( + this.request, this.policy, this.serviceInstanceChooser, this.serviceName); + LoadBalancedRetryContext context = mock(LoadBalancedRetryContext.class); + when(context.getRetryCount()).thenReturn(1); + assertThat(interceptorRetryPolicy.canRetry(context), is(false)); + } - @Test - public void equals() throws Exception { - InterceptorRetryPolicy interceptorRetryPolicy = new InterceptorRetryPolicy(request, policy, serviceInstanceChooser, serviceName); - assertThat(interceptorRetryPolicy.equals(null), is(false)); - assertThat(interceptorRetryPolicy.equals(new Object()), is(false)); - assertThat(interceptorRetryPolicy.equals(interceptorRetryPolicy), is(true)); - assertThat(interceptorRetryPolicy.equals(new InterceptorRetryPolicy(request, policy, serviceInstanceChooser, serviceName)), is(true)); - } + @Test + public void open() throws Exception { + InterceptorRetryPolicy interceptorRetryPolicy = new InterceptorRetryPolicy( + this.request, this.policy, this.serviceInstanceChooser, this.serviceName); + RetryContext context = interceptorRetryPolicy.open(null); + assertThat(context, IsInstanceOf.instanceOf(LoadBalancedRetryContext.class)); + } -} \ No newline at end of file + @Test + public void close() throws Exception { + InterceptorRetryPolicy interceptorRetryPolicy = new InterceptorRetryPolicy( + this.request, this.policy, this.serviceInstanceChooser, this.serviceName); + LoadBalancedRetryContext context = mock(LoadBalancedRetryContext.class); + interceptorRetryPolicy.close(context); + verify(this.policy, times(1)).close(eq(context)); + } + + @Test + public void registerThrowable() throws Exception { + InterceptorRetryPolicy interceptorRetryPolicy = new InterceptorRetryPolicy( + this.request, this.policy, this.serviceInstanceChooser, this.serviceName); + LoadBalancedRetryContext context = mock(LoadBalancedRetryContext.class); + Throwable thrown = new Exception(); + interceptorRetryPolicy.registerThrowable(context, thrown); + verify(context, times(1)).registerThrowable(eq(thrown)); + verify(this.policy, times(1)).registerThrowable(eq(context), eq(thrown)); + } + + @Test + public void equals() throws Exception { + InterceptorRetryPolicy interceptorRetryPolicy = new InterceptorRetryPolicy( + this.request, this.policy, this.serviceInstanceChooser, this.serviceName); + assertThat(interceptorRetryPolicy.equals(null), is(false)); + assertThat(interceptorRetryPolicy.equals(new Object()), is(false)); + assertThat(interceptorRetryPolicy.equals(interceptorRetryPolicy), is(true)); + assertThat( + interceptorRetryPolicy.equals(new InterceptorRetryPolicy(this.request, + this.policy, this.serviceInstanceChooser, this.serviceName)), + is(true)); + } + +} diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/LoadBalancedRetryContextTest.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/LoadBalancedRetryContextTest.java index 6e7f9aa6..a770e507 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/LoadBalancedRetryContextTest.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/LoadBalancedRetryContextTest.java @@ -5,6 +5,7 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.runners.MockitoJUnitRunner; + import org.springframework.cloud.client.ServiceInstance; import org.springframework.http.HttpRequest; import org.springframework.retry.RetryContext; @@ -19,40 +20,45 @@ import static org.mockito.Mockito.mock; @RunWith(MockitoJUnitRunner.class) public class LoadBalancedRetryContextTest { - private RetryContext context; - private HttpRequest request; + private RetryContext context; - @Before - public void setUp() throws Exception { - context = mock(RetryContext.class); - request = mock(HttpRequest.class); - } + private HttpRequest request; - @After - public void tearDown() throws Exception { - context = null; - request = null; - } + @Before + public void setUp() throws Exception { + this.context = mock(RetryContext.class); + this.request = mock(HttpRequest.class); + } - @Test - public void getRequest() throws Exception { - LoadBalancedRetryContext lbContext = new LoadBalancedRetryContext(context, request); - assertThat(lbContext.getRequest(), is(request)); - } + @After + public void tearDown() throws Exception { + this.context = null; + this.request = null; + } - @Test - public void setRequest() throws Exception { - LoadBalancedRetryContext lbContext = new LoadBalancedRetryContext(context, request); - HttpRequest newRequest = mock(HttpRequest.class); - lbContext.setRequest(newRequest); - assertThat(lbContext.getRequest(), is(newRequest)); - } + @Test + public void getRequest() throws Exception { + LoadBalancedRetryContext lbContext = new LoadBalancedRetryContext(this.context, + this.request); + assertThat(lbContext.getRequest(), is(this.request)); + } - @Test - public void getServiceInstance() throws Exception { - LoadBalancedRetryContext lbContext = new LoadBalancedRetryContext(context, request); - ServiceInstance serviceInstance = mock(ServiceInstance.class); - lbContext.setServiceInstance(serviceInstance); - assertThat(lbContext.getServiceInstance(), is(serviceInstance)); - } -} \ No newline at end of file + @Test + public void setRequest() throws Exception { + LoadBalancedRetryContext lbContext = new LoadBalancedRetryContext(this.context, + this.request); + HttpRequest newRequest = mock(HttpRequest.class); + lbContext.setRequest(newRequest); + assertThat(lbContext.getRequest(), is(newRequest)); + } + + @Test + public void getServiceInstance() throws Exception { + LoadBalancedRetryContext lbContext = new LoadBalancedRetryContext(this.context, + this.request); + ServiceInstance serviceInstance = mock(ServiceInstance.class); + lbContext.setServiceInstance(serviceInstance); + assertThat(lbContext.getServiceInstance(), is(serviceInstance)); + } + +} diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/LoadBalancerAutoConfigurationTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/LoadBalancerAutoConfigurationTests.java index fd564247..077a60b5 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/LoadBalancerAutoConfigurationTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/LoadBalancerAutoConfigurationTests.java @@ -18,8 +18,9 @@ import static org.hamcrest.Matchers.is; * @author Spencer Gibb */ @RunWith(ModifiedClassPathRunner.class) -@ClassPathExclusions({"spring-retry-*.jar", "spring-boot-starter-aop-*.jar"}) -public class LoadBalancerAutoConfigurationTests extends AbstractLoadBalancerAutoConfigurationTests { +@ClassPathExclusions({ "spring-retry-*.jar", "spring-boot-starter-aop-*.jar" }) +public class LoadBalancerAutoConfigurationTests + extends AbstractLoadBalancerAutoConfigurationTests { @Override protected void assertLoadBalanced(RestTemplate restTemplate) { @@ -28,4 +29,5 @@ public class LoadBalancerAutoConfigurationTests extends AbstractLoadBalancerAuto ClientHttpRequestInterceptor interceptor = interceptors.get(0); assertThat(interceptor, is(instanceOf(LoadBalancerInterceptor.class))); } + } diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/LoadBalancerRequestFactoryConfigurationTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/LoadBalancerRequestFactoryConfigurationTests.java index c89a3e14..0bdc33df 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/LoadBalancerRequestFactoryConfigurationTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/LoadBalancerRequestFactoryConfigurationTests.java @@ -15,19 +15,13 @@ */ package org.springframework.cloud.client.loadbalancer; -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; + import org.springframework.boot.WebApplicationType; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.cloud.client.ServiceInstance; @@ -38,37 +32,53 @@ import org.springframework.core.annotation.Order; import org.springframework.http.HttpRequest; import org.springframework.http.client.ClientHttpRequestExecution; +import static org.junit.Assert.assertEquals; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + @RunWith(MockitoJUnitRunner.class) public class LoadBalancerRequestFactoryConfigurationTests { @Mock private HttpRequest request; + @Mock private HttpRequest transformedRequest; + @Mock private HttpRequest transformedRequest2; + @Mock private ClientHttpRequestExecution execution; + @Mock private ServiceInstance instance; private byte[] body = new byte[] {}; + private ArgumentCaptor httpRequestCaptor; + private LoadBalancerRequestFactory lbReqFactory; + private LoadBalancerRequest lbRequest; @Before public void setup() { - httpRequestCaptor = ArgumentCaptor.forClass(HttpRequest.class); + this.httpRequestCaptor = ArgumentCaptor.forClass(HttpRequest.class); } protected ConfigurableApplicationContext init(Class config) { - ConfigurableApplicationContext context = new SpringApplicationBuilder().web(WebApplicationType.NONE) + ConfigurableApplicationContext context = new SpringApplicationBuilder() + .web(WebApplicationType.NONE) .properties("spring.aop.proxyTargetClass=true") .sources(config, LoadBalancerAutoConfiguration.class).run(); - lbReqFactory = context.getBean(LoadBalancerRequestFactory.class); - lbRequest = lbReqFactory.createRequest(request, body, execution); + this.lbReqFactory = context.getBean(LoadBalancerRequestFactory.class); + this.lbRequest = this.lbReqFactory.createRequest(this.request, this.body, + this.execution); return context; } @@ -78,29 +88,27 @@ public class LoadBalancerRequestFactoryConfigurationTests { LoadBalancerRequestTransformer transformer = context.getBean("transformer", LoadBalancerRequestTransformer.class); - when(transformer.transformRequest(any(ServiceRequestWrapper.class), eq(instance))) - .thenReturn(transformedRequest); + when(transformer.transformRequest(any(ServiceRequestWrapper.class), + eq(this.instance))).thenReturn(this.transformedRequest); - lbRequest.apply(instance); + this.lbRequest.apply(this.instance); - verify(execution).execute(httpRequestCaptor.capture(), eq(body)); + verify(this.execution).execute(this.httpRequestCaptor.capture(), eq(this.body)); assertEquals( "transformer should have transformed the ServiceRequestWrapper into transformedRequest", - transformedRequest, - httpRequestCaptor.getValue()); + this.transformedRequest, this.httpRequestCaptor.getValue()); } @Test public void noTransformer() throws Exception { init(NoTransformer.class); - lbRequest.apply(instance); + this.lbRequest.apply(this.instance); - verify(execution).execute(httpRequestCaptor.capture(), eq(body)); - assertEquals( - "ServiceRequestWrapper should be executed", + verify(this.execution).execute(this.httpRequestCaptor.capture(), eq(this.body)); + assertEquals("ServiceRequestWrapper should be executed", ServiceRequestWrapper.class, - httpRequestCaptor.getValue().getClass()); + this.httpRequestCaptor.getValue().getClass()); } @Test @@ -109,19 +117,18 @@ public class LoadBalancerRequestFactoryConfigurationTests { LoadBalancerRequestTransformer transformer = context.getBean("transformer", LoadBalancerRequestTransformer.class); - when(transformer.transformRequest(any(ServiceRequestWrapper.class), eq(instance))) - .thenReturn(transformedRequest); + when(transformer.transformRequest(any(ServiceRequestWrapper.class), + eq(this.instance))).thenReturn(this.transformedRequest); LoadBalancerRequestTransformer transformer2 = context.getBean("transformer2", LoadBalancerRequestTransformer.class); - when(transformer2.transformRequest(transformedRequest, instance)).thenReturn(transformedRequest2); + when(transformer2.transformRequest(this.transformedRequest, this.instance)) + .thenReturn(this.transformedRequest2); - lbRequest.apply(instance); + this.lbRequest.apply(this.instance); - verify(execution).execute(httpRequestCaptor.capture(), eq(body)); - assertEquals( - "transformer2 should run after transformer", - transformedRequest2, - httpRequestCaptor.getValue()); + verify(this.execution).execute(this.httpRequestCaptor.capture(), eq(this.body)); + assertEquals("transformer2 should run after transformer", + this.transformedRequest2, this.httpRequestCaptor.getValue()); } @Configuration diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/LoadBalancerRequestFactoryTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/LoadBalancerRequestFactoryTests.java index b2640b1d..d8d7dcf8 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/LoadBalancerRequestFactoryTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/LoadBalancerRequestFactoryTests.java @@ -15,12 +15,6 @@ */ package org.springframework.cloud.client.loadbalancer; -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.any; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - import java.util.Arrays; import java.util.Collections; import java.util.List; @@ -32,20 +26,30 @@ import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; + import org.springframework.cloud.client.ServiceInstance; import org.springframework.http.HttpRequest; import org.springframework.http.client.ClientHttpRequestExecution; import org.springframework.http.client.ClientHttpResponse; +import static org.junit.Assert.assertEquals; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + @RunWith(MockitoJUnitRunner.class) public class LoadBalancerRequestFactoryTests { @Mock private LoadBalancerClient loadBalancer; + @Mock private HttpRequest request; + @Mock private HttpRequest transformedRequest1; + @Mock private HttpRequest transformedRequest2; @@ -53,10 +57,13 @@ public class LoadBalancerRequestFactoryTests { @Mock private ClientHttpRequestExecution execution; + @Mock private ServiceInstance instance; + @Mock private LoadBalancerRequestTransformer transformer1; + @Mock private LoadBalancerRequestTransformer transformer2; @@ -64,16 +71,17 @@ public class LoadBalancerRequestFactoryTests { @Before public void setup() { - httpRequestCaptor = ArgumentCaptor.forClass(HttpRequest.class); + this.httpRequestCaptor = ArgumentCaptor.forClass(HttpRequest.class); } @Test public void testNullTransformers() throws Exception { executeLbRequest(null); - verify(execution).execute(httpRequestCaptor.capture(), eq(body)); - Assert.assertEquals("request should be of type ServiceRequestWrapper", ServiceRequestWrapper.class, - httpRequestCaptor.getValue().getClass()); + verify(this.execution).execute(this.httpRequestCaptor.capture(), eq(this.body)); + Assert.assertEquals("request should be of type ServiceRequestWrapper", + ServiceRequestWrapper.class, + this.httpRequestCaptor.getValue().getClass()); } @Test @@ -82,42 +90,51 @@ public class LoadBalancerRequestFactoryTests { executeLbRequest(transformers); - verify(execution).execute(httpRequestCaptor.capture(), eq(body)); - Assert.assertEquals("request should be of type ServiceRequestWrapper", ServiceRequestWrapper.class, - httpRequestCaptor.getValue().getClass()); + verify(this.execution).execute(this.httpRequestCaptor.capture(), eq(this.body)); + Assert.assertEquals("request should be of type ServiceRequestWrapper", + ServiceRequestWrapper.class, + this.httpRequestCaptor.getValue().getClass()); } @Test public void testOneTransformer() throws Exception { - List transformers = Arrays.asList(transformer1); - when(transformer1.transformRequest(any(ServiceRequestWrapper.class), eq(instance))).thenReturn(transformedRequest1); + List transformers = Arrays + .asList(this.transformer1); + when(this.transformer1.transformRequest(any(ServiceRequestWrapper.class), + eq(this.instance))).thenReturn(this.transformedRequest1); executeLbRequest(transformers); - verify(execution).execute(httpRequestCaptor.capture(), eq(body)); - assertEquals("transformer1 should have transformed request into transformedRequest1", transformedRequest1, - httpRequestCaptor.getValue()); + verify(this.execution).execute(this.httpRequestCaptor.capture(), eq(this.body)); + assertEquals( + "transformer1 should have transformed request into transformedRequest1", + this.transformedRequest1, this.httpRequestCaptor.getValue()); } @Test public void testTwoTransformers() throws Exception { - List transformers = Arrays.asList(transformer1, transformer2); - when(transformer1.transformRequest(any(ServiceRequestWrapper.class), eq(instance))).thenReturn(transformedRequest1); - when(transformer2.transformRequest(transformedRequest1, instance)) - .thenReturn(transformedRequest2); + List transformers = Arrays + .asList(this.transformer1, this.transformer2); + when(this.transformer1.transformRequest(any(ServiceRequestWrapper.class), + eq(this.instance))).thenReturn(this.transformedRequest1); + when(this.transformer2.transformRequest(this.transformedRequest1, this.instance)) + .thenReturn(this.transformedRequest2); executeLbRequest(transformers); - verify(execution).execute(httpRequestCaptor.capture(), eq(body)); - assertEquals("transformer2 should have transformed transformedRequest1 into transformedRequest2", - transformedRequest2, - httpRequestCaptor.getValue()); + verify(this.execution).execute(this.httpRequestCaptor.capture(), eq(this.body)); + assertEquals( + "transformer2 should have transformed transformedRequest1 into transformedRequest2", + this.transformedRequest2, this.httpRequestCaptor.getValue()); } - private void executeLbRequest(List transformers) throws Exception { - LoadBalancerRequestFactory lbReqFactory = new LoadBalancerRequestFactory(loadBalancer, transformers); - LoadBalancerRequest lbRequest = lbReqFactory.createRequest(request, body, execution); - lbRequest.apply(instance); + private void executeLbRequest(List transformers) + throws Exception { + LoadBalancerRequestFactory lbReqFactory = new LoadBalancerRequestFactory( + this.loadBalancer, transformers); + LoadBalancerRequest lbRequest = lbReqFactory + .createRequest(this.request, this.body, this.execution); + lbRequest.apply(this.instance); } } diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/RetryLoadBalancerAutoConfigurationTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/RetryLoadBalancerAutoConfigurationTests.java index cb395f4a..ab7f8632 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/RetryLoadBalancerAutoConfigurationTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/RetryLoadBalancerAutoConfigurationTests.java @@ -3,6 +3,7 @@ package org.springframework.cloud.client.loadbalancer; import java.util.List; import org.junit.Test; + import org.springframework.context.ConfigurableApplicationContext; import org.springframework.http.client.ClientHttpRequestInterceptor; import org.springframework.retry.backoff.NoBackOffPolicy; @@ -16,7 +17,9 @@ import static org.hamcrest.Matchers.is; /** * @author Ryan Baxter */ -public class RetryLoadBalancerAutoConfigurationTests extends AbstractLoadBalancerAutoConfigurationTests { +public class RetryLoadBalancerAutoConfigurationTests + extends AbstractLoadBalancerAutoConfigurationTests { + @Override protected void assertLoadBalanced(RestTemplate restTemplate) { List interceptors = restTemplate.getInterceptors(); @@ -28,9 +31,12 @@ public class RetryLoadBalancerAutoConfigurationTests extends AbstractLoadBalance @Test public void testDefaultBackOffPolicy() throws Exception { ConfigurableApplicationContext context = init(OneRestTemplate.class); - LoadBalancedRetryFactory loadBalancedRetryFactory = context.getBean(LoadBalancedRetryFactory.class); - assertThat(loadBalancedRetryFactory, is(instanceOf(LoadBalancedRetryFactory.class))); - assertThat(loadBalancedRetryFactory.createBackOffPolicy("foo"), is(instanceOf(NoBackOffPolicy.class))); + LoadBalancedRetryFactory loadBalancedRetryFactory = context + .getBean(LoadBalancedRetryFactory.class); + assertThat(loadBalancedRetryFactory, + is(instanceOf(LoadBalancedRetryFactory.class))); + assertThat(loadBalancedRetryFactory.createBackOffPolicy("foo"), + is(instanceOf(NoBackOffPolicy.class))); } -} +} diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/RetryLoadBalancerInterceptorTest.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/RetryLoadBalancerInterceptorTest.java index 7563daea..c48879ae 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/RetryLoadBalancerInterceptorTest.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/RetryLoadBalancerInterceptorTest.java @@ -4,24 +4,24 @@ import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URI; + import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentMatchers; import org.mockito.junit.MockitoJUnitRunner; + import org.springframework.cloud.client.ServiceInstance; import org.springframework.http.HttpRequest; import org.springframework.http.HttpStatus; import org.springframework.http.client.ClientHttpRequestExecution; import org.springframework.http.client.ClientHttpResponse; import org.springframework.mock.http.client.MockClientHttpResponse; - import org.springframework.retry.RetryCallback; import org.springframework.retry.RetryContext; import org.springframework.retry.RetryListener; import org.springframework.retry.TerminatedRetryException; - import org.springframework.retry.backoff.BackOffContext; import org.springframework.retry.backoff.BackOffInterruptedException; import org.springframework.retry.backoff.BackOffPolicy; @@ -45,349 +45,423 @@ import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class RetryLoadBalancerInterceptorTest { - private LoadBalancerClient client; - private LoadBalancerRetryProperties lbProperties; - private LoadBalancerRequestFactory lbRequestFactory; - private LoadBalancedRetryFactory loadBalancedRetryFactory = new LoadBalancedRetryFactory(){}; + private LoadBalancerClient client; - @Before - public void setUp() throws Exception { - client = mock(LoadBalancerClient.class); - lbProperties = new LoadBalancerRetryProperties(); - lbRequestFactory = mock(LoadBalancerRequestFactory.class); + private LoadBalancerRetryProperties lbProperties; - } + private LoadBalancerRequestFactory lbRequestFactory; - @After - public void tearDown() throws Exception { - client = null; - lbProperties = null; - } + private LoadBalancedRetryFactory loadBalancedRetryFactory = new LoadBalancedRetryFactory() { + }; - @Test(expected = IOException.class) - public void interceptDisableRetry() throws Throwable { - HttpRequest request = mock(HttpRequest.class); - when(request.getURI()).thenReturn(new URI("http://foo")); - ServiceInstance serviceInstance = mock(ServiceInstance.class); - when(client.choose(eq("foo"))).thenReturn(serviceInstance); - when(client.execute(eq("foo"), eq(serviceInstance), any(LoadBalancerRequest.class))).thenThrow(new IOException()); - lbProperties.setEnabled(false); - RetryLoadBalancerInterceptor interceptor = new RetryLoadBalancerInterceptor(client, lbProperties, - lbRequestFactory, loadBalancedRetryFactory); - byte[] body = new byte[]{}; - ClientHttpRequestExecution execution = mock(ClientHttpRequestExecution.class); + @Before + public void setUp() throws Exception { + this.client = mock(LoadBalancerClient.class); + this.lbProperties = new LoadBalancerRetryProperties(); + this.lbRequestFactory = mock(LoadBalancerRequestFactory.class); - when(this.lbRequestFactory.createRequest(any(), any(), any())).thenReturn(mock(LoadBalancerRequest.class)); + } - interceptor.intercept(request, body, execution); - verify(lbRequestFactory).createRequest(request, body, execution); - } + @After + public void tearDown() throws Exception { + this.client = null; + this.lbProperties = null; + } - @Test(expected = IllegalStateException.class) - public void interceptInvalidHost() throws Throwable { - HttpRequest request = mock(HttpRequest.class); - when(request.getURI()).thenReturn(new URI("http://foo_underscore")); - lbProperties.setEnabled(true); - RetryLoadBalancerInterceptor interceptor = new RetryLoadBalancerInterceptor(client, lbProperties, lbRequestFactory, - loadBalancedRetryFactory); - byte[] body = new byte[]{}; - ClientHttpRequestExecution execution = mock(ClientHttpRequestExecution.class); - interceptor.intercept(request, body, execution); - } + @Test(expected = IOException.class) + public void interceptDisableRetry() throws Throwable { + HttpRequest request = mock(HttpRequest.class); + when(request.getURI()).thenReturn(new URI("http://foo")); + ServiceInstance serviceInstance = mock(ServiceInstance.class); + when(this.client.choose(eq("foo"))).thenReturn(serviceInstance); + when(this.client.execute(eq("foo"), eq(serviceInstance), + any(LoadBalancerRequest.class))).thenThrow(new IOException()); + this.lbProperties.setEnabled(false); + RetryLoadBalancerInterceptor interceptor = new RetryLoadBalancerInterceptor( + this.client, this.lbProperties, this.lbRequestFactory, + this.loadBalancedRetryFactory); + byte[] body = new byte[] {}; + ClientHttpRequestExecution execution = mock(ClientHttpRequestExecution.class); - @Test - public void interceptNeverRetry() throws Throwable { - HttpRequest request = mock(HttpRequest.class); - when(request.getURI()).thenReturn(new URI("http://foo")); - ClientHttpResponse clientHttpResponse = new MockClientHttpResponse(new byte[]{}, HttpStatus.OK); - ServiceInstance serviceInstance = mock(ServiceInstance.class); - when(client.choose(eq("foo"))).thenReturn(serviceInstance); - when(client.execute(eq("foo"), eq(serviceInstance), any(LoadBalancerRequest.class))).thenReturn(clientHttpResponse); - when(this.lbRequestFactory.createRequest(any(), any(), any())).thenReturn(mock(LoadBalancerRequest.class)); - lbProperties.setEnabled(true); - RetryLoadBalancerInterceptor interceptor = new RetryLoadBalancerInterceptor(client, lbProperties, - lbRequestFactory, loadBalancedRetryFactory); - byte[] body = new byte[]{}; - ClientHttpRequestExecution execution = mock(ClientHttpRequestExecution.class); - interceptor.intercept(request, body, execution); - verify(lbRequestFactory).createRequest(request, body, execution); - } + when(this.lbRequestFactory.createRequest(any(), any(), any())) + .thenReturn(mock(LoadBalancerRequest.class)); - @Test - public void interceptSuccess() throws Throwable { - HttpRequest request = mock(HttpRequest.class); - when(request.getURI()).thenReturn(new URI("http://foo")); - ClientHttpResponse clientHttpResponse = new MockClientHttpResponse(new byte[]{}, HttpStatus.OK); - LoadBalancedRetryPolicy policy = mock(LoadBalancedRetryPolicy.class); - ServiceInstance serviceInstance = mock(ServiceInstance.class); - when(client.choose(eq("foo"))).thenReturn(serviceInstance); - when(client.execute(eq("foo"), eq(serviceInstance), any(LoadBalancerRequest.class))).thenReturn(clientHttpResponse); - when(this.lbRequestFactory.createRequest(any(), any(), any())).thenReturn(mock(LoadBalancerRequest.class)); - lbProperties.setEnabled(true); - RetryLoadBalancerInterceptor interceptor = new RetryLoadBalancerInterceptor(client, lbProperties, - lbRequestFactory, new MyLoadBalancedRetryFactory(policy)); - byte[] body = new byte[]{}; - ClientHttpRequestExecution execution = mock(ClientHttpRequestExecution.class); - ClientHttpResponse rsp = interceptor.intercept(request, body, execution); - assertThat(rsp, is(clientHttpResponse)); - verify(lbRequestFactory).createRequest(request, body, execution); - } + interceptor.intercept(request, body, execution); + verify(this.lbRequestFactory).createRequest(request, body, execution); + } - @Test - public void interceptRetryOnStatusCode() throws Throwable { - HttpRequest request = mock(HttpRequest.class); - when(request.getURI()).thenReturn(new URI("http://foo")); - InputStream notFoundStream = mock(InputStream.class); - when(notFoundStream.read(any(byte[].class))).thenReturn(-1); - ClientHttpResponse clientHttpResponseNotFound = new MockClientHttpResponse(notFoundStream, HttpStatus.NOT_FOUND); - ClientHttpResponse clientHttpResponseOk = new MockClientHttpResponse(new byte[]{}, HttpStatus.OK); - LoadBalancedRetryPolicy policy = mock(LoadBalancedRetryPolicy.class); - when(policy.retryableStatusCode(eq(HttpStatus.NOT_FOUND.value()))).thenReturn(true); - when(policy.canRetryNextServer(any(LoadBalancedRetryContext.class))).thenReturn(true); - ServiceInstance serviceInstance = mock(ServiceInstance.class); - when(client.choose(eq("foo"))).thenReturn(serviceInstance); - when(client.execute(eq("foo"), eq(serviceInstance), nullable(LoadBalancerRequest.class))). - thenReturn(clientHttpResponseNotFound).thenReturn(clientHttpResponseOk); - lbProperties.setEnabled(true); - RetryLoadBalancerInterceptor interceptor = new RetryLoadBalancerInterceptor(client, lbProperties, - lbRequestFactory, new MyLoadBalancedRetryFactory(policy)); - byte[] body = new byte[]{}; - ClientHttpRequestExecution execution = mock(ClientHttpRequestExecution.class); - ClientHttpResponse rsp = interceptor.intercept(request, body, execution); - verify(client, times(2)).execute(eq("foo"), eq(serviceInstance), nullable(LoadBalancerRequest.class)); - verify(notFoundStream, times(1)).close(); - assertThat(rsp, is(clientHttpResponseOk)); - verify(lbRequestFactory, times(2)).createRequest(request, body, execution); - } + @Test(expected = IllegalStateException.class) + public void interceptInvalidHost() throws Throwable { + HttpRequest request = mock(HttpRequest.class); + when(request.getURI()).thenReturn(new URI("http://foo_underscore")); + this.lbProperties.setEnabled(true); + RetryLoadBalancerInterceptor interceptor = new RetryLoadBalancerInterceptor( + this.client, this.lbProperties, this.lbRequestFactory, + this.loadBalancedRetryFactory); + byte[] body = new byte[] {}; + ClientHttpRequestExecution execution = mock(ClientHttpRequestExecution.class); + interceptor.intercept(request, body, execution); + } - @Test - public void interceptRetryFailOnStatusCode() throws Throwable { - HttpRequest request = mock(HttpRequest.class); - when(request.getURI()).thenReturn(new URI("http://foo")); + @Test + public void interceptNeverRetry() throws Throwable { + HttpRequest request = mock(HttpRequest.class); + when(request.getURI()).thenReturn(new URI("http://foo")); + ClientHttpResponse clientHttpResponse = new MockClientHttpResponse(new byte[] {}, + HttpStatus.OK); + ServiceInstance serviceInstance = mock(ServiceInstance.class); + when(this.client.choose(eq("foo"))).thenReturn(serviceInstance); + when(this.client.execute(eq("foo"), eq(serviceInstance), + any(LoadBalancerRequest.class))).thenReturn(clientHttpResponse); + when(this.lbRequestFactory.createRequest(any(), any(), any())) + .thenReturn(mock(LoadBalancerRequest.class)); + this.lbProperties.setEnabled(true); + RetryLoadBalancerInterceptor interceptor = new RetryLoadBalancerInterceptor( + this.client, this.lbProperties, this.lbRequestFactory, + this.loadBalancedRetryFactory); + byte[] body = new byte[] {}; + ClientHttpRequestExecution execution = mock(ClientHttpRequestExecution.class); + interceptor.intercept(request, body, execution); + verify(this.lbRequestFactory).createRequest(request, body, execution); + } - InputStream notFoundStream = new ByteArrayInputStream("foo".getBytes()); - ClientHttpResponse clientHttpResponseNotFound = new MockClientHttpResponse(notFoundStream, HttpStatus.NOT_FOUND); + @Test + public void interceptSuccess() throws Throwable { + HttpRequest request = mock(HttpRequest.class); + when(request.getURI()).thenReturn(new URI("http://foo")); + ClientHttpResponse clientHttpResponse = new MockClientHttpResponse(new byte[] {}, + HttpStatus.OK); + LoadBalancedRetryPolicy policy = mock(LoadBalancedRetryPolicy.class); + ServiceInstance serviceInstance = mock(ServiceInstance.class); + when(this.client.choose(eq("foo"))).thenReturn(serviceInstance); + when(this.client.execute(eq("foo"), eq(serviceInstance), + any(LoadBalancerRequest.class))).thenReturn(clientHttpResponse); + when(this.lbRequestFactory.createRequest(any(), any(), any())) + .thenReturn(mock(LoadBalancerRequest.class)); + this.lbProperties.setEnabled(true); + RetryLoadBalancerInterceptor interceptor = new RetryLoadBalancerInterceptor( + this.client, this.lbProperties, this.lbRequestFactory, + new MyLoadBalancedRetryFactory(policy)); + byte[] body = new byte[] {}; + ClientHttpRequestExecution execution = mock(ClientHttpRequestExecution.class); + ClientHttpResponse rsp = interceptor.intercept(request, body, execution); + assertThat(rsp, is(clientHttpResponse)); + verify(this.lbRequestFactory).createRequest(request, body, execution); + } - LoadBalancedRetryPolicy policy = mock(LoadBalancedRetryPolicy.class); - when(policy.retryableStatusCode(eq(HttpStatus.NOT_FOUND.value()))).thenReturn(true); - when(policy.canRetryNextServer(any(LoadBalancedRetryContext.class))).thenReturn(false); + @Test + public void interceptRetryOnStatusCode() throws Throwable { + HttpRequest request = mock(HttpRequest.class); + when(request.getURI()).thenReturn(new URI("http://foo")); + InputStream notFoundStream = mock(InputStream.class); + when(notFoundStream.read(any(byte[].class))).thenReturn(-1); + ClientHttpResponse clientHttpResponseNotFound = new MockClientHttpResponse( + notFoundStream, HttpStatus.NOT_FOUND); + ClientHttpResponse clientHttpResponseOk = new MockClientHttpResponse( + new byte[] {}, HttpStatus.OK); + LoadBalancedRetryPolicy policy = mock(LoadBalancedRetryPolicy.class); + when(policy.retryableStatusCode(eq(HttpStatus.NOT_FOUND.value()))) + .thenReturn(true); + when(policy.canRetryNextServer(any(LoadBalancedRetryContext.class))) + .thenReturn(true); + ServiceInstance serviceInstance = mock(ServiceInstance.class); + when(this.client.choose(eq("foo"))).thenReturn(serviceInstance); + when(this.client.execute(eq("foo"), eq(serviceInstance), + nullable(LoadBalancerRequest.class))) + .thenReturn(clientHttpResponseNotFound) + .thenReturn(clientHttpResponseOk); + this.lbProperties.setEnabled(true); + RetryLoadBalancerInterceptor interceptor = new RetryLoadBalancerInterceptor( + this.client, this.lbProperties, this.lbRequestFactory, + new MyLoadBalancedRetryFactory(policy)); + byte[] body = new byte[] {}; + ClientHttpRequestExecution execution = mock(ClientHttpRequestExecution.class); + ClientHttpResponse rsp = interceptor.intercept(request, body, execution); + verify(this.client, times(2)).execute(eq("foo"), eq(serviceInstance), + nullable(LoadBalancerRequest.class)); + verify(notFoundStream, times(1)).close(); + assertThat(rsp, is(clientHttpResponseOk)); + verify(this.lbRequestFactory, times(2)).createRequest(request, body, execution); + } - ServiceInstance serviceInstance = mock(ServiceInstance.class); - when(client.choose(eq("foo"))).thenReturn(serviceInstance); - when(client.execute(eq("foo"), eq(serviceInstance), ArgumentMatchers.>any())) - .thenReturn(clientHttpResponseNotFound); + @Test + public void interceptRetryFailOnStatusCode() throws Throwable { + HttpRequest request = mock(HttpRequest.class); + when(request.getURI()).thenReturn(new URI("http://foo")); - lbProperties.setEnabled(true); - byte[] body = new byte[]{}; - ClientHttpRequestExecution execution = mock(ClientHttpRequestExecution.class); - RetryLoadBalancerInterceptor interceptor = new RetryLoadBalancerInterceptor(client, lbProperties, - lbRequestFactory, new MyLoadBalancedRetryFactory(policy)); - ClientHttpResponse rsp = interceptor.intercept(request, body, execution); + InputStream notFoundStream = new ByteArrayInputStream("foo".getBytes()); + ClientHttpResponse clientHttpResponseNotFound = new MockClientHttpResponse( + notFoundStream, HttpStatus.NOT_FOUND); - verify(client, times(1)).execute(eq("foo"), eq(serviceInstance), - ArgumentMatchers.>any()); - verify(lbRequestFactory, times(1)).createRequest(request, body, execution); - verify(policy, times(2)).canRetryNextServer(any(LoadBalancedRetryContext.class)); + LoadBalancedRetryPolicy policy = mock(LoadBalancedRetryPolicy.class); + when(policy.retryableStatusCode(eq(HttpStatus.NOT_FOUND.value()))) + .thenReturn(true); + when(policy.canRetryNextServer(any(LoadBalancedRetryContext.class))) + .thenReturn(false); - //call twice in a retry attempt - byte[] content = new byte[1024]; - int length = rsp.getBody().read(content); - assertThat(length, is("foo".getBytes().length)); - assertThat(new String(content, 0, length), is("foo")); - } + ServiceInstance serviceInstance = mock(ServiceInstance.class); + when(this.client.choose(eq("foo"))).thenReturn(serviceInstance); + when(this.client.execute(eq("foo"), eq(serviceInstance), + ArgumentMatchers.>any())) + .thenReturn(clientHttpResponseNotFound); - @Test - public void interceptRetry() throws Throwable { - HttpRequest request = mock(HttpRequest.class); - when(request.getURI()).thenReturn(new URI("http://foo")); - ClientHttpResponse clientHttpResponse = new MockClientHttpResponse(new byte[]{}, HttpStatus.OK); - LoadBalancedRetryPolicy policy = mock(LoadBalancedRetryPolicy.class); - when(policy.canRetryNextServer(any(LoadBalancedRetryContext.class))).thenReturn(true); - MyBackOffPolicy backOffPolicy = new MyBackOffPolicy(); - ServiceInstance serviceInstance = mock(ServiceInstance.class); - when(client.choose(eq("foo"))).thenReturn(serviceInstance); - when(client.execute(eq("foo"), eq(serviceInstance), any(LoadBalancerRequest.class))).thenThrow(new IOException()).thenReturn(clientHttpResponse); - when(this.lbRequestFactory.createRequest(any(), any(), any())).thenReturn(mock(LoadBalancerRequest.class)); - lbProperties.setEnabled(true); - RetryLoadBalancerInterceptor interceptor = new RetryLoadBalancerInterceptor(client, lbProperties, lbRequestFactory, - new MyLoadBalancedRetryFactory(policy, backOffPolicy)); - byte[] body = new byte[]{}; - ClientHttpRequestExecution execution = mock(ClientHttpRequestExecution.class); - ClientHttpResponse rsp = interceptor.intercept(request, body, execution); - verify(client, times(2)).execute(eq("foo"), eq(serviceInstance), any(LoadBalancerRequest.class)); - assertThat(rsp, is(clientHttpResponse)); - verify(lbRequestFactory, times(2)).createRequest(request, body, execution); - assertThat(backOffPolicy.getBackoffAttempts(), is(1)); - } + this.lbProperties.setEnabled(true); + byte[] body = new byte[] {}; + ClientHttpRequestExecution execution = mock(ClientHttpRequestExecution.class); + RetryLoadBalancerInterceptor interceptor = new RetryLoadBalancerInterceptor( + this.client, this.lbProperties, this.lbRequestFactory, + new MyLoadBalancedRetryFactory(policy)); + ClientHttpResponse rsp = interceptor.intercept(request, body, execution); - @Test(expected = IOException.class) - public void interceptFailedRetry() throws Exception { - HttpRequest request = mock(HttpRequest.class); - when(request.getURI()).thenReturn(new URI("http://foo")); - ClientHttpResponse clientHttpResponse = new MockClientHttpResponse(new byte[]{}, HttpStatus.OK); - LoadBalancedRetryPolicy policy = mock(LoadBalancedRetryPolicy.class); - when(policy.canRetryNextServer(any(LoadBalancedRetryContext.class))).thenReturn(false); - ServiceInstance serviceInstance = mock(ServiceInstance.class); - when(client.choose(eq("foo"))).thenReturn(serviceInstance); - when(client.execute(eq("foo"), eq(serviceInstance), any(LoadBalancerRequest.class))).thenThrow(new IOException()).thenReturn(clientHttpResponse); - when(this.lbRequestFactory.createRequest(any(), any(), any())).thenReturn(mock(LoadBalancerRequest.class)); - lbProperties.setEnabled(true); - RetryLoadBalancerInterceptor interceptor = new RetryLoadBalancerInterceptor(client, lbProperties, - lbRequestFactory, new MyLoadBalancedRetryFactory(policy)); - byte[] body = new byte[]{}; - ClientHttpRequestExecution execution = mock(ClientHttpRequestExecution.class); - interceptor.intercept(request, body, execution); - verify(lbRequestFactory).createRequest(request, body, execution); - } + verify(this.client, times(1)).execute(eq("foo"), eq(serviceInstance), + ArgumentMatchers.>any()); + verify(this.lbRequestFactory, times(1)).createRequest(request, body, execution); + verify(policy, times(2)).canRetryNextServer(any(LoadBalancedRetryContext.class)); - @Test - public void retryListenerTest() throws Throwable { - HttpRequest request = mock(HttpRequest.class); - when(request.getURI()).thenReturn(new URI("http://listener")); - ClientHttpResponse clientHttpResponse = new MockClientHttpResponse(new byte[]{}, HttpStatus.OK); - LoadBalancedRetryPolicy policy = mock(LoadBalancedRetryPolicy.class); - when(policy.canRetryNextServer(any(LoadBalancedRetryContext.class))).thenReturn(true); - MyBackOffPolicy backOffPolicy = new MyBackOffPolicy(); - ServiceInstance serviceInstance = mock(ServiceInstance.class); - when(client.choose(eq("listener"))).thenReturn(serviceInstance); - when(client.execute(eq("listener"), eq(serviceInstance), any(LoadBalancerRequest.class))).thenThrow(new IOException()).thenReturn(clientHttpResponse); - lbProperties.setEnabled(true); - MyRetryListener retryListener = new MyRetryListener(); - when(this.lbRequestFactory.createRequest(any(), any(), any())).thenReturn(mock(LoadBalancerRequest.class)); - RetryLoadBalancerInterceptor interceptor = new RetryLoadBalancerInterceptor(client, lbProperties, lbRequestFactory, - new MyLoadBalancedRetryFactory(policy, backOffPolicy, new RetryListener[]{retryListener})); - byte[] body = new byte[]{}; - ClientHttpRequestExecution execution = mock(ClientHttpRequestExecution.class); - ClientHttpResponse rsp = interceptor.intercept(request, body, execution); - verify(client, times(2)).execute(eq("listener"), eq(serviceInstance), any(LoadBalancerRequest.class)); - assertThat(rsp, is(clientHttpResponse)); - verify(lbRequestFactory, times(2)).createRequest(request, body, execution); - assertThat(backOffPolicy.getBackoffAttempts(), is(1)); - assertThat(retryListener.getOnError(), is(1)); - } + // call twice in a retry attempt + byte[] content = new byte[1024]; + int length = rsp.getBody().read(content); + assertThat(length, is("foo".getBytes().length)); + assertThat(new String(content, 0, length), is("foo")); + } - @Test(expected = TerminatedRetryException.class) - public void retryListenerTestNoRetry() throws Throwable { - HttpRequest request = mock(HttpRequest.class); - when(request.getURI()).thenReturn(new URI("http://noRetry")); - LoadBalancedRetryPolicy policy = mock(LoadBalancedRetryPolicy.class); - MyBackOffPolicy backOffPolicy = new MyBackOffPolicy(); - lbProperties.setEnabled(true); - RetryListener myRetryListener = new RetryListenerSupport(){ - @Override - public boolean open(RetryContext context, RetryCallback callback) { - return false; - } - }; - RetryLoadBalancerInterceptor interceptor = new RetryLoadBalancerInterceptor(client, lbProperties, lbRequestFactory, - new MyLoadBalancedRetryFactory(policy, backOffPolicy, new RetryListener[]{myRetryListener})); - ClientHttpRequestExecution execution = mock(ClientHttpRequestExecution.class); - interceptor.intercept(request, new byte[]{}, execution); - } + @Test + public void interceptRetry() throws Throwable { + HttpRequest request = mock(HttpRequest.class); + when(request.getURI()).thenReturn(new URI("http://foo")); + ClientHttpResponse clientHttpResponse = new MockClientHttpResponse(new byte[] {}, + HttpStatus.OK); + LoadBalancedRetryPolicy policy = mock(LoadBalancedRetryPolicy.class); + when(policy.canRetryNextServer(any(LoadBalancedRetryContext.class))) + .thenReturn(true); + MyBackOffPolicy backOffPolicy = new MyBackOffPolicy(); + ServiceInstance serviceInstance = mock(ServiceInstance.class); + when(this.client.choose(eq("foo"))).thenReturn(serviceInstance); + when(this.client.execute(eq("foo"), eq(serviceInstance), + any(LoadBalancerRequest.class))).thenThrow(new IOException()) + .thenReturn(clientHttpResponse); + when(this.lbRequestFactory.createRequest(any(), any(), any())) + .thenReturn(mock(LoadBalancerRequest.class)); + this.lbProperties.setEnabled(true); + RetryLoadBalancerInterceptor interceptor = new RetryLoadBalancerInterceptor( + this.client, this.lbProperties, this.lbRequestFactory, + new MyLoadBalancedRetryFactory(policy, backOffPolicy)); + byte[] body = new byte[] {}; + ClientHttpRequestExecution execution = mock(ClientHttpRequestExecution.class); + ClientHttpResponse rsp = interceptor.intercept(request, body, execution); + verify(this.client, times(2)).execute(eq("foo"), eq(serviceInstance), + any(LoadBalancerRequest.class)); + assertThat(rsp, is(clientHttpResponse)); + verify(this.lbRequestFactory, times(2)).createRequest(request, body, execution); + assertThat(backOffPolicy.getBackoffAttempts(), is(1)); + } - @Test - public void retryWithDefaultConstructorTest() throws Throwable { - HttpRequest request = mock(HttpRequest.class); - when(request.getURI()).thenReturn(new URI("http://default")); - ClientHttpResponse clientHttpResponse = new MockClientHttpResponse(new byte[]{}, HttpStatus.OK); - LoadBalancedRetryPolicy policy = mock(LoadBalancedRetryPolicy.class); - when(policy.canRetryNextServer(any(LoadBalancedRetryContext.class))).thenReturn(true); - MyBackOffPolicy backOffPolicy = new MyBackOffPolicy(); - ServiceInstance serviceInstance = mock(ServiceInstance.class); - when(client.choose(eq("default"))).thenReturn(serviceInstance); - when(client.execute(eq("default"), eq(serviceInstance), any(LoadBalancerRequest.class))).thenThrow(new IOException()).thenReturn(clientHttpResponse); - lbProperties.setEnabled(true); - when(this.lbRequestFactory.createRequest(any(), any(), any())).thenReturn(mock(LoadBalancerRequest.class)); - RetryLoadBalancerInterceptor interceptor = new RetryLoadBalancerInterceptor(client, lbProperties, lbRequestFactory, - new MyLoadBalancedRetryFactory(policy, backOffPolicy)); - byte[] body = new byte[]{}; - ClientHttpRequestExecution execution = mock(ClientHttpRequestExecution.class); - ClientHttpResponse rsp = interceptor.intercept(request, body, execution); - verify(client, times(2)).execute(eq("default"), eq(serviceInstance), any(LoadBalancerRequest.class)); - assertThat(rsp, is(clientHttpResponse)); - verify(lbRequestFactory, times(2)).createRequest(request, body, execution); - assertThat(backOffPolicy.getBackoffAttempts(), is(1)); - } + @Test(expected = IOException.class) + public void interceptFailedRetry() throws Exception { + HttpRequest request = mock(HttpRequest.class); + when(request.getURI()).thenReturn(new URI("http://foo")); + ClientHttpResponse clientHttpResponse = new MockClientHttpResponse(new byte[] {}, + HttpStatus.OK); + LoadBalancedRetryPolicy policy = mock(LoadBalancedRetryPolicy.class); + when(policy.canRetryNextServer(any(LoadBalancedRetryContext.class))) + .thenReturn(false); + ServiceInstance serviceInstance = mock(ServiceInstance.class); + when(this.client.choose(eq("foo"))).thenReturn(serviceInstance); + when(this.client.execute(eq("foo"), eq(serviceInstance), + any(LoadBalancerRequest.class))).thenThrow(new IOException()) + .thenReturn(clientHttpResponse); + when(this.lbRequestFactory.createRequest(any(), any(), any())) + .thenReturn(mock(LoadBalancerRequest.class)); + this.lbProperties.setEnabled(true); + RetryLoadBalancerInterceptor interceptor = new RetryLoadBalancerInterceptor( + this.client, this.lbProperties, this.lbRequestFactory, + new MyLoadBalancedRetryFactory(policy)); + byte[] body = new byte[] {}; + ClientHttpRequestExecution execution = mock(ClientHttpRequestExecution.class); + interceptor.intercept(request, body, execution); + verify(this.lbRequestFactory).createRequest(request, body, execution); + } - class MyLoadBalancedRetryFactory implements LoadBalancedRetryFactory { - private LoadBalancedRetryPolicy loadBalancedRetryPolicy; - private BackOffPolicy backOffPolicy; - private RetryListener[] retryListeners; + @Test + public void retryListenerTest() throws Throwable { + HttpRequest request = mock(HttpRequest.class); + when(request.getURI()).thenReturn(new URI("http://listener")); + ClientHttpResponse clientHttpResponse = new MockClientHttpResponse(new byte[] {}, + HttpStatus.OK); + LoadBalancedRetryPolicy policy = mock(LoadBalancedRetryPolicy.class); + when(policy.canRetryNextServer(any(LoadBalancedRetryContext.class))) + .thenReturn(true); + MyBackOffPolicy backOffPolicy = new MyBackOffPolicy(); + ServiceInstance serviceInstance = mock(ServiceInstance.class); + when(this.client.choose(eq("listener"))).thenReturn(serviceInstance); + when(this.client.execute(eq("listener"), eq(serviceInstance), + any(LoadBalancerRequest.class))).thenThrow(new IOException()) + .thenReturn(clientHttpResponse); + this.lbProperties.setEnabled(true); + MyRetryListener retryListener = new MyRetryListener(); + when(this.lbRequestFactory.createRequest(any(), any(), any())) + .thenReturn(mock(LoadBalancerRequest.class)); + RetryLoadBalancerInterceptor interceptor = new RetryLoadBalancerInterceptor( + this.client, this.lbProperties, this.lbRequestFactory, + new MyLoadBalancedRetryFactory(policy, backOffPolicy, + new RetryListener[] { retryListener })); + byte[] body = new byte[] {}; + ClientHttpRequestExecution execution = mock(ClientHttpRequestExecution.class); + ClientHttpResponse rsp = interceptor.intercept(request, body, execution); + verify(this.client, times(2)).execute(eq("listener"), eq(serviceInstance), + any(LoadBalancerRequest.class)); + assertThat(rsp, is(clientHttpResponse)); + verify(this.lbRequestFactory, times(2)).createRequest(request, body, execution); + assertThat(backOffPolicy.getBackoffAttempts(), is(1)); + assertThat(retryListener.getOnError(), is(1)); + } - public MyLoadBalancedRetryFactory(LoadBalancedRetryPolicy loadBalancedRetryPolicy) { - this.loadBalancedRetryPolicy = loadBalancedRetryPolicy; - } + @Test(expected = TerminatedRetryException.class) + public void retryListenerTestNoRetry() throws Throwable { + HttpRequest request = mock(HttpRequest.class); + when(request.getURI()).thenReturn(new URI("http://noRetry")); + LoadBalancedRetryPolicy policy = mock(LoadBalancedRetryPolicy.class); + MyBackOffPolicy backOffPolicy = new MyBackOffPolicy(); + this.lbProperties.setEnabled(true); + RetryListener myRetryListener = new RetryListenerSupport() { + @Override + public boolean open(RetryContext context, + RetryCallback callback) { + return false; + } + }; + RetryLoadBalancerInterceptor interceptor = new RetryLoadBalancerInterceptor( + this.client, this.lbProperties, this.lbRequestFactory, + new MyLoadBalancedRetryFactory(policy, backOffPolicy, + new RetryListener[] { myRetryListener })); + ClientHttpRequestExecution execution = mock(ClientHttpRequestExecution.class); + interceptor.intercept(request, new byte[] {}, execution); + } - public MyLoadBalancedRetryFactory(LoadBalancedRetryPolicy loadBalancedRetryPolicy, BackOffPolicy backOffPolicy) { - this(loadBalancedRetryPolicy); - this.backOffPolicy = backOffPolicy; + @Test + public void retryWithDefaultConstructorTest() throws Throwable { + HttpRequest request = mock(HttpRequest.class); + when(request.getURI()).thenReturn(new URI("http://default")); + ClientHttpResponse clientHttpResponse = new MockClientHttpResponse(new byte[] {}, + HttpStatus.OK); + LoadBalancedRetryPolicy policy = mock(LoadBalancedRetryPolicy.class); + when(policy.canRetryNextServer(any(LoadBalancedRetryContext.class))) + .thenReturn(true); + MyBackOffPolicy backOffPolicy = new MyBackOffPolicy(); + ServiceInstance serviceInstance = mock(ServiceInstance.class); + when(this.client.choose(eq("default"))).thenReturn(serviceInstance); + when(this.client.execute(eq("default"), eq(serviceInstance), + any(LoadBalancerRequest.class))).thenThrow(new IOException()) + .thenReturn(clientHttpResponse); + this.lbProperties.setEnabled(true); + when(this.lbRequestFactory.createRequest(any(), any(), any())) + .thenReturn(mock(LoadBalancerRequest.class)); + RetryLoadBalancerInterceptor interceptor = new RetryLoadBalancerInterceptor( + this.client, this.lbProperties, this.lbRequestFactory, + new MyLoadBalancedRetryFactory(policy, backOffPolicy)); + byte[] body = new byte[] {}; + ClientHttpRequestExecution execution = mock(ClientHttpRequestExecution.class); + ClientHttpResponse rsp = interceptor.intercept(request, body, execution); + verify(this.client, times(2)).execute(eq("default"), eq(serviceInstance), + any(LoadBalancerRequest.class)); + assertThat(rsp, is(clientHttpResponse)); + verify(this.lbRequestFactory, times(2)).createRequest(request, body, execution); + assertThat(backOffPolicy.getBackoffAttempts(), is(1)); + } + + class MyLoadBalancedRetryFactory implements LoadBalancedRetryFactory { + + private LoadBalancedRetryPolicy loadBalancedRetryPolicy; + + private BackOffPolicy backOffPolicy; + + private RetryListener[] retryListeners; + + public MyLoadBalancedRetryFactory( + LoadBalancedRetryPolicy loadBalancedRetryPolicy) { + this.loadBalancedRetryPolicy = loadBalancedRetryPolicy; } - public MyLoadBalancedRetryFactory(LoadBalancedRetryPolicy loadBalancedRetryPolicy, BackOffPolicy backOffPolicy, - RetryListener[] retryListeners) { - this(loadBalancedRetryPolicy, backOffPolicy); - this.retryListeners = retryListeners; + public MyLoadBalancedRetryFactory(LoadBalancedRetryPolicy loadBalancedRetryPolicy, + BackOffPolicy backOffPolicy) { + this(loadBalancedRetryPolicy); + this.backOffPolicy = backOffPolicy; } - @Override - public LoadBalancedRetryPolicy createRetryPolicy(String service, ServiceInstanceChooser serviceInstanceChooser) { - return loadBalancedRetryPolicy; - } + public MyLoadBalancedRetryFactory(LoadBalancedRetryPolicy loadBalancedRetryPolicy, + BackOffPolicy backOffPolicy, RetryListener[] retryListeners) { + this(loadBalancedRetryPolicy, backOffPolicy); + this.retryListeners = retryListeners; + } + + @Override + public LoadBalancedRetryPolicy createRetryPolicy(String service, + ServiceInstanceChooser serviceInstanceChooser) { + return this.loadBalancedRetryPolicy; + } @Override public BackOffPolicy createBackOffPolicy(String service) { - if(backOffPolicy == null) { + if (this.backOffPolicy == null) { return new NoBackOffPolicy(); - } else { - return backOffPolicy; + } + else { + return this.backOffPolicy; } } @Override public RetryListener[] createRetryListeners(String service) { - if(retryListeners == null) { + if (this.retryListeners == null) { return new RetryListener[0]; - } else { - return retryListeners; + } + else { + return this.retryListeners; } } + } - class MyBackOffPolicy implements BackOffPolicy { + class MyBackOffPolicy implements BackOffPolicy { - private int backoffAttempts = 0; - - @Override - public BackOffContext start(RetryContext retryContext) { - return new BackOffContext() { - @Override - protected Object clone() throws CloneNotSupportedException { - return super.clone(); - } - }; - } - - @Override - public void backOff(BackOffContext backOffContext) throws BackOffInterruptedException { - backoffAttempts++; - } - - int getBackoffAttempts() { - return backoffAttempts; - } - } - - class MyRetryListener extends RetryListenerSupport { - - private int onError = 0; + private int backoffAttempts = 0; @Override - public void onError(RetryContext retryContext, RetryCallback retryCallback, Throwable throwable) { - onError++; + public BackOffContext start(RetryContext retryContext) { + return new BackOffContext() { + @Override + protected Object clone() throws CloneNotSupportedException { + return super.clone(); + } + }; + } + + @Override + public void backOff(BackOffContext backOffContext) + throws BackOffInterruptedException { + this.backoffAttempts++; + } + + int getBackoffAttempts() { + return this.backoffAttempts; } - int getOnError() { - return onError; - } } -} \ No newline at end of file + + class MyRetryListener extends RetryListenerSupport { + + private int onError = 0; + + @Override + public void onError(RetryContext retryContext, + RetryCallback retryCallback, Throwable throwable) { + this.onError++; + } + + int getOnError() { + return this.onError; + } + + } + +} diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/reactive/LoadBalancerExchangeFilterFunctionTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/reactive/LoadBalancerExchangeFilterFunctionTests.java index b45072fa..01259c92 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/reactive/LoadBalancerExchangeFilterFunctionTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/reactive/LoadBalancerExchangeFilterFunctionTests.java @@ -9,6 +9,7 @@ import java.util.Random; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringBootConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; @@ -55,39 +56,28 @@ public class LoadBalancerExchangeFilterFunctionTests { SimpleServiceInstance instance = new SimpleServiceInstance(); instance.setServiceId("testservice"); instance.setUri(URI.create("http://localhost:" + this.port)); - properties.getInstances().put("testservice", Arrays.asList(instance)); + this.properties.getInstances().put("testservice", Arrays.asList(instance)); } @Test public void testFilterFunctionWorks() { - String value = WebClient.builder() - .baseUrl("http://testservice") - .filter(lbFunction) - .build() - .get() - .uri("/hello") - .retrieve() + String value = WebClient.builder().baseUrl("http://testservice") + .filter(this.lbFunction).build().get().uri("/hello").retrieve() .bodyToMono(String.class).block(); assertThat(value).isEqualTo("Hello World"); } @Test public void testNoInstance() { - ClientResponse clientResponse = WebClient.builder() - .baseUrl("http://foobar") - .filter(lbFunction) - .build() - .get().exchange().block(); + ClientResponse clientResponse = WebClient.builder().baseUrl("http://foobar") + .filter(this.lbFunction).build().get().exchange().block(); assertThat(clientResponse.statusCode()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE); } @Test public void testNoHostName() { - ClientResponse clientResponse = WebClient.builder() - .baseUrl("http:///foobar") - .filter(lbFunction) - .build() - .get().exchange().block(); + ClientResponse clientResponse = WebClient.builder().baseUrl("http:///foobar") + .filter(this.lbFunction).build().get().exchange().block(); assertThat(clientResponse.statusCode()).isEqualTo(HttpStatus.BAD_REQUEST); } @@ -108,35 +98,36 @@ public class LoadBalancerExchangeFilterFunctionTests { Random random = new Random(); @Override - public T execute(String serviceId, LoadBalancerRequest request) throws IOException { + public T execute(String serviceId, LoadBalancerRequest request) + throws IOException { throw new UnsupportedOperationException(); } @Override - public T execute(String serviceId, ServiceInstance serviceInstance, LoadBalancerRequest request) throws IOException { + public T execute(String serviceId, ServiceInstance serviceInstance, + LoadBalancerRequest request) throws IOException { throw new UnsupportedOperationException(); } @Override public URI reconstructURI(ServiceInstance instance, URI original) { - return UriComponentsBuilder.fromUri(original) - .host(instance.getHost()) - .port(instance.getPort()) - .build() - .toUri(); + return UriComponentsBuilder.fromUri(original).host(instance.getHost()) + .port(instance.getPort()).build().toUri(); } @Override public ServiceInstance choose(String serviceId) { - List instances = discoveryClient.getInstances(serviceId); - if(instances.size() == 0) { + List instances = discoveryClient + .getInstances(serviceId); + if (instances.size() == 0) { return null; } - int instanceIdx = random.nextInt(instances.size()); + int instanceIdx = this.random.nextInt(instances.size()); return instances.get(instanceIdx); } }; } } + } diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/reactive/ReactiveLoadBalancerAutoConfigurationTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/reactive/ReactiveLoadBalancerAutoConfigurationTests.java index f9c58c02..7d84cb4b 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/reactive/ReactiveLoadBalancerAutoConfigurationTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/reactive/ReactiveLoadBalancerAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 the original author or authors. + * Copyright 2017-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,6 @@ import org.springframework.web.reactive.function.client.WebClient; import static org.assertj.core.api.Assertions.assertThat; - /** * @author Spencer Gibb * @author Tim Ysewyn @@ -73,7 +72,8 @@ public class ReactiveLoadBalancerAutoConfigurationTests { @SuppressWarnings("unchecked") private List getFilters(WebClient.Builder builder) { - return (List) ReflectionTestUtils.getField(builder, "filters"); + return (List) ReflectionTestUtils.getField(builder, + "filters"); } @Test @@ -111,7 +111,8 @@ public class ReactiveLoadBalancerAutoConfigurationTests { return new SpringApplicationBuilder().web(WebApplicationType.NONE) // .properties("spring.aop.proxyTargetClass=true") .sources(config, WebClientAutoConfiguration.class, - ReactiveLoadBalancerAutoConfiguration.class).run(); + ReactiveLoadBalancerAutoConfiguration.class) + .run(); } @Configuration @@ -123,7 +124,10 @@ public class ReactiveLoadBalancerAutoConfigurationTests { } @Bean - LoadBalancedRetryFactory loadBalancedRetryFactory() {return new LoadBalancedRetryFactory(){};} + LoadBalancedRetryFactory loadBalancedRetryFactory() { + return new LoadBalancedRetryFactory() { + }; + } } @@ -149,17 +153,20 @@ public class ReactiveLoadBalancerAutoConfigurationTests { @Configuration protected static class Two { + @Autowired WebClient.Builder nonLoadBalanced; @Autowired @LoadBalanced WebClient.Builder loadBalanced; + } } private static class NoopLoadBalancerClient implements LoadBalancerClient { + private final Random random = new Random(); @Override @@ -172,16 +179,19 @@ public class ReactiveLoadBalancerAutoConfigurationTests { public T execute(String serviceId, LoadBalancerRequest request) { try { return request.apply(choose(serviceId)); - } catch (Exception e) { + } + catch (Exception e) { throw new RuntimeException(e); } } @Override - public T execute(String serviceId, ServiceInstance serviceInstance, LoadBalancerRequest request) throws IOException { + public T execute(String serviceId, ServiceInstance serviceInstance, + LoadBalancerRequest request) throws IOException { try { return request.apply(choose(serviceId)); - } catch (Exception e) { + } + catch (Exception e) { throw new RuntimeException(e); } } @@ -190,5 +200,7 @@ public class ReactiveLoadBalancerAutoConfigurationTests { public URI reconstructURI(ServiceInstance instance, URI original) { return DefaultServiceInstance.getUri(instance); } + } + } diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/serviceregistry/AbstractAutoServiceRegistrationMgmtDisabledTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/serviceregistry/AbstractAutoServiceRegistrationMgmtDisabledTests.java index f0540f0d..517b9165 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/serviceregistry/AbstractAutoServiceRegistrationMgmtDisabledTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/serviceregistry/AbstractAutoServiceRegistrationMgmtDisabledTests.java @@ -16,9 +16,14 @@ package org.springframework.cloud.client.serviceregistry; +import java.net.URI; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; + import org.assertj.core.api.Assertions; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; @@ -26,10 +31,6 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.junit4.SpringRunner; -import java.net.URI; -import java.util.Map; -import java.util.concurrent.atomic.AtomicInteger; - import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; /** @@ -37,9 +38,9 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen * @author Tim Ysewyn */ @RunWith(SpringRunner.class) -@SpringBootTest(classes = AbstractAutoServiceRegistrationMgmtDisabledTests.Config.class, - properties = {"management.port=0", "spring.cloud.service-registry.auto-registration.register-management=false"}, - webEnvironment = RANDOM_PORT) +@SpringBootTest(classes = AbstractAutoServiceRegistrationMgmtDisabledTests.Config.class, properties = { + "management.port=0", + "spring.cloud.service-registry.auto-registration.register-management=false" }, webEnvironment = RANDOM_PORT) public class AbstractAutoServiceRegistrationMgmtDisabledTests { @Autowired @@ -47,19 +48,23 @@ public class AbstractAutoServiceRegistrationMgmtDisabledTests { @Test public void portsWork() { - Assertions.assertThat(autoRegistration.shouldRegisterManagement()).isFalse(); + Assertions.assertThat(this.autoRegistration.shouldRegisterManagement()).isFalse(); } @EnableAutoConfiguration @Configuration public static class Config { + @Bean - public TestAutoServiceRegistration testAutoServiceRegistration(AutoServiceRegistrationProperties properties) { + public TestAutoServiceRegistration testAutoServiceRegistration( + AutoServiceRegistrationProperties properties) { return new TestAutoServiceRegistration(properties); } + } public static class TestRegistration implements Registration { + @Override public String getInstanceId() { return "testRegistrationInstance3"; @@ -94,17 +99,22 @@ public class AbstractAutoServiceRegistrationMgmtDisabledTests { public Map getMetadata() { return null; } + } public static class TestMgmtRegistration extends TestRegistration { + @Override public String getServiceId() { return "testMgmtRegistration3"; } + } public static class TestServiceRegistry implements ServiceRegistry { + private boolean registered = false; + private boolean deregistered = false; @Override @@ -128,35 +138,43 @@ public class AbstractAutoServiceRegistrationMgmtDisabledTests { } @Override - public void close() { } + public void close() { + } @Override public void setStatus(TestRegistration registration, String status) { - //TODO: test setStatus + // TODO: test setStatus } @Override public Object getStatus(TestRegistration registration) { - //TODO: test getStatus + // TODO: test getStatus return null; } boolean isRegistered() { - return registered; + return this.registered; } boolean isDeregistered() { - return deregistered; + return this.deregistered; } + } - public static class TestAutoServiceRegistration extends AbstractAutoServiceRegistration { + public static class TestAutoServiceRegistration + extends AbstractAutoServiceRegistration { + private int port = 0; public TestAutoServiceRegistration(AutoServiceRegistrationProperties properties) { super(new TestServiceRegistry(), properties); } + protected TestAutoServiceRegistration() { + super(new TestServiceRegistry()); + } + @Override protected AtomicInteger getPort() { return super.getPort(); @@ -167,10 +185,6 @@ public class AbstractAutoServiceRegistrationMgmtDisabledTests { return super.getAppName(); } - protected TestAutoServiceRegistration() { - super(new TestServiceRegistry()); - } - @Override protected TestRegistration getRegistration() { return new TestRegistration(); @@ -191,6 +205,6 @@ public class AbstractAutoServiceRegistrationMgmtDisabledTests { return true; } - } + } diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/serviceregistry/AbstractAutoServiceRegistrationTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/serviceregistry/AbstractAutoServiceRegistrationTests.java index f1e1a8f8..93009733 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/serviceregistry/AbstractAutoServiceRegistrationTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/serviceregistry/AbstractAutoServiceRegistrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2018 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. @@ -22,6 +22,7 @@ import java.util.concurrent.atomic.AtomicInteger; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.autoconfigure.web.server.LocalManagementPort; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; @@ -32,7 +33,6 @@ import org.springframework.cloud.client.discovery.event.InstanceRegisteredEvent; import org.springframework.context.ApplicationListener; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.stereotype.Component; import org.springframework.test.context.junit4.SpringRunner; import static org.hamcrest.Matchers.instanceOf; @@ -48,19 +48,18 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen * @author Tim Ysewyn */ @RunWith(SpringRunner.class) -@SpringBootTest(classes = AbstractAutoServiceRegistrationTests.Config.class, - properties = "management.port=0", webEnvironment = RANDOM_PORT) +@SpringBootTest(classes = AbstractAutoServiceRegistrationTests.Config.class, properties = "management.port=0", webEnvironment = RANDOM_PORT) public class AbstractAutoServiceRegistrationTests { + @Autowired + public PostEventListener postEventListener; + @Autowired private TestAutoServiceRegistration autoRegistration; @Autowired private PreEventListener preEventListener; - @Autowired - public PostEventListener postEventListener; - @LocalServerPort private int port; @@ -69,27 +68,36 @@ public class AbstractAutoServiceRegistrationTests { @Test public void portsWork() { - assertNotEquals("Lifecycle port is zero", 0, autoRegistration.getPort().get()); - assertNotEquals("Lifecycle port is management port", managementPort, autoRegistration.getPort().get()); - assertEquals("Lifecycle port is wrong", port, autoRegistration.getPort().get()); - assertTrue("Lifecycle not running", autoRegistration.isRunning()); - assertThat("ServiceRegistry is wrong type", autoRegistration.getServiceRegistry(), is(instanceOf(TestServiceRegistry.class))); - TestServiceRegistry serviceRegistry = (TestServiceRegistry) autoRegistration.getServiceRegistry(); + assertNotEquals("Lifecycle port is zero", 0, + this.autoRegistration.getPort().get()); + assertNotEquals("Lifecycle port is management port", this.managementPort, + this.autoRegistration.getPort().get()); + assertEquals("Lifecycle port is wrong", this.port, + this.autoRegistration.getPort().get()); + assertTrue("Lifecycle not running", this.autoRegistration.isRunning()); + assertThat("ServiceRegistry is wrong type", + this.autoRegistration.getServiceRegistry(), + is(instanceOf(TestServiceRegistry.class))); + TestServiceRegistry serviceRegistry = (TestServiceRegistry) this.autoRegistration + .getServiceRegistry(); assertTrue("Lifecycle not registered", serviceRegistry.isRegistered()); - assertEquals("Lifecycle appName is wrong", "application", autoRegistration.getAppName()); + assertEquals("Lifecycle appName is wrong", "application", + this.autoRegistration.getAppName()); } @Test public void eventsFireTest() { - assertTrue(preEventListener.wasFired); - assertEquals("testRegistration2", preEventListener.registration.getServiceId()); - assertTrue(postEventListener.wasFired); - assertEquals("testRegistration2", postEventListener.config.getServiceId()); + assertTrue(this.preEventListener.wasFired); + assertEquals("testRegistration2", + this.preEventListener.registration.getServiceId()); + assertTrue(this.postEventListener.wasFired); + assertEquals("testRegistration2", this.postEventListener.config.getServiceId()); } @EnableAutoConfiguration @Configuration public static class Config { + @Bean public TestAutoServiceRegistration testAutoServiceRegistration() { return new TestAutoServiceRegistration(); @@ -104,29 +112,41 @@ public class AbstractAutoServiceRegistrationTests { public PostEventListener postEventListener() { return new PostEventListener(); } + } - public static class PreEventListener implements ApplicationListener { + public static class PreEventListener + implements ApplicationListener { + public boolean wasFired = false; + public Registration registration; + @Override public void onApplicationEvent(InstancePreRegisteredEvent event) { this.registration = event.getRegistration(); this.wasFired = true; } + } - public static class PostEventListener implements ApplicationListener { + public static class PostEventListener + implements ApplicationListener { + public boolean wasFired = false; + public Registration config; + @Override public void onApplicationEvent(InstanceRegisteredEvent event) { - this.config = (Registration)event.getConfig(); + this.config = (Registration) event.getConfig(); this.wasFired = true; } + } public static class TestRegistration implements Registration { + @Override public String getInstanceId() { return "testRegistrationInstance2"; @@ -161,17 +181,22 @@ public class AbstractAutoServiceRegistrationTests { public Map getMetadata() { return null; } + } public static class TestMgmtRegistration extends TestRegistration { + @Override public String getServiceId() { return "testMgmtRegistration2"; } + } public static class TestServiceRegistry implements ServiceRegistry { + private boolean registered = false; + private boolean deregistered = false; @Override @@ -195,35 +220,43 @@ public class AbstractAutoServiceRegistrationTests { } @Override - public void close() { } + public void close() { + } @Override public void setStatus(TestRegistration registration, String status) { - //TODO: test setStatus + // TODO: test setStatus } @Override public Object getStatus(TestRegistration registration) { - //TODO: test getStatus + // TODO: test getStatus return null; } boolean isRegistered() { - return registered; + return this.registered; } boolean isDeregistered() { - return deregistered; + return this.deregistered; } + } - public static class TestAutoServiceRegistration extends AbstractAutoServiceRegistration { + public static class TestAutoServiceRegistration + extends AbstractAutoServiceRegistration { + private int port = 0; public TestAutoServiceRegistration(AutoServiceRegistrationProperties properties) { super(null, properties); } + protected TestAutoServiceRegistration() { + super(new TestServiceRegistry()); + } + @Override protected AtomicInteger getPort() { return super.getPort(); @@ -234,12 +267,8 @@ public class AbstractAutoServiceRegistrationTests { return super.getAppName(); } - protected TestAutoServiceRegistration() { - super(new TestServiceRegistry()); - } - protected int getConfiguredPort() { - return port; + return this.port; } protected void setConfiguredPort(int port) { @@ -266,6 +295,6 @@ public class AbstractAutoServiceRegistrationTests { return true; } - } + } diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/serviceregistry/AutoServiceRegistrationAutoConfigurationTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/serviceregistry/AutoServiceRegistrationAutoConfigurationTests.java index a1126619..3717f25e 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/serviceregistry/AutoServiceRegistrationAutoConfigurationTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/serviceregistry/AutoServiceRegistrationAutoConfigurationTests.java @@ -28,8 +28,10 @@ public class AutoServiceRegistrationAutoConfigurationTests { @Test public void hasAutoServiceRegistration() { - try(AnnotationConfigApplicationContext context = setup(HasAutoServiceRegistrationConfiguration.class)) { - AutoServiceRegistration autoServiceRegistration = context.getBean(AutoServiceRegistration.class); + try (AnnotationConfigApplicationContext context = setup( + HasAutoServiceRegistrationConfiguration.class)) { + AutoServiceRegistration autoServiceRegistration = context + .getBean(AutoServiceRegistration.class); assertThat(autoServiceRegistration).isNotNull(); } } @@ -37,32 +39,27 @@ public class AutoServiceRegistrationAutoConfigurationTests { @Test public void noAutoServiceRegistrationAndFailFast() { this.exception.expect(BeanCreationException.class); - this.exception.expectMessage(Matchers.containsString("no AutoServiceRegistration")); - try(AnnotationConfigApplicationContext context = setup("spring.cloud.service-registry.auto-registration.failFast=true")) { + this.exception + .expectMessage(Matchers.containsString("no AutoServiceRegistration")); + try (AnnotationConfigApplicationContext context = setup( + "spring.cloud.service-registry.auto-registration.failFast=true")) { assertNoBean(context); } } @Test public void noAutoServiceRegistrationAndFailFastFalse() { - try(AnnotationConfigApplicationContext context = setup()) { + try (AnnotationConfigApplicationContext context = setup()) { assertNoBean(context); } } private void assertNoBean(AnnotationConfigApplicationContext context) { - Map beans = context.getBeansOfType(AutoServiceRegistration.class); + Map beans = context + .getBeansOfType(AutoServiceRegistration.class); assertThat(beans).isEmpty(); } - @Configuration - static class HasAutoServiceRegistrationConfiguration { - @Bean - public AutoServiceRegistration autoServiceRegistration() { - return new AutoServiceRegistration() {}; - } - } - private AnnotationConfigApplicationContext setup(Class... classes) { return setup(null, classes); } @@ -80,4 +77,16 @@ public class AutoServiceRegistrationAutoConfigurationTests { context.refresh(); return context; } + + @Configuration + static class HasAutoServiceRegistrationConfiguration { + + @Bean + public AutoServiceRegistration autoServiceRegistration() { + return new AutoServiceRegistration() { + }; + } + + } + } diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/serviceregistry/ServiceRegistryAutoConfigurationTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/serviceregistry/ServiceRegistryAutoConfigurationTests.java index f706beb0..f6583fa9 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/serviceregistry/ServiceRegistryAutoConfigurationTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/serviceregistry/ServiceRegistryAutoConfigurationTests.java @@ -17,16 +17,19 @@ import static org.assertj.core.api.Assertions.fail; * @author Spencer Gibb */ @RunWith(ModifiedClassPathRunner.class) -@ClassPathExclusions({"spring-boot-actuator-*.jar", "spring-boot-starter-actuator-*.jar"}) +@ClassPathExclusions({ "spring-boot-actuator-*.jar", + "spring-boot-starter-actuator-*.jar" }) public class ServiceRegistryAutoConfigurationTests { @Test public void runsWithoutActuator() { - ConfigurableApplicationContext context = new SpringApplicationBuilder(TestConfig.class).web(WebApplicationType.NONE).run(); + ConfigurableApplicationContext context = new SpringApplicationBuilder( + TestConfig.class).web(WebApplicationType.NONE).run(); try { context.getBean("serviceRegistryEndpoint"); fail("found a bean that shouldn't be there"); - } catch (NoSuchBeanDefinitionException e) { + } + catch (NoSuchBeanDefinitionException e) { // success } } @@ -35,4 +38,5 @@ public class ServiceRegistryAutoConfigurationTests { protected static class TestConfig { } + } diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/serviceregistry/endpoint/ServiceRegistryEndpointNoRegistrationTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/serviceregistry/endpoint/ServiceRegistryEndpointNoRegistrationTests.java index a07f5a4a..8e8a2a60 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/serviceregistry/endpoint/ServiceRegistryEndpointNoRegistrationTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/serviceregistry/endpoint/ServiceRegistryEndpointNoRegistrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2018 the original author or authors. + * Copyright 2006-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. @@ -18,6 +18,7 @@ package org.springframework.cloud.client.serviceregistry.endpoint; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.autoconfigure.endpoint.EndpointAutoConfiguration; import org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration; @@ -50,21 +51,24 @@ public class ServiceRegistryEndpointNoRegistrationTests { @Test public void testGet() throws Exception { - this.mvc.perform(get("/service-registry/instance-status")).andExpect(status().isNotFound()); + this.mvc.perform(get("/service-registry/instance-status")) + .andExpect(status().isNotFound()); } @Test public void testPost() throws Exception { - this.mvc.perform(post("/service-registry/instance-status").content("newstatus")).andExpect(status().isNotFound()); + this.mvc.perform(post("/service-registry/instance-status").content("newstatus")) + .andExpect(status().isNotFound()); } - @Import({JacksonAutoConfiguration.class, - HttpMessageConvertersAutoConfiguration.class, - EndpointAutoConfiguration.class, WebMvcAutoConfiguration.class, + @Import({ JacksonAutoConfiguration.class, + HttpMessageConvertersAutoConfiguration.class, EndpointAutoConfiguration.class, + WebMvcAutoConfiguration.class, // ManagementServerPropertiesAutoConfiguration.class }) @Configuration public static class TestConfiguration { + @Bean ServiceRegistryEndpoint serviceRegistryEndpoint() { return new ServiceRegistryEndpoint(serviceRegistry()); @@ -72,7 +76,9 @@ public class ServiceRegistryEndpointNoRegistrationTests { @Bean ServiceRegistry serviceRegistry() { - return new TestServiceRegistry() ; + return new TestServiceRegistry(); } + } + } diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/serviceregistry/endpoint/ServiceRegistryEndpointTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/serviceregistry/endpoint/ServiceRegistryEndpointTests.java index 7905a4e4..e60b85a3 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/serviceregistry/endpoint/ServiceRegistryEndpointTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/serviceregistry/endpoint/ServiceRegistryEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2018 the original author or authors. + * Copyright 2006-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. @@ -21,8 +21,10 @@ import java.util.Collections; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; +import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringBootConfiguration; import org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties; @@ -36,8 +38,6 @@ import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; -import com.fasterxml.jackson.databind.ObjectMapper; - import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.containsString; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; @@ -53,9 +53,11 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @SpringBootTest(classes = ServiceRegistryEndpointTests.TestConfiguration.class, properties = "management.endpoints.web.exposure.include=*") @AutoConfigureMockMvc public class ServiceRegistryEndpointTests { + private static final String BASE_PATH = new WebEndpointProperties().getBasePath(); - + private static final String UPDATED_STATUS = "updatedstatus"; + private static final String MYSTATUS = "mystatus"; @Autowired @@ -75,14 +77,15 @@ public class ServiceRegistryEndpointTests { Map status = Collections.singletonMap("status", UPDATED_STATUS); this.mvc.perform(post(BASE_PATH + "/service-registry") .content(new ObjectMapper().writeValueAsString(status)) - .contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()); - assertThat(this.serviceRegistry.getUpdatedStatus().get()).isEqualTo(UPDATED_STATUS); + .contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()); + assertThat(this.serviceRegistry.getUpdatedStatus().get()) + .isEqualTo(UPDATED_STATUS); } @EnableAutoConfiguration @SpringBootConfiguration public static class TestConfiguration { + @Bean Registration registration() { return new Registration() { @@ -125,8 +128,9 @@ public class ServiceRegistryEndpointTests { @Bean ServiceRegistry serviceRegistry() { - return new TestServiceRegistry() ; + return new TestServiceRegistry(); } + } static class TestServiceRegistry implements ServiceRegistry { @@ -150,7 +154,7 @@ public class ServiceRegistryEndpointTests { @Override public void setStatus(Registration registration, String status) { - updatedStatus.compareAndSet(null, status); + this.updatedStatus.compareAndSet(null, status); } @Override @@ -159,7 +163,9 @@ public class ServiceRegistryEndpointTests { } public AtomicReference getUpdatedStatus() { - return updatedStatus; + return this.updatedStatus; } + } + } diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/httpclient/CustomHttpClientBuilderConfigurationTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/httpclient/CustomHttpClientBuilderConfigurationTests.java index a55c6dc0..4e2c118e 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/httpclient/CustomHttpClientBuilderConfigurationTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/httpclient/CustomHttpClientBuilderConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-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. @@ -18,6 +18,7 @@ package org.springframework.cloud.commons.httpclient; import org.apache.http.impl.client.HttpClientBuilder; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.AutoConfigureBefore; @@ -41,9 +42,11 @@ public class CustomHttpClientBuilderConfigurationTests { @Test public void testCustomBuilder() { - HttpClientBuilder builder = apacheHttpClientFactory.createBuilder(); - assertTrue(CustomHttpClientBuilderApplication.MyHttpClientBuilder.class.isInstance(builder)); + HttpClientBuilder builder = this.apacheHttpClientFactory.createBuilder(); + assertTrue(CustomHttpClientBuilderApplication.MyHttpClientBuilder.class + .isInstance(builder)); } + } @Configuration @@ -66,5 +69,7 @@ class CustomHttpClientBuilderApplication { } static class MyHttpClientBuilder extends HttpClientBuilder { + } + } diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/httpclient/CustomHttpClientConfigurationTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/httpclient/CustomHttpClientConfigurationTests.java index 748d3d3c..5815efd3 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/httpclient/CustomHttpClientConfigurationTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/httpclient/CustomHttpClientConfigurationTests.java @@ -1,14 +1,15 @@ package org.springframework.cloud.commons.httpclient; +import java.util.concurrent.TimeUnit; + import okhttp3.ConnectionPool; import okhttp3.OkHttpClient; - -import java.util.concurrent.TimeUnit; import org.apache.http.config.RegistryBuilder; import org.apache.http.conn.HttpClientConnectionManager; import org.apache.http.impl.client.HttpClientBuilder; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; @@ -23,7 +24,8 @@ import static org.junit.Assert.assertTrue; * @author Ryan Baxter */ @RunWith(SpringRunner.class) -@SpringBootTest(classes = CustomApplication.class, properties = {"spring.cloud.httpclient.ok.enabled: true"}) +@SpringBootTest(classes = CustomApplication.class, properties = { + "spring.cloud.httpclient.ok.enabled: true" }) public class CustomHttpClientConfigurationTests { @Autowired @@ -41,28 +43,31 @@ public class CustomHttpClientConfigurationTests { @Test public void connManFactory() throws Exception { assertTrue(ApacheHttpClientConnectionManagerFactory.class - .isInstance(connectionManagerFactory)); + .isInstance(this.connectionManagerFactory)); assertTrue(CustomApplication.MyApacheHttpClientConnectionManagerFactory.class - .isInstance(connectionManagerFactory)); + .isInstance(this.connectionManagerFactory)); } @Test public void apacheHttpClientFactory() throws Exception { - assertTrue(ApacheHttpClientFactory.class.isInstance(httpClientFactory)); + assertTrue(ApacheHttpClientFactory.class.isInstance(this.httpClientFactory)); assertTrue(CustomApplication.MyApacheHttpClientFactory.class - .isInstance(httpClientFactory)); + .isInstance(this.httpClientFactory)); } @Test public void connectionPoolFactory() throws Exception { - assertTrue(OkHttpClientConnectionPoolFactory.class.isInstance(okHttpClientConnectionPoolFactory)); - assertTrue(CustomApplication.MyOkHttpConnectionPoolFactory.class.isInstance(okHttpClientConnectionPoolFactory)); + assertTrue(OkHttpClientConnectionPoolFactory.class + .isInstance(this.okHttpClientConnectionPoolFactory)); + assertTrue(CustomApplication.MyOkHttpConnectionPoolFactory.class + .isInstance(this.okHttpClientConnectionPoolFactory)); } @Test public void okHttpClientFactory() throws Exception { - assertTrue(OkHttpClientFactory.class.isInstance(okHttpClientFactory)); - assertTrue(CustomApplication.MyOkHttpClientFactory.class.isInstance(okHttpClientFactory)); + assertTrue(OkHttpClientFactory.class.isInstance(this.okHttpClientFactory)); + assertTrue(CustomApplication.MyOkHttpClientFactory.class + .isInstance(this.okHttpClientFactory)); } } @@ -106,6 +111,7 @@ class CustomApplication { public HttpClientBuilder createBuilder() { return HttpClientBuilder.create(); } + } static class MyApacheHttpClientConnectionManagerFactory @@ -118,20 +124,27 @@ class CustomApplication { RegistryBuilder registryBuilder) { return null; } + } static class MyOkHttpClientFactory implements OkHttpClientFactory { + @Override public OkHttpClient.Builder createBuilder(boolean disableSslValidation) { return new OkHttpClient.Builder(); } + } - static class MyOkHttpConnectionPoolFactory implements OkHttpClientConnectionPoolFactory { + static class MyOkHttpConnectionPoolFactory + implements OkHttpClientConnectionPoolFactory { @Override - public ConnectionPool create(int maxIdleConnections, long keepAliveDuration, TimeUnit timeUnit) { + public ConnectionPool create(int maxIdleConnections, long keepAliveDuration, + TimeUnit timeUnit) { return null; } + } + } diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/httpclient/CustomOkHttpClientBuilderConfigurationTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/httpclient/CustomOkHttpClientBuilderConfigurationTests.java index ac8afa5c..d3de81e7 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/httpclient/CustomOkHttpClientBuilderConfigurationTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/httpclient/CustomOkHttpClientBuilderConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-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. @@ -15,12 +15,13 @@ */ package org.springframework.cloud.commons.httpclient; -import okhttp3.OkHttpClient; - import java.lang.reflect.Field; import java.util.concurrent.TimeUnit; + +import okhttp3.OkHttpClient; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; @@ -44,7 +45,7 @@ public class CustomOkHttpClientBuilderConfigurationTests { @Test public void testCustomBuilder() { - OkHttpClient.Builder builder = okHttpClientFactory.createBuilder(false); + OkHttpClient.Builder builder = this.okHttpClientFactory.createBuilder(false); Integer timeout = getField(builder, "connectTimeout"); assertEquals(1, timeout.intValue()); } @@ -73,5 +74,7 @@ class CustomOkHttpClientBuilderApplication { public OkHttpClient.Builder builder() { return new OkHttpClient.Builder().connectTimeout(1, TimeUnit.MILLISECONDS); } + } + } diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/httpclient/DefaultApacheHttpClientConnectionManagerFactoryTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/httpclient/DefaultApacheHttpClientConnectionManagerFactoryTests.java index b748bd9d..6adda042 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/httpclient/DefaultApacheHttpClientConnectionManagerFactoryTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/httpclient/DefaultApacheHttpClientConnectionManagerFactoryTests.java @@ -27,6 +27,7 @@ import static org.junit.Assert.assertThat; * @author Michael Wirth */ public class DefaultApacheHttpClientConnectionManagerFactoryTests { + @Test public void newConnectionManager() throws Exception { HttpClientConnectionManager connectionManager = new DefaultApacheHttpClientConnectionManagerFactory() @@ -105,4 +106,5 @@ public class DefaultApacheHttpClientConnectionManagerFactoryTests { Object value = ReflectionUtils.getField(field, target); return (T) value; } + } diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/httpclient/DefaultApacheHttpClientFactoryTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/httpclient/DefaultApacheHttpClientFactoryTests.java index 03810b0a..b18a7edc 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/httpclient/DefaultApacheHttpClientFactoryTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/httpclient/DefaultApacheHttpClientFactoryTests.java @@ -1,6 +1,7 @@ package org.springframework.cloud.commons.httpclient; import java.lang.reflect.Field; + import org.apache.http.client.config.CookieSpecs; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.Configurable; @@ -9,6 +10,7 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.assertj.core.api.Assertions; import org.junit.Test; + import org.springframework.util.ReflectionUtils; import static org.junit.Assert.assertEquals; @@ -18,13 +20,15 @@ import static org.mockito.Mockito.mock; * @author Ryan Baxter */ public class DefaultApacheHttpClientFactoryTests { + @Test public void createClient() throws Exception { final RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(100) .setConnectTimeout(200).setCookieSpec(CookieSpecs.IGNORE_COOKIES).build(); - CloseableHttpClient httpClient = new DefaultApacheHttpClientFactory(HttpClientBuilder.create()).createBuilder(). - setConnectionManager(mock(HttpClientConnectionManager.class)). - setDefaultRequestConfig(requestConfig).build(); + CloseableHttpClient httpClient = new DefaultApacheHttpClientFactory( + HttpClientBuilder.create()).createBuilder() + .setConnectionManager(mock(HttpClientConnectionManager.class)) + .setDefaultRequestConfig(requestConfig).build(); Assertions.assertThat(httpClient).isInstanceOf(Configurable.class); RequestConfig config = ((Configurable) httpClient).getConfig(); assertEquals(100, config.getSocketTimeout()); @@ -39,4 +43,4 @@ public class DefaultApacheHttpClientFactoryTests { return (T) value; } -} \ No newline at end of file +} diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/httpclient/DefaultHttpClientConfigurationTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/httpclient/DefaultHttpClientConfigurationTests.java index d3f7d04f..9a577185 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/httpclient/DefaultHttpClientConfigurationTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/httpclient/DefaultHttpClientConfigurationTests.java @@ -2,6 +2,7 @@ package org.springframework.cloud.commons.httpclient; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; @@ -9,14 +10,16 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.junit4.SpringRunner; -import static org.junit.Assert.*; +import static org.junit.Assert.assertTrue; /** * @author Ryan Baxter */ @RunWith(SpringRunner.class) -@SpringBootTest(classes = MyApplication.class, properties = {"spring.cloud.httpclient.ok.enabled: true"}) +@SpringBootTest(classes = MyApplication.class, properties = { + "spring.cloud.httpclient.ok.enabled: true" }) public class DefaultHttpClientConfigurationTests { + @Autowired ApacheHttpClientFactory httpClientFactory; @@ -32,28 +35,32 @@ public class DefaultHttpClientConfigurationTests { @Test public void connManFactory() throws Exception { assertTrue(ApacheHttpClientConnectionManagerFactory.class - .isInstance(connectionManagerFactory)); + .isInstance(this.connectionManagerFactory)); assertTrue(DefaultApacheHttpClientConnectionManagerFactory.class - .isInstance(connectionManagerFactory)); + .isInstance(this.connectionManagerFactory)); } @Test public void apacheHttpClientFactory() throws Exception { - assertTrue(ApacheHttpClientFactory.class.isInstance(httpClientFactory)); - assertTrue(DefaultApacheHttpClientFactory.class.isInstance(httpClientFactory)); + assertTrue(ApacheHttpClientFactory.class.isInstance(this.httpClientFactory)); + assertTrue( + DefaultApacheHttpClientFactory.class.isInstance(this.httpClientFactory)); } @Test public void connPoolFactory() throws Exception { - assertTrue(OkHttpClientConnectionPoolFactory.class.isInstance(okHttpClientConnectionPoolFactory)); - assertTrue(DefaultOkHttpClientConnectionPoolFactory.class.isInstance(okHttpClientConnectionPoolFactory)); + assertTrue(OkHttpClientConnectionPoolFactory.class + .isInstance(this.okHttpClientConnectionPoolFactory)); + assertTrue(DefaultOkHttpClientConnectionPoolFactory.class + .isInstance(this.okHttpClientConnectionPoolFactory)); } @Test public void setOkHttpClientFactory() throws Exception { - assertTrue(OkHttpClientFactory.class.isInstance(okHttpClientFactory)); - assertTrue(DefaultOkHttpClientFactory.class.isInstance(okHttpClientFactory)); + assertTrue(OkHttpClientFactory.class.isInstance(this.okHttpClientFactory)); + assertTrue(DefaultOkHttpClientFactory.class.isInstance(this.okHttpClientFactory)); } + } @Configuration @@ -63,4 +70,5 @@ class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } -} \ No newline at end of file + +} diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/httpclient/DefaultOkHttpClientConnectionPoolFactoryTest.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/httpclient/DefaultOkHttpClientConnectionPoolFactoryTest.java index a7658e3b..5fa97047 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/httpclient/DefaultOkHttpClientConnectionPoolFactoryTest.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/httpclient/DefaultOkHttpClientConnectionPoolFactoryTest.java @@ -1,10 +1,11 @@ package org.springframework.cloud.commons.httpclient; -import okhttp3.ConnectionPool; - import java.lang.reflect.Field; import java.util.concurrent.TimeUnit; + +import okhttp3.ConnectionPool; import org.junit.Test; + import org.springframework.util.ReflectionUtils; import static org.junit.Assert.assertEquals; @@ -13,11 +14,12 @@ import static org.junit.Assert.assertEquals; * @author Ryan Baxter */ public class DefaultOkHttpClientConnectionPoolFactoryTest { + @Test public void create() throws Exception { DefaultOkHttpClientConnectionPoolFactory connectionPoolFactory = new DefaultOkHttpClientConnectionPoolFactory(); - ConnectionPool connectionPool = connectionPoolFactory.create(2, - 3, TimeUnit.MILLISECONDS); + ConnectionPool connectionPool = connectionPoolFactory.create(2, 3, + TimeUnit.MILLISECONDS); int idleConnections = getField(connectionPool, "maxIdleConnections"); long keepAliveDuration = getField(connectionPool, "keepAliveDurationNs"); assertEquals(2, idleConnections); @@ -31,4 +33,4 @@ public class DefaultOkHttpClientConnectionPoolFactoryTest { return (T) value; } -} \ No newline at end of file +} diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/httpclient/DefaultOkHttpClientFactoryTest.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/httpclient/DefaultOkHttpClientFactoryTest.java index b14e7f05..67428e27 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/httpclient/DefaultOkHttpClientFactoryTest.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/httpclient/DefaultOkHttpClientFactoryTest.java @@ -1,12 +1,14 @@ package org.springframework.cloud.commons.httpclient; -import okhttp3.ConnectionPool; -import okhttp3.OkHttpClient; - import java.lang.reflect.Field; import java.util.concurrent.TimeUnit; + import javax.net.ssl.HostnameVerifier; + +import okhttp3.ConnectionPool; +import okhttp3.OkHttpClient; import org.junit.Test; + import org.springframework.util.ReflectionUtils; import static org.junit.Assert.assertEquals; @@ -16,16 +18,16 @@ import static org.junit.Assert.assertTrue; * @author Ryan Baxter */ public class DefaultOkHttpClientFactoryTest { + @Test public void create() throws Exception { - DefaultOkHttpClientFactory okHttpClientFactory = new DefaultOkHttpClientFactory(new OkHttpClient.Builder()); + DefaultOkHttpClientFactory okHttpClientFactory = new DefaultOkHttpClientFactory( + new OkHttpClient.Builder()); DefaultOkHttpClientConnectionPoolFactory poolFactory = new DefaultOkHttpClientConnectionPoolFactory(); ConnectionPool pool = poolFactory.create(4, 5, TimeUnit.DAYS); - OkHttpClient httpClient = okHttpClientFactory.createBuilder(true). - connectTimeout(2, TimeUnit.MILLISECONDS). - readTimeout(3, TimeUnit.HOURS). - followRedirects(true). - connectionPool(pool).build(); + OkHttpClient httpClient = okHttpClientFactory.createBuilder(true) + .connectTimeout(2, TimeUnit.MILLISECONDS).readTimeout(3, TimeUnit.HOURS) + .followRedirects(true).connectionPool(pool).build(); int connectTimeout = getField(httpClient, "connectTimeout"); assertEquals(2, connectTimeout); int readTimeout = getField(httpClient, "readTimeout"); @@ -35,7 +37,8 @@ public class DefaultOkHttpClientFactoryTest { ConnectionPool poolFromClient = getField(httpClient, "connectionPool"); assertEquals(pool, poolFromClient); HostnameVerifier hostnameVerifier = getField(httpClient, "hostnameVerifier"); - assertTrue(OkHttpClientFactory.TrustAllHostnames.class.isInstance(hostnameVerifier)); + assertTrue( + OkHttpClientFactory.TrustAllHostnames.class.isInstance(hostnameVerifier)); } protected T getField(Object target, String name) { @@ -44,4 +47,5 @@ public class DefaultOkHttpClientFactoryTest { Object value = ReflectionUtils.getField(field, target); return (T) value; } -} \ No newline at end of file + +} diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/util/IdUtilsTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/util/IdUtilsTests.java index 59c53886..4c7a3bc7 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/util/IdUtilsTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/util/IdUtilsTests.java @@ -1,19 +1,21 @@ package org.springframework.cloud.commons.util; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - import org.junit.After; import org.junit.Before; import org.junit.Test; + import org.springframework.mock.env.MockEnvironment; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + /** * @author Spencer Gibb */ public class IdUtilsTests { public static final String DEFAULT_ID = "id1"; + private MockEnvironment env; @Before @@ -56,9 +58,10 @@ public class IdUtilsTests { @Test public void hostnameAndAppNameWorks() { this.env.setProperty("spring.application.name", DEFAULT_ID); - this.env.setProperty("spring.cloud.client.hostname", DEFAULT_ID+"2"); + this.env.setProperty("spring.cloud.client.hostname", DEFAULT_ID + "2"); String instanceId = IdUtils.getDefaultInstanceId(this.env); - assertEquals("instanceId was wrong", DEFAULT_ID+"2"+":"+DEFAULT_ID, instanceId); + assertEquals("instanceId was wrong", DEFAULT_ID + "2" + ":" + DEFAULT_ID, + instanceId); } @Test @@ -80,7 +83,7 @@ public class IdUtilsTests { this.env.setProperty("spring.application.name", DEFAULT_ID); this.env.setProperty("server.port", "80"); String instanceId = IdUtils.getDefaultInstanceId(this.env); - assertEquals("instanceId was wrong", DEFAULT_ID+":80", instanceId); + assertEquals("instanceId was wrong", DEFAULT_ID + ":80", instanceId); } @Test @@ -89,7 +92,7 @@ public class IdUtilsTests { this.env.setProperty("spring.application.name", DEFAULT_ID); this.env.setProperty("server.port", "80"); String instanceId = IdUtils.getDefaultInstanceId(this.env); - assertEquals("instanceId was wrong", "myhost:"+DEFAULT_ID+":80", instanceId); + assertEquals("instanceId was wrong", "myhost:" + DEFAULT_ID + ":80", instanceId); } } diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/util/InetUtilsTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/util/InetUtilsTests.java index 74f10a50..68339768 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/util/InetUtilsTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/util/InetUtilsTests.java @@ -97,7 +97,7 @@ public class InetUtilsTests { assertFalse(utils.isPreferredAddress(InetAddress.getByName("5.5.8.1"))); } } - + @Test public void testPreferredNetworksRegex() throws Exception { InetUtilsProperties properties = new InetUtilsProperties(); @@ -110,7 +110,7 @@ public class InetUtilsTests { assertFalse(utils.isPreferredAddress(InetAddress.getByName("10.255.10.1"))); } } - + @Test public void testPreferredNetworksSimple() throws Exception { InetUtilsProperties properties = new InetUtilsProperties(); @@ -135,4 +135,5 @@ public class InetUtilsTests { assertTrue(utils.isPreferredAddress(InetAddress.getByName("10.0.10.1"))); } } + } diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/util/SpringFactoryImportSelectorTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/util/SpringFactoryImportSelectorTests.java index 225e2d6f..74d3c701 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/util/SpringFactoryImportSelectorTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/util/SpringFactoryImportSelectorTests.java @@ -33,10 +33,11 @@ public class SpringFactoryImportSelectorTests { } public @interface MyAnnotation { + } - public static class MyAnnotationImportSelector extends - SpringFactoryImportSelector { + public static class MyAnnotationImportSelector + extends SpringFactoryImportSelector { @Override protected boolean isEnabled() { @@ -44,4 +45,5 @@ public class SpringFactoryImportSelectorTests { } } + } diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/configuration/CompatibilityVerifierAutoConfigurationTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/configuration/CompatibilityVerifierAutoConfigurationTests.java index 5b821d1a..eb42b586 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/configuration/CompatibilityVerifierAutoConfigurationTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/configuration/CompatibilityVerifierAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-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. You may obtain a copy of the License at @@ -41,10 +41,12 @@ public class CompatibilityVerifierAutoConfigurationTests { @Configuration @EnableAutoConfiguration static class TestConfiguration { + @Bean MyCompatibilityVerifier myMismatchVerifier() { return new MyCompatibilityVerifier(); } + } private static class MyCompatibilityVerifier implements CompatibilityVerifier { @@ -56,6 +58,7 @@ public class CompatibilityVerifierAutoConfigurationTests { this.called = true; return VerificationResult.compatible(); } - } -} + } + +} diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/configuration/CompatibilityVerifierDisabledAutoConfigurationTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/configuration/CompatibilityVerifierDisabledAutoConfigurationTests.java index ba803079..07091c65 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/configuration/CompatibilityVerifierDisabledAutoConfigurationTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/configuration/CompatibilityVerifierDisabledAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-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. You may obtain a copy of the License at @@ -31,7 +31,7 @@ public class CompatibilityVerifierDisabledAutoConfigurationTests { @Autowired(required = false) CompositeCompatibilityVerifier compositeCompatibilityVerifier; - + @Test public void contextLoads() { BDDAssertions.then(this.compositeCompatibilityVerifier).isNull(); @@ -40,6 +40,7 @@ public class CompatibilityVerifierDisabledAutoConfigurationTests { @Configuration @EnableAutoConfiguration static class TestConfiguration { - } -} + } + +} diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/configuration/CompatibilityVerifierFailureAutoConfigurationTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/configuration/CompatibilityVerifierFailureAutoConfigurationTests.java index a081b851..5043f6f8 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/configuration/CompatibilityVerifierFailureAutoConfigurationTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/configuration/CompatibilityVerifierFailureAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-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. You may obtain a copy of the License at @@ -28,7 +28,8 @@ import org.springframework.core.NestedExceptionUtils; */ public class CompatibilityVerifierFailureAutoConfigurationTests { - @Rule public OutputCapture outputCapture = new OutputCapture(); + @Rule + public OutputCapture outputCapture = new OutputCapture(); @Test public void contextFailsToLoad() { @@ -36,7 +37,8 @@ public class CompatibilityVerifierFailureAutoConfigurationTests { SpringApplication.run(TestConfiguration.class, "--spring.cloud.compatibility-verifier.compatible-boot-versions=1.2.x,1.3.x"); BDDAssertions.fail("should throw exception"); - } catch (BeanCreationException ex) { + } + catch (BeanCreationException ex) { Throwable cause = NestedExceptionUtils.getRootCause(ex); BDDAssertions.then(((CompatibilityNotMetException) cause).results).hasSize(1); } @@ -45,6 +47,7 @@ public class CompatibilityVerifierFailureAutoConfigurationTests { @Configuration @EnableAutoConfiguration static class TestConfiguration { - } -} + } + +} diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/configuration/CompatibilityVerifierTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/configuration/CompatibilityVerifierTests.java index 23487d7e..658777ce 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/configuration/CompatibilityVerifierTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/configuration/CompatibilityVerifierTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-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. You may obtain a copy of the License at @@ -26,15 +26,18 @@ import org.springframework.boot.test.rule.OutputCapture; */ public class CompatibilityVerifierTests { - @Rule public OutputCapture outputCapture = new OutputCapture(); + @Rule + public OutputCapture outputCapture = new OutputCapture(); @Test public void should_not_print_the_report_when_no_errors_were_found() { - CompositeCompatibilityVerifier verifier = new CompositeCompatibilityVerifier(new ArrayList()); + CompositeCompatibilityVerifier verifier = new CompositeCompatibilityVerifier( + new ArrayList()); verifier.verifyDependencies(); - BDDAssertions.then(outputCapture.toString()).doesNotContain("SPRING CLOUD VERIFICATION FAILED"); + BDDAssertions.then(this.outputCapture.toString()) + .doesNotContain("SPRING CLOUD VERIFICATION FAILED"); } @Test @@ -43,23 +46,27 @@ public class CompatibilityVerifierTests { list.add(new CompatibilityVerifier() { @Override public VerificationResult verify() { - return VerificationResult.notCompatible("Wrong Boot version", "Use Boot version 1.2"); + return VerificationResult.notCompatible("Wrong Boot version", + "Use Boot version 1.2"); } }); list.add(new CompatibilityVerifier() { @Override public VerificationResult verify() { - return VerificationResult.notCompatible("Wrong JDK version", "Use JDK 25"); + return VerificationResult.notCompatible("Wrong JDK version", + "Use JDK 25"); } }); - CompositeCompatibilityVerifier verifier = new CompositeCompatibilityVerifier(list); + CompositeCompatibilityVerifier verifier = new CompositeCompatibilityVerifier( + list); try { verifier.verifyDependencies(); BDDAssertions.fail("should fail"); - } catch (CompatibilityNotMetException ex) { + } + catch (CompatibilityNotMetException ex) { BDDAssertions.then(ex.results).hasSize(2); } } -} \ No newline at end of file +} diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/configuration/SpringBootDependencyTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/configuration/SpringBootDependencyTests.java index f839e3d7..8337d38a 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/configuration/SpringBootDependencyTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/configuration/SpringBootDependencyTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at @@ -26,8 +26,8 @@ public class SpringBootDependencyTests { @Test public void should_read_concrete_version_from_manifest() { List acceptedVersions = Collections.singletonList("2.1.3.RELEASE"); - SpringBootVersionVerifier - versionVerifier = new SpringBootVersionVerifier(acceptedVersions) { + SpringBootVersionVerifier versionVerifier = new SpringBootVersionVerifier( + acceptedVersions) { @Override String getVersionFromManifest() { return "2.1.3.RELEASE"; @@ -44,8 +44,8 @@ public class SpringBootDependencyTests { @Test public void should_read_concrete_version_from_manifest_and_return_false_when_version_is_not_matched() { List acceptedVersions = Collections.singletonList("2.1.9.RELEASE"); - SpringBootVersionVerifier - versionVerifier = new SpringBootVersionVerifier(acceptedVersions) { + SpringBootVersionVerifier versionVerifier = new SpringBootVersionVerifier( + acceptedVersions) { @Override String getVersionFromManifest() { return "2.1.3.RELEASE"; @@ -62,8 +62,8 @@ public class SpringBootDependencyTests { @Test public void should_read_concrete_version_from_manifest_and_return_false_when_minor_version_is_not_matched() { List acceptedVersions = Collections.singletonList("2.1"); - SpringBootVersionVerifier - versionVerifier = new SpringBootVersionVerifier(acceptedVersions) { + SpringBootVersionVerifier versionVerifier = new SpringBootVersionVerifier( + acceptedVersions) { @Override String getVersionFromManifest() { return "2.99.3.RELEASE"; @@ -80,8 +80,8 @@ public class SpringBootDependencyTests { @Test public void should_read_concrete_version_from_manifest_and_match_it_against_minor_version() { List acceptedVersions = Collections.singletonList("2.1"); - SpringBootVersionVerifier - versionVerifier = new SpringBootVersionVerifier(acceptedVersions) { + SpringBootVersionVerifier versionVerifier = new SpringBootVersionVerifier( + acceptedVersions) { @Override String getVersionFromManifest() { return "2.1.3.RELEASE"; @@ -98,8 +98,8 @@ public class SpringBootDependencyTests { @Test public void should_match_against_predicate() { List acceptedVersions = Collections.singletonList("2.5"); - SpringBootVersionVerifier - versionVerifier = new SpringBootVersionVerifier(acceptedVersions) { + SpringBootVersionVerifier versionVerifier = new SpringBootVersionVerifier( + acceptedVersions) { @Override String getVersionFromManifest() { return ""; @@ -122,8 +122,8 @@ public class SpringBootDependencyTests { @Test public void should_fail_to_match_against_predicate_when_none_is_matching() { List acceptedVersions = Collections.singletonList("2.5"); - SpringBootVersionVerifier - versionVerifier = new SpringBootVersionVerifier(acceptedVersions) { + SpringBootVersionVerifier versionVerifier = new SpringBootVersionVerifier( + acceptedVersions) { @Override String getVersionFromManifest() { return ""; @@ -140,8 +140,8 @@ public class SpringBootDependencyTests { @Test public void should_match_against_current_manifest() { List acceptedVersions = Collections.singletonList("2.1"); - SpringBootVersionVerifier - versionVerifier = new SpringBootVersionVerifier(acceptedVersions); + SpringBootVersionVerifier versionVerifier = new SpringBootVersionVerifier( + acceptedVersions); versionVerifier.ACCEPTED_VERSIONS.clear(); VerificationResult verificationResult = versionVerifier.verify(); @@ -153,8 +153,8 @@ public class SpringBootDependencyTests { @Test public void should_match_against_current_predicate() { List acceptedVersions = Collections.singletonList("2.1"); - SpringBootVersionVerifier - versionVerifier = new SpringBootVersionVerifier(acceptedVersions){ + SpringBootVersionVerifier versionVerifier = new SpringBootVersionVerifier( + acceptedVersions) { @Override String getVersionFromManifest() { return ""; @@ -172,8 +172,8 @@ public class SpringBootDependencyTests { @Test public void should_match_against_current_predicate_with_version_ending_with_x() { List acceptedVersions = Collections.singletonList("2.1.x"); - SpringBootVersionVerifier - versionVerifier = new SpringBootVersionVerifier(acceptedVersions){ + SpringBootVersionVerifier versionVerifier = new SpringBootVersionVerifier( + acceptedVersions) { @Override String getVersionFromManifest() { return ""; @@ -191,8 +191,8 @@ public class SpringBootDependencyTests { @Test public void should_fail_to_match_against_predicate_for_non_current_versions() { List acceptedVersions = Collections.singletonList("2.1"); - SpringBootVersionVerifier - versionVerifier = new SpringBootVersionVerifier(acceptedVersions) { + SpringBootVersionVerifier versionVerifier = new SpringBootVersionVerifier( + acceptedVersions) { @Override String getVersionFromManifest() { return ""; @@ -206,4 +206,4 @@ public class SpringBootDependencyTests { BDDAssertions.then(verificationResult.action).isNotEmpty(); } -} \ No newline at end of file +} diff --git a/spring-cloud-commons/src/test/resources/application-encrypt.properties b/spring-cloud-commons/src/test/resources/application-encrypt.properties index b1329f64..d57ed3fe 100644 --- a/spring-cloud-commons/src/test/resources/application-encrypt.properties +++ b/spring-cloud-commons/src/test/resources/application-encrypt.properties @@ -1 +1,2 @@ -foo: {cipher}e4e061f9fe39ba5b14d8012d2f17d39775606039409b71ed4be0fdd033d5324a +foo:{cipher}e4e061f9fe39ba5b14d8012d2f17d39775606039409b71ed4be0fdd033d5324a + diff --git a/spring-cloud-commons/src/test/resources/application.properties b/spring-cloud-commons/src/test/resources/application.properties index 72f38d17..a3c02545 100644 --- a/spring-cloud-commons/src/test/resources/application.properties +++ b/spring-cloud-commons/src/test/resources/application.properties @@ -1,9 +1,9 @@ -message: Hello scope! -delay: 0 -debug: true +message:Hello scope! +delay:0 +debug:true #logging.level.org.springframework.web: DEBUG #logging.level.org.springframework.context.annotation: DEBUG - spring.cloud.hypermedia.refresh.initial-delay=50000 spring.cloud.hypermedia.refresh.fixed-delay=10000 management.security.enabled=false + diff --git a/spring-cloud-commons/src/test/resources/bootstrap-encrypt.properties b/spring-cloud-commons/src/test/resources/bootstrap-encrypt.properties index 3035e009..81ce3411 100644 --- a/spring-cloud-commons/src/test/resources/bootstrap-encrypt.properties +++ b/spring-cloud-commons/src/test/resources/bootstrap-encrypt.properties @@ -1 +1 @@ -bar: {cipher}6154ca04d4bb6144d672c4e3d750b5147116dd381946d51fa44f8bc25dc256f4 \ No newline at end of file +bar:{cipher}6154ca04d4bb6144d672c4e3d750b5147116dd381946d51fa44f8bc25dc256f4 diff --git a/spring-cloud-commons/src/test/resources/bootstrap-parent.properties b/spring-cloud-commons/src/test/resources/bootstrap-parent.properties index 0c36bbdd..3ff20cea 100644 --- a/spring-cloud-commons/src/test/resources/bootstrap-parent.properties +++ b/spring-cloud-commons/src/test/resources/bootstrap-parent.properties @@ -1 +1 @@ -info.name: parent \ No newline at end of file +info.name:parent diff --git a/spring-cloud-commons/src/test/resources/bootstrap.properties b/spring-cloud-commons/src/test/resources/bootstrap.properties index 9ec10bf9..8c8931c8 100644 --- a/spring-cloud-commons/src/test/resources/bootstrap.properties +++ b/spring-cloud-commons/src/test/resources/bootstrap.properties @@ -1,2 +1,3 @@ -spring.main.sources: org.springframework.cloud.bootstrap.config.BootstrapConfigurationTests.PropertySourceConfiguration -info.name: child +spring.main.sources:org.springframework.cloud.bootstrap.config.BootstrapConfigurationTests.PropertySourceConfiguration +info.name:child + diff --git a/spring-cloud-commons/src/test/resources/external-properties/bootstrap.properties b/spring-cloud-commons/src/test/resources/external-properties/bootstrap.properties index 925265df..49cbc6ac 100644 --- a/spring-cloud-commons/src/test/resources/external-properties/bootstrap.properties +++ b/spring-cloud-commons/src/test/resources/external-properties/bootstrap.properties @@ -1 +1 @@ -info.name: externalPropertiesInfoName \ No newline at end of file +info.name:externalPropertiesInfoName diff --git a/spring-cloud-commons/src/test/resources/other.properties b/spring-cloud-commons/src/test/resources/other.properties index dc756282..0c4bb2a0 100644 --- a/spring-cloud-commons/src/test/resources/other.properties +++ b/spring-cloud-commons/src/test/resources/other.properties @@ -1 +1 @@ -spring.application.name: main \ No newline at end of file +spring.application.name:main diff --git a/spring-cloud-commons/src/test/resources/plain.properties b/spring-cloud-commons/src/test/resources/plain.properties index aa8f5408..132334be 100644 --- a/spring-cloud-commons/src/test/resources/plain.properties +++ b/spring-cloud-commons/src/test/resources/plain.properties @@ -1 +1 @@ -spring.application.name: app +spring.application.name:app diff --git a/spring-cloud-context-integration-tests/eclipse/eclipse-code-formatter.xml b/spring-cloud-context-integration-tests/eclipse/eclipse-code-formatter.xml index 4694d7f2..5cbf769b 100644 --- a/spring-cloud-context-integration-tests/eclipse/eclipse-code-formatter.xml +++ b/spring-cloud-context-integration-tests/eclipse/eclipse-code-formatter.xml @@ -1,295 +1,754 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spring-cloud-context-integration-tests/pom.xml b/spring-cloud-context-integration-tests/pom.xml index 41e71802..0a7bfce5 100644 --- a/spring-cloud-context-integration-tests/pom.xml +++ b/spring-cloud-context-integration-tests/pom.xml @@ -1,6 +1,7 @@ - + 4.0.0 diff --git a/spring-cloud-context-integration-tests/src/test/java/org/springframework/cloud/autoconfigure/RefreshScopeIntegrationTests.java b/spring-cloud-context-integration-tests/src/test/java/org/springframework/cloud/autoconfigure/RefreshScopeIntegrationTests.java index 47c6b6c6..cec09d0e 100644 --- a/spring-cloud-context-integration-tests/src/test/java/org/springframework/cloud/autoconfigure/RefreshScopeIntegrationTests.java +++ b/spring-cloud-context-integration-tests/src/test/java/org/springframework/cloud/autoconfigure/RefreshScopeIntegrationTests.java @@ -145,12 +145,29 @@ public class RefreshScopeIntegrationTests { private static Log logger = LogFactory.getLog(ExampleService.class); private volatile static int initCount = 0; + private volatile static int destroyCount = 0; + private volatile static RefreshScopeRefreshedEvent event; private String message = null; + private volatile long delay = 0; + public static void reset() { + initCount = 0; + destroyCount = 0; + event = null; + } + + public static int getInitCount() { + return initCount; + } + + public static int getDestroyCount() { + return destroyCount; + } + public void setDelay(long delay) { this.delay = delay; } @@ -168,25 +185,6 @@ public class RefreshScopeIntegrationTests { this.message = null; } - public static void reset() { - initCount = 0; - destroyCount = 0; - event = null; - } - - public static int getInitCount() { - return initCount; - } - - public static int getDestroyCount() { - return destroyCount; - } - - public void setMessage(String message) { - logger.debug("Setting message: " + message); - this.message = message; - } - @Override public String getMessage() { logger.debug("Getting message: " + this.message); @@ -200,6 +198,11 @@ public class RefreshScopeIntegrationTests { return this.message; } + public void setMessage(String message) { + logger.debug("Setting message: " + message); + this.message = message; + } + @Override public String throwsException() throws ServiceException { throw new ServiceException(); @@ -209,10 +212,13 @@ public class RefreshScopeIntegrationTests { public void onApplicationEvent(RefreshScopeRefreshedEvent e) { event = e; } + } @SuppressWarnings("serial") - public static class ServiceException extends Exception {} + public static class ServiceException extends Exception { + + } @Configuration @EnableConfigurationProperties(TestProperties.class) @@ -236,7 +242,9 @@ public class RefreshScopeIntegrationTests { @ConfigurationProperties @ManagedResource protected static class TestProperties { + private String message; + private int delay; @ManagedAttribute @@ -256,6 +264,7 @@ public class RefreshScopeIntegrationTests { public void setDelay(int delay) { this.delay = delay; } + } } diff --git a/spring-cloud-context-integration-tests/src/test/resources/application.properties b/spring-cloud-context-integration-tests/src/test/resources/application.properties index a57fb091..9246b588 100644 --- a/spring-cloud-context-integration-tests/src/test/resources/application.properties +++ b/spring-cloud-context-integration-tests/src/test/resources/application.properties @@ -1,8 +1,8 @@ -message: Hello scope! -delay: 0 -debug: true +message:Hello scope! +delay:0 +debug:true #logging.level.org.springframework.web: DEBUG #logging.level.org.springframework.context.annotation: DEBUG logging.level.org.hibernate=ERROR logging.level.com.zaxxer.hikari=ERROR -spring.datasource.initialization-mode=always \ No newline at end of file +spring.datasource.initialization-mode=always diff --git a/spring-cloud-context-integration-tests/src/test/resources/bootstrap.properties b/spring-cloud-context-integration-tests/src/test/resources/bootstrap.properties index 8d342078..90319f84 100644 --- a/spring-cloud-context-integration-tests/src/test/resources/bootstrap.properties +++ b/spring-cloud-context-integration-tests/src/test/resources/bootstrap.properties @@ -1 +1 @@ -info.name: child +info.name:child diff --git a/spring-cloud-context/eclipse/eclipse-code-formatter.xml b/spring-cloud-context/eclipse/eclipse-code-formatter.xml index 4694d7f2..5cbf769b 100644 --- a/spring-cloud-context/eclipse/eclipse-code-formatter.xml +++ b/spring-cloud-context/eclipse/eclipse-code-formatter.xml @@ -1,295 +1,754 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spring-cloud-context/pom.xml b/spring-cloud-context/pom.xml index 0302ef09..9b2867cf 100644 --- a/spring-cloud-context/pom.xml +++ b/spring-cloud-context/pom.xml @@ -1,6 +1,7 @@ - + 4.0.0 diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/autoconfigure/ConfigurationPropertiesRebinderAutoConfiguration.java b/spring-cloud-context/src/main/java/org/springframework/cloud/autoconfigure/ConfigurationPropertiesRebinderAutoConfiguration.java index 110dfd40..77228a05 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/autoconfigure/ConfigurationPropertiesRebinderAutoConfiguration.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/autoconfigure/ConfigurationPropertiesRebinderAutoConfiguration.java @@ -29,6 +29,11 @@ import org.springframework.context.ApplicationContextAware; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +/** + * Auto-configuration for {@link ConfigurationPropertiesRebinder}. + * + * @author Dave Syer + */ @Configuration @ConditionalOnBean(ConfigurationPropertiesBindingPostProcessor.class) public class ConfigurationPropertiesRebinderAutoConfiguration @@ -50,7 +55,7 @@ public class ConfigurationPropertiesRebinderAutoConfiguration // choice). ConfigurationBeanFactoryMetadata metaData = this.context.getBean( ConfigurationBeanFactoryMetadata.BEAN_NAME, - ConfigurationBeanFactoryMetadata.class); + ConfigurationBeanFactoryMetadata.class); ConfigurationPropertiesBeans beans = new ConfigurationPropertiesBeans(); beans.setBeanMetaDataStore(metaData); return beans; @@ -75,11 +80,12 @@ public class ConfigurationPropertiesRebinderAutoConfiguration if (this.context.getParent() != null) { // TODO: make this optional? (E.g. when creating child contexts that prefer to // be isolated.) - ConfigurationPropertiesRebinder rebinder = context + ConfigurationPropertiesRebinder rebinder = this.context .getBean(ConfigurationPropertiesRebinder.class); - for (String name : context.getParent().getBeanDefinitionNames()) { + for (String name : this.context.getParent().getBeanDefinitionNames()) { rebinder.rebind(name); } } } -} \ No newline at end of file + +} diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/autoconfigure/LifecycleMvcEndpointAutoConfiguration.java b/spring-cloud-context/src/main/java/org/springframework/cloud/autoconfigure/LifecycleMvcEndpointAutoConfiguration.java index 66c554cd..5a8ad8fa 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/autoconfigure/LifecycleMvcEndpointAutoConfiguration.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/autoconfigure/LifecycleMvcEndpointAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2012-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. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.autoconfigure; import org.springframework.boot.autoconfigure.AutoConfigureAfter; diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/autoconfigure/RefreshAutoConfiguration.java b/spring-cloud-context/src/main/java/org/springframework/cloud/autoconfigure/RefreshAutoConfiguration.java index 28988c7f..67264312 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/autoconfigure/RefreshAutoConfiguration.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/autoconfigure/RefreshAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2014 the original author or authors. + * Copyright 2012-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. @@ -12,7 +12,6 @@ * WITHOUT 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.autoconfigure; @@ -68,8 +67,19 @@ import org.springframework.util.StringUtils; @AutoConfigureBefore(HibernateJpaAutoConfiguration.class) public class RefreshAutoConfiguration { + /** + * Name of the refresh scope name. + */ public static final String REFRESH_SCOPE_NAME = "refresh"; + + /** + * Name of the prefix for refresh scope. + */ public static final String REFRESH_SCOPE_PREFIX = "spring.cloud.refresh"; + + /** + * Name of the enabled prefix for refresh scope. + */ public static final String REFRESH_SCOPE_ENABLED = REFRESH_SCOPE_PREFIX + ".enabled"; @Bean @@ -78,6 +88,24 @@ public class RefreshAutoConfiguration { return new RefreshScope(); } + @Bean + @ConditionalOnMissingBean + public static LoggingRebinder loggingRebinder() { + return new LoggingRebinder(); + } + + @Bean + @ConditionalOnMissingBean + public ContextRefresher contextRefresher(ConfigurableApplicationContext context, + RefreshScope scope) { + return new ContextRefresher(context, scope); + } + + @Bean + public RefreshEventListener refreshEventListener(ContextRefresher contextRefresher) { + return new RefreshEventListener(contextRefresher); + } + @Configuration @ConditionalOnClass(name = "javax.persistence.EntityManagerFactory") protected static class JpaInvokerConfiguration implements LoadTimeWeaverAware { @@ -88,8 +116,8 @@ public class RefreshAutoConfiguration { @PostConstruct public void init() { String cls = "org.springframework.boot.autoconfigure.jdbc.DataSourceInitializerInvoker"; - if (beanFactory.containsBean(cls)) { - beanFactory.getBean(cls); + if (this.beanFactory.containsBean(cls)) { + this.beanFactory.getBean(cls); } } @@ -176,13 +204,13 @@ public class RefreshAutoConfiguration { } private void bindEnvironmentIfNeeded(BeanDefinitionRegistry registry) { - if (!bound) { // only bind once + if (!this.bound) { // only bind once if (this.environment == null) { this.environment = new StandardEnvironment(); } - Binder.get(environment).bind("spring.cloud.refresh", + Binder.get(this.environment).bind("spring.cloud.refresh", Bindable.ofInstance(this)); - bound = true; + this.bound = true; } } @@ -190,24 +218,7 @@ public class RefreshAutoConfiguration { public void setEnvironment(Environment environment) { this.environment = environment; } - } - @Bean - @ConditionalOnMissingBean - public static LoggingRebinder loggingRebinder() { - return new LoggingRebinder(); - } - - @Bean - @ConditionalOnMissingBean - public ContextRefresher contextRefresher(ConfigurableApplicationContext context, - RefreshScope scope) { - return new ContextRefresher(context, scope); - } - - @Bean - public RefreshEventListener refreshEventListener(ContextRefresher contextRefresher) { - return new RefreshEventListener(contextRefresher); } } diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/autoconfigure/RefreshEndpointAutoConfiguration.java b/spring-cloud-context/src/main/java/org/springframework/cloud/autoconfigure/RefreshEndpointAutoConfiguration.java index 4f440f91..1a8735ec 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/autoconfigure/RefreshEndpointAutoConfiguration.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/autoconfigure/RefreshEndpointAutoConfiguration.java @@ -45,9 +45,9 @@ import org.springframework.integration.monitor.IntegrationMBeanExporter; * @author Venil Noronha */ @Configuration -@ConditionalOnClass({EndpointAutoConfiguration.class, Health.class}) +@ConditionalOnClass({ EndpointAutoConfiguration.class, Health.class }) @AutoConfigureAfter({ LifecycleMvcEndpointAutoConfiguration.class, - RefreshAutoConfiguration.class}) + RefreshAutoConfiguration.class }) @Import({ RestartEndpointWithIntegrationConfiguration.class, RestartEndpointWithoutIntegrationConfiguration.class, PauseResumeEndpointsConfiguration.class }) @@ -56,8 +56,9 @@ public class RefreshEndpointAutoConfiguration { @Bean @ConditionalOnMissingBean @ConditionalOnEnabledHealthIndicator("refresh") - RefreshScopeHealthIndicator refreshScopeHealthIndicator(ObjectProvider scope, - ConfigurationPropertiesRebinder rebinder) { + RefreshScopeHealthIndicator refreshScopeHealthIndicator( + ObjectProvider scope, + ConfigurationPropertiesRebinder rebinder) { return new RefreshScopeHealthIndicator(scope, rebinder); } @@ -74,6 +75,7 @@ public class RefreshEndpointAutoConfiguration { } } + } @Configuration diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/autoconfigure/WritableEnvironmentEndpointAutoConfiguration.java b/spring-cloud-context/src/main/java/org/springframework/cloud/autoconfigure/WritableEnvironmentEndpointAutoConfiguration.java index aa2e62ce..7bed60c6 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/autoconfigure/WritableEnvironmentEndpointAutoConfiguration.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/autoconfigure/WritableEnvironmentEndpointAutoConfiguration.java @@ -1,3 +1,19 @@ +/* + * Copyright 2012-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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.autoconfigure; import org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnEnabledEndpoint; @@ -46,7 +62,8 @@ public class WritableEnvironmentEndpointAutoConfiguration { @ConditionalOnMissingBean @ConditionalOnEnabledEndpoint public WritableEnvironmentEndpoint environmentEndpoint(Environment environment) { - WritableEnvironmentEndpoint endpoint = new WritableEnvironmentEndpoint(environment); + WritableEnvironmentEndpoint endpoint = new WritableEnvironmentEndpoint( + environment); String[] keysToSanitize = this.properties.getKeysToSanitize(); if (keysToSanitize != null) { endpoint.setKeysToSanitize(keysToSanitize); diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/BootstrapApplicationListener.java b/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/BootstrapApplicationListener.java index 73406c30..a9c67e1e 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/BootstrapApplicationListener.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/BootstrapApplicationListener.java @@ -71,10 +71,19 @@ import org.springframework.util.StringUtils; public class BootstrapApplicationListener implements ApplicationListener, Ordered { + /** + * Property source name for bootstrap. + */ public static final String BOOTSTRAP_PROPERTY_SOURCE_NAME = "bootstrap"; + /** + * The default order for this listener. + */ public static final int DEFAULT_ORDER = Ordered.HIGHEST_PRECEDENCE + 5; + /** + * The name of the default properties. + */ public static final String DEFAULT_PROPERTIES = "defaultProperties"; private int order = DEFAULT_ORDER; @@ -104,7 +113,8 @@ public class BootstrapApplicationListener if (context == null) { context = bootstrapServiceContext(environment, event.getSpringApplication(), configName); - event.getSpringApplication().addListeners(new CloseContextOnFailureApplicationListener(context)); + event.getSpringApplication() + .addListeners(new CloseContextOnFailureApplicationListener(context)); } apply(context, event.getSpringApplication(), environment); @@ -146,8 +156,10 @@ public class BootstrapApplicationListener .resolvePlaceholders("${spring.cloud.bootstrap.location:}"); Map bootstrapMap = new HashMap<>(); bootstrapMap.put("spring.config.name", configName); - // if an app (or test) uses spring.main.web-application-type=reactive, bootstrap will fail - // force the environment to use none, because if though it is set below in the builder + // if an app (or test) uses spring.main.web-application-type=reactive, bootstrap + // will fail + // force the environment to use none, because if though it is set below in the + // builder // the environment overrides it bootstrapMap.put("spring.main.web-application-type", "none"); if (StringUtils.hasText(configLocation)) { @@ -169,7 +181,7 @@ public class BootstrapApplicationListener .registerShutdownHook(false).logStartupInfo(false) .web(WebApplicationType.NONE); final SpringApplication builderApplication = builder.application(); - if(builderApplication.getMainApplicationClass() == null){ + if (builderApplication.getMainApplicationClass() == null) { // gh_425: // SpringApplication cannot deduce the MainApplicationClass here // if it is booted from SpringBootServletInitializer due to the @@ -225,18 +237,14 @@ public class BootstrapApplicationListener } else { PropertySource target = environment.get(name); - if (target instanceof MapPropertySource) { + if (target instanceof MapPropertySource && target != source + && source instanceof MapPropertySource) { Map targetMap = ((MapPropertySource) target) .getSource(); - if (target != source) { - if (source instanceof MapPropertySource) { - Map map = ((MapPropertySource) source) - .getSource(); - for (String key : map.keySet()) { - if (!target.containsProperty(key)) { - targetMap.put(key, map.get(key)); - } - } + Map map = ((MapPropertySource) source).getSource(); + for (String key : map.keySet()) { + if (!target.containsProperty(key)) { + targetMap.put(key, map.get(key)); } } } @@ -303,13 +311,11 @@ public class BootstrapApplicationListener private void addBootstrapDecryptInitializer(SpringApplication application) { DelegatingEnvironmentDecryptApplicationInitializer decrypter = null; - for (ApplicationContextInitializer initializer : application - .getInitializers()) { - if (initializer instanceof EnvironmentDecryptApplicationInitializer) { + for (ApplicationContextInitializer ini : application.getInitializers()) { + if (ini instanceof EnvironmentDecryptApplicationInitializer) { @SuppressWarnings("unchecked") - ApplicationContextInitializer delegate = (ApplicationContextInitializer) initializer; - decrypter = new DelegatingEnvironmentDecryptApplicationInitializer( - delegate); + ApplicationContextInitializer del = (ApplicationContextInitializer) ini; + decrypter = new DelegatingEnvironmentDecryptApplicationInitializer(del); } } if (decrypter != null) { @@ -327,21 +333,21 @@ public class BootstrapApplicationListener return result; } - public void setOrder(int order) { - this.order = order; - } - @Override public int getOrder() { return this.order; } + public void setOrder(int order) { + this.order = order; + } + private static class AncestorInitializer implements ApplicationContextInitializer, Ordered { private ConfigurableApplicationContext parent; - public AncestorInitializer(ConfigurableApplicationContext parent) { + AncestorInitializer(ConfigurableApplicationContext parent) { this.parent = parent; } @@ -397,7 +403,7 @@ public class BootstrapApplicationListener private ApplicationContextInitializer delegate; - public DelegatingEnvironmentDecryptApplicationInitializer( + DelegatingEnvironmentDecryptApplicationInitializer( ApplicationContextInitializer delegate) { this.delegate = delegate; } @@ -413,14 +419,22 @@ public class BootstrapApplicationListener extends SystemEnvironmentPropertySource { private final CompositePropertySource sources; + private final List names = new ArrayList<>(); - public ExtendedDefaultPropertySource(String name, - PropertySource propertySource) { + ExtendedDefaultPropertySource(String name, PropertySource propertySource) { super(name, findMap(propertySource)); this.sources = new CompositePropertySource(name); } + @SuppressWarnings("unchecked") + private static Map findMap(PropertySource propertySource) { + if (propertySource instanceof MapPropertySource) { + return (Map) propertySource.getSource(); + } + return new LinkedHashMap(); + } + public CompositePropertySource getPropertySources() { return this.sources; } @@ -461,21 +475,14 @@ public class BootstrapApplicationListener return names.toArray(new String[0]); } - @SuppressWarnings("unchecked") - private static Map findMap(PropertySource propertySource) { - if (propertySource instanceof MapPropertySource) { - return (Map) propertySource.getSource(); - } - return new LinkedHashMap(); - } - } - private static class CloseContextOnFailureApplicationListener implements SmartApplicationListener { + private static class CloseContextOnFailureApplicationListener + implements SmartApplicationListener { private final ConfigurableApplicationContext context; - public CloseContextOnFailureApplicationListener(ConfigurableApplicationContext context) { + CloseContextOnFailureApplicationListener(ConfigurableApplicationContext context) { this.context = context; } @@ -491,6 +498,7 @@ public class BootstrapApplicationListener } } + } } diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/BootstrapConfiguration.java b/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/BootstrapConfiguration.java index 5343950d..34038eb3 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/BootstrapConfiguration.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/BootstrapConfiguration.java @@ -1,15 +1,19 @@ /* - * Copyright 2013-2014 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 - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on - * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. + * Copyright 2012-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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.bootstrap; import java.lang.annotation.Documented; @@ -21,7 +25,7 @@ import java.lang.annotation.Target; /** * A marker interface used as a key in META-INF/spring.factories. Entries in * the factories file are used to create the bootstrap application context. - * + * * @author Dave Syer * */ @@ -32,6 +36,7 @@ public @interface BootstrapConfiguration { /** * Excludes specific auto-configuration classes such that they will never be applied. + * @return classes to exclude */ Class[] exclude() default {}; diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/BootstrapImportSelector.java b/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/BootstrapImportSelector.java index 9f36210f..9e192193 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/BootstrapImportSelector.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/BootstrapImportSelector.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-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. @@ -39,10 +39,12 @@ import org.springframework.util.StringUtils; /** * This class uses {@link SpringFactoriesLoader} to load {@link BootstrapConfiguration} - * entries from {@code spring.factories}. The classes are then loaded so they can - * be sorted using {@link AnnotationAwareOrderComparator#sort(List)}. - * This class is a {@link DeferredImportSelector} so {@code @Conditional} annotations - * on imported classes are supported. + * entries from {@code spring.factories}. The classes are then loaded so they can be + * sorted using {@link AnnotationAwareOrderComparator#sort(List)}. This class is a + * {@link DeferredImportSelector} so {@code @Conditional} annotations on imported classes + * are supported. + * + * @author Spencer Gibb */ public class BootstrapImportSelector implements EnvironmentAware, DeferredImportSelector { @@ -62,21 +64,21 @@ public class BootstrapImportSelector implements EnvironmentAware, DeferredImport List names = new ArrayList<>(SpringFactoriesLoader .loadFactoryNames(BootstrapConfiguration.class, classLoader)); names.addAll(Arrays.asList(StringUtils.commaDelimitedListToStringArray( - environment.getProperty("spring.cloud.bootstrap.sources", "")))); + this.environment.getProperty("spring.cloud.bootstrap.sources", "")))); List elements = new ArrayList<>(); for (String name : names) { try { - elements.add(new OrderedAnnotatedElement(metadataReaderFactory, name)); - } catch (IOException e) { + elements.add( + new OrderedAnnotatedElement(this.metadataReaderFactory, name)); + } + catch (IOException e) { continue; } } AnnotationAwareOrderComparator.sort(elements); - String[] classNames = elements.stream() - .map(e -> e.name) - .toArray(String[]::new); + String[] classNames = elements.stream().map(e -> e.name).toArray(String[]::new); return classNames; } @@ -84,17 +86,21 @@ public class BootstrapImportSelector implements EnvironmentAware, DeferredImport class OrderedAnnotatedElement implements AnnotatedElement { private final String name; + private Order order = null; + private Integer value; - public OrderedAnnotatedElement(MetadataReaderFactory metadataReaderFactory, String name) throws IOException { + OrderedAnnotatedElement(MetadataReaderFactory metadataReaderFactory, String name) + throws IOException { MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(name); AnnotationMetadata metadata = metadataReader.getAnnotationMetadata(); - Map attributes = metadata.getAnnotationAttributes(Order.class.getName()); + Map attributes = metadata + .getAnnotationAttributes(Order.class.getName()); this.name = name; if (attributes != null && attributes.containsKey("value")) { - value = (Integer) attributes.get("value"); - order = new Order() { + this.value = (Integer) attributes.get("value"); + this.order = new Order() { @Override public Class annotationType() { return Order.class; @@ -102,7 +108,7 @@ public class BootstrapImportSelector implements EnvironmentAware, DeferredImport @Override public int value() { - return value; + return OrderedAnnotatedElement.this.value; } }; } @@ -112,14 +118,15 @@ public class BootstrapImportSelector implements EnvironmentAware, DeferredImport @SuppressWarnings("unchecked") public T getAnnotation(Class annotationClass) { if (annotationClass == Order.class) { - return (T) order; + return (T) this.order; } return null; } @Override public Annotation[] getAnnotations() { - return order == null ? new Annotation[0] : new Annotation[]{order}; + return this.order == null ? new Annotation[0] + : new Annotation[] { this.order }; } @Override @@ -129,10 +136,10 @@ public class BootstrapImportSelector implements EnvironmentAware, DeferredImport @Override public String toString() { - return new ToStringCreator(this) - .append("name", name) - .append("value", value) - .toString(); + return new ToStringCreator(this).append("name", this.name) + .append("value", this.value).toString(); } + } + } diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/BootstrapImportSelectorConfiguration.java b/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/BootstrapImportSelectorConfiguration.java index 318cdde1..b991e025 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/BootstrapImportSelectorConfiguration.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/BootstrapImportSelectorConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-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. @@ -19,7 +19,13 @@ package org.springframework.cloud.bootstrap; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; +/** + * Configuration to import the {@link BootstrapImportSelector} configuration. + * + * @author Spencer Gibb + */ @Configuration @Import(BootstrapImportSelector.class) public class BootstrapImportSelectorConfiguration { + } diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/LoggingSystemShutdownListener.java b/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/LoggingSystemShutdownListener.java index 684e0098..b348c4de 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/LoggingSystemShutdownListener.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/LoggingSystemShutdownListener.java @@ -33,6 +33,9 @@ import org.springframework.util.ClassUtils; public class LoggingSystemShutdownListener implements ApplicationListener, Ordered { + /** + * Default order for the listener. + */ public static final int DEFAULT_ORDER = BootstrapApplicationListener.DEFAULT_ORDER + 1; @@ -50,13 +53,13 @@ public class LoggingSystemShutdownListener loggingSystem.beforeInitialize(); } - public void setOrder(int order) { - this.order = order; - } - @Override public int getOrder() { return this.order; } + public void setOrder(int order) { + this.order = order; + } + } diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/config/PropertySourceBootstrapConfiguration.java b/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/config/PropertySourceBootstrapConfiguration.java index 3a272fca..c70fcc1f 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/config/PropertySourceBootstrapConfiguration.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/config/PropertySourceBootstrapConfiguration.java @@ -61,6 +61,9 @@ import org.springframework.util.StringUtils; public class PropertySourceBootstrapConfiguration implements ApplicationContextInitializer, Ordered { + /** + * Bootstrap property source name. + */ public static final String BOOTSTRAP_PROPERTY_SOURCE_NAME = BootstrapApplicationListener.BOOTSTRAP_PROPERTY_SOURCE_NAME + "Properties"; @@ -116,7 +119,8 @@ public class PropertySourceBootstrapConfiguration implements private void reinitializeLoggingSystem(ConfigurableEnvironment environment, String oldLogConfig, LogFile oldLogFile) { Map props = Binder.get(environment) - .bind("logging", Bindable.mapOf(String.class, Object.class)).orElseGet(Collections::emptyMap); + .bind("logging", Bindable.mapOf(String.class, Object.class)) + .orElseGet(Collections::emptyMap); if (!props.isEmpty()) { String logConfig = environment.resolvePlaceholders("${logging.config:}"); LogFile logFile = LogFile.get(environment); @@ -154,7 +158,8 @@ public class PropertySourceBootstrapConfiguration implements MutablePropertySources incoming = new MutablePropertySources(); incoming.addFirst(composite); PropertySourceBootstrapProperties remoteProperties = new PropertySourceBootstrapProperties(); - Binder.get(environment(incoming)).bind("spring.cloud.config", Bindable.ofInstance(remoteProperties)); + Binder.get(environment(incoming)).bind("spring.cloud.config", + Bindable.ofInstance(remoteProperties)); if (!remoteProperties.isAllowOverride() || (!remoteProperties.isOverrideNone() && remoteProperties.isOverrideSystemProperties())) { propertySources.addFirst(composite); @@ -231,7 +236,8 @@ public class PropertySourceBootstrapConfiguration implements private String[] getProfilesForValue(Object property) { final String value = (property == null ? null : property.toString()); - return property == null ? new String[0] : StringUtils.tokenizeToStringArray(value, ","); + return property == null ? new String[0] + : StringUtils.tokenizeToStringArray(value, ","); } } diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/config/PropertySourceBootstrapProperties.java b/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/config/PropertySourceBootstrapProperties.java index f686cc44..3eece617 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/config/PropertySourceBootstrapProperties.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/config/PropertySourceBootstrapProperties.java @@ -1,7 +1,28 @@ +/* + * Copyright 2012-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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.bootstrap.config; import org.springframework.boot.context.properties.ConfigurationProperties; +/** + * Properties for Spring Cloud Config bootstrap. + * + * @author Dave Syer + */ @ConfigurationProperties("spring.cloud.config") public class PropertySourceBootstrapProperties { diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/config/PropertySourceLocator.java b/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/config/PropertySourceLocator.java index ea6bcf10..066217a3 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/config/PropertySourceLocator.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/config/PropertySourceLocator.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2014 the original author or authors. + * Copyright 2012-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. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.bootstrap.config; import org.springframework.core.env.Environment; @@ -22,7 +23,7 @@ import org.springframework.core.env.PropertySource; * Strategy for locating (possibly remote) property sources for the Environment. * Implementations should not fail unless they intend to prevent the application from * starting. - * + * * @author Dave Syer * */ @@ -31,7 +32,6 @@ public interface PropertySourceLocator { /** * @param environment The current Environment. * @return A PropertySource, or null if there is none. - * * @throws IllegalStateException if there is a fail-fast condition. */ PropertySource locate(Environment environment); diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/encrypt/EncryptionBootstrapConfiguration.java b/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/encrypt/EncryptionBootstrapConfiguration.java index c437c92d..074b4ffe 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/encrypt/EncryptionBootstrapConfiguration.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/encrypt/EncryptionBootstrapConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2014 the original author or authors. + * Copyright 2012-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. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.bootstrap.encrypt; import org.springframework.beans.factory.annotation.Autowired; @@ -41,7 +42,7 @@ import org.springframework.util.StringUtils; */ @Configuration @ConditionalOnClass({ TextEncryptor.class }) -@EnableConfigurationProperties({KeyProperties.class}) +@EnableConfigurationProperties({ KeyProperties.class }) public class EncryptionBootstrapConfiguration { @Autowired(required = false) @@ -50,10 +51,21 @@ public class EncryptionBootstrapConfiguration { @Autowired private KeyProperties key; + @Bean + public EnvironmentDecryptApplicationInitializer environmentDecryptApplicationListener() { + if (this.encryptor == null) { + this.encryptor = new FailsafeTextEncryptor(); + } + EnvironmentDecryptApplicationInitializer listener = new EnvironmentDecryptApplicationInitializer( + this.encryptor); + listener.setFailOnError(this.key.isFailOnError()); + return listener; + } + @Configuration @Conditional(KeyCondition.class) @ConditionalOnClass(RsaSecretEncryptor.class) - @EnableConfigurationProperties({RsaProperties.class}) + @EnableConfigurationProperties({ RsaProperties.class }) protected static class RsaEncryptionConfiguration { @Autowired @@ -73,10 +85,10 @@ public class EncryptionBootstrapConfiguration { keyStore.getPassword().toCharArray()).getKeyPair( keyStore.getAlias(), keyStore.getSecret().toCharArray()), - this.rsaProperties.getAlgorithm(), this.rsaProperties.getSalt(), - this.rsaProperties.isStrong()); - } - + this.rsaProperties.getAlgorithm(), + this.rsaProperties.getSalt(), this.rsaProperties.isStrong()); + } + throw new IllegalStateException("Invalid keystore location"); } @@ -101,17 +113,9 @@ public class EncryptionBootstrapConfiguration { } - @Bean - public EnvironmentDecryptApplicationInitializer environmentDecryptApplicationListener() { - if (this.encryptor == null) { - this.encryptor = new FailsafeTextEncryptor(); - } - EnvironmentDecryptApplicationInitializer listener = new EnvironmentDecryptApplicationInitializer( - this.encryptor); - listener.setFailOnError(this.key.isFailOnError()); - return listener; - } - + /** + * A Spring Boot condition for key encryption. + */ public static class KeyCondition extends SpringBootCondition { @Override diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/encrypt/EnvironmentDecryptApplicationInitializer.java b/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/encrypt/EnvironmentDecryptApplicationInitializer.java index 0c868645..863b2253 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/encrypt/EnvironmentDecryptApplicationInitializer.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/encrypt/EnvironmentDecryptApplicationInitializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2012-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. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.bootstrap.encrypt; import java.util.ArrayList; @@ -52,32 +53,40 @@ import org.springframework.security.crypto.encrypt.TextEncryptor; public class EnvironmentDecryptApplicationInitializer implements ApplicationContextInitializer, Ordered { + /** + * Name of the decrypted property source. + */ public static final String DECRYPTED_PROPERTY_SOURCE_NAME = "decrypted"; + /** + * Name of the decrypted bootstrap property source. + */ public static final String DECRYPTED_BOOTSTRAP_PROPERTY_SOURCE_NAME = "decryptedBootstrap"; - private int order = Ordered.HIGHEST_PRECEDENCE + 15; + private static final Pattern COLLECTION_PROPERTY = Pattern + .compile("(\\S+)?\\[(\\d+)\\](\\.\\S+)?"); private static Log logger = LogFactory .getLog(EnvironmentDecryptApplicationInitializer.class); + private int order = Ordered.HIGHEST_PRECEDENCE + 15; + private TextEncryptor encryptor; private boolean failOnError = true; + public EnvironmentDecryptApplicationInitializer(TextEncryptor encryptor) { + this.encryptor = encryptor; + } + /** * Strategy to determine how to handle exceptions during decryption. - * * @param failOnError The flag value (default true). */ public void setFailOnError(boolean failOnError) { this.failOnError = failOnError; } - public EnvironmentDecryptApplicationInitializer(TextEncryptor encryptor) { - this.encryptor = encryptor; - } - @Override public int getOrder() { return this.order; @@ -178,9 +187,6 @@ public class EnvironmentDecryptApplicationInitializer implements return overrides; } - private static final Pattern COLLECTION_PROPERTY = Pattern - .compile("(\\S+)?\\[(\\d+)\\](\\.\\S+)?"); - private void collectEncryptedProperties(PropertySource source, Map overrides) { @@ -193,7 +199,8 @@ public class EnvironmentDecryptApplicationInitializer implements collectEncryptedProperties(nested, overrides); } - } else if (source instanceof EnumerablePropertySource) { + } + else if (source instanceof EnumerablePropertySource) { Map otherCollectionProperties = new LinkedHashMap<>(); boolean sourceHasDecryptedCollection = false; @@ -207,11 +214,13 @@ public class EnvironmentDecryptApplicationInitializer implements if (COLLECTION_PROPERTY.matcher(key).matches()) { sourceHasDecryptedCollection = true; } - } else if (COLLECTION_PROPERTY.matcher(key).matches()) { + } + else if (COLLECTION_PROPERTY.matcher(key).matches()) { // put non-encrypted properties so merging of index properties // happens correctly otherCollectionProperties.put(key, value); - } else { + } + else { overrides.remove(key); } } diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/encrypt/KeyProperties.java b/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/encrypt/KeyProperties.java index bb2c773e..e3f75a3a 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/encrypt/KeyProperties.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/encrypt/KeyProperties.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2012-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. @@ -13,11 +13,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.bootstrap.encrypt; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.core.io.Resource; +/** + * Key encryption properties. + * + * @author Dave Syer + */ @ConfigurationProperties("encrypt") public class KeyProperties { @@ -27,8 +33,8 @@ public class KeyProperties { private String key; /** - * A salt for the symmetric key, in the form of a hex-encoded byte array. As a stronger - * alternative, consider using a keystore. + * A salt for the symmetric key, in the form of a hex-encoded byte array. As a + * stronger alternative, consider using a keystore. */ private String salt = "deadbeef"; @@ -61,7 +67,7 @@ public class KeyProperties { } public String getSalt() { - return salt; + return this.salt; } public void setSalt(String salt) { @@ -76,6 +82,9 @@ public class KeyProperties { this.keyStore = keyStore; } + /** + * Key store properties. + */ public static class KeyStore { /** @@ -131,4 +140,5 @@ public class KeyProperties { } } + } diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/encrypt/RsaProperties.java b/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/encrypt/RsaProperties.java index 78d5cdef..01db5c1a 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/encrypt/RsaProperties.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/encrypt/RsaProperties.java @@ -1,6 +1,5 @@ -package org.springframework.cloud.bootstrap.encrypt; /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-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. @@ -15,6 +14,8 @@ package org.springframework.cloud.bootstrap.encrypt; * limitations under the License. */ +package org.springframework.cloud.bootstrap.encrypt; + import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.security.rsa.crypto.RsaAlgorithm; @@ -33,10 +34,10 @@ public class RsaProperties { private RsaAlgorithm algorithm = RsaAlgorithm.DEFAULT; /** - * Flag to indicate that "strong" AES encryption should be used internally. If - * true, then the GCM algorithm is applied to the AES encrypted bytes. Default is - * false (in which case "standard" CBC is used instead). Once it is set, do not - * change it (or existing ciphers will not be decryptable). + * Flag to indicate that "strong" AES encryption should be used internally. If true, + * then the GCM algorithm is applied to the AES encrypted bytes. Default is false (in + * which case "standard" CBC is used instead). Once it is set, do not change it (or + * existing ciphers will not be decryptable). */ private boolean strong = false; diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/context/config/annotation/RefreshScope.java b/spring-cloud-context/src/main/java/org/springframework/cloud/context/config/annotation/RefreshScope.java index d46daa24..6304fe0f 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/context/config/annotation/RefreshScope.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/context/config/annotation/RefreshScope.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2014 the original author or authors. + * Copyright 2012-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. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.context.config.annotation; import java.lang.annotation.Documented; @@ -30,7 +31,7 @@ import org.springframework.context.annotation.ScopedProxyMode; * Beans annotated this way can be refreshed at runtime and any components that are using * them will get a new instance on the next method call, fully initialized and injected * with all dependencies. - * + * * @author Dave Syer * */ @@ -39,8 +40,10 @@ import org.springframework.context.annotation.ScopedProxyMode; @Scope("refresh") @Documented public @interface RefreshScope { + /** * @see Scope#proxyMode() + * @return proxy mode */ ScopedProxyMode proxyMode() default ScopedProxyMode.TARGET_CLASS; diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/context/encrypt/EncryptorFactory.java b/spring-cloud-context/src/main/java/org/springframework/cloud/context/encrypt/EncryptorFactory.java index 6ac4d86d..261ac5f1 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/context/encrypt/EncryptorFactory.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/context/encrypt/EncryptorFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2012-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. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.context.encrypt; import java.io.IOException; @@ -67,7 +68,7 @@ public class EncryptorFactory { throw new KeyFormatException(); } else { - encryptor = Encryptors.text(data, salt); + encryptor = Encryptors.text(data, this.salt); } return encryptor; diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/context/encrypt/KeyFormatException.java b/spring-cloud-context/src/main/java/org/springframework/cloud/context/encrypt/KeyFormatException.java index 9a609972..dc46a55f 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/context/encrypt/KeyFormatException.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/context/encrypt/KeyFormatException.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2014 the original author or authors. + * Copyright 2012-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. @@ -13,15 +13,23 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.context.encrypt; +/** + * Exception related to the format of key. + * + * @author Dave Syer + */ @SuppressWarnings("serial") public class KeyFormatException extends RuntimeException { + public KeyFormatException() { super(); } - + public KeyFormatException(Throwable t) { super(t); } -} \ No newline at end of file + +} diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/context/environment/EnvironmentChangeEvent.java b/spring-cloud-context/src/main/java/org/springframework/cloud/context/environment/EnvironmentChangeEvent.java index e6df1e32..81f9e4e4 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/context/environment/EnvironmentChangeEvent.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/context/environment/EnvironmentChangeEvent.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2014 the original author or authors. + * Copyright 2012-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. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.context.environment; import java.util.Set; @@ -22,7 +23,7 @@ import org.springframework.core.env.Environment; /** * Event published to signal a change in the {@link Environment}. - * + * * @author Dave Syer * */ @@ -45,7 +46,7 @@ public class EnvironmentChangeEvent extends ApplicationEvent { * @return The keys. */ public Set getKeys() { - return keys; + return this.keys; } } diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/context/environment/EnvironmentManager.java b/spring-cloud-context/src/main/java/org/springframework/cloud/context/environment/EnvironmentManager.java index 7edfac7f..3a847ee8 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/context/environment/EnvironmentManager.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/context/environment/EnvironmentManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2014 the original author or authors. + * Copyright 2012-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. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.context.environment; import java.util.Collections; @@ -33,18 +34,20 @@ import org.springframework.stereotype.Component; * Entry point for making local (but volatile) changes to the {@link Environment} of a * running application. Allows properties to be added and values changed, simply by adding * them to a high-priority property source in the existing Environment. - * + * * @author Dave Syer - * + * */ @Component @ManagedResource public class EnvironmentManager implements ApplicationEventPublisherAware { private static final String MANAGER_PROPERTY_SOURCE = "manager"; + private Map map = new LinkedHashMap(); private ConfigurableEnvironment environment; + private ApplicationEventPublisher publisher; public EnvironmentManager(ConfigurableEnvironment environment) { @@ -65,10 +68,10 @@ public class EnvironmentManager implements ApplicationEventPublisherAware { @ManagedOperation public Map reset() { - Map result = new LinkedHashMap(map); - if (!map.isEmpty()) { - map.clear(); - publish(new EnvironmentChangeEvent(publisher, result.keySet())); + Map result = new LinkedHashMap(this.map); + if (!this.map.isEmpty()) { + this.map.clear(); + publish(new EnvironmentChangeEvent(this.publisher, result.keySet())); } return result; } @@ -76,31 +79,33 @@ public class EnvironmentManager implements ApplicationEventPublisherAware { @ManagedOperation public void setProperty(String name, String value) { - if (!environment.getPropertySources().contains(MANAGER_PROPERTY_SOURCE)) { - synchronized (map) { - if (!environment.getPropertySources().contains(MANAGER_PROPERTY_SOURCE)) { + if (!this.environment.getPropertySources().contains(MANAGER_PROPERTY_SOURCE)) { + synchronized (this.map) { + if (!this.environment.getPropertySources() + .contains(MANAGER_PROPERTY_SOURCE)) { MapPropertySource source = new MapPropertySource( - MANAGER_PROPERTY_SOURCE, map); - environment.getPropertySources().addFirst(source); + MANAGER_PROPERTY_SOURCE, this.map); + this.environment.getPropertySources().addFirst(source); } } } - if (!value.equals(environment.getProperty(name))) { - map.put(name, value); - publish(new EnvironmentChangeEvent(publisher, Collections.singleton(name))); + if (!value.equals(this.environment.getProperty(name))) { + this.map.put(name, value); + publish(new EnvironmentChangeEvent(this.publisher, + Collections.singleton(name))); } } @ManagedOperation public Object getProperty(String name) { - return environment.getProperty(name); + return this.environment.getProperty(name); } private void publish(EnvironmentChangeEvent environmentChangeEvent) { - if (publisher != null) { - publisher.publishEvent(environmentChangeEvent); + if (this.publisher != null) { + this.publisher.publishEvent(environmentChangeEvent); } } diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/context/environment/WritableEnvironmentEndpoint.java b/spring-cloud-context/src/main/java/org/springframework/cloud/context/environment/WritableEnvironmentEndpoint.java index 86c98849..56273870 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/context/environment/WritableEnvironmentEndpoint.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/context/environment/WritableEnvironmentEndpoint.java @@ -1,3 +1,19 @@ +/* + * Copyright 2012-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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.context.environment; import org.springframework.boot.actuate.env.EnvironmentEndpoint; diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/context/environment/WritableEnvironmentEndpointWebExtension.java b/spring-cloud-context/src/main/java/org/springframework/cloud/context/environment/WritableEnvironmentEndpointWebExtension.java index 7c8a02e4..3f5aa100 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/context/environment/WritableEnvironmentEndpointWebExtension.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/context/environment/WritableEnvironmentEndpointWebExtension.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2012-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. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.context.environment; import java.util.Collections; @@ -26,9 +27,9 @@ import org.springframework.boot.actuate.env.EnvironmentEndpointWebExtension; /** * MVC endpoint for the {@link EnvironmentManager}, providing a POST to /env as a simple * way to change the Environment. - * + * * @author Dave Syer - * + * */ @EndpointWebExtension(endpoint = WritableEnvironmentEndpoint.class) public class WritableEnvironmentEndpointWebExtension @@ -44,13 +45,13 @@ public class WritableEnvironmentEndpointWebExtension @WriteOperation public Object write(String name, String value) { - environment.setProperty(name, value); + this.environment.setProperty(name, value); return Collections.singletonMap(name, value); } @DeleteOperation public Map reset() { - return environment.reset(); + return this.environment.reset(); } public void setEnvironmentManager(EnvironmentManager environment) { diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/context/named/ClientFactoryObjectProvider.java b/spring-cloud-context/src/main/java/org/springframework/cloud/context/named/ClientFactoryObjectProvider.java index 1de53ae0..b3ffec4c 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/context/named/ClientFactoryObjectProvider.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/context/named/ClientFactoryObjectProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-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. @@ -16,29 +16,34 @@ package org.springframework.cloud.context.named; -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.ObjectProvider; -import org.springframework.lang.Nullable; - import java.util.Iterator; import java.util.Spliterator; import java.util.function.Consumer; import java.util.function.Supplier; import java.util.stream.Stream; +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.lang.Nullable; + /** - * Special ObjectProvider that allows the actual ObjectProvider to be resolved - * later because of the creation of the named child context. - * @param + * Special ObjectProvider that allows the actual ObjectProvider to be resolved later + * because of the creation of the named child context. + * + * @param - type of the provided object */ class ClientFactoryObjectProvider implements ObjectProvider { - + private final NamedContextFactory clientFactory; + private final String name; + private final Class type; + private ObjectProvider provider; - public ClientFactoryObjectProvider(NamedContextFactory clientFactory, String name, Class type) { + ClientFactoryObjectProvider(NamedContextFactory clientFactory, String name, + Class type) { this.clientFactory = clientFactory; this.name = name; this.type = type; @@ -109,8 +114,9 @@ class ClientFactoryObjectProvider implements ObjectProvider { @SuppressWarnings("unchecked") private ObjectProvider delegate() { if (this.provider == null) { - provider = this.clientFactory.getProvider(name, type); + this.provider = this.clientFactory.getProvider(this.name, this.type); } - return provider; + return this.provider; } + } diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/context/named/NamedContextFactory.java b/spring-cloud-context/src/main/java/org/springframework/cloud/context/named/NamedContextFactory.java index 6287bc04..57538878 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/context/named/NamedContextFactory.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/context/named/NamedContextFactory.java @@ -1,3 +1,19 @@ +/* + * Copyright 2012-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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.context.named; import java.util.Collection; @@ -25,18 +41,17 @@ import org.springframework.core.env.MapPropertySource; * * Ported from spring-cloud-netflix FeignClientFactory and SpringClientFactory * + * @param specification * @author Spencer Gibb * @author Dave Syer */ -//TODO: add javadoc +// TODO: add javadoc public abstract class NamedContextFactory implements DisposableBean, ApplicationContextAware { - public interface Specification { - String getName(); + private final String propertySourceName; - Class[] getConfiguration(); - } + private final String propertyName; private Map contexts = new ConcurrentHashMap<>(); @@ -45,8 +60,6 @@ public abstract class NamedContextFactory defaultConfigType; - private final String propertySourceName; - private final String propertyName; public NamedContextFactory(Class defaultConfigType, String propertySourceName, String propertyName) { @@ -67,7 +80,7 @@ public abstract class NamedContextFactory getContextNames() { - return new HashSet<>(contexts.keySet()); + return new HashSet<>(this.contexts.keySet()); } @Override @@ -111,7 +124,7 @@ public abstract class NamedContextFactory singletonMap(this.propertyName, name))); + Collections.singletonMap(this.propertyName, name))); if (this.parent != null) { // Uses Environment from parent as well as beans context.setParent(this.parent); @@ -124,7 +137,7 @@ public abstract class NamedContextFactory T getInstance(String name, Class type) { AnnotationConfigApplicationContext context = getContext(name); if (BeanFactoryUtils.beanNamesForTypeIncludingAncestors(context, @@ -172,4 +185,15 @@ public abstract class NamedContextFactory[] getConfiguration(); + + } + } diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/context/properties/ConfigurationPropertiesBeans.java b/spring-cloud-context/src/main/java/org/springframework/cloud/context/properties/ConfigurationPropertiesBeans.java index d9b9cedd..f0f86ebc 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/context/properties/ConfigurationPropertiesBeans.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/context/properties/ConfigurationPropertiesBeans.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2014 the original author or authors. + * Copyright 2012-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. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.context.properties; import java.util.HashMap; @@ -38,8 +39,8 @@ import org.springframework.stereotype.Component; * */ @Component -public class ConfigurationPropertiesBeans implements BeanPostProcessor, -ApplicationContextAware { +public class ConfigurationPropertiesBeans + implements BeanPostProcessor, ApplicationContextAware { private ConfigurationBeanFactoryMetadata metaData; @@ -56,12 +57,13 @@ ApplicationContextAware { @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { - if (applicationContext.getAutowireCapableBeanFactory() instanceof ConfigurableListableBeanFactory) { + if (applicationContext + .getAutowireCapableBeanFactory() instanceof ConfigurableListableBeanFactory) { this.beanFactory = (ConfigurableListableBeanFactory) applicationContext .getAutowireCapableBeanFactory(); } - if (applicationContext.getParent() != null - && applicationContext.getParent().getAutowireCapableBeanFactory() instanceof ConfigurableListableBeanFactory) { + if (applicationContext.getParent() != null && applicationContext.getParent() + .getAutowireCapableBeanFactory() instanceof ConfigurableListableBeanFactory) { ConfigurableListableBeanFactory listable = (ConfigurableListableBeanFactory) applicationContext .getParent().getAutowireCapableBeanFactory(); String[] names = listable @@ -86,8 +88,8 @@ ApplicationContextAware { if (isRefreshScoped(beanName)) { return bean; } - ConfigurationProperties annotation = AnnotationUtils.findAnnotation( - bean.getClass(), ConfigurationProperties.class); + ConfigurationProperties annotation = AnnotationUtils + .findAnnotation(bean.getClass(), ConfigurationProperties.class); if (annotation != null) { this.beans.put(beanName, bean); } @@ -105,7 +107,8 @@ ApplicationContextAware { if (this.refreshScope == null && !this.refreshScopeInitialized) { this.refreshScopeInitialized = true; for (String scope : this.beanFactory.getRegisteredScopeNames()) { - if (this.beanFactory.getRegisteredScope(scope) instanceof org.springframework.cloud.context.scope.refresh.RefreshScope) { + if (this.beanFactory.getRegisteredScope( + scope) instanceof org.springframework.cloud.context.scope.refresh.RefreshScope) { this.refreshScope = scope; break; } @@ -114,9 +117,8 @@ ApplicationContextAware { if (beanName == null || this.refreshScope == null) { return false; } - return this.beanFactory.containsBeanDefinition(beanName) - && this.refreshScope.equals(this.beanFactory.getBeanDefinition(beanName) - .getScope()); + return this.beanFactory.containsBeanDefinition(beanName) && this.refreshScope + .equals(this.beanFactory.getBeanDefinition(beanName).getScope()); } @Override diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/context/properties/ConfigurationPropertiesRebinder.java b/spring-cloud-context/src/main/java/org/springframework/cloud/context/properties/ConfigurationPropertiesRebinder.java index c393b26d..b50d6447 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/context/properties/ConfigurationPropertiesRebinder.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/context/properties/ConfigurationPropertiesRebinder.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2014 the original author or authors. + * Copyright 2012-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. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.context.properties; import java.util.HashSet; @@ -25,6 +26,7 @@ import org.springframework.beans.BeansException; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.cloud.context.environment.EnvironmentChangeEvent; +import org.springframework.cloud.util.ProxyUtils; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.ApplicationListener; @@ -33,17 +35,15 @@ import org.springframework.jmx.export.annotation.ManagedAttribute; import org.springframework.jmx.export.annotation.ManagedOperation; import org.springframework.jmx.export.annotation.ManagedResource; import org.springframework.stereotype.Component; -import org.springframework.cloud.util.ProxyUtils; /** * Listens for {@link EnvironmentChangeEvent} and rebinds beans that were bound to the * {@link Environment} using {@link ConfigurationProperties * @ConfigurationProperties}. When these beans are re-bound and - * re-initialized, the changes are available immediately to any component that is using the - * @ConfigurationProperties bean. + * re-initialized, the changes are available immediately to any component that is using + * the @ConfigurationProperties bean. * * @see RefreshScope for a deeper and optionally more focused refresh of bean components. - * * @author Dave Syer * */ @@ -70,7 +70,6 @@ public class ConfigurationPropertiesRebinder /** * A map of bean name to errors when instantiating the bean. - * * @return The errors accumulated since the latest destroy. */ public Map getErrors() { @@ -97,9 +96,10 @@ public class ConfigurationPropertiesRebinder bean = ProxyUtils.getTargetObject(bean); } if (bean != null) { - this.applicationContext.getAutowireCapableBeanFactory().destroyBean(bean); - this.applicationContext.getAutowireCapableBeanFactory() - .initializeBean(bean, name); + this.applicationContext.getAutowireCapableBeanFactory() + .destroyBean(bean); + this.applicationContext.getAutowireCapableBeanFactory() + .initializeBean(bean, name); return true; } } @@ -117,7 +117,7 @@ public class ConfigurationPropertiesRebinder @ManagedAttribute public Set getBeanNames() { - return new HashSet(this.beans.getBeanNames()); + return new HashSet<>(this.beans.getBeanNames()); } @Override diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/context/refresh/ContextRefresher.java b/spring-cloud-context/src/main/java/org/springframework/cloud/context/refresh/ContextRefresher.java index 8bd7bd40..2e98c9d0 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/context/refresh/ContextRefresher.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/context/refresh/ContextRefresher.java @@ -1,3 +1,19 @@ +/* + * Copyright 2012-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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.context.refresh; import java.util.ArrayList; @@ -45,10 +61,11 @@ public class ContextRefresher { StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, StandardServletEnvironment.JNDI_PROPERTY_SOURCE_NAME, StandardServletEnvironment.SERVLET_CONFIG_PROPERTY_SOURCE_NAME, - StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME, + StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME, "configurationProperties")); private ConfigurableApplicationContext context; + private RefreshScope scope; public ContextRefresher(ConfigurableApplicationContext context, RefreshScope scope) { @@ -76,7 +93,7 @@ public class ContextRefresher { addConfigFilesToEnvironment(); Set keys = changes(before, extract(this.context.getEnvironment().getPropertySources())).keySet(); - this.context.publishEvent(new EnvironmentChangeEvent(context, keys)); + this.context.publishEvent(new EnvironmentChangeEvent(this.context, keys)); return keys; } diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/context/restart/RestartEndpoint.java b/spring-cloud-context/src/main/java/org/springframework/cloud/context/restart/RestartEndpoint.java index 7aca1824..fa4f2d13 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/context/restart/RestartEndpoint.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/context/restart/RestartEndpoint.java @@ -119,33 +119,6 @@ public class RestartEndpoint implements ApplicationListener * * @author Dave Syer - * * @since 3.1 * */ public class GenericScope implements Scope, BeanFactoryPostProcessor, BeanDefinitionRegistryPostProcessor, DisposableBean { - private static final Log logger = LogFactory.getLog(GenericScope.class); - + /** + * Prefix for the scoped target. + */ public static final String SCOPED_TARGET_PREFIX = "scopedTarget."; + private static final Log logger = LogFactory.getLog(GenericScope.class); + private BeanLifecycleWrapperCache cache = new BeanLifecycleWrapperCache( new StandardScopeCache()); @@ -90,28 +95,27 @@ public class GenericScope implements Scope, BeanFactoryPostProcessor, private ConcurrentMap locks = new ConcurrentHashMap<>(); + static RuntimeException wrapIfNecessary(Throwable throwable) { + if (throwable instanceof RuntimeException) { + return (RuntimeException) throwable; + } + if (throwable instanceof Error) { + throw (Error) throwable; + } + return new IllegalStateException(throwable); + } + /** * Manual override for the serialization ID that will be used to identify the bean * factory. The default is a unique key based on the bean names in the bean factory. - * * @param id The ID to set. */ public void setId(String id) { this.id = id; } - /** - * The name of this scope. Default "generic". - * - * @param name The name value to set. - */ - public void setName(String name) { - this.name = name; - } - /** * The cache implementation to use for bean instances in this scope. - * * @param cache The cache to use. */ public void setScopeCache(ScopeCache cache) { @@ -120,7 +124,6 @@ public class GenericScope implements Scope, BeanFactoryPostProcessor, /** * A map of bean name to errors when instantiating the bean. - * * @return The errors accumulated since the latest destroy. */ public Map getErrors() { @@ -133,7 +136,7 @@ public class GenericScope implements Scope, BeanFactoryPostProcessor, Collection wrappers = this.cache.clear(); for (BeanLifecycleWrapper wrapper : wrappers) { try { - Lock lock = locks.get(wrapper.getName()).writeLock(); + Lock lock = this.locks.get(wrapper.getName()).writeLock(); lock.lock(); try { wrapper.destroy(); @@ -154,14 +157,13 @@ public class GenericScope implements Scope, BeanFactoryPostProcessor, /** * Destroys the named bean (i.e. flushes it from the cache by default). - * * @param name The bean name to flush. * @return True if the bean was already cached; false otherwise. */ protected boolean destroy(String name) { BeanLifecycleWrapper wrapper = this.cache.remove(name); if (wrapper != null) { - Lock lock = locks.get(wrapper.getName()).writeLock(); + Lock lock = this.locks.get(wrapper.getName()).writeLock(); lock.lock(); try { wrapper.destroy(); @@ -179,7 +181,7 @@ public class GenericScope implements Scope, BeanFactoryPostProcessor, public Object get(String name, ObjectFactory objectFactory) { BeanLifecycleWrapper value = this.cache.put(name, new BeanLifecycleWrapper(name, objectFactory)); - locks.putIfAbsent(name, new ReentrantReadWriteLock()); + this.locks.putIfAbsent(name, new ReentrantReadWriteLock()); try { return value.getBean(); } @@ -274,7 +276,6 @@ public class GenericScope implements Scope, BeanFactoryPostProcessor, * IDs of the bean factories match. This method sets up the serialization ID to be * either the ID provided to the scope instance, or if that is null, a hash of all the * bean names. - * * @param beanFactory The bean factory to configure. */ private void setSerializationId(ConfigurableListableBeanFactory beanFactory) { @@ -303,29 +304,27 @@ public class GenericScope implements Scope, BeanFactoryPostProcessor, } - static RuntimeException wrapIfNecessary(Throwable throwable) { - if (throwable instanceof RuntimeException) { - return (RuntimeException) throwable; - } - if (throwable instanceof Error) { - throw (Error) throwable; - } - return new IllegalStateException(throwable); - } - protected String getName() { return this.name; } + /** + * The name of this scope. Default "generic". + * @param name The name value to set. + */ + public void setName(String name) { + this.name = name; + } + protected ReadWriteLock getLock(String beanName) { - return locks.get(beanName); + return this.locks.get(beanName); } private static class BeanLifecycleWrapperCache { private final ScopeCache cache; - public BeanLifecycleWrapperCache(ScopeCache cache) { + BeanLifecycleWrapperCache(ScopeCache cache) { this.cache = cache; } @@ -362,15 +361,15 @@ public class GenericScope implements Scope, BeanFactoryPostProcessor, */ private static class BeanLifecycleWrapper { - private Object bean; - - private Runnable callback; - private final String name; private final ObjectFactory objectFactory; - public BeanLifecycleWrapper(String name, ObjectFactory objectFactory) { + private Object bean; + + private Runnable callback; + + BeanLifecycleWrapper(String name, ObjectFactory objectFactory) { this.name = name; this.objectFactory = objectFactory; } @@ -441,11 +440,17 @@ public class GenericScope implements Scope, BeanFactoryPostProcessor, } + /** + * A factory bean with a locked scope. + * + * @param - a generic scope extension + */ @SuppressWarnings("serial") public static class LockedScopedProxyFactoryBean extends ScopedProxyFactoryBean implements MethodInterceptor { private final S scope; + private String targetBeanName; public LockedScopedProxyFactoryBean(S scope) { @@ -477,7 +482,7 @@ public class GenericScope implements Scope, BeanFactoryPostProcessor, return invocation.proceed(); } Object proxy = getObject(); - ReadWriteLock readWriteLock = scope.getLock(this.targetBeanName); + ReadWriteLock readWriteLock = this.scope.getLock(this.targetBeanName); if (readWriteLock == null) { if (logger.isDebugEnabled()) { logger.debug("For bean with name [" + this.targetBeanName @@ -497,7 +502,8 @@ public class GenericScope implements Scope, BeanFactoryPostProcessor, } return invocation.proceed(); } - // see gh-349. Throw the original exception rather than the UndeclaredThrowableException + // see gh-349. Throw the original exception rather than the + // UndeclaredThrowableException catch (UndeclaredThrowableException e) { throw e.getUndeclaredThrowable(); } @@ -511,6 +517,7 @@ public class GenericScope implements Scope, BeanFactoryPostProcessor, && method.getName().equals("getTargetObject") && method.getParameterTypes().length == 0; } + } } diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/context/scope/ScopeCache.java b/spring-cloud-context/src/main/java/org/springframework/cloud/context/scope/ScopeCache.java index 42ac62b9..e5f8e90e 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/context/scope/ScopeCache.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/context/scope/ScopeCache.java @@ -19,19 +19,19 @@ package org.springframework.cloud.context.scope; import java.util.Collection; /** - * A special-purpose cache interface specifically for the {@link GenericScope} to use to manage cached bean instances. - * Implementations generally fall into two categories: those that store values "globally" (i.e. one instance per key), - * and those that store potentially multiple instances per key based on context (e.g. via a thread local). All + * A special-purpose cache interface specifically for the {@link GenericScope} to use to + * manage cached bean instances. Implementations generally fall into two categories: those + * that store values "globally" (i.e. one instance per key), and those that store + * potentially multiple instances per key based on context (e.g. via a thread local). All * implementations should be thread safe. - * + * * @author Dave Syer - * + * */ public interface ScopeCache { /** * Removes the object with this name from the cache. - * * @param name The object name. * @return The object removed, or null if there was none. */ @@ -39,23 +39,20 @@ public interface ScopeCache { /** * Clears the cache and returns all objects in an unmodifiable collection. - * * @return All objects stored in the cache. */ Collection clear(); /** * Gets the named object from the cache. - * * @param name The name of the object. * @return The object with that name, or null if there is none. */ Object get(String name); /** - * Put a value in the cache if the key is not already used. If one is already present with the name provided, it is - * not replaced, but is returned to the caller. - * + * Put a value in the cache if the key is not already used. If one is already present + * with the name provided, it is not replaced, but is returned to the caller. * @param name The key. * @param value The new candidate value. * @return The value that is in the cache at the end of the operation. diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/context/scope/StandardScopeCache.java b/spring-cloud-context/src/main/java/org/springframework/cloud/context/scope/StandardScopeCache.java index e3591a0d..a2d05493 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/context/scope/StandardScopeCache.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/context/scope/StandardScopeCache.java @@ -23,31 +23,31 @@ import java.util.concurrent.ConcurrentMap; /** * A simple cache implementation backed by a concurrent map. - * + * * @author Dave Syer * */ public class StandardScopeCache implements ScopeCache { - + private final ConcurrentMap cache = new ConcurrentHashMap(); public Object remove(String name) { - return cache.remove(name); + return this.cache.remove(name); } public Collection clear() { - Collection values = new ArrayList(cache.values()); - cache.clear(); + Collection values = new ArrayList(this.cache.values()); + this.cache.clear(); return values; } public Object get(String name) { - return cache.get(name); + return this.cache.get(name); } public Object put(String name, Object value) { - Object result = cache.putIfAbsent(name, value); - if (result!=null) { + Object result = this.cache.putIfAbsent(name, value); + if (result != null) { return result; } return value; diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/context/scope/refresh/RefreshScope.java b/spring-cloud-context/src/main/java/org/springframework/cloud/context/scope/refresh/RefreshScope.java index 994e4a4c..d7a5703a 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/context/scope/refresh/RefreshScope.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/context/scope/refresh/RefreshScope.java @@ -1,14 +1,17 @@ /* - * Copyright 2002-2009 the original author or authors. + * Copyright 2012-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. You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on - * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.springframework.cloud.context.scope.refresh; @@ -64,17 +67,19 @@ import org.springframework.jmx.export.annotation.ManagedResource; *

* * @author Dave Syer - * * @since 3.1 * */ @ManagedResource -public class RefreshScope extends GenericScope - implements ApplicationContextAware, ApplicationListener, Ordered { +public class RefreshScope extends GenericScope implements ApplicationContextAware, + ApplicationListener, Ordered { private ApplicationContext context; + private BeanDefinitionRegistry registry; + private boolean eager = true; + private int order = Ordered.LOWEST_PRECEDENCE - 100; /** @@ -96,7 +101,6 @@ public class RefreshScope extends GenericScope /** * Flag to determine whether all beans in refresh scope should be instantiated eagerly * on startup. Default true. - * * @param eager The flag to set. */ public void setEager(boolean eager) { @@ -135,7 +139,8 @@ public class RefreshScope extends GenericScope } } - @ManagedOperation(description = "Dispose of the current instance of bean name provided and force a refresh on next method execution.") + @ManagedOperation(description = "Dispose of the current instance of bean name " + + "provided and force a refresh on next method execution.") public boolean refresh(String name) { if (!name.startsWith(SCOPED_TARGET_PREFIX)) { // User wants to refresh the bean with this name but that isn't the one in the @@ -150,7 +155,8 @@ public class RefreshScope extends GenericScope return false; } - @ManagedOperation(description = "Dispose of the current instance of all beans in this scope and force a refresh on next method execution.") + @ManagedOperation(description = "Dispose of the current instance of all beans " + + "in this scope and force a refresh on next method execution.") public void refreshAll() { super.destroy(); this.context.publishEvent(new RefreshScopeRefreshedEvent()); diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/context/scope/refresh/RefreshScopeRefreshedEvent.java b/spring-cloud-context/src/main/java/org/springframework/cloud/context/scope/refresh/RefreshScopeRefreshedEvent.java index 0216108d..289bb727 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/context/scope/refresh/RefreshScopeRefreshedEvent.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/context/scope/refresh/RefreshScopeRefreshedEvent.java @@ -1,3 +1,19 @@ +/* + * Copyright 2012-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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.context.scope.refresh; import org.springframework.context.ApplicationEvent; @@ -7,7 +23,12 @@ import org.springframework.context.ApplicationEvent; */ @SuppressWarnings("serial") public class RefreshScopeRefreshedEvent extends ApplicationEvent { + + /** + * Default name for the refresh scope refreshed event. + */ public static final String DEFAULT_NAME = "__refreshAll__"; + private String name; public RefreshScopeRefreshedEvent() { @@ -20,6 +41,7 @@ public class RefreshScopeRefreshedEvent extends ApplicationEvent { } public String getName() { - return name; + return this.name; } + } diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/context/scope/thread/ThreadLocalScopeCache.java b/spring-cloud-context/src/main/java/org/springframework/cloud/context/scope/thread/ThreadLocalScopeCache.java index c140d63d..8cfec61e 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/context/scope/thread/ThreadLocalScopeCache.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/context/scope/thread/ThreadLocalScopeCache.java @@ -25,7 +25,7 @@ import org.springframework.cloud.context.scope.ScopeCache; /** * @author Dave Syer - * + * */ public class ThreadLocalScopeCache implements ScopeCache { @@ -36,23 +36,23 @@ public class ThreadLocalScopeCache implements ScopeCache { }; public Object remove(String name) { - return data.get().remove(name); + return this.data.get().remove(name); } public Collection clear() { - ConcurrentMap map = data.get(); + ConcurrentMap map = this.data.get(); Collection values = new ArrayList(map.values()); map.clear(); return values; } public Object get(String name) { - return data.get().get(name); + return this.data.get().get(name); } public Object put(String name, Object value) { - Object result = data.get().putIfAbsent(name, value); - if (result!=null) { + Object result = this.data.get().putIfAbsent(name, value); + if (result != null) { return result; } return value; diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/context/scope/thread/ThreadScope.java b/spring-cloud-context/src/main/java/org/springframework/cloud/context/scope/thread/ThreadScope.java index 1db0548d..8dc20ebd 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/context/scope/thread/ThreadScope.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/context/scope/thread/ThreadScope.java @@ -1,14 +1,17 @@ /* - * Copyright 2002-2009 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 - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on - * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. + * Copyright 2012-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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.context.scope.thread; @@ -16,11 +19,9 @@ package org.springframework.cloud.context.scope.thread; import org.springframework.cloud.context.scope.GenericScope; /** - * * @author Dave Syer - * * @since 3.1 - * + * */ public class ThreadScope extends GenericScope { diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/endpoint/RefreshEndpoint.java b/spring-cloud-context/src/main/java/org/springframework/cloud/endpoint/RefreshEndpoint.java index 6fe8c993..c05ea7b0 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/endpoint/RefreshEndpoint.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/endpoint/RefreshEndpoint.java @@ -38,7 +38,7 @@ public class RefreshEndpoint { @WriteOperation public Collection refresh() { - Set keys = contextRefresher.refresh(); + Set keys = this.contextRefresher.refresh(); return keys; } diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/endpoint/event/RefreshEvent.java b/spring-cloud-context/src/main/java/org/springframework/cloud/endpoint/event/RefreshEvent.java index fafba6df..2f2dcf7a 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/endpoint/event/RefreshEvent.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/endpoint/event/RefreshEvent.java @@ -1,3 +1,19 @@ +/* + * Copyright 2012-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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.endpoint.event; import org.springframework.cloud.endpoint.RefreshEndpoint; @@ -5,12 +21,14 @@ import org.springframework.context.ApplicationEvent; /** * Event that triggers a call to {@link RefreshEndpoint#refresh()}. + * * @author Spencer Gibb */ @SuppressWarnings("serial") public class RefreshEvent extends ApplicationEvent { private Object event; + private String eventDesc; public RefreshEvent(Object source, Object event, String eventDesc) { @@ -26,4 +44,5 @@ public class RefreshEvent extends ApplicationEvent { public String getEventDesc() { return this.eventDesc; } + } diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/endpoint/event/RefreshEventListener.java b/spring-cloud-context/src/main/java/org/springframework/cloud/endpoint/event/RefreshEventListener.java index 4452ce29..6dda84d9 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/endpoint/event/RefreshEventListener.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/endpoint/event/RefreshEventListener.java @@ -1,3 +1,19 @@ +/* + * Copyright 2012-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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.endpoint.event; import java.util.Set; @@ -13,12 +29,17 @@ import org.springframework.context.event.SmartApplicationListener; /** * Calls {@link RefreshEventListener#refresh} when a {@link RefreshEvent} is received. - * Only responds to {@link RefreshEvent} after receiving an {@link ApplicationReadyEvent}, as the RefreshEvents might come too early in the application lifecycle. + * Only responds to {@link RefreshEvent} after receiving an {@link ApplicationReadyEvent}, + * as the RefreshEvents might come too early in the application lifecycle. + * * @author Spencer Gibb */ public class RefreshEventListener implements SmartApplicationListener { + private static Log log = LogFactory.getLog(RefreshEventListener.class); + private ContextRefresher refresh; + private AtomicBoolean ready = new AtomicBoolean(false); public RefreshEventListener(ContextRefresher refresh) { @@ -35,7 +56,8 @@ public class RefreshEventListener implements SmartApplicationListener { public void onApplicationEvent(ApplicationEvent event) { if (event instanceof ApplicationReadyEvent) { handle((ApplicationReadyEvent) event); - } else if (event instanceof RefreshEvent) { + } + else if (event instanceof RefreshEvent) { handle((RefreshEvent) event); } } @@ -51,4 +73,5 @@ public class RefreshEventListener implements SmartApplicationListener { log.info("Refresh keys changed: " + keys); } } + } diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/env/EnvironmentUtils.java b/spring-cloud-context/src/main/java/org/springframework/cloud/env/EnvironmentUtils.java index 791e7cf6..6837aceb 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/env/EnvironmentUtils.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/env/EnvironmentUtils.java @@ -1,3 +1,19 @@ +/* + * Copyright 2012-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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.env; import java.util.Collections; @@ -10,11 +26,17 @@ import org.springframework.core.env.Environment; /** * @author Spencer Gibb */ -public class EnvironmentUtils { +public final class EnvironmentUtils { + + private EnvironmentUtils() { + throw new IllegalStateException("Can't instantiate a utility class"); + } + public static Map getSubProperties(Environment environment, String keyPrefix) { return Binder.get(environment) .bind(keyPrefix, Bindable.mapOf(String.class, String.class)) .orElseGet(Collections::emptyMap); } + } diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/health/RefreshScopeHealthIndicator.java b/spring-cloud-context/src/main/java/org/springframework/cloud/health/RefreshScopeHealthIndicator.java index 9b1f0b8b..9ef8b7e5 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/health/RefreshScopeHealthIndicator.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/health/RefreshScopeHealthIndicator.java @@ -35,10 +35,11 @@ import org.springframework.cloud.context.scope.refresh.RefreshScope; public class RefreshScopeHealthIndicator extends AbstractHealthIndicator { private ObjectProvider scope; + private ConfigurationPropertiesRebinder rebinder; public RefreshScopeHealthIndicator(ObjectProvider scope, - ConfigurationPropertiesRebinder rebinder) { + ConfigurationPropertiesRebinder rebinder) { this.scope = scope; this.rebinder = rebinder; } diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/logging/LoggingRebinder.java b/spring-cloud-context/src/main/java/org/springframework/cloud/logging/LoggingRebinder.java index 2ab1cdb3..856bc220 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/logging/LoggingRebinder.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/logging/LoggingRebinder.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2014 the original author or authors. + * Copyright 2012-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. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.cloud.logging; import java.util.Collections; @@ -64,7 +65,8 @@ public class LoggingRebinder protected void setLogLevels(LoggingSystem system, Environment environment) { Map levels = Binder.get(environment) - .bind("logging.level", STRING_STRING_MAP).orElseGet(Collections::emptyMap); + .bind("logging.level", STRING_STRING_MAP) + .orElseGet(Collections::emptyMap); for (Entry entry : levels.entrySet()) { setLogLevel(system, environment, entry.getKey(), entry.getValue().toString()); } diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/util/ProxyUtils.java b/spring-cloud-context/src/main/java/org/springframework/cloud/util/ProxyUtils.java index 57549c43..cf61bbb2 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/util/ProxyUtils.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/util/ProxyUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-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. @@ -22,7 +22,11 @@ import org.springframework.aop.support.AopUtils; /** * @author Ryan Baxter */ -public class ProxyUtils { +public final class ProxyUtils { + + private ProxyUtils() { + throw new IllegalStateException("Can't instantiate a utility class"); + } @SuppressWarnings("unchecked") public static T getTargetObject(Object candidate) { @@ -36,4 +40,5 @@ public class ProxyUtils { } return (T) candidate; } + } diff --git a/spring-cloud-context/src/main/resources/META-INF/additional-spring-configuration-metadata.json b/spring-cloud-context/src/main/resources/META-INF/additional-spring-configuration-metadata.json index b8b03f05..484e74fa 100644 --- a/spring-cloud-context/src/main/resources/META-INF/additional-spring-configuration-metadata.json +++ b/spring-cloud-context/src/main/resources/META-INF/additional-spring-configuration-metadata.json @@ -1,45 +1,47 @@ -{"properties": [ - { - "name": "management.health.refresh.enabled", - "type": "java.lang.Boolean", - "description": "Enable the health endpoint for the refresh scope.", - "defaultValue": true - }, - { - "name": "management.endpoint.env.post.enabled", - "type": "java.lang.Boolean", - "description": "Enable changing the Environment through a POST to /env.", - "defaultValue": true - }, - { - "name": "management.endpoint.refresh.enabled", - "type": "java.lang.Boolean", - "description": "Enable the /refresh endpoint to refresh configuration and re-initialize refresh scoped beans.", - "defaultValue": true - }, - { - "name": "management.endpoint.restart.enabled", - "type": "java.lang.Boolean", - "description": "Enable the /restart endpoint to restart the application context.", - "defaultValue": true - }, - { - "name": "management.endpoint.pause.enabled", - "type": "java.lang.Boolean", - "description": "Enable the /pause endpoint (to send Lifecycle.stop()).", - "defaultValue": true - }, - { - "name": "management.endpoint.resume.enabled", - "type": "java.lang.Boolean", - "description": "Enable the /resume endpoint (to send Lifecycle.start()).", - "defaultValue": true - }, - { - "name": "spring.cloud.refresh.extra-refreshable", - "type": "java.util.Set", - "description": "Additional class names for beans to post process into refresh scope.", - "defaultValue": true - } -]} +{ + "properties": [ + { + "name": "management.health.refresh.enabled", + "type": "java.lang.Boolean", + "description": "Enable the health endpoint for the refresh scope.", + "defaultValue": true + }, + { + "name": "management.endpoint.env.post.enabled", + "type": "java.lang.Boolean", + "description": "Enable changing the Environment through a POST to /env.", + "defaultValue": true + }, + { + "name": "management.endpoint.refresh.enabled", + "type": "java.lang.Boolean", + "description": "Enable the /refresh endpoint to refresh configuration and re-initialize refresh scoped beans.", + "defaultValue": true + }, + { + "name": "management.endpoint.restart.enabled", + "type": "java.lang.Boolean", + "description": "Enable the /restart endpoint to restart the application context.", + "defaultValue": true + }, + { + "name": "management.endpoint.pause.enabled", + "type": "java.lang.Boolean", + "description": "Enable the /pause endpoint (to send Lifecycle.stop()).", + "defaultValue": true + }, + { + "name": "management.endpoint.resume.enabled", + "type": "java.lang.Boolean", + "description": "Enable the /resume endpoint (to send Lifecycle.start()).", + "defaultValue": true + }, + { + "name": "spring.cloud.refresh.extra-refreshable", + "type": "java.util.Set", + "description": "Additional class names for beans to post process into refresh scope.", + "defaultValue": true + } + ] +} diff --git a/spring-cloud-context/src/main/resources/META-INF/spring.factories b/spring-cloud-context/src/main/resources/META-INF/spring.factories index be5c5d76..ed8b9b17 100644 --- a/spring-cloud-context/src/main/resources/META-INF/spring.factories +++ b/spring-cloud-context/src/main/resources/META-INF/spring.factories @@ -5,13 +5,11 @@ org.springframework.cloud.autoconfigure.LifecycleMvcEndpointAutoConfiguration,\ org.springframework.cloud.autoconfigure.RefreshAutoConfiguration,\ org.springframework.cloud.autoconfigure.RefreshEndpointAutoConfiguration,\ org.springframework.cloud.autoconfigure.WritableEnvironmentEndpointAutoConfiguration - # Application Listeners org.springframework.context.ApplicationListener=\ org.springframework.cloud.bootstrap.BootstrapApplicationListener,\ org.springframework.cloud.bootstrap.LoggingSystemShutdownListener,\ org.springframework.cloud.context.restart.RestartListener - # Bootstrap components org.springframework.cloud.bootstrap.BootstrapConfiguration=\ org.springframework.cloud.bootstrap.config.PropertySourceBootstrapConfiguration,\ diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/autoconfigure/LifecycleMvcAutoConfigurationTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/autoconfigure/LifecycleMvcAutoConfigurationTests.java index 440c31ff..fb3a94e4 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/autoconfigure/LifecycleMvcAutoConfigurationTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/autoconfigure/LifecycleMvcAutoConfigurationTests.java @@ -5,6 +5,7 @@ import java.util.function.Function; import org.assertj.core.util.Lists; import org.junit.Test; + import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.cloud.context.restart.RestartEndpoint; @@ -21,9 +22,20 @@ import static org.junit.Assert.assertThat; /** * @author Spencer Gibb */ -//TODO: super slow. Port to @SpringBootTest +// TODO: super slow. Port to @SpringBootTest public class LifecycleMvcAutoConfigurationTests { + private static ConfigurableApplicationContext getApplicationContext( + Class configuration, String... properties) { + + List defaultProperties = Lists.newArrayList(properties); + defaultProperties.add("server.port=0"); + defaultProperties.add("spring.jmx.default-domain=${random.uuid}"); + + return new SpringApplicationBuilder(configuration) + .properties(defaultProperties.toArray(new String[] {})).run(); + } + @Test public void environmentWebEndpointExtensionDisabled() { beanNotCreated("environmentWebEndpointExtension", @@ -45,47 +57,41 @@ public class LifecycleMvcAutoConfigurationTests { // restartEndpoint @Test public void restartEndpointDisabled() { - beanNotCreated("restartEndpoint", - "management.endpoint.restart.enabled=false"); + beanNotCreated("restartEndpoint", "management.endpoint.restart.enabled=false"); } @Test public void restartEndpointGloballyDisabled() { - beanNotCreated("restartEndpoint", - "management.endpoint.default.enabled=false"); + beanNotCreated("restartEndpoint", "management.endpoint.default.enabled=false"); } @Test public void restartEndpointEnabled() { beanCreatedAndEndpointEnabled("restartEndpoint", RestartEndpoint.class, - RestartEndpoint::restart, - "management.endpoint.restart.enabled=true"); + RestartEndpoint::restart, "management.endpoint.restart.enabled=true"); } // pauseEndpoint @Test public void pauseEndpointDisabled() { - beanNotCreated("pauseEndpoint", - "management.endpoint.pause.enabled=false"); + beanNotCreated("pauseEndpoint", "management.endpoint.pause.enabled=false"); } @Test public void pauseEndpointRestartDisabled() { - beanNotCreated("pauseEndpoint", - "management.endpoint.restart.enabled=false", + beanNotCreated("pauseEndpoint", "management.endpoint.restart.enabled=false", "management.endpoint.pause.enabled=true"); } @Test public void pauseEndpointGloballyDisabled() { - beanNotCreated("pauseEndpoint", - "management.endpoint.default.enabled=false"); + beanNotCreated("pauseEndpoint", "management.endpoint.default.enabled=false"); } @Test public void pauseEndpointEnabled() { - beanCreatedAndEndpointEnabled("pauseEndpoint", RestartEndpoint.PauseEndpoint.class, - RestartEndpoint.PauseEndpoint::pause, + beanCreatedAndEndpointEnabled("pauseEndpoint", + RestartEndpoint.PauseEndpoint.class, RestartEndpoint.PauseEndpoint::pause, "management.endpoint.restart.enabled=true", "management.endpoint.pause.enabled=true"); } @@ -93,48 +99,53 @@ public class LifecycleMvcAutoConfigurationTests { // resumeEndpoint @Test public void resumeEndpointDisabled() { - beanNotCreated("resumeEndpoint", - "management.endpoint.restart.enabled=true", + beanNotCreated("resumeEndpoint", "management.endpoint.restart.enabled=true", "management.endpoint.resume.enabled=false"); } @Test public void resumeEndpointRestartDisabled() { - beanNotCreated("resumeEndpoint", - "management.endpoint.restart.enabled=false", + beanNotCreated("resumeEndpoint", "management.endpoint.restart.enabled=false", "management.endpoint.resume.enabled=true"); } @Test public void resumeEndpointGloballyDisabled() { - beanNotCreated("resumeEndpoint", - "management.endpoint.default.enabled=false"); + beanNotCreated("resumeEndpoint", "management.endpoint.default.enabled=false"); } @Test public void resumeEndpointEnabled() { - beanCreatedAndEndpointEnabled("resumeEndpoint", RestartEndpoint.ResumeEndpoint.class, + beanCreatedAndEndpointEnabled("resumeEndpoint", + RestartEndpoint.ResumeEndpoint.class, RestartEndpoint.ResumeEndpoint::resume, "management.endpoint.restart.enabled=true", "management.endpoint.resume.enabled=true"); } private void beanNotCreated(String beanName, String... contextProperties) { - try (ConfigurableApplicationContext context = getApplicationContext(Config.class, contextProperties)) { - assertThat("bean was created", context.containsBeanDefinition(beanName), equalTo(false)); + try (ConfigurableApplicationContext context = getApplicationContext(Config.class, + contextProperties)) { + assertThat("bean was created", context.containsBeanDefinition(beanName), + equalTo(false)); } } private void beanCreated(String beanName, String... contextProperties) { - try (ConfigurableApplicationContext context = getApplicationContext(Config.class, contextProperties)) { - assertThat("bean was not created", context.containsBeanDefinition(beanName), equalTo(true)); + try (ConfigurableApplicationContext context = getApplicationContext(Config.class, + contextProperties)) { + assertThat("bean was not created", context.containsBeanDefinition(beanName), + equalTo(true)); } } @SuppressWarnings("unchecked") - private void beanCreatedAndEndpointEnabled(String beanName, Class type, Function function, String... properties) { - try (ConfigurableApplicationContext context = getApplicationContext(Config.class, properties)) { - assertThat("bean was not created", context.containsBeanDefinition(beanName), equalTo(true)); + private void beanCreatedAndEndpointEnabled(String beanName, Class type, + Function function, String... properties) { + try (ConfigurableApplicationContext context = getApplicationContext(Config.class, + properties)) { + assertThat("bean was not created", context.containsBeanDefinition(beanName), + equalTo(true)); Object endpoint = context.getBean(beanName, type); Object result = function.apply((T) endpoint); @@ -144,19 +155,10 @@ public class LifecycleMvcAutoConfigurationTests { } } - private static ConfigurableApplicationContext getApplicationContext( - Class configuration, String... properties) { - - List defaultProperties = Lists.newArrayList(properties); - defaultProperties.add("server.port=0"); - defaultProperties.add("spring.jmx.default-domain=${random.uuid}"); - - return new SpringApplicationBuilder(configuration).properties(defaultProperties.toArray(new String[]{})).run(); - } - @Configuration @EnableAutoConfiguration static class Config { } + } diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/autoconfigure/RefreshAutoConfigurationClassPathTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/autoconfigure/RefreshAutoConfigurationClassPathTests.java index eb32a9e6..fc872c89 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/autoconfigure/RefreshAutoConfigurationClassPathTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/autoconfigure/RefreshAutoConfigurationClassPathTests.java @@ -2,6 +2,7 @@ package org.springframework.cloud.autoconfigure; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.boot.WebApplicationType; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.builder.SpringApplicationBuilder; @@ -17,26 +18,31 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Spencer Gibb */ @RunWith(ModifiedClassPathRunner.class) -@ClassPathExclusions({"spring-boot-actuator-*.jar", "spring-boot-starter-actuator-*.jar"}) +@ClassPathExclusions({ "spring-boot-actuator-*.jar", + "spring-boot-starter-actuator-*.jar" }) public class RefreshAutoConfigurationClassPathTests { + private static ConfigurableApplicationContext getApplicationContext( + Class configuration, String... properties) { + return new SpringApplicationBuilder(configuration).web(WebApplicationType.NONE) + .properties(properties).run(); + } + @Test public void refreshEventListenerCreated() { try (ConfigurableApplicationContext context = getApplicationContext( Config.class)) { - assertThat(context.getBeansOfType(RefreshEventListener.class)).as("RefreshEventListeners not created").isNotEmpty(); - assertThat(context.containsBean("refreshEndpoint")).as("refreshEndpoint created").isFalse(); + assertThat(context.getBeansOfType(RefreshEventListener.class)) + .as("RefreshEventListeners not created").isNotEmpty(); + assertThat(context.containsBean("refreshEndpoint")) + .as("refreshEndpoint created").isFalse(); } } - private static ConfigurableApplicationContext getApplicationContext( - Class configuration, String... properties) { - return new SpringApplicationBuilder(configuration).web(WebApplicationType.NONE).properties(properties).run(); - } - @Configuration @EnableAutoConfiguration static class Config { } + } diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/autoconfigure/RefreshAutoConfigurationMoreClassPathTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/autoconfigure/RefreshAutoConfigurationMoreClassPathTests.java index c2d8faa8..3be02870 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/autoconfigure/RefreshAutoConfigurationMoreClassPathTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/autoconfigure/RefreshAutoConfigurationMoreClassPathTests.java @@ -19,25 +19,28 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Spencer Gibb */ @RunWith(ModifiedClassPathRunner.class) -@ClassPathExclusions({"spring-boot-actuator-autoconfigure-*.jar", "spring-boot-starter-actuator-*.jar"}) +@ClassPathExclusions({ "spring-boot-actuator-autoconfigure-*.jar", + "spring-boot-starter-actuator-*.jar" }) public class RefreshAutoConfigurationMoreClassPathTests { @Rule public OutputCapture outputCapture = new OutputCapture(); - @Test - public void unknownClassProtected() { - try (ConfigurableApplicationContext context = getApplicationContext( - Config.class, "debug=true")) { - String output = this.outputCapture.toString(); - assertThat(output).doesNotContain("Failed to introspect annotations on [class org.springframework.cloud.autoconfigure.RefreshEndpointAutoConfiguration") - .doesNotContain("TypeNotPresentExceptionProxy"); - } - } - private static ConfigurableApplicationContext getApplicationContext( Class configuration, String... properties) { - return new SpringApplicationBuilder(configuration).web(WebApplicationType.NONE).properties(properties).run(); + return new SpringApplicationBuilder(configuration).web(WebApplicationType.NONE) + .properties(properties).run(); + } + + @Test + public void unknownClassProtected() { + try (ConfigurableApplicationContext context = getApplicationContext(Config.class, + "debug=true")) { + String output = this.outputCapture.toString(); + assertThat(output).doesNotContain( + "Failed to introspect annotations on [class org.springframework.cloud.autoconfigure.RefreshEndpointAutoConfiguration") + .doesNotContain("TypeNotPresentExceptionProxy"); + } } @Configuration @@ -45,4 +48,5 @@ public class RefreshAutoConfigurationMoreClassPathTests { static class Config { } + } diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/autoconfigure/RefreshAutoConfigurationTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/autoconfigure/RefreshAutoConfigurationTests.java index 9510e72b..addc92d5 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/autoconfigure/RefreshAutoConfigurationTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/autoconfigure/RefreshAutoConfigurationTests.java @@ -24,12 +24,18 @@ public class RefreshAutoConfigurationTests { @Rule public OutputCapture output = new OutputCapture(); + private static ConfigurableApplicationContext getApplicationContext( + WebApplicationType type, Class configuration, String... properties) { + return new SpringApplicationBuilder(configuration).web(type) + .properties(properties).properties("server.port=0").run(); + } + @Test public void noWarnings() { try (ConfigurableApplicationContext context = getApplicationContext( WebApplicationType.NONE, Config.class)) { assertThat(context.containsBean("refreshScope")).isTrue(); - assertThat(output.toString()).doesNotContain("WARN"); + assertThat(this.output.toString()).doesNotContain("WARN"); } } @@ -63,12 +69,6 @@ public class RefreshAutoConfigurationTests { } } - private static ConfigurableApplicationContext getApplicationContext( - WebApplicationType type, Class configuration, String... properties) { - return new SpringApplicationBuilder(configuration).web(type) - .properties(properties).properties("server.port=0").run(); - } - @Configuration @EnableAutoConfiguration(exclude = DataSourceAutoConfiguration.class) @EnableConfigurationProperties(ConfigProps.class) @@ -78,7 +78,9 @@ public class RefreshAutoConfigurationTests { @ConfigurationProperties("config") static class ConfigProps { + private String foo; + private boolean sealed; public String getFoo() { @@ -92,5 +94,7 @@ public class RefreshAutoConfigurationTests { this.foo = foo; this.sealed = true; } + } + } diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/BootstrapDisabledAutoConfigurationIntegrationTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/BootstrapDisabledAutoConfigurationIntegrationTests.java index 9d1745ea..13fe53ed 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/BootstrapDisabledAutoConfigurationIntegrationTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/BootstrapDisabledAutoConfigurationIntegrationTests.java @@ -2,6 +2,7 @@ package org.springframework.cloud.bootstrap; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; @@ -13,16 +14,15 @@ import org.springframework.test.context.junit4.SpringRunner; import static org.junit.Assert.assertFalse; @RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class, - properties = "spring.cloud.bootstrap.enabled:false") +@SpringBootTest(classes = Application.class, properties = "spring.cloud.bootstrap.enabled:false") public class BootstrapDisabledAutoConfigurationIntegrationTests { - + @Autowired private ConfigurableEnvironment environment; @Test public void noBootstrapProperties() { - assertFalse(environment.getPropertySources().contains("bootstrap")); + assertFalse(this.environment.getPropertySources().contains("bootstrap")); } @EnableAutoConfiguration diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/BootstrapOrderingAutoConfigurationIntegrationTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/BootstrapOrderingAutoConfigurationIntegrationTests.java index 3cfbece8..63ed41b2 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/BootstrapOrderingAutoConfigurationIntegrationTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/BootstrapOrderingAutoConfigurationIntegrationTests.java @@ -3,6 +3,7 @@ package org.springframework.cloud.bootstrap; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; @@ -25,7 +26,7 @@ public class BootstrapOrderingAutoConfigurationIntegrationTests { private ConfigurableEnvironment environment; @Test - @Ignore //FIXME: spring boot 2.0.0 + @Ignore // FIXME: spring boot 2.0.0 public void bootstrapPropertiesExist() { assertTrue(this.environment.getPropertySources().contains( PropertySourceBootstrapConfiguration.BOOTSTRAP_PROPERTY_SOURCE_NAME)); diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/BootstrapOrderingCustomPropertySourceIntegrationTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/BootstrapOrderingCustomPropertySourceIntegrationTests.java index 00afe01d..0f6e8eb8 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/BootstrapOrderingCustomPropertySourceIntegrationTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/BootstrapOrderingCustomPropertySourceIntegrationTests.java @@ -7,6 +7,7 @@ import java.util.Map; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; @@ -25,8 +26,8 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class, - properties = { "encrypt.key:deadbeef", "spring.cloud.bootstrap.name:custom" }) +@SpringBootTest(classes = Application.class, properties = { "encrypt.key:deadbeef", + "spring.cloud.bootstrap.name:custom" }) @ActiveProfiles("encrypt") public class BootstrapOrderingCustomPropertySourceIntegrationTests { @@ -34,7 +35,7 @@ public class BootstrapOrderingCustomPropertySourceIntegrationTests { private ConfigurableEnvironment environment; @Test - @Ignore //FIXME: spring boot 2.0.0 + @Ignore // FIXME: spring boot 2.0.0 public void bootstrapPropertiesExist() { assertTrue(this.environment.getPropertySources().contains( PropertySourceBootstrapConfiguration.BOOTSTRAP_PROPERTY_SOURCE_NAME)); @@ -56,7 +57,7 @@ public class BootstrapOrderingCustomPropertySourceIntegrationTests { protected static class PropertySourceConfiguration implements PropertySourceLocator { public static Map MAP = new HashMap( - Collections. singletonMap("custom.foo", + Collections.singletonMap("custom.foo", "{cipher}6154ca04d4bb6144d672c4e3d750b5147116dd381946d51fa44f8bc25dc256f4")); @Override diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/BootstrapOrderingSpringApplicationJsonIntegrationTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/BootstrapOrderingSpringApplicationJsonIntegrationTests.java index f9df20bf..78fceea7 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/BootstrapOrderingSpringApplicationJsonIntegrationTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/BootstrapOrderingSpringApplicationJsonIntegrationTests.java @@ -4,6 +4,7 @@ import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; @@ -16,10 +17,12 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class, - properties = "spring.cloud.bootstrap.name:json") +@SpringBootTest(classes = Application.class, properties = "spring.cloud.bootstrap.name:json") public class BootstrapOrderingSpringApplicationJsonIntegrationTests { + @Autowired + private ConfigurableEnvironment environment; + @BeforeClass public static void spikeJson() { System.setProperty("SPRING_APPLICATION_JSON", "{\"message\":\"From JSON\"}"); @@ -30,9 +33,6 @@ public class BootstrapOrderingSpringApplicationJsonIntegrationTests { System.clearProperty("SPRING_APPLICATION_JSON"); } - @Autowired - private ConfigurableEnvironment environment; - @Test public void bootstrapPropertiesExist() { assertTrue(this.environment.getPropertySources() @@ -43,6 +43,7 @@ public class BootstrapOrderingSpringApplicationJsonIntegrationTests { @EnableAutoConfiguration @Configuration protected static class Application { + } } diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/BootstrapSourcesOrderingTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/BootstrapSourcesOrderingTests.java index 1e1630cd..e77c27f7 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/BootstrapSourcesOrderingTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/BootstrapSourcesOrderingTests.java @@ -26,6 +26,7 @@ public class BootstrapSourcesOrderingTests { @EnableAutoConfiguration @Configuration protected static class Application { + } } diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/MessageSourceConfigurationTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/MessageSourceConfigurationTests.java index ac193a87..2d2aa9ff 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/MessageSourceConfigurationTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/MessageSourceConfigurationTests.java @@ -26,6 +26,7 @@ import java.util.Locale; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; @@ -35,8 +36,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) -@SpringBootTest(classes = TestApplication.class, - properties = "debug=true") +@SpringBootTest(classes = TestApplication.class, properties = "debug=true") public class MessageSourceConfigurationTests { @Autowired @@ -44,7 +44,8 @@ public class MessageSourceConfigurationTests { @Test public void loadsMessage() { - Assert.assertEquals("Hello World!", this.messageSource.getMessage("hello.message", null, Locale.getDefault())); + Assert.assertEquals("Hello World!", this.messageSource.getMessage("hello.message", + null, Locale.getDefault())); } @Configuration diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/TestBootstrapConfiguration.java b/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/TestBootstrapConfiguration.java index 9b10593c..f20b011a 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/TestBootstrapConfiguration.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/TestBootstrapConfiguration.java @@ -24,15 +24,16 @@ import static org.springframework.cloud.bootstrap.TestHigherPriorityBootstrapCon @EnableConfigurationProperties public class TestBootstrapConfiguration { + public static List fooSightings = null; + public TestBootstrapConfiguration() { firstToBeCreated.compareAndSet(null, TestBootstrapConfiguration.class); } - public static List fooSightings = null; - @Bean @Qualifier("foo-during-bootstrap") - public String fooDuringBootstrap(ConfigurableEnvironment environment, ApplicationEventPublisher publisher) { + public String fooDuringBootstrap(ConfigurableEnvironment environment, + ApplicationEventPublisher publisher) { String property = environment.getProperty("test.bootstrap.foo", "undefined"); if (fooSightings != null) { diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/TestHigherPriorityBootstrapConfiguration.java b/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/TestHigherPriorityBootstrapConfiguration.java index 90aa8b5c..56476ea3 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/TestHigherPriorityBootstrapConfiguration.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/TestHigherPriorityBootstrapConfiguration.java @@ -12,13 +12,13 @@ import org.springframework.core.annotation.Order; @Order(Ordered.HIGHEST_PRECEDENCE) public class TestHigherPriorityBootstrapConfiguration { - static final AtomicReference> firstToBeCreated = new AtomicReference<>(); - public static final AtomicInteger count = new AtomicInteger(); + static final AtomicReference> firstToBeCreated = new AtomicReference<>(); public TestHigherPriorityBootstrapConfiguration() { count.incrementAndGet(); - firstToBeCreated.compareAndSet(null, TestHigherPriorityBootstrapConfiguration.class); + firstToBeCreated.compareAndSet(null, + TestHigherPriorityBootstrapConfiguration.class); } } diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/config/BootstrapConfigurationTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/config/BootstrapConfigurationTests.java index 020b4f17..81f3ea5d 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/config/BootstrapConfigurationTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/config/BootstrapConfigurationTests.java @@ -53,13 +53,13 @@ import static org.junit.Assert.assertTrue; */ public class BootstrapConfigurationTests { + @Rule + public ExpectedException expected = ExpectedException.none(); + private ConfigurableApplicationContext context; private ConfigurableApplicationContext sibling; - @Rule - public ExpectedException expected = ExpectedException.none(); - @After public void close() { // Expected.* is bound to the PropertySourceConfiguration below @@ -111,7 +111,6 @@ public class BootstrapConfigurationTests { /** * Running the test from maven will start from a different directory then starting it * from intellij - * * @return */ private String getExternalProperties() { @@ -275,10 +274,10 @@ public class BootstrapConfigurationTests { this.context = new SpringApplicationBuilder().sources(BareConfiguration.class) .child(BareConfiguration.class).web(WebApplicationType.NONE).run(); assertEquals(1, TestHigherPriorityBootstrapConfiguration.count.get()); - assertNotNull(context.getParent()); - assertEquals("bootstrap", context.getParent().getParent().getId()); - assertNull(context.getParent().getParent().getParent()); - assertEquals("bar", context.getEnvironment().getProperty("custom.foo")); + assertNotNull(this.context.getParent()); + assertEquals("bootstrap", this.context.getParent().getParent().getId()); + assertNull(this.context.getParent().getParent().getParent()); + assertEquals("bar", this.context.getEnvironment().getProperty("custom.foo")); } @Test @@ -294,18 +293,18 @@ public class BootstrapConfigurationTests { .properties("spring.application.name=context") .web(WebApplicationType.NONE).run(); assertEquals(1, TestHigherPriorityBootstrapConfiguration.count.get()); - assertNotNull(context.getParent()); - assertEquals("bootstrap", context.getParent().getParent().getId()); - assertNull(context.getParent().getParent().getParent()); - assertEquals("context", context.getEnvironment().getProperty("custom.foo")); + assertNotNull(this.context.getParent()); + assertEquals("bootstrap", this.context.getParent().getParent().getId()); + assertNull(this.context.getParent().getParent().getParent()); + assertEquals("context", this.context.getEnvironment().getProperty("custom.foo")); assertEquals("context", - context.getEnvironment().getProperty("spring.application.name")); - assertNotNull(sibling.getParent()); - assertEquals("bootstrap", sibling.getParent().getParent().getId()); - assertNull(sibling.getParent().getParent().getParent()); - assertEquals("sibling", sibling.getEnvironment().getProperty("custom.foo")); + this.context.getEnvironment().getProperty("spring.application.name")); + assertNotNull(this.sibling.getParent()); + assertEquals("bootstrap", this.sibling.getParent().getParent().getId()); + assertNull(this.sibling.getParent().getParent().getParent()); + assertEquals("sibling", this.sibling.getEnvironment().getProperty("custom.foo")); assertEquals("sibling", - sibling.getEnvironment().getProperty("spring.application.name")); + this.sibling.getEnvironment().getProperty("spring.application.name")); } @Test @@ -375,6 +374,7 @@ public class BootstrapConfigurationTests { @Configuration @EnableConfigurationProperties protected static class BareConfiguration { + } @Configuration @@ -416,6 +416,7 @@ public class BootstrapConfigurationTests { public void setFail(boolean fail) { this.fail = fail; } + } } diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/config/BootstrapListenerHierarchyIntegrationTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/config/BootstrapListenerHierarchyIntegrationTests.java index 1cb291a1..4ef41805 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/config/BootstrapListenerHierarchyIntegrationTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/config/BootstrapListenerHierarchyIntegrationTests.java @@ -16,21 +16,22 @@ package org.springframework.cloud.bootstrap.config; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.springframework.boot.WebApplicationType.NONE; - import org.junit.Test; + import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.springframework.boot.WebApplicationType.NONE; + /** * Integration tests for Bootstrap Listener's functionality of adding a bootstrap context * as the root Application Context - * + * * @author Biju Kunjummen */ public class BootstrapListenerHierarchyIntegrationTests { @@ -88,6 +89,7 @@ public class BootstrapListenerHierarchyIntegrationTests { @Configuration static class BasicConfiguration { + } @Configuration @@ -97,5 +99,7 @@ public class BootstrapListenerHierarchyIntegrationTests { public String rootBean() { return "rootBean"; } + } -} \ No newline at end of file + +} diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/encrypt/EncryptionBootstrapConfigurationTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/encrypt/EncryptionBootstrapConfigurationTests.java index 58be5d16..c631b756 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/encrypt/EncryptionBootstrapConfigurationTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/encrypt/EncryptionBootstrapConfigurationTests.java @@ -1,7 +1,7 @@ package org.springframework.cloud.bootstrap.encrypt; /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-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. @@ -70,17 +70,17 @@ public class EncryptionBootstrapConfigurationTests { context.close(); } - @Test public void rsaProperties() { ConfigurableApplicationContext context = new SpringApplicationBuilder( - EncryptionBootstrapConfiguration.class).web(WebApplicationType.NONE).properties( - "encrypt.key-store.location:classpath:/server.jks", - "encrypt.key-store.password:letmein", - "encrypt.key-store.alias:mytestkey", "encrypt.key-store.secret:changeme", - "encrypt.rsa.strong:true", - "encrypt.rsa.salt:foobar") - .run(); + EncryptionBootstrapConfiguration.class) + .web(WebApplicationType.NONE) + .properties("encrypt.key-store.location:classpath:/server.jks", + "encrypt.key-store.password:letmein", + "encrypt.key-store.alias:mytestkey", + "encrypt.key-store.secret:changeme", + "encrypt.rsa.strong:true", "encrypt.rsa.salt:foobar") + .run(); RsaProperties properties = context.getBean(RsaProperties.class); assertEquals("foobar", properties.getSalt()); assertTrue(properties.isStrong()); @@ -88,7 +88,6 @@ public class EncryptionBootstrapConfigurationTests { context.close(); } - @Test public void nonExistentKeystoreLocationShouldNotBeAllowed() { try { @@ -107,4 +106,5 @@ public class EncryptionBootstrapConfigurationTests { assertThat(e).hasRootCauseInstanceOf(IllegalStateException.class); } } + } diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/encrypt/EncryptionIntegrationTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/encrypt/EncryptionIntegrationTests.java index 5f5442cb..d9b8f89a 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/encrypt/EncryptionIntegrationTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/encrypt/EncryptionIntegrationTests.java @@ -1,6 +1,7 @@ package org.springframework.cloud.bootstrap.encrypt; import org.junit.Test; + import org.springframework.boot.WebApplicationType; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.context.properties.ConfigurationProperties; @@ -40,14 +41,17 @@ public class EncryptionIntegrationTests { @ConfigurationProperties("foo") protected static class PasswordProperties { + private String password; public String getPassword() { - return password; + return this.password; } public void setPassword(String password) { this.password = password; } + } + } diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/encrypt/EncryptorFactoryTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/encrypt/EncryptorFactoryTests.java index 9376b9e0..8667e3f3 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/encrypt/EncryptorFactoryTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/encrypt/EncryptorFactoryTests.java @@ -15,14 +15,15 @@ */ package org.springframework.cloud.bootstrap.encrypt; +import java.nio.charset.Charset; + import org.junit.Test; + import org.springframework.cloud.context.encrypt.EncryptorFactory; import org.springframework.core.io.ClassPathResource; import org.springframework.security.crypto.encrypt.TextEncryptor; import org.springframework.util.StreamUtils; -import java.nio.charset.Charset; - import static org.junit.Assert.assertEquals; /** @@ -49,4 +50,5 @@ public class EncryptorFactoryTests { + "MIIEowIBAAKCAQEAwClFgrRa/PUHPIJr9gvIPL6g6Rjp/TVZmVNOf2fL96DYbkj5\n"; new EncryptorFactory().create(key); } -} \ No newline at end of file + +} diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/encrypt/EnvironmentDecryptApplicationInitializerTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/encrypt/EnvironmentDecryptApplicationInitializerTests.java index a74906ee..f227c65a 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/encrypt/EnvironmentDecryptApplicationInitializerTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/encrypt/EnvironmentDecryptApplicationInitializerTests.java @@ -212,4 +212,5 @@ public class EnvironmentDecryptApplicationInitializerTests { verify(encryptor).decrypt("bar2"); verifyNoMoreInteractions(encryptor); } + } diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/encrypt/RsaDisabledTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/encrypt/RsaDisabledTests.java index df21f93d..0ddf57bf 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/encrypt/RsaDisabledTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/encrypt/RsaDisabledTests.java @@ -1,6 +1,6 @@ package org.springframework.cloud.bootstrap.encrypt; /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-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. @@ -35,30 +35,32 @@ import static org.hamcrest.Matchers.hasSize; * @author Ryan Baxter */ @RunWith(ModifiedClassPathRunner.class) -@ClassPathExclusions({"spring-security-rsa*.jar"}) +@ClassPathExclusions({ "spring-security-rsa*.jar" }) public class RsaDisabledTests { private ConfigurableApplicationContext context; @Before public void setUp() { - context = new SpringApplicationBuilder().web(WebApplicationType.NONE) - .sources(EncryptionBootstrapConfiguration.class).web(WebApplicationType.NONE).properties( - "encrypt.key:mykey", - "encrypt.rsa.strong:true", - "encrypt.rsa.salt:foobar").run(); + this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE) + .sources(EncryptionBootstrapConfiguration.class) + .web(WebApplicationType.NONE).properties("encrypt.key:mykey", + "encrypt.rsa.strong:true", "encrypt.rsa.salt:foobar") + .run(); } @After public void tearDown() { - if(context != null) { - context.close(); + if (this.context != null) { + this.context.close(); } } @Test public void testLoadBalancedRetryFactoryBean() throws Exception { - Map properties = context.getBeansOfType(RsaProperties.class); + Map properties = this.context + .getBeansOfType(RsaProperties.class); assertThat(properties.values(), hasSize(0)); } + } diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/context/environment/EnvironmentManagerIntegrationTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/context/environment/EnvironmentManagerIntegrationTests.java index 497e924f..f5397565 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/context/environment/EnvironmentManagerIntegrationTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/context/environment/EnvironmentManagerIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2018 the original author or authors. + * Copyright 2006-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. @@ -72,15 +72,13 @@ public class EnvironmentManagerIntegrationTests { @Test public void testRefresh() throws Exception { - assertEquals("Hello scope!", properties.getMessage()); + assertEquals("Hello scope!", this.properties.getMessage()); String content = property("message", "Foo"); - this.mvc.perform(post(BASE_PATH + "/env") - .content(content) - .contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) + this.mvc.perform(post(BASE_PATH + "/env").content(content) + .contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) .andExpect(content().string("{\"message\":\"Foo\"}")); - assertEquals("Foo", properties.getMessage()); + assertEquals("Foo", this.properties.getMessage()); } private String property(String name, String value) throws JsonProcessingException { @@ -89,23 +87,21 @@ public class EnvironmentManagerIntegrationTests { property.put("name", name); property.put("value", value); - return mapper.writeValueAsString(property); + return this.mapper.writeValueAsString(property); } @Test public void testRefreshFails() throws Exception { try { - this.mvc.perform(post(BASE_PATH + "/env") - .content(property("delay", "foo")) - .contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) + this.mvc.perform(post(BASE_PATH + "/env").content(property("delay", "foo")) + .contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) .andExpect(status().is5xxServerError()); fail("expected ServletException"); } catch (ServletException e) { // The underlying BindException is not handled by the dispatcher servlet } - assertEquals(0, properties.getDelay()); + assertEquals(0, this.properties.getDelay()); } @Test @@ -116,15 +112,15 @@ public class EnvironmentManagerIntegrationTests { @Test public void environmentBeansConfiguredCorrectly() { - Map envbeans = this.context.getBeansOfType(EnvironmentEndpoint.class); - assertThat(envbeans).hasSize(1) - .containsKey("environmentEndpoint"); + Map envbeans = this.context + .getBeansOfType(EnvironmentEndpoint.class); + assertThat(envbeans).hasSize(1).containsKey("environmentEndpoint"); assertThat(envbeans.get("environmentEndpoint")) .isInstanceOf(WritableEnvironmentEndpoint.class); - Map extbeans = this.context.getBeansOfType(EnvironmentEndpointWebExtension.class); - assertThat(extbeans).hasSize(1) - .containsKey("environmentEndpointWebExtension"); + Map extbeans = this.context + .getBeansOfType(EnvironmentEndpointWebExtension.class); + assertThat(extbeans).hasSize(1).containsKey("environmentEndpointWebExtension"); assertThat(extbeans.get("environmentEndpointWebExtension")) .isInstanceOf(WritableEnvironmentEndpointWebExtension.class); } @@ -148,7 +144,7 @@ public class EnvironmentManagerIntegrationTests { private int delay; public String getMessage() { - return message; + return this.message; } public void setMessage(String message) { @@ -156,12 +152,13 @@ public class EnvironmentManagerIntegrationTests { } public int getDelay() { - return delay; + return this.delay; } public void setDelay(int delay) { this.delay = delay; } + } } diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/context/environment/EnvironmentManagerTest.java b/spring-cloud-context/src/test/java/org/springframework/cloud/context/environment/EnvironmentManagerTest.java index a1c4affe..78b6a8d2 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/context/environment/EnvironmentManagerTest.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/context/environment/EnvironmentManagerTest.java @@ -42,4 +42,4 @@ public class EnvironmentManagerTest { assertThat(event.getKeys()).containsExactly("foo"); } -} \ No newline at end of file +} diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/context/named/NamedContextFactoryTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/context/named/NamedContextFactoryTests.java index 82ce09c7..37d60e67 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/context/named/NamedContextFactoryTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/context/named/NamedContextFactoryTests.java @@ -35,7 +35,8 @@ public class NamedContextFactoryTests { Bar bar = factory.getInstance("bar", Bar.class); assertThat("bar was null", bar, is(notNullValue())); - assertThat("context names not exposed", factory.getContextNames(), hasItems("foo", "bar")); + assertThat("context names not exposed", factory.getContextNames(), + hasItems("foo", "bar")); Bar foobar = factory.getInstance("foo", Bar.class); assertThat("bar was not null", foobar, is(nullValue())); @@ -60,7 +61,7 @@ public class NamedContextFactoryTests { } private TestSpec getSpec(String name, Class configClass) { - return new TestSpec(name, new Class[]{configClass}); + return new TestSpec(name, new Class[] { configClass }); } static class TestClientFactory extends NamedContextFactory { @@ -68,9 +69,11 @@ public class NamedContextFactoryTests { public TestClientFactory() { super(TestSpec.class, "testfactory", "test.client.name"); } + } static class TestSpec implements NamedContextFactory.Specification { + private String name; private Class[] configuration; @@ -85,7 +88,7 @@ public class NamedContextFactoryTests { @Override public String getName() { - return name; + return this.name; } public void setName(String name) { @@ -94,31 +97,43 @@ public class NamedContextFactoryTests { @Override public Class[] getConfiguration() { - return configuration; + return this.configuration; } public void setConfiguration(Class[] configuration) { this.configuration = configuration; } + } static class BaseConfig { + @Bean Baz baz1() { return new Baz(); } + + } + + static class Baz { + } - static class Baz{} static class FooConfig { + @Bean Foo foo() { return new Foo(); } + + } + + static class Foo { + } - static class Foo{} static class BarConfig { + @Bean Bar bar() { return new Bar(); @@ -128,7 +143,11 @@ public class NamedContextFactoryTests { Baz baz2() { return new Baz(); } + + } + + static class Bar { + } - static class Bar{} } diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/context/properties/ConfigurationPropertiesRebinderIntegrationTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/context/properties/ConfigurationPropertiesRebinderIntegrationTests.java index b5cae4eb..f4f4a40b 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/context/properties/ConfigurationPropertiesRebinderIntegrationTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/context/properties/ConfigurationPropertiesRebinderIntegrationTests.java @@ -108,6 +108,12 @@ public class ConfigurationPropertiesRebinderIntegrationTests { assertEquals(2, this.properties.getCount()); } + interface SomeService { + + void foo(); + + } + @Configuration @EnableConfigurationProperties @Import({ RefreshConfiguration.RebinderConfiguration.class, @@ -123,27 +129,30 @@ public class ConfigurationPropertiesRebinderIntegrationTests { @Bean @ConfigurationProperties("some.service") public SomeService someService() { - return ProxyFactory.getProxy(SomeService.class, (MethodInterceptor) methodInvocation -> null); + return ProxyFactory.getProxy(SomeService.class, + (MethodInterceptor) methodInvocation -> null); } - } - interface SomeService { - void foo(); } // Hack out a protected inner class for testing protected static class RefreshConfiguration extends RefreshAutoConfiguration { + @Configuration protected static class RebinderConfiguration extends ConfigurationPropertiesRebinderAutoConfiguration { } + } @ConfigurationProperties protected static class TestProperties { + private String message; + private int delay; + private int count = 0; public int getCount() { @@ -170,19 +179,23 @@ public class ConfigurationPropertiesRebinderIntegrationTests { public void init() { this.count++; } + } @ConfigurationProperties("config") @ConditionalOnMissingBean(ConfigProperties.class) public static class ConfigProperties { + private String name; public String getName() { - return name; + return this.name; } public void setName(String name) { this.name = name; } + } + } diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/context/properties/ConfigurationPropertiesRebinderLifecycleIntegrationTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/context/properties/ConfigurationPropertiesRebinderLifecycleIntegrationTests.java index a6c41c6f..129b970c 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/context/properties/ConfigurationPropertiesRebinderLifecycleIntegrationTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/context/properties/ConfigurationPropertiesRebinderLifecycleIntegrationTests.java @@ -80,16 +80,20 @@ public class ConfigurationPropertiesRebinderLifecycleIntegrationTests { // Hack out a protected inner class for testing protected static class RefreshConfiguration extends RefreshAutoConfiguration { + @Configuration protected static class RebinderConfiguration extends ConfigurationPropertiesRebinderAutoConfiguration { } + } @ConfigurationProperties protected static class TestProperties implements DisposableBean, InitializingBean { + private String message; + private int count = 0; public int getCount() { @@ -114,6 +118,7 @@ public class ConfigurationPropertiesRebinderLifecycleIntegrationTests { this.message = ""; this.count++; } + } } diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/context/properties/ConfigurationPropertiesRebinderListIntegrationTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/context/properties/ConfigurationPropertiesRebinderListIntegrationTests.java index a11e9f7b..1824870f 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/context/properties/ConfigurationPropertiesRebinderListIntegrationTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/context/properties/ConfigurationPropertiesRebinderListIntegrationTests.java @@ -15,8 +15,6 @@ */ package org.springframework.cloud.context.properties; -import static org.junit.Assert.assertEquals; - import java.util.List; import java.util.Map; @@ -25,6 +23,7 @@ import javax.annotation.PostConstruct; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; import org.springframework.boot.context.properties.ConfigurationProperties; @@ -42,9 +41,10 @@ import org.springframework.core.env.PropertySource; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringRunner; +import static org.junit.Assert.assertEquals; + @RunWith(SpringRunner.class) -@SpringBootTest(classes = TestConfiguration.class, - properties = "messages=one,two") +@SpringBootTest(classes = TestConfiguration.class, properties = "messages=one,two") public class ConfigurationPropertiesRebinderListIntegrationTests { @Autowired @@ -114,16 +114,20 @@ public class ConfigurationPropertiesRebinderListIntegrationTests { // Hack out a protected inner class for testing protected static class RefreshConfiguration extends RefreshAutoConfiguration { + @Configuration protected static class RebinderConfiguration extends ConfigurationPropertiesRebinderAutoConfiguration { } + } @ConfigurationProperties protected static class TestProperties { + private List messages; + private int count; public List getMessages() { @@ -142,6 +146,7 @@ public class ConfigurationPropertiesRebinderListIntegrationTests { public void init() { this.count++; } + } } diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/context/properties/ConfigurationPropertiesRebinderProxyIntegrationTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/context/properties/ConfigurationPropertiesRebinderProxyIntegrationTests.java index 7dfca19a..d44950e9 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/context/properties/ConfigurationPropertiesRebinderProxyIntegrationTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/context/properties/ConfigurationPropertiesRebinderProxyIntegrationTests.java @@ -15,8 +15,6 @@ */ package org.springframework.cloud.context.properties; -import static org.junit.Assert.assertEquals; - import java.util.HashMap; import java.util.Map; @@ -24,6 +22,7 @@ import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.aop.AopAutoConfiguration; import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; @@ -41,9 +40,11 @@ import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringRunner; +import static org.junit.Assert.assertEquals; + @RunWith(SpringRunner.class) -@SpringBootTest(classes = TestConfiguration.class, - properties = { "messages.expiry.one=168", "messages.expiry.two=76" }) +@SpringBootTest(classes = TestConfiguration.class, properties = { + "messages.expiry.one=168", "messages.expiry.two=76" }) public class ConfigurationPropertiesRebinderProxyIntegrationTests { @Autowired @@ -81,39 +82,44 @@ public class ConfigurationPropertiesRebinderProxyIntegrationTests { @Aspect protected static class Interceptor { + @Before("execution(* *..TestProperties.*(..))") public void before() { System.err.println("Before"); } + } // Hack out a protected inner class for testing protected static class RefreshConfiguration extends RefreshAutoConfiguration { + @Configuration protected static class RebinderConfiguration extends ConfigurationPropertiesRebinderAutoConfiguration { } + } @ConfigurationProperties("messages") protected static class TestProperties { - private String name; private final Map expiry = new HashMap<>(); + private String name; + public Map getExpiry() { - return expiry; + return this.expiry; } public String getName() { - return name; + return this.name; } public void setName(String name) { this.name = name; } + } } - diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/context/properties/ConfigurationPropertiesRebinderRefreshScopeIntegrationTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/context/properties/ConfigurationPropertiesRebinderRefreshScopeIntegrationTests.java index 04a07ff3..a612e141 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/context/properties/ConfigurationPropertiesRebinderRefreshScopeIntegrationTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/context/properties/ConfigurationPropertiesRebinderRefreshScopeIntegrationTests.java @@ -15,12 +15,11 @@ */ package org.springframework.cloud.context.properties; -import static org.junit.Assert.assertEquals; - import javax.annotation.PostConstruct; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; import org.springframework.boot.context.properties.ConfigurationProperties; @@ -38,6 +37,8 @@ import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringRunner; +import static org.junit.Assert.assertEquals; + @RunWith(SpringRunner.class) @SpringBootTest(classes = TestConfiguration.class) public class ConfigurationPropertiesRebinderRefreshScopeIntegrationTests { @@ -57,31 +58,31 @@ public class ConfigurationPropertiesRebinderRefreshScopeIntegrationTests { @Test @DirtiesContext public void testSimpleProperties() throws Exception { - assertEquals("Hello scope!", properties.getMessage()); + assertEquals("Hello scope!", this.properties.getMessage()); // Change the dynamic property source... TestPropertyValues.of("message:Foo").applyTo(this.environment); // ...but don't refresh, so the bean stays the same: - assertEquals("Hello scope!", properties.getMessage()); - assertEquals(1, properties.getCount()); + assertEquals("Hello scope!", this.properties.getMessage()); + assertEquals(1, this.properties.getCount()); } @Test @DirtiesContext public void testRefresh() throws Exception { - assertEquals(1, properties.getCount()); - assertEquals("Hello scope!", properties.getMessage()); - assertEquals(1, properties.getCount()); + assertEquals(1, this.properties.getCount()); + assertEquals("Hello scope!", this.properties.getMessage()); + assertEquals(1, this.properties.getCount()); // Change the dynamic property source... TestPropertyValues.of("message:Foo").applyTo(this.environment); // ...rebind, but the bean is not re-initialized: - rebinder.rebind(); - assertEquals("Hello scope!", properties.getMessage()); - assertEquals(1, properties.getCount()); + this.rebinder.rebind(); + assertEquals("Hello scope!", this.properties.getMessage()); + assertEquals(1, this.properties.getCount()); // ...and then refresh, so the bean is re-initialized: - refreshScope.refreshAll(); - assertEquals("Foo", properties.getMessage()); + this.refreshScope.refreshAll(); + assertEquals("Foo", this.properties.getMessage()); // It's a new instance so the initialization count is 1 - assertEquals(1, properties.getCount()); + assertEquals(1, this.properties.getCount()); } @Configuration @@ -101,16 +102,19 @@ public class ConfigurationPropertiesRebinderRefreshScopeIntegrationTests { @ConfigurationProperties protected static class TestProperties { + private String message; + private int delay; + private int count = 0; public int getCount() { - return count; + return this.count; } public String getMessage() { - return message; + return this.message; } public void setMessage(String message) { @@ -118,7 +122,7 @@ public class ConfigurationPropertiesRebinderRefreshScopeIntegrationTests { } public int getDelay() { - return delay; + return this.delay; } public void setDelay(int delay) { @@ -129,6 +133,7 @@ public class ConfigurationPropertiesRebinderRefreshScopeIntegrationTests { public void init() { this.count++; } + } } diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/context/refresh/ContextRefresherIntegrationTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/context/refresh/ContextRefresherIntegrationTests.java index f43083be..66e987a4 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/context/refresh/ContextRefresherIntegrationTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/context/refresh/ContextRefresherIntegrationTests.java @@ -74,7 +74,7 @@ public class ContextRefresherIntegrationTests { public void testUpdateHikari() throws Exception { assertEquals("Hello scope!", this.properties.getMessage()); TestPropertyValues.of("spring.datasource.hikari.read-only=true") - .applyTo(environment); + .applyTo(this.environment); // ...and then refresh, so the bean is re-initialized: this.refresher.refresh(); assertEquals("Hello scope!", this.properties.getMessage()); @@ -84,12 +84,15 @@ public class ContextRefresherIntegrationTests { @EnableConfigurationProperties(TestProperties.class) @EnableAutoConfiguration protected static class TestConfiguration { + } @ConfigurationProperties @ManagedResource protected static class TestProperties { + private String message; + private int delay; @ManagedAttribute @@ -109,6 +112,7 @@ public class ContextRefresherIntegrationTests { public void setDelay(int delay) { this.delay = delay; } + } } diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/context/refresh/ContextRefresherTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/context/refresh/ContextRefresherTests.java index d7591d0f..95c2d18f 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/context/refresh/ContextRefresherTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/context/refresh/ContextRefresherTests.java @@ -9,6 +9,7 @@ import java.util.Map; import org.junit.After; import org.junit.Test; import org.mockito.Mockito; + import org.springframework.boot.SpringApplication; import org.springframework.boot.logging.LoggingSystem; import org.springframework.boot.test.util.TestPropertyValues; @@ -44,7 +45,7 @@ public class ContextRefresherTests { List names = names(context.getEnvironment().getPropertySources()); assertThat(names).doesNotContain( "applicationConfig: [classpath:/bootstrap-refresh.properties]"); - ContextRefresher refresher = new ContextRefresher(context, scope); + ContextRefresher refresher = new ContextRefresher(context, this.scope); refresher.refresh(); names = names(context.getEnvironment().getPropertySources()); assertThat(names).contains( @@ -67,7 +68,7 @@ public class ContextRefresherTests { List names = names(context.getEnvironment().getPropertySources()); System.err.println("***** " + context.getEnvironment().getPropertySources()); assertThat(names).doesNotContain("bootstrapProperties"); - ContextRefresher refresher = new ContextRefresher(context, scope); + ContextRefresher refresher = new ContextRefresher(context, this.scope); TestPropertyValues.of( "spring.cloud.bootstrap.sources: org.springframework.cloud.context.refresh.ContextRefresherTests.PropertySourceConfiguration") .applyTo(context.getEnvironment(), Type.MAP, "defaultProperties"); @@ -85,7 +86,7 @@ public class ContextRefresherTests { ContextRefresherTests.class, "--spring.main.web-application-type=none", "--debug=false", "--spring.main.bannerMode=OFF", "--spring.cloud.bootstrap.name=refresh")) { - ContextRefresher refresher = new ContextRefresher(context, scope); + ContextRefresher refresher = new ContextRefresher(context, this.scope); TestPropertyValues.of( "spring.cloud.bootstrap.sources: org.springframework.cloud.context.refresh.ContextRefresherTests.PropertySourceConfiguration") .applyTo(context); @@ -111,7 +112,7 @@ public class ContextRefresherTests { "--spring.main.bannerMode=OFF", "--spring.cloud.bootstrap.name=refresh")) { assertThat(system.getCount()).isEqualTo(4); - ContextRefresher refresher = new ContextRefresher(context, scope); + ContextRefresher refresher = new ContextRefresher(context, this.scope); refresher.refresh(); assertThat(system.getCount()).isEqualTo(4); } @@ -122,21 +123,20 @@ public class ContextRefresherTests { TestBootstrapConfiguration.fooSightings = new ArrayList<>(); - try (ConfigurableApplicationContext context = SpringApplication.run(ContextRefresherTests.class, - "--spring.main.web-application-type=none", "--debug=false", - "--spring.main.bannerMode=OFF", - "--spring.cloud.bootstrap.name=refresh", - "--test.bootstrap.foo=bar")) { + try (ConfigurableApplicationContext context = SpringApplication.run( + ContextRefresherTests.class, "--spring.main.web-application-type=none", + "--debug=false", "--spring.main.bannerMode=OFF", + "--spring.cloud.bootstrap.name=refresh", "--test.bootstrap.foo=bar")) { context.getEnvironment().setActiveProfiles("refresh"); - ContextRefresher refresher = new ContextRefresher(context, scope); + ContextRefresher refresher = new ContextRefresher(context, this.scope); refresher.refresh(); - assertThat(TestBootstrapConfiguration.fooSightings).containsExactly("bar", "bar"); + assertThat(TestBootstrapConfiguration.fooSightings).containsExactly("bar", + "bar"); } TestBootstrapConfiguration.fooSightings = null; } - private List names(MutablePropertySources propertySources) { List list = new ArrayList<>(); for (PropertySource p : propertySources) { @@ -147,6 +147,7 @@ public class ContextRefresherTests { @Configuration protected static class Empty { + } @Configuration diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/context/restart/RestartIntegrationTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/context/restart/RestartIntegrationTests.java index 579e7247..7f8e3edd 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/context/restart/RestartIntegrationTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/context/restart/RestartIntegrationTests.java @@ -34,36 +34,40 @@ public class RestartIntegrationTests { private ConfigurableApplicationContext context; + public static void main(String[] args) { + SpringApplication.run(TestConfiguration.class, args); + } + @After public void close() { - if (context != null) { - context.close(); + if (this.context != null) { + this.context.close(); } } @Test public void testRestartTwice() throws Exception { - context = SpringApplication.run(TestConfiguration.class, + this.context = SpringApplication.run(TestConfiguration.class, "--management.endpoint.restart.enabled=true", "--server.port=0", "--spring.liveBeansView.mbeanDomain=livebeans"); - RestartEndpoint endpoint = context.getBean(RestartEndpoint.class); - assertNotNull(context.getParent()); - assertNull(context.getParent().getParent()); - context = endpoint.doRestart(); + RestartEndpoint endpoint = this.context.getBean(RestartEndpoint.class); + assertNotNull(this.context.getParent()); + assertNull(this.context.getParent().getParent()); + this.context = endpoint.doRestart(); - assertNotNull(context); - assertNotNull(context.getParent()); - assertNull(context.getParent().getParent()); + assertNotNull(this.context); + assertNotNull(this.context.getParent()); + assertNull(this.context.getParent().getParent()); - RestartEndpoint next = context.getBean(RestartEndpoint.class); + RestartEndpoint next = this.context.getBean(RestartEndpoint.class); assertNotSame(endpoint, next); - context = next.doRestart(); + this.context = next.doRestart(); - assertNotNull(context); - assertNotNull(context.getParent()); - assertNull(context.getParent().getParent()); + assertNotNull(this.context); + assertNotNull(this.context.getParent()); + assertNull(this.context.getParent().getParent()); LiveBeansView beans = new LiveBeansView(); String json = beans.getSnapshotAsJson(); @@ -71,13 +75,10 @@ public class RestartIntegrationTests { assertThat(json).containsOnlyOnce("parent\": null"); } - public static void main(String[] args) { - SpringApplication.run(TestConfiguration.class, args); - } - @Configuration @EnableAutoConfiguration protected static class TestConfiguration { + } } diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/ImportRefreshScopeIntegrationTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/ImportRefreshScopeIntegrationTests.java index 3ebfbc4a..45946d55 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/ImportRefreshScopeIntegrationTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/ImportRefreshScopeIntegrationTests.java @@ -17,6 +17,7 @@ package org.springframework.cloud.context.scope.refresh; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.boot.test.context.SpringBootTest; @@ -33,15 +34,15 @@ import static org.junit.Assert.assertEquals; @SpringBootTest(classes = TestConfiguration.class) public class ImportRefreshScopeIntegrationTests { + @Autowired + org.springframework.cloud.context.scope.refresh.RefreshScope scope; + @Autowired private ConfigurableListableBeanFactory beanFactory; @Autowired private ExampleService service; - @Autowired - org.springframework.cloud.context.scope.refresh.RefreshScope scope; - @Test public void testSimpleProperties() throws Exception { assertEquals("Hello scope!", this.service.getMessage()); @@ -63,6 +64,7 @@ public class ImportRefreshScopeIntegrationTests { @Configuration @Import({ RefreshAutoConfiguration.class, ExampleService.class }) protected static class TestConfiguration { + } } diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/MoreRefreshScopeIntegrationTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/MoreRefreshScopeIntegrationTests.java index 164ebcfd..5a749ccd 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/MoreRefreshScopeIntegrationTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/MoreRefreshScopeIntegrationTests.java @@ -16,17 +16,13 @@ package org.springframework.cloud.context.scope.refresh; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.aop.framework.Advised; import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.DisposableBean; @@ -46,6 +42,11 @@ import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringRunner; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + @RunWith(SpringRunner.class) @SpringBootTest(classes = TestConfiguration.class) public class MoreRefreshScopeIntegrationTests { @@ -89,7 +90,8 @@ public class MoreRefreshScopeIntegrationTests { assertEquals("Hello scope!", this.service.getMessage()); String id1 = this.service.toString(); // Change the dynamic property source... - TestPropertyValues.of("message:Foo").applyTo(this.environment, Type.MAP, "morerefreshtests"); + TestPropertyValues.of("message:Foo").applyTo(this.environment, Type.MAP, + "morerefreshtests"); // ...and then refresh, so the bean is re-initialized: this.scope.refreshAll(); String id2 = this.service.toString(); @@ -123,7 +125,6 @@ public class MoreRefreshScopeIntegrationTests { assertEquals("Foo", this.service.getMessage()); } - public static class TestService implements InitializingBean, DisposableBean { private static Log logger = LogFactory.getLog(TestService.class); @@ -136,6 +137,19 @@ public class MoreRefreshScopeIntegrationTests { private volatile long delay = 0; + public static void reset() { + initCount = 0; + destroyCount = 0; + } + + public static int getInitCount() { + return initCount; + } + + public static int getDestroyCount() { + return destroyCount; + } + public void setDelay(long delay) { this.delay = delay; } @@ -153,24 +167,6 @@ public class MoreRefreshScopeIntegrationTests { this.message = null; } - public static void reset() { - initCount = 0; - destroyCount = 0; - } - - public static int getInitCount() { - return initCount; - } - - public static int getDestroyCount() { - return destroyCount; - } - - public void setMessage(String message) { - logger.debug("Setting message: " + message); - this.message = message; - } - public String getMessage() { logger.debug("Getting message: " + this.message); try { @@ -183,6 +179,11 @@ public class MoreRefreshScopeIntegrationTests { return this.message; } + public void setMessage(String message) { + logger.debug("Setting message: " + message); + this.message = message; + } + } @Configuration @@ -232,6 +233,7 @@ public class MoreRefreshScopeIntegrationTests { public void setDelay(int delay) { this.delay = delay; } + } } diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshEndpointIntegrationTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshEndpointIntegrationTests.java index c175cef2..3ec0e661 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshEndpointIntegrationTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshEndpointIntegrationTests.java @@ -22,6 +22,7 @@ import java.util.Map; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties; @@ -51,9 +52,9 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen @RunWith(SpringRunner.class) @SpringBootTest(classes = ClientApp.class, properties = "management.endpoints.web.exposure.include=*", webEnvironment = RANDOM_PORT) public class RefreshEndpointIntegrationTests { - + private static final String BASE_PATH = new WebEndpointProperties().getBasePath(); - + @LocalServerPort private int port; @@ -61,9 +62,11 @@ public class RefreshEndpointIntegrationTests { public void webAccess() throws Exception { TestRestTemplate template = new TestRestTemplate(); template.exchange( - getUrlEncodedEntity("http://localhost:" + this.port + BASE_PATH + "/env", "message", - "Hello Dave!"), String.class); - template.postForObject("http://localhost:" + this.port + BASE_PATH + "/refresh", null, String.class); + getUrlEncodedEntity("http://localhost:" + this.port + BASE_PATH + "/env", + "message", "Hello Dave!"), + String.class); + template.postForObject("http://localhost:" + this.port + BASE_PATH + "/refresh", + null, String.class); String message = template.getForObject("http://localhost:" + this.port + "/", String.class); assertEquals("Hello Dave!", message); @@ -76,8 +79,8 @@ public class RefreshEndpointIntegrationTests { property.put("value", value); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); - RequestEntity> entity = new RequestEntity<>( - property, headers, HttpMethod.POST, new URI(uri)); + RequestEntity> entity = new RequestEntity<>(property, headers, + HttpMethod.POST, new URI(uri)); return entity; } @@ -85,23 +88,23 @@ public class RefreshEndpointIntegrationTests { @EnableAutoConfiguration protected static class ClientApp { + public static void main(String[] args) { + SpringApplication.run(ClientApp.class, args); + } + @Bean @RefreshScope public Controller controller() { return new Controller(); } - public static void main(String[] args) { - SpringApplication.run(ClientApp.class, args); - } - } @RestController protected static class Controller { String message; - + @Value("${message:Hello World!}") public void setMessage(String message) { this.message = message; @@ -114,5 +117,4 @@ public class RefreshEndpointIntegrationTests { } - } diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeConcurrencyTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeConcurrencyTests.java index 5ab26ccd..69d90ec4 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeConcurrencyTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeConcurrencyTests.java @@ -113,6 +113,7 @@ public class RefreshScopeConcurrencyTests { private static Log logger = LogFactory.getLog(ExampleService.class); private String message = null; + private volatile long delay = 0; public void setDelay(long delay) { @@ -130,11 +131,6 @@ public class RefreshScopeConcurrencyTests { this.message = null; } - public void setMessage(String message) { - logger.debug("Setting message: " + message); - this.message = message; - } - @Override public String getMessage() { logger.debug("Getting message: " + this.message); @@ -148,6 +144,11 @@ public class RefreshScopeConcurrencyTests { return this.message; } + public void setMessage(String message) { + logger.debug("Setting message: " + message); + this.message = message; + } + } @Configuration @@ -173,7 +174,9 @@ public class RefreshScopeConcurrencyTests { @ConfigurationProperties @ManagedResource protected static class TestProperties { + private String message; + private int delay; @ManagedAttribute @@ -193,6 +196,7 @@ public class RefreshScopeConcurrencyTests { public void setDelay(int delay) { this.delay = delay; } + } } diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeConfigurationScaleTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeConfigurationScaleTests.java index 47615bc1..759152d5 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeConfigurationScaleTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeConfigurationScaleTests.java @@ -15,9 +15,6 @@ */ package org.springframework.cloud.context.scope.refresh; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; @@ -31,6 +28,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; @@ -51,6 +49,9 @@ import org.springframework.test.annotation.Repeat; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.util.ObjectUtils; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + @RunWith(SpringRunner.class) @SpringBootTest(classes = TestConfiguration.class, properties = "logging.level.org.springframework.cloud.context.scope.refresh.RefreshScopeConfigurationScaleTests=DEBUG") public class RefreshScopeConfigurationScaleTests { @@ -58,11 +59,11 @@ public class RefreshScopeConfigurationScaleTests { private static Log logger = LogFactory .getLog(RefreshScopeConfigurationScaleTests.class); - private ExecutorService executor = Executors.newFixedThreadPool(8); - @Autowired org.springframework.cloud.context.scope.refresh.RefreshScope scope; + private ExecutorService executor = Executors.newFixedThreadPool(8); + @Autowired private ExampleService service; @@ -74,11 +75,11 @@ public class RefreshScopeConfigurationScaleTests { @DirtiesContext public void testConcurrentRefresh() throws Exception { - scope.setEager(false); + this.scope.setEager(false); // overload the thread pool and try to force Spring to create too many instances int n = 80; - TestPropertyValues.of("message=Foo").applyTo(environment); + TestPropertyValues.of("message=Foo").applyTo(this.environment); this.scope.refreshAll(); final CountDownLatch latch = new CountDownLatch(n); List> results = new ArrayList<>(); @@ -124,6 +125,7 @@ public class RefreshScopeConfigurationScaleTests { private static Log logger = LogFactory.getLog(ExampleService.class); private String message = null; + private volatile long delay = 0; public void setDelay(long delay) { @@ -151,12 +153,6 @@ public class RefreshScopeConfigurationScaleTests { this.message = null; } - public void setMessage(String message) { - logger.debug("Setting message: " + ObjectUtils.getIdentityHexString(this) - + ", " + message); - this.message = message; - } - @Override public String getMessage() { logger.debug("Returning message: " + ObjectUtils.getIdentityHexString(this) @@ -164,6 +160,12 @@ public class RefreshScopeConfigurationScaleTests { return this.message; } + public void setMessage(String message) { + logger.debug("Setting message: " + ObjectUtils.getIdentityHexString(this) + + ", " + message); + this.message = message; + } + } @Configuration @@ -191,7 +193,9 @@ public class RefreshScopeConfigurationScaleTests { @ConfigurationProperties protected static class TestProperties { + private String message; + private int delay; public String getMessage() { @@ -209,6 +213,7 @@ public class RefreshScopeConfigurationScaleTests { public void setDelay(int delay) { this.delay = delay; } + } } diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeConfigurationTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeConfigurationTests.java index 46ecce5f..20cd0f55 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeConfigurationTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeConfigurationTests.java @@ -41,23 +41,26 @@ import static org.junit.Assert.assertEquals; * */ public class RefreshScopeConfigurationTests { - - private AnnotationConfigApplicationContext context; - + @Rule public ExpectedException expected = ExpectedException.none(); + private AnnotationConfigApplicationContext context; + @After public void init() { - if (context!=null) { - context.close(); + if (this.context != null) { + this.context.close(); } } private void refresh() { - EnvironmentManager environmentManager = context.getBean(EnvironmentManager.class); + EnvironmentManager environmentManager = this.context + .getBean(EnvironmentManager.class); environmentManager.setProperty("message", "Hello Dave!"); - org.springframework.cloud.context.scope.refresh.RefreshScope scope = context.getBean(org.springframework.cloud.context.scope.refresh.RefreshScope.class); + org.springframework.cloud.context.scope.refresh.RefreshScope scope = this.context + .getBean( + org.springframework.cloud.context.scope.refresh.RefreshScope.class); scope.refreshAll(); } @@ -66,10 +69,13 @@ public class RefreshScopeConfigurationTests { */ @Test public void configurationWithRefreshScope() throws Exception { - context = new AnnotationConfigApplicationContext(Application.class, - PropertyPlaceholderAutoConfiguration.class, RefreshAutoConfiguration.class, LifecycleMvcEndpointAutoConfiguration.class); - Application application = context.getBean(Application.class); - assertEquals("refresh", context.getBeanDefinition("scopedTarget.application").getScope()); + this.context = new AnnotationConfigApplicationContext(Application.class, + PropertyPlaceholderAutoConfiguration.class, + RefreshAutoConfiguration.class, + LifecycleMvcEndpointAutoConfiguration.class); + Application application = this.context.getBean(Application.class); + assertEquals("refresh", + this.context.getBeanDefinition("scopedTarget.application").getScope()); application.hello(); refresh(); String message = application.hello(); @@ -78,9 +84,11 @@ public class RefreshScopeConfigurationTests { @Test public void refreshScopeOnBean() throws Exception { - context = new AnnotationConfigApplicationContext(ClientApp.class, - PropertyPlaceholderAutoConfiguration.class, RefreshAutoConfiguration.class, LifecycleMvcEndpointAutoConfiguration.class); - Controller application = context.getBean(Controller.class); + this.context = new AnnotationConfigApplicationContext(ClientApp.class, + PropertyPlaceholderAutoConfiguration.class, + RefreshAutoConfiguration.class, + LifecycleMvcEndpointAutoConfiguration.class); + Controller application = this.context.getBean(Controller.class); application.hello(); refresh(); String message = application.hello(); @@ -89,9 +97,11 @@ public class RefreshScopeConfigurationTests { @Test public void refreshScopeOnNested() throws Exception { - context = new AnnotationConfigApplicationContext(NestedApp.class, - PropertyPlaceholderAutoConfiguration.class, RefreshAutoConfiguration.class, LifecycleMvcEndpointAutoConfiguration.class); - NestedController application = context.getBean(NestedController.class); + this.context = new AnnotationConfigApplicationContext(NestedApp.class, + PropertyPlaceholderAutoConfiguration.class, + RefreshAutoConfiguration.class, + LifecycleMvcEndpointAutoConfiguration.class); + NestedController application = this.context.getBean(NestedController.class); application.hello(); refresh(); String message = application.hello(); @@ -101,7 +111,11 @@ public class RefreshScopeConfigurationTests { // WTF? Maven can't compile without the FQN on this one (not the others). @org.springframework.context.annotation.Configuration protected static class NestedApp { - + + public static void main(String[] args) { + SpringApplication.run(ClientApp.class, args); + } + @RestController @RefreshScope protected static class NestedController { @@ -111,15 +125,11 @@ public class RefreshScopeConfigurationTests { @RequestMapping("/") public String hello() { - return message; + return this.message; } } - public static void main(String[] args) { - SpringApplication.run(ClientApp.class, args); - } - } @Configuration("application") @@ -129,30 +139,30 @@ public class RefreshScopeConfigurationTests { @Value("${message:Hello World!}") String message = "Hello World"; - @RequestMapping("/") - public String hello() { - return message; - } - public static void main(String[] args) { SpringApplication.run(Application.class, args); } + @RequestMapping("/") + public String hello() { + return this.message; + } + } @Configuration protected static class ClientApp { - + + public static void main(String[] args) { + SpringApplication.run(ClientApp.class, args); + } + @Bean @RefreshScope public Controller controller() { return new Controller(); } - public static void main(String[] args) { - SpringApplication.run(ClientApp.class, args); - } - } @RestController @@ -164,7 +174,7 @@ public class RefreshScopeConfigurationTests { @RequestMapping("/") // Deliberately use package scope String hello() { - return message; + return this.message; } } diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeIntegrationTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeIntegrationTests.java index 522aa1f9..d3646b4a 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeIntegrationTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeIntegrationTests.java @@ -143,12 +143,29 @@ public class RefreshScopeIntegrationTests { private static Log logger = LogFactory.getLog(ExampleService.class); private volatile static int initCount = 0; + private volatile static int destroyCount = 0; + private volatile static RefreshScopeRefreshedEvent event; private String message = null; + private volatile long delay = 0; + public static void reset() { + initCount = 0; + destroyCount = 0; + event = null; + } + + public static int getInitCount() { + return initCount; + } + + public static int getDestroyCount() { + return destroyCount; + } + public void setDelay(long delay) { this.delay = delay; } @@ -166,25 +183,6 @@ public class RefreshScopeIntegrationTests { this.message = null; } - public static void reset() { - initCount = 0; - destroyCount = 0; - event = null; - } - - public static int getInitCount() { - return initCount; - } - - public static int getDestroyCount() { - return destroyCount; - } - - public void setMessage(String message) { - logger.debug("Setting message: " + message); - this.message = message; - } - @Override public String getMessage() { logger.debug("Getting message: " + this.message); @@ -198,6 +196,11 @@ public class RefreshScopeIntegrationTests { return this.message; } + public void setMessage(String message) { + logger.debug("Setting message: " + message); + this.message = message; + } + @Override public String throwsException() throws ServiceException { throw new ServiceException(); @@ -207,10 +210,13 @@ public class RefreshScopeIntegrationTests { public void onApplicationEvent(RefreshScopeRefreshedEvent e) { event = e; } + } @SuppressWarnings("serial") - public static class ServiceException extends Exception {} + public static class ServiceException extends Exception { + + } @Configuration @EnableConfigurationProperties(TestProperties.class) @@ -234,7 +240,9 @@ public class RefreshScopeIntegrationTests { @ConfigurationProperties @ManagedResource protected static class TestProperties { + private String message; + private int delay; @ManagedAttribute @@ -254,6 +262,7 @@ public class RefreshScopeIntegrationTests { public void setDelay(int delay) { this.delay = delay; } + } } diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeLazyIntegrationTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeLazyIntegrationTests.java index 3c8ff038..03930fe8 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeLazyIntegrationTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeLazyIntegrationTests.java @@ -136,12 +136,29 @@ public class RefreshScopeLazyIntegrationTests { private static Log logger = LogFactory.getLog(ExampleService.class); private volatile static int initCount = 0; + private volatile static int destroyCount = 0; + private volatile static RefreshScopeRefreshedEvent event; private String message = null; + private volatile long delay = 0; + public static void reset() { + initCount = 0; + destroyCount = 0; + event = null; + } + + public static int getInitCount() { + return initCount; + } + + public static int getDestroyCount() { + return destroyCount; + } + public void setDelay(long delay) { this.delay = delay; } @@ -159,25 +176,6 @@ public class RefreshScopeLazyIntegrationTests { this.message = null; } - public static void reset() { - initCount = 0; - destroyCount = 0; - event = null; - } - - public static int getInitCount() { - return initCount; - } - - public static int getDestroyCount() { - return destroyCount; - } - - public void setMessage(String message) { - logger.debug("Setting message: " + message); - this.message = message; - } - @Override public String getMessage() { logger.debug("Getting message: " + this.message); @@ -191,10 +189,16 @@ public class RefreshScopeLazyIntegrationTests { return this.message; } + public void setMessage(String message) { + logger.debug("Setting message: " + message); + this.message = message; + } + @Override public void onApplicationEvent(RefreshScopeRefreshedEvent e) { event = e; } + } @Configuration @@ -227,7 +231,9 @@ public class RefreshScopeLazyIntegrationTests { @ConfigurationProperties @ManagedResource protected static class TestProperties { + private String message; + private int delay; @ManagedAttribute @@ -247,6 +253,7 @@ public class RefreshScopeLazyIntegrationTests { public void setDelay(int delay) { this.delay = delay; } + } } diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeNullBeanIntegrationTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeNullBeanIntegrationTests.java index 755d994f..3db2509c 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeNullBeanIntegrationTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeNullBeanIntegrationTests.java @@ -17,6 +17,7 @@ package org.springframework.cloud.context.scope.refresh; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; @@ -31,7 +32,8 @@ import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringRunner.class) -@SpringBootTest(classes = {RefreshScopeNullBeanIntegrationTests.TestConfiguration.class}) +@SpringBootTest(classes = { + RefreshScopeNullBeanIntegrationTests.TestConfiguration.class }) public class RefreshScopeNullBeanIntegrationTests { @Autowired @@ -49,7 +51,9 @@ public class RefreshScopeNullBeanIntegrationTests { // this.scope.refreshAll(); } - protected static class OptionalService { } + protected static class OptionalService { + + } public static class MyCustomComponent { @@ -58,6 +62,7 @@ public class RefreshScopeNullBeanIntegrationTests { public MyCustomComponent(OptionalService optionalService) { this.optionalService = optionalService; } + } @Configuration @@ -68,10 +73,12 @@ public class RefreshScopeNullBeanIntegrationTests { public OptionalService service() { return null; } + } @Configuration - @Import({ RefreshAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, OptionalConfiguration.class }) + @Import({ RefreshAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, + OptionalConfiguration.class }) protected static class TestConfiguration { @Autowired(required = false) @@ -79,8 +86,9 @@ public class RefreshScopeNullBeanIntegrationTests { @Bean public MyCustomComponent myCustomComponent() { - return new MyCustomComponent(optionalService); + return new MyCustomComponent(this.optionalService); } + } } diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopePureScaleTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopePureScaleTests.java index 26549e72..cf542ede 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopePureScaleTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopePureScaleTests.java @@ -15,9 +15,6 @@ */ package org.springframework.cloud.context.scope.refresh; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; @@ -31,6 +28,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; @@ -47,18 +45,22 @@ import org.springframework.test.annotation.Repeat; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.util.ObjectUtils; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + @RunWith(SpringRunner.class) @SpringBootTest(classes = TestConfiguration.class) -// , properties="logging.level.org.springframework.cloud.context.scope.refresh.RefreshScopePureScaleTests=DEBUG") +// , +// properties="logging.level.org.springframework.cloud.context.scope.refresh.RefreshScopePureScaleTests=DEBUG") public class RefreshScopePureScaleTests { private static Log logger = LogFactory.getLog(RefreshScopePureScaleTests.class); - private ExecutorService executor = Executors.newFixedThreadPool(8); - @Autowired org.springframework.cloud.context.scope.refresh.RefreshScope scope; + private ExecutorService executor = Executors.newFixedThreadPool(8); + @Autowired private ExampleService service; @@ -91,7 +93,8 @@ public class RefreshScopePureScaleTests { public void run() { logger.debug("Refreshing."); RefreshScopePureScaleTests.this.scope.refreshAll(); - }}); + } + }); } assertTrue(latch.await(15000, TimeUnit.MILLISECONDS)); assertEquals("Foo", this.service.getMessage()); @@ -112,6 +115,7 @@ public class RefreshScopePureScaleTests { private static Log logger = LogFactory.getLog(ExampleService.class); private String message = null; + private volatile long delay = 0; public void setDelay(long delay) { @@ -120,33 +124,38 @@ public class RefreshScopePureScaleTests { @Override public void afterPropertiesSet() throws Exception { - logger.debug("Initializing: " + ObjectUtils.getIdentityHexString(this) + ", " + this.message); + logger.debug("Initializing: " + ObjectUtils.getIdentityHexString(this) + ", " + + this.message); try { Thread.sleep(this.delay); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } - logger.debug("Initialized: " + ObjectUtils.getIdentityHexString(this) + ", " + this.message); + logger.debug("Initialized: " + ObjectUtils.getIdentityHexString(this) + ", " + + this.message); } @Override public void destroy() throws Exception { - logger.debug("Destroying message: " + ObjectUtils.getIdentityHexString(this) + ", " + this.message); + logger.debug("Destroying message: " + ObjectUtils.getIdentityHexString(this) + + ", " + this.message); this.message = null; } - public void setMessage(String message) { - logger.debug("Setting message: " + ObjectUtils.getIdentityHexString(this) + ", " + message); - this.message = message; - } - @Override public String getMessage() { - logger.debug("Returning message: " + ObjectUtils.getIdentityHexString(this) + ", " + this.message); + logger.debug("Returning message: " + ObjectUtils.getIdentityHexString(this) + + ", " + this.message); return this.message; } + public void setMessage(String message) { + logger.debug("Setting message: " + ObjectUtils.getIdentityHexString(this) + + ", " + message); + this.message = message; + } + } @Configuration diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeScaleTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeScaleTests.java index 0cd9b7d6..9ba555d0 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeScaleTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeScaleTests.java @@ -56,11 +56,11 @@ public class RefreshScopeScaleTests { private static Log logger = LogFactory.getLog(RefreshScopeScaleTests.class); - private ExecutorService executor = Executors.newFixedThreadPool(8); - @Autowired org.springframework.cloud.context.scope.refresh.RefreshScope scope; + private ExecutorService executor = Executors.newFixedThreadPool(8); + @Autowired private ExampleService service; @@ -113,10 +113,12 @@ public class RefreshScopeScaleTests { private static Log logger = LogFactory.getLog(ExampleService.class); - private String message = null; - private volatile long delay = 0; private static volatile int count; + private String message = null; + + private volatile long delay = 0; + public void setDelay(long delay) { this.delay = delay; } @@ -139,17 +141,17 @@ public class RefreshScopeScaleTests { this.message = null; } - public void setMessage(String message) { - logger.debug("Setting message: " + message); - this.message = message; - } - @Override public String getMessage() { logger.debug("Returning message: " + this.message); return this.message; } + public void setMessage(String message) { + logger.debug("Setting message: " + message); + this.message = message; + } + } @Configuration @@ -175,7 +177,9 @@ public class RefreshScopeScaleTests { @ConfigurationProperties @ManagedResource protected static class TestProperties { + private String message; + private int delay; @ManagedAttribute @@ -195,6 +199,7 @@ public class RefreshScopeScaleTests { public void setDelay(int delay) { this.delay = delay; } + } } diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeSerializationTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeSerializationTests.java index 2343e780..f6322b22 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeSerializationTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeSerializationTests.java @@ -79,4 +79,5 @@ public class RefreshScopeSerializationTests { protected static class TestBean { } + } diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeWebIntegrationTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeWebIntegrationTests.java index 43eca069..b14262cf 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeWebIntegrationTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeWebIntegrationTests.java @@ -17,6 +17,7 @@ package org.springframework.cloud.context.scope.refresh; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; @@ -44,43 +45,44 @@ public class RefreshScopeWebIntegrationTests { @Autowired private org.springframework.cloud.context.scope.refresh.RefreshScope scope; - + @Autowired private EnvironmentManager environmentManager; - + @Autowired private Client application; - + @Autowired private ConfigurableListableBeanFactory beanFactory; - + @Test public void scopeOnBeanDefinition() throws Exception { - assertEquals("refresh", beanFactory.getBeanDefinition("scopedTarget.application").getScope()); + assertEquals("refresh", this.beanFactory + .getBeanDefinition("scopedTarget.application").getScope()); } @Test public void beanAccess() throws Exception { - application.hello(); - environmentManager.setProperty("message", "Hello Dave!"); - scope.refreshAll(); - String message = application.hello(); + this.application.hello(); + this.environmentManager.setProperty("message", "Hello Dave!"); + this.scope.refreshAll(); + String message = this.application.hello(); assertEquals("Hello Dave!", message); } - + @Configuration @EnableAutoConfiguration protected static class Application { - + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + @Bean @RefreshScope public Client application() { return new Client(); } - - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } } @@ -92,7 +94,7 @@ public class RefreshScopeWebIntegrationTests { @RequestMapping("/") public String hello() { - return message; + return this.message; } } diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/endpoint/RefreshEndpointTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/endpoint/RefreshEndpointTests.java index 1e562431..db6c98e5 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/endpoint/RefreshEndpointTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/endpoint/RefreshEndpointTests.java @@ -73,7 +73,7 @@ public class RefreshEndpointTests { .properties("spring.cloud.bootstrap.name:none").run(); RefreshScope scope = new RefreshScope(); scope.setApplicationContext(this.context); - context.getEnvironment().setActiveProfiles("local"); + this.context.getEnvironment().setActiveProfiles("local"); ContextRefresher contextRefresher = new ContextRefresher(this.context, scope); RefreshEndpoint endpoint = new RefreshEndpoint(contextRefresher); Collection keys = endpoint.refresh(); @@ -87,7 +87,7 @@ public class RefreshEndpointTests { .properties("spring.cloud.bootstrap.name:none").run(); RefreshScope scope = new RefreshScope(); scope.setApplicationContext(this.context); - context.getEnvironment().setActiveProfiles("override"); + this.context.getEnvironment().setActiveProfiles("override"); ContextRefresher contextRefresher = new ContextRefresher(this.context, scope); RefreshEndpoint endpoint = new RefreshEndpoint(contextRefresher); Collection keys = endpoint.refresh(); @@ -148,8 +148,8 @@ public class RefreshEndpointTests { @Test public void shutdownHooksCleaned() { - try (ConfigurableApplicationContext context = new SpringApplicationBuilder(Empty.class) - .web(WebApplicationType.NONE).bannerMode(Mode.OFF).run()) { + try (ConfigurableApplicationContext context = new SpringApplicationBuilder( + Empty.class).web(WebApplicationType.NONE).bannerMode(Mode.OFF).run()) { RefreshScope scope = new RefreshScope(); scope.setApplicationContext(context); ContextRefresher contextRefresher = new ContextRefresher(context, scope); @@ -173,8 +173,8 @@ public class RefreshEndpointTests { @Configuration protected static class Empty implements SmartApplicationListener { - private List events = new ArrayList(); + private List events = new ArrayList(); @Override public boolean supportsEventType(Class eventType) { @@ -184,11 +184,12 @@ public class RefreshEndpointTests { @Override public void onApplicationEvent(ApplicationEvent event) { - if (event instanceof EnvironmentChangeEvent || - event instanceof RefreshScopeRefreshedEvent) { + if (event instanceof EnvironmentChangeEvent + || event instanceof RefreshScopeRefreshedEvent) { this.events.add(event); } } + } @Component @@ -202,4 +203,5 @@ public class RefreshEndpointTests { } } + } diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/health/RefreshScopeHealthIndicatorTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/health/RefreshScopeHealthIndicatorTests.java index 88adea70..56878f7c 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/health/RefreshScopeHealthIndicatorTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/health/RefreshScopeHealthIndicatorTests.java @@ -38,19 +38,20 @@ public class RefreshScopeHealthIndicatorTests { @SuppressWarnings("unchecked") private ObjectProvider scopeProvider = mock(ObjectProvider.class); - private ConfigurationPropertiesRebinder rebinder = - mock(ConfigurationPropertiesRebinder.class); + + private ConfigurationPropertiesRebinder rebinder = mock( + ConfigurationPropertiesRebinder.class); + private RefreshScope scope = mock(RefreshScope.class); + private RefreshScopeHealthIndicator indicator = new RefreshScopeHealthIndicator( this.scopeProvider, this.rebinder); @Before public void init() { - BDDMockito.willReturn(scope).given(scopeProvider).getIfAvailable(); - when(this.rebinder.getErrors()) - .thenReturn(Collections.emptyMap()); - when(this.scope.getErrors()) - .thenReturn(Collections.emptyMap()); + BDDMockito.willReturn(this.scope).given(this.scopeProvider).getIfAvailable(); + when(this.rebinder.getErrors()).thenReturn(Collections.emptyMap()); + when(this.scope.getErrors()).thenReturn(Collections.emptyMap()); } @Test @@ -60,24 +61,24 @@ public class RefreshScopeHealthIndicatorTests { @Test public void binderError() { - when(this.rebinder.getErrors()).thenReturn(Collections - .singletonMap("foo", new RuntimeException("FOO"))); + when(this.rebinder.getErrors()) + .thenReturn(Collections.singletonMap("foo", new RuntimeException("FOO"))); assertEquals(Status.DOWN, this.indicator.health().getStatus()); } @Test public void scopeError() { - when(this.scope.getErrors()).thenReturn(Collections - .singletonMap("foo", new RuntimeException("FOO"))); + when(this.scope.getErrors()) + .thenReturn(Collections.singletonMap("foo", new RuntimeException("FOO"))); assertEquals(Status.DOWN, this.indicator.health().getStatus()); } @Test public void bothError() { - when(this.rebinder.getErrors()).thenReturn(Collections - .singletonMap("foo", new RuntimeException("FOO"))); - when(this.scope.getErrors()).thenReturn(Collections - .singletonMap("bar", new RuntimeException("BAR"))); + when(this.rebinder.getErrors()) + .thenReturn(Collections.singletonMap("foo", new RuntimeException("FOO"))); + when(this.scope.getErrors()) + .thenReturn(Collections.singletonMap("bar", new RuntimeException("BAR"))); assertEquals(Status.DOWN, this.indicator.health().getStatus()); } diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/logging/LoggingRebinderTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/logging/LoggingRebinderTests.java index b752360c..a7aafb84 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/logging/LoggingRebinderTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/logging/LoggingRebinderTests.java @@ -15,9 +15,6 @@ */ package org.springframework.cloud.logging; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - import java.util.Collections; import org.junit.After; @@ -31,6 +28,9 @@ import org.springframework.boot.test.util.TestPropertyValues; import org.springframework.cloud.context.environment.EnvironmentChangeEvent; import org.springframework.core.env.StandardEnvironment; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + /** * @author Dave Syer * @@ -38,6 +38,7 @@ import org.springframework.core.env.StandardEnvironment; public class LoggingRebinderTests { private LoggingRebinder rebinder = new LoggingRebinder(); + private Logger logger = LoggerFactory.getLogger("org.springframework.web"); @After diff --git a/spring-cloud-context/src/test/resources/application-config.properties b/spring-cloud-context/src/test/resources/application-config.properties index d4408d3f..b2456bd0 100644 --- a/spring-cloud-context/src/test/resources/application-config.properties +++ b/spring-cloud-context/src/test/resources/application-config.properties @@ -1 +1 @@ -config.name: main +config.name:main diff --git a/spring-cloud-context/src/test/resources/application-encrypt.properties b/spring-cloud-context/src/test/resources/application-encrypt.properties index b1329f64..95f6d292 100644 --- a/spring-cloud-context/src/test/resources/application-encrypt.properties +++ b/spring-cloud-context/src/test/resources/application-encrypt.properties @@ -1 +1 @@ -foo: {cipher}e4e061f9fe39ba5b14d8012d2f17d39775606039409b71ed4be0fdd033d5324a +foo:{cipher}e4e061f9fe39ba5b14d8012d2f17d39775606039409b71ed4be0fdd033d5324a diff --git a/spring-cloud-context/src/test/resources/application-local.properties b/spring-cloud-context/src/test/resources/application-local.properties index 4da25c00..8f441186 100644 --- a/spring-cloud-context/src/test/resources/application-local.properties +++ b/spring-cloud-context/src/test/resources/application-local.properties @@ -1 +1 @@ -added: Hello added! +added:Hello added! diff --git a/spring-cloud-context/src/test/resources/application-override.properties b/spring-cloud-context/src/test/resources/application-override.properties index ea5f7924..5ccbd612 100644 --- a/spring-cloud-context/src/test/resources/application-override.properties +++ b/spring-cloud-context/src/test/resources/application-override.properties @@ -1 +1 @@ -message: Hello override! +message:Hello override! diff --git a/spring-cloud-context/src/test/resources/application.properties b/spring-cloud-context/src/test/resources/application.properties index 7d728818..80038522 100644 --- a/spring-cloud-context/src/test/resources/application.properties +++ b/spring-cloud-context/src/test/resources/application.properties @@ -1,7 +1,7 @@ -message: Hello scope! -delay: 0 -debug: true +message:Hello scope! +delay:0 +debug:true #logging.level.org.springframework.web: DEBUG #logging.level.org.springframework.context.annotation: DEBUG logging.level.org.hibernate=ERROR -logging.level.com.zaxxer.hikari=ERROR \ No newline at end of file +logging.level.com.zaxxer.hikari=ERROR diff --git a/spring-cloud-context/src/test/resources/bootstrap-config.properties b/spring-cloud-context/src/test/resources/bootstrap-config.properties index d61d540a..f8e4e860 100644 --- a/spring-cloud-context/src/test/resources/bootstrap-config.properties +++ b/spring-cloud-context/src/test/resources/bootstrap-config.properties @@ -1,2 +1,2 @@ -spring.main.sources: org.springframework.cloud.context.properties.ConfigurationPropertiesRebinderIntegrationTests.ConfigProperties -config.name: parent +spring.main.sources:org.springframework.cloud.context.properties.ConfigurationPropertiesRebinderIntegrationTests.ConfigProperties +config.name:parent diff --git a/spring-cloud-context/src/test/resources/bootstrap-encrypt.properties b/spring-cloud-context/src/test/resources/bootstrap-encrypt.properties index 3035e009..81ce3411 100644 --- a/spring-cloud-context/src/test/resources/bootstrap-encrypt.properties +++ b/spring-cloud-context/src/test/resources/bootstrap-encrypt.properties @@ -1 +1 @@ -bar: {cipher}6154ca04d4bb6144d672c4e3d750b5147116dd381946d51fa44f8bc25dc256f4 \ No newline at end of file +bar:{cipher}6154ca04d4bb6144d672c4e3d750b5147116dd381946d51fa44f8bc25dc256f4 diff --git a/spring-cloud-context/src/test/resources/bootstrap-parent.properties b/spring-cloud-context/src/test/resources/bootstrap-parent.properties index 0c36bbdd..3ff20cea 100644 --- a/spring-cloud-context/src/test/resources/bootstrap-parent.properties +++ b/spring-cloud-context/src/test/resources/bootstrap-parent.properties @@ -1 +1 @@ -info.name: parent \ No newline at end of file +info.name:parent diff --git a/spring-cloud-context/src/test/resources/bootstrap-refresh.properties b/spring-cloud-context/src/test/resources/bootstrap-refresh.properties index 7c55d8a5..3a3d334c 100644 --- a/spring-cloud-context/src/test/resources/bootstrap-refresh.properties +++ b/spring-cloud-context/src/test/resources/bootstrap-refresh.properties @@ -1,2 +1,2 @@ -info.name: refresh-child -test.bootstrap.foo: refresh \ No newline at end of file +info.name:refresh-child +test.bootstrap.foo:refresh diff --git a/spring-cloud-context/src/test/resources/bootstrap.properties b/spring-cloud-context/src/test/resources/bootstrap.properties index 9ec10bf9..dd6946b7 100644 --- a/spring-cloud-context/src/test/resources/bootstrap.properties +++ b/spring-cloud-context/src/test/resources/bootstrap.properties @@ -1,2 +1,2 @@ -spring.main.sources: org.springframework.cloud.bootstrap.config.BootstrapConfigurationTests.PropertySourceConfiguration -info.name: child +spring.main.sources:org.springframework.cloud.bootstrap.config.BootstrapConfigurationTests.PropertySourceConfiguration +info.name:child diff --git a/spring-cloud-context/src/test/resources/custom.properties b/spring-cloud-context/src/test/resources/custom.properties index 1ee3320d..dd62949d 100644 --- a/spring-cloud-context/src/test/resources/custom.properties +++ b/spring-cloud-context/src/test/resources/custom.properties @@ -1 +1 @@ -spring.main.sources: org.springframework.cloud.bootstrap.BootstrapOrderingCustomPropertySourceIntegrationTests.PropertySourceConfiguration +spring.main.sources:org.springframework.cloud.bootstrap.BootstrapOrderingCustomPropertySourceIntegrationTests.PropertySourceConfiguration diff --git a/spring-cloud-context/src/test/resources/external-properties/bootstrap.properties b/spring-cloud-context/src/test/resources/external-properties/bootstrap.properties index 925265df..49cbc6ac 100644 --- a/spring-cloud-context/src/test/resources/external-properties/bootstrap.properties +++ b/spring-cloud-context/src/test/resources/external-properties/bootstrap.properties @@ -1 +1 @@ -info.name: externalPropertiesInfoName \ No newline at end of file +info.name:externalPropertiesInfoName diff --git a/spring-cloud-context/src/test/resources/local.properties b/spring-cloud-context/src/test/resources/local.properties index 745d475e..34f56a4c 100644 --- a/spring-cloud-context/src/test/resources/local.properties +++ b/spring-cloud-context/src/test/resources/local.properties @@ -1 +1 @@ -spring.profiles.active: local \ No newline at end of file +spring.profiles.active:local diff --git a/spring-cloud-context/src/test/resources/messages.properties b/spring-cloud-context/src/test/resources/messages.properties index 16f361eb..ce7bbd5e 100644 --- a/spring-cloud-context/src/test/resources/messages.properties +++ b/spring-cloud-context/src/test/resources/messages.properties @@ -1 +1 @@ -hello.message=Hello World! \ No newline at end of file +hello.message=Hello World! diff --git a/spring-cloud-context/src/test/resources/other.properties b/spring-cloud-context/src/test/resources/other.properties index dc756282..0c4bb2a0 100644 --- a/spring-cloud-context/src/test/resources/other.properties +++ b/spring-cloud-context/src/test/resources/other.properties @@ -1 +1 @@ -spring.application.name: main \ No newline at end of file +spring.application.name:main diff --git a/spring-cloud-context/src/test/resources/plain.properties b/spring-cloud-context/src/test/resources/plain.properties index aa8f5408..132334be 100644 --- a/spring-cloud-context/src/test/resources/plain.properties +++ b/spring-cloud-context/src/test/resources/plain.properties @@ -1 +1 @@ -spring.application.name: app +spring.application.name:app diff --git a/spring-cloud-loadbalancer/pom.xml b/spring-cloud-loadbalancer/pom.xml index d770fb38..625699fd 100644 --- a/spring-cloud-loadbalancer/pom.xml +++ b/spring-cloud-loadbalancer/pom.xml @@ -1,6 +1,7 @@ - + 4.0.0 diff --git a/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/annotation/LoadBalancerClient.java b/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/annotation/LoadBalancerClient.java index ff84c880..998aa79b 100644 --- a/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/annotation/LoadBalancerClient.java +++ b/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/annotation/LoadBalancerClient.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-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. @@ -29,8 +29,8 @@ import org.springframework.core.annotation.AliasFor; /** * Declarative configuration for a load balancer client. Add this annotation to any - * @Configuration and then inject a {@link LoadBalancerClientFactory} to access the - * client that is created. + * @Configuration and then inject a {@link LoadBalancerClientFactory} to + * access the client that is created. * * @author Dave Syer */ @@ -42,25 +42,28 @@ import org.springframework.core.annotation.AliasFor; public @interface LoadBalancerClient { /** - * Synonym for name (the name of the client) + * Synonym for name (the name of the client). * * @see #name() + * @return the name of the load balancer client */ @AliasFor("name") String value() default ""; /** - * The name of the load balancer client, uniquely identifying a set of client resources, - * including a load balancer. + * The name of the load balancer client, uniquely identifying a set of client + * resources, including a load balancer. + * @return the name of the load balancer client */ @AliasFor("value") String name() default ""; /** - * A custom @Configuration for the load balancer client. Can contain override - * @Bean definition for the pieces that make up the client. + * A custom @Configuration for the load balancer client. Can contain + * override @Bean definition for the pieces that make up the client. * * @see LoadBalancerClientConfiguration for the defaults + * @return configuration classes for the load balancer client. */ Class[] configuration() default {}; diff --git a/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/annotation/LoadBalancerClientConfiguration.java b/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/annotation/LoadBalancerClientConfiguration.java index 95eb8f35..3124e557 100644 --- a/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/annotation/LoadBalancerClientConfiguration.java +++ b/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/annotation/LoadBalancerClientConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-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. @@ -38,11 +38,14 @@ public class LoadBalancerClientConfiguration { @Bean @ConditionalOnMissingBean public ServiceInstanceSupplier discoveryClientServiceInstanceSupplier( - DiscoveryClient discoveryClient, Environment env, ObjectProvider cacheManager) { - //TODO: bean post processor to enable caching? - DiscoveryClientServiceInstanceSupplier delegate = new DiscoveryClientServiceInstanceSupplier(discoveryClient, env); + DiscoveryClient discoveryClient, Environment env, + ObjectProvider cacheManager) { + // TODO: bean post processor to enable caching? + DiscoveryClientServiceInstanceSupplier delegate = new DiscoveryClientServiceInstanceSupplier( + discoveryClient, env); if (cacheManager.getIfAvailable() != null) { - return new CachingServiceInstanceSupplier(delegate, cacheManager.getIfAvailable()); + return new CachingServiceInstanceSupplier(delegate, + cacheManager.getIfAvailable()); } return delegate; } diff --git a/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/annotation/LoadBalancerClientConfigurationRegistrar.java b/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/annotation/LoadBalancerClientConfigurationRegistrar.java index 67c0fa07..98030fef 100644 --- a/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/annotation/LoadBalancerClientConfigurationRegistrar.java +++ b/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/annotation/LoadBalancerClientConfigurationRegistrar.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-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. @@ -28,37 +28,8 @@ import org.springframework.util.StringUtils; /** * @author Dave Syer */ -public class LoadBalancerClientConfigurationRegistrar implements ImportBeanDefinitionRegistrar { - - @Override - public void registerBeanDefinitions(AnnotationMetadata metadata, - BeanDefinitionRegistry registry) { - Map attrs = metadata.getAnnotationAttributes( - LoadBalancerClients.class.getName(), true); - if (attrs != null && attrs.containsKey("value")) { - AnnotationAttributes[] clients = (AnnotationAttributes[]) attrs.get("value"); - for (AnnotationAttributes client : clients) { - registerClientConfiguration(registry, getClientName(client), - client.get("configuration")); - } - } - if (attrs != null && attrs.containsKey("defaultConfiguration")) { - String name; - if (metadata.hasEnclosingClass()) { - name = "default." + metadata.getEnclosingClassName(); - } else { - name = "default." + metadata.getClassName(); - } - registerClientConfiguration(registry, name, - attrs.get("defaultConfiguration")); - } - Map client = metadata.getAnnotationAttributes( - LoadBalancerClient.class.getName(), true); - String name = getClientName(client); - if (name != null) { - registerClientConfiguration(registry, name, client.get("configuration")); - } - } +public class LoadBalancerClientConfigurationRegistrar + implements ImportBeanDefinitionRegistrar { private static String getClientName(Map client) { if (client == null) { @@ -76,7 +47,7 @@ public class LoadBalancerClientConfigurationRegistrar implements ImportBeanDefin } private static void registerClientConfiguration(BeanDefinitionRegistry registry, - Object name, Object configuration) { + Object name, Object configuration) { BeanDefinitionBuilder builder = BeanDefinitionBuilder .genericBeanDefinition(LoadBalancerClientSpecification.class); builder.addConstructorArgValue(name); @@ -85,4 +56,35 @@ public class LoadBalancerClientConfigurationRegistrar implements ImportBeanDefin builder.getBeanDefinition()); } + @Override + public void registerBeanDefinitions(AnnotationMetadata metadata, + BeanDefinitionRegistry registry) { + Map attrs = metadata + .getAnnotationAttributes(LoadBalancerClients.class.getName(), true); + if (attrs != null && attrs.containsKey("value")) { + AnnotationAttributes[] clients = (AnnotationAttributes[]) attrs.get("value"); + for (AnnotationAttributes client : clients) { + registerClientConfiguration(registry, getClientName(client), + client.get("configuration")); + } + } + if (attrs != null && attrs.containsKey("defaultConfiguration")) { + String name; + if (metadata.hasEnclosingClass()) { + name = "default." + metadata.getEnclosingClassName(); + } + else { + name = "default." + metadata.getClassName(); + } + registerClientConfiguration(registry, name, + attrs.get("defaultConfiguration")); + } + Map client = metadata + .getAnnotationAttributes(LoadBalancerClient.class.getName(), true); + String name = getClientName(client); + if (name != null) { + registerClientConfiguration(registry, name, client.get("configuration")); + } + } + } diff --git a/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/annotation/LoadBalancerClientSpecification.java b/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/annotation/LoadBalancerClientSpecification.java index b990e1a3..30afe2b2 100644 --- a/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/annotation/LoadBalancerClientSpecification.java +++ b/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/annotation/LoadBalancerClientSpecification.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-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. @@ -26,7 +26,8 @@ import org.springframework.util.Assert; /** * @author Dave Syer */ -public class LoadBalancerClientSpecification implements NamedContextFactory.Specification { +public class LoadBalancerClientSpecification + implements NamedContextFactory.Specification { private String name; @@ -43,7 +44,7 @@ public class LoadBalancerClientSpecification implements NamedContextFactory.Spec } public String getName() { - return name; + return this.name; } public void setName(String name) { @@ -52,7 +53,7 @@ public class LoadBalancerClientSpecification implements NamedContextFactory.Spec } public Class[] getConfiguration() { - return configuration; + return this.configuration; } public void setConfiguration(Class[] configuration) { @@ -63,22 +64,27 @@ public class LoadBalancerClientSpecification implements NamedContextFactory.Spec @Override public String toString() { ToStringCreator to = new ToStringCreator(this); - to.append("name", name); - to.append("configuration", configuration); + to.append("name", this.name); + to.append("configuration", this.configuration); return to.toString(); } @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } LoadBalancerClientSpecification that = (LoadBalancerClientSpecification) o; - return Objects.equals(name, that.name) && - Arrays.equals(configuration, that.configuration); + return Objects.equals(this.name, that.name) + && Arrays.equals(this.configuration, that.configuration); } @Override public int hashCode() { - return Objects.hash(name, configuration); + return Objects.hash(this.name, this.configuration); } + } diff --git a/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/annotation/LoadBalancerClients.java b/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/annotation/LoadBalancerClients.java index f7f94254..dfd42fa3 100644 --- a/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/annotation/LoadBalancerClients.java +++ b/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/annotation/LoadBalancerClients.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-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. @@ -27,8 +27,8 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; /** - * Convenience annotation that allows user to combine multiple @LoadBalancerClient - * annotations on a single class (including in Java 7). + * Convenience annotation that allows user to combine multiple + * @LoadBalancerClient annotations on a single class (including in Java 7). * * @author Dave Syer */ @@ -42,10 +42,12 @@ public @interface LoadBalancerClients { LoadBalancerClient[] value() default {}; /** - * {@link LoadBalancerClientConfigurationRegistrar} creates a {@link LoadBalancerClientSpecification} - * with this as an argument. These in turn are added as default contexts in {@link LoadBalancerClientFactory}. - * Configuration defined in these classes are used as defaults if values aren't defined via + * {@link LoadBalancerClientConfigurationRegistrar} creates a + * {@link LoadBalancerClientSpecification} with this as an argument. These in turn are + * added as default contexts in {@link LoadBalancerClientFactory}. Configuration + * defined in these classes are used as defaults if values aren't defined via * {@link LoadBalancerClient#configuration()} + * @return classes for default configurations */ Class[] defaultConfiguration() default {}; diff --git a/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/config/LoadBalancerAutoConfiguration.java b/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/config/LoadBalancerAutoConfiguration.java index f078adf3..93d5c438 100644 --- a/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/config/LoadBalancerAutoConfiguration.java +++ b/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/config/LoadBalancerAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-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. @@ -34,16 +34,20 @@ import org.springframework.context.annotation.Configuration; // @EnableCaching //TODO: how to enforce, or check conditions? // @AutoConfigureBefore(CacheAutoConfiguration.class) public class LoadBalancerAutoConfiguration { + private final ObjectProvider> configurations; - public LoadBalancerAutoConfiguration(ObjectProvider> configurations) { + public LoadBalancerAutoConfiguration( + ObjectProvider> configurations) { this.configurations = configurations; } @Bean public LoadBalancerClientFactory loadBalancerClientFactory() { LoadBalancerClientFactory clientFactory = new LoadBalancerClientFactory(); - clientFactory.setConfigurations(configurations.getIfAvailable(Collections::emptyList)); + clientFactory.setConfigurations( + this.configurations.getIfAvailable(Collections::emptyList)); return clientFactory; } + } diff --git a/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/core/CachingServiceInstanceSupplier.java b/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/core/CachingServiceInstanceSupplier.java index 8f8ad69c..f8e53f64 100644 --- a/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/core/CachingServiceInstanceSupplier.java +++ b/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/core/CachingServiceInstanceSupplier.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-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. @@ -31,34 +31,37 @@ import org.springframework.cloud.client.ServiceInstance; */ public class CachingServiceInstanceSupplier implements ServiceInstanceSupplier { - public static final String SERVICE_INSTANCE_CACHE_NAME = CachingServiceInstanceSupplier.class.getSimpleName()+"Cache"; + /** + * Name of the service cache instance. + */ + public static final String SERVICE_INSTANCE_CACHE_NAME = CachingServiceInstanceSupplier.class + .getSimpleName() + "Cache"; private final ServiceInstanceSupplier delegate; + private final Flux serviceInstances; @SuppressWarnings("unchecked") - public CachingServiceInstanceSupplier(ServiceInstanceSupplier delegate, CacheManager cacheManager) { + public CachingServiceInstanceSupplier(ServiceInstanceSupplier delegate, + CacheManager cacheManager) { this.delegate = delegate; this.serviceInstances = CacheFlux.lookup(key -> { - Cache cache = cacheManager.getCache(SERVICE_INSTANCE_CACHE_NAME); //TODO: configurable cache name + Cache cache = cacheManager.getCache(SERVICE_INSTANCE_CACHE_NAME); // TODO: + // configurable + // cache + // name List list = cache.get(key, List.class); if (list == null || list.isEmpty()) { return Mono.empty(); } - return Flux.fromIterable(list) - .materialize() - .collectList(); - }, delegate.getServiceId()) - .onCacheMissResume(this.delegate::get) - .andWriteWith((key, signals) -> Flux.fromIterable(signals) - .dematerialize() - .cast(ServiceInstance.class) - .collectList() - .doOnNext(instances -> { - Cache cache = cacheManager.getCache(SERVICE_INSTANCE_CACHE_NAME); + return Flux.fromIterable(list).materialize().collectList(); + }, delegate.getServiceId()).onCacheMissResume(this.delegate::get) + .andWriteWith((key, signals) -> Flux.fromIterable(signals).dematerialize() + .cast(ServiceInstance.class).collectList().doOnNext(instances -> { + Cache cache = cacheManager + .getCache(SERVICE_INSTANCE_CACHE_NAME); cache.put(key, instances); - }) - .then()); + }).then()); } @Override @@ -70,4 +73,5 @@ public class CachingServiceInstanceSupplier implements ServiceInstanceSupplier { public String getServiceId() { return this.delegate.getServiceId(); } + } diff --git a/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/core/DiscoveryClientServiceInstanceSupplier.java b/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/core/DiscoveryClientServiceInstanceSupplier.java index 7b75a5b9..95c38b54 100644 --- a/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/core/DiscoveryClientServiceInstanceSupplier.java +++ b/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/core/DiscoveryClientServiceInstanceSupplier.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-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. @@ -32,20 +32,23 @@ import static org.springframework.cloud.loadbalancer.support.LoadBalancerClientF public class DiscoveryClientServiceInstanceSupplier implements ServiceInstanceSupplier { private final DiscoveryClient delegate; + private final String serviceId; - public DiscoveryClientServiceInstanceSupplier(DiscoveryClient delegate, Environment environment) { + public DiscoveryClientServiceInstanceSupplier(DiscoveryClient delegate, + Environment environment) { this.delegate = delegate; - serviceId = environment.getProperty(PROPERTY_NAME); + this.serviceId = environment.getProperty(PROPERTY_NAME); } @Override public Flux get() { - List instances = delegate.getInstances(serviceId); + List instances = this.delegate.getInstances(this.serviceId); return Flux.fromIterable(instances); } public String getServiceId() { return this.serviceId; } + } diff --git a/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/core/ReactorLoadBalancer.java b/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/core/ReactorLoadBalancer.java index 3b3f0b6f..fb65a623 100644 --- a/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/core/ReactorLoadBalancer.java +++ b/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/core/ReactorLoadBalancer.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-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. @@ -22,15 +22,23 @@ import org.springframework.cloud.client.loadbalancer.reactive.ReactiveLoadBalanc import org.springframework.cloud.client.loadbalancer.reactive.Request; import org.springframework.cloud.client.loadbalancer.reactive.Response; +/** + * A Reactor based implementation of {@link ReactiveLoadBalancer}. + * + * @param - type of the response + * @author Spencer Gibb + */ public interface ReactorLoadBalancer extends ReactiveLoadBalancer { + /** - * Choose the next server based on the load balancing algorithm - * @param request - * @return + * Choose the next server based on the load balancing algorithm. + * @param request - an input request + * @return - mono of response */ Mono> choose(Request request); default Mono> choose() { return choose(REQUEST); } + } diff --git a/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/core/RoundRobinLoadBalancer.java b/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/core/RoundRobinLoadBalancer.java index bd17c40e..d2bb2c3d 100644 --- a/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/core/RoundRobinLoadBalancer.java +++ b/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/core/RoundRobinLoadBalancer.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-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. @@ -38,38 +38,43 @@ public class RoundRobinLoadBalancer implements ReactorLoadBalancer serviceInstanceSupplier; + private final String serviceId; - public RoundRobinLoadBalancer(String serviceId, ObjectProvider serviceInstanceSupplier) { + public RoundRobinLoadBalancer(String serviceId, + ObjectProvider serviceInstanceSupplier) { this(serviceId, serviceInstanceSupplier, new Random().nextInt(1000)); } - public RoundRobinLoadBalancer(String serviceId, ObjectProvider serviceInstanceSupplier, - int seedPosition) { + public RoundRobinLoadBalancer(String serviceId, + ObjectProvider serviceInstanceSupplier, + int seedPosition) { this.serviceId = serviceId; this.serviceInstanceSupplier = serviceInstanceSupplier; this.position = new AtomicInteger(seedPosition); } @Override - /** - * see original https://github.com/Netflix/ocelli/blob/master/ocelli-core/src/main/java/netflix/ocelli/loadbalancer/RoundRobinLoadBalancer.java - */ + // see original + // https://github.com/Netflix/ocelli/blob/master/ocelli-core/ + // src/main/java/netflix/ocelli/loadbalancer/RoundRobinLoadBalancer.java public Mono> choose(Request request) { // TODO: move supplier to Request? - ServiceInstanceSupplier supplier = serviceInstanceSupplier.getIfAvailable(); + ServiceInstanceSupplier supplier = this.serviceInstanceSupplier.getIfAvailable(); return supplier.get().collectList().map(instances -> { if (instances.isEmpty()) { log.warn("No servers available for service: " + this.serviceId); return new EmptyResponse(); } // TODO: enforce order? - int pos = Math.abs(position.incrementAndGet()); + int pos = Math.abs(this.position.incrementAndGet()); ServiceInstance instance = instances.get(pos % instances.size()); return new DefaultResponse(instance); }); } + } diff --git a/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/core/ServiceInstanceSupplier.java b/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/core/ServiceInstanceSupplier.java index 96ba3ede..58ad4535 100644 --- a/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/core/ServiceInstanceSupplier.java +++ b/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/core/ServiceInstanceSupplier.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-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. @@ -28,4 +28,5 @@ import org.springframework.cloud.client.ServiceInstance; public interface ServiceInstanceSupplier extends Supplier> { String getServiceId(); + } diff --git a/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/support/LoadBalancerClientFactory.java b/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/support/LoadBalancerClientFactory.java index a7623d08..846fc018 100644 --- a/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/support/LoadBalancerClientFactory.java +++ b/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/support/LoadBalancerClientFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-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. @@ -29,9 +29,17 @@ import org.springframework.core.env.Environment; * @author Spencer Gibb * @author Dave Syer */ -public class LoadBalancerClientFactory extends NamedContextFactory { +public class LoadBalancerClientFactory + extends NamedContextFactory { + /** + * Property source name for load balancer. + */ public static final String NAMESPACE = "loadbalancer"; + + /** + * Property for client name within the load balancer namespace. + */ public static final String PROPERTY_NAME = NAMESPACE + ".client.name"; public LoadBalancerClientFactory() { @@ -43,4 +51,3 @@ public class LoadBalancerClientFactory extends NamedContextFactory get() { @@ -37,7 +48,9 @@ public class ServiceInstanceSuppliers { }; } - public static ObjectProvider toProvider(String serviceId, ServiceInstance... instances) { + public static ObjectProvider toProvider(String serviceId, + ServiceInstance... instances) { return new SimpleObjectProvider<>(from(serviceId, instances)); } + } diff --git a/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/support/SimpleObjectProvider.java b/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/support/SimpleObjectProvider.java index 0b2d0366..7f6d2a40 100644 --- a/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/support/SimpleObjectProvider.java +++ b/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/support/SimpleObjectProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-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. @@ -19,6 +19,12 @@ package org.springframework.cloud.loadbalancer.support; import org.springframework.beans.BeansException; import org.springframework.beans.factory.ObjectProvider; +/** + * Wrapper for {@link ObjectProvider}. + * + * @param type of the object to fetch + * @author Spencer Gibb + */ public class SimpleObjectProvider implements ObjectProvider { private final T object; @@ -46,4 +52,5 @@ public class SimpleObjectProvider implements ObjectProvider { public T getObject() throws BeansException { return this.object; } + } diff --git a/spring-cloud-loadbalancer/src/test/java/org/springframework/cloud/loadbalancer/core/LoadBalancerTest.java b/spring-cloud-loadbalancer/src/test/java/org/springframework/cloud/loadbalancer/core/LoadBalancerTest.java index ac8e8a96..48cab162 100644 --- a/spring-cloud-loadbalancer/src/test/java/org/springframework/cloud/loadbalancer/core/LoadBalancerTest.java +++ b/spring-cloud-loadbalancer/src/test/java/org/springframework/cloud/loadbalancer/core/LoadBalancerTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-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. @@ -59,19 +59,21 @@ public class LoadBalancerTest { @Test public void roundRobbinLoadbalancerWorks() { ReactiveLoadBalancer reactiveLoadBalancer = this.clientFactory - .getInstance("myservice", ReactiveLoadBalancer.class, ServiceInstance.class); + .getInstance("myservice", ReactiveLoadBalancer.class, + ServiceInstance.class); assertThat(reactiveLoadBalancer).isInstanceOf(RoundRobinLoadBalancer.class); assertThat(reactiveLoadBalancer).isInstanceOf(ReactorLoadBalancer.class); ReactorLoadBalancer loadBalancer = (ReactorLoadBalancer) reactiveLoadBalancer; - //order dependent on seedPosition -1 of RoundRobinLoadBalancer + // order dependent on seedPosition -1 of RoundRobinLoadBalancer List hosts = Arrays.asList("a.host", "c.host", "b.host-secure", "a.host"); assertLoadBalancer(loadBalancer, hosts); } - private void assertLoadBalancer(ReactorLoadBalancer loadBalancer, List hosts) { + private void assertLoadBalancer(ReactorLoadBalancer loadBalancer, + List hosts) { for (String host : hosts) { Mono> source = loadBalancer.choose(); StepVerifier.create(source).consumeNextWith(response -> { @@ -80,13 +82,13 @@ public class LoadBalancerTest { ServiceInstance instance = response.getServer(); assertThat(instance).isNotNull(); - assertThat(instance.getHost()) - .as("instance host is incorrent %s", host) + assertThat(instance.getHost()).as("instance host is incorrent %s", host) .isEqualTo(host); if (host.contains("secure")) { assertThat(instance.isSecure()).isTrue(); - } else { + } + else { assertThat(instance.isSecure()).isFalse(); } @@ -97,8 +99,10 @@ public class LoadBalancerTest { @Test public void emptyHosts() { - ResolvableType type = ResolvableType.forClassWithGenerics(ReactorLoadBalancer.class, ServiceInstance.class); - ReactorLoadBalancer loadBalancer = this.clientFactory.getInstance("unknownservice", type); + ResolvableType type = ResolvableType + .forClassWithGenerics(ReactorLoadBalancer.class, ServiceInstance.class); + ReactorLoadBalancer loadBalancer = this.clientFactory + .getInstance("unknownservice", type); assertThat(loadBalancer).isInstanceOf(RoundRobinLoadBalancer.class); @@ -113,13 +117,15 @@ public class LoadBalancerTest { public void staticConfigurationWorks() { String serviceId = "test1"; RoundRobinLoadBalancer loadBalancer = new RoundRobinLoadBalancer(serviceId, - ServiceInstanceSuppliers.toProvider(serviceId, instance(serviceId, "1.host", false), + ServiceInstanceSuppliers.toProvider(serviceId, + instance(serviceId, "1.host", false), instance(serviceId, "2.host-secure", true)), -1); assertLoadBalancer(loadBalancer, Arrays.asList("1.host", "2.host-secure")); } - private DefaultServiceInstance instance(String serviceId, String host, boolean secure) { + private DefaultServiceInstance instance(String serviceId, String host, + boolean secure) { return new DefaultServiceInstance(serviceId, host, 80, secure); } @@ -127,18 +133,22 @@ public class LoadBalancerTest { @SpringBootConfiguration @LoadBalancerClients({ @LoadBalancerClient(name = "myservice", configuration = MyServiceConfig.class), - @LoadBalancerClient(name = "unknownservice", configuration = MyServiceConfig.class), - }) + @LoadBalancerClient(name = "unknownservice", configuration = MyServiceConfig.class), }) @EnableCaching - protected static class Config { } + protected static class Config { + + } protected static class MyServiceConfig { + @Bean - public RoundRobinLoadBalancer roundRobinContextLoadBalancer(LoadBalancerClientFactory clientFactory, Environment env) { + public RoundRobinLoadBalancer roundRobinContextLoadBalancer( + LoadBalancerClientFactory clientFactory, Environment env) { String serviceId = clientFactory.getName(env); - return new RoundRobinLoadBalancer(serviceId, - clientFactory.getLazyProvider(serviceId, ServiceInstanceSupplier.class), - -1); + return new RoundRobinLoadBalancer(serviceId, clientFactory + .getLazyProvider(serviceId, ServiceInstanceSupplier.class), -1); } + } + } diff --git a/spring-cloud-loadbalancer/src/test/resources/application.yml b/spring-cloud-loadbalancer/src/test/resources/application.yml index 41b22c67..683117e3 100644 --- a/spring-cloud-loadbalancer/src/test/resources/application.yml +++ b/spring-cloud-loadbalancer/src/test/resources/application.yml @@ -5,32 +5,23 @@ spring: simple: instances: myservice: - - - service-id: myservice - uri: http://a.host - - - service-id: myservice - uri: http://c.host - - - service-id: myservice - uri: https://b.host-secure + - service-id: myservice + uri: http://a.host + - service-id: myservice + uri: http://c.host + - service-id: myservice + uri: https://b.host-secure anotherservice: - - - service-id: myservice - uri: http://d.host - - - service-id: myservice - uri: http://f.host - - - service-id: myservice - uri: https://e.host + - service-id: myservice + uri: http://d.host + - service-id: myservice + uri: http://f.host + - service-id: myservice + uri: https://e.host thirdservice: - - - service-id: myservice - uri: http://g.host - - - service-id: myservice - uri: http://h.host - - - service-id: myservice - uri: https://i.host \ No newline at end of file + - service-id: myservice + uri: http://g.host + - service-id: myservice + uri: http://h.host + - service-id: myservice + uri: https://i.host diff --git a/spring-cloud-starter/pom.xml b/spring-cloud-starter/pom.xml index 390f6a2f..9a81ed5d 100644 --- a/spring-cloud-starter/pom.xml +++ b/spring-cloud-starter/pom.xml @@ -1,6 +1,7 @@ - + 4.0.0 org.springframework.cloud diff --git a/spring-cloud-test-support/eclipse/eclipse-code-formatter.xml b/spring-cloud-test-support/eclipse/eclipse-code-formatter.xml index 4694d7f2..5cbf769b 100644 --- a/spring-cloud-test-support/eclipse/eclipse-code-formatter.xml +++ b/spring-cloud-test-support/eclipse/eclipse-code-formatter.xml @@ -1,295 +1,754 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spring-cloud-test-support/pom.xml b/spring-cloud-test-support/pom.xml index 5dfa60a6..23d6fc4f 100644 --- a/spring-cloud-test-support/pom.xml +++ b/spring-cloud-test-support/pom.xml @@ -1,6 +1,7 @@ - + 4.0.0 diff --git a/spring-cloud-test-support/src/main/java/org/springframework/cloud/test/ClassPathExclusions.java b/spring-cloud-test-support/src/main/java/org/springframework/cloud/test/ClassPathExclusions.java index 4bef9dff..5c2b02b1 100644 --- a/spring-cloud-test-support/src/main/java/org/springframework/cloud/test/ClassPathExclusions.java +++ b/spring-cloud-test-support/src/main/java/org/springframework/cloud/test/ClassPathExclusions.java @@ -1,3 +1,19 @@ +/* + * Copyright 2012-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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.test; import java.lang.annotation.ElementType; @@ -6,8 +22,8 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** - * Taken from Spring Boot test utils. - * https://github.com/spring-projects/spring-boot/blob/1.4.x/spring-boot/src/test/java/org/springframework/boot/testutil/ClassPathExclusions.java + * Taken from Spring Boot test utils. https://github.com/spring-projects/spring-boot/blob/ + * 1.4.x/spring-boot/src/test/java/org/springframework/boot/testutil/ClassPathExclusions.java * @author Ryan Baxter */ @Retention(RetentionPolicy.RUNTIME) @@ -16,10 +32,11 @@ public @interface ClassPathExclusions { /** * One or more Ant-style patterns that identify entries to be excluded from the class - * path. Matching is performed against an entry's {@link java.io.File#getName() file name}. - * For example, to exclude Hibernate Validator from the classpath, + * path. Matching is performed against an entry's {@link java.io.File#getName() file + * name}. For example, to exclude Hibernate Validator from the classpath, * {@code "hibernate-validator-*.jar"} can be used. * @return the exclusion patterns */ String[] value(); + } diff --git a/spring-cloud-test-support/src/main/java/org/springframework/cloud/test/ClassPathOverrides.java b/spring-cloud-test-support/src/main/java/org/springframework/cloud/test/ClassPathOverrides.java index 81166d11..a2ec06f2 100644 --- a/spring-cloud-test-support/src/main/java/org/springframework/cloud/test/ClassPathOverrides.java +++ b/spring-cloud-test-support/src/main/java/org/springframework/cloud/test/ClassPathOverrides.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-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. diff --git a/spring-cloud-test-support/src/main/java/org/springframework/cloud/test/ModifiedClassPathRunner.java b/spring-cloud-test-support/src/main/java/org/springframework/cloud/test/ModifiedClassPathRunner.java index b284eefc..4e9b56a2 100644 --- a/spring-cloud-test-support/src/main/java/org/springframework/cloud/test/ModifiedClassPathRunner.java +++ b/spring-cloud-test-support/src/main/java/org/springframework/cloud/test/ModifiedClassPathRunner.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-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. @@ -364,7 +364,7 @@ public class ModifiedClassPathRunner extends BlockJUnit4ClassRunner { private final ClassLoader junitLoader; ModifiedClassPathClassLoader(URL[] urls, ClassLoader parent, - ClassLoader junitLoader) { + ClassLoader junitLoader) { super(urls, parent); this.junitLoader = junitLoader; } @@ -379,4 +379,4 @@ public class ModifiedClassPathRunner extends BlockJUnit4ClassRunner { } -} \ No newline at end of file +}