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=/**\n * @return the ${bare_field_name}\n *//**\n * @param ${param} the ${bare_field_name} to set\n *//**\n * ${tags}\n *//*\n * Copyright 2012-2018 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the "License");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http\://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an "AS IS" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *//**\n * @author ${user}\n *//**\n * \n *//**\n * ${tags}\n *//* (non-Javadoc)\n * ${see_to_overridden}\n *//**\n * ${tags}\n * ${see_to_target}\n */${filecomment}\n\n${package_declaration}\n${typecomment}\n${type_declaration}\n\n\n\n// ${todo} Auto-generated catch block\nthrow new UnsupportedOperationException("Auto-generated method stub", ${exception_var});// ${todo} Auto-generated method stub\nthrow new UnsupportedOperationException("Auto-generated method stub");${body_statement}\n// ${todo} Auto-generated constructor stubreturn ${field};${field} \= ${param};
+org.eclipse.jdt.ui.text.custom_code_templates=/**\n * @return the ${bare_field_name}\n *//**\n * @param ${param} the ${bare_field_name} to set\n *//**\n * ${tags}\n *//*\n * Copyright 2012-2019 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the "License");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http\://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an "AS IS" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *//**\n * @author ${user}\n *//**\n * \n *//**\n * ${tags}\n *//* (non-Javadoc)\n * ${see_to_overridden}\n *//**\n * ${tags}\n * ${see_to_target}\n */${filecomment}\n\n${package_declaration}\n${typecomment}\n${type_declaration}\n\n\n\n// ${todo} Auto-generated catch block\nthrow new UnsupportedOperationException("Auto-generated method stub", ${exception_var});// ${todo} Auto-generated method stub\nthrow new UnsupportedOperationException("Auto-generated method stub");${body_statement}\n// ${todo} Auto-generated constructor stubreturn ${field};${field} \= ${param};
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