Compare commits

...
54 Commits
Author SHA1 Message Date
buildmaster ef9ded650f Update SNAPSHOT to 3.0.0-M5 2020-11-17 20:41:05 +00:00
buildmaster 3c25b010c3 Bumping versions 2020-11-17 11:37:02 +00:00
Olga Maciaszek-Sharma f9a8dd13f2 Adjust to changes in security config. 2020-11-03 11:49:21 +01:00
Olga Maciaszek-Sharma f6fdd63cef Merge remote-tracking branch 'origin/master' 2020-11-03 11:47:36 +01:00
Olga Maciaszek-Sharma 410d0f29a3 Merge remote-tracking branch 'origin/2.2.x'
# Conflicts:
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientsRegistrar.java
#	spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/FeignClientsRegistrarTests.java
2020-11-03 11:47:30 +01:00
Olga Maciaszek-Sharma 82de713d06 Remove unnecessary test configuration. 2020-11-03 11:46:15 +01:00
Michal Domagalaandmichal a8a2a0155f Fix for @EnableFeignClients(clients) scans classes in nested packages (#422)
* Test to verify sub level client error

Error is described in https://github.com/spring-cloud/spring-cloud-openfeign/issues/331

Application fails when one Feign client is `org.TopClient` and second is in subpackage:  `org.sub.SubClient`

The error reason is that `SubClient` is registered twice

* Fix for @EnableFeignClients(clients) scans classes in nested packages twice

https://github.com/spring-cloud/spring-cloud-openfeign/issues/331
(cherry picked from commit fe62b0db90)

# Conflicts:
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientsRegistrar.java

* delete unused code

(cherry picked from commit 4df865d1d6)

* add file header

* Apply review

Co-authored-by: michal <michal@michal-desktop>
2020-11-03 10:31:23 +01:00
Olga Maciaszek-Sharma 5e455ed14b Adjust to changes in master. 2020-11-02 14:33:58 +01:00
Olga Maciaszek-Sharma a3584a9cc8 Merge remote-tracking branch 'origin/2.2.x' 2020-11-02 14:30:54 +01:00
Nikolas Charalambidis cf4fa54ac8 Fixes gh-391 timeout handling documentation (#421)
* Fixes gh-391

* Fixes gh-391 sentence reworded

* Fixes gh-391 fixed spelling

* Fixes gh-391 fixed code format

* Fixes gh-391 fixed sentence

* Fixes gh-391 fixed code

* Fixes gh-391 word deletion
2020-11-02 14:10:58 +01:00
Olga Maciaszek-Sharma ffb17a4552 Merge remote-tracking branch 'origin/2.2.x'
# Conflicts:
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/FeignClientProperties.java
2020-10-29 16:54:47 +01:00
Ilia Ilinykh 93327fcace Ability to configure client to send default headers #284 at 2.2.x (#420)
* Implemented ability to provide default query parameters and headers to feign clients.
Issue was mentioned in №284

* Removed wrong names of test data. Replaced with correct ones.

* Thread sleep was repalced with more verbose TimeUnit sleep

* Fixed more names of the clients.
2020-10-29 15:58:38 +01:00
Olga Maciaszek-Sharma 20e2548a5d Automatic reformat. 2020-10-28 18:39:20 +01:00
Olga Maciaszek-Sharma d93defe1c1 Merge remote-tracking branch 'origin/2.2.x' 2020-10-28 18:37:15 +01:00
Olga Maciaszek-Sharma bc6c3b7bf2 Sort request interceptors. (#419) 2020-10-28 18:36:46 +01:00
Olga Maciaszek-Sharma db8d10a511 Merge remote-tracking branch 'origin/2.2.x'
# Conflicts:
#	pom.xml
2020-10-28 17:53:01 +01:00
Olga Maciaszek-Sharma f410385237 Upgrade jackson to 2.11.3. 2020-10-28 17:46:44 +01:00
Olga Maciaszek-Sharma 6649c86be1 Support loadbalancer lifecycle (#418)
* Add LoadBalancerLifecycle support.

* Add info on SC LoadBalancer documentation.
2020-10-27 11:12:34 -05:00
Olga Maciaszek-Sharma 3f0c2850ee Extract duplicate method to utility class. 2020-10-27 17:02:04 +01:00
Olga Maciaszek-Sharma 479e1ab743 Add info on SC LoadBalancer documentation. 2020-10-23 16:12:39 +02:00
Olga Maciaszek-Sharma 77a1367796 Add LoadBalancerLifecycle support. 2020-10-23 16:04:03 +02:00
buildmaster 89f8942dff Going back to snapshots 2020-10-03 13:57:43 +00:00
buildmaster d31ce6d428 Update SNAPSHOT to 3.0.0-M4 2020-10-03 13:56:37 +00:00
Olga Maciaszek-Sharma 3c3b9a5a14 Add support for passing hints to LoadBalancer. (#412) 2020-10-02 17:15:20 +02:00
Olga Maciaszek-Sharma 582e4c0175 Merge remote-tracking branch 'origin/2.2.x'
# Conflicts:
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/loadbalancer/DefaultFeignLoadBalancerConfiguration.java
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/loadbalancer/HttpClientFeignLoadBalancerConfiguration.java
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/loadbalancer/OkHttpFeignLoadBalancerConfiguration.java
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/loadbalancer/RetryableFeignBlockingLoadBalancerClient.java
#	spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/loadbalancer/FeignLoadBalancerAutoConfigurationTests.java
2020-10-02 15:32:53 +02:00
Olga Maciaszek-Sharma a5ab3383c9 Rename new class. 2020-10-02 15:25:18 +02:00
Olga Maciaszek-Sharma db3513b97b Merge remote-tracking branch 'origin/2.2.x'
Fixes gh-286.

# Conflicts:
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/loadbalancer/DefaultFeignLoadBalancerConfiguration.java
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/loadbalancer/HttpClientFeignLoadBalancerConfiguration.java
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/loadbalancer/OkHttpFeignLoadBalancerConfiguration.java
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/ribbon/FeignLoadBalancer.java
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/ribbon/RetryableFeignLoadBalancer.java
#	spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/loadbalancer/FeignLoadBalancerAutoConfigurationTests.java
2020-10-02 15:15:43 +02:00
Olga Maciaszek-Sharma dd518a812b Add support for load-balanced retries. (#408) 2020-10-01 20:20:24 +02:00
Olga Maciaszek-Sharma 1178739437 Merge remote-tracking branch 'origin/2.2.x' 2020-09-17 14:51:13 +02:00
Olga Maciaszek-Sharma c3dcb1f376 Remove maven compiler plugin version to use the one provided by Boot instead. 2020-09-17 14:49:03 +02:00
Olga Maciaszek-Sharma 27e2775c5f Upgrade protobuf-java. 2020-09-17 14:30:54 +02:00
Olga Maciaszek-Sharma 83ef242406 Upgrade vavr. 2020-09-17 14:20:29 +02:00
Olga Maciaszek-Sharma 2d9f51a17f Merge 2.2.x. 2020-09-17 14:09:15 +02:00
Olga Maciaszek-Sharma faff6aef8a Reformat with updated JavaFormat plugin version. 2020-09-17 13:54:45 +02:00
Olga Maciaszek-Sharma 6534950ed2 Upgrade jakson. 2020-09-17 12:57:47 +02:00
Olga Maciaszek-Sharma 80710a9f20 Merge remote-tracking branch 'origin/2.2.x'
# Conflicts:
#	docs/pom.xml
#	pom.xml
#	spring-cloud-openfeign-core/pom.xml
#	spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/FeignClientOverrideDefaultsTests.java
#	spring-cloud-openfeign-dependencies/pom.xml
#	spring-cloud-starter-openfeign/pom.xml
2020-09-16 13:01:34 +02:00
Olga Maciaszek-Sharma e83593651c Clean up test. 2020-09-16 12:50:57 +02:00
Olga Maciaszek-Sharma 4cbf6da17b Adjust test to changes in commons. 2020-09-16 12:38:22 +02:00
liuzeyanga 5fea4f3b35 change "Sprig Cloud" to  "Spring Cloud" 2020-09-16 11:53:59 +02:00
buildmaster 36c06c97a6 Bumping versions to 2.2.6.BUILD-SNAPSHOT after release 2020-08-28 20:04:40 +00:00
buildmaster d6b021eaa4 Going back to snapshots 2020-08-28 20:04:40 +00:00
buildmaster c2430c0e29 Update SNAPSHOT to 2.2.5.RELEASE 2020-08-28 20:02:41 +00:00
Olga Maciaszek-Sharma d41f041efc Merge remote-tracking branch 'origin/2.2.x'
# Conflicts:
#	pom.xml
2020-08-13 14:41:12 +02:00
Olga Maciaszek-Sharma b66e08fda8 Fix the docs. 2020-08-13 14:37:55 +02:00
spencergibb 84819e1328 Bumps s-c-build to 2.3.2.BUILD-SNAPSHOT 2020-08-03 13:21:35 -04:00
spencergibb b6422db8e9 ignores .sdkmanrc 2020-08-03 13:21:17 -04:00
Olga Maciaszek-Sharma 2f13eb4816 Merge remote-tracking branch 'origin/2.2.x'
# Conflicts:
#	docs/pom.xml
#	pom.xml
#	spring-cloud-openfeign-core/pom.xml
#	spring-cloud-openfeign-dependencies/pom.xml
#	spring-cloud-starter-openfeign/pom.xml
2020-08-03 10:05:52 +02:00
Olga Maciaszek-Sharma 4bf010e810 Ignore InvalidMediaTypeException when verifying if Multipart content. Fixes gh-363. (#388) 2020-08-03 10:02:05 +02:00
buildmaster bd671efed9 Bumping versions to 2.2.5.BUILD-SNAPSHOT after release 2020-07-31 20:53:35 +00:00
buildmaster bfd473cb8f Going back to snapshots 2020-07-31 20:53:35 +00:00
buildmaster 2f5d63a061 Update SNAPSHOT to 2.2.4.RELEASE 2020-07-31 20:51:47 +00:00
Olga Maciaszek-Sharma 62aa76fb97 Merge remote-tracking branch 'origin/2.2.x' 2020-07-30 16:24:25 +02:00
Olga Maciaszek-Sharma 14929cbfee Revert "Fix double @RequestMapping with empty value (#245)"
This reverts commit 0afb60a72a.

# Conflicts:
#	spring-cloud-openfeign-core/src/main/java/org/springframework/cloud/openfeign/support/SpringMvcContract.java
#	spring-cloud-openfeign-core/src/test/java/org/springframework/cloud/openfeign/support/SpringMvcContractTests.java
2020-07-30 16:18:25 +02:00
buildmaster 5ce900828f Going back to snapshots 2020-07-23 18:26:47 +00:00
110 changed files with 2285 additions and 2018 deletions
+1
View File
@@ -20,4 +20,5 @@ _site/
*.swo
.vscode/
.flattened-pom.xml
.sdkmanrc
+1 -1
View File
@@ -6,7 +6,7 @@
<parent>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-openfeign</artifactId>
<version>3.0.0-M3</version>
<version>3.0.0-M5</version>
</parent>
<artifactId>spring-cloud-openfeign-docs</artifactId>
<packaging>jar</packaging>
+19 -19
View File
@@ -1,24 +1,24 @@
|===
|Name | Default | Description
|feign.client.config | |
|feign.client.default-config | default |
|feign.client.default-to-properties | true |
|feign.compression.request.enabled | false | Enables the request sent by Feign to be compressed.
|feign.compression.request.mime-types | [text/xml, application/xml, application/json] | The list of supported mime types.
|feign.compression.request.min-request-size | 2048 | The minimum threshold content size.
|feign.compression.response.enabled | false | Enables the response from Feign to be compressed.
|feign.compression.response.useGzipDecoder | false | Enables the default gzip decoder to be used.
|feign.httpclient.connection-timeout | 2000 |
|feign.httpclient.connection-timer-repeat | 3000 |
|feign.httpclient.disable-ssl-validation | false |
|feign.httpclient.enabled | true | Enables the use of the Apache HTTP Client by Feign.
|feign.httpclient.follow-redirects | true |
|feign.httpclient.max-connections | 200 |
|feign.httpclient.max-connections-per-route | 50 |
|feign.httpclient.time-to-live | 900 |
|feign.httpclient.time-to-live-unit | |
|feign.hystrix.enabled | false | If true, an OpenFeign client will be wrapped with a Hystrix circuit breaker.
|feign.okhttp.enabled | false | Enables the use of the OK HTTP Client by Feign.
|feign.client.config | `` |
|feign.client.default-config | `default` |
|feign.client.default-to-properties | `true` |
|feign.compression.request.enabled | `false` | Enables the request sent by Feign to be compressed.
|feign.compression.request.mime-types | `[text/xml, application/xml, application/json]` | The list of supported mime types.
|feign.compression.request.min-request-size | `2048` | The minimum threshold content size.
|feign.compression.response.enabled | `false` | Enables the response from Feign to be compressed.
|feign.compression.response.useGzipDecoder | `false` | Enables the default gzip decoder to be used.
|feign.httpclient.connection-timeout | `2000` |
|feign.httpclient.connection-timer-repeat | `3000` |
|feign.httpclient.disable-ssl-validation | `false` |
|feign.httpclient.enabled | `true` | Enables the use of the Apache HTTP Client by Feign.
|feign.httpclient.follow-redirects | `true` |
|feign.httpclient.max-connections | `200` |
|feign.httpclient.max-connections-per-route | `50` |
|feign.httpclient.time-to-live | `900` |
|feign.httpclient.time-to-live-unit | `` |
|feign.hystrix.enabled | `false` | If true, an OpenFeign client will be wrapped with a Hystrix circuit breaker.
|feign.okhttp.enabled | `false` | Enables the use of the OK HTTP Client by Feign.
|===
@@ -68,6 +68,8 @@ it will resolve the service in the Eureka service registry. If you
don't want to use Eureka, you can simply configure a list of servers
in your external configuration using https://cloud.spring.io/spring-cloud-static/spring-cloud-commons/current/reference/html/#simplediscoveryclient[`SimpleDiscoveryClient`].
Spring Cloud OpenFeign supports all the features available for the blocking mode of Spring Cloud LoadBalancer. You can read more about them in the https://docs.spring.io/spring-cloud-commons/docs/current/reference/html/#spring-cloud-loadbalancer[project documentation].
[[spring-cloud-feign-overriding-defaults]]
=== Overriding Feign Defaults
@@ -171,6 +173,10 @@ feign:
loggerLevel: full
errorDecoder: com.example.SimpleErrorDecoder
retryer: com.example.SimpleRetryer
defaultQueryParameters:
query: queryValue
defaultRequestHeaders:
header: headerValue
requestInterceptors:
- com.example.FooRequestInterceptor
- com.example.BarRequestInterceptor
@@ -184,6 +190,8 @@ Default configurations can be specified in the `@EnableFeignClients` attribute `
If you prefer using configuration properties to configured all `@FeignClient`, you can create configuration properties with `default` feign name.
You can use `feign.client.config.feignName.defaultQueryParameters` and `feign.client.config.feignName.defaultRequestHeaders` to specify query parameters and headers that will be sent with every request of the client named `feignName`.
application.yml
[source,yaml]
----
@@ -264,6 +272,16 @@ public FeignClientConfigurer feignClientConfigurer() {
}
----
[[timeout-handling]]
=== Timeout Handling
We can configure timeouts on both the default and the named client. OpenFeign works with two timeout parameters:
- `connectTimeout` prevents blocking the caller due to the long server processing time.
- `readTimeout` is applied from the time of connection establishment and is triggered when returning the response takes too long.
NOTE: In case the server is not running or available a packet results in _connection refused_. The communication ends either with an error message or in a fallback. This can happen _before_ the `connectTimeout` if it is set very low. The time taken to perform a lookup and to receive such a packet causes a significant part of this delay. It is subject to change based on the remote host that involves a DNS lookup.
=== Creating Feign Clients Manually
In some cases it might be necessary to customize your Feign Clients in a way that is not
@@ -301,7 +319,7 @@ class FooController {
----
NOTE: In the above example `FeignClientsConfiguration.class` is the default configuration
provided by Spring Cloud Netflix.
provided by Spring Cloud OpenFeign.
NOTE: `PROD-SVC` is the name of the service the Clients will be making requests to.
@@ -384,7 +402,7 @@ WARNING: There is a limitation with the implementation of fallbacks in Feign and
=== Feign and `@Primary`
When using Feign with Hystrix fallbacks, there are multiple beans in the `ApplicationContext` of the same type. This will cause `@Autowired` to not work because there isn't exactly one bean, or one marked as primary. To work around this, Spring Cloud Netflix marks all Feign instances as `@Primary`, so Spring Framework will know which bean to inject. In some cases, this may not be desirable. To turn off this behavior set the `primary` attribute of `@FeignClient` to false.
When using Feign with Hystrix fallbacks, there are multiple beans in the `ApplicationContext` of the same type. This will cause `@Autowired` to not work because there isn't exactly one bean, or one marked as primary. To work around this, Spring Cloud OpenFeign marks all Feign instances as `@Primary`, so Spring Framework will know which bean to inject. In some cases, this may not be desirable. To turn off this behavior set the `primary` attribute of `@FeignClient` to false.
[source,java,indent=0]
----
@@ -561,7 +579,7 @@ If a map is passed as the method argument, the `@MatrixVariable` path segment is
If a different object is passed, either the `name` provided in the `@MatrixVariable` annotation (if defined) or the annotated variable name is
joined with the provided method argument using `=`.
IMPORTANT:: Even though, on the server side, Spring does not require the users to name the path segment placeholder same as the matrix variable name, since it would be too ambiguous on the client side, Sprig Cloud OpenFeign requires that you add a path segment placeholder with a name matching either the `name` provided in the `@MatrixVariable` annotation (if defined) or the annotated variable name.
IMPORTANT:: Even though, on the server side, Spring does not require the users to name the path segment placeholder same as the matrix variable name, since it would be too ambiguous on the client side, Spring Cloud OpenFeign requires that you add a path segment placeholder with a name matching either the `name` provided in the `@MatrixVariable` annotation (if defined) or the annotated variable name.
For example:
+4 -6
View File
@@ -4,14 +4,14 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-cloud-openfeign</artifactId>
<version>3.0.0-M3</version>
<version>3.0.0-M5</version>
<packaging>pom</packaging>
<name>Spring Cloud OpenFeign</name>
<description>Spring Cloud OpenFeign</description>
<parent>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-build</artifactId>
<version>3.0.0-M3</version>
<version>3.0.0-M5</version>
<relativePath/>
</parent>
<scm>
@@ -25,11 +25,10 @@
</scm>
<properties>
<main.basedir>${basedir}</main.basedir>
<jackson.version>2.7.3</jackson.version>
<spring-cloud-commons.version>3.0.0-M3</spring-cloud-commons.version>
<jackson.version>2.11.3</jackson.version>
<spring-cloud-commons.version>3.0.0-M5</spring-cloud-commons.version>
<!-- Plugin versions -->
<maven-compiler-plugin.version>3.6.1</maven-compiler-plugin.version>
<maven-eclipse-plugin.version>2.10</maven-eclipse-plugin.version>
<!-- Sonar -->
<surefire.plugin.version>2.19.1</surefire.plugin.version>
@@ -67,7 +66,6 @@
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
+3 -9
View File
@@ -6,7 +6,7 @@
<parent>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-openfeign</artifactId>
<version>3.0.0-M3</version>
<version>3.0.0-M5</version>
<relativePath>..</relativePath> <!-- lookup parent from repository -->
</parent>
<artifactId>spring-cloud-openfeign-core</artifactId>
@@ -168,13 +168,13 @@
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
<version>3.4.0</version>
<version>3.13.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.vavr</groupId>
<artifactId>vavr</artifactId>
<version>0.10.0</version>
<version>0.10.3</version>
<scope>test</scope>
</dependency>
<dependency>
@@ -182,12 +182,6 @@
<artifactId>spring-cloud-loadbalancer</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>pl.pragmatists</groupId>
<artifactId>JUnitParams</artifactId>
<version>1.1.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<profiles>
<profile>
@@ -43,8 +43,7 @@ public interface AnnotatedParameterProcessor {
* @param method the method that contains the annotation
* @return whether the parameter is http
*/
boolean processArgument(AnnotatedParameterContext context, Annotation annotation,
Method method);
boolean processArgument(AnnotatedParameterContext context, Annotation annotation, Method method);
/**
* Specifies the parameter context.
@@ -25,8 +25,8 @@ import feign.Target;
class DefaultTargeter implements Targeter {
@Override
public <T> T target(FeignClientFactoryBean factory, Feign.Builder feign,
FeignContext context, Target.HardCodedTarget<T> target) {
public <T> T target(FeignClientFactoryBean factory, Feign.Builder feign, FeignContext context,
Target.HardCodedTarget<T> target) {
return feign.target(target);
}
@@ -57,8 +57,7 @@ import org.springframework.context.annotation.Import;
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(Feign.class)
@EnableConfigurationProperties({ FeignClientProperties.class,
FeignHttpClientProperties.class })
@EnableConfigurationProperties({ FeignClientProperties.class, FeignHttpClientProperties.class })
@Import(DefaultGzipDecoderConfiguration.class)
public class FeignAutoConfiguration {
@@ -111,13 +110,10 @@ public class FeignAutoConfiguration {
public HttpClientConnectionManager connectionManager(
ApacheHttpClientConnectionManagerFactory connectionManagerFactory,
FeignHttpClientProperties httpClientProperties) {
final HttpClientConnectionManager connectionManager = connectionManagerFactory
.newConnectionManager(httpClientProperties.isDisableSslValidation(),
httpClientProperties.getMaxConnections(),
httpClientProperties.getMaxConnectionsPerRoute(),
httpClientProperties.getTimeToLive(),
httpClientProperties.getTimeToLiveUnit(),
this.registryBuilder);
final HttpClientConnectionManager connectionManager = connectionManagerFactory.newConnectionManager(
httpClientProperties.isDisableSslValidation(), httpClientProperties.getMaxConnections(),
httpClientProperties.getMaxConnectionsPerRoute(), httpClientProperties.getTimeToLive(),
httpClientProperties.getTimeToLiveUnit(), this.registryBuilder);
this.connectionManagerTimer.schedule(new TimerTask() {
@Override
public void run() {
@@ -133,10 +129,8 @@ public class FeignAutoConfiguration {
FeignHttpClientProperties httpClientProperties) {
RequestConfig defaultRequestConfig = RequestConfig.custom()
.setConnectTimeout(httpClientProperties.getConnectionTimeout())
.setRedirectsEnabled(httpClientProperties.isFollowRedirects())
.build();
this.httpClient = httpClientFactory.createBuilder()
.setConnectionManager(httpClientConnectionManager)
.setRedirectsEnabled(httpClientProperties.isFollowRedirects()).build();
this.httpClient = httpClientFactory.createBuilder().setConnectionManager(httpClientConnectionManager)
.setDefaultRequestConfig(defaultRequestConfig).build();
return this.httpClient;
}
@@ -167,8 +161,7 @@ public class FeignAutoConfiguration {
@Bean
@ConditionalOnMissingBean(ConnectionPool.class)
public ConnectionPool httpClientConnectionPool(
FeignHttpClientProperties httpClientProperties,
public ConnectionPool httpClientConnectionPool(FeignHttpClientProperties httpClientProperties,
OkHttpClientConnectionPoolFactory connectionPoolFactory) {
Integer maxTotalConnections = httpClientProperties.getMaxConnections();
Long timeToLive = httpClientProperties.getTimeToLive();
@@ -177,16 +170,14 @@ public class FeignAutoConfiguration {
}
@Bean
public okhttp3.OkHttpClient client(OkHttpClientFactory httpClientFactory,
ConnectionPool connectionPool,
public okhttp3.OkHttpClient client(OkHttpClientFactory httpClientFactory, ConnectionPool connectionPool,
FeignHttpClientProperties httpClientProperties) {
Boolean followRedirects = httpClientProperties.isFollowRedirects();
Integer connectTimeout = httpClientProperties.getConnectionTimeout();
Boolean disableSslValidation = httpClientProperties.isDisableSslValidation();
this.okHttpClient = httpClientFactory.createBuilder(disableSslValidation)
.connectTimeout(connectTimeout, TimeUnit.MILLISECONDS)
.followRedirects(followRedirects).connectionPool(connectionPool)
.build();
.connectTimeout(connectTimeout, TimeUnit.MILLISECONDS).followRedirects(followRedirects)
.connectionPool(connectionPool).build();
return this.okHttpClient;
}
@@ -39,8 +39,8 @@ public class FeignClientBuilder {
return new Builder<>(this.applicationContext, type, name);
}
public <T> Builder<T> forType(final Class<T> type,
final FeignClientFactoryBean clientFactoryBean, final String name) {
public <T> Builder<T> forType(final Class<T> type, final FeignClientFactoryBean clientFactoryBean,
final String name) {
return new Builder<>(this.applicationContext, clientFactoryBean, type, name);
}
@@ -53,14 +53,12 @@ public class FeignClientBuilder {
private FeignClientFactoryBean feignClientFactoryBean;
private Builder(final ApplicationContext applicationContext, final Class<T> type,
final String name) {
private Builder(final ApplicationContext applicationContext, final Class<T> type, final String name) {
this(applicationContext, new FeignClientFactoryBean(), type, name);
}
private Builder(final ApplicationContext applicationContext,
final FeignClientFactoryBean clientFactoryBean, final Class<T> type,
final String name) {
private Builder(final ApplicationContext applicationContext, final FeignClientFactoryBean clientFactoryBean,
final Class<T> type, final String name) {
this.feignClientFactoryBean = clientFactoryBean;
this.feignClientFactoryBean.setApplicationContext(applicationContext);
@@ -16,6 +16,8 @@
package org.springframework.cloud.openfeign;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
@@ -54,9 +56,9 @@ import org.springframework.util.StringUtils;
* @author Gregor Zurowski
* @author Matt King
* @author Olga Maciaszek-Sharma
* @author Ilia Ilinykh
*/
public class FeignClientFactoryBean
implements FactoryBean<Object>, InitializingBean, ApplicationContextAware {
public class FeignClientFactoryBean implements FactoryBean<Object>, InitializingBean, ApplicationContextAware {
/***********************************
* WARNING! Nothing in this class should be @Autowired. It causes NPEs because of some
@@ -113,37 +115,29 @@ public class FeignClientFactoryBean
}
private void applyBuildCustomizers(FeignContext context, Feign.Builder builder) {
Map<String, FeignBuilderCustomizer> customizerMap = context
.getInstances(contextId, FeignBuilderCustomizer.class);
Map<String, FeignBuilderCustomizer> customizerMap = context.getInstances(contextId,
FeignBuilderCustomizer.class);
if (customizerMap != null) {
customizerMap.values().stream()
.sorted(AnnotationAwareOrderComparator.INSTANCE)
.forEach(feignBuilderCustomizer -> feignBuilderCustomizer
.customize(builder));
customizerMap.values().stream().sorted(AnnotationAwareOrderComparator.INSTANCE)
.forEach(feignBuilderCustomizer -> feignBuilderCustomizer.customize(builder));
}
}
protected void configureFeign(FeignContext context, Feign.Builder builder) {
FeignClientProperties properties = applicationContext
.getBean(FeignClientProperties.class);
FeignClientProperties properties = applicationContext.getBean(FeignClientProperties.class);
FeignClientConfigurer feignClientConfigurer = getOptional(context,
FeignClientConfigurer.class);
FeignClientConfigurer feignClientConfigurer = getOptional(context, FeignClientConfigurer.class);
setInheritParentContext(feignClientConfigurer.inheritParentConfiguration());
if (properties != null && inheritParentContext) {
if (properties.isDefaultToProperties()) {
configureUsingConfiguration(context, builder);
configureUsingProperties(
properties.getConfig().get(properties.getDefaultConfig()),
builder);
configureUsingProperties(properties.getConfig().get(properties.getDefaultConfig()), builder);
configureUsingProperties(properties.getConfig().get(contextId), builder);
}
else {
configureUsingProperties(
properties.getConfig().get(properties.getDefaultConfig()),
builder);
configureUsingProperties(properties.getConfig().get(properties.getDefaultConfig()), builder);
configureUsingProperties(properties.getConfig().get(contextId), builder);
configureUsingConfiguration(context, builder);
}
@@ -153,8 +147,7 @@ public class FeignClientFactoryBean
}
}
protected void configureUsingConfiguration(FeignContext context,
Feign.Builder builder) {
protected void configureUsingConfiguration(FeignContext context, Feign.Builder builder) {
Logger.Level level = getInheritedAwareOptional(context, Logger.Level.class);
if (level != null) {
builder.logLevel(level);
@@ -163,48 +156,45 @@ public class FeignClientFactoryBean
if (retryer != null) {
builder.retryer(retryer);
}
ErrorDecoder errorDecoder = getInheritedAwareOptional(context,
ErrorDecoder.class);
ErrorDecoder errorDecoder = getInheritedAwareOptional(context, ErrorDecoder.class);
if (errorDecoder != null) {
builder.errorDecoder(errorDecoder);
}
else {
FeignErrorDecoderFactory errorDecoderFactory = getOptional(context,
FeignErrorDecoderFactory.class);
FeignErrorDecoderFactory errorDecoderFactory = getOptional(context, FeignErrorDecoderFactory.class);
if (errorDecoderFactory != null) {
ErrorDecoder factoryErrorDecoder = errorDecoderFactory.create(type);
builder.errorDecoder(factoryErrorDecoder);
}
}
Request.Options options = getInheritedAwareOptional(context,
Request.Options.class);
Request.Options options = getInheritedAwareOptional(context, Request.Options.class);
if (options != null) {
builder.options(options);
readTimeoutMillis = options.readTimeoutMillis();
connectTimeoutMillis = options.connectTimeoutMillis();
}
Map<String, RequestInterceptor> requestInterceptors = getInheritedAwareInstances(
context, RequestInterceptor.class);
Map<String, RequestInterceptor> requestInterceptors = getInheritedAwareInstances(context,
RequestInterceptor.class);
if (requestInterceptors != null) {
builder.requestInterceptors(requestInterceptors.values());
List<RequestInterceptor> interceptors = new ArrayList<>(requestInterceptors.values());
AnnotationAwareOrderComparator.sort(interceptors);
builder.requestInterceptors(interceptors);
}
QueryMapEncoder queryMapEncoder = getInheritedAwareOptional(context,
QueryMapEncoder.class);
QueryMapEncoder queryMapEncoder = getInheritedAwareOptional(context, QueryMapEncoder.class);
if (queryMapEncoder != null) {
builder.queryMapEncoder(queryMapEncoder);
}
if (decode404) {
builder.decode404();
}
ExceptionPropagationPolicy exceptionPropagationPolicy = getInheritedAwareOptional(
context, ExceptionPropagationPolicy.class);
ExceptionPropagationPolicy exceptionPropagationPolicy = getInheritedAwareOptional(context,
ExceptionPropagationPolicy.class);
if (exceptionPropagationPolicy != null) {
builder.exceptionPropagationPolicy(exceptionPropagationPolicy);
}
}
protected void configureUsingProperties(
FeignClientProperties.FeignClientConfiguration config,
protected void configureUsingProperties(FeignClientProperties.FeignClientConfiguration config,
Feign.Builder builder) {
if (config == null) {
return;
@@ -214,13 +204,11 @@ public class FeignClientFactoryBean
builder.logLevel(config.getLoggerLevel());
}
connectTimeoutMillis = config.getConnectTimeout() != null
? config.getConnectTimeout() : connectTimeoutMillis;
readTimeoutMillis = config.getReadTimeout() != null ? config.getReadTimeout()
: readTimeoutMillis;
connectTimeoutMillis = config.getConnectTimeout() != null ? config.getConnectTimeout() : connectTimeoutMillis;
readTimeoutMillis = config.getReadTimeout() != null ? config.getReadTimeout() : readTimeoutMillis;
builder.options(new Request.Options(connectTimeoutMillis, TimeUnit.MILLISECONDS,
readTimeoutMillis, TimeUnit.MILLISECONDS, true));
builder.options(new Request.Options(connectTimeoutMillis, TimeUnit.MILLISECONDS, readTimeoutMillis,
TimeUnit.MILLISECONDS, true));
if (config.getRetryer() != null) {
Retryer retryer = getOrInstantiate(config.getRetryer());
@@ -232,8 +220,7 @@ public class FeignClientFactoryBean
builder.errorDecoder(errorDecoder);
}
if (config.getRequestInterceptors() != null
&& !config.getRequestInterceptors().isEmpty()) {
if (config.getRequestInterceptors() != null && !config.getRequestInterceptors().isEmpty()) {
// this will add request interceptor to builder, not replace existing
for (Class<RequestInterceptor> bean : config.getRequestInterceptors()) {
RequestInterceptor interceptor = getOrInstantiate(bean);
@@ -251,6 +238,14 @@ public class FeignClientFactoryBean
builder.encoder(getOrInstantiate(config.getEncoder()));
}
if (Objects.nonNull(config.getDefaultRequestHeaders())) {
builder.requestInterceptor(requestTemplate -> requestTemplate.headers(config.getDefaultRequestHeaders()));
}
if (Objects.nonNull(config.getDefaultQueryParameters())) {
builder.requestInterceptor(requestTemplate -> requestTemplate.queries(config.getDefaultQueryParameters()));
}
if (Objects.nonNull(config.getDecoder())) {
builder.decoder(getOrInstantiate(config.getDecoder()));
}
@@ -276,8 +271,7 @@ public class FeignClientFactoryBean
protected <T> T get(FeignContext context, Class<T> type) {
T instance = context.getInstance(contextId, type);
if (instance == null) {
throw new IllegalStateException(
"No bean found of type " + type + " for " + contextId);
throw new IllegalStateException("No bean found of type " + type + " for " + contextId);
}
return instance;
}
@@ -295,8 +289,7 @@ public class FeignClientFactoryBean
}
}
protected <T> Map<String, T> getInheritedAwareInstances(FeignContext context,
Class<T> type) {
protected <T> Map<String, T> getInheritedAwareInstances(FeignContext context, Class<T> type) {
if (inheritParentContext) {
return context.getInstances(contextId, type);
}
@@ -305,8 +298,7 @@ public class FeignClientFactoryBean
}
}
protected <T> T loadBalance(Feign.Builder builder, FeignContext context,
HardCodedTarget<T> target) {
protected <T> T loadBalance(Feign.Builder builder, FeignContext context, HardCodedTarget<T> target) {
Client client = getOptional(context, Client.class);
if (client != null) {
builder.client(client);
@@ -340,8 +332,7 @@ public class FeignClientFactoryBean
url = name;
}
url += cleanPath();
return (T) loadBalance(builder, context,
new HardCodedTarget<>(type, name, url));
return (T) loadBalance(builder, context, new HardCodedTarget<>(type, name, url));
}
if (StringUtils.hasText(url) && !url.startsWith("http")) {
url = "http://" + url;
@@ -357,8 +348,7 @@ public class FeignClientFactoryBean
builder.client(client);
}
Targeter targeter = get(context, Targeter.class);
return (T) targeter.target(this, builder, context,
new HardCodedTarget<>(type, name, url));
return (T) targeter.target(this, builder, context, new HardCodedTarget<>(type, name, url));
}
private String cleanPath() {
@@ -474,32 +464,26 @@ public class FeignClientFactoryBean
return false;
}
FeignClientFactoryBean that = (FeignClientFactoryBean) o;
return Objects.equals(applicationContext, that.applicationContext)
&& decode404 == that.decode404
&& inheritParentContext == that.inheritParentContext
&& Objects.equals(fallback, that.fallback)
&& Objects.equals(fallbackFactory, that.fallbackFactory)
&& Objects.equals(name, that.name) && Objects.equals(path, that.path)
&& Objects.equals(type, that.type) && Objects.equals(url, that.url);
return Objects.equals(applicationContext, that.applicationContext) && decode404 == that.decode404
&& inheritParentContext == that.inheritParentContext && Objects.equals(fallback, that.fallback)
&& Objects.equals(fallbackFactory, that.fallbackFactory) && Objects.equals(name, that.name)
&& Objects.equals(path, that.path) && Objects.equals(type, that.type) && Objects.equals(url, that.url);
}
@Override
public int hashCode() {
return Objects.hash(applicationContext, decode404, inheritParentContext, fallback,
fallbackFactory, name, path, type, url);
return Objects.hash(applicationContext, decode404, inheritParentContext, fallback, fallbackFactory, name, path,
type, url);
}
@Override
public String toString() {
return new StringBuilder("FeignClientFactoryBean{").append("type=").append(type)
.append(", ").append("name='").append(name).append("', ").append("url='")
.append(url).append("', ").append("path='").append(path).append("', ")
.append("decode404=").append(decode404).append(", ")
.append("inheritParentContext=").append(inheritParentContext).append(", ")
.append("applicationContext=").append(applicationContext).append(", ")
.append("fallback=").append(fallback).append(", ")
.append("fallbackFactory=").append(fallbackFactory).append("}")
.toString();
return new StringBuilder("FeignClientFactoryBean{").append("type=").append(type).append(", ").append("name='")
.append(name).append("', ").append("url='").append(url).append("', ").append("path='").append(path)
.append("', ").append("decode404=").append(decode404).append(", ").append("inheritParentContext=")
.append(inheritParentContext).append(", ").append("applicationContext=").append(applicationContext)
.append(", ").append("fallback=").append(fallback).append(", ").append("fallbackFactory=")
.append(fallbackFactory).append("}").toString();
}
}
@@ -16,6 +16,7 @@
package org.springframework.cloud.openfeign;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -34,6 +35,7 @@ import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* @author Eko Kurniawan Khannedy
* @author Ilia Ilinykh
*/
@ConfigurationProperties("feign.client")
public class FeignClientProperties {
@@ -78,8 +80,7 @@ public class FeignClientProperties {
}
FeignClientProperties that = (FeignClientProperties) o;
return this.defaultToProperties == that.defaultToProperties
&& Objects.equals(this.defaultConfig, that.defaultConfig)
&& Objects.equals(this.config, that.config);
&& Objects.equals(this.defaultConfig, that.defaultConfig) && Objects.equals(this.config, that.config);
}
@Override
@@ -104,6 +105,10 @@ public class FeignClientProperties {
private List<Class<RequestInterceptor>> requestInterceptors;
private Map<String, Collection<String>> defaultRequestHeaders;
private Map<String, Collection<String>> defaultQueryParameters;
private Boolean decode404;
private Class<Decoder> decoder;
@@ -158,11 +163,26 @@ public class FeignClientProperties {
return this.requestInterceptors;
}
public void setRequestInterceptors(
List<Class<RequestInterceptor>> requestInterceptors) {
public void setRequestInterceptors(List<Class<RequestInterceptor>> requestInterceptors) {
this.requestInterceptors = requestInterceptors;
}
public Map<String, Collection<String>> getDefaultRequestHeaders() {
return defaultRequestHeaders;
}
public void setDefaultRequestHeaders(Map<String, Collection<String>> defaultRequestHeaders) {
this.defaultRequestHeaders = defaultRequestHeaders;
}
public Map<String, Collection<String>> getDefaultQueryParameters() {
return defaultQueryParameters;
}
public void setDefaultQueryParameters(Map<String, Collection<String>> defaultQueryParameters) {
this.defaultQueryParameters = defaultQueryParameters;
}
public Boolean getDecode404() {
return this.decode404;
}
@@ -199,8 +219,7 @@ public class FeignClientProperties {
return exceptionPropagationPolicy;
}
public void setExceptionPropagationPolicy(
ExceptionPropagationPolicy exceptionPropagationPolicy) {
public void setExceptionPropagationPolicy(ExceptionPropagationPolicy exceptionPropagationPolicy) {
this.exceptionPropagationPolicy = exceptionPropagationPolicy;
}
@@ -213,26 +232,23 @@ public class FeignClientProperties {
return false;
}
FeignClientConfiguration that = (FeignClientConfiguration) o;
return this.loggerLevel == that.loggerLevel
&& Objects.equals(this.connectTimeout, that.connectTimeout)
&& Objects.equals(this.readTimeout, that.readTimeout)
&& Objects.equals(this.retryer, that.retryer)
return this.loggerLevel == that.loggerLevel && Objects.equals(this.connectTimeout, that.connectTimeout)
&& Objects.equals(this.readTimeout, that.readTimeout) && Objects.equals(this.retryer, that.retryer)
&& Objects.equals(this.errorDecoder, that.errorDecoder)
&& Objects.equals(this.requestInterceptors, that.requestInterceptors)
&& Objects.equals(this.decode404, that.decode404)
&& Objects.equals(this.encoder, that.encoder)
&& Objects.equals(this.decoder, that.decoder)
&& Objects.equals(this.contract, that.contract)
&& Objects.equals(this.exceptionPropagationPolicy,
that.exceptionPropagationPolicy);
&& Objects.equals(this.decode404, that.decode404) && Objects.equals(this.encoder, that.encoder)
&& Objects.equals(this.decoder, that.decoder) && Objects.equals(this.contract, that.contract)
&& Objects.equals(this.exceptionPropagationPolicy, that.exceptionPropagationPolicy)
&& Objects.equals(this.defaultRequestHeaders, that.defaultRequestHeaders)
&& Objects.equals(this.defaultQueryParameters, that.defaultQueryParameters);
}
@Override
public int hashCode() {
return Objects.hash(this.loggerLevel, this.connectTimeout, this.readTimeout,
this.retryer, this.errorDecoder, this.requestInterceptors,
this.decode404, this.encoder, this.decoder, this.contract,
this.exceptionPropagationPolicy);
return Objects.hash(this.loggerLevel, this.connectTimeout, this.readTimeout, this.retryer,
this.errorDecoder, this.requestInterceptors, this.decode404, this.encoder, this.decoder,
this.contract, this.exceptionPropagationPolicy, this.defaultQueryParameters,
this.defaultRequestHeaders);
}
}
@@ -64,8 +64,7 @@ class FeignClientSpecification implements NamedContextFactory.Specification {
return false;
}
FeignClientSpecification that = (FeignClientSpecification) o;
return Objects.equals(this.name, that.name)
&& Arrays.equals(this.configuration, that.configuration);
return Objects.equals(this.name, that.name) && Arrays.equals(this.configuration, that.configuration);
}
@Override
@@ -75,9 +74,8 @@ class FeignClientSpecification implements NamedContextFactory.Specification {
@Override
public String toString() {
return new StringBuilder("FeignClientSpecification{").append("name='")
.append(this.name).append("', ").append("configuration=")
.append(Arrays.toString(this.configuration)).append("}").toString();
return new StringBuilder("FeignClientSpecification{").append("name='").append(this.name).append("', ")
.append("configuration=").append(Arrays.toString(this.configuration)).append("}").toString();
}
}
@@ -82,8 +82,7 @@ public class FeignClientsConfiguration {
@Bean
@ConditionalOnMissingBean
public Decoder feignDecoder() {
return new OptionalDecoder(
new ResponseEntityDecoder(new SpringDecoder(this.messageConverters)));
return new OptionalDecoder(new ResponseEntityDecoder(new SpringDecoder(this.messageConverters)));
}
@Bean
@@ -96,18 +95,13 @@ public class FeignClientsConfiguration {
@Bean
@ConditionalOnClass(name = "org.springframework.data.domain.Pageable")
@ConditionalOnMissingBean
public Encoder feignEncoderPageable(
ObjectProvider<AbstractFormWriter> formWriterProvider) {
PageableSpringEncoder encoder = new PageableSpringEncoder(
springEncoder(formWriterProvider));
public Encoder feignEncoderPageable(ObjectProvider<AbstractFormWriter> formWriterProvider) {
PageableSpringEncoder encoder = new PageableSpringEncoder(springEncoder(formWriterProvider));
if (springDataWebProperties != null) {
encoder.setPageParameter(
springDataWebProperties.getPageable().getPageParameter());
encoder.setSizeParameter(
springDataWebProperties.getPageable().getSizeParameter());
encoder.setSortParameter(
springDataWebProperties.getSort().getSortParameter());
encoder.setPageParameter(springDataWebProperties.getPageable().getPageParameter());
encoder.setSizeParameter(springDataWebProperties.getPageable().getSizeParameter());
encoder.setSortParameter(springDataWebProperties.getSort().getSortParameter());
}
return encoder;
}
@@ -169,8 +163,7 @@ public class FeignClientsConfiguration {
AbstractFormWriter formWriter = formWriterProvider.getIfAvailable();
if (formWriter != null) {
return new SpringEncoder(new SpringPojoFormEncoder(formWriter),
this.messageConverters);
return new SpringEncoder(new SpringPojoFormEncoder(formWriter), this.messageConverters);
}
else {
return new SpringEncoder(new SpringFormEncoder(), this.messageConverters);
@@ -182,8 +175,7 @@ public class FeignClientsConfiguration {
SpringPojoFormEncoder(AbstractFormWriter formWriter) {
super();
MultipartFormContentProcessor processor = (MultipartFormContentProcessor) getContentProcessor(
MULTIPART);
MultipartFormContentProcessor processor = (MultipartFormContentProcessor) getContentProcessor(MULTIPART);
processor.addFirstWriter(formWriter);
}
@@ -16,19 +16,18 @@
package org.springframework.cloud.openfeign;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.annotation.AnnotatedGenericBeanDefinition;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
@@ -43,12 +42,7 @@ import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.ClassMetadata;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.filter.AbstractClassTestingTypeFilter;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.core.type.filter.TypeFilter;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
@@ -58,9 +52,9 @@ import org.springframework.util.StringUtils;
* @author Jakub Narloch
* @author Venil Noronha
* @author Gang Li
* @author Michal Domagala
*/
class FeignClientsRegistrar
implements ImportBeanDefinitionRegistrar, ResourceLoaderAware, EnvironmentAware {
class FeignClientsRegistrar implements ImportBeanDefinitionRegistrar, ResourceLoaderAware, EnvironmentAware {
// patterned after Spring Integration IntegrationComponentScanRegistrar
// and RibbonClientsConfigurationRegistgrar
@@ -73,8 +67,7 @@ class FeignClientsRegistrar
}
static void validateFallback(final Class clazz) {
Assert.isTrue(!clazz.isInterface(),
"Fallback class must implement the interface annotated by @FeignClient");
Assert.isTrue(!clazz.isInterface(), "Fallback class must implement the interface annotated by @FeignClient");
}
static void validateFallbackFactory(final Class clazz) {
@@ -139,16 +132,13 @@ class FeignClientsRegistrar
}
@Override
public void registerBeanDefinitions(AnnotationMetadata metadata,
BeanDefinitionRegistry registry) {
public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
registerDefaultConfiguration(metadata, registry);
registerFeignClients(metadata, registry);
}
private void registerDefaultConfiguration(AnnotationMetadata metadata,
BeanDefinitionRegistry registry) {
Map<String, Object> defaultAttrs = metadata
.getAnnotationAttributes(EnableFeignClients.class.getName(), true);
private void registerDefaultConfiguration(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
Map<String, Object> defaultAttrs = metadata.getAnnotationAttributes(EnableFeignClients.class.getName(), true);
if (defaultAttrs != null && defaultAttrs.containsKey("defaultConfiguration")) {
String name;
@@ -158,76 +148,53 @@ class FeignClientsRegistrar
else {
name = "default." + metadata.getClassName();
}
registerClientConfiguration(registry, name,
defaultAttrs.get("defaultConfiguration"));
registerClientConfiguration(registry, name, defaultAttrs.get("defaultConfiguration"));
}
}
public void registerFeignClients(AnnotationMetadata metadata,
BeanDefinitionRegistry registry) {
ClassPathScanningCandidateComponentProvider scanner = getScanner();
scanner.setResourceLoader(this.resourceLoader);
public void registerFeignClients(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
Set<String> basePackages;
Map<String, Object> attrs = metadata
.getAnnotationAttributes(EnableFeignClients.class.getName());
AnnotationTypeFilter annotationTypeFilter = new AnnotationTypeFilter(
FeignClient.class);
final Class<?>[] clients = attrs == null ? null
: (Class<?>[]) attrs.get("clients");
LinkedHashSet<BeanDefinition> candidateComponents = new LinkedHashSet<>();
Map<String, Object> attrs = metadata.getAnnotationAttributes(EnableFeignClients.class.getName());
AnnotationTypeFilter annotationTypeFilter = new AnnotationTypeFilter(FeignClient.class);
final Class<?>[] clients = attrs == null ? null : (Class<?>[]) attrs.get("clients");
if (clients == null || clients.length == 0) {
scanner.addIncludeFilter(annotationTypeFilter);
basePackages = getBasePackages(metadata);
ClassPathScanningCandidateComponentProvider scanner = getScanner();
scanner.setResourceLoader(this.resourceLoader);
scanner.addIncludeFilter(new AnnotationTypeFilter(FeignClient.class));
Set<String> basePackages = getBasePackages(metadata);
for (String basePackage : basePackages) {
candidateComponents.addAll(scanner.findCandidateComponents(basePackage));
}
}
else {
final Set<String> clientClasses = new HashSet<>();
basePackages = new HashSet<>();
for (Class<?> clazz : clients) {
basePackages.add(ClassUtils.getPackageName(clazz));
clientClasses.add(clazz.getCanonicalName());
candidateComponents.add(new AnnotatedGenericBeanDefinition(clazz));
}
AbstractClassTestingTypeFilter filter = new AbstractClassTestingTypeFilter() {
@Override
protected boolean match(ClassMetadata metadata) {
String cleaned = metadata.getClassName().replaceAll("\\$", ".");
return clientClasses.contains(cleaned);
}
};
scanner.addIncludeFilter(
new AllTypeFilter(Arrays.asList(filter, annotationTypeFilter)));
}
for (String basePackage : basePackages) {
Set<BeanDefinition> candidateComponents = scanner
.findCandidateComponents(basePackage);
for (BeanDefinition candidateComponent : candidateComponents) {
if (candidateComponent instanceof AnnotatedBeanDefinition) {
// verify annotated class is an interface
AnnotatedBeanDefinition beanDefinition = (AnnotatedBeanDefinition) candidateComponent;
AnnotationMetadata annotationMetadata = beanDefinition.getMetadata();
Assert.isTrue(annotationMetadata.isInterface(),
"@FeignClient can only be specified on an interface");
for (BeanDefinition candidateComponent : candidateComponents) {
if (candidateComponent instanceof AnnotatedBeanDefinition) {
// verify annotated class is an interface
AnnotatedBeanDefinition beanDefinition = (AnnotatedBeanDefinition) candidateComponent;
AnnotationMetadata annotationMetadata = beanDefinition.getMetadata();
Assert.isTrue(annotationMetadata.isInterface(), "@FeignClient can only be specified on an interface");
Map<String, Object> attributes = annotationMetadata
.getAnnotationAttributes(
FeignClient.class.getCanonicalName());
Map<String, Object> attributes = annotationMetadata
.getAnnotationAttributes(FeignClient.class.getCanonicalName());
String name = getClientName(attributes);
registerClientConfiguration(registry, name,
attributes.get("configuration"));
String name = getClientName(attributes);
registerClientConfiguration(registry, name, attributes.get("configuration"));
registerFeignClient(registry, annotationMetadata, attributes);
}
registerFeignClient(registry, annotationMetadata, attributes);
}
}
}
private void registerFeignClient(BeanDefinitionRegistry registry,
AnnotationMetadata annotationMetadata, Map<String, Object> attributes) {
private void registerFeignClient(BeanDefinitionRegistry registry, AnnotationMetadata annotationMetadata,
Map<String, Object> attributes) {
String className = annotationMetadata.getClassName();
BeanDefinitionBuilder definition = BeanDefinitionBuilder
.genericBeanDefinition(FeignClientFactoryBean.class);
BeanDefinitionBuilder definition = BeanDefinitionBuilder.genericBeanDefinition(FeignClientFactoryBean.class);
validate(attributes);
definition.addPropertyValue("url", getUrl(attributes));
definition.addPropertyValue("path", getPath(attributes));
@@ -255,8 +222,7 @@ class FeignClientsRegistrar
alias = qualifier;
}
BeanDefinitionHolder holder = new BeanDefinitionHolder(beanDefinition, className,
new String[] { alias });
BeanDefinitionHolder holder = new BeanDefinitionHolder(beanDefinition, className, new String[] { alias });
BeanDefinitionReaderUtils.registerBeanDefinition(holder, registry);
}
@@ -310,8 +276,7 @@ class FeignClientsRegistrar
protected ClassPathScanningCandidateComponentProvider getScanner() {
return new ClassPathScanningCandidateComponentProvider(false, this.environment) {
@Override
protected boolean isCandidateComponent(
AnnotatedBeanDefinition beanDefinition) {
protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
boolean isCandidate = false;
if (beanDefinition.getMetadata().isIndependent()) {
if (!beanDefinition.getMetadata().isAnnotation()) {
@@ -343,8 +308,7 @@ class FeignClientsRegistrar
}
if (basePackages.isEmpty()) {
basePackages.add(
ClassUtils.getPackageName(importingClassMetadata.getClassName()));
basePackages.add(ClassUtils.getPackageName(importingClassMetadata.getClassName()));
}
return basePackages;
}
@@ -378,18 +342,15 @@ class FeignClientsRegistrar
return value;
}
throw new IllegalStateException("Either 'name' or 'value' must be provided in @"
+ FeignClient.class.getSimpleName());
throw new IllegalStateException(
"Either 'name' or 'value' must be provided in @" + FeignClient.class.getSimpleName());
}
private void registerClientConfiguration(BeanDefinitionRegistry registry, Object name,
Object configuration) {
BeanDefinitionBuilder builder = BeanDefinitionBuilder
.genericBeanDefinition(FeignClientSpecification.class);
private void registerClientConfiguration(BeanDefinitionRegistry registry, Object name, Object configuration) {
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(FeignClientSpecification.class);
builder.addConstructorArgValue(name);
builder.addConstructorArgValue(configuration);
registry.registerBeanDefinition(
name + "." + FeignClientSpecification.class.getSimpleName(),
registry.registerBeanDefinition(name + "." + FeignClientSpecification.class.getSimpleName(),
builder.getBeanDefinition());
}
@@ -398,38 +359,4 @@ class FeignClientsRegistrar
this.environment = environment;
}
/**
* Helper class to create a {@link TypeFilter} that matches if all the delegates
* match.
*
* @author Oliver Gierke
*/
private static class AllTypeFilter implements TypeFilter {
private final List<TypeFilter> delegates;
/**
* Creates a new {@link AllTypeFilter} to match if all the given delegates match.
* @param delegates must not be {@literal null}.
*/
AllTypeFilter(List<TypeFilter> delegates) {
Assert.notNull(delegates, "This argument is required, it must not be null");
this.delegates = delegates;
}
@Override
public boolean match(MetadataReader metadataReader,
MetadataReaderFactory metadataReaderFactory) throws IOException {
for (TypeFilter filter : this.delegates) {
if (!filter.match(metadataReader, metadataReaderFactory)) {
return false;
}
}
return true;
}
}
}
@@ -24,7 +24,7 @@ import feign.Target;
*/
public interface Targeter {
<T> T target(FeignClientFactoryBean factory, Feign.Builder feign,
FeignContext context, Target.HardCodedTarget<T> target);
<T> T target(FeignClientFactoryBean factory, Feign.Builder feign, FeignContext context,
Target.HardCodedTarget<T> target);
}
@@ -48,15 +48,13 @@ public class MatrixVariableParameterProcessor implements AnnotatedParameterProce
}
@Override
public boolean processArgument(AnnotatedParameterContext context,
Annotation annotation, Method method) {
public boolean processArgument(AnnotatedParameterContext context, Annotation annotation, Method method) {
int parameterIndex = context.getParameterIndex();
Class<?> parameterType = method.getParameterTypes()[parameterIndex];
MethodMetadata data = context.getMethodMetadata();
String name = ANNOTATION.cast(annotation).value();
checkState(emptyToNull(name) != null,
"MatrixVariable annotation was empty on param %s.",
checkState(emptyToNull(name) != null, "MatrixVariable annotation was empty on param %s.",
context.getParameterIndex());
context.setParameterName(name);
@@ -65,8 +63,7 @@ public class MatrixVariableParameterProcessor implements AnnotatedParameterProce
data.indexToExpander().put(parameterIndex, this::expandMap);
}
else {
data.indexToExpander().put(parameterIndex,
object -> ";" + name + "=" + object.toString());
data.indexToExpander().put(parameterIndex, object -> ";" + name + "=" + object.toString());
}
return true;
@@ -75,8 +72,7 @@ public class MatrixVariableParameterProcessor implements AnnotatedParameterProce
private String expandMap(Object object) {
Map<String, Object> paramMap = (Map) object;
return paramMap.keySet().stream()
.map(key -> ";" + key + "=" + paramMap.get(key).toString())
return paramMap.keySet().stream().map(key -> ";" + key + "=" + paramMap.get(key).toString())
.collect(Collectors.joining());
}
@@ -46,18 +46,15 @@ public class PathVariableParameterProcessor implements AnnotatedParameterProcess
}
@Override
public boolean processArgument(AnnotatedParameterContext context,
Annotation annotation, Method method) {
public boolean processArgument(AnnotatedParameterContext context, Annotation annotation, Method method) {
String name = ANNOTATION.cast(annotation).value();
checkState(emptyToNull(name) != null,
"PathVariable annotation was empty on param %s.",
checkState(emptyToNull(name) != null, "PathVariable annotation was empty on param %s.",
context.getParameterIndex());
context.setParameterName(name);
MethodMetadata data = context.getMethodMetadata();
String varName = '{' + name + '}';
if (!data.template().url().contains(varName)
&& !searchMapValues(data.template().queries(), varName)
if (!data.template().url().contains(varName) && !searchMapValues(data.template().queries(), varName)
&& !searchMapValues(data.template().headers(), varName)) {
data.formParams().add(name);
}
@@ -40,8 +40,7 @@ public class QueryMapParameterProcessor implements AnnotatedParameterProcessor {
}
@Override
public boolean processArgument(AnnotatedParameterContext context,
Annotation annotation, Method method) {
public boolean processArgument(AnnotatedParameterContext context, Annotation annotation, Method method) {
int paramIndex = context.getParameterIndex();
MethodMetadata metadata = context.getMethodMetadata();
if (metadata.queryMapIndex() == null) {
@@ -46,27 +46,23 @@ public class RequestHeaderParameterProcessor implements AnnotatedParameterProces
}
@Override
public boolean processArgument(AnnotatedParameterContext context,
Annotation annotation, Method method) {
public boolean processArgument(AnnotatedParameterContext context, Annotation annotation, Method method) {
int parameterIndex = context.getParameterIndex();
Class<?> parameterType = method.getParameterTypes()[parameterIndex];
MethodMetadata data = context.getMethodMetadata();
if (Map.class.isAssignableFrom(parameterType)) {
checkState(data.headerMapIndex() == null,
"Header map can only be present once.");
checkState(data.headerMapIndex() == null, "Header map can only be present once.");
data.headerMapIndex(parameterIndex);
return true;
}
String name = ANNOTATION.cast(annotation).value();
checkState(emptyToNull(name) != null,
"RequestHeader.value() was empty on parameter %s", parameterIndex);
checkState(emptyToNull(name) != null, "RequestHeader.value() was empty on parameter %s", parameterIndex);
context.setParameterName(name);
Collection<String> header = context.setTemplateParameter(name,
data.template().headers().get(name));
Collection<String> header = context.setTemplateParameter(name, data.template().headers().get(name));
data.template().header(name, header);
return true;
}
@@ -46,15 +46,13 @@ public class RequestParamParameterProcessor implements AnnotatedParameterProcess
}
@Override
public boolean processArgument(AnnotatedParameterContext context,
Annotation annotation, Method method) {
public boolean processArgument(AnnotatedParameterContext context, Annotation annotation, Method method) {
int parameterIndex = context.getParameterIndex();
Class<?> parameterType = method.getParameterTypes()[parameterIndex];
MethodMetadata data = context.getMethodMetadata();
if (Map.class.isAssignableFrom(parameterType)) {
checkState(data.queryMapIndex() == null,
"Query map can only be present once.");
checkState(data.queryMapIndex() == null, "Query map can only be present once.");
data.queryMapIndex(parameterIndex);
return true;
@@ -62,12 +60,10 @@ public class RequestParamParameterProcessor implements AnnotatedParameterProcess
RequestParam requestParam = ANNOTATION.cast(annotation);
String name = requestParam.value();
checkState(emptyToNull(name) != null,
"RequestParam.value() was empty on parameter %s", parameterIndex);
checkState(emptyToNull(name) != null, "RequestParam.value() was empty on parameter %s", parameterIndex);
context.setParameterName(name);
Collection<String> query = context.setTemplateParameter(name,
data.template().queries().get(name));
Collection<String> query = context.setTemplateParameter(name, data.template().queries().get(name));
data.template().query(name, query);
return true;
}
@@ -44,19 +44,16 @@ public class RequestPartParameterProcessor implements AnnotatedParameterProcesso
}
@Override
public boolean processArgument(AnnotatedParameterContext context,
Annotation annotation, Method method) {
public boolean processArgument(AnnotatedParameterContext context, Annotation annotation, Method method) {
int parameterIndex = context.getParameterIndex();
MethodMetadata data = context.getMethodMetadata();
String name = ANNOTATION.cast(annotation).value();
checkState(emptyToNull(name) != null,
"RequestPart.value() was empty on parameter %s", parameterIndex);
checkState(emptyToNull(name) != null, "RequestPart.value() was empty on parameter %s", parameterIndex);
context.setParameterName(name);
data.formParams().add(name);
Collection<String> names = context.setTemplateParameter(name,
data.indexToName().get(parameterIndex));
Collection<String> names = context.setTemplateParameter(name, data.indexToName().get(parameterIndex));
data.indexToName().put(parameterIndex, names);
return true;
}
@@ -48,8 +48,8 @@ import org.springframework.context.annotation.Configuration;
@ConditionalOnMissingBean(CloseableHttpClient.class)
public class HttpClientFeignConfiguration {
private final Timer connectionManagerTimer = new Timer(
"FeignApacheHttpClientConfiguration.connectionManagerTimer", true);
private final Timer connectionManagerTimer = new Timer("FeignApacheHttpClientConfiguration.connectionManagerTimer",
true);
private CloseableHttpClient httpClient;
@@ -61,12 +61,10 @@ public class HttpClientFeignConfiguration {
public HttpClientConnectionManager connectionManager(
ApacheHttpClientConnectionManagerFactory connectionManagerFactory,
FeignHttpClientProperties httpClientProperties) {
final HttpClientConnectionManager connectionManager = connectionManagerFactory
.newConnectionManager(httpClientProperties.isDisableSslValidation(),
httpClientProperties.getMaxConnections(),
httpClientProperties.getMaxConnectionsPerRoute(),
httpClientProperties.getTimeToLive(),
httpClientProperties.getTimeToLiveUnit(), this.registryBuilder);
final HttpClientConnectionManager connectionManager = connectionManagerFactory.newConnectionManager(
httpClientProperties.isDisableSslValidation(), httpClientProperties.getMaxConnections(),
httpClientProperties.getMaxConnectionsPerRoute(), httpClientProperties.getTimeToLive(),
httpClientProperties.getTimeToLiveUnit(), this.registryBuilder);
this.connectionManagerTimer.schedule(new TimerTask() {
@Override
public void run() {
@@ -77,37 +75,29 @@ public class HttpClientFeignConfiguration {
}
@Bean
@ConditionalOnProperty(value = "feign.compression.response.enabled",
havingValue = "true")
public CloseableHttpClient customHttpClient(
HttpClientConnectionManager httpClientConnectionManager,
@ConditionalOnProperty(value = "feign.compression.response.enabled", havingValue = "true")
public CloseableHttpClient customHttpClient(HttpClientConnectionManager httpClientConnectionManager,
FeignHttpClientProperties httpClientProperties) {
HttpClientBuilder builder = HttpClientBuilder.create().disableCookieManagement()
.useSystemProperties();
this.httpClient = createClient(builder, httpClientConnectionManager,
httpClientProperties);
HttpClientBuilder builder = HttpClientBuilder.create().disableCookieManagement().useSystemProperties();
this.httpClient = createClient(builder, httpClientConnectionManager, httpClientProperties);
return this.httpClient;
}
@Bean
@ConditionalOnProperty(value = "feign.compression.response.enabled",
havingValue = "false", matchIfMissing = true)
@ConditionalOnProperty(value = "feign.compression.response.enabled", havingValue = "false", matchIfMissing = true)
public CloseableHttpClient httpClient(ApacheHttpClientFactory httpClientFactory,
HttpClientConnectionManager httpClientConnectionManager,
FeignHttpClientProperties httpClientProperties) {
this.httpClient = createClient(httpClientFactory.createBuilder(),
httpClientConnectionManager, httpClientProperties);
HttpClientConnectionManager httpClientConnectionManager, FeignHttpClientProperties httpClientProperties) {
this.httpClient = createClient(httpClientFactory.createBuilder(), httpClientConnectionManager,
httpClientProperties);
return this.httpClient;
}
private CloseableHttpClient createClient(HttpClientBuilder builder,
HttpClientConnectionManager httpClientConnectionManager,
FeignHttpClientProperties httpClientProperties) {
HttpClientConnectionManager httpClientConnectionManager, FeignHttpClientProperties httpClientProperties) {
RequestConfig defaultRequestConfig = RequestConfig.custom()
.setConnectTimeout(httpClientProperties.getConnectionTimeout())
.setRedirectsEnabled(httpClientProperties.isFollowRedirects()).build();
CloseableHttpClient httpClient = builder
.setDefaultRequestConfig(defaultRequestConfig)
CloseableHttpClient httpClient = builder.setDefaultRequestConfig(defaultRequestConfig)
.setConnectionManager(httpClientConnectionManager).build();
return httpClient;
}
@@ -46,8 +46,7 @@ public class OkHttpFeignConfiguration {
@Bean
@ConditionalOnMissingBean(ConnectionPool.class)
public ConnectionPool httpClientConnectionPool(
FeignHttpClientProperties httpClientProperties,
public ConnectionPool httpClientConnectionPool(FeignHttpClientProperties httpClientProperties,
OkHttpClientConnectionPoolFactory connectionPoolFactory) {
Integer maxTotalConnections = httpClientProperties.getMaxConnections();
Long timeToLive = httpClientProperties.getTimeToLive();
@@ -56,15 +55,13 @@ public class OkHttpFeignConfiguration {
}
@Bean
public okhttp3.OkHttpClient client(OkHttpClientFactory httpClientFactory,
ConnectionPool connectionPool,
public okhttp3.OkHttpClient client(OkHttpClientFactory httpClientFactory, ConnectionPool connectionPool,
FeignHttpClientProperties httpClientProperties) {
Boolean followRedirects = httpClientProperties.isFollowRedirects();
Integer connectTimeout = httpClientProperties.getConnectionTimeout();
this.okHttpClient = httpClientFactory
.createBuilder(httpClientProperties.isDisableSslValidation())
.connectTimeout(connectTimeout, TimeUnit.MILLISECONDS)
.followRedirects(followRedirects).connectionPool(connectionPool).build();
this.okHttpClient = httpClientFactory.createBuilder(httpClientProperties.isDisableSslValidation())
.connectTimeout(connectTimeout, TimeUnit.MILLISECONDS).followRedirects(followRedirects)
.connectionPool(connectionPool).build();
return this.okHttpClient;
}
@@ -48,8 +48,7 @@ public abstract class BaseRequestInterceptor implements RequestInterceptor {
* @param name the header name
* @param values the header values
*/
protected void addHeader(RequestTemplate requestTemplate, String name,
String... values) {
protected void addHeader(RequestTemplate requestTemplate, String name, String... values) {
if (!requestTemplate.headers().containsKey(name)) {
requestTemplate.header(name, values);
@@ -39,8 +39,7 @@ import org.springframework.context.annotation.Configuration;
@EnableConfigurationProperties(FeignClientEncodingProperties.class)
@ConditionalOnClass(Feign.class)
@ConditionalOnBean(Client.class)
@ConditionalOnProperty(value = "feign.compression.response.enabled",
matchIfMissing = false)
@ConditionalOnProperty(value = "feign.compression.response.enabled", matchIfMissing = false)
// The OK HTTP client uses "transparent" compression.
// If the accept-encoding header is present it disable transparent compression
@ConditionalOnMissingBean(type = "okhttp3.OkHttpClient")
@@ -33,8 +33,7 @@ public class FeignAcceptGzipEncodingInterceptor extends BaseRequestInterceptor {
* Creates new instance of {@link FeignAcceptGzipEncodingInterceptor}.
* @param properties the encoding properties
*/
protected FeignAcceptGzipEncodingInterceptor(
FeignClientEncodingProperties properties) {
protected FeignAcceptGzipEncodingInterceptor(FeignClientEncodingProperties properties) {
super(properties);
}
@@ -44,8 +43,8 @@ public class FeignAcceptGzipEncodingInterceptor extends BaseRequestInterceptor {
@Override
public void apply(RequestTemplate template) {
addHeader(template, HttpEncoding.ACCEPT_ENCODING_HEADER,
HttpEncoding.GZIP_ENCODING, HttpEncoding.DEFLATE_ENCODING);
addHeader(template, HttpEncoding.ACCEPT_ENCODING_HEADER, HttpEncoding.GZIP_ENCODING,
HttpEncoding.DEFLATE_ENCODING);
}
}
@@ -32,8 +32,7 @@ public class FeignClientEncodingProperties {
/**
* The list of supported mime types.
*/
private String[] mimeTypes = new String[] { "text/xml", "application/xml",
"application/json" };
private String[] mimeTypes = new String[] { "text/xml", "application/xml", "application/json" };
/**
* The minimum threshold content size.
@@ -77,9 +76,8 @@ public class FeignClientEncodingProperties {
@Override
public String toString() {
return new StringBuilder("FeignClientEncodingProperties{").append("mimeTypes=")
.append(Arrays.toString(this.mimeTypes)).append(", ")
.append("minRequestSize=").append(this.minRequestSize).append("}")
.toString();
.append(Arrays.toString(this.mimeTypes)).append(", ").append("minRequestSize=")
.append(this.minRequestSize).append("}").toString();
}
}
@@ -33,8 +33,7 @@ public class FeignContentGzipEncodingInterceptor extends BaseRequestInterceptor
* Creates new instance of {@link FeignContentGzipEncodingInterceptor}.
* @param properties the encoding properties
*/
protected FeignContentGzipEncodingInterceptor(
FeignClientEncodingProperties properties) {
protected FeignContentGzipEncodingInterceptor(FeignClientEncodingProperties properties) {
super(properties);
}
@@ -45,8 +44,8 @@ public class FeignContentGzipEncodingInterceptor extends BaseRequestInterceptor
public void apply(RequestTemplate template) {
if (requiresCompression(template)) {
addHeader(template, HttpEncoding.CONTENT_ENCODING_HEADER,
HttpEncoding.GZIP_ENCODING, HttpEncoding.DEFLATE_ENCODING);
addHeader(template, HttpEncoding.CONTENT_ENCODING_HEADER, HttpEncoding.GZIP_ENCODING,
HttpEncoding.DEFLATE_ENCODING);
}
}
@@ -93,8 +92,7 @@ public class FeignContentGzipEncodingInterceptor extends BaseRequestInterceptor
return false;
}
if (getProperties().getMimeTypes() == null
|| getProperties().getMimeTypes().length == 0) {
if (getProperties().getMimeTypes() == null || getProperties().getMimeTypes().length == 0) {
// no specific mime types has been set - matching everything
return true;
}
@@ -51,8 +51,7 @@ import static org.springframework.hateoas.MediaTypes.HAL_JSON;
@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication
@ConditionalOnClass(RepresentationModel.class)
@AutoConfigureAfter({ JacksonAutoConfiguration.class,
HttpMessageConvertersAutoConfiguration.class,
@AutoConfigureAfter({ JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class,
RepositoryRestMvcAutoConfiguration.class })
@AutoConfigureBefore(HypermediaAutoConfiguration.class)
public class FeignHalAutoConfiguration {
@@ -60,24 +59,21 @@ public class FeignHalAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public TypeConstrainedMappingJackson2HttpMessageConverter halJacksonHttpMessageConverter(
ObjectProvider<ObjectMapper> objectMapper,
ObjectProvider<HalConfiguration> halConfiguration,
ObjectProvider<MessageResolver> messageResolver,
ObjectProvider<CurieProvider> curieProvider,
ObjectProvider<ObjectMapper> objectMapper, ObjectProvider<HalConfiguration> halConfiguration,
ObjectProvider<MessageResolver> messageResolver, ObjectProvider<CurieProvider> curieProvider,
ObjectProvider<LinkRelationProvider> linkRelationProvider) {
ObjectMapper mapper = objectMapper.getIfAvailable(ObjectMapper::new).copy();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
HalConfiguration configuration = halConfiguration
.getIfAvailable(HalConfiguration::new);
HalConfiguration configuration = halConfiguration.getIfAvailable(HalConfiguration::new);
CurieProvider curieProviderInstance = curieProvider
.getIfAvailable(() -> new DefaultCurieProvider(Collections.emptyMap()));
Jackson2HalModule.HalHandlerInstantiator halHandlerInstantiator = new Jackson2HalModule.HalHandlerInstantiator(
linkRelationProvider.getIfAvailable(), curieProviderInstance,
messageResolver.getIfAvailable(), configuration);
linkRelationProvider.getIfAvailable(), curieProviderInstance, messageResolver.getIfAvailable(),
configuration);
mapper.setHandlerInstantiator(halHandlerInstantiator);
@@ -18,9 +18,17 @@ package org.springframework.cloud.openfeign.loadbalancer;
import feign.Client;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.client.loadbalancer.reactive.LoadBalancerProperties;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
/**
@@ -31,13 +39,29 @@ import org.springframework.context.annotation.Configuration;
* @since 2.2.0
*/
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(LoadBalancerProperties.class)
class DefaultFeignLoadBalancerConfiguration {
@Bean
@ConditionalOnMissingBean
public Client feignClient(LoadBalancerClient loadBalancerClient) {
return new FeignBlockingLoadBalancerClient(new Client.Default(null, null),
loadBalancerClient);
@Conditional(OnRetryNotEnabledCondition.class)
public Client feignClient(LoadBalancerClient loadBalancerClient, LoadBalancerProperties properties,
LoadBalancerClientFactory loadBalancerClientFactory) {
return new FeignBlockingLoadBalancerClient(new Client.Default(null, null), loadBalancerClient, properties,
loadBalancerClientFactory);
}
@Bean
@ConditionalOnMissingBean
@ConditionalOnClass(name = "org.springframework.retry.support.RetryTemplate")
@ConditionalOnBean(LoadBalancedRetryFactory.class)
@ConditionalOnProperty(value = "spring.cloud.loadbalancer.retry.enabled", havingValue = "true",
matchIfMissing = true)
public Client feignRetryClient(LoadBalancerClient loadBalancerClient,
LoadBalancedRetryFactory loadBalancedRetryFactory, LoadBalancerProperties properties,
LoadBalancerClientFactory loadBalancerClientFactory) {
return new RetryableFeignBlockingLoadBalancerClient(new Client.Default(null, null), loadBalancerClient,
loadBalancedRetryFactory, properties, loadBalancerClientFactory);
}
}
@@ -19,6 +19,7 @@ package org.springframework.cloud.openfeign.loadbalancer;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Set;
import feign.Client;
import feign.Request;
@@ -27,10 +28,22 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.CompletionContext;
import org.springframework.cloud.client.loadbalancer.DefaultRequest;
import org.springframework.cloud.client.loadbalancer.DefaultRequestContext;
import org.springframework.cloud.client.loadbalancer.DefaultResponse;
import org.springframework.cloud.client.loadbalancer.HttpRequestContext;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerLifecycle;
import org.springframework.cloud.client.loadbalancer.LoadBalancerLifecycleValidator;
import org.springframework.cloud.client.loadbalancer.reactive.LoadBalancerProperties;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.util.Assert;
import static org.springframework.cloud.openfeign.loadbalancer.LoadBalancerUtils.executeWithLoadBalancerLifecycleProcessing;
/**
* A {@link Client} implementation that uses {@link LoadBalancerClient} to select a
* {@link ServiceInstance} to use while resolving the request host.
@@ -38,44 +51,59 @@ import org.springframework.util.Assert;
* @author Olga Maciaszek-Sharma
* @since 2.2.0
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public class FeignBlockingLoadBalancerClient implements Client {
private static final Log LOG = LogFactory
.getLog(FeignBlockingLoadBalancerClient.class);
private static final Log LOG = LogFactory.getLog(FeignBlockingLoadBalancerClient.class);
private final Client delegate;
private final LoadBalancerClient loadBalancerClient;
public FeignBlockingLoadBalancerClient(Client delegate,
LoadBalancerClient loadBalancerClient) {
private final LoadBalancerProperties properties;
private final LoadBalancerClientFactory loadBalancerClientFactory;
public FeignBlockingLoadBalancerClient(Client delegate, LoadBalancerClient loadBalancerClient,
LoadBalancerProperties properties, LoadBalancerClientFactory loadBalancerClientFactory) {
this.delegate = delegate;
this.loadBalancerClient = loadBalancerClient;
this.properties = properties;
this.loadBalancerClientFactory = loadBalancerClientFactory;
}
@Override
public Response execute(Request request, Request.Options options) throws IOException {
final URI originalUri = URI.create(request.url());
String serviceId = originalUri.getHost();
Assert.state(serviceId != null,
"Request URI does not contain a valid hostname: " + originalUri);
ServiceInstance instance = loadBalancerClient.choose(serviceId);
Assert.state(serviceId != null, "Request URI does not contain a valid hostname: " + originalUri);
String hint = getHint(serviceId);
DefaultRequest<DefaultRequestContext> lbRequest = new DefaultRequest<>(
new DefaultRequestContext(request, hint));
Set<LoadBalancerLifecycle> supportedLifecycleProcessors = LoadBalancerLifecycleValidator
.getSupportedLifecycleProcessors(
loadBalancerClientFactory.getInstances(serviceId, LoadBalancerLifecycle.class),
HttpRequestContext.class, ClientHttpResponse.class, ServiceInstance.class);
supportedLifecycleProcessors.forEach(lifecycle -> lifecycle.onStart(lbRequest));
ServiceInstance instance = loadBalancerClient.choose(serviceId, lbRequest);
org.springframework.cloud.client.loadbalancer.Response<ServiceInstance> lbResponse = new DefaultResponse(
instance);
if (instance == null) {
String message = "Load balancer does not contain an instance for the service "
+ serviceId;
String message = "Load balancer does not contain an instance for the service " + serviceId;
if (LOG.isWarnEnabled()) {
LOG.warn(message);
}
return Response.builder().request(request)
.status(HttpStatus.SERVICE_UNAVAILABLE.value())
supportedLifecycleProcessors.forEach(
lifecycle -> lifecycle.onComplete(new CompletionContext<ClientHttpResponse, ServiceInstance>(
CompletionContext.Status.DISCARD, lbResponse)));
return Response.builder().request(request).status(HttpStatus.SERVICE_UNAVAILABLE.value())
.body(message, StandardCharsets.UTF_8).build();
}
String reconstructedUrl = loadBalancerClient.reconstructURI(instance, originalUri)
.toString();
Request newRequest = Request.create(request.httpMethod(), reconstructedUrl,
request.headers(), request.body(), request.charset(),
request.requestTemplate());
return delegate.execute(newRequest, options);
String reconstructedUrl = loadBalancerClient.reconstructURI(instance, originalUri).toString();
Request newRequest = Request.create(request.httpMethod(), reconstructedUrl, request.headers(), request.body(),
request.charset(), request.requestTemplate());
return executeWithLoadBalancerLifecycleProcessing(delegate, options, newRequest, lbResponse,
supportedLifecycleProcessors);
}
// Visible for Sleuth instrumentation
@@ -83,4 +111,10 @@ public class FeignBlockingLoadBalancerClient implements Client {
return delegate;
}
private String getHint(String serviceId) {
String defaultHint = properties.getHint().getOrDefault("default", "default");
String hintPropertyValue = properties.getHint().get(serviceId);
return hintPropertyValue != null ? hintPropertyValue : defaultHint;
}
}
@@ -24,6 +24,7 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.cloud.openfeign.FeignAutoConfiguration;
import org.springframework.cloud.openfeign.support.FeignHttpClientProperties;
import org.springframework.context.annotation.Configuration;
@@ -37,15 +38,14 @@ import org.springframework.context.annotation.Import;
* @since 2.2.0
*/
@ConditionalOnClass(Feign.class)
@ConditionalOnBean(LoadBalancerClient.class)
@ConditionalOnBean({ LoadBalancerClient.class, LoadBalancerClientFactory.class })
@AutoConfigureBefore(FeignAutoConfiguration.class)
@EnableConfigurationProperties(FeignHttpClientProperties.class)
@Configuration(proxyBeanMethods = false)
// Order is important here, last should be the default, first should be optional
// see
// https://github.com/spring-cloud/spring-cloud-netflix/issues/2086#issuecomment-316281653
@Import({ HttpClientFeignLoadBalancerConfiguration.class,
OkHttpFeignLoadBalancerConfiguration.class,
@Import({ HttpClientFeignLoadBalancerConfiguration.class, OkHttpFeignLoadBalancerConfiguration.class,
DefaultFeignLoadBalancerConfiguration.class })
public class FeignLoadBalancerAutoConfiguration {
@@ -24,9 +24,14 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.client.loadbalancer.reactive.LoadBalancerProperties;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.cloud.openfeign.clientconfig.HttpClientFeignConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@@ -39,17 +44,33 @@ import org.springframework.context.annotation.Import;
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(ApacheHttpClient.class)
@ConditionalOnBean(LoadBalancerClient.class)
@ConditionalOnBean({ LoadBalancerClient.class, LoadBalancerClientFactory.class })
@ConditionalOnProperty(value = "feign.httpclient.enabled", matchIfMissing = true)
@Import(HttpClientFeignConfiguration.class)
@EnableConfigurationProperties(LoadBalancerProperties.class)
class HttpClientFeignLoadBalancerConfiguration {
@Bean
@ConditionalOnMissingBean
public Client feignClient(LoadBalancerClient loadBalancerClient,
HttpClient httpClient) {
@Conditional(OnRetryNotEnabledCondition.class)
public Client feignClient(LoadBalancerClient loadBalancerClient, HttpClient httpClient,
LoadBalancerProperties properties, LoadBalancerClientFactory loadBalancerClientFactory) {
ApacheHttpClient delegate = new ApacheHttpClient(httpClient);
return new FeignBlockingLoadBalancerClient(delegate, loadBalancerClient);
return new FeignBlockingLoadBalancerClient(delegate, loadBalancerClient, properties, loadBalancerClientFactory);
}
@Bean
@ConditionalOnMissingBean
@ConditionalOnClass(name = "org.springframework.retry.support.RetryTemplate")
@ConditionalOnBean(LoadBalancedRetryFactory.class)
@ConditionalOnProperty(value = "spring.cloud.loadbalancer.retry.enabled", havingValue = "true",
matchIfMissing = true)
public Client feignRetryClient(LoadBalancerClient loadBalancerClient, HttpClient httpClient,
LoadBalancedRetryFactory loadBalancedRetryFactory, LoadBalancerProperties properties,
LoadBalancerClientFactory loadBalancerClientFactory) {
ApacheHttpClient delegate = new ApacheHttpClient(httpClient);
return new RetryableFeignBlockingLoadBalancerClient(delegate, loadBalancerClient, loadBalancedRetryFactory,
properties, loadBalancerClientFactory);
}
}
@@ -0,0 +1,69 @@
/*
* Copyright 2013-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.openfeign.loadbalancer;
import java.io.IOException;
import java.util.Set;
import feign.Client;
import feign.Request;
import feign.Response;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.CompletionContext;
import org.springframework.cloud.client.loadbalancer.LoadBalancerLifecycle;
/**
* @author Olga Maciaszek-Sharma
*
* A utility class for handling {@link LoadBalancerLifecycle} calls.
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
final class LoadBalancerUtils {
private LoadBalancerUtils() {
throw new IllegalStateException("Can't instantiate a utility class");
}
static Response executeWithLoadBalancerLifecycleProcessing(Client feignClient, Request.Options options,
Request feignRequest, org.springframework.cloud.client.loadbalancer.Response<ServiceInstance> lbResponse,
Set<LoadBalancerLifecycle> supportedLifecycleProcessors, boolean loadBalanced) throws IOException {
try {
Response response = feignClient.execute(feignRequest, options);
if (loadBalanced) {
supportedLifecycleProcessors.forEach(lifecycle -> lifecycle
.onComplete(new CompletionContext<>(CompletionContext.Status.SUCCESS, lbResponse, response)));
}
return response;
}
catch (Exception exception) {
if (loadBalanced) {
supportedLifecycleProcessors.forEach(lifecycle -> lifecycle
.onComplete(new CompletionContext<>(CompletionContext.Status.FAILED, exception, lbResponse)));
}
throw exception;
}
}
static Response executeWithLoadBalancerLifecycleProcessing(Client feignClient, Request.Options options,
Request feignRequest, org.springframework.cloud.client.loadbalancer.Response<ServiceInstance> lbResponse,
Set<LoadBalancerLifecycle> supportedLifecycleProcessors) throws IOException {
return executeWithLoadBalancerLifecycleProcessing(feignClient, options, feignRequest, lbResponse,
supportedLifecycleProcessors, true);
}
}
@@ -23,9 +23,14 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.client.loadbalancer.reactive.LoadBalancerProperties;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.cloud.openfeign.clientconfig.OkHttpFeignConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@@ -39,16 +44,32 @@ import org.springframework.context.annotation.Import;
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(OkHttpClient.class)
@ConditionalOnProperty("feign.okhttp.enabled")
@ConditionalOnBean(LoadBalancerClient.class)
@ConditionalOnBean({ LoadBalancerClient.class, LoadBalancerClientFactory.class })
@Import(OkHttpFeignConfiguration.class)
@EnableConfigurationProperties(LoadBalancerProperties.class)
class OkHttpFeignLoadBalancerConfiguration {
@Bean
@ConditionalOnMissingBean
public Client feignClient(okhttp3.OkHttpClient okHttpClient,
LoadBalancerClient loadBalancerClient) {
@Conditional(OnRetryNotEnabledCondition.class)
public Client feignClient(okhttp3.OkHttpClient okHttpClient, LoadBalancerClient loadBalancerClient,
LoadBalancerProperties properties, LoadBalancerClientFactory loadBalancerClientFactory) {
OkHttpClient delegate = new OkHttpClient(okHttpClient);
return new FeignBlockingLoadBalancerClient(delegate, loadBalancerClient);
return new FeignBlockingLoadBalancerClient(delegate, loadBalancerClient, properties, loadBalancerClientFactory);
}
@Bean
@ConditionalOnMissingBean
@ConditionalOnClass(name = "org.springframework.retry.support.RetryTemplate")
@ConditionalOnBean(LoadBalancedRetryFactory.class)
@ConditionalOnProperty(value = "spring.cloud.loadbalancer.retry.enabled", havingValue = "true",
matchIfMissing = true)
public Client feignRetryClient(LoadBalancerClient loadBalancerClient, okhttp3.OkHttpClient okHttpClient,
LoadBalancedRetryFactory loadBalancedRetryFactory, LoadBalancerProperties properties,
LoadBalancerClientFactory loadBalancerClientFactory) {
OkHttpClient delegate = new OkHttpClient(okHttpClient);
return new RetryableFeignBlockingLoadBalancerClient(delegate, loadBalancerClient, loadBalancedRetryFactory,
properties, loadBalancerClientFactory);
}
}
@@ -0,0 +1,55 @@
/*
* Copyright 2013-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.openfeign.loadbalancer;
import org.springframework.boot.autoconfigure.condition.AnyNestedCondition;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory;
import org.springframework.retry.support.RetryTemplate;
/**
* A condition that verifies that {@link RetryTemplate} is on the classpath, a
* {@link LoadBalancedRetryFactory} bean is present and
* <code>spring.cloud.loadbalancer.retry.enabled</code> is not set to <code>false</code>.
*
* @author Olga Maciaszek-Sharma
* @since 2.2.6
*/
public class OnRetryNotEnabledCondition extends AnyNestedCondition {
public OnRetryNotEnabledCondition() {
super(ConfigurationPhase.REGISTER_BEAN);
}
@ConditionalOnMissingClass("org.springframework.retry.support.RetryTemplate")
static class OnNoRetryTemplateCondition {
}
@ConditionalOnMissingBean(LoadBalancedRetryFactory.class)
static class OnRetryFactoryCondition {
}
@ConditionalOnProperty(value = "spring.cloud.loadbalancer.retry.enabled", havingValue = "false")
static class OnLoadBalancerRetryEnabledCondition {
}
}
@@ -0,0 +1,232 @@
/*
* Copyright 2013-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.openfeign.loadbalancer;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import feign.Client;
import feign.Request;
import feign.Response;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.CompletionContext;
import org.springframework.cloud.client.loadbalancer.DefaultRequest;
import org.springframework.cloud.client.loadbalancer.DefaultResponse;
import org.springframework.cloud.client.loadbalancer.HttpRequestContext;
import org.springframework.cloud.client.loadbalancer.InterceptorRetryPolicy;
import org.springframework.cloud.client.loadbalancer.LoadBalancedRecoveryCallback;
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryContext;
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory;
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryPolicy;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerLifecycle;
import org.springframework.cloud.client.loadbalancer.LoadBalancerLifecycleValidator;
import org.springframework.cloud.client.loadbalancer.RetryableRequestContext;
import org.springframework.cloud.client.loadbalancer.RetryableStatusCodeException;
import org.springframework.cloud.client.loadbalancer.reactive.LoadBalancerProperties;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.retry.RetryListener;
import org.springframework.retry.backoff.BackOffPolicy;
import org.springframework.retry.backoff.NoBackOffPolicy;
import org.springframework.retry.policy.NeverRetryPolicy;
import org.springframework.retry.support.RetryTemplate;
import org.springframework.util.Assert;
import static org.springframework.cloud.openfeign.loadbalancer.LoadBalancerUtils.executeWithLoadBalancerLifecycleProcessing;
/**
* A {@link Client} implementation that provides Spring Retry support for requests
* load-balanced with Spring Cloud LoadBalancer.
*
* @author Olga Maciaszek-Sharma
* @since 2.2.6
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public class RetryableFeignBlockingLoadBalancerClient implements Client {
private static final Log LOG = LogFactory.getLog(FeignBlockingLoadBalancerClient.class);
private final Client delegate;
private final LoadBalancerClient loadBalancerClient;
private final LoadBalancedRetryFactory loadBalancedRetryFactory;
private final LoadBalancerProperties properties;
private final LoadBalancerClientFactory loadBalancerClientFactory;
public RetryableFeignBlockingLoadBalancerClient(Client delegate, LoadBalancerClient loadBalancerClient,
LoadBalancedRetryFactory loadBalancedRetryFactory, LoadBalancerProperties properties,
LoadBalancerClientFactory loadBalancerClientFactory) {
this.delegate = delegate;
this.loadBalancerClient = loadBalancerClient;
this.loadBalancedRetryFactory = loadBalancedRetryFactory;
this.properties = properties;
this.loadBalancerClientFactory = loadBalancerClientFactory;
}
@Override
public Response execute(Request request, Request.Options options) throws IOException {
final URI originalUri = URI.create(request.url());
String serviceId = originalUri.getHost();
Assert.state(serviceId != null, "Request URI does not contain a valid hostname: " + originalUri);
final LoadBalancedRetryPolicy retryPolicy = loadBalancedRetryFactory.createRetryPolicy(serviceId,
loadBalancerClient);
RetryTemplate retryTemplate = buildRetryTemplate(serviceId, request, retryPolicy);
return retryTemplate.execute(context -> {
Request feignRequest = null;
ServiceInstance retrievedServiceInstance = null;
Set<LoadBalancerLifecycle> supportedLifecycleProcessors = LoadBalancerLifecycleValidator
.getSupportedLifecycleProcessors(
loadBalancerClientFactory.getInstances(serviceId, LoadBalancerLifecycle.class),
HttpRequestContext.class, ClientHttpResponse.class, ServiceInstance.class);
// On retries the policy will choose the server and set it in the context
// and extract the server and update the request being made
if (context instanceof LoadBalancedRetryContext) {
LoadBalancedRetryContext lbContext = (LoadBalancedRetryContext) context;
ServiceInstance serviceInstance = lbContext.getServiceInstance();
if (serviceInstance == null) {
if (LOG.isDebugEnabled()) {
LOG.debug("Service instance retrieved from LoadBalancedRetryContext: was null. "
+ "Reattempting service instance selection");
}
ServiceInstance previousServiceInstance = lbContext.getPreviousServiceInstance();
String hint = getHint(serviceId);
DefaultRequest<RetryableRequestContext> lbRequest = new DefaultRequest<>(
new RetryableRequestContext(previousServiceInstance, request, hint));
supportedLifecycleProcessors.forEach(lifecycle -> lifecycle.onStart(lbRequest));
retrievedServiceInstance = loadBalancerClient.choose(serviceId, lbRequest);
if (LOG.isDebugEnabled()) {
LOG.debug(String.format("Selected service instance: %s", retrievedServiceInstance));
}
lbContext.setServiceInstance(retrievedServiceInstance);
}
if (retrievedServiceInstance == null) {
if (LOG.isWarnEnabled()) {
LOG.warn("Service instance was not resolved, executing the original request");
}
org.springframework.cloud.client.loadbalancer.Response<ServiceInstance> lbResponse = new DefaultResponse(
retrievedServiceInstance);
supportedLifecycleProcessors.forEach(lifecycle -> lifecycle.onComplete(
new CompletionContext<ClientHttpResponse, ServiceInstance>(CompletionContext.Status.DISCARD,
lbResponse)));
feignRequest = request;
}
else {
if (LOG.isDebugEnabled()) {
LOG.debug(String.format("Using service instance from LoadBalancedRetryContext: %s",
retrievedServiceInstance));
}
String reconstructedUrl = loadBalancerClient.reconstructURI(retrievedServiceInstance, originalUri)
.toString();
feignRequest = Request.create(request.httpMethod(), reconstructedUrl, request.headers(),
request.body(), request.charset(), request.requestTemplate());
}
}
org.springframework.cloud.client.loadbalancer.Response<ServiceInstance> lbResponse = new DefaultResponse(
retrievedServiceInstance);
Response response = executeWithLoadBalancerLifecycleProcessing(delegate, options, feignRequest, lbResponse,
supportedLifecycleProcessors, retrievedServiceInstance != null);
int responseStatus = response.status();
if (retryPolicy != null && retryPolicy.retryableStatusCode(responseStatus)) {
if (LOG.isDebugEnabled()) {
LOG.debug(String.format("Retrying on status code: %d", responseStatus));
}
response.close();
throw new RetryableStatusCodeException(serviceId, responseStatus, response, URI.create(request.url()));
}
return response;
}, new LoadBalancedRecoveryCallback<Response, Response>() {
@Override
protected Response createResponse(Response response, URI uri) {
return response;
}
});
}
private RetryTemplate buildRetryTemplate(String serviceId, Request request, LoadBalancedRetryPolicy retryPolicy) {
RetryTemplate retryTemplate = new RetryTemplate();
BackOffPolicy backOffPolicy = this.loadBalancedRetryFactory.createBackOffPolicy(serviceId);
retryTemplate.setBackOffPolicy(backOffPolicy == null ? new NoBackOffPolicy() : backOffPolicy);
RetryListener[] retryListeners = this.loadBalancedRetryFactory.createRetryListeners(serviceId);
if (retryListeners != null && retryListeners.length != 0) {
retryTemplate.setListeners(retryListeners);
}
retryTemplate.setRetryPolicy(retryPolicy == null ? new NeverRetryPolicy()
: new InterceptorRetryPolicy(toHttpRequest(request), retryPolicy, loadBalancerClient, serviceId));
return retryTemplate;
}
// Visible for Sleuth instrumentation
public Client getDelegate() {
return delegate;
}
private HttpRequest toHttpRequest(Request request) {
return new HttpRequest() {
@Override
public HttpMethod getMethod() {
return HttpMethod.resolve(request.httpMethod().name());
}
@Override
public String getMethodValue() {
return getMethod().name();
}
@Override
public URI getURI() {
return URI.create(request.url());
}
@Override
public HttpHeaders getHeaders() {
Map<String, List<String>> headers = new HashMap<>();
Map<String, Collection<String>> feignHeaders = request.headers();
for (String key : feignHeaders.keySet()) {
headers.put(key, new ArrayList<>(feignHeaders.get(key)));
}
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.putAll(headers);
return httpHeaders;
}
};
}
private String getHint(String serviceId) {
String defaultHint = properties.getHint().getOrDefault("default", "default");
String hintPropertyValue = properties.getHint().get(serviceId);
return hintPropertyValue != null ? hintPropertyValue : defaultHint;
}
}
@@ -44,12 +44,10 @@ public abstract class AbstractFormWriter extends AbstractWriter {
@Override
public void write(Output output, String key, Object object) throws EncodeException {
try {
String string = new StringBuilder()
.append("Content-Disposition: form-data; name=\"").append(key)
.append('"').append(CRLF).append("Content-Type: ")
.append(getContentType()).append("; charset=")
.append(output.getCharset().name()).append(CRLF).append(CRLF)
.append(writeAsString(object)).toString();
String string = new StringBuilder().append("Content-Disposition: form-data; name=\"").append(key)
.append('"').append(CRLF).append("Content-Type: ").append(getContentType()).append("; charset=")
.append(output.getCharset().name()).append(CRLF).append(CRLF).append(writeAsString(object))
.toString();
output.write(string);
}
@@ -45,19 +45,15 @@ public class DefaultGzipDecoder implements Decoder {
}
@Override
public Object decode(final Response response, Type type)
throws IOException, FeignException {
Collection<String> encoding = response.headers()
.containsKey(HttpEncoding.CONTENT_ENCODING_HEADER)
? response.headers().get(HttpEncoding.CONTENT_ENCODING_HEADER)
: null;
public Object decode(final Response response, Type type) throws IOException, FeignException {
Collection<String> encoding = response.headers().containsKey(HttpEncoding.CONTENT_ENCODING_HEADER)
? response.headers().get(HttpEncoding.CONTENT_ENCODING_HEADER) : null;
if (encoding != null) {
if (encoding.contains(HttpEncoding.GZIP_ENCODING)) {
String decompressedBody = decompress(response);
if (decompressedBody != null) {
Response decompressedResponse = response.toBuilder()
.body(decompressedBody.getBytes()).build();
Response decompressedResponse = response.toBuilder().body(decompressedBody.getBytes()).build();
return decoder.decode(decompressedResponse, type);
}
}
@@ -69,8 +65,7 @@ public class DefaultGzipDecoder implements Decoder {
if (response.body() == null) {
return null;
}
try (GZIPInputStream gzipInputStream = new GZIPInputStream(
response.body().asInputStream());
try (GZIPInputStream gzipInputStream = new GZIPInputStream(response.body().asInputStream());
BufferedReader reader = new BufferedReader(
new InputStreamReader(gzipInputStream, StandardCharsets.UTF_8))) {
String outputString = "";
@@ -43,8 +43,7 @@ public class DefaultGzipDecoderConfiguration {
private ObjectFactory<HttpMessageConverters> messageConverters;
public DefaultGzipDecoderConfiguration(
ObjectFactory<HttpMessageConverters> messageConverters) {
public DefaultGzipDecoderConfiguration(ObjectFactory<HttpMessageConverters> messageConverters) {
this.messageConverters = messageConverters;
}
@@ -52,8 +51,8 @@ public class DefaultGzipDecoderConfiguration {
@ConditionalOnMissingBean
@ConditionalOnProperty("feign.compression.response.useGzipDecoder")
public Decoder defaultGzipDecoder() {
return new OptionalDecoder(new ResponseEntityDecoder(
new DefaultGzipDecoder(new SpringDecoder(messageConverters))));
return new OptionalDecoder(
new ResponseEntityDecoder(new DefaultGzipDecoder(new SpringDecoder(messageConverters))));
}
}
@@ -54,10 +54,8 @@ public final class FeignUtils {
return headers;
}
static Collection<String> addTemplateParameter(Collection<String> possiblyNull,
String paramName) {
Collection<String> params = ofNullable(possiblyNull).map(ArrayList::new)
.orElse(new ArrayList<>());
static Collection<String> addTemplateParameter(Collection<String> possiblyNull, String paramName) {
Collection<String> params = ofNullable(possiblyNull).map(ArrayList::new).orElse(new ArrayList<>());
params.add(String.format("{%s}", paramName));
return params;
}
@@ -63,9 +63,8 @@ public class PageJacksonModule extends Module {
private final Page<T> delegate;
SimplePageImpl(@JsonProperty("content") List<T> content,
@JsonProperty("number") int number, @JsonProperty("size") int size,
@JsonProperty("totalElements") long totalElements,
SimplePageImpl(@JsonProperty("content") List<T> content, @JsonProperty("number") int number,
@JsonProperty("size") int size, @JsonProperty("totalElements") long totalElements,
@JsonProperty("sort") Sort sort) {
PageRequest pageRequest;
if (sort != null) {
@@ -75,8 +75,7 @@ public class PageableSpringEncoder implements Encoder {
}
@Override
public void encode(Object object, Type bodyType, RequestTemplate template)
throws EncodeException {
public void encode(Object object, Type bodyType, RequestTemplate template) throws EncodeException {
if (supports(object)) {
if (object instanceof Pageable) {
@@ -101,18 +100,15 @@ public class PageableSpringEncoder implements Encoder {
delegate.encode(object, bodyType, template);
}
else {
throw new EncodeException(
"PageableSpringEncoder does not support the given object "
+ object.getClass()
+ " and no delegate was provided for fallback!");
throw new EncodeException("PageableSpringEncoder does not support the given object " + object.getClass()
+ " and no delegate was provided for fallback!");
}
}
}
private void applySort(RequestTemplate template, Sort sort) {
Collection<String> existingSorts = template.queries().get("sort");
List<String> sortQueries = existingSorts != null ? new ArrayList<>(existingSorts)
: new ArrayList<>();
List<String> sortQueries = existingSorts != null ? new ArrayList<>(existingSorts) : new ArrayList<>();
if (!sortParameter.equals("sort")) {
existingSorts = template.queries().get(sortParameter);
if (existingSorts != null) {
@@ -46,8 +46,7 @@ public class ResponseEntityDecoder implements Decoder {
}
@Override
public Object decode(final Response response, Type type)
throws IOException, FeignException {
public Object decode(final Response response, Type type) throws IOException, FeignException {
if (isParameterizeHttpEntity(type)) {
type = ((ParameterizedType) type).getActualTypeArguments()[0];
@@ -86,8 +85,7 @@ public class ResponseEntityDecoder implements Decoder {
headers.put(key, new LinkedList<>(response.headers().get(key)));
}
return new ResponseEntity<>((T) instance, headers,
HttpStatus.valueOf(response.status()));
return new ResponseEntity<>((T) instance, headers, HttpStatus.valueOf(response.status()));
}
}
@@ -48,8 +48,7 @@ public class SortJacksonModule extends Module {
context.addSerializers(serializers);
SimpleDeserializers deserializers = new SimpleDeserializers();
deserializers.addDeserializer(Sort.class,
new SortJsonComponent.SortDeserializer());
deserializers.addDeserializer(Sort.class, new SortJsonComponent.SortDeserializer());
context.addDeserializers(deserializers);
}
@@ -44,8 +44,7 @@ public class SortJsonComponent {
public static class SortSerializer extends JsonSerializer<Sort> {
@Override
public void serialize(Sort value, JsonGenerator gen,
SerializerProvider serializers) throws IOException {
public void serialize(Sort value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartArray();
value.iterator().forEachRemaining(v -> {
try {
@@ -68,15 +67,14 @@ public class SortJsonComponent {
public static class SortDeserializer extends JsonDeserializer<Sort> {
@Override
public Sort deserialize(JsonParser jsonParser,
DeserializationContext deserializationContext) throws IOException {
public Sort deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
throws IOException {
TreeNode treeNode = jsonParser.getCodec().readTree(jsonParser);
if (treeNode.isArray()) {
ArrayNode arrayNode = (ArrayNode) treeNode;
List<Sort.Order> orders = new ArrayList<>();
for (JsonNode jsonNode : arrayNode) {
Sort.Order order = new Sort.Order(
Sort.Direction.valueOf(jsonNode.get("direction").textValue()),
Sort.Order order = new Sort.Order(Sort.Direction.valueOf(jsonNode.get("direction").textValue()),
jsonNode.get("property").textValue());
orders.add(order);
}
@@ -48,18 +48,15 @@ public class SpringDecoder implements Decoder {
}
@Override
public Object decode(final Response response, Type type)
throws IOException, FeignException {
if (type instanceof Class || type instanceof ParameterizedType
|| type instanceof WildcardType) {
public Object decode(final Response response, Type type) throws IOException, FeignException {
if (type instanceof Class || type instanceof ParameterizedType || type instanceof WildcardType) {
@SuppressWarnings({ "unchecked", "rawtypes" })
HttpMessageConverterExtractor<?> extractor = new HttpMessageConverterExtractor(
type, this.messageConverters.getObject().getConverters());
HttpMessageConverterExtractor<?> extractor = new HttpMessageConverterExtractor(type,
this.messageConverters.getObject().getConverters());
return extractor.extractData(new FeignResponseAdapter(response));
}
throw new DecodeException(response.status(),
"type is not an instance of Class or ParameterizedType: " + type,
throw new DecodeException(response.status(), "type is not an instance of Class or ParameterizedType: " + type,
response.request());
}
@@ -69,19 +69,16 @@ public class SpringEncoder implements Encoder {
this.messageConverters = messageConverters;
}
public SpringEncoder(SpringFormEncoder springFormEncoder,
ObjectFactory<HttpMessageConverters> messageConverters) {
public SpringEncoder(SpringFormEncoder springFormEncoder, ObjectFactory<HttpMessageConverters> messageConverters) {
this.springFormEncoder = springFormEncoder;
this.messageConverters = messageConverters;
}
@Override
public void encode(Object requestBody, Type bodyType, RequestTemplate request)
throws EncodeException {
public void encode(Object requestBody, Type bodyType, RequestTemplate request) throws EncodeException {
// template.body(conversionService.convert(object, String.class));
if (requestBody != null) {
Collection<String> contentTypes = request.headers()
.get(HttpEncoding.CONTENT_TYPE);
Collection<String> contentTypes = request.headers().get(HttpEncoding.CONTENT_TYPE);
MediaType requestContentType = null;
if (contentTypes != null && !contentTypes.isEmpty()) {
@@ -95,24 +92,20 @@ public class SpringEncoder implements Encoder {
}
else {
if (bodyType == MultipartFile.class) {
log.warn(
"For MultipartFile to be handled correctly, the 'consumes' parameter of @RequestMapping "
+ "should be specified as MediaType.MULTIPART_FORM_DATA_VALUE");
log.warn("For MultipartFile to be handled correctly, the 'consumes' parameter of @RequestMapping "
+ "should be specified as MediaType.MULTIPART_FORM_DATA_VALUE");
}
}
for (HttpMessageConverter messageConverter : this.messageConverters
.getObject().getConverters()) {
for (HttpMessageConverter messageConverter : this.messageConverters.getObject().getConverters()) {
FeignOutputMessage outputMessage;
try {
if (messageConverter instanceof GenericHttpMessageConverter) {
outputMessage = checkAndWrite(requestBody, bodyType,
requestContentType,
outputMessage = checkAndWrite(requestBody, bodyType, requestContentType,
(GenericHttpMessageConverter) messageConverter, request);
}
else {
outputMessage = checkAndWrite(requestBody, requestContentType,
messageConverter, request);
outputMessage = checkAndWrite(requestBody, requestContentType, messageConverter, request);
}
}
catch (IOException | HttpMessageConversionException ex) {
@@ -131,20 +124,19 @@ public class SpringEncoder implements Encoder {
charset = null;
}
else if (messageConverter instanceof ProtobufHttpMessageConverter
&& ProtobufHttpMessageConverter.PROTOBUF.isCompatibleWith(
outputMessage.getHeaders().getContentType())) {
&& ProtobufHttpMessageConverter.PROTOBUF
.isCompatibleWith(outputMessage.getHeaders().getContentType())) {
charset = null;
}
else {
charset = StandardCharsets.UTF_8;
}
request.body(Request.Body.encoded(
outputMessage.getOutputStream().toByteArray(), charset));
request.body(Request.Body.encoded(outputMessage.getOutputStream().toByteArray(), charset));
return;
}
}
String message = "Could not write request: no suitable HttpMessageConverter "
+ "found for request type [" + requestBody.getClass().getName() + "]";
String message = "Could not write request: no suitable HttpMessageConverter " + "found for request type ["
+ requestBody.getClass().getName() + "]";
if (requestContentType != null) {
message += " and content type [" + requestContentType + "]";
}
@@ -153,8 +145,8 @@ public class SpringEncoder implements Encoder {
}
@SuppressWarnings("unchecked")
private FeignOutputMessage checkAndWrite(Object body, MediaType contentType,
HttpMessageConverter converter, RequestTemplate request) throws IOException {
private FeignOutputMessage checkAndWrite(Object body, MediaType contentType, HttpMessageConverter converter,
RequestTemplate request) throws IOException {
if (converter.canWrite(body.getClass(), contentType)) {
logBeforeWrite(body, contentType, converter);
FeignOutputMessage outputMessage = new FeignOutputMessage(request);
@@ -167,9 +159,8 @@ public class SpringEncoder implements Encoder {
}
@SuppressWarnings("unchecked")
private FeignOutputMessage checkAndWrite(Object body, Type genericType,
MediaType contentType, GenericHttpMessageConverter converter,
RequestTemplate request) throws IOException {
private FeignOutputMessage checkAndWrite(Object body, Type genericType, MediaType contentType,
GenericHttpMessageConverter converter, RequestTemplate request) throws IOException {
if (converter.canWrite(genericType, body.getClass(), contentType)) {
logBeforeWrite(body, contentType, converter);
FeignOutputMessage outputMessage = new FeignOutputMessage(request);
@@ -185,12 +176,11 @@ public class SpringEncoder implements Encoder {
HttpMessageConverter messageConverter) {
if (log.isDebugEnabled()) {
if (requestContentType != null) {
log.debug("Writing [" + requestBody + "] as \"" + requestContentType
+ "\" using [" + messageConverter + "]");
log.debug("Writing [" + requestBody + "] as \"" + requestContentType + "\" using [" + messageConverter
+ "]");
}
else {
log.debug(
"Writing [" + requestBody + "] using [" + messageConverter + "]");
log.debug("Writing [" + requestBody + "] using [" + messageConverter + "]");
}
}
}
@@ -57,6 +57,7 @@ import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.InvalidMediaTypeException;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
@@ -78,18 +79,15 @@ import static org.springframework.core.annotation.AnnotatedElementUtils.findMerg
* @author Artyom Romanenko
* @author Darren Foong
*/
public class SpringMvcContract extends Contract.BaseContract
implements ResourceLoaderAware {
public class SpringMvcContract extends Contract.BaseContract implements ResourceLoaderAware {
private static final String ACCEPT = "Accept";
private static final String CONTENT_TYPE = "Content-Type";
private static final TypeDescriptor STRING_TYPE_DESCRIPTOR = TypeDescriptor
.valueOf(String.class);
private static final TypeDescriptor STRING_TYPE_DESCRIPTOR = TypeDescriptor.valueOf(String.class);
private static final TypeDescriptor ITERABLE_TYPE_DESCRIPTOR = TypeDescriptor
.valueOf(Iterable.class);
private static final TypeDescriptor ITERABLE_TYPE_DESCRIPTOR = TypeDescriptor.valueOf(Iterable.class);
private static final ParameterNameDiscoverer PARAMETER_NAME_DISCOVERER = new DefaultParameterNameDiscoverer();
@@ -107,16 +105,13 @@ public class SpringMvcContract extends Contract.BaseContract
this(Collections.emptyList());
}
public SpringMvcContract(
List<AnnotatedParameterProcessor> annotatedParameterProcessors) {
public SpringMvcContract(List<AnnotatedParameterProcessor> annotatedParameterProcessors) {
this(annotatedParameterProcessors, new DefaultConversionService());
}
public SpringMvcContract(
List<AnnotatedParameterProcessor> annotatedParameterProcessors,
public SpringMvcContract(List<AnnotatedParameterProcessor> annotatedParameterProcessors,
ConversionService conversionService) {
Assert.notNull(annotatedParameterProcessors,
"Parameter processors can not be null.");
Assert.notNull(annotatedParameterProcessors, "Parameter processors can not be null.");
Assert.notNull(conversionService, "ConversionService can not be null.");
List<AnnotatedParameterProcessor> processors = getDefaultAnnotatedArgumentsProcessors();
@@ -135,26 +130,21 @@ public class SpringMvcContract extends Contract.BaseContract
// Feign applies the Param.Expander to each element of an Iterable, so in those
// cases we need to provide a TypeDescriptor of the element.
if (typeDescriptor.isAssignableTo(ITERABLE_TYPE_DESCRIPTOR)) {
TypeDescriptor elementTypeDescriptor = getElementTypeDescriptor(
typeDescriptor);
TypeDescriptor elementTypeDescriptor = getElementTypeDescriptor(typeDescriptor);
checkState(elementTypeDescriptor != null,
"Could not resolve element type of Iterable type %s. Not declared?",
typeDescriptor);
"Could not resolve element type of Iterable type %s. Not declared?", typeDescriptor);
typeDescriptor = elementTypeDescriptor;
}
return typeDescriptor;
}
private static TypeDescriptor getElementTypeDescriptor(
TypeDescriptor typeDescriptor) {
private static TypeDescriptor getElementTypeDescriptor(TypeDescriptor typeDescriptor) {
TypeDescriptor elementTypeDescriptor = typeDescriptor.getElementTypeDescriptor();
// that means it's not a collection but it is iterable, gh-135
if (elementTypeDescriptor == null
&& Iterable.class.isAssignableFrom(typeDescriptor.getType())) {
ResolvableType type = typeDescriptor.getResolvableType().as(Iterable.class)
.getGeneric(0);
if (elementTypeDescriptor == null && Iterable.class.isAssignableFrom(typeDescriptor.getType())) {
ResolvableType type = typeDescriptor.getResolvableType().as(Iterable.class).getGeneric(0);
if (type.resolve() == null) {
return null;
}
@@ -171,16 +161,16 @@ public class SpringMvcContract extends Contract.BaseContract
@Override
protected void processAnnotationOnClass(MethodMetadata data, Class<?> clz) {
if (clz.getInterfaces().length == 0) {
RequestMapping classAnnotation = findMergedAnnotation(clz,
RequestMapping.class);
if (classAnnotation != null && classAnnotation.value().length > 0) {
RequestMapping classAnnotation = findMergedAnnotation(clz, RequestMapping.class);
if (classAnnotation != null) {
// Prepend path from class annotation if specified
String pathValue = emptyToNull(classAnnotation.value()[0]);
if (pathValue != null) {
if (classAnnotation.value().length > 0) {
String pathValue = emptyToNull(classAnnotation.value()[0]);
pathValue = resolve(pathValue);
if (!pathValue.equals("/")) {
data.template().uri(pathValue);
if (!pathValue.startsWith("/")) {
pathValue = "/" + pathValue;
}
data.template().uri(pathValue);
}
}
}
@@ -191,8 +181,7 @@ public class SpringMvcContract extends Contract.BaseContract
processedMethods.put(Feign.configKey(targetType, method), method);
MethodMetadata md = super.parseAndValidateMetadata(targetType, method);
RequestMapping classAnnotation = findMergedAnnotation(targetType,
RequestMapping.class);
RequestMapping classAnnotation = findMergedAnnotation(targetType, RequestMapping.class);
if (classAnnotation != null) {
// produces - use from class annotation only if method has not specified this
if (!md.template().headers().containsKey(ACCEPT)) {
@@ -212,16 +201,14 @@ public class SpringMvcContract extends Contract.BaseContract
}
@Override
protected void processAnnotationOnMethod(MethodMetadata data,
Annotation methodAnnotation, Method method) {
protected void processAnnotationOnMethod(MethodMetadata data, Annotation methodAnnotation, Method method) {
if (CollectionFormat.class.isInstance(methodAnnotation)) {
CollectionFormat collectionFormat = findMergedAnnotation(method,
CollectionFormat.class);
CollectionFormat collectionFormat = findMergedAnnotation(method, CollectionFormat.class);
data.template().collectionFormat(collectionFormat.value());
}
if (!RequestMapping.class.isInstance(methodAnnotation) && !methodAnnotation
.annotationType().isAnnotationPresent(RequestMapping.class)) {
if (!RequestMapping.class.isInstance(methodAnnotation)
&& !methodAnnotation.annotationType().isAnnotationPresent(RequestMapping.class)) {
return;
}
@@ -240,9 +227,11 @@ public class SpringMvcContract extends Contract.BaseContract
String pathValue = emptyToNull(methodMapping.value()[0]);
if (pathValue != null) {
pathValue = resolve(pathValue);
if (!pathValue.equals("/")) {
data.template().uri(pathValue, true);
// Append path from @RequestMapping if value is present on method
if (!pathValue.startsWith("/") && !data.template().path().endsWith("/")) {
pathValue = "/" + pathValue;
}
data.template().uri(pathValue, true);
}
}
@@ -259,34 +248,29 @@ public class SpringMvcContract extends Contract.BaseContract
}
private String resolve(String value) {
if (StringUtils.hasText(value)
&& resourceLoader instanceof ConfigurableApplicationContext) {
return ((ConfigurableApplicationContext) resourceLoader).getEnvironment()
.resolvePlaceholders(value);
if (StringUtils.hasText(value) && resourceLoader instanceof ConfigurableApplicationContext) {
return ((ConfigurableApplicationContext) resourceLoader).getEnvironment().resolvePlaceholders(value);
}
return value;
}
private void checkAtMostOne(Method method, Object[] values, String fieldName) {
checkState(values != null && (values.length == 0 || values.length == 1),
"Method %s can only contain at most 1 %s field. Found: %s",
method.getName(), fieldName,
"Method %s can only contain at most 1 %s field. Found: %s", method.getName(), fieldName,
values == null ? null : Arrays.asList(values));
}
private void checkOne(Method method, Object[] values, String fieldName) {
checkState(values != null && values.length == 1,
"Method %s can only contain 1 %s field. Found: %s", method.getName(),
fieldName, values == null ? null : Arrays.asList(values));
checkState(values != null && values.length == 1, "Method %s can only contain 1 %s field. Found: %s",
method.getName(), fieldName, values == null ? null : Arrays.asList(values));
}
@Override
protected boolean processAnnotationsOnParameter(MethodMetadata data,
Annotation[] annotations, int paramIndex) {
protected boolean processAnnotationsOnParameter(MethodMetadata data, Annotation[] annotations, int paramIndex) {
boolean isHttpAnnotation = false;
AnnotatedParameterProcessor.AnnotatedParameterContext context = new SimpleAnnotatedParameterContext(
data, paramIndex);
AnnotatedParameterProcessor.AnnotatedParameterContext context = new SimpleAnnotatedParameterContext(data,
paramIndex);
Method method = processedMethods.get(data.configKey());
for (Annotation parameterAnnotation : annotations) {
AnnotatedParameterProcessor processor = annotatedArgumentProcessors
@@ -295,19 +279,16 @@ public class SpringMvcContract extends Contract.BaseContract
Annotation processParameterAnnotation;
// synthesize, handling @AliasFor, while falling back to parameter name on
// missing String #value():
processParameterAnnotation = synthesizeWithMethodParameterNameAsFallbackValue(
parameterAnnotation, method, paramIndex);
isHttpAnnotation |= processor.processArgument(context,
processParameterAnnotation, method);
processParameterAnnotation = synthesizeWithMethodParameterNameAsFallbackValue(parameterAnnotation,
method, paramIndex);
isHttpAnnotation |= processor.processArgument(context, processParameterAnnotation, method);
}
}
if (!isMultipartFormData(data) && isHttpAnnotation
&& data.indexToExpander().get(paramIndex) == null) {
if (!isMultipartFormData(data) && isHttpAnnotation && data.indexToExpander().get(paramIndex) == null) {
TypeDescriptor typeDescriptor = createTypeDescriptor(method, paramIndex);
if (conversionService.canConvert(typeDescriptor, STRING_TYPE_DESCRIPTOR)) {
Param.Expander expander = convertingExpanderFactory
.getExpander(typeDescriptor);
Param.Expander expander = convertingExpanderFactory.getExpander(typeDescriptor);
if (expander != null) {
data.indexToExpander().put(paramIndex, expander);
}
@@ -316,28 +297,23 @@ public class SpringMvcContract extends Contract.BaseContract
return isHttpAnnotation;
}
private void parseProduces(MethodMetadata md, Method method,
RequestMapping annotation) {
private void parseProduces(MethodMetadata md, Method method, RequestMapping annotation) {
String[] serverProduces = annotation.produces();
String clientAccepts = serverProduces.length == 0 ? null
: emptyToNull(serverProduces[0]);
String clientAccepts = serverProduces.length == 0 ? null : emptyToNull(serverProduces[0]);
if (clientAccepts != null) {
md.template().header(ACCEPT, clientAccepts);
}
}
private void parseConsumes(MethodMetadata md, Method method,
RequestMapping annotation) {
private void parseConsumes(MethodMetadata md, Method method, RequestMapping annotation) {
String[] serverConsumes = annotation.consumes();
String clientProduces = serverConsumes.length == 0 ? null
: emptyToNull(serverConsumes[0]);
String clientProduces = serverConsumes.length == 0 ? null : emptyToNull(serverConsumes[0]);
if (clientProduces != null) {
md.template().header(CONTENT_TYPE, clientProduces);
}
}
private void parseHeaders(MethodMetadata md, Method method,
RequestMapping annotation) {
private void parseHeaders(MethodMetadata md, Method method, RequestMapping annotation) {
// TODO: only supports one header value per key
if (annotation.headers() != null && annotation.headers().length > 0) {
for (String header : annotation.headers()) {
@@ -373,26 +349,21 @@ public class SpringMvcContract extends Contract.BaseContract
return annotatedArgumentResolvers;
}
private Annotation synthesizeWithMethodParameterNameAsFallbackValue(
Annotation parameterAnnotation, Method method, int parameterIndex) {
Map<String, Object> annotationAttributes = AnnotationUtils
.getAnnotationAttributes(parameterAnnotation);
private Annotation synthesizeWithMethodParameterNameAsFallbackValue(Annotation parameterAnnotation, Method method,
int parameterIndex) {
Map<String, Object> annotationAttributes = AnnotationUtils.getAnnotationAttributes(parameterAnnotation);
Object defaultValue = AnnotationUtils.getDefaultValue(parameterAnnotation);
if (defaultValue instanceof String
&& defaultValue.equals(annotationAttributes.get(AnnotationUtils.VALUE))) {
if (defaultValue instanceof String && defaultValue.equals(annotationAttributes.get(AnnotationUtils.VALUE))) {
Type[] parameterTypes = method.getGenericParameterTypes();
String[] parameterNames = PARAMETER_NAME_DISCOVERER.getParameterNames(method);
if (shouldAddParameterName(parameterIndex, parameterTypes, parameterNames)) {
annotationAttributes.put(AnnotationUtils.VALUE,
parameterNames[parameterIndex]);
annotationAttributes.put(AnnotationUtils.VALUE, parameterNames[parameterIndex]);
}
}
return AnnotationUtils.synthesizeAnnotation(annotationAttributes,
parameterAnnotation.annotationType(), null);
return AnnotationUtils.synthesizeAnnotation(annotationAttributes, parameterAnnotation.annotationType(), null);
}
private boolean shouldAddParameterName(int parameterIndex, Type[] parameterTypes,
String[] parameterNames) {
private boolean shouldAddParameterName(int parameterIndex, Type[] parameterTypes, String[] parameterNames) {
// has a parameter name
return parameterNames != null && parameterNames.length > parameterIndex
// has a type
@@ -400,12 +371,16 @@ public class SpringMvcContract extends Contract.BaseContract
}
private boolean isMultipartFormData(MethodMetadata data) {
Collection<String> contentTypes = data.template().headers()
.get(HttpEncoding.CONTENT_TYPE);
Collection<String> contentTypes = data.template().headers().get(HttpEncoding.CONTENT_TYPE);
if (contentTypes != null && !contentTypes.isEmpty()) {
String type = contentTypes.iterator().next();
return Objects.equals(MediaType.valueOf(type), MediaType.MULTIPART_FORM_DATA);
try {
return Objects.equals(MediaType.valueOf(type), MediaType.MULTIPART_FORM_DATA);
}
catch (InvalidMediaTypeException ignored) {
return false;
}
}
return false;
@@ -440,23 +415,20 @@ public class SpringMvcContract extends Contract.BaseContract
Param.Expander getExpander(TypeDescriptor typeDescriptor) {
return value -> {
Object converted = conversionService.convert(value, typeDescriptor,
STRING_TYPE_DESCRIPTOR);
Object converted = conversionService.convert(value, typeDescriptor, STRING_TYPE_DESCRIPTOR);
return (String) converted;
};
}
}
private class SimpleAnnotatedParameterContext
implements AnnotatedParameterProcessor.AnnotatedParameterContext {
private class SimpleAnnotatedParameterContext implements AnnotatedParameterProcessor.AnnotatedParameterContext {
private final MethodMetadata methodMetadata;
private final int parameterIndex;
SimpleAnnotatedParameterContext(MethodMetadata methodMetadata,
int parameterIndex) {
SimpleAnnotatedParameterContext(MethodMetadata methodMetadata, int parameterIndex) {
this.methodMetadata = methodMetadata;
this.parameterIndex = parameterIndex;
}
@@ -477,8 +449,7 @@ public class SpringMvcContract extends Contract.BaseContract
}
@Override
public Collection<String> setTemplateParameter(String name,
Collection<String> rest) {
public Collection<String> setTemplateParameter(String name, Collection<String> rest) {
return addTemplateParameter(rest, name);
}
@@ -43,10 +43,8 @@ import static org.assertj.core.api.Assertions.assertThat;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = DefaultGzipDecoderTests.Application.class,
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
value = { "spring.application.name=defaultGzipDecoderTests",
"feign.compression.response.enabled=true",
"feign.compression.response.useGzipDecoder=true",
"feign.client.config.default.loggerLevel=full",
value = { "spring.application.name=defaultGzipDecoderTests", "feign.compression.response.enabled=true",
"feign.compression.response.useGzipDecoder=true", "feign.client.config.default.loggerLevel=full",
"logging.level.org.springframework.cloud.openfeign=DEBUG" })
@DirtiesContext
public class DefaultGzipDecoderTests extends FeignClientFactoryBean {
@@ -71,20 +69,17 @@ public class DefaultGzipDecoderTests extends FeignClientFactoryBean {
public void testBodyDecompress() {
ResponseEntity<Hello> response = testClient().getGzipResponse();
assertThat(response).as("response was null").isNotNull();
assertThat(response.getStatusCode()).as("wrong status code")
.isEqualTo(HttpStatus.OK);
assertThat(response.getStatusCode()).as("wrong status code").isEqualTo(HttpStatus.OK);
Hello hello = response.getBody();
assertThat(hello).as("hello was null").isNotNull();
assertThat(hello).as("first hello didn't match")
.isEqualTo(new Hello("hello world via response"));
assertThat(hello).as("first hello didn't match").isEqualTo(new Hello("hello world via response"));
}
@Test
public void testNullBodyDecompress() {
ResponseEntity<Hello> response = testClient().getNullResponse();
assertThat(response).as("response was null").isNotNull();
assertThat(response.getStatusCode()).as("wrong status code")
.isEqualTo(HttpStatus.OK);
assertThat(response.getStatusCode()).as("wrong status code").isEqualTo(HttpStatus.OK);
Hello hello = response.getBody();
assertThat(hello).as("hello was not null").isNull();
assertThat(hello).as("null hello didn't match").isEqualTo(null);
@@ -94,12 +89,10 @@ public class DefaultGzipDecoderTests extends FeignClientFactoryBean {
public void testCharsetDecompress() {
ResponseEntity<Hello> response = testClient().getUtf8Response();
assertThat(response).as("response was null").isNotNull();
assertThat(response.getStatusCode()).as("wrong status code")
.isEqualTo(HttpStatus.OK);
assertThat(response.getStatusCode()).as("wrong status code").isEqualTo(HttpStatus.OK);
Hello hello = response.getBody();
assertThat(hello).as("hello was null").isNotNull();
assertThat(hello).as("utf8 hello didn't match")
.isEqualTo(new Hello("안녕하세요 means Hello in Korean"));
assertThat(hello).as("utf8 hello didn't match").isEqualTo(new Hello("안녕하세요 means Hello in Korean"));
}
private static class Hello {
@@ -42,8 +42,7 @@ public class EnableFeignClientsSpringDataTests {
@Test
public void encoderDefaultCorrect() {
PageableSpringEncoder.class
.cast(this.feignContext.getInstance("foo", Encoder.class));
PageableSpringEncoder.class.cast(this.feignContext.getInstance("foo", Encoder.class));
}
@Configuration(proxyBeanMethods = false)
@@ -41,8 +41,7 @@ public class FeignBuilderCustomizerTests {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
FeignBuilderCustomizerTests.SampleConfiguration2.class);
FeignClientFactoryBean clientFactoryBean = context
.getBean(FeignClientFactoryBean.class);
FeignClientFactoryBean clientFactoryBean = context.getBean(FeignClientFactoryBean.class);
FeignContext feignContext = context.getBean(FeignContext.class);
Feign.Builder builder = clientFactoryBean.feign(feignContext);
@@ -52,14 +51,12 @@ public class FeignBuilderCustomizerTests {
context.close();
}
private void assertFeignBuilderField(Feign.Builder builder, String fieldName,
Object expectedValue) {
private void assertFeignBuilderField(Feign.Builder builder, String fieldName, Object expectedValue) {
Field builderField = ReflectionUtils.findField(Feign.Builder.class, fieldName);
ReflectionUtils.makeAccessible(builderField);
Object value = ReflectionUtils.getField(builderField, builder);
assertThat(value).as("Expected value for the field '" + fieldName + "':")
.isEqualTo(expectedValue);
assertThat(value).as("Expected value for the field '" + fieldName + "':").isEqualTo(expectedValue);
}
@Test
@@ -67,8 +64,7 @@ public class FeignBuilderCustomizerTests {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
FeignBuilderCustomizerTests.SampleConfiguration3.class);
FeignClientFactoryBean clientFactoryBean = context
.getBean(FeignClientFactoryBean.class);
FeignClientFactoryBean clientFactoryBean = context.getBean(FeignClientFactoryBean.class);
FeignContext feignContext = context.getBean(FeignContext.class);
Feign.Builder builder = clientFactoryBean.feign(feignContext);
@@ -49,26 +49,23 @@ public class FeignClientBuilderTests {
private ApplicationContext applicationContext;
private static Object getDefaultValueFromFeignClientAnnotation(
final String methodName) {
private static Object getDefaultValueFromFeignClientAnnotation(final String methodName) {
final Method method = ReflectionUtils.findMethod(FeignClient.class, methodName);
return method.getDefaultValue();
}
private static void assertFactoryBeanField(final FeignClientBuilder.Builder builder,
final String fieldName, final Object expectedValue) {
final Field factoryBeanField = ReflectionUtils
.findField(FeignClientBuilder.Builder.class, "feignClientFactoryBean");
private static void assertFactoryBeanField(final FeignClientBuilder.Builder builder, final String fieldName,
final Object expectedValue) {
final Field factoryBeanField = ReflectionUtils.findField(FeignClientBuilder.Builder.class,
"feignClientFactoryBean");
ReflectionUtils.makeAccessible(factoryBeanField);
final FeignClientFactoryBean factoryBean = (FeignClientFactoryBean) ReflectionUtils
.getField(factoryBeanField, builder);
final FeignClientFactoryBean factoryBean = (FeignClientFactoryBean) ReflectionUtils.getField(factoryBeanField,
builder);
final Field field = ReflectionUtils.findField(FeignClientFactoryBean.class,
fieldName);
final Field field = ReflectionUtils.findField(FeignClientFactoryBean.class, fieldName);
ReflectionUtils.makeAccessible(field);
final Object value = ReflectionUtils.getField(field, factoryBean);
assertThat(value).as("Expected value for the field '" + fieldName + "':")
.isEqualTo(expectedValue);
assertThat(value).as("Expected value for the field '" + fieldName + "':").isEqualTo(expectedValue);
}
@Before
@@ -83,9 +80,8 @@ public class FeignClientBuilderTests {
for (final Method method : FeignClient.class.getMethods()) {
methodNames.add(method.getName());
}
methodNames.removeAll(
Arrays.asList("annotationType", "value", "serviceId", "qualifier",
"configuration", "primary", "equals", "hashCode", "toString"));
methodNames.removeAll(Arrays.asList("annotationType", "value", "serviceId", "qualifier", "configuration",
"primary", "equals", "hashCode", "toString"));
Collections.sort(methodNames);
// If this safety check fails the Builder has to be updated.
// (1) Either a field was removed from the FeignClient annotation and so it has to
@@ -93,15 +89,14 @@ public class FeignClientBuilderTests {
// on this builder class.
// (2) Or a new field was added and the builder class has to be extended with this
// new field.
assertThat(methodNames).containsExactly("contextId", "decode404", "fallback",
"fallbackFactory", "name", "path", "url");
assertThat(methodNames).containsExactly("contextId", "decode404", "fallback", "fallbackFactory", "name", "path",
"url");
}
@Test
public void forType_preinitializedBuilder() {
// when:
final FeignClientBuilder.Builder builder = this.feignClientBuilder
.forType(TestFeignClient.class, "TestClient");
final FeignClientBuilder.Builder builder = this.feignClientBuilder.forType(TestFeignClient.class, "TestClient");
// then:
assertFactoryBeanField(builder, "applicationContext", this.applicationContext);
@@ -110,24 +105,18 @@ public class FeignClientBuilderTests {
assertFactoryBeanField(builder, "contextId", "TestClient");
// and:
assertFactoryBeanField(builder, "url",
getDefaultValueFromFeignClientAnnotation("url"));
assertFactoryBeanField(builder, "path",
getDefaultValueFromFeignClientAnnotation("path"));
assertFactoryBeanField(builder, "decode404",
getDefaultValueFromFeignClientAnnotation("decode404"));
assertFactoryBeanField(builder, "fallback",
getDefaultValueFromFeignClientAnnotation("fallback"));
assertFactoryBeanField(builder, "fallbackFactory",
getDefaultValueFromFeignClientAnnotation("fallbackFactory"));
assertFactoryBeanField(builder, "url", getDefaultValueFromFeignClientAnnotation("url"));
assertFactoryBeanField(builder, "path", getDefaultValueFromFeignClientAnnotation("path"));
assertFactoryBeanField(builder, "decode404", getDefaultValueFromFeignClientAnnotation("decode404"));
assertFactoryBeanField(builder, "fallback", getDefaultValueFromFeignClientAnnotation("fallback"));
assertFactoryBeanField(builder, "fallbackFactory", getDefaultValueFromFeignClientAnnotation("fallbackFactory"));
}
@Test
public void forType_allFieldsSetOnBuilder() {
// when:
final FeignClientBuilder.Builder builder = this.feignClientBuilder
.forType(TestFeignClient.class, "TestClient").decode404(true).url("Url/")
.path("/Path").contextId("TestContext");
final FeignClientBuilder.Builder builder = this.feignClientBuilder.forType(TestFeignClient.class, "TestClient")
.decode404(true).url("Url/").path("/Path").contextId("TestContext");
// then:
assertFactoryBeanField(builder, "applicationContext", this.applicationContext);
@@ -146,9 +135,8 @@ public class FeignClientBuilderTests {
public void forType_clientFactoryBeanProvided() {
// when:
final FeignClientBuilder.Builder builder = this.feignClientBuilder
.forType(TestFeignClient.class, new FeignClientFactoryBean(),
"TestClient")
.decode404(true).path("Path/").url("Url/").contextId("TestContext");
.forType(TestFeignClient.class, new FeignClientFactoryBean(), "TestClient").decode404(true)
.path("Path/").url("Url/").contextId("TestContext");
// then:
assertFactoryBeanField(builder, "applicationContext", this.applicationContext);
@@ -165,12 +153,14 @@ public class FeignClientBuilderTests {
@Test
public void forType_build() {
// given:
Mockito.when(this.applicationContext.getBean(FeignContext.class))
.thenThrow(new ClosedFileSystemException()); // throw an unusual exception
// in the
// FeignClientFactoryBean
final FeignClientBuilder.Builder builder = this.feignClientBuilder
.forType(TestClient.class, "TestClient");
Mockito.when(this.applicationContext.getBean(FeignContext.class)).thenThrow(new ClosedFileSystemException()); // throw
// an
// unusual
// exception
// in
// the
// FeignClientFactoryBean
final FeignClientBuilder.Builder builder = this.feignClientBuilder.forType(TestClient.class, "TestClient");
// expect: 'the build will fail right after calling build() with the mocked
// unusual exception'
@@ -67,8 +67,7 @@ public class FeignClientErrorDecoderTests {
@Test
public void errorDecoderInConfiguration() {
assertThat(this.context.getInstance("foo", ErrorDecoder.class))
.isInstanceOf(ErrorDecoder.Default.class);
assertThat(this.context.getInstance("foo", ErrorDecoder.class)).isInstanceOf(ErrorDecoder.Default.class);
assertThat(this.context.getInstance("bar", ErrorDecoder.class)).isNull();
}
@@ -90,8 +89,7 @@ public class FeignClientErrorDecoderTests {
Map<Method, InvocationHandlerFactory.MethodHandler> dispatch = (Map<Method, InvocationHandlerFactory.MethodHandler>) ReflectionTestUtils
.getField(invocationHandler, "dispatch");
Method key = new ArrayList<>(dispatch.keySet()).get(0);
return ReflectionTestUtils.getField(
ReflectionTestUtils.getField(dispatch.get(key), "asyncResponseHandler"),
return ReflectionTestUtils.getField(ReflectionTestUtils.getField(dispatch.get(key), "asyncResponseHandler"),
"errorDecoder");
}
@@ -53,8 +53,7 @@ public class FeignClientFactoryTests {
parent.refresh();
FeignContext context = new FeignContext();
context.setApplicationContext(parent);
context.setConfigurations(Arrays.asList(getSpec("foo", FooConfig.class),
getSpec("bar", BarConfig.class)));
context.setConfigurations(Arrays.asList(getSpec("foo", FooConfig.class), getSpec("bar", BarConfig.class)));
Foo foo = context.getInstance("foo", Foo.class);
assertThat(foo).as("foo was null").isNotNull();
@@ -68,8 +67,7 @@ public class FeignClientFactoryTests {
@Test
public void shouldRedirectToDelegateWhenUrlSet() {
new ApplicationContextRunner().withUserConfiguration(TestConfig.class)
.run(this::defaultClientUsed);
new ApplicationContextRunner().withUserConfiguration(TestConfig.class).run(this::defaultClientUsed);
}
@SuppressWarnings({ "unchecked", "ConstantConditions" })
@@ -99,16 +97,14 @@ public class FeignClientFactoryTests {
@Bean
BlockingLoadBalancerClient loadBalancerClient() {
return new BlockingLoadBalancerClient(new LoadBalancerClientFactory(),
new LoadBalancerProperties());
return new BlockingLoadBalancerClient(new LoadBalancerClientFactory(), new LoadBalancerProperties());
}
@Bean
FeignContext feignContext() {
FeignContext feignContext = new FeignContext();
feignContext.setConfigurations(
Collections.singletonList(new FeignClientSpecification("test",
new Class[] { LoadBalancerAutoConfiguration.class })));
feignContext.setConfigurations(Collections.singletonList(
new FeignClientSpecification("test", new Class[] { LoadBalancerAutoConfiguration.class })));
return feignContext;
}
@@ -23,7 +23,6 @@ import feign.QueryMapEncoder;
import feign.Request;
import feign.RequestInterceptor;
import feign.RequestLine;
import feign.RequestTemplate;
import feign.Retryer;
import feign.auth.BasicAuthRequestInterceptor;
import feign.codec.Decoder;
@@ -32,8 +31,7 @@ import feign.codec.ErrorDecoder;
import feign.optionals.OptionalDecoder;
import feign.querymap.BeanQueryMapEncoder;
import feign.slf4j.Slf4jLogger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
@@ -43,7 +41,6 @@ import org.springframework.cloud.openfeign.support.SpringMvcContract;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@@ -52,10 +49,9 @@ import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Spencer Gibb
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = FeignClientOverrideDefaultsTests.TestConfiguration.class)
@DirtiesContext
public class FeignClientOverrideDefaultsTests {
class FeignClientOverrideDefaultsTests {
@Autowired
private FeignContext context;
@@ -67,90 +63,81 @@ public class FeignClientOverrideDefaultsTests {
private BarClient bar;
@Test
public void clientsAvailable() {
assertThat(this.foo).isNotNull();
assertThat(this.bar).isNotNull();
void clientsAvailable() {
assertThat(foo).isNotNull();
assertThat(bar).isNotNull();
}
@Test
public void overrideDecoder() {
Decoder.Default.class.cast(this.context.getInstance("foo", Decoder.class));
OptionalDecoder.class.cast(this.context.getInstance("bar", Decoder.class));
void overrideDecoder() {
Decoder.Default.class.cast(context.getInstance("foo", Decoder.class));
OptionalDecoder.class.cast(context.getInstance("bar", Decoder.class));
}
@Test
public void overrideEncoder() {
Encoder.Default.class.cast(this.context.getInstance("foo", Encoder.class));
PageableSpringEncoder.class.cast(this.context.getInstance("bar", Encoder.class));
void overrideEncoder() {
Encoder.Default.class.cast(context.getInstance("foo", Encoder.class));
PageableSpringEncoder.class.cast(context.getInstance("bar", Encoder.class));
}
@Test
public void overrideLogger() {
Logger.JavaLogger.class.cast(this.context.getInstance("foo", Logger.class));
Slf4jLogger.class.cast(this.context.getInstance("bar", Logger.class));
void overrideLogger() {
Logger.JavaLogger.class.cast(context.getInstance("foo", Logger.class));
Slf4jLogger.class.cast(context.getInstance("bar", Logger.class));
}
@Test
public void overrideContract() {
Contract.Default.class.cast(this.context.getInstance("foo", Contract.class));
SpringMvcContract.class.cast(this.context.getInstance("bar", Contract.class));
void overrideContract() {
Contract.Default.class.cast(context.getInstance("foo", Contract.class));
SpringMvcContract.class.cast(context.getInstance("bar", Contract.class));
}
@Test
public void overrideLoggerLevel() {
assertThat(this.context.getInstance("foo", Logger.Level.class)).isNull();
assertThat(this.context.getInstance("bar", Logger.Level.class))
.isEqualTo(Logger.Level.HEADERS);
void overrideLoggerLevel() {
assertThat(context.getInstance("foo", Logger.Level.class)).isNull();
assertThat(context.getInstance("bar", Logger.Level.class)).isEqualTo(Logger.Level.HEADERS);
}
@Test
public void overrideRetryer() {
assertThat(this.context.getInstance("foo", Retryer.class))
.isEqualTo(Retryer.NEVER_RETRY);
Retryer.Default.class.cast(this.context.getInstance("bar", Retryer.class));
void overrideRetryer() {
assertThat(context.getInstance("foo", Retryer.class)).isEqualTo(Retryer.NEVER_RETRY);
Retryer.Default.class.cast(context.getInstance("bar", Retryer.class));
}
@Test
public void overrideErrorDecoder() {
assertThat(this.context.getInstance("foo", ErrorDecoder.class)).isNull();
ErrorDecoder.Default.class
.cast(this.context.getInstance("bar", ErrorDecoder.class));
void overrideErrorDecoder() {
assertThat(context.getInstance("foo", ErrorDecoder.class)).isNull();
ErrorDecoder.Default.class.cast(context.getInstance("bar", ErrorDecoder.class));
}
@Test
public void overrideRequestOptions() {
assertThat(this.context.getInstance("foo", Request.Options.class)).isNull();
Request.Options options = this.context.getInstance("bar", Request.Options.class);
void overrideRequestOptions() {
assertThat(context.getInstance("foo", Request.Options.class)).isNull();
Request.Options options = context.getInstance("bar", Request.Options.class);
assertThat(options.connectTimeoutMillis()).isEqualTo(1);
assertThat(options.readTimeoutMillis()).isEqualTo(1);
}
@Test
public void overrideQueryMapEncoder() {
QueryMapEncoder.Default.class
.cast(this.context.getInstance("foo", QueryMapEncoder.class));
BeanQueryMapEncoder.class
.cast(this.context.getInstance("bar", QueryMapEncoder.class));
void overrideQueryMapEncoder() {
QueryMapEncoder.Default.class.cast(context.getInstance("foo", QueryMapEncoder.class));
BeanQueryMapEncoder.class.cast(context.getInstance("bar", QueryMapEncoder.class));
}
@Test
public void addRequestInterceptor() {
assertThat(this.context.getInstances("foo", RequestInterceptor.class).size())
.isEqualTo(1);
assertThat(this.context.getInstances("bar", RequestInterceptor.class).size())
.isEqualTo(2);
void addRequestInterceptor() {
assertThat(context.getInstances("foo", RequestInterceptor.class).size()).isEqualTo(1);
assertThat(context.getInstances("bar", RequestInterceptor.class).size()).isEqualTo(2);
}
@Test
public void exceptionPropagationPolicy() {
assertThat(this.context.getInstances("foo", ExceptionPropagationPolicy.class))
.isNull();
assertThat(this.context.getInstances("bar", ExceptionPropagationPolicy.class))
void exceptionPropagationPolicy() {
assertThat(context.getInstances("foo", ExceptionPropagationPolicy.class)).isEmpty();
assertThat(context.getInstances("bar", ExceptionPropagationPolicy.class))
.containsValues(ExceptionPropagationPolicy.UNWRAP);
}
@FeignClient(name = "foo", url = "https://foo",
configuration = FooConfiguration.class)
@FeignClient(name = "foo", url = "https://foo", configuration = FooConfiguration.class)
interface FooClient {
@RequestLine("GET /")
@@ -158,8 +145,7 @@ public class FeignClientOverrideDefaultsTests {
}
@FeignClient(name = "bar", url = "https://bar",
configuration = BarConfiguration.class)
@FeignClient(name = "bar", url = "https://bar", configuration = BarConfiguration.class)
interface BarClient {
@RequestMapping(value = "/", method = RequestMethod.GET)
@@ -174,10 +160,7 @@ public class FeignClientOverrideDefaultsTests {
@Bean
RequestInterceptor defaultRequestInterceptor() {
return new RequestInterceptor() {
@Override
public void apply(RequestTemplate template) {
}
return template -> {
};
}
@@ -63,11 +63,9 @@ public class FeignClientUsingConfigurerTest {
.getBean(BEAN_NAME_PREFIX + "TestFeignClient");
Feign.Builder builder = factoryBean.feign(context);
List<RequestInterceptor> interceptors = (List) getBuilderValue(builder,
"requestInterceptors");
List<RequestInterceptor> interceptors = (List) getBuilderValue(builder, "requestInterceptors");
assertThat(interceptors.size()).as("interceptors not set").isEqualTo(3);
assertThat(getBuilderValue(builder, "logLevel")).as("log level not set")
.isEqualTo(Logger.Level.FULL);
assertThat(getBuilderValue(builder, "logLevel")).as("log level not set").isEqualTo(Logger.Level.FULL);
}
private Object getBuilderValue(Feign.Builder builder, String member) {
@@ -83,12 +81,10 @@ public class FeignClientUsingConfigurerTest {
.getBean(BEAN_NAME_PREFIX + "NoInheritFeignClient");
Feign.Builder builder = factoryBean.feign(context);
List<RequestInterceptor> interceptors = (List) getBuilderValue(builder,
"requestInterceptors");
List<RequestInterceptor> interceptors = (List) getBuilderValue(builder, "requestInterceptors");
assertThat(interceptors).as("interceptors not set").isEmpty();
assertThat(factoryBean.isInheritParentContext())
.as("is inheriting from parent configuration").isFalse();
assertThat(factoryBean.isInheritParentContext()).as("is inheriting from parent configuration").isFalse();
}
@Test
@@ -97,8 +93,7 @@ public class FeignClientUsingConfigurerTest {
.getBean(BEAN_NAME_PREFIX + "NoInheritFeignClient");
Feign.Builder builder = factoryBean.feign(context);
assertThat(getBuilderValue(builder, "logLevel")).as("log level not set")
.isEqualTo(Logger.Level.HEADERS);
assertThat(getBuilderValue(builder, "logLevel")).as("log level not set").isEqualTo(Logger.Level.HEADERS);
}
@EnableAutoConfiguration
@@ -140,8 +135,7 @@ public class FeignClientUsingConfigurerTest {
}
@FeignClient(name = "noInheritFeignClient",
configuration = NoInheritConfiguration.class)
@FeignClient(name = "noInheritFeignClient", configuration = NoInheritConfiguration.class)
interface NoInheritFeignClient {
}
@@ -22,9 +22,15 @@ import java.lang.reflect.Proxy;
import java.lang.reflect.Type;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.servlet.http.HttpServletRequest;
@@ -55,8 +61,11 @@ import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import static org.assertj.core.api.Assertions.assertThat;
@@ -66,11 +75,11 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
/**
* @author Eko Kurniawan Khannedy
* @author Olga Maciaszek-Sharma
* @author Ilia Ilinykh
*/
@SuppressWarnings("FieldMayBeFinal")
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = FeignClientUsingPropertiesTests.Application.class,
webEnvironment = RANDOM_PORT)
@SpringBootTest(classes = FeignClientUsingPropertiesTests.Application.class, webEnvironment = RANDOM_PORT)
@TestPropertySource("classpath:feign-properties.properties")
@DirtiesContext
public class FeignClientUsingPropertiesTests {
@@ -92,6 +101,10 @@ public class FeignClientUsingPropertiesTests {
private FeignClientFactoryBean formFactoryBean;
private FeignClientFactoryBean defaultHeadersAndQuerySingleParamsFeignClientFactoryBean;
private FeignClientFactoryBean defaultHeadersAndQueryMultipleParamsFeignClientFactoryBean;
public FeignClientUsingPropertiesTests() {
fooFactoryBean = new FeignClientFactoryBean();
fooFactoryBean.setContextId("foo");
@@ -108,30 +121,34 @@ public class FeignClientUsingPropertiesTests {
formFactoryBean = new FeignClientFactoryBean();
formFactoryBean.setContextId("form");
formFactoryBean.setType(FeignClientFactoryBean.class);
this.defaultHeadersAndQuerySingleParamsFeignClientFactoryBean = new FeignClientFactoryBean();
this.defaultHeadersAndQuerySingleParamsFeignClientFactoryBean.setContextId("singleValue");
this.defaultHeadersAndQuerySingleParamsFeignClientFactoryBean.setType(FeignClientFactoryBean.class);
this.defaultHeadersAndQueryMultipleParamsFeignClientFactoryBean = new FeignClientFactoryBean();
this.defaultHeadersAndQueryMultipleParamsFeignClientFactoryBean.setContextId("multipleValue");
this.defaultHeadersAndQueryMultipleParamsFeignClientFactoryBean.setType(FeignClientFactoryBean.class);
}
public FooClient fooClient() {
fooFactoryBean.setApplicationContext(applicationContext);
return fooFactoryBean.feign(context).target(FooClient.class,
"http://localhost:" + port);
return fooFactoryBean.feign(context).target(FooClient.class, "http://localhost:" + port);
}
public BarClient barClient() {
barFactoryBean.setApplicationContext(applicationContext);
return barFactoryBean.feign(context).target(BarClient.class,
"http://localhost:" + port);
return barFactoryBean.feign(context).target(BarClient.class, "http://localhost:" + port);
}
public UnwrapClient unwrapClient() {
unwrapFactoryBean.setApplicationContext(applicationContext);
return unwrapFactoryBean.feign(context).target(UnwrapClient.class,
"http://localhost:" + port);
return unwrapFactoryBean.feign(context).target(UnwrapClient.class, "http://localhost:" + port);
}
public FormClient formClient() {
formFactoryBean.setApplicationContext(applicationContext);
return formFactoryBean.feign(context).target(FormClient.class,
"http://localhost:" + port);
return formFactoryBean.feign(context).target(FormClient.class, "http://localhost:" + port);
}
@Test
@@ -159,6 +176,30 @@ public class FeignClientUsingPropertiesTests {
assertThat(response).isEqualTo("Data");
}
@Test
public void testSingleValue() {
List<String> response = singleValueClient().singleValue();
assertThat(response).isEqualTo(Arrays.asList("header", "parameter"));
}
@Test
public void testMultipleValue() {
List<String> response = multipleValueClient().multipleValue();
assertThat(response).isEqualTo(Arrays.asList("header1", "header2", "parameter1", "parameter2"));
}
public SingleValueClient singleValueClient() {
this.defaultHeadersAndQuerySingleParamsFeignClientFactoryBean.setApplicationContext(this.applicationContext);
return this.defaultHeadersAndQuerySingleParamsFeignClientFactoryBean.feign(this.context)
.target(SingleValueClient.class, "http://localhost:" + this.port);
}
public MultipleValueClient multipleValueClient() {
this.defaultHeadersAndQueryMultipleParamsFeignClientFactoryBean.setApplicationContext(this.applicationContext);
return this.defaultHeadersAndQueryMultipleParamsFeignClientFactoryBean.feign(this.context)
.target(MultipleValueClient.class, "http://localhost:" + this.port);
}
@Test
public void readTimeoutShouldWorkWhenConnectTimeoutNotSet() {
FeignClientFactoryBean readTimeoutFactoryBean = new FeignClientFactoryBean();
@@ -166,8 +207,8 @@ public class FeignClientUsingPropertiesTests {
readTimeoutFactoryBean.setType(FeignClientFactoryBean.class);
readTimeoutFactoryBean.setApplicationContext(applicationContext);
TimeoutClient client = readTimeoutFactoryBean.feign(context)
.target(TimeoutClient.class, "http://localhost:" + port);
TimeoutClient client = readTimeoutFactoryBean.feign(context).target(TimeoutClient.class,
"http://localhost:" + port);
Request.Options options = getRequestOptions((Proxy) client);
@@ -182,8 +223,8 @@ public class FeignClientUsingPropertiesTests {
readTimeoutFactoryBean.setType(FeignClientFactoryBean.class);
readTimeoutFactoryBean.setApplicationContext(applicationContext);
TimeoutClient client = readTimeoutFactoryBean.feign(context)
.target(TimeoutClient.class, "http://localhost:" + port);
TimeoutClient client = readTimeoutFactoryBean.feign(context).target(TimeoutClient.class,
"http://localhost:" + port);
Request.Options options = getRequestOptions((Proxy) client);
@@ -196,27 +237,26 @@ public class FeignClientUsingPropertiesTests {
Map<Method, InvocationHandlerFactory.MethodHandler> dispatch = (Map<Method, InvocationHandlerFactory.MethodHandler>) ReflectionTestUtils
.getField(Objects.requireNonNull(invocationHandler), "dispatch");
Method key = new ArrayList<>(dispatch.keySet()).get(0);
return (Request.Options) ReflectionTestUtils.getField(dispatch.get(key),
"options");
return (Request.Options) ReflectionTestUtils.getField(dispatch.get(key), "options");
}
protected interface FooClient {
@RequestMapping(method = RequestMethod.GET, value = "/foo")
@GetMapping(path = "/foo")
String foo();
}
protected interface BarClient {
@RequestMapping(method = RequestMethod.GET, value = "/bar")
@GetMapping(path = "/bar")
String bar();
}
protected interface UnwrapClient {
@RequestMapping(method = RequestMethod.GET, value = "/bar") // intentionally /bar
@GetMapping(path = "/bar") // intentionally /bar
String unwrap() throws IOException;
}
@@ -229,6 +269,20 @@ public class FeignClientUsingPropertiesTests {
}
protected interface SingleValueClient {
@GetMapping(path = "/singleValue")
List<String> singleValue();
}
protected interface MultipleValueClient {
@GetMapping(path = "/multipleValue")
List<String> multipleValue();
}
protected interface TimeoutClient {
@GetMapping("/timeouts")
@@ -244,8 +298,7 @@ public class FeignClientUsingPropertiesTests {
@RequestMapping(method = RequestMethod.GET, value = "/foo")
public String foo(HttpServletRequest request) throws IllegalAccessException {
if ("Foo".equals(request.getHeader("Foo"))
&& "Bar".equals(request.getHeader("Bar"))) {
if ("Foo".equals(request.getHeader("Foo")) && "Bar".equals(request.getHeader("Bar"))) {
return "OK";
}
else {
@@ -253,18 +306,31 @@ public class FeignClientUsingPropertiesTests {
}
}
@RequestMapping(method = RequestMethod.GET, value = "/bar")
@GetMapping(path = "/bar")
public String bar() throws InterruptedException {
Thread.sleep(2000L);
TimeUnit.SECONDS.sleep(2);
return "OK";
}
@RequestMapping(value = "/form", method = RequestMethod.POST,
consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
@PostMapping(path = "/form", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public String form(HttpServletRequest request) {
return request.getParameter("form");
}
@GetMapping(path = "/singleValue")
public List<String> singleValue(@RequestHeader List<String> singleValueHeaders,
@RequestParam List<String> singleValueParameters) {
return Stream.of(singleValueHeaders, singleValueParameters).flatMap(Collection::stream)
.collect(Collectors.toList());
}
@GetMapping(path = "/multipleValue")
public List<String> multipleValue(@RequestHeader List<String> multipleValueHeaders,
@RequestParam List<String> multipleValueParameters) {
return Stream.of(multipleValueHeaders, multipleValueParameters).flatMap(Collection::stream)
.collect(Collectors.toList());
}
}
public static class FooRequestInterceptor implements RequestInterceptor {
@@ -306,16 +372,14 @@ public class FeignClientUsingPropertiesTests {
public static class FormEncoder implements Encoder {
@Override
public void encode(Object o, Type type, RequestTemplate requestTemplate)
throws EncodeException {
public void encode(Object o, Type type, RequestTemplate requestTemplate) throws EncodeException {
Map<String, String> form = (Map<String, String>) o;
StringBuilder builder = new StringBuilder();
form.forEach((key, value) -> {
builder.append(key + "=" + value + "&");
});
requestTemplate.header(HttpHeaders.CONTENT_TYPE,
MediaType.APPLICATION_FORM_URLENCODED_VALUE);
requestTemplate.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE);
requestTemplate.body(builder.toString());
}
@@ -20,6 +20,7 @@ import java.util.Collections;
import org.junit.Test;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;
@@ -28,10 +29,12 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
/**
* @author Spencer Gibb
* @author Gang Li
* @author Michal Domagala
*/
public class FeignClientsRegistrarTests {
@@ -89,8 +92,18 @@ public class FeignClientsRegistrarTests {
new AnnotationConfigApplicationContext(FallbackFactoryTestConfig.class);
}
@FeignClient(name = "fallbackTestClient", url = "http://localhost:8080/",
fallback = FallbackClient.class)
@Test
public void shouldPassSubLevelFeignClient() {
AnnotationConfigApplicationContext config = new AnnotationConfigApplicationContext();
((DefaultListableBeanFactory) config.getBeanFactory()).setAllowBeanDefinitionOverriding(false);
config.register(TopLevelSubLevelTestConfig.class);
assertThatCode(() -> config.refresh())
.as("Case https://github.com/spring-cloud/spring-cloud-openfeign/issues/331 should be solved")
.doesNotThrowAnyException();
}
@FeignClient(name = "fallbackTestClient", url = "http://localhost:8080/", fallback = FallbackClient.class)
protected interface FallbackClient {
@RequestMapping(method = RequestMethod.GET, value = "/hello")
@@ -116,10 +129,15 @@ public class FeignClientsRegistrarTests {
@Configuration(proxyBeanMethods = false)
@EnableAutoConfiguration
@EnableFeignClients(
clients = { FeignClientsRegistrarTests.FallbackFactoryClient.class })
@EnableFeignClients(clients = { FeignClientsRegistrarTests.FallbackFactoryClient.class })
protected static class FallbackFactoryTestConfig {
}
@EnableFeignClients(clients = { org.springframework.cloud.openfeign.feignclientsregistrar.TopLevelClient.class,
org.springframework.cloud.openfeign.feignclientsregistrar.sub.SubLevelClient.class })
protected static class TopLevelSubLevelTestConfig {
}
}
@@ -50,17 +50,15 @@ public class FeignCompressionTests {
@Test
public void testInterceptors() {
new ApplicationContextRunner()
.withPropertyValues("feign.compression.response.enabled=true",
"feign.compression.request.enabled=true",
.withPropertyValues("feign.compression.response.enabled=true", "feign.compression.request.enabled=true",
"feign.okhttp.enabled=false")
.withConfiguration(AutoConfigurations.of(FeignAutoConfiguration.class,
FeignContentGzipEncodingAutoConfiguration.class,
FeignAcceptGzipEncodingAutoConfiguration.class,
FeignContentGzipEncodingAutoConfiguration.class, FeignAcceptGzipEncodingAutoConfiguration.class,
HttpClientConfiguration.class, PlainConfig.class))
.run(context -> {
FeignContext feignContext = context.getBean(FeignContext.class);
Map<String, RequestInterceptor> interceptors = feignContext
.getInstances("foo", RequestInterceptor.class);
Map<String, RequestInterceptor> interceptors = feignContext.getInstances("foo",
RequestInterceptor.class);
assertThat(interceptors.size()).isEqualTo(2);
assertThat(interceptors.get("feignAcceptGzipEncodingInterceptor"))
.isInstanceOf(FeignAcceptGzipEncodingInterceptor.class);
@@ -39,11 +39,9 @@ public class FeignContextTest {
FeignContext feignContext = new FeignContext();
feignContext.setApplicationContext(parent);
feignContext.setConfigurations(
Lists.newArrayList(getSpec("empty", EmptyConfiguration.class)));
feignContext.setConfigurations(Lists.newArrayList(getSpec("empty", EmptyConfiguration.class)));
Logger.Level level = feignContext.getInstanceWithoutAncestors("empty",
Logger.Level.class);
Logger.Level level = feignContext.getInstanceWithoutAncestors("empty", Logger.Level.class);
assertThat(level).as("Logger was not null").isNull();
}
@@ -59,8 +57,7 @@ public class FeignContextTest {
FeignContext feignContext = new FeignContext();
feignContext.setApplicationContext(parent);
feignContext.setConfigurations(
Lists.newArrayList(getSpec("empty", EmptyConfiguration.class)));
feignContext.setConfigurations(Lists.newArrayList(getSpec("empty", EmptyConfiguration.class)));
Collection<RequestInterceptor> interceptors = feignContext
.getInstancesWithoutAncestors("empty", RequestInterceptor.class).values();
@@ -75,11 +72,9 @@ public class FeignContextTest {
FeignContext feignContext = new FeignContext();
feignContext.setApplicationContext(parent);
feignContext.setConfigurations(
Lists.newArrayList(getSpec("demo", DemoConfiguration.class)));
feignContext.setConfigurations(Lists.newArrayList(getSpec("demo", DemoConfiguration.class)));
Logger.Level level = feignContext.getInstanceWithoutAncestors("demo",
Logger.Level.class);
Logger.Level level = feignContext.getInstanceWithoutAncestors("demo", Logger.Level.class);
assertThat(level).isEqualTo(Logger.Level.FULL);
}
@@ -91,8 +86,7 @@ public class FeignContextTest {
FeignContext feignContext = new FeignContext();
feignContext.setApplicationContext(parent);
feignContext.setConfigurations(
Lists.newArrayList(getSpec("demo", DemoConfiguration.class)));
feignContext.setConfigurations(Lists.newArrayList(getSpec("demo", DemoConfiguration.class)));
Collection<RequestInterceptor> interceptors = feignContext
.getInstancesWithoutAncestors("demo", RequestInterceptor.class).values();
@@ -34,20 +34,16 @@ public class FeignErrorDecoderFactoryTests {
@Test
public void testNoDefaultFactory() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
SampleConfiguration1.class);
String[] beanNamesForType = context
.getBeanNamesForType(FeignErrorDecoderFactory.class);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SampleConfiguration1.class);
String[] beanNamesForType = context.getBeanNamesForType(FeignErrorDecoderFactory.class);
assertThat(beanNamesForType).isEmpty();
context.close();
}
@Test
public void testCustomErrorDecoderFactory() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
SampleConfiguration2.class);
FeignErrorDecoderFactory errorDecoderFactory = context
.getBean(FeignErrorDecoderFactory.class);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SampleConfiguration2.class);
FeignErrorDecoderFactory errorDecoderFactory = context.getBean(FeignErrorDecoderFactory.class);
assertThat(errorDecoderFactory).isNotNull();
ErrorDecoder errorDecoder = errorDecoderFactory.create(Object.class);
assertThat(errorDecoder).isNotNull();
@@ -57,10 +53,8 @@ public class FeignErrorDecoderFactoryTests {
@Test
public void testCustomErrorDecoderFactoryNotOverwritingErrorDecoder() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
SampleConfiguration3.class);
FeignErrorDecoderFactory errorDecoderFactory = context
.getBean(FeignErrorDecoderFactory.class);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SampleConfiguration3.class);
FeignErrorDecoderFactory errorDecoderFactory = context.getBean(FeignErrorDecoderFactory.class);
assertThat(errorDecoderFactory).isNotNull();
ErrorDecoder errorDecoderFromFactory = errorDecoderFactory.create(Object.class);
assertThat(errorDecoderFromFactory).isNotNull();
@@ -53,10 +53,8 @@ public class FeignHttpClientConfigurationTests {
@Before
public void setUp() {
this.context = new SpringApplicationBuilder()
.properties("debug=true", "feign.httpclient.disableSslValidation=true")
.web(WebApplicationType.NONE)
.sources(HttpClientConfiguration.class, FeignAutoConfiguration.class)
.run();
.properties("debug=true", "feign.httpclient.disableSslValidation=true").web(WebApplicationType.NONE)
.sources(HttpClientConfiguration.class, FeignAutoConfiguration.class).run();
}
@After
@@ -68,13 +66,10 @@ public class FeignHttpClientConfigurationTests {
@Test
public void disableSslTest() throws Exception {
HttpClientConnectionManager connectionManager = this.context
.getBean(HttpClientConnectionManager.class);
Lookup<ConnectionSocketFactory> socketFactoryRegistry = getConnectionSocketFactoryLookup(
connectionManager);
HttpClientConnectionManager connectionManager = this.context.getBean(HttpClientConnectionManager.class);
Lookup<ConnectionSocketFactory> socketFactoryRegistry = getConnectionSocketFactoryLookup(connectionManager);
assertThat(socketFactoryRegistry.lookup("https")).isNotNull();
assertThat(this.getX509TrustManager(socketFactoryRegistry).getAcceptedIssuers())
.isNull();
assertThat(this.getX509TrustManager(socketFactoryRegistry).getAcceptedIssuers()).isNull();
}
private Lookup<ConnectionSocketFactory> getConnectionSocketFactoryLookup(
@@ -84,14 +79,11 @@ public class FeignHttpClientConfigurationTests {
return (Lookup) this.getField(connectionOperator, "socketFactoryRegistry");
}
private X509TrustManager getX509TrustManager(
Lookup<ConnectionSocketFactory> socketFactoryRegistry) {
private X509TrustManager getX509TrustManager(Lookup<ConnectionSocketFactory> socketFactoryRegistry) {
ConnectionSocketFactory connectionSocketFactory = (ConnectionSocketFactory) socketFactoryRegistry
.lookup("https");
SSLSocketFactory sslSocketFactory = (SSLSocketFactory) this
.getField(connectionSocketFactory, "socketfactory");
SSLContextSpi sslContext = (SSLContextSpi) this.getField(sslSocketFactory,
"context");
SSLSocketFactory sslSocketFactory = (SSLSocketFactory) this.getField(connectionSocketFactory, "socketfactory");
SSLContextSpi sslContext = (SSLContextSpi) this.getField(sslSocketFactory, "context");
return (X509TrustManager) this.getField(sslContext, "trustManager");
}
@@ -23,10 +23,9 @@ import feign.Client;
import feign.Feign;
import feign.Target;
import feign.httpclient.ApacheHttpClient;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
@@ -36,7 +35,6 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.SocketUtils;
import org.springframework.web.bind.annotation.RequestMapping;
@@ -49,13 +47,11 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
/**
* @author Spencer Gibb
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = FeignHttpClientUrlTests.TestConfig.class,
webEnvironment = DEFINED_PORT,
value = { "spring.application.name=feignclienturltest",
"feign.hystrix.enabled=false", "feign.okhttp.enabled=false" })
@SpringBootTest(classes = FeignHttpClientUrlTests.TestConfig.class, webEnvironment = DEFINED_PORT,
value = { "spring.application.name=feignclienturltest", "feign.hystrix.enabled=false",
"feign.okhttp.enabled=false", "spring.cloud.loadbalancer.retry.enabled=false" })
@DirtiesContext
public class FeignHttpClientUrlTests {
class FeignHttpClientUrlTests {
static int port;
@@ -68,40 +64,37 @@ public class FeignHttpClientUrlTests {
@Autowired
private BeanUrlClient beanClient;
@BeforeClass
@BeforeAll
public static void beforeClass() {
port = SocketUtils.findAvailableTcpPort();
System.setProperty("server.port", String.valueOf(port));
}
@AfterClass
@AfterAll
public static void afterClass() {
System.clearProperty("server.port");
}
@Test
public void testUrlHttpClient() {
assertThat(this.urlClient).as("UrlClient was null").isNotNull();
Hello hello = this.urlClient.getHello();
void testUrlHttpClient() {
assertThat(urlClient).as("UrlClient was null").isNotNull();
Hello hello = urlClient.getHello();
assertThat(hello).as("hello was null").isNotNull();
assertThat(hello).as("first hello didn't match")
.isEqualTo(new Hello("hello world 1"));
assertThat(hello).as("first hello didn't match").isEqualTo(new Hello("hello world 1"));
}
@Test
public void testBeanUrl() {
Hello hello = this.beanClient.getHello();
void testBeanUrl() {
Hello hello = beanClient.getHello();
assertThat(hello).as("hello was null").isNotNull();
assertThat(hello).as("first hello didn't match")
.isEqualTo(new Hello("hello world 1"));
assertThat(hello).as("first hello didn't match").isEqualTo(new Hello("hello world 1"));
}
@Test
public void testBeanUrlNoProtocol() {
Hello hello = this.beanClientNoProtocol.getHello();
Hello hello = beanClientNoProtocol.getHello();
assertThat(hello).as("hello was null").isNotNull();
assertThat(hello).as("first hello didn't match")
.isEqualTo(new Hello("hello world 1"));
assertThat(hello).as("first hello didn't match").isEqualTo(new Hello("hello world 1"));
}
// this tests that
@@ -132,8 +125,7 @@ public class FeignHttpClientUrlTests {
@Configuration(proxyBeanMethods = false)
@EnableAutoConfiguration
@RestController
@EnableFeignClients(clients = { UrlClient.class, BeanUrlClient.class,
BeanUrlClientNoProtocol.class })
@EnableFeignClients(clients = { UrlClient.class, BeanUrlClient.class, BeanUrlClientNoProtocol.class })
@Import(NoSecurityConfiguration.class)
protected static class TestConfig {
@@ -161,15 +153,13 @@ public class FeignHttpClientUrlTests {
public Targeter feignTargeter() {
return new Targeter() {
@Override
public <T> T target(FeignClientFactoryBean factory, Feign.Builder feign,
FeignContext context, Target.HardCodedTarget<T> target) {
Field field = ReflectionUtils.findField(Feign.Builder.class,
"client");
public <T> T target(FeignClientFactoryBean factory, Feign.Builder feign, FeignContext context,
Target.HardCodedTarget<T> target) {
Field field = ReflectionUtils.findField(Feign.Builder.class, "client");
ReflectionUtils.makeAccessible(field);
Client client = (Client) ReflectionUtils.getField(field, feign);
if (target.name().equals("localappurl")) {
assertThat(client).isInstanceOf(ApacheHttpClient.class)
.as("client was wrong type");
assertThat(client).isInstanceOf(ApacheHttpClient.class).as("client was wrong type");
}
return feign.target(target);
}
@@ -182,15 +172,15 @@ public class FeignHttpClientUrlTests {
private String message;
public Hello() {
Hello() {
}
public Hello(String message) {
Hello(String message) {
this.message = message;
}
public String getMessage() {
return this.message;
return message;
}
public void setMessage(String message) {
@@ -206,12 +196,12 @@ public class FeignHttpClientUrlTests {
return false;
}
Hello that = (Hello) o;
return Objects.equals(this.message, that.message);
return Objects.equals(message, that.message);
}
@Override
public int hashCode() {
return Objects.hash(this.message);
return Objects.hash(message);
}
}
@@ -34,8 +34,7 @@ public class FeignLoggerFactoryTests {
@Test
public void testDefaultLogger() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
SampleConfiguration1.class);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SampleConfiguration1.class);
FeignLoggerFactory loggerFactory = context.getBean(FeignLoggerFactory.class);
assertThat(loggerFactory).isNotNull();
Logger logger = loggerFactory.create(Object.class);
@@ -46,8 +45,7 @@ public class FeignLoggerFactoryTests {
@Test
public void testCustomLogger() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
SampleConfiguration2.class);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SampleConfiguration2.class);
FeignLoggerFactory loggerFactory = context.getBean(FeignLoggerFactory.class);
assertThat(loggerFactory).isNotNull();
Logger logger = loggerFactory.create(Object.class);
@@ -58,8 +56,7 @@ public class FeignLoggerFactoryTests {
@Test
public void testCustomLoggerFactory() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
SampleConfiguration3.class);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SampleConfiguration3.class);
FeignLoggerFactory loggerFactory = context.getBean(FeignLoggerFactory.class);
assertThat(loggerFactory).isNotNull();
assertThat(loggerFactory instanceof LoggerFactoryImpl).isTrue();
@@ -49,10 +49,9 @@ public class FeignOkHttpConfigurationTests {
@Before
public void setUp() {
this.context = new SpringApplicationBuilder()
.properties("debug=true", "feign.httpclient.disableSslValidation=true",
"feign.okhttp.enabled=true", "feign.httpclient.enabled=false")
.web(WebApplicationType.NONE)
.sources(HttpClientConfiguration.class, FeignAutoConfiguration.class)
.properties("debug=true", "feign.httpclient.disableSslValidation=true", "feign.okhttp.enabled=true",
"feign.httpclient.enabled=false")
.web(WebApplicationType.NONE).sources(HttpClientConfiguration.class, FeignAutoConfiguration.class)
.run();
}
@@ -66,11 +65,8 @@ public class FeignOkHttpConfigurationTests {
@Test
public void disableSslTest() throws Exception {
OkHttpClient httpClient = this.context.getBean(OkHttpClient.class);
HostnameVerifier hostnameVerifier = (HostnameVerifier) this.getField(httpClient,
"hostnameVerifier");
assertThat(
OkHttpClientFactory.TrustAllHostnames.class.isInstance(hostnameVerifier))
.isTrue();
HostnameVerifier hostnameVerifier = (HostnameVerifier) this.getField(httpClient, "hostnameVerifier");
assertThat(OkHttpClientFactory.TrustAllHostnames.class.isInstance(hostnameVerifier)).isTrue();
}
protected <T> Object getField(Object target, String name) {
@@ -47,9 +47,8 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Spencer Gibb
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = SpringDecoderTests.Application.class,
webEnvironment = WebEnvironment.RANDOM_PORT, value = {
"spring.application.name=springdecodertest", "spring.jmx.enabled=false" })
@SpringBootTest(classes = SpringDecoderTests.Application.class, webEnvironment = WebEnvironment.RANDOM_PORT,
value = { "spring.application.name=springdecodertest", "spring.jmx.enabled=false" })
@DirtiesContext
public class SpringDecoderTests extends FeignClientFactoryBean {
@@ -71,28 +70,24 @@ public class SpringDecoderTests extends FeignClientFactoryBean {
public TestClient testClient(boolean decode404) {
setType(this.getClass());
setDecode404(decode404);
return feign(this.context).target(TestClient.class,
"http://localhost:" + this.port);
return feign(this.context).target(TestClient.class, "http://localhost:" + this.port);
}
@Test
public void testResponseEntity() {
ResponseEntity<Hello> response = testClient().getHelloResponse();
assertThat(response).as("response was null").isNotNull();
assertThat(response.getStatusCode()).as("wrong status code")
.isEqualTo(HttpStatus.OK);
assertThat(response.getStatusCode()).as("wrong status code").isEqualTo(HttpStatus.OK);
Hello hello = response.getBody();
assertThat(hello).as("hello was null").isNotNull();
assertThat(hello).as("first hello didn't match")
.isEqualTo(new Hello("hello world via response"));
assertThat(hello).as("first hello didn't match").isEqualTo(new Hello("hello world via response"));
}
@Test
public void testSimpleType() {
Hello hello = testClient().getHello();
assertThat(hello).as("hello was null").isNotNull();
assertThat(hello).as("first hello didn't match")
.isEqualTo(new Hello("hello world 1"));
assertThat(hello).as("first hello didn't match").isEqualTo(new Hello("hello world 1"));
}
@Test
@@ -100,8 +95,7 @@ public class SpringDecoderTests extends FeignClientFactoryBean {
List<Hello> hellos = testClient().getHellos();
assertThat(hellos).as("hellos was null").isNotNull();
assertThat(hellos.size()).as("hellos was not the right size").isEqualTo(2);
assertThat(hellos.get(0)).as("first hello didn't match")
.isEqualTo(new Hello("hello world 1"));
assertThat(hellos.get(0)).as("first hello didn't match").isEqualTo(new Hello("hello world 1"));
}
@Test
@@ -109,8 +103,7 @@ public class SpringDecoderTests extends FeignClientFactoryBean {
List<String> hellos = testClient().getHelloStrings();
assertThat(hellos).as("hellos was null").isNotNull();
assertThat(hellos.size()).as("hellos was not the right size").isEqualTo(2);
assertThat(hellos.get(0)).as("first hello didn't match")
.isEqualTo("hello world 1");
assertThat(hellos.get(0)).as("first hello didn't match").isEqualTo("hello world 1");
}
@Test
@@ -118,15 +111,12 @@ public class SpringDecoderTests extends FeignClientFactoryBean {
public void testWildcardTypeDecode() {
ResponseEntity<?> wildcard = testClient().getWildcard();
assertThat(wildcard).as("wildcard was null").isNotNull();
assertThat(wildcard.getStatusCode()).as("wrong status code")
.isEqualTo(HttpStatus.OK);
assertThat(wildcard.getStatusCode()).as("wrong status code").isEqualTo(HttpStatus.OK);
Object wildcardBody = wildcard.getBody();
assertThat(wildcardBody).as("wildcardBody was null").isNotNull();
assertThat(wildcardBody instanceof Map).as("wildcard not an instance of Map")
.isTrue();
assertThat(wildcardBody instanceof Map).as("wildcard not an instance of Map").isTrue();
Map<String, String> hello = (Map<String, String>) wildcardBody;
assertThat(hello.get("message")).as("first hello didn't match")
.isEqualTo("wildcard");
assertThat(hello.get("message")).as("first hello didn't match").isEqualTo("wildcard");
}
@Test
@@ -54,11 +54,10 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Aaron Whiteside
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = BeansFeignClientTests.Application.class,
webEnvironment = WebEnvironment.RANDOM_PORT,
@SpringBootTest(classes = BeansFeignClientTests.Application.class, webEnvironment = WebEnvironment.RANDOM_PORT,
value = { "spring.application.name=feignclienttest",
"logging.level.org.springframework.cloud.openfeign.valid=DEBUG",
"feign.httpclient.enabled=false", "feign.okhttp.enabled=false" })
"logging.level.org.springframework.cloud.openfeign.valid=DEBUG", "feign.httpclient.enabled=false",
"feign.okhttp.enabled=false" })
@DirtiesContext
public class BeansFeignClientTests {
@@ -81,18 +80,15 @@ public class BeansFeignClientTests {
@Test
public void testAnnotations() {
Map<String, Object> beans = this.context
.getBeansWithAnnotation(FeignClient.class);
assertThat(beans.containsKey(TestClient.class.getName()))
.as("Wrong clients: " + beans).isTrue();
Map<String, Object> beans = this.context.getBeansWithAnnotation(FeignClient.class);
assertThat(beans.containsKey(TestClient.class.getName())).as("Wrong clients: " + beans).isTrue();
}
@Test
public void testClient() {
assertThat(this.testClient).as("testClient was null").isNotNull();
assertThat(this.extraClient).as("extraClient was null").isNotNull();
assertThat(Proxy.isProxyClass(this.testClient.getClass()))
.as("testClient is not a java Proxy").isTrue();
assertThat(Proxy.isProxyClass(this.testClient.getClass())).as("testClient is not a java Proxy").isTrue();
InvocationHandler invocationHandler = Proxy.getInvocationHandler(this.testClient);
assertThat(invocationHandler).as("invocationHandler was null").isNotNull();
}
@@ -100,20 +96,17 @@ public class BeansFeignClientTests {
@Test
public void extraClient() {
assertThat(this.extraClient).as("extraClient was null").isNotNull();
assertThat(Proxy.isProxyClass(this.extraClient.getClass()))
.as("extraClient is not a java Proxy").isTrue();
InvocationHandler invocationHandler = Proxy
.getInvocationHandler(this.extraClient);
assertThat(Proxy.isProxyClass(this.extraClient.getClass())).as("extraClient is not a java Proxy").isTrue();
InvocationHandler invocationHandler = Proxy.getInvocationHandler(this.extraClient);
assertThat(invocationHandler).as("invocationHandler was null").isNotNull();
}
@Test
public void buildByBuilder() {
assertThat(this.buildByBuilder).as("buildByBuilder was null").isNotNull();
assertThat(Proxy.isProxyClass(this.buildByBuilder.getClass()))
.as("buildByBuilder is not a java Proxy").isTrue();
InvocationHandler invocationHandler = Proxy
.getInvocationHandler(this.buildByBuilder);
assertThat(Proxy.isProxyClass(this.buildByBuilder.getClass())).as("buildByBuilder is not a java Proxy")
.isTrue();
InvocationHandler invocationHandler = Proxy.getInvocationHandler(this.buildByBuilder);
assertThat(invocationHandler).as("invocationHandler was null").isNotNull();
}
@@ -48,8 +48,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
*
* @author Jakub Narloch
*/
@SpringBootTest(classes = FeignAcceptEncodingTests.Application.class,
webEnvironment = RANDOM_PORT,
@SpringBootTest(classes = FeignAcceptEncodingTests.Application.class, webEnvironment = RANDOM_PORT,
value = { "feign.compression.response.enabled=true" })
@RunWith(SpringRunner.class)
@DirtiesContext
@@ -74,8 +73,7 @@ public class FeignAcceptEncodingTests {
@EnableFeignClients(clients = InvoiceClient.class)
@LoadBalancerClient(name = "local", configuration = LocalClientConfiguration.class)
@SpringBootApplication(
scanBasePackages = "org.springframework.cloud.openfeign.encoding.app")
@SpringBootApplication(scanBasePackages = "org.springframework.cloud.openfeign.encoding.app")
@Import(NoSecurityConfiguration.class)
public static class Application {
@@ -88,8 +86,7 @@ public class FeignAcceptEncodingTests {
private int port = 0;
@Bean
public ServiceInstanceListSupplier staticServiceInstanceListSupplier(
Environment env) {
public ServiceInstanceListSupplier staticServiceInstanceListSupplier(Environment env) {
return ServiceInstanceListSupplier.fixed(env).instance(port, "local").build();
}
@@ -47,8 +47,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
*
* @author Jakub Narloch
*/
@SpringBootTest(classes = FeignContentEncodingTests.Application.class,
webEnvironment = RANDOM_PORT,
@SpringBootTest(classes = FeignContentEncodingTests.Application.class, webEnvironment = RANDOM_PORT,
value = { "feign.compression.request.enabled=true",
"hystrix.command.default.execution.isolation.strategy=SEMAPHORE",
"ribbon.OkToRetryOnAllOperations=false" })
@@ -65,8 +64,7 @@ public class FeignContentEncodingTests {
final List<Invoice> invoices = Invoices.createInvoiceList(50);
// when
final ResponseEntity<List<Invoice>> response = this.invoiceClient
.saveInvoices(invoices);
final ResponseEntity<List<Invoice>> response = this.invoiceClient.saveInvoices(invoices);
// then
assertThat(response).isNotNull();
@@ -78,8 +76,7 @@ public class FeignContentEncodingTests {
@EnableFeignClients(clients = InvoiceClient.class)
@LoadBalancerClient(name = "local", configuration = LocalClientConfiguration.class)
@SpringBootApplication(
scanBasePackages = "org.springframework.cloud.openfeign.encoding.app")
@SpringBootApplication(scanBasePackages = "org.springframework.cloud.openfeign.encoding.app")
@Import(NoSecurityConfiguration.class)
public static class Application {
@@ -92,8 +89,7 @@ public class FeignContentEncodingTests {
private int port = 0;
@Bean
public ServiceInstanceListSupplier staticServiceInstanceListSupplier(
Environment env) {
public ServiceInstanceListSupplier staticServiceInstanceListSupplier(Environment env) {
return ServiceInstanceListSupplier.fixed(env).instance(port, "local").build();
}
@@ -54,8 +54,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
*
* @author Charlie Mordant.
*/
@SpringBootTest(classes = FeignPageableEncodingTests.Application.class,
webEnvironment = RANDOM_PORT,
@SpringBootTest(classes = FeignPageableEncodingTests.Application.class, webEnvironment = RANDOM_PORT,
value = { "feign.compression.request.enabled=true",
"hystrix.command.default.execution.isolation.strategy=SEMAPHORE",
"ribbon.OkToRetryOnAllOperations=false" })
@@ -72,8 +71,7 @@ public class FeignPageableEncodingTests {
Pageable pageable = PageRequest.of(0, 10, Sort.Direction.ASC, "sortProperty");
// when
final ResponseEntity<Page<Invoice>> response = this.invoiceClient
.getInvoicesPaged(pageable);
final ResponseEntity<Page<Invoice>> response = this.invoiceClient.getInvoicesPaged(pageable);
// then
assertThat(response).isNotNull();
@@ -81,8 +79,7 @@ public class FeignPageableEncodingTests {
assertThat(response.getBody()).isNotNull();
assertThat(pageable.getPageSize()).isEqualTo(response.getBody().getSize());
assertThat(response.getBody().getPageable().getSort()).hasSize(1);
Optional<Sort.Order> optionalOrder = response.getBody().getPageable().getSort()
.get().findFirst();
Optional<Sort.Order> optionalOrder = response.getBody().getPageable().getSort().get().findFirst();
if (optionalOrder.isPresent()) {
Sort.Order order = optionalOrder.get();
assertThat(order.getDirection()).isEqualTo(Sort.Direction.ASC);
@@ -93,8 +90,7 @@ public class FeignPageableEncodingTests {
@EnableFeignClients(clients = InvoiceClient.class)
@LoadBalancerClient(name = "local", configuration = LocalClientConfiguration.class)
@SpringBootApplication(
scanBasePackages = "org.springframework.cloud.openfeign.encoding.app",
@SpringBootApplication(scanBasePackages = "org.springframework.cloud.openfeign.encoding.app",
exclude = { RepositoryRestMvcAutoConfiguration.class })
@EnableSpringDataWebSupport
@Import({ NoSecurityConfiguration.class, FeignClientsConfiguration.class })
@@ -109,8 +105,7 @@ public class FeignPageableEncodingTests {
private int port = 0;
@Bean
public ServiceInstanceListSupplier staticServiceInstanceListSupplier(
Environment env) {
public ServiceInstanceListSupplier staticServiceInstanceListSupplier(Environment env) {
return ServiceInstanceListSupplier.fixed(env).instance(port, "local").build();
}
@@ -35,8 +35,7 @@ final class Invoices {
for (int ind = 0; ind < count; ind++) {
final Invoice invoice = new Invoice();
invoice.setTitle("Invoice " + (ind + 1));
invoice.setAmount(new BigDecimal(
String.format(Locale.US, "%.2f", Math.random() * 1000)));
invoice.setAmount(new BigDecimal(String.format(Locale.US, "%.2f", Math.random() * 1000)));
invoices.add(invoice);
}
return invoices;
@@ -34,17 +34,13 @@ import org.springframework.web.bind.annotation.RequestMethod;
@FeignClient("local")
public interface InvoiceClient {
@RequestMapping(value = "invoicesPaged", method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
ResponseEntity<Page<Invoice>> getInvoicesPaged(
org.springframework.data.domain.Pageable pageable);
@RequestMapping(value = "invoicesPaged", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
ResponseEntity<Page<Invoice>> getInvoicesPaged(org.springframework.data.domain.Pageable pageable);
@RequestMapping(value = "invoices", method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@RequestMapping(value = "invoices", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
ResponseEntity<List<Invoice>> getInvoices();
@RequestMapping(value = "invoices", method = RequestMethod.POST,
consumes = MediaType.APPLICATION_JSON_VALUE,
@RequestMapping(value = "invoices", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
ResponseEntity<List<Invoice>> saveInvoices(List<Invoice> invoices);
@@ -39,27 +39,22 @@ import org.springframework.web.bind.annotation.RestController;
@RestController
public class InvoiceResource {
@RequestMapping(value = "invoices", method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@RequestMapping(value = "invoices", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<Invoice>> getInvoices() {
return ResponseEntity.ok(createInvoiceList(100));
}
@RequestMapping(value = "invoices", method = RequestMethod.POST,
consumes = MediaType.APPLICATION_JSON_VALUE,
@RequestMapping(value = "invoices", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
ResponseEntity<List<Invoice>> saveInvoices(@RequestBody List<Invoice> invoices) {
return ResponseEntity.ok(invoices);
}
@RequestMapping(value = "invoicesPaged", method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Page<Invoice>> getInvoicesPaged(
org.springframework.data.domain.Pageable pageable) {
Page<Invoice> page = new PageImpl<>(createInvoiceList(pageable.getPageSize()),
pageable, 100);
@RequestMapping(value = "invoicesPaged", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Page<Invoice>> getInvoicesPaged(org.springframework.data.domain.Pageable pageable) {
Page<Invoice> page = new PageImpl<>(createInvoiceList(pageable.getPageSize()), pageable, 100);
return ResponseEntity.ok(page);
}
@@ -68,8 +63,7 @@ public class InvoiceResource {
for (int ind = 0; ind < count; ind++) {
final Invoice invoice = new Invoice();
invoice.setTitle("Invoice " + (ind + 1));
invoice.setAmount(new BigDecimal(
String.format(Locale.US, "%.2f", Math.random() * 1000)));
invoice.setAmount(new BigDecimal(String.format(Locale.US, "%.2f", Math.random() * 1000)));
invoices.add(invoice);
}
return invoices;
@@ -68,9 +68,8 @@ public class ProtobufSpringEncoderTest {
// a protobuf object with some content
private org.springframework.cloud.openfeign.encoding.proto.Request request = org.springframework.cloud.openfeign.encoding.proto.Request
.newBuilder().setId(1000000).setMsg("Erlang/OTP 最初是爱立信为开发电信设备系统设计的编程语言平台,"
+ "电信设备(路由器、接入网关、…)典型设计是通过背板连接主控板卡与多块业务板卡的分布式系统。")
.build();
.newBuilder().setId(1000000)
.setMsg("Erlang/OTP 最初是爱立信为开发电信设备系统设计的编程语言平台," + "电信设备(路由器、接入网关、…)典型设计是通过背板连接主控板卡与多块业务板卡的分布式系统。").build();
@Test
public void testProtobuf() throws IOException, URISyntaxException {
@@ -92,8 +91,7 @@ public class ProtobufSpringEncoderTest {
RequestTemplate requestTemplate = newRequestTemplate();
newEncoder().encode(this.request, Request.class, requestTemplate);
// set a charset
requestTemplate.body(
encoded(requestTemplate.requestBody().asBytes(), StandardCharsets.UTF_8));
requestTemplate.body(encoded(requestTemplate.requestBody().asBytes(), StandardCharsets.UTF_8));
HttpEntity entity = toApacheHttpEntity(requestTemplate);
byte[] bytes = read(entity.getContent(), (int) entity.getContentLength());
@@ -125,21 +123,17 @@ public class ProtobufSpringEncoderTest {
return requestTemplate;
}
private HttpEntity toApacheHttpEntity(RequestTemplate requestTemplate)
throws IOException, URISyntaxException {
private HttpEntity toApacheHttpEntity(RequestTemplate requestTemplate) throws IOException, URISyntaxException {
final List<HttpUriRequest> request = new ArrayList<>(1);
BDDMockito.given(this.httpClient.execute(ArgumentMatchers.<HttpUriRequest>any()))
.will(new Answer<HttpResponse>() {
@Override
public HttpResponse answer(InvocationOnMock invocationOnMock)
throws Throwable {
public HttpResponse answer(InvocationOnMock invocationOnMock) throws Throwable {
request.add((HttpUriRequest) invocationOnMock.getArguments()[0]);
return new BasicHttpResponse(new BasicStatusLine(
new ProtocolVersion("http", 1, 1), 200, null));
return new BasicHttpResponse(new BasicStatusLine(new ProtocolVersion("http", 1, 1), 200, null));
}
});
new ApacheHttpClient(this.httpClient).execute(
requestTemplate.resolve(new HashMap<>()).request(),
new ApacheHttpClient(this.httpClient).execute(requestTemplate.resolve(new HashMap<>()).request(),
new feign.Request.Options());
HttpUriRequest httpUriRequest = request.get(0);
return ((HttpEntityEnclosingRequestBase) httpUriRequest).getEntity();
@@ -27,10 +27,8 @@ public final class ProtobufTest {
private static com.google.protobuf.Descriptors.FileDescriptor descriptor;
static {
String[] descriptorData = {
"\n\023protobuf_test.proto\"\"\n\007Request\022\n\n\002id\030\001"
+ " \001(\005\022\013\n\003msg\030\002 \001(\tB\024\n\020feign.httpclientP\001b"
+ "\006proto3" };
String[] descriptorData = { "\n\023protobuf_test.proto\"\"\n\007Request\022\n\n\002id\030\001"
+ " \001(\005\022\013\n\003msg\030\002 \001(\tB\024\n\020feign.httpclientP\001b" + "\006proto3" };
com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() {
public com.google.protobuf.ExtensionRegistry assignDescriptors(
com.google.protobuf.Descriptors.FileDescriptor root) {
@@ -38,9 +36,8 @@ public final class ProtobufTest {
return null;
}
};
com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom(
descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] {},
assigner);
com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom(descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {}, assigner);
internal_static_Request_descriptor = getDescriptor().getMessageTypes().get(0);
internal_static_Request_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_Request_descriptor, new String[] { "Id", "Msg", });
@@ -49,12 +46,10 @@ public final class ProtobufTest {
private ProtobufTest() {
}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistryLite registry) {
public static void registerAllExtensions(com.google.protobuf.ExtensionRegistryLite registry) {
}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistry registry) {
public static void registerAllExtensions(com.google.protobuf.ExtensionRegistry registry) {
registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry);
}
@@ -68,8 +68,7 @@ public final class Request extends com.google.protobuf.GeneratedMessageV3 implem
throws com.google.protobuf.InvalidProtocolBufferException {
this();
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet
.newBuilder();
com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
@@ -79,8 +78,7 @@ public final class Request extends com.google.protobuf.GeneratedMessageV3 implem
done = true;
break;
default:
if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry,
tag)) {
if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
@@ -98,8 +96,7 @@ public final class Request extends com.google.protobuf.GeneratedMessageV3 implem
throw e.setUnfinishedMessage(this);
}
catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e)
.setUnfinishedMessage(this);
throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this);
}
finally {
this.unknownFields = unknownFields.build();
@@ -133,52 +130,40 @@ public final class Request extends com.google.protobuf.GeneratedMessageV3 implem
return PARSER.parseFrom(data, extensionRegistry);
}
public static Request parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
public static Request parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static Request parseFrom(byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
public static Request parseFrom(byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static Request parseFrom(java.io.InputStream input)
throws java.io.IOException {
public static Request parseFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static Request parseFrom(java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input,
extensionRegistry);
com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, extensionRegistry);
}
public static Request parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
public static Request parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static Request parseDelimitedFrom(java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static Request parseFrom(com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
public static Request parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static Request parseFrom(com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input,
extensionRegistry);
com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, extensionRegistry);
}
public static Builder newBuilder() {
@@ -236,8 +221,7 @@ public final class Request extends com.google.protobuf.GeneratedMessageV3 implem
public com.google.protobuf.ByteString getMsgBytes() {
Object ref = this.msg_;
if (ref instanceof String) {
com.google.protobuf.ByteString b = com.google.protobuf.ByteString
.copyFromUtf8((String) ref);
com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((String) ref);
this.msg_ = b;
return b;
}
@@ -258,8 +242,7 @@ public final class Request extends com.google.protobuf.GeneratedMessageV3 implem
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (this.id_ != 0) {
output.writeInt32(1, this.id_);
}
@@ -280,8 +263,7 @@ public final class Request extends com.google.protobuf.GeneratedMessageV3 implem
size += com.google.protobuf.CodedOutputStream.computeInt32Size(1, this.id_);
}
if (!getMsgBytes().isEmpty()) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2,
this.msg_);
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, this.msg_);
}
size += this.unknownFields.getSerializedSize();
this.memoizedSize = size;
@@ -347,8 +329,7 @@ public final class Request extends com.google.protobuf.GeneratedMessageV3 implem
/**
* Protobuf type {@code Request}
*/
public static final class Builder
extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:Request)
org.springframework.cloud.openfeign.encoding.proto.RequestOrBuilder {
@@ -373,8 +354,7 @@ public final class Request extends com.google.protobuf.GeneratedMessageV3 implem
protected FieldAccessorTable internalGetFieldAccessorTable() {
return org.springframework.cloud.openfeign.encoding.proto.ProtobufTest.internal_static_Request_fieldAccessorTable
.ensureFieldAccessorsInitialized(Request.class,
Request.Builder.class);
.ensureFieldAccessorsInitialized(Request.class, Request.Builder.class);
}
private void maybeForceBuilderInitialization() {
@@ -418,8 +398,7 @@ public final class Request extends com.google.protobuf.GeneratedMessageV3 implem
return (Builder) super.clone();
}
public Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field,
Object value) {
public Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field, Object value) {
return (Builder) super.setField(field, value);
}
@@ -431,14 +410,12 @@ public final class Request extends com.google.protobuf.GeneratedMessageV3 implem
return (Builder) super.clearOneof(oneof);
}
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index,
public Builder setRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, int index,
Object value) {
return (Builder) super.setRepeatedField(field, index, value);
}
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, Object value) {
public Builder addRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, Object value) {
return (Builder) super.addRepeatedField(field, value);
}
@@ -473,8 +450,7 @@ public final class Request extends com.google.protobuf.GeneratedMessageV3 implem
}
public Builder mergeFrom(com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException {
Request parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
@@ -553,8 +529,7 @@ public final class Request extends com.google.protobuf.GeneratedMessageV3 implem
public com.google.protobuf.ByteString getMsgBytes() {
Object ref = this.msg_;
if (ref instanceof String) {
com.google.protobuf.ByteString b = com.google.protobuf.ByteString
.copyFromUtf8((String) ref);
com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((String) ref);
this.msg_ = b;
return b;
}
@@ -587,13 +562,11 @@ public final class Request extends com.google.protobuf.GeneratedMessageV3 implem
return this;
}
public Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
public Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFieldsProto3(unknownFields);
}
public Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
public Builder mergeUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
@@ -0,0 +1,28 @@
/*
* Copyright 2013-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.openfeign.feignclientsregistrar;
import org.springframework.cloud.openfeign.FeignClient;
/**
* @author Michal Domagala
*/
@FeignClient("top-level")
public interface TopLevelClient {
}
@@ -0,0 +1,28 @@
/*
* Copyright 2013-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.openfeign.feignclientsregistrar.sub;
import org.springframework.cloud.openfeign.FeignClient;
/**
* @author Michal Domagala
*/
@FeignClient("sub-level")
public interface SubLevelClient {
}
@@ -42,34 +42,29 @@ public class FeignHalAutoConfigurationContextTests {
public void setUp() {
contextRunner = new WebApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class,
HttpMessageConvertersAutoConfiguration.class,
HypermediaAutoConfiguration.class,
RepositoryRestMvcAutoConfiguration.class,
FeignHalAutoConfiguration.class))
HttpMessageConvertersAutoConfiguration.class, HypermediaAutoConfiguration.class,
RepositoryRestMvcAutoConfiguration.class, FeignHalAutoConfiguration.class))
.withPropertyValues("debug=true");
}
@Test
public void testHalJacksonHttpMessageConverterIsNotLoaded() {
FilteredClassLoader filteredClassLoader = new FilteredClassLoader(
RepositoryRestMvcConfiguration.class, RepresentationModel.class);
FilteredClassLoader filteredClassLoader = new FilteredClassLoader(RepositoryRestMvcConfiguration.class,
RepresentationModel.class);
contextRunner.withClassLoader(filteredClassLoader)
.run(context -> assertThat(context)
.doesNotHaveBean("halJacksonHttpMessageConverter"));
.run(context -> assertThat(context).doesNotHaveBean("halJacksonHttpMessageConverter"));
}
@Test
public void testHalJacksonHttpMessageConverterIsLoaded() {
FilteredClassLoader filteredClassLoader = new FilteredClassLoader(
RepositoryRestMvcConfiguration.class);
contextRunner.withClassLoader(filteredClassLoader).run(
context -> assertThat(context).hasBean("halJacksonHttpMessageConverter"));
FilteredClassLoader filteredClassLoader = new FilteredClassLoader(RepositoryRestMvcConfiguration.class);
contextRunner.withClassLoader(filteredClassLoader)
.run(context -> assertThat(context).hasBean("halJacksonHttpMessageConverter"));
}
@Test
public void testHalJacksonHttpMessageConverterIsNotLoadedUseRestDataMessageConverterInstead() {
contextRunner.run(
context -> assertThat(context).hasBean("halJacksonHttpMessageConverter"));
contextRunner.run(context -> assertThat(context).hasBean("halJacksonHttpMessageConverter"));
}
}
@@ -68,22 +68,20 @@ public class FeignHalAutoConfigurationTests {
ObjectMapper mapper = new ObjectMapper();
when(objectMapper.getIfAvailable(any())).thenReturn(mapper);
when(halConfiguration.getIfAvailable(any()))
.thenReturn(mock(HalConfiguration.class));
when(halConfiguration.getIfAvailable(any())).thenReturn(mock(HalConfiguration.class));
when(relProvider.getIfAvailable()).thenReturn(mock(LinkRelationProvider.class));
when(curieProvider.getIfAvailable(any())).thenReturn(mock(CurieProvider.class));
when(messageResolver.getIfAvailable()).thenReturn(mock(MessageResolver.class));
TypeConstrainedMappingJackson2HttpMessageConverter converter = feignHalAutoConfiguration
.halJacksonHttpMessageConverter(objectMapper, halConfiguration,
messageResolver, curieProvider, relProvider);
.halJacksonHttpMessageConverter(objectMapper, halConfiguration, messageResolver, curieProvider,
relProvider);
assertThat(converter).isNotNull();
assertThat(converter.getObjectMapper()).isNotNull();
assertThat(converter.getSupportedMediaTypes()).isEqualTo(Arrays.asList(HAL_JSON));
assertThat(Jackson2HalModule.isAlreadyRegisteredIn(converter.getObjectMapper()))
.isTrue();
assertThat(Jackson2HalModule.isAlreadyRegisteredIn(converter.getObjectMapper())).isTrue();
}
}
@@ -41,8 +41,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
*
* @author Hector Espert
*/
@SpringBootTest(classes = FeignHalApplication.class, webEnvironment = RANDOM_PORT,
value = "debug=true")
@SpringBootTest(classes = FeignHalApplication.class, webEnvironment = RANDOM_PORT, value = "debug=true")
@RunWith(SpringRunner.class)
@DirtiesContext
public class FeignHalTests {
@@ -74,8 +73,7 @@ public class FeignHalTests {
assertThat(collectionModel.hasLinks()).isTrue();
assertThat(collectionModel.hasLink("self")).isTrue();
assertThat(collectionModel.getLink("self")).map(Link::getHref)
.contains("/collection");
assertThat(collectionModel.getLink("self")).map(Link::getHref).contains("/collection");
Collection<MarsRover> collection = collectionModel.getContent();
assertThat(collection).isNotEmpty();
@@ -33,8 +33,7 @@ import org.springframework.core.env.Environment;
* @author Hector Espert
*/
@EnableFeignClients(clients = FeignHalClient.class)
@SpringBootApplication(
scanBasePackages = "org.springframework.cloud.openfeign.hateoas.app",
@SpringBootApplication(scanBasePackages = "org.springframework.cloud.openfeign.hateoas.app",
exclude = RepositoryRestMvcAutoConfiguration.class)
@LoadBalancerClient(name = "local", configuration = LocalHalClientConfiguration.class)
@Import(NoSecurityConfiguration.class)
@@ -50,8 +49,7 @@ class LocalHalClientConfiguration {
private int port = 0;
@Bean
public ServiceInstanceListSupplier staticServiceInstanceListSupplier(
Environment env) {
public ServiceInstanceListSupplier staticServiceInstanceListSupplier(Environment env) {
return ServiceInstanceListSupplier.fixed(env).instance(port, "local").build();
}
@@ -45,8 +45,7 @@ public class FeignClientValidationTests {
public void testServiceIdAndValue() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
LoadBalancerAutoConfiguration.class, NameAndServiceIdConfiguration.class);
assertThat(context.getBean(NameAndServiceIdConfiguration.Client.class))
.isNotNull();
assertThat(context.getBean(NameAndServiceIdConfiguration.Client.class)).isNotNull();
context.close();
}
@@ -54,15 +53,10 @@ public class FeignClientValidationTests {
public void testDuplicatedClientNames() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.setAllowBeanDefinitionOverriding(false);
context.register(LoadBalancerAutoConfiguration.class,
DuplicatedFeignClientNamesConfiguration.class);
context.register(LoadBalancerAutoConfiguration.class, DuplicatedFeignClientNamesConfiguration.class);
context.refresh();
assertThat(
context.getBean(DuplicatedFeignClientNamesConfiguration.FooClient.class))
.isNotNull();
assertThat(
context.getBean(DuplicatedFeignClientNamesConfiguration.BarClient.class))
.isNotNull();
assertThat(context.getBean(DuplicatedFeignClientNamesConfiguration.FooClient.class)).isNotNull();
assertThat(context.getBean(DuplicatedFeignClientNamesConfiguration.BarClient.class)).isNotNull();
context.close();
}
@@ -89,9 +83,8 @@ public class FeignClientValidationTests {
@Configuration(proxyBeanMethods = false)
@Import({ FeignAutoConfiguration.class, HttpClientConfiguration.class })
@EnableFeignClients(
clients = { DuplicatedFeignClientNamesConfiguration.FooClient.class,
DuplicatedFeignClientNamesConfiguration.BarClient.class })
@EnableFeignClients(clients = { DuplicatedFeignClientNamesConfiguration.FooClient.class,
DuplicatedFeignClientNamesConfiguration.BarClient.class })
protected static class DuplicatedFeignClientNamesConfiguration {
@FeignClient(contextId = "foo", name = "bar")
@@ -23,6 +23,8 @@ import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import feign.Client;
import feign.Request;
@@ -34,13 +36,19 @@ import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.cloud.client.DefaultServiceInstance;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.CompletionContext;
import org.springframework.cloud.client.loadbalancer.DefaultRequestContext;
import org.springframework.cloud.client.loadbalancer.LoadBalancerLifecycle;
import org.springframework.cloud.client.loadbalancer.reactive.LoadBalancerProperties;
import org.springframework.cloud.loadbalancer.blocking.client.BlockingLoadBalancerClient;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
@@ -62,11 +70,14 @@ class FeignBlockingLoadBalancerClientTests {
private Client delegate = mock(Client.class);
private BlockingLoadBalancerClient loadBalancerClient = mock(
BlockingLoadBalancerClient.class);
private BlockingLoadBalancerClient loadBalancerClient = mock(BlockingLoadBalancerClient.class);
private final LoadBalancerClientFactory loadBalancerClientFactory = mock(LoadBalancerClientFactory.class);
private final LoadBalancerProperties loadBalancerProperties = new LoadBalancerProperties();
private FeignBlockingLoadBalancerClient feignBlockingLoadBalancerClient = new FeignBlockingLoadBalancerClient(
delegate, loadBalancerClient);
delegate, loadBalancerClient, loadBalancerProperties, loadBalancerClientFactory);
@Test
void shouldExtractServiceIdFromRequestUrl() throws IOException {
@@ -74,7 +85,7 @@ class FeignBlockingLoadBalancerClientTests {
feignBlockingLoadBalancerClient.execute(request, new Request.Options());
verify(loadBalancerClient).choose("test");
verify(loadBalancerClient).choose(eq("test"), any());
}
@Test
@@ -82,22 +93,19 @@ class FeignBlockingLoadBalancerClientTests {
Request request = testRequest("");
assertThatIllegalStateException()
.isThrownBy(() -> feignBlockingLoadBalancerClient.execute(request,
new Request.Options()))
.withMessage(
"Request URI does not contain a valid hostname: http:///path");
.isThrownBy(() -> feignBlockingLoadBalancerClient.execute(request, new Request.Options()))
.withMessage("Request URI does not contain a valid hostname: http:///path");
}
@Test
void shouldRespondWithServiceUnavailableIfInstanceNotFound() throws IOException {
Request request = testRequest();
Response response = feignBlockingLoadBalancerClient.execute(request,
new Request.Options());
Response response = feignBlockingLoadBalancerClient.execute(request, new Request.Options());
assertThat(response.status()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE.value());
assertThat(response.body().toString()).isEqualTo(
"Load balancer does not contain an instance for the service test");
assertThat(response.body().toString())
.isEqualTo("Load balancer does not contain an instance for the service test");
}
@Test
@@ -105,11 +113,10 @@ class FeignBlockingLoadBalancerClientTests {
Request request = testRequest();
Request.Options options = new Request.Options();
String url = "http://127.0.0.1/path";
ServiceInstance serviceInstance = new DefaultServiceInstance("test-1", "test",
"test-host", 8888, false);
when(loadBalancerClient.choose("test")).thenReturn(serviceInstance);
when(loadBalancerClient.reconstructURI(serviceInstance,
URI.create("http://test/path"))).thenReturn(URI.create(url));
ServiceInstance serviceInstance = new DefaultServiceInstance("test-1", "test", "test-host", 8888, false);
when(loadBalancerClient.choose(eq("test"), any())).thenReturn(serviceInstance);
when(loadBalancerClient.reconstructURI(serviceInstance, URI.create("http://test/path")))
.thenReturn(URI.create(url));
feignBlockingLoadBalancerClient.execute(request, options);
@@ -124,21 +131,88 @@ class FeignBlockingLoadBalancerClientTests {
assertThat(new String(actualRequest.body())).isEqualTo("hello");
}
@Test
void shouldExecuteLoadBalancerLifecycleCallbacks() throws IOException {
Request request = testRequest();
Request.Options options = new Request.Options();
String url = "http://127.0.0.1/path";
ServiceInstance serviceInstance = new DefaultServiceInstance("test-1", "test", "test-host", 8888, false);
when(loadBalancerClient.choose(eq("test"), any())).thenReturn(serviceInstance);
when(loadBalancerClient.reconstructURI(serviceInstance, URI.create("http://test/path")))
.thenReturn(URI.create(url));
String callbackTestHint = "callbackTestHint";
loadBalancerProperties.getHint().put("test", callbackTestHint);
Map<String, LoadBalancerLifecycle> loadBalancerLifecycleBeans = new HashMap<>();
loadBalancerLifecycleBeans.put("loadBalancerLifecycle", new TestLoadBalancerLifecycle());
loadBalancerLifecycleBeans.put("anotherLoadBalancerLifecycle", new AnotherLoadBalancerLifecycle());
when(loadBalancerClientFactory.getInstances("test", LoadBalancerLifecycle.class))
.thenReturn(loadBalancerLifecycleBeans);
Object actualResult = feignBlockingLoadBalancerClient.execute(request, options);
Collection<org.springframework.cloud.client.loadbalancer.Request<Object>> lifecycleLogRequests = ((TestLoadBalancerLifecycle) loadBalancerLifecycleBeans
.get("loadBalancerLifecycle")).getStartLog().values();
Collection<CompletionContext<Object, ServiceInstance>> anotherLifecycleLogRequests = ((AnotherLoadBalancerLifecycle) loadBalancerLifecycleBeans
.get("anotherLoadBalancerLifecycle")).getCompleteLog().values();
assertThat(lifecycleLogRequests)
.extracting(lbRequest -> ((DefaultRequestContext) lbRequest.getContext()).getHint())
.contains(callbackTestHint);
assertThat(anotherLifecycleLogRequests).extracting(CompletionContext::getClientResponse).contains(actualResult);
}
private Request testRequest() {
return testRequest("test");
}
private Request testRequest(String host) {
return Request.create(Request.HttpMethod.GET, "http://" + host + "/path",
testHeaders(), "hello".getBytes(), StandardCharsets.UTF_8, null);
return Request.create(Request.HttpMethod.GET, "http://" + host + "/path", testHeaders(), "hello".getBytes(),
StandardCharsets.UTF_8, null);
}
private Map<String, Collection<String>> testHeaders() {
Map<String, Collection<String>> feignHeaders = new HashMap<>();
feignHeaders.put(HttpHeaders.CONTENT_TYPE,
Collections.singletonList(MediaType.APPLICATION_JSON_VALUE));
feignHeaders.put(HttpHeaders.CONTENT_TYPE, Collections.singletonList(MediaType.APPLICATION_JSON_VALUE));
return feignHeaders;
}
protected static class TestLoadBalancerLifecycle implements LoadBalancerLifecycle<Object, Object, ServiceInstance> {
final ConcurrentHashMap<String, org.springframework.cloud.client.loadbalancer.Request<Object>> startLog = new ConcurrentHashMap<>();
final ConcurrentHashMap<String, CompletionContext<Object, ServiceInstance>> completeLog = new ConcurrentHashMap<>();
@Override
public void onStart(org.springframework.cloud.client.loadbalancer.Request<Object> request) {
startLog.put(getName() + UUID.randomUUID(), request);
}
@Override
public void onComplete(CompletionContext<Object, ServiceInstance> completionContext) {
completeLog.put(getName() + UUID.randomUUID(), completionContext);
}
ConcurrentHashMap<String, org.springframework.cloud.client.loadbalancer.Request<Object>> getStartLog() {
return startLog;
}
ConcurrentHashMap<String, CompletionContext<Object, ServiceInstance>> getCompleteLog() {
return completeLog;
}
protected String getName() {
return this.getClass().getSimpleName();
}
}
protected static class AnotherLoadBalancerLifecycle extends TestLoadBalancerLifecycle {
@Override
protected String getName() {
return this.getClass().getSimpleName();
}
}
}
@@ -21,7 +21,7 @@ import java.util.Map;
import feign.Client;
import feign.httpclient.ApacheHttpClient;
import feign.okhttp.OkHttpClient;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.builder.SpringApplicationBuilder;
@@ -36,54 +36,81 @@ import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Olga Maciaszek-Sharma
*/
public class FeignLoadBalancerAutoConfigurationTests {
class FeignLoadBalancerAutoConfigurationTests {
@Test
public void shouldInstantiateDefaultFeignBlockingLoadBalancerClientWhenHttpClientDisabled() {
ConfigurableApplicationContext context = initContext(
"feign.httpclient.enabled=false");
void shouldInstantiateDefaultFeignBlockingLoadBalancerClientWhenHttpClientDisabled() {
ConfigurableApplicationContext context = initContext("feign.httpclient.enabled=false",
"spring.cloud.loadbalancer.retry.enabled=false");
assertThatOneBeanPresent(context, BlockingLoadBalancerClient.class);
assertLoadBalanced(context, Client.Default.class);
}
@Test
public void shouldInstantiateHttpFeignClientWhenEnabled() {
ConfigurableApplicationContext context = initContext(
"spring.cloud.loadbalancer.ribbon.enabled=false");
void shouldInstantiateHttpFeignClientWhenEnabled() {
ConfigurableApplicationContext context = initContext("spring.cloud.loadbalancer.retry.enabled=false");
assertThatOneBeanPresent(context, BlockingLoadBalancerClient.class);
assertLoadBalanced(context, ApacheHttpClient.class);
}
@Test
public void shouldInstantiateOkHttpFeignClientWhenEnabled() {
ConfigurableApplicationContext context = initContext(
"feign.httpclient.enabled=false", "feign.okhttp.enabled=true");
void shouldInstantiateOkHttpFeignClientWhenEnabled() {
ConfigurableApplicationContext context = initContext("feign.httpclient.enabled=false",
"feign.okhttp.enabled=true", "spring.cloud.loadbalancer.retry.enabled=false");
assertThatOneBeanPresent(context, BlockingLoadBalancerClient.class);
assertLoadBalanced(context, OkHttpClient.class);
}
@Test
void shouldInstantiateRetryableDefaultFeignBlockingLoadBalancerClientWhenHttpClientDisabled() {
ConfigurableApplicationContext context = initContext("spring.cloud.loadbalancer.ribbon.enabled=false",
"feign.httpclient.enabled=false");
assertThatOneBeanPresent(context, BlockingLoadBalancerClient.class);
assertLoadBalancedWithRetries(context, Client.Default.class);
}
@Test
void shouldInstantiateRetryableHttpFeignClientWhenEnabled() {
ConfigurableApplicationContext context = initContext("spring.cloud.loadbalancer.ribbon.enabled=false");
assertThatOneBeanPresent(context, BlockingLoadBalancerClient.class);
assertLoadBalancedWithRetries(context, ApacheHttpClient.class);
}
@Test
void shouldInstantiateRetryableOkHttpFeignClientWhenEnabled() {
ConfigurableApplicationContext context = initContext("spring.cloud.loadbalancer.ribbon.enabled=false",
"feign.httpclient.enabled=false", "feign.okhttp.enabled=true");
assertThatOneBeanPresent(context, BlockingLoadBalancerClient.class);
assertLoadBalancedWithRetries(context, OkHttpClient.class);
}
private ConfigurableApplicationContext initContext(String... properties) {
return new SpringApplicationBuilder().web(WebApplicationType.NONE)
.properties(properties)
.sources(HttpClientConfiguration.class,
LoadBalancerAutoConfiguration.class,
BlockingLoadBalancerClientAutoConfiguration.class,
FeignLoadBalancerAutoConfiguration.class)
return new SpringApplicationBuilder().web(WebApplicationType.NONE).properties(properties)
.sources(HttpClientConfiguration.class, LoadBalancerAutoConfiguration.class,
BlockingLoadBalancerClientAutoConfiguration.class, FeignLoadBalancerAutoConfiguration.class)
.run();
}
private void assertThatOneBeanPresent(ConfigurableApplicationContext context,
Class<?> beanClass) {
private void assertThatOneBeanPresent(ConfigurableApplicationContext context, Class<?> beanClass) {
Map<String, ?> beans = context.getBeansOfType(beanClass);
assertThat(beans).as("Missing bean of type %s", beanClass).hasSize(1);
}
private void assertLoadBalanced(ConfigurableApplicationContext context,
Class delegateClass) {
private void assertLoadBalanced(ConfigurableApplicationContext context, Class delegateClass) {
Map<String, FeignBlockingLoadBalancerClient> beans = context
.getBeansOfType(FeignBlockingLoadBalancerClient.class);
assertThat(beans).as("Missing bean of type %s", delegateClass).hasSize(1);
assertThat(beans.get("feignClient").getDelegate()).isInstanceOf(delegateClass);
}
private void assertLoadBalancedWithRetries(ConfigurableApplicationContext context, Class delegateClass) {
Map<String, RetryableFeignBlockingLoadBalancerClient> retryableBeans = context
.getBeansOfType(RetryableFeignBlockingLoadBalancerClient.class);
assertThat(retryableBeans).hasSize(1);
Map<String, FeignBlockingLoadBalancerClient> beans = context
.getBeansOfType(FeignBlockingLoadBalancerClient.class);
assertThat(beans).isEmpty();
assertThat(retryableBeans.get("feignRetryClient").getDelegate()).isInstanceOf(delegateClass);
}
}
@@ -0,0 +1,263 @@
/*
* Copyright 2013-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.openfeign.loadbalancer;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import feign.Client;
import feign.Request;
import feign.Response;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.cloud.client.DefaultServiceInstance;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.CompletionContext;
import org.springframework.cloud.client.loadbalancer.DefaultRequestContext;
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory;
import org.springframework.cloud.client.loadbalancer.LoadBalancerLifecycle;
import org.springframework.cloud.client.loadbalancer.reactive.LoadBalancerProperties;
import org.springframework.cloud.loadbalancer.blocking.client.BlockingLoadBalancerClient;
import org.springframework.cloud.loadbalancer.blocking.retry.BlockingLoadBalancedRetryPolicy;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Tests for {@link RetryableFeignBlockingLoadBalancerClient}. Note: the underlying
* {@link BlockingLoadBalancerClient} is already extensively tested in the Spring Cloud
* Commons project, so here we are only testing the interactions between
* {@link RetryableFeignBlockingLoadBalancerClient} and its delegates.
*
* @see <a href=
* "https://github.com/spring-cloud/spring-cloud-commons/blob/master/spring-cloud-loadbalancer/src/test/java/org/springframework/cloud/loadbalancer/blocking/client/BlockingLoadBalancerClientTests.java">BlockingLoadBalancerClientTests</a>
* @author Olga Maciaszek-Sharma
*/
@ExtendWith(MockitoExtension.class)
class RetryableFeignBlockingLoadBalancerClientTests {
private Client delegate = mock(Client.class);
private LoadBalancedRetryFactory retryFactory = mock(LoadBalancedRetryFactory.class);
private BlockingLoadBalancerClient loadBalancerClient = mock(BlockingLoadBalancerClient.class);
private final LoadBalancerClientFactory loadBalancerClientFactory = mock(LoadBalancerClientFactory.class);
private LoadBalancerProperties properties = new LoadBalancerProperties();
private RetryableFeignBlockingLoadBalancerClient feignBlockingLoadBalancerClient = new RetryableFeignBlockingLoadBalancerClient(
delegate, loadBalancerClient, retryFactory, properties, loadBalancerClientFactory);
private ServiceInstance serviceInstance = new DefaultServiceInstance("test-a", "test", "testhost", 80, false);
@BeforeEach
void setUp() {
when(retryFactory.createRetryPolicy(any(), eq(loadBalancerClient)))
.thenReturn(new BlockingLoadBalancedRetryPolicy(properties));
when(loadBalancerClient.choose(eq("test"), any())).thenReturn(serviceInstance);
}
@Test
void shouldExtractServiceIdFromRequestUrl() throws IOException {
Request request = testRequest();
Response response = testResponse(200);
when(delegate.execute(any(), any())).thenReturn(response);
when(retryFactory.createRetryPolicy(any(), eq(loadBalancerClient)))
.thenReturn(new BlockingLoadBalancedRetryPolicy(properties));
when(loadBalancerClient.reconstructURI(serviceInstance, URI.create("http://test/path")))
.thenReturn(URI.create("http://testhost:80/path"));
feignBlockingLoadBalancerClient.execute(request, new Request.Options());
verify(loadBalancerClient).choose(eq("test"), any());
verify(loadBalancerClient).reconstructURI(serviceInstance, URI.create("http://test/path"));
verify(delegate).execute(
argThat((Request actualRequest) -> actualRequest.url().equals("http://testhost:80/path")), any());
}
private Response testResponse(int status) {
return Response.builder().request(testRequest()).status(status).build();
}
@Test
void shouldExecuteOriginalRequestIfInstanceNotFound() throws IOException {
Request request = testRequest();
Response response = testResponse(503);
when(loadBalancerClient.choose(eq("test"), any())).thenReturn(null);
when(delegate.execute(any(), any())).thenReturn(response);
when(retryFactory.createRetryPolicy(any(), eq(loadBalancerClient)))
.thenReturn(new BlockingLoadBalancedRetryPolicy(properties));
feignBlockingLoadBalancerClient.execute(request, new Request.Options());
verify(delegate).execute(eq(request), any());
}
@Test
void shouldRetryOnRepeatableStatusCode() throws IOException {
properties.getRetry().getRetryableStatusCodes().add(503);
Request request = testRequest();
Response response = testResponse(503);
when(delegate.execute(any(), any())).thenReturn(response);
when(retryFactory.createRetryPolicy(any(), eq(loadBalancerClient)))
.thenReturn(new BlockingLoadBalancedRetryPolicy(properties));
when(loadBalancerClient.reconstructURI(serviceInstance, URI.create("http://test/path")))
.thenReturn(URI.create("http://testhost:80/path"));
feignBlockingLoadBalancerClient.execute(request, new Request.Options());
verify(loadBalancerClient, times(2)).reconstructURI(serviceInstance, URI.create("http://test/path"));
verify(delegate, times(2)).execute(any(), any());
}
@Test
void shouldPassCorrectRequestToDelegate() throws IOException {
Request request = testRequest();
Request.Options options = new Request.Options();
String url = "http://127.0.0.1/path";
ServiceInstance serviceInstance = new DefaultServiceInstance("test-1", "test", "test-host", 8888, false);
when(loadBalancerClient.choose(eq("test"), any())).thenReturn(serviceInstance);
when(loadBalancerClient.reconstructURI(serviceInstance, URI.create("http://test/path")))
.thenReturn(URI.create(url));
Response response = testResponse(200);
when(delegate.execute(any(), any())).thenReturn(response);
when(retryFactory.createRetryPolicy(any(), eq(loadBalancerClient)))
.thenReturn(new BlockingLoadBalancedRetryPolicy(properties));
feignBlockingLoadBalancerClient.execute(request, options);
ArgumentCaptor<Request> captor = ArgumentCaptor.forClass(Request.class);
verify(delegate, times(1)).execute(captor.capture(), eq(options));
Request actualRequest = captor.getValue();
assertThat(actualRequest.httpMethod()).isEqualTo(Request.HttpMethod.GET);
assertThat(actualRequest.url()).isEqualTo(url);
assertThat(actualRequest.headers()).hasSize(1);
assertThat(actualRequest.headers()).containsEntry(HttpHeaders.CONTENT_TYPE,
Collections.singletonList(MediaType.APPLICATION_JSON_VALUE));
assertThat(new String(actualRequest.body())).isEqualTo("hello");
}
@Test
void shouldExecuteLoadBalancerLifecycleCallbacks() throws IOException {
Request request = testRequest();
Request.Options options = new Request.Options();
String url = "http://127.0.0.1/path";
ServiceInstance serviceInstance = new DefaultServiceInstance("test-1", "test", "test-host", 8888, false);
when(loadBalancerClient.choose(eq("test"), any())).thenReturn(serviceInstance);
when(loadBalancerClient.reconstructURI(serviceInstance, URI.create("http://test/path")))
.thenReturn(URI.create(url));
Response response = testResponse(200);
when(delegate.execute(any(), any())).thenReturn(response);
String callbackTestHint = "callbackTestHint";
properties.getHint().put("test", callbackTestHint);
Map<String, LoadBalancerLifecycle> loadBalancerLifecycleBeans = new HashMap<>();
loadBalancerLifecycleBeans.put("loadBalancerLifecycle", new TestLoadBalancerLifecycle());
loadBalancerLifecycleBeans.put("anotherLoadBalancerLifecycle", new AnotherLoadBalancerLifecycle());
when(loadBalancerClientFactory.getInstances("test", LoadBalancerLifecycle.class))
.thenReturn(loadBalancerLifecycleBeans);
Object actualResult = feignBlockingLoadBalancerClient.execute(request, options);
Collection<org.springframework.cloud.client.loadbalancer.Request<Object>> lifecycleLogRequests = ((TestLoadBalancerLifecycle) loadBalancerLifecycleBeans
.get("loadBalancerLifecycle")).getStartLog().values();
Collection<CompletionContext<Object, ServiceInstance>> anotherLifecycleLogRequests = ((AnotherLoadBalancerLifecycle) loadBalancerLifecycleBeans
.get("anotherLoadBalancerLifecycle")).getCompleteLog().values();
assertThat(lifecycleLogRequests)
.extracting(lbRequest -> ((DefaultRequestContext) lbRequest.getContext()).getHint())
.contains(callbackTestHint);
assertThat(anotherLifecycleLogRequests).extracting(CompletionContext::getClientResponse).contains(actualResult);
}
private Request testRequest() {
return testRequest("test");
}
private Request testRequest(String host) {
return Request.create(Request.HttpMethod.GET, "http://" + host + "/path", testHeaders(), "hello".getBytes(),
StandardCharsets.UTF_8, null);
}
private Map<String, Collection<String>> testHeaders() {
Map<String, Collection<String>> feignHeaders = new HashMap<>();
feignHeaders.put(HttpHeaders.CONTENT_TYPE, Collections.singletonList(MediaType.APPLICATION_JSON_VALUE));
return feignHeaders;
}
protected static class TestLoadBalancerLifecycle implements LoadBalancerLifecycle<Object, Object, ServiceInstance> {
final ConcurrentHashMap<String, org.springframework.cloud.client.loadbalancer.Request<Object>> startLog = new ConcurrentHashMap<>();
final ConcurrentHashMap<String, CompletionContext<Object, ServiceInstance>> completeLog = new ConcurrentHashMap<>();
@Override
public void onStart(org.springframework.cloud.client.loadbalancer.Request<Object> request) {
startLog.put(getName() + UUID.randomUUID(), request);
}
@Override
public void onComplete(CompletionContext<Object, ServiceInstance> completionContext) {
completeLog.put(getName() + UUID.randomUUID(), completionContext);
}
ConcurrentHashMap<String, org.springframework.cloud.client.loadbalancer.Request<Object>> getStartLog() {
return startLog;
}
ConcurrentHashMap<String, CompletionContext<Object, ServiceInstance>> getCompleteLog() {
return completeLog;
}
protected String getName() {
return this.getClass().getSimpleName();
}
}
protected static class AnotherLoadBalancerLifecycle
extends FeignBlockingLoadBalancerClientTests.TestLoadBalancerLifecycle {
@Override
protected String getName() {
return this.getClass().getSimpleName();
}
}
}
@@ -52,26 +52,22 @@ public class FeignHttpClientPropertiesTests {
setupContext();
assertThat(getProperties().getConnectionTimeout())
.isEqualTo(FeignHttpClientProperties.DEFAULT_CONNECTION_TIMEOUT);
assertThat(getProperties().getMaxConnections())
.isEqualTo(FeignHttpClientProperties.DEFAULT_MAX_CONNECTIONS);
assertThat(getProperties().getMaxConnections()).isEqualTo(FeignHttpClientProperties.DEFAULT_MAX_CONNECTIONS);
assertThat(getProperties().getMaxConnectionsPerRoute())
.isEqualTo(FeignHttpClientProperties.DEFAULT_MAX_CONNECTIONS_PER_ROUTE);
assertThat(getProperties().getTimeToLive())
.isEqualTo(FeignHttpClientProperties.DEFAULT_TIME_TO_LIVE);
assertThat(getProperties().getTimeToLive()).isEqualTo(FeignHttpClientProperties.DEFAULT_TIME_TO_LIVE);
assertThat(getProperties().isDisableSslValidation())
.isEqualTo(FeignHttpClientProperties.DEFAULT_DISABLE_SSL_VALIDATION);
assertThat(getProperties().isFollowRedirects())
.isEqualTo(FeignHttpClientProperties.DEFAULT_FOLLOW_REDIRECTS);
assertThat(getProperties().isFollowRedirects()).isEqualTo(FeignHttpClientProperties.DEFAULT_FOLLOW_REDIRECTS);
}
@Test
public void testCustomization() {
TestPropertyValues.of("feign.httpclient.maxConnections=2",
"feign.httpclient.connectionTimeout=2",
"feign.httpclient.maxConnectionsPerRoute=2",
"feign.httpclient.timeToLive=2",
"feign.httpclient.disableSslValidation=true",
"feign.httpclient.followRedirects=false").applyTo(this.context);
TestPropertyValues
.of("feign.httpclient.maxConnections=2", "feign.httpclient.connectionTimeout=2",
"feign.httpclient.maxConnectionsPerRoute=2", "feign.httpclient.timeToLive=2",
"feign.httpclient.disableSslValidation=true", "feign.httpclient.followRedirects=false")
.applyTo(this.context);
setupContext();
assertThat(getProperties().getMaxConnections()).isEqualTo(2);
assertThat(getProperties().getConnectionTimeout()).isEqualTo(2);
@@ -82,8 +78,7 @@ public class FeignHttpClientPropertiesTests {
}
private void setupContext() {
this.context.register(PropertyPlaceholderAutoConfiguration.class,
TestConfiguration.class);
this.context.register(PropertyPlaceholderAutoConfiguration.class, TestConfiguration.class);
this.context.refresh();
}
@@ -39,9 +39,8 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
* @author Charlie Mordant.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = SpringEncoderTests.Application.class,
webEnvironment = RANDOM_PORT, value = {
"spring.application.name=springencodertest", "spring.jmx.enabled=false" })
@SpringBootTest(classes = SpringEncoderTests.Application.class, webEnvironment = RANDOM_PORT,
value = { "spring.application.name=springencodertest", "spring.jmx.enabled=false" })
@DirtiesContext
public class PageableEncoderTests {
@@ -16,6 +16,7 @@
package org.springframework.cloud.openfeign.support;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
@@ -40,8 +41,7 @@ import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Olga Maciaszek-Sharma
*/
@SpringBootTest(classes = PageableSupportTest.Config.class,
webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@SpringBootTest(classes = PageableSupportTest.Config.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class PageableSupportTest {
@Autowired
@@ -49,14 +49,17 @@ public class PageableSupportTest {
@BeforeAll
public static void beforeClass() {
System.setProperty("server.port",
String.valueOf(SocketUtils.findAvailableTcpPort()));
System.setProperty("server.port", String.valueOf(SocketUtils.findAvailableTcpPort()));
}
@AfterAll
public static void afterClass() {
System.clearProperty("server.port");
}
@Test
void shouldProperlyFormatPageable() {
String direction = feignClient.performRequest(
PageRequest.of(1, 10, Sort.by(Sort.Order.desc("property"))));
String direction = feignClient.performRequest(PageRequest.of(1, 10, Sort.by(Sort.Order.desc("property"))));
assertThat(direction).isEqualTo("DESC");
}
@@ -67,8 +67,7 @@ class SortJacksonModuleTests {
assertThat(result.getPageable().getPageSize(), is(2));
assertThat(result.getPageable().getSort(), notNullValue());
result.getPageable().getSort();
Optional<Sort.Order> optionalOrder = result.getPageable().getSort().get()
.findFirst();
Optional<Sort.Order> optionalOrder = result.getPageable().getSort().get().findFirst();
if (optionalOrder.isPresent()) {
Sort.Order order = optionalOrder.get();
assertThat(order, hasProperty("property", is("field")));
@@ -66,9 +66,8 @@ import static org.springframework.http.MediaType.MULTIPART_FORM_DATA_VALUE;
* @author Ahmad Mozafarnia
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = SpringEncoderTests.Application.class,
webEnvironment = WebEnvironment.RANDOM_PORT, value = {
"spring.application.name=springencodertest", "spring.jmx.enabled=false" })
@SpringBootTest(classes = SpringEncoderTests.Application.class, webEnvironment = WebEnvironment.RANDOM_PORT,
value = { "spring.application.name=springencodertest", "spring.jmx.enabled=false" })
@DirtiesContext
public class SpringEncoderTests {
@@ -93,16 +92,13 @@ public class SpringEncoderTests {
Collection<String> contentTypeHeader = request.headers().get("Content-Type");
assertThat(contentTypeHeader).as("missing content type header").isNotNull();
assertThat(contentTypeHeader.isEmpty()).as("missing content type header")
.isFalse();
assertThat(contentTypeHeader.isEmpty()).as("missing content type header").isFalse();
String header = contentTypeHeader.iterator().next();
assertThat(header).as("content type header is wrong")
.isEqualTo("application/mytype");
assertThat(header).as("content type header is wrong").isEqualTo("application/mytype");
assertThat(request.requestCharset()).as("request charset is null").isNotNull();
assertThat(request.requestCharset()).as("request charset is wrong")
.isEqualTo(StandardCharsets.UTF_8);
assertThat(request.requestCharset()).as("request charset is wrong").isEqualTo(StandardCharsets.UTF_8);
}
// gh-225
@@ -116,21 +112,17 @@ public class SpringEncoderTests {
};
request.header(HttpEncoding.CONTENT_TYPE, "application/mygenerictype");
encoder.encode(Collections.singletonList("hi"), stringListType.getType(),
request);
encoder.encode(Collections.singletonList("hi"), stringListType.getType(), request);
Collection<String> contentTypeHeader = request.headers().get("Content-Type");
assertThat(contentTypeHeader).as("missing content type header").isNotNull();
assertThat(contentTypeHeader.isEmpty()).as("missing content type header")
.isFalse();
assertThat(contentTypeHeader.isEmpty()).as("missing content type header").isFalse();
String header = contentTypeHeader.iterator().next();
assertThat(header).as("content type header is wrong")
.isEqualTo("application/mygenerictype");
assertThat(header).as("content type header is wrong").isEqualTo("application/mygenerictype");
assertThat(request.requestCharset()).as("request charset is null").isNotNull();
assertThat(request.requestCharset()).as("request charset is wrong")
.isEqualTo(StandardCharsets.UTF_8);
assertThat(request.requestCharset()).as("request charset is wrong").isEqualTo(StandardCharsets.UTF_8);
}
@Test
@@ -142,8 +134,7 @@ public class SpringEncoderTests {
encoder.encode("hi".getBytes(), null, request);
assertThat(((List) request.headers().get(CONTENT_TYPE)).get(0))
.as("Request Content-Type is not octet-stream")
assertThat(((List) request.headers().get(CONTENT_TYPE)).get(0)).as("Request Content-Type is not octet-stream")
.isEqualTo(APPLICATION_OCTET_STREAM_VALUE);
}
@@ -153,8 +144,7 @@ public class SpringEncoderTests {
assertThat(encoder).isNotNull();
RequestTemplate request = new RequestTemplate();
MultipartFile multipartFile = new MockMultipartFile("test_multipart_file",
"hi".getBytes());
MultipartFile multipartFile = new MockMultipartFile("test_multipart_file", "hi".getBytes());
encoder.encode(multipartFile, MultipartFile.class, request);
}
@@ -167,22 +157,19 @@ public class SpringEncoderTests {
request.header(ACCEPT, MediaType.MULTIPART_FORM_DATA_VALUE);
request.header(CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE);
MultipartFile multipartFile = new MockMultipartFile("test_multipart_file",
"hi".getBytes());
MultipartFile multipartFile = new MockMultipartFile("test_multipart_file", "hi".getBytes());
encoder.encode(multipartFile, MultipartFile.class, request);
assertThat((String) ((List) request.headers().get(CONTENT_TYPE)).get(0))
.as("Request Content-Type is not multipart/form-data")
.contains("multipart/form-data; charset=UTF-8; boundary=");
assertThat(request.headers().get(CONTENT_TYPE).size())
.as("There is more than one Content-Type request header").isEqualTo(1);
assertThat(((List) request.headers().get(ACCEPT)).get(0))
.as("Request Accept header is not multipart/form-data")
assertThat(request.headers().get(CONTENT_TYPE).size()).as("There is more than one Content-Type request header")
.isEqualTo(1);
assertThat(((List) request.headers().get(ACCEPT)).get(0)).as("Request Accept header is not multipart/form-data")
.isEqualTo(MULTIPART_FORM_DATA_VALUE);
assertThat(((List) request.headers().get(CONTENT_LENGTH)).get(0))
.as("Request Content-Length is not equal to 186").isEqualTo("186");
assertThat(new String(request.requestBody().asBytes()))
.as("Body content cannot be decoded").contains("hi");
assertThat(new String(request.requestBody().asBytes())).as("Body content cannot be decoded").contains("hi");
}
protected interface TestClient {
@@ -218,8 +205,7 @@ public class SpringEncoderTests {
return new MyGenericHttpMessageConverter();
}
private static class MyHttpMessageConverter
extends AbstractGenericHttpMessageConverter<Object> {
private static class MyHttpMessageConverter extends AbstractGenericHttpMessageConverter<Object> {
MyHttpMessageConverter() {
super(new MediaType("application", "mytype"));
@@ -241,8 +227,7 @@ public class SpringEncoderTests {
}
@Override
protected void writeInternal(Object o, Type type,
HttpOutputMessage outputMessage)
protected void writeInternal(Object o, Type type, HttpOutputMessage outputMessage)
throws HttpMessageNotWritableException {
}
@@ -254,16 +239,14 @@ public class SpringEncoderTests {
}
@Override
public Object read(Type type, Class<?> contextClass,
HttpInputMessage inputMessage)
public Object read(Type type, Class<?> contextClass, HttpInputMessage inputMessage)
throws HttpMessageNotReadableException {
return null;
}
}
private static class MyGenericHttpMessageConverter
extends AbstractGenericHttpMessageConverter<Object> {
private static class MyGenericHttpMessageConverter extends AbstractGenericHttpMessageConverter<Object> {
MyGenericHttpMessageConverter() {
super(new MediaType("application", "mygenerictype"));
@@ -273,8 +256,7 @@ public class SpringEncoderTests {
if (type instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) type;
return parameterizedType.getRawType() == List.class
&& parameterizedType
.getActualTypeArguments()[0] == String.class;
&& parameterizedType.getActualTypeArguments()[0] == String.class;
}
else {
return false;
@@ -292,21 +274,18 @@ public class SpringEncoderTests {
}
@Override
public boolean canRead(Type type, Class<?> contextClass,
MediaType mediaType) {
public boolean canRead(Type type, Class<?> contextClass, MediaType mediaType) {
return canRead(mediaType) && isStringList(type);
}
@Override
protected void writeInternal(Object o, Type type,
HttpOutputMessage outputMessage)
protected void writeInternal(Object o, Type type, HttpOutputMessage outputMessage)
throws HttpMessageNotWritableException {
}
@Override
public Object read(Type type, Class<?> contextClass,
HttpInputMessage inputMessage)
public Object read(Type type, Class<?> contextClass, HttpInputMessage inputMessage)
throws HttpMessageNotReadableException {
return null;
}
@@ -0,0 +1,111 @@
/*
* Copyright 2013-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.openfeign.support;
import java.nio.charset.Charset;
import feign.codec.Decoder;
import feign.codec.Encoder;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.cloud.openfeign.test.NoSecurityConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.http.HttpHeaders;
import org.springframework.util.SocketUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
import static org.assertj.core.api.Assertions.assertThatCode;
/**
* Integration tests for {@link SpringMvcContract}
*
* @author Olga Maciaszek-Sharma
*/
@SpringBootTest(classes = SpringMvcContractIntegrationTests.Config.class,
webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class SpringMvcContractIntegrationTests {
@Autowired
private TestClient client;
@BeforeAll
public static void beforeClass() {
System.setProperty("server.port", String.valueOf(SocketUtils.findAvailableTcpPort()));
}
@AfterAll
public static void afterClass() {
System.clearProperty("server.port");
}
@Test
public void shouldNotThrowInvalidMediaTypeExceptionWhenContentTypeTemplateUsed() {
assertThatCode(() -> client.sendMessage("test", "text/markdown")).doesNotThrowAnyException();
}
@FeignClient(name = "test", url = "http://localhost:${server.port}/",
configuration = NoCodecsFeignConfiguration.class)
interface TestClient {
@PostMapping("/test")
Object sendMessage(@RequestBody String message, @RequestHeader(HttpHeaders.CONTENT_TYPE) String acceptHeader);
}
@Configuration(proxyBeanMethods = false)
@EnableFeignClients(clients = TestClient.class)
@EnableAutoConfiguration
@RestController
@Import(NoSecurityConfiguration.class)
protected static class Config {
@PostMapping("/test")
Object sendMessage(@RequestBody String message, @RequestHeader(HttpHeaders.CONTENT_TYPE) String acceptHeader) {
return message;
}
}
// avoid feign.codec.EncodeException - this feature works for users that override
// Encoder
protected static class NoCodecsFeignConfiguration {
@Bean
public Decoder decoder() {
return (response, type) -> response;
}
@Bean
public Encoder encoder() {
return (object, bodyType, request) -> request.body(object.toString().getBytes(), Charset.defaultCharset());
}
}
}
@@ -31,11 +31,8 @@ import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import feign.MethodMetadata;
import feign.Param;
import junitparams.JUnitParamsRunner;
import junitparams.Parameters;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.cloud.openfeign.CollectionFormat;
import org.springframework.cloud.openfeign.SpringQueryMap;
@@ -75,7 +72,6 @@ import static org.junit.Assume.assumeTrue;
* @author Artyom Romanenko
* @author Olga Maciaszek-Sharma
*/
@RunWith(JUnitParamsRunner.class)
public class SpringMvcContractTests {
private static final Class<?> EXECUTABLE_TYPE;
@@ -102,19 +98,15 @@ public class SpringMvcContractTests {
* @throws IllegalArgumentException if method has no parameters
*/
private static boolean hasJava8ParameterNames(Method m) {
org.springframework.util.Assert.isTrue(m.getParameterTypes().length > 0,
"method has no parameters");
org.springframework.util.Assert.isTrue(m.getParameterTypes().length > 0, "method has no parameters");
if (EXECUTABLE_TYPE != null) {
Method getParameters = ReflectionUtils.findMethod(EXECUTABLE_TYPE,
"getParameters");
Method getParameters = ReflectionUtils.findMethod(EXECUTABLE_TYPE, "getParameters");
try {
Object[] parameters = (Object[]) getParameters.invoke(m);
Method isNamePresent = ReflectionUtils
.findMethod(parameters[0].getClass(), "isNamePresent");
Method isNamePresent = ReflectionUtils.findMethod(parameters[0].getClass(), "isNamePresent");
return Boolean.TRUE.equals(isNamePresent.invoke(parameters[0]));
}
catch (IllegalAccessException | IllegalArgumentException
| InvocationTargetException ex) {
catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
}
}
return false;
@@ -131,10 +123,8 @@ public class SpringMvcContractTests {
@Test
public void testProcessAnnotationOnMethod_Simple() throws Exception {
Method method = TestTemplate_Simple.class.getDeclaredMethod("getTest",
String.class);
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
Method method = TestTemplate_Simple.class.getDeclaredMethod("getTest", String.class);
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
assertThat(data.template().url()).isEqualTo("/test/{id}");
assertThat(data.template().method()).isEqualTo("GET");
@@ -144,10 +134,8 @@ public class SpringMvcContractTests {
@Test
public void testProcessAnnotations_Simple() throws Exception {
Method method = TestTemplate_Simple.class.getDeclaredMethod("getTest",
String.class);
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
Method method = TestTemplate_Simple.class.getDeclaredMethod("getTest", String.class);
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
assertThat(data.template().url()).isEqualTo("/test/{id}");
assertThat(data.template().method()).isEqualTo("GET");
@@ -159,10 +147,8 @@ public class SpringMvcContractTests {
@Test
public void testProcessAnnotations_SimpleGetMapping() throws Exception {
Method method = TestTemplate_Simple.class.getDeclaredMethod("getMappingTest",
String.class);
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
Method method = TestTemplate_Simple.class.getDeclaredMethod("getMappingTest", String.class);
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
assertThat(data.template().url()).isEqualTo("/test/{id}");
assertThat(data.template().method()).isEqualTo("GET");
@@ -173,12 +159,10 @@ public class SpringMvcContractTests {
}
@Test
public void testProcessAnnotations_Class_AnnotationsGetSpecificTest()
throws Exception {
Method method = TestTemplate_Class_Annotations.class
.getDeclaredMethod("getSpecificTest", String.class, String.class);
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
public void testProcessAnnotations_Class_AnnotationsGetSpecificTest() throws Exception {
Method method = TestTemplate_Class_Annotations.class.getDeclaredMethod("getSpecificTest", String.class,
String.class);
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
assertThat(data.template().url()).isEqualTo("/prepend/{classId}/test/{testId}");
assertThat(data.template().method()).isEqualTo("GET");
@@ -189,10 +173,8 @@ public class SpringMvcContractTests {
@Test
public void testProcessAnnotations_Class_AnnotationsGetAllTests() throws Exception {
Method method = TestTemplate_Class_Annotations.class
.getDeclaredMethod("getAllTests", String.class);
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
Method method = TestTemplate_Class_Annotations.class.getDeclaredMethod("getAllTests", String.class);
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
assertThat(data.template().url()).isEqualTo("/prepend/{classId}");
assertThat(data.template().method()).isEqualTo("GET");
@@ -202,29 +184,23 @@ public class SpringMvcContractTests {
@Test
public void testProcessAnnotations_ExtendedInterface() throws Exception {
Method extendedMethod = TestTemplate_Extended.class.getMethod("getAllTests",
String.class);
MethodMetadata extendedData = contract.parseAndValidateMetadata(
extendedMethod.getDeclaringClass(), extendedMethod);
Method extendedMethod = TestTemplate_Extended.class.getMethod("getAllTests", String.class);
MethodMetadata extendedData = contract.parseAndValidateMetadata(extendedMethod.getDeclaringClass(),
extendedMethod);
Method method = TestTemplate_Class_Annotations.class
.getDeclaredMethod("getAllTests", String.class);
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
Method method = TestTemplate_Class_Annotations.class.getDeclaredMethod("getAllTests", String.class);
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
assertThat(data.template().url()).isEqualTo(extendedData.template().url());
assertThat(data.template().method()).isEqualTo(extendedData.template().method());
assertThat(data.indexToName().get(0).iterator().next())
.isEqualTo(data.indexToName().get(0).iterator().next());
assertThat(data.indexToName().get(0).iterator().next()).isEqualTo(data.indexToName().get(0).iterator().next());
}
@Test
public void testProcessAnnotations_SimplePost() throws Exception {
Method method = TestTemplate_Simple.class.getDeclaredMethod("postTest",
TestObject.class);
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
Method method = TestTemplate_Simple.class.getDeclaredMethod("postTest", TestObject.class);
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
assertThat(data.template().url()).isEqualTo("/");
assertThat(data.template().method()).isEqualTo("POST");
@@ -235,10 +211,8 @@ public class SpringMvcContractTests {
@Test
public void testProcessAnnotations_SimplePostMapping() throws Exception {
Method method = TestTemplate_Simple.class.getDeclaredMethod("postMappingTest",
TestObject.class);
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
Method method = TestTemplate_Simple.class.getDeclaredMethod("postMappingTest", TestObject.class);
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
assertThat(data.template().url()).isEqualTo("/");
assertThat(data.template().method()).isEqualTo("POST");
@@ -249,102 +223,82 @@ public class SpringMvcContractTests {
@Test
public void testProcessAnnotationsOnMethod_Advanced() throws Exception {
Method method = TestTemplate_Advanced.class.getDeclaredMethod("getTest",
String.class, String.class, Integer.class);
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
Method method = TestTemplate_Advanced.class.getDeclaredMethod("getTest", String.class, String.class,
Integer.class);
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
assertThat(data.template().url())
.isEqualTo("/advanced/test/{id}?amount=" + "{amount}");
assertThat(data.template().url()).isEqualTo("/advanced/test/{id}?amount=" + "{amount}");
assertThat(data.template().method()).isEqualTo("PUT");
assertThat(data.template().headers().get("Accept").iterator().next())
.isEqualTo(MediaType.APPLICATION_JSON_VALUE);
}
@Test
public void testProcessAnnotationsOnMethod_Advanced_UnknownAnnotation()
throws Exception {
Method method = TestTemplate_Advanced.class.getDeclaredMethod("getTest",
String.class, String.class, Integer.class);
public void testProcessAnnotationsOnMethod_Advanced_UnknownAnnotation() throws Exception {
Method method = TestTemplate_Advanced.class.getDeclaredMethod("getTest", String.class, String.class,
Integer.class);
contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
// Don't throw an exception and this passes
}
@Test
public void testProcessAnnotationsOnMethod_CollectionFormat()
throws NoSuchMethodException {
Method method = TestTemplate_Advanced.class
.getDeclaredMethod("getWithCollectionFormat");
public void testProcessAnnotationsOnMethod_CollectionFormat() throws NoSuchMethodException {
Method method = TestTemplate_Advanced.class.getDeclaredMethod("getWithCollectionFormat");
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
assertThat(data.template().collectionFormat()).isEqualTo(SSV);
}
@Test
public void testProcessAnnotations_Advanced() throws Exception {
Method method = TestTemplate_Advanced.class.getDeclaredMethod("getTest",
String.class, String.class, Integer.class);
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
Method method = TestTemplate_Advanced.class.getDeclaredMethod("getTest", String.class, String.class,
Integer.class);
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
assertThat(data.template().url())
.isEqualTo("/advanced/test/{id}?amount=" + "{amount}");
assertThat(data.template().url()).isEqualTo("/advanced/test/{id}?amount=" + "{amount}");
assertThat(data.template().method()).isEqualTo("PUT");
assertThat(data.template().headers().get("Accept").iterator().next())
.isEqualTo(MediaType.APPLICATION_JSON_VALUE);
assertThat(data.indexToName().get(0).iterator().next())
.isEqualTo("Authorization");
assertThat(data.indexToName().get(0).iterator().next()).isEqualTo("Authorization");
assertThat(data.indexToName().get(1).iterator().next()).isEqualTo("id");
assertThat(data.indexToName().get(2).iterator().next()).isEqualTo("amount");
assertThat(data.indexToExpander().get(2)).isNotNull();
assertThat(data.template().headers().get("Authorization").iterator().next())
.isEqualTo("{Authorization}");
assertThat(data.template().queries().get("amount").iterator().next())
.isEqualTo("{amount}");
assertThat(data.template().headers().get("Authorization").iterator().next()).isEqualTo("{Authorization}");
assertThat(data.template().queries().get("amount").iterator().next()).isEqualTo("{amount}");
}
@Test
public void testProcessAnnotations_Aliased() throws Exception {
Method method = TestTemplate_Advanced.class.getDeclaredMethod("getTest2",
String.class, Integer.class);
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
Method method = TestTemplate_Advanced.class.getDeclaredMethod("getTest2", String.class, Integer.class);
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
assertThat(data.template().url())
.isEqualTo("/advanced/test2?amount=" + "{amount}");
assertThat(data.template().url()).isEqualTo("/advanced/test2?amount=" + "{amount}");
assertThat(data.template().method()).isEqualTo("PUT");
assertThat(data.template().headers().get("Accept").iterator().next())
.isEqualTo(MediaType.APPLICATION_JSON_VALUE);
assertThat(data.indexToName().get(0).iterator().next())
.isEqualTo("Authorization");
assertThat(data.indexToName().get(0).iterator().next()).isEqualTo("Authorization");
assertThat(data.indexToName().get(1).iterator().next()).isEqualTo("amount");
assertThat(data.template().headers().get("Authorization").iterator().next())
.isEqualTo("{Authorization}");
assertThat(data.template().queries().get("amount").iterator().next())
.isEqualTo("{amount}");
assertThat(data.template().headers().get("Authorization").iterator().next()).isEqualTo("{Authorization}");
assertThat(data.template().queries().get("amount").iterator().next()).isEqualTo("{amount}");
}
@Test
public void testProcessAnnotations_DateTimeFormatParam() throws Exception {
Method method = TestTemplate_DateTimeFormatParameter.class
.getDeclaredMethod("getTest", LocalDateTime.class);
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
Method method = TestTemplate_DateTimeFormatParameter.class.getDeclaredMethod("getTest", LocalDateTime.class);
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
Param.Expander expander = data.indexToExpander().get(0);
assertThat(expander).isNotNull();
LocalDateTime input = LocalDateTime.of(2001, 10, 12, 23, 56, 3);
DateTimeFormatter formatter = DateTimeFormatter
.ofPattern(TestTemplate_DateTimeFormatParameter.CUSTOM_PATTERN);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(TestTemplate_DateTimeFormatParameter.CUSTOM_PATTERN);
String expected = formatter.format(input);
@@ -353,16 +307,13 @@ public class SpringMvcContractTests {
@Test
public void testProcessAnnotations_NumberFormatParam() throws Exception {
Method method = TestTemplate_NumberFormatParameter.class
.getDeclaredMethod("getTest", BigDecimal.class);
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
Method method = TestTemplate_NumberFormatParameter.class.getDeclaredMethod("getTest", BigDecimal.class);
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
Param.Expander expander = data.indexToExpander().get(0);
assertThat(expander).isNotNull();
NumberStyleFormatter formatter = new NumberStyleFormatter(
TestTemplate_NumberFormatParameter.CUSTOM_PATTERN);
NumberStyleFormatter formatter = new NumberStyleFormatter(TestTemplate_NumberFormatParameter.CUSTOM_PATTERN);
BigDecimal input = BigDecimal.valueOf(1220.345);
@@ -375,8 +326,7 @@ public class SpringMvcContractTests {
@Test
public void testProcessAnnotations_Advanced2() throws Exception {
Method method = TestTemplate_Advanced.class.getDeclaredMethod("getTest");
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
assertThat(data.template().url()).isEqualTo("/advanced");
assertThat(data.template().method()).isEqualTo("GET");
@@ -387,8 +337,7 @@ public class SpringMvcContractTests {
@Test
public void testProcessAnnotations_Advanced3() throws Exception {
Method method = TestTemplate_Simple.class.getDeclaredMethod("getTest");
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
assertThat(data.template().url()).isEqualTo("/");
assertThat(data.template().method()).isEqualTo("GET");
@@ -398,10 +347,8 @@ public class SpringMvcContractTests {
@Test
public void testProcessAnnotations_ListParams() throws Exception {
Method method = TestTemplate_ListParams.class.getDeclaredMethod("getTest",
List.class);
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
Method method = TestTemplate_ListParams.class.getDeclaredMethod("getTest", List.class);
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
assertThat(data.template().url()).isEqualTo("/test?id=" + "{id}");
assertThat(data.template().method()).isEqualTo("GET");
@@ -411,10 +358,8 @@ public class SpringMvcContractTests {
@Test
public void testProcessAnnotations_ListParamsWithoutName() throws Exception {
Method method = TestTemplate_ListParamsWithoutName.class
.getDeclaredMethod("getTest", List.class);
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
Method method = TestTemplate_ListParamsWithoutName.class.getDeclaredMethod("getTest", List.class);
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
assertThat(data.template().url()).isEqualTo("/test?id=" + "{id}");
assertThat(data.template().method()).isEqualTo("GET");
@@ -424,10 +369,8 @@ public class SpringMvcContractTests {
@Test
public void testProcessAnnotations_MapParams() throws Exception {
Method method = TestTemplate_MapParams.class.getDeclaredMethod("getTest",
Map.class);
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
Method method = TestTemplate_MapParams.class.getDeclaredMethod("getTest", Map.class);
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
assertThat(data.template().url()).isEqualTo("/test");
assertThat(data.template().method()).isEqualTo("GET");
@@ -437,23 +380,18 @@ public class SpringMvcContractTests {
@Test
public void testProcessHeaders() throws Exception {
Method method = TestTemplate_Headers.class.getDeclaredMethod("getTest",
String.class);
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
Method method = TestTemplate_Headers.class.getDeclaredMethod("getTest", String.class);
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
assertThat(data.template().url()).isEqualTo("/test/{id}");
assertThat(data.template().method()).isEqualTo("GET");
assertThat(data.template().headers().get("x-Foo").iterator().next())
.isEqualTo("bar");
assertThat(data.template().headers().get("x-Foo").iterator().next()).isEqualTo("bar");
}
@Test
public void testProcessHeadersWithoutValues() throws Exception {
Method method = TestTemplate_HeadersWithoutValues.class
.getDeclaredMethod("getTest", String.class);
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
Method method = TestTemplate_HeadersWithoutValues.class.getDeclaredMethod("getTest", String.class);
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
assertThat(data.template().url()).isEqualTo("/test/{id}");
assertThat(data.template().method()).isEqualTo("GET");
@@ -462,38 +400,30 @@ public class SpringMvcContractTests {
@Test
public void testProcessAnnotations_Fallback() throws Exception {
Method method = TestTemplate_Advanced.class.getDeclaredMethod("getTestFallback",
String.class, String.class, Integer.class);
Method method = TestTemplate_Advanced.class.getDeclaredMethod("getTestFallback", String.class, String.class,
Integer.class);
assumeTrue("does not have java 8 parameter names",
hasJava8ParameterNames(method));
assumeTrue("does not have java 8 parameter names", hasJava8ParameterNames(method));
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
assertThat(data.template().url())
.isEqualTo("/advanced/testfallback/{id}?amount=" + "{amount}");
assertThat(data.template().url()).isEqualTo("/advanced/testfallback/{id}?amount=" + "{amount}");
assertThat(data.template().method()).isEqualTo("PUT");
assertThat(data.template().headers().get("Accept").iterator().next())
.isEqualTo(MediaType.APPLICATION_JSON_VALUE);
assertThat(data.indexToName().get(0).iterator().next())
.isEqualTo("Authorization");
assertThat(data.indexToName().get(0).iterator().next()).isEqualTo("Authorization");
assertThat(data.indexToName().get(1).iterator().next()).isEqualTo("id");
assertThat(data.indexToName().get(2).iterator().next()).isEqualTo("amount");
assertThat(data.template().headers().get("Authorization").iterator().next())
.isEqualTo("{Authorization}");
assertThat(data.template().queries().get("amount").iterator().next())
.isEqualTo("{amount}");
assertThat(data.template().headers().get("Authorization").iterator().next()).isEqualTo("{Authorization}");
assertThat(data.template().queries().get("amount").iterator().next()).isEqualTo("{amount}");
}
@Test
public void testProcessHeaderMap() throws Exception {
Method method = TestTemplate_HeaderMap.class.getDeclaredMethod("headerMap",
MultiValueMap.class, String.class);
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
Method method = TestTemplate_HeaderMap.class.getDeclaredMethod("headerMap", MultiValueMap.class, String.class);
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
assertThat(data.template().url()).isEqualTo("/headerMap");
assertThat(data.template().method()).isEqualTo("GET");
@@ -504,17 +434,15 @@ public class SpringMvcContractTests {
@Test(expected = IllegalStateException.class)
public void testProcessHeaderMapMoreThanOnce() throws Exception {
Method method = TestTemplate_HeaderMap.class.getDeclaredMethod(
"headerMapMoreThanOnce", MultiValueMap.class, MultiValueMap.class);
Method method = TestTemplate_HeaderMap.class.getDeclaredMethod("headerMapMoreThanOnce", MultiValueMap.class,
MultiValueMap.class);
contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
}
@Test
public void testProcessQueryMap() throws Exception {
Method method = TestTemplate_QueryMap.class.getDeclaredMethod("queryMap",
MultiValueMap.class, String.class);
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
Method method = TestTemplate_QueryMap.class.getDeclaredMethod("queryMap", MultiValueMap.class, String.class);
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
assertThat(data.template().url()).isEqualTo("/queryMap?aParam=" + "{aParam}");
assertThat(data.template().method()).isEqualTo("GET");
@@ -525,13 +453,10 @@ public class SpringMvcContractTests {
@Test
public void testProcessQueryMapObject() throws Exception {
Method method = TestTemplate_QueryMap.class.getDeclaredMethod("queryMapObject",
TestObject.class, String.class);
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
Method method = TestTemplate_QueryMap.class.getDeclaredMethod("queryMapObject", TestObject.class, String.class);
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
assertThat(data.template().url())
.isEqualTo("/queryMapObject?aParam=" + "{aParam}");
assertThat(data.template().url()).isEqualTo("/queryMapObject?aParam=" + "{aParam}");
assertThat(data.template().method()).isEqualTo("GET");
assertThat(data.queryMapIndex().intValue()).isEqualTo(0);
Map<String, Collection<String>> params = data.template().queries();
@@ -540,140 +465,77 @@ public class SpringMvcContractTests {
@Test(expected = IllegalStateException.class)
public void testProcessQueryMapMoreThanOnce() throws Exception {
Method method = TestTemplate_QueryMap.class.getDeclaredMethod(
"queryMapMoreThanOnce", MultiValueMap.class, MultiValueMap.class);
Method method = TestTemplate_QueryMap.class.getDeclaredMethod("queryMapMoreThanOnce", MultiValueMap.class,
MultiValueMap.class);
contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
}
@Test
public void testMatrixVariable_MapParam() throws Exception {
Method method = TestTemplate_MatrixVariable.class
.getDeclaredMethod("matrixVariable", Map.class);
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
Method method = TestTemplate_MatrixVariable.class.getDeclaredMethod("matrixVariable", Map.class);
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
Map<String, String> testMap = new HashMap<>();
testMap.put("param", "value");
assertThat(data.template().method()).isEqualTo("GET");
assertThat(data.template().url()).isEqualTo("/matrixVariable/{params}");
assertThat(";param=value")
.isEqualTo(data.indexToExpander().get(0).expand(testMap));
assertThat(";param=value").isEqualTo(data.indexToExpander().get(0).expand(testMap));
}
@Test
public void testMatrixVariable_ObjectParam() throws Exception {
Method method = TestTemplate_MatrixVariable.class
.getDeclaredMethod("matrixVariableObject", Object.class);
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
Method method = TestTemplate_MatrixVariable.class.getDeclaredMethod("matrixVariableObject", Object.class);
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
assertThat(data.template().method()).isEqualTo("GET");
assertThat(data.template().url()).isEqualTo("/matrixVariableObject/{param}");
assertThat(";param=value")
.isEqualTo(data.indexToExpander().get(0).expand("value"));
assertThat(";param=value").isEqualTo(data.indexToExpander().get(0).expand("value"));
}
@Test
public void testMatrixVariableWithNoName() throws NoSuchMethodException {
Method method = TestTemplate_MatrixVariable.class
.getDeclaredMethod("matrixVariableNotNamed", Map.class);
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
Method method = TestTemplate_MatrixVariable.class.getDeclaredMethod("matrixVariableNotNamed", Map.class);
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
Map<String, String> testMap = new HashMap<>();
testMap.put("param", "value");
assertThat(data.template().method()).isEqualTo("GET");
assertThat(data.template().url()).isEqualTo("/matrixVariable/{params}");
assertThat(";param=value")
.isEqualTo(data.indexToExpander().get(0).expand(testMap));
assertThat(";param=value").isEqualTo(data.indexToExpander().get(0).expand(testMap));
}
@Test
public void testAddingTemplatedParameterWithTheSameKey()
throws NoSuchMethodException {
Method method = TestTemplate_Advanced.class.getDeclaredMethod(
"testAddingTemplatedParamForExistingKey", String.class);
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
public void testAddingTemplatedParameterWithTheSameKey() throws NoSuchMethodException {
Method method = TestTemplate_Advanced.class.getDeclaredMethod("testAddingTemplatedParamForExistingKey",
String.class);
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
assertThat(data.template().headers().get("Accept")).contains("application/json",
"{Accept}");
}
private Class[] doubleMappingClassesProvider() {
return new Class[] { TestTemplate_RequestMapping_Empty_Class.class,
TestTemplate_RequestMapping_Empty_Method.class };
}
@Test
@Parameters(method = "doubleMappingClassesProvider")
public void testDoubleRequestMapping_root(Class clazz) throws NoSuchMethodException {
Method method = clazz.getDeclaredMethod("root");
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
assertThat(data.template().url()).isEqualTo("/");
}
@Test
@Parameters(method = "doubleMappingClassesProvider")
public void testDoubleRequestMapping_rootReverse(Class clazz)
throws NoSuchMethodException {
Method method = clazz.getDeclaredMethod("rootReverse");
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
assertThat(data.template().url()).isEqualTo("/");
}
@Test
@Parameters(method = "doubleMappingClassesProvider")
public void testDoubleRequestMapping_sub(Class clazz) throws NoSuchMethodException {
Method method = clazz.getDeclaredMethod("sub");
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
assertThat(data.template().url()).isEqualTo("/sub");
}
@Test
@Parameters(method = "doubleMappingClassesProvider")
public void testDoubleRequestMapping_subEmpty(Class clazz)
throws NoSuchMethodException {
Method method = clazz.getDeclaredMethod("subEmpty");
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
assertThat(data.template().url()).isEqualTo("/subEmpty");
assertThat(data.template().headers().get("Accept")).contains("application/json", "{Accept}");
}
@Test
public void testMultipleRequestPartAnnotations() throws NoSuchMethodException {
Method method = TestTemplate_RequestPart.class.getDeclaredMethod(
"requestWithMultipleParts", MultipartFile.class, String.class);
Method method = TestTemplate_RequestPart.class.getDeclaredMethod("requestWithMultipleParts",
MultipartFile.class, String.class);
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
assertThat(data.formParams()).contains("file", "id");
}
public interface TestTemplate_Simple {
@RequestMapping(value = "/test/{id}", method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@RequestMapping(value = "/test/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
ResponseEntity<TestObject> getTest(@PathVariable("id") String id);
@RequestMapping(method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
TestObject getTest();
@GetMapping(value = "/test/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
ResponseEntity<TestObject> getMappingTest(@PathVariable("id") String id);
@RequestMapping(method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE)
@RequestMapping(method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
TestObject postTest(@RequestBody TestObject object);
@PostMapping(produces = MediaType.APPLICATION_JSON_VALUE)
@@ -685,8 +547,7 @@ public class SpringMvcContractTests {
public interface TestTemplate_Class_Annotations {
@RequestMapping(value = "/test/{testId}", method = RequestMethod.GET)
TestObject getSpecificTest(@PathVariable("classId") String classId,
@PathVariable("testId") String testId);
TestObject getSpecificTest(@PathVariable("classId") String classId, @PathVariable("testId") String testId);
@RequestMapping(method = RequestMethod.GET)
TestObject getAllTests(@PathVariable("classId") String classId);
@@ -699,8 +560,7 @@ public class SpringMvcContractTests {
public interface TestTemplate_Headers {
@RequestMapping(value = "/test/{id}", method = RequestMethod.GET,
headers = "X-Foo=bar")
@RequestMapping(value = "/test/{id}", method = RequestMethod.GET, headers = "X-Foo=bar")
ResponseEntity<TestObject> getTest(@PathVariable("id") String id);
}
@@ -741,8 +601,7 @@ public class SpringMvcContractTests {
@RequestHeader(name = "aHeader") String aHeader);
@RequestMapping(path = "/headerMapMoreThanOnce")
String headerMapMoreThanOnce(
@RequestHeader MultiValueMap<String, String> headerMap1,
String headerMapMoreThanOnce(@RequestHeader MultiValueMap<String, String> headerMap1,
@RequestHeader MultiValueMap<String, String> headerMap2);
}
@@ -758,8 +617,7 @@ public class SpringMvcContractTests {
@RequestParam MultiValueMap<String, String> queryMap2);
@RequestMapping(path = "/queryMapObject")
String queryMapObject(@SpringQueryMap TestObject queryMap,
@RequestParam(name = "aParam") String aParam);
String queryMapObject(@SpringQueryMap TestObject queryMap, @RequestParam(name = "aParam") String aParam);
}
@@ -767,8 +625,7 @@ public class SpringMvcContractTests {
@RequestMapping(path = "/requestPart", method = RequestMethod.POST,
consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
void requestWithMultipleParts(@RequestPart("file") MultipartFile file,
@RequestPart("id") String identifier);
void requestWithMultipleParts(@RequestPart("file") MultipartFile file, @RequestPart("id") String identifier);
}
@@ -794,30 +651,25 @@ public class SpringMvcContractTests {
ResponseEntity<TestObject> getWithCollectionFormat();
@ExceptionHandler
@RequestMapping(path = "/test/{id}", method = RequestMethod.PUT,
produces = MediaType.APPLICATION_JSON_VALUE)
ResponseEntity<TestObject> getTest(@RequestHeader("Authorization") String auth,
@PathVariable("id") String id, @RequestParam("amount") Integer amount);
@RequestMapping(path = "/test/{id}", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE)
ResponseEntity<TestObject> getTest(@RequestHeader("Authorization") String auth, @PathVariable("id") String id,
@RequestParam("amount") Integer amount);
@RequestMapping(path = "/test2", method = RequestMethod.PUT,
produces = MediaType.APPLICATION_JSON_VALUE)
ResponseEntity<TestObject> getTest2(
@RequestHeader(name = "Authorization") String auth,
@RequestMapping(path = "/test2", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE)
ResponseEntity<TestObject> getTest2(@RequestHeader(name = "Authorization") String auth,
@RequestParam(name = "amount") Integer amount);
@ExceptionHandler
@RequestMapping(path = "/testfallback/{id}", method = RequestMethod.PUT,
produces = MediaType.APPLICATION_JSON_VALUE)
ResponseEntity<TestObject> getTestFallback(@RequestHeader String Authorization,
@PathVariable String id, @RequestParam Integer amount);
ResponseEntity<TestObject> getTestFallback(@RequestHeader String Authorization, @PathVariable String id,
@RequestParam Integer amount);
@RequestMapping(method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
TestObject getTest();
@GetMapping(produces = "application/json")
String testAddingTemplatedParamForExistingKey(
@RequestHeader("Accept") String accept);
String testAddingTemplatedParamForExistingKey(@RequestHeader("Accept") String accept);
}
@@ -836,47 +688,11 @@ public class SpringMvcContractTests {
String CUSTOM_PATTERN = "$###,###.###";
@RequestMapping(method = RequestMethod.GET)
String getTest(@RequestParam("amount") @NumberFormat(
pattern = CUSTOM_PATTERN) BigDecimal amount);
String getTest(@RequestParam("amount") @NumberFormat(pattern = CUSTOM_PATTERN) BigDecimal amount);
}
@RequestMapping("")
public interface TestTemplate_RequestMapping_Empty_Class {
@RequestMapping("/")
String root();
@RequestMapping("")
String rootReverse();
@RequestMapping("/sub")
String sub();
@RequestMapping("subEmpty")
String subEmpty();
}
@RequestMapping("/")
public interface TestTemplate_RequestMapping_Empty_Method {
@RequestMapping("")
String root();
@RequestMapping("/")
String rootReverse();
@RequestMapping("/sub")
String sub();
@RequestMapping("subEmpty")
String subEmpty();
}
@JsonAutoDetect(fieldVisibility = ANY, getterVisibility = NONE,
setterVisibility = NONE)
@JsonAutoDetect(fieldVisibility = ANY, getterVisibility = NONE, setterVisibility = NONE)
public class TestObject {
public String something;
@@ -905,8 +721,7 @@ public class SpringMvcContractTests {
if (number != null ? !number.equals(that.number) : that.number != null) {
return false;
}
if (something != null ? !something.equals(that.something)
: that.something != null) {
if (something != null ? !something.equals(that.something) : that.something != null) {
return false;
}
@@ -922,9 +737,8 @@ public class SpringMvcContractTests {
@Override
public String toString() {
return new StringBuilder("TestObject{").append("something='")
.append(something).append("', ").append("number=").append(number)
.append("}").toString();
return new StringBuilder("TestObject{").append("something='").append(something).append("', ")
.append("number=").append(number).append("}").toString();
}
}
@@ -33,8 +33,7 @@ import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeader;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.mockito.MockingDetails;
import org.mockito.Mockito;
@@ -52,7 +51,6 @@ import org.springframework.cloud.openfeign.loadbalancer.FeignBlockingLoadBalance
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.ReflectionUtils;
import static org.assertj.core.api.Assertions.assertThat;
@@ -63,11 +61,11 @@ import static org.mockito.Mockito.mockingDetails;
/**
* @author Ryan Baxter
* @author Olga Maciaszek-Sharma
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(properties = { "feign.okhttp.enabled: false" })
@SpringBootTest(properties = { "feign.okhttp.enabled: false", "spring.cloud.loadbalancer.retry.enabled=false" })
@DirtiesContext
public class ApacheHttpClientConfigurationTests {
class ApacheHttpClientConfigurationTests {
@Autowired
ApacheHttpClientConnectionManagerFactory connectionManagerFactory;
@@ -79,19 +77,18 @@ public class ApacheHttpClientConfigurationTests {
FeignBlockingLoadBalancerClient feignClient;
@Test
public void testFactories() {
assertThat(this.connectionManagerFactory)
.isInstanceOf(ApacheHttpClientConnectionManagerFactory.class);
assertThat(this.connectionManagerFactory).isInstanceOf(
ApacheHttpClientConfigurationTestApp.MyApacheHttpClientConnectionManagerFactory.class);
assertThat(this.httpClientFactory).isInstanceOf(ApacheHttpClientFactory.class);
assertThat(this.httpClientFactory).isInstanceOf(
ApacheHttpClientConfigurationTestApp.MyApacheHttpClientFactory.class);
void testFactories() {
assertThat(connectionManagerFactory).isInstanceOf(ApacheHttpClientConnectionManagerFactory.class);
assertThat(connectionManagerFactory)
.isInstanceOf(ApacheHttpClientConfigurationTestApp.MyApacheHttpClientConnectionManagerFactory.class);
assertThat(httpClientFactory).isInstanceOf(ApacheHttpClientFactory.class);
assertThat(httpClientFactory)
.isInstanceOf(ApacheHttpClientConfigurationTestApp.MyApacheHttpClientFactory.class);
}
@Test
public void testHttpClientWithFeign() {
Client delegate = this.feignClient.getDelegate();
void testHttpClientWithFeign() {
Client delegate = feignClient.getDelegate();
assertThat(ApacheHttpClient.class.isInstance(delegate)).isTrue();
ApacheHttpClient apacheHttpClient = (ApacheHttpClient) delegate;
HttpClient httpClient = getField(apacheHttpClient, "client");
@@ -108,8 +105,7 @@ public class ApacheHttpClientConfigurationTests {
@SpringBootConfiguration
@EnableAutoConfiguration
@EnableFeignClients(
clients = { ApacheHttpClientConfigurationTestApp.FooClient.class })
@EnableFeignClients(clients = { ApacheHttpClientConfigurationTestApp.FooClient.class })
static class ApacheHttpClientConfigurationTestApp {
@FeignClient(name = "foo", serviceId = "foo")
@@ -121,9 +117,8 @@ public class ApacheHttpClientConfigurationTests {
extends DefaultApacheHttpClientConnectionManagerFactory {
@Override
public HttpClientConnectionManager newConnectionManager(
boolean disableSslValidation, int maxTotalConnections,
int maxConnectionsPerRoute, long timeToLive, TimeUnit timeUnit,
public HttpClientConnectionManager newConnectionManager(boolean disableSslValidation,
int maxTotalConnections, int maxConnectionsPerRoute, long timeToLive, TimeUnit timeUnit,
RegistryBuilder registry) {
return mock(PoolingHttpClientConnectionManager.class);
}
@@ -146,8 +141,7 @@ public class ApacheHttpClientConfigurationTests {
Header[] headers = new BasicHeader[0];
doReturn(headers).when(response).getAllHeaders();
try {
Mockito.doReturn(response).when(client)
.execute(any(HttpUriRequest.class));
Mockito.doReturn(response).when(client).execute(any(HttpUriRequest.class));
}
catch (IOException e) {
e.printStackTrace();
@@ -163,8 +157,7 @@ public class ApacheHttpClientConfigurationTests {
static class MyConfig {
@Bean
public ApacheHttpClientFactory apacheHttpClientFactory(
HttpClientBuilder builder) {
public ApacheHttpClientFactory apacheHttpClientFactory(HttpClientBuilder builder) {
return new MyApacheHttpClientFactory(builder);
}
@@ -21,8 +21,7 @@ import java.util.concurrent.TimeUnit;
import feign.Client;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.mockito.MockingDetails;
import org.springframework.beans.factory.annotation.Autowired;
@@ -37,7 +36,6 @@ import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.cloud.openfeign.loadbalancer.FeignBlockingLoadBalancerClient;
import org.springframework.context.annotation.Bean;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.util.ReflectionTestUtils;
import static org.assertj.core.api.Assertions.assertThat;
@@ -46,15 +44,14 @@ import static org.mockito.Mockito.mockingDetails;
/**
* @author Ryan Baxter
* @author Olga Maciaszek-Sharma
*/
@RunWith(SpringRunner.class)
@SpringBootTest(properties = { "feign.okhttp.enabled: true",
"spring.cloud.httpclientfactories.ok.enabled: true",
"ribbon.eureka.enabled = false", "ribbon.okhttp.enabled: true",
"feign.okhttp.enabled: true", "ribbon.httpclient.enabled: false",
"feign.httpclient.enabled: false" })
@SpringBootTest(properties = { "feign.okhttp.enabled: true", "spring.cloud.httpclientfactories.ok.enabled: true",
"ribbon.eureka.enabled = false", "ribbon.okhttp.enabled: true", "feign.okhttp.enabled: true",
"ribbon.httpclient.enabled: false", "feign.httpclient.enabled: false",
"spring.cloud.loadbalancer.retry.enabled=false" })
@DirtiesContext
public class OkHttpClientConfigurationTests {
class OkHttpClientConfigurationTests {
@Autowired
OkHttpClientFactory okHttpClientFactory;
@@ -66,19 +63,16 @@ public class OkHttpClientConfigurationTests {
FeignBlockingLoadBalancerClient feignClient;
@Test
public void testFactories() {
assertThat(this.connectionPoolFactory)
.isInstanceOf(OkHttpClientConnectionPoolFactory.class);
assertThat(this.connectionPoolFactory)
.isInstanceOf(TestConfig.MyOkHttpClientConnectionPoolFactory.class);
assertThat(this.okHttpClientFactory).isInstanceOf(OkHttpClientFactory.class);
assertThat(this.okHttpClientFactory)
.isInstanceOf(TestConfig.MyOkHttpClientFactory.class);
void testFactories() {
assertThat(connectionPoolFactory).isInstanceOf(OkHttpClientConnectionPoolFactory.class);
assertThat(connectionPoolFactory).isInstanceOf(TestConfig.MyOkHttpClientConnectionPoolFactory.class);
assertThat(okHttpClientFactory).isInstanceOf(OkHttpClientFactory.class);
assertThat(okHttpClientFactory).isInstanceOf(TestConfig.MyOkHttpClientFactory.class);
}
@Test
public void testHttpClientWithFeign() {
Client delegate = this.feignClient.getDelegate();
void testHttpClientWithFeign() {
Client delegate = feignClient.getDelegate();
assertThat(feign.okhttp.OkHttpClient.class.isInstance(delegate)).isTrue();
feign.okhttp.OkHttpClient okHttpClient = (feign.okhttp.OkHttpClient) delegate;
OkHttpClient httpClient = getField(okHttpClient, "delegate");
@@ -115,12 +109,10 @@ public class OkHttpClientConfigurationTests {
return mock(OkHttpClient.class);
}
static class MyOkHttpClientConnectionPoolFactory
extends DefaultOkHttpClientConnectionPoolFactory {
static class MyOkHttpClientConnectionPoolFactory extends DefaultOkHttpClientConnectionPoolFactory {
@Override
public ConnectionPool create(int maxIdleConnections, long keepAliveDuration,
TimeUnit timeUnit) {
public ConnectionPool create(int maxIdleConnections, long keepAliveDuration, TimeUnit timeUnit) {
return new ConnectionPool();
}
@@ -1,71 +0,0 @@
/*
* Copyright 2013-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.openfeign.test;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.cloud.client.discovery.noop.NoopDiscoveryClientAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
/**
* @author Spencer Gibb
*/
@Configuration(proxyBeanMethods = false)
@Import({ NoopDiscoveryClientAutoConfiguration.class })
@AutoConfigureBefore(SecurityAutoConfiguration.class)
public class TestAutoConfiguration {
public static final String USER = "user";
public static final String PASSWORD = "{noop}password";
@Configuration(proxyBeanMethods = false)
@Order(Ordered.HIGHEST_PRECEDENCE)
protected static class TestSecurityConfiguration
extends WebSecurityConfigurerAdapter {
TestSecurityConfiguration() {
super(true);
}
@Bean
public UserDetailsService userDetailsService() {
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
manager.createUser(
User.withUsername(USER).password(PASSWORD).roles("USER").build());
return manager;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
// super.configure(http);
http.antMatcher("/proxy-username").httpBasic().and().authorizeRequests()
.antMatchers("/**").permitAll();
}
}
}
@@ -48,11 +48,10 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
* @author Jakub Narloch
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = FeignClientNotPrimaryTests.Application.class,
webEnvironment = RANDOM_PORT,
@SpringBootTest(classes = FeignClientNotPrimaryTests.Application.class, webEnvironment = RANDOM_PORT,
value = { "spring.application.name=feignclientnotprimarytest",
"logging.level.org.springframework.cloud.openfeign.valid=DEBUG",
"feign.httpclient.enabled=false", "feign.okhttp.enabled=false" })
"logging.level.org.springframework.cloud.openfeign.valid=DEBUG", "feign.httpclient.enabled=false",
"feign.okhttp.enabled=false" })
@DirtiesContext
public class FeignClientNotPrimaryTests {
@@ -66,8 +65,7 @@ public class FeignClientNotPrimaryTests {
@Test
public void testClientType() {
assertThat(this.testClient).as("testClient was of wrong type")
.isInstanceOf(PrimaryTestClient.class);
assertThat(this.testClient).as("testClient was of wrong type").isInstanceOf(PrimaryTestClient.class);
}
@Test
@@ -92,8 +90,7 @@ public class FeignClientNotPrimaryTests {
@Configuration(proxyBeanMethods = false)
@EnableAutoConfiguration
@RestController
@EnableFeignClients(clients = { TestClient.class },
defaultConfiguration = TestDefaultFeignConfig.class)
@EnableFeignClients(clients = { TestClient.class }, defaultConfiguration = TestDefaultFeignConfig.class)
@LoadBalancerClient(name = "localapp", configuration = LocalClientConfiguration.class)
protected static class Application {
@@ -158,10 +155,8 @@ public class FeignClientNotPrimaryTests {
private int port = 0;
@Bean
public ServiceInstanceListSupplier staticServiceInstanceListSupplier(
Environment env) {
return ServiceInstanceListSupplier.fixed(env).instance(port, "localapp")
.build();
public ServiceInstanceListSupplier staticServiceInstanceListSupplier(Environment env) {
return ServiceInstanceListSupplier.fixed(env).instance(port, "localapp").build();
}
}
@@ -39,8 +39,7 @@ public class FeignClientValidationTests {
@Test
public void validNotLoadBalanced() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
GoodUrlConfiguration.class);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(GoodUrlConfiguration.class);
assertThat(context.getBean(GoodUrlConfiguration.Client.class)).isNotNull();
context.close();
}
@@ -58,8 +57,7 @@ public class FeignClientValidationTests {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
LoadBalancerAutoConfiguration.class,
org.springframework.cloud.loadbalancer.config.LoadBalancerAutoConfiguration.class,
FeignLoadBalancerAutoConfiguration.class,
GoodServiceIdConfiguration.class);
FeignLoadBalancerAutoConfiguration.class, GoodServiceIdConfiguration.class);
assertThat(context.getBean(GoodServiceIdConfiguration.Client.class)).isNotNull();
context.close();
}

Some files were not shown because too many files have changed in this diff Show More