Compare commits

...
Author SHA1 Message Date
buildmaster f4ca971253 Update SNAPSHOT to 2.2.6.RELEASE 2020-11-09 10:38:56 +00: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
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
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 bc6c3b7bf2 Sort request interceptors. (#419) 2020-10-28 18:36:46 +01:00
Olga Maciaszek-Sharma f410385237 Upgrade jackson to 2.11.3. 2020-10-28 17:46:44 +01:00
Olga Maciaszek-Sharma a5ab3383c9 Rename new class. 2020-10-02 15:25:18 +02:00
Olga Maciaszek-Sharma dd518a812b Add support for load-balanced retries. (#408) 2020-10-01 20:20:24 +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 6534950ed2 Upgrade jakson. 2020-09-17 12:57:47 +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 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 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 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
Olga Maciaszek-Sharma d3da7e16e8 Add CollectionFormat support (#371)
* Add CollectionFormat support. Fixes gh-146.

* Minor refactoring.

* Fix docs.
2020-07-17 15:05:21 +02:00
Olga Maciaszek-Sharma 4e89dd1523 Annotate @FeignClient with @Inherited. Fixes gh-322. (#370) 2020-07-14 17:38:02 +02:00
Olga Maciaszek-Sharma 63ba4d40ff Fix checkstyle. 2020-07-14 16:02:28 +02:00
Olga Maciaszek-Sharma 06862ab090 Add test for @MockBean. Fixes gh-343. 2020-07-14 15:19:58 +02:00
Olga Maciaszek-Sharma 72784920d8 Fix read timeout (#369)
* Fix setting readTimeout and connectionTimeout separately from each other. Fixes gh-324.

* Refactor (remove superfluous keywords) and reformat.
2020-07-13 17:19:18 +02:00
Olga Maciaszek-Sharma bf13ae95c9 Remove superfluous conditional. Fixes gh-323. (#350) 2020-06-05 18:26:34 +02:00
Olga Maciaszek-Sharma af06086c30 Fix docs. 2020-06-05 16:28:25 +02:00
Marcin Grzejszczak 5497f5a37c Migrated to docs.spring.io & updated sc-build 2020-06-04 15:50:09 +02:00
Olga Maciaszek-Sharma 12084de3a9 Fix docs. Fixes gh-340. 2020-06-04 14:54:38 +02:00
chang-chao 84cf97b391 update doc on default retrying behavior 2020-06-04 13:17:58 +02:00
buildmaster 3002643ee7 Bumping versions to 2.2.4.BUILD-SNAPSHOT after release 2020-05-28 17:53:50 +00:00
buildmaster b1ec55cb01 Going back to snapshots 2020-05-28 17:53:50 +00:00
35 changed files with 1548 additions and 463 deletions
+1
View File
@@ -20,4 +20,5 @@ _site/
*.swo
.vscode/
.flattened-pom.xml
.sdkmanrc
+2 -1
View File
@@ -4,6 +4,7 @@ Manual changes to this file will be lost when it is generated again.
Edit the files in the src/main/asciidoc/ directory instead.
////
image:https://circleci.com/gh/spring-cloud/spring-cloud-openfeign.svg?style=svg["CircleCI", link="https://circleci.com/gh/spring-cloud/spring-cloud-openfeign"]
image:https://codecov.io/gh/spring-cloud/spring-cloud-openfeign/branch/master/graph/badge.svg["Codecov", link="https://codecov.io/gh/spring-cloud/spring-cloud-openfeign"]
@@ -312,4 +313,4 @@ Go to `File` -> `Settings` -> `Other settings` -> `Checkstyle`. There click on t
- `checkstyle.suppressions.file` - default suppressions. Please point it to the Spring Cloud Build's, `spring-cloud-build-tools/src/checkstyle/checkstyle-suppressions.xml` file either in your cloned repo or via the `https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-build-tools/src/checkstyle/checkstyle-suppressions.xml` URL.
- `checkstyle.additional.suppressions.file` - this variable corresponds to suppressions in your local project. E.g. you're working on `spring-cloud-contract`. Then point to the `project-root/src/checkstyle/checkstyle-suppressions.xml` folder. Example for `spring-cloud-contract` would be: `/home/username/spring-cloud-contract/src/checkstyle/checkstyle-suppressions.xml`.
IMPORTANT: Remember to set the `Scan Scope` to `All sources` since we apply checkstyle rules for production and test sources.
IMPORTANT: Remember to set the `Scan Scope` to `All sources` since we apply checkstyle rules for production and test sources.
+5 -15
View File
@@ -6,7 +6,7 @@
<parent>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-openfeign</artifactId>
<version>2.2.3.RELEASE</version>
<version>2.2.6.RELEASE</version>
</parent>
<artifactId>spring-cloud-openfeign-docs</artifactId>
<packaging>pom</packaging>
@@ -15,8 +15,8 @@
<properties>
<docs.main>spring-cloud-openfeign</docs.main>
<main.basedir>${basedir}/..</main.basedir>
<docs.whitelisted.branches>2.1.x,2.2.x</docs.whitelisted.branches>
<configprops.inclusionPattern>feign.*</configprops.inclusionPattern>
<upload-docs-zip.phase>deploy</upload-docs-zip.phase>
</properties>
<dependencies>
<dependency>
@@ -24,16 +24,6 @@
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>docs</id>
@@ -44,11 +34,9 @@
<artifactId>git-commit-id-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
</plugin>
<plugin>
@@ -60,9 +48,11 @@
<artifactId>asciidoctor-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
</plugin>
</plugins>
</build>
</profile>
+1 -1
View File
@@ -21,4 +21,4 @@
|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.
|===
|===
@@ -112,7 +112,7 @@ public interface StoreClient {
}
----
Spring Cloud Netflix provides the following beans by default for feign (`BeanType` beanName: `ClassName`):
Spring Cloud OpenFeign provides the following beans by default for feign (`BeanType` beanName: `ClassName`):
* `Decoder` feignDecoder: `ResponseEntityDecoder` (which wraps a `SpringDecoder`)
* `Encoder` feignEncoder: `SpringEncoder`
@@ -122,7 +122,7 @@ Spring Cloud Netflix provides the following beans by default for feign (`BeanTyp
* `Client` feignClient: if Ribbon is in the classpath and is enabled it is a `LoadBalancerFeignClient`, otherwise if Spring Cloud LoadBalancer is in the classpath, `FeignBlockingLoadBalancerClient` is used.
If none of them is in the classpath, the default feign client is used.
NOTE: `spring-cloud-starter-openfeign` contains both `spring-cloud-starter-netflix-ribbon` and `spring-cloud-starter-loadbalancer`.
NOTE: `spring-cloud-starter-openfeign` supports both `spring-cloud-starter-netflix-ribbon` and `spring-cloud-starter-loadbalancer`. However, as they are optional dependencies, you need to make sure the one you want to use has been added to your project.
The OkHttpClient and ApacheHttpClient feign clients can be used by setting `feign.okhttp.enabled` or `feign.httpclient.enabled` to `true`, respectively, and having them on the classpath.
You can customize the HTTP client used by providing a bean of either `org.apache.http.impl.client.CloseableHttpClient` when using Apache or `okhttp3.OkHttpClient` when using OK HTTP.
@@ -137,6 +137,10 @@ Spring Cloud OpenFeign _does not_ provide the following beans by default for fei
* `SetterFactory`
* `QueryMapEncoder`
A bean of `Retryer.NEVER_RETRY` with the type `Retryer` is created by default, which will disable retrying.
Notice this retrying behavior is different from the Feign default one, where it will automatically retry IOExceptions,
treating them as transient network related exceptions, and any RetryableException thrown from an ErrorDecoder.
Creating a bean of one of those type and placing it in a `@FeignClient` configuration (such as `FooConfiguration` above) allows you to override each one of the beans described. Example:
[source,java,indent=0]
@@ -171,6 +175,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 +192,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 +274,42 @@ 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.
When Hystrix <<spring-cloud-openfeign#spring-cloud-feign-hystrix,is enabled>>, its timeout configuration link:https://github.com/Netflix/Hystrix/wiki/Configuration#execution.isolation.thread.timeoutInMilliseconds[defaults] to 1000 milliseconds. Hence, it might occur before the client timeout that we configured earlier. Increasing this timeout prevents it from happening.
[source,yaml]
----
feign:
client:
config:
default:
connectTimeout: 5000
readTimeout: 5000
hystrix:
enabled: true
hystrix:
command:
default:
execution:
timeout:
enabled: true
isolation:
thread:
timeoutInMilliseconds: 60000
----
NOTE: When the Hystrix timeout is enabled and its timeout is set longer than that of a feign client, `HystrixTimeoutException` wraps a feign exception. Otherwise, the only difference is the cause of the exception. The purpose of `HystrixTimeoutException` is to wrap any runtime exception that occurs first and throw an instance of itself.
=== Creating Feign Clients Manually
In some cases it might be necessary to customize your Feign Clients in a way that is not
@@ -301,7 +347,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 +430,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 +607,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:
@@ -582,6 +628,25 @@ public interface DemoTemplate {
}
----
=== Feign `CollectionFormat` support
We support `feign.CollectionFormat` by providing the `@CollectionFormat` annotation. You can annotate a Feign client method with it by passing the desired `feign.CollectionFormat` as annotation value.
In the following example, the `CSV` format is used instead of the default `EXPLODED` to process the method.
[source,java,indent=0]
----
@FeignClient(name = "demo")
protected interface PageableFeignClient {
@CollectionFormat(feign.CollectionFormat.CSV)
@GetMapping(path = "/page")
ResponseEntity performRequest(Pageable page);
}
----
TIP: Set the `CSV` format while sending `Pageable` as a query parameter in order for it to be encoded correctly.
=== Reactive Support
As the https://github.com/OpenFeign/feign[OpenFeign project] does not currently support reactive clients, such as https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/reactive/function/client/WebClient.html[Spring WebClient], neither does Spring Cloud OpenFeign. We will add support for it here as soon as it becomes available in the core project.
+5 -7
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>2.2.3.RELEASE</version>
<version>2.2.6.RELEASE</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>2.3.0.RELEASE</version>
<version>2.3.1.RELEASE</version>
<relativePath/>
</parent>
<scm>
@@ -25,12 +25,11 @@
</scm>
<properties>
<main.basedir>${basedir}</main.basedir>
<jackson.version>2.7.3</jackson.version>
<spring-cloud-commons.version>2.2.3.RELEASE</spring-cloud-commons.version>
<spring-cloud-netflix.version>2.2.3.RELEASE</spring-cloud-netflix.version>
<jackson.version>2.11.3</jackson.version>
<spring-cloud-commons.version>2.2.6.RELEASE</spring-cloud-commons.version>
<spring-cloud-netflix.version>2.2.6.RELEASE</spring-cloud-netflix.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>
@@ -68,7 +67,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>2.2.3.RELEASE</version>
<version>2.2.6.RELEASE</version>
<relativePath>..</relativePath> <!-- lookup parent from repository -->
</parent>
<artifactId>spring-cloud-openfeign-core</artifactId>
@@ -217,13 +217,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>
@@ -231,12 +231,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>
@@ -0,0 +1,41 @@
/*
* 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;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Indicates which collection format should be used while processing the annotated method.
*
* @author Olga Maciaszek-Sharma
* @see feign.CollectionFormat
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CollectionFormat {
/**
* Allows setting the {@link feign.CollectionFormat} to be used while processing the
* annotated method.
* @return the {@link feign.CollectionFormat} to be used
*/
feign.CollectionFormat value();
}
@@ -18,6 +18,7 @@ package org.springframework.cloud.openfeign;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@@ -36,6 +37,7 @@ import org.springframework.core.annotation.AliasFor;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface FeignClient {
/**
@@ -16,8 +16,11 @@
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;
import feign.Client;
import feign.Contract;
@@ -43,6 +46,7 @@ import org.springframework.cloud.openfeign.loadbalancer.FeignBlockingLoadBalance
import org.springframework.cloud.openfeign.ribbon.LoadBalancerFeignClient;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
@@ -52,6 +56,8 @@ import org.springframework.util.StringUtils;
* @author Eko Kurniawan Khannedy
* @author Gregor Zurowski
* @author Matt King
* @author Olga Maciaszek-Sharma
* @author Ilia Ilinykh
*/
class FeignClientFactoryBean
implements FactoryBean<Object>, InitializingBean, ApplicationContextAware {
@@ -81,15 +87,19 @@ class FeignClientFactoryBean
private Class<?> fallbackFactory = void.class;
private int readTimeoutMillis = new Request.Options().readTimeoutMillis();
private int connectTimeoutMillis = new Request.Options().connectTimeoutMillis();
@Override
public void afterPropertiesSet() throws Exception {
Assert.hasText(this.contextId, "Context id must be set");
Assert.hasText(this.name, "Name must be set");
public void afterPropertiesSet() {
Assert.hasText(contextId, "Context id must be set");
Assert.hasText(name, "Name must be set");
}
protected Feign.Builder feign(FeignContext context) {
FeignLoggerFactory loggerFactory = get(context, FeignLoggerFactory.class);
Logger logger = loggerFactory.create(this.type);
Logger logger = loggerFactory.create(type);
// @formatter:off
Feign.Builder builder = get(context, Feign.Builder.class)
@@ -106,7 +116,7 @@ class FeignClientFactoryBean
}
protected void configureFeign(FeignContext context, Feign.Builder builder) {
FeignClientProperties properties = this.applicationContext
FeignClientProperties properties = applicationContext
.getBean(FeignClientProperties.class);
FeignClientConfigurer feignClientConfigurer = getOptional(context,
@@ -119,15 +129,13 @@ class FeignClientFactoryBean
configureUsingProperties(
properties.getConfig().get(properties.getDefaultConfig()),
builder);
configureUsingProperties(properties.getConfig().get(this.contextId),
builder);
configureUsingProperties(properties.getConfig().get(contextId), builder);
}
else {
configureUsingProperties(
properties.getConfig().get(properties.getDefaultConfig()),
builder);
configureUsingProperties(properties.getConfig().get(this.contextId),
builder);
configureUsingProperties(properties.getConfig().get(contextId), builder);
configureUsingConfiguration(context, builder);
}
}
@@ -155,7 +163,7 @@ class FeignClientFactoryBean
FeignErrorDecoderFactory errorDecoderFactory = getOptional(context,
FeignErrorDecoderFactory.class);
if (errorDecoderFactory != null) {
ErrorDecoder factoryErrorDecoder = errorDecoderFactory.create(this.type);
ErrorDecoder factoryErrorDecoder = errorDecoderFactory.create(type);
builder.errorDecoder(factoryErrorDecoder);
}
}
@@ -163,18 +171,23 @@ class FeignClientFactoryBean
Request.Options.class);
if (options != null) {
builder.options(options);
readTimeoutMillis = options.readTimeoutMillis();
connectTimeoutMillis = options.connectTimeoutMillis();
}
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);
if (queryMapEncoder != null) {
builder.queryMapEncoder(queryMapEncoder);
}
if (this.decode404) {
if (decode404) {
builder.decode404();
}
ExceptionPropagationPolicy exceptionPropagationPolicy = getInheritedAwareOptional(
@@ -195,10 +208,13 @@ class FeignClientFactoryBean
builder.logLevel(config.getLoggerLevel());
}
if (config.getConnectTimeout() != null && config.getReadTimeout() != null) {
builder.options(new Request.Options(config.getConnectTimeout(),
config.getReadTimeout()));
}
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));
if (config.getRetryer() != null) {
Retryer retryer = getOrInstantiate(config.getRetryer());
@@ -229,6 +245,16 @@ 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()));
}
@@ -244,7 +270,7 @@ class FeignClientFactoryBean
private <T> T getOrInstantiate(Class<T> tClass) {
try {
return this.applicationContext.getBean(tClass);
return applicationContext.getBean(tClass);
}
catch (NoSuchBeanDefinitionException e) {
return BeanUtils.instantiateClass(tClass);
@@ -252,16 +278,16 @@ class FeignClientFactoryBean
}
protected <T> T get(FeignContext context, Class<T> type) {
T instance = context.getInstance(this.contextId, type);
T instance = context.getInstance(contextId, type);
if (instance == null) {
throw new IllegalStateException(
"No bean found of type " + type + " for " + this.contextId);
"No bean found of type " + type + " for " + contextId);
}
return instance;
}
protected <T> T getOptional(FeignContext context, Class<T> type) {
return context.getInstance(this.contextId, type);
return context.getInstance(contextId, type);
}
protected <T> T getInheritedAwareOptional(FeignContext context, Class<T> type) {
@@ -269,17 +295,17 @@ class FeignClientFactoryBean
return getOptional(context, type);
}
else {
return context.getInstanceWithoutAncestors(this.contextId, type);
return context.getInstanceWithoutAncestors(contextId, type);
}
}
protected <T> Map<String, T> getInheritedAwareInstances(FeignContext context,
Class<T> type) {
if (inheritParentContext) {
return context.getInstances(this.contextId, type);
return context.getInstances(contextId, type);
}
else {
return context.getInstancesWithoutAncestors(this.contextId, type);
return context.getInstancesWithoutAncestors(contextId, type);
}
}
@@ -307,22 +333,22 @@ class FeignClientFactoryBean
* information
*/
<T> T getTarget() {
FeignContext context = this.applicationContext.getBean(FeignContext.class);
FeignContext context = applicationContext.getBean(FeignContext.class);
Feign.Builder builder = feign(context);
if (!StringUtils.hasText(this.url)) {
if (!this.name.startsWith("http")) {
this.url = "http://" + this.name;
if (!StringUtils.hasText(url)) {
if (!name.startsWith("http")) {
url = "http://" + name;
}
else {
this.url = this.name;
url = name;
}
this.url += cleanPath();
url += cleanPath();
return (T) loadBalance(builder, context,
new HardCodedTarget<>(this.type, this.name, this.url));
new HardCodedTarget<>(type, name, url));
}
if (StringUtils.hasText(this.url) && !this.url.startsWith("http")) {
this.url = "http://" + this.url;
if (StringUtils.hasText(url) && !url.startsWith("http")) {
url = "http://" + url;
}
String url = this.url + cleanPath();
Client client = getOptional(context, Client.class);
@@ -341,7 +367,7 @@ class FeignClientFactoryBean
}
Targeter targeter = get(context, Targeter.class);
return (T) targeter.target(this, builder, context,
new HardCodedTarget<>(this.type, this.name, url));
new HardCodedTarget<>(type, name, url));
}
private String cleanPath() {
@@ -359,7 +385,7 @@ class FeignClientFactoryBean
@Override
public Class<?> getObjectType() {
return this.type;
return type;
}
@Override
@@ -368,7 +394,7 @@ class FeignClientFactoryBean
}
public Class<?> getType() {
return this.type;
return type;
}
public void setType(Class<?> type) {
@@ -376,7 +402,7 @@ class FeignClientFactoryBean
}
public String getName() {
return this.name;
return name;
}
public void setName(String name) {
@@ -384,7 +410,7 @@ class FeignClientFactoryBean
}
public String getContextId() {
return this.contextId;
return contextId;
}
public void setContextId(String contextId) {
@@ -392,7 +418,7 @@ class FeignClientFactoryBean
}
public String getUrl() {
return this.url;
return url;
}
public void setUrl(String url) {
@@ -400,7 +426,7 @@ class FeignClientFactoryBean
}
public String getPath() {
return this.path;
return path;
}
public void setPath(String path) {
@@ -408,7 +434,7 @@ class FeignClientFactoryBean
}
public boolean isDecode404() {
return this.decode404;
return decode404;
}
public void setDecode404(boolean decode404) {
@@ -424,7 +450,7 @@ class FeignClientFactoryBean
}
public ApplicationContext getApplicationContext() {
return this.applicationContext;
return applicationContext;
}
@Override
@@ -433,7 +459,7 @@ class FeignClientFactoryBean
}
public Class<?> getFallback() {
return this.fallback;
return fallback;
}
public void setFallback(Class<?> fallback) {
@@ -441,7 +467,7 @@ class FeignClientFactoryBean
}
public Class<?> getFallbackFactory() {
return this.fallbackFactory;
return fallbackFactory;
}
public void setFallbackFactory(Class<?> fallbackFactory) {
@@ -457,35 +483,31 @@ class FeignClientFactoryBean
return false;
}
FeignClientFactoryBean that = (FeignClientFactoryBean) o;
return Objects.equals(this.applicationContext, that.applicationContext)
&& this.decode404 == that.decode404
&& this.inheritParentContext == that.inheritParentContext
&& Objects.equals(this.fallback, that.fallback)
&& Objects.equals(this.fallbackFactory, that.fallbackFactory)
&& Objects.equals(this.name, that.name)
&& Objects.equals(this.path, that.path)
&& Objects.equals(this.type, that.type)
&& Objects.equals(this.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(this.applicationContext, this.decode404,
this.inheritParentContext, this.fallback, this.fallbackFactory, this.name,
this.path, this.type, this.url);
return Objects.hash(applicationContext, decode404, inheritParentContext, fallback,
fallbackFactory, name, path, type, url);
}
@Override
public String toString() {
return new StringBuilder("FeignClientFactoryBean{").append("type=")
.append(this.type).append(", ").append("name='").append(this.name)
.append("', ").append("url='").append(this.url).append("', ")
.append("path='").append(this.path).append("', ").append("decode404=")
.append(this.decode404).append(", ").append("inheritParentContext=")
.append(this.inheritParentContext).append(", ")
.append("applicationContext=").append(this.applicationContext)
.append(", ").append("fallback=").append(this.fallback).append(", ")
.append("fallbackFactory=").append(this.fallbackFactory).append("}")
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 {
@@ -104,6 +106,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;
@@ -163,6 +169,24 @@ public class FeignClientProperties {
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;
}
@@ -224,7 +248,11 @@ public class FeignClientProperties {
&& Objects.equals(this.decoder, that.decoder)
&& Objects.equals(this.contract, that.contract)
&& Objects.equals(this.exceptionPropagationPolicy,
that.exceptionPropagationPolicy);
that.exceptionPropagationPolicy)
&& Objects.equals(this.defaultRequestHeaders,
that.defaultRequestHeaders)
&& Objects.equals(this.defaultQueryParameters,
that.defaultQueryParameters);
}
@Override
@@ -232,7 +260,8 @@ public class FeignClientProperties {
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.exceptionPropagationPolicy, this.defaultQueryParameters,
this.defaultRequestHeaders);
}
}
@@ -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,6 +52,7 @@ import org.springframework.util.StringUtils;
* @author Jakub Narloch
* @author Venil Noronha
* @author Gang Li
* @author Michal Domagala
*/
class FeignClientsRegistrar
implements ImportBeanDefinitionRegistrar, ResourceLoaderAware, EnvironmentAware {
@@ -165,11 +160,8 @@ class FeignClientsRegistrar
public void registerFeignClients(AnnotationMetadata metadata,
BeanDefinitionRegistry registry) {
ClassPathScanningCandidateComponentProvider scanner = getScanner();
scanner.setResourceLoader(this.resourceLoader);
Set<String> basePackages;
LinkedHashSet<BeanDefinition> candidateComponents = new LinkedHashSet<>();
Map<String, Object> attrs = metadata
.getAnnotationAttributes(EnableFeignClients.class.getName());
AnnotationTypeFilter annotationTypeFilter = new AnnotationTypeFilter(
@@ -177,48 +169,36 @@ class FeignClientsRegistrar
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);
}
}
}
@@ -398,38 +378,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;
}
}
}
@@ -16,11 +16,9 @@
package org.springframework.cloud.openfeign.encoding;
import feign.Client;
import feign.Feign;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
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;
@@ -38,12 +36,10 @@ import org.springframework.context.annotation.Configuration;
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(FeignClientEncodingProperties.class)
@ConditionalOnClass(Feign.class)
@ConditionalOnBean(Client.class)
// The OK HTTP client uses "transparent" compression.
// If the content-encoding header is present it disable transparent compression
@ConditionalOnMissingBean(type = "okhttp3.OkHttpClient")
@ConditionalOnProperty(value = "feign.compression.request.enabled",
matchIfMissing = false)
@ConditionalOnProperty("feign.compression.request.enabled")
@AutoConfigureAfter(FeignAutoConfiguration.class)
public class FeignContentGzipEncodingAutoConfiguration {
@@ -16,12 +16,20 @@
package org.springframework.cloud.openfeign.loadbalancer;
import java.util.List;
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.cloud.client.loadbalancer.LoadBalancedRetryFactory;
import org.springframework.cloud.loadbalancer.blocking.client.BlockingLoadBalancerClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
/**
* Configuration instantiating a {@link BlockingLoadBalancerClient}-based {@link Client}
@@ -35,9 +43,24 @@ class DefaultFeignLoadBalancerConfiguration {
@Bean
@ConditionalOnMissingBean
@Conditional(OnRetryNotEnabledCondition.class)
public Client feignClient(BlockingLoadBalancerClient loadBalancerClient) {
return new FeignBlockingLoadBalancerClient(new Client.Default(null, null),
loadBalancerClient);
}
@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(BlockingLoadBalancerClient loadBalancerClient,
List<LoadBalancedRetryFactory> loadBalancedRetryFactories) {
AnnotationAwareOrderComparator.sort(loadBalancedRetryFactories);
return new RetryableFeignBlockingLoadBalancerClient(
new Client.Default(null, null), loadBalancerClient,
loadBalancedRetryFactories.get(0));
}
}
@@ -16,6 +16,8 @@
package org.springframework.cloud.openfeign.loadbalancer;
import java.util.List;
import feign.Client;
import feign.httpclient.ApacheHttpClient;
import org.apache.http.client.HttpClient;
@@ -24,11 +26,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.cloud.client.loadbalancer.LoadBalancedRetryFactory;
import org.springframework.cloud.loadbalancer.blocking.client.BlockingLoadBalancerClient;
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;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
/**
* Configuration instantiating a {@link BlockingLoadBalancerClient}-based {@link Client}
@@ -46,10 +51,26 @@ class HttpClientFeignLoadBalancerConfiguration {
@Bean
@ConditionalOnMissingBean
@Conditional(OnRetryNotEnabledCondition.class)
public Client feignClient(BlockingLoadBalancerClient loadBalancerClient,
HttpClient httpClient) {
ApacheHttpClient delegate = new ApacheHttpClient(httpClient);
return new FeignBlockingLoadBalancerClient(delegate, loadBalancerClient);
}
@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(BlockingLoadBalancerClient loadBalancerClient,
HttpClient httpClient,
List<LoadBalancedRetryFactory> loadBalancedRetryFactories) {
AnnotationAwareOrderComparator.sort(loadBalancedRetryFactories);
ApacheHttpClient delegate = new ApacheHttpClient(httpClient);
return new RetryableFeignBlockingLoadBalancerClient(delegate, loadBalancerClient,
loadBalancedRetryFactories.get(0));
}
}
@@ -16,6 +16,8 @@
package org.springframework.cloud.openfeign.loadbalancer;
import java.util.List;
import feign.Client;
import feign.okhttp.OkHttpClient;
@@ -23,11 +25,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.cloud.client.loadbalancer.LoadBalancedRetryFactory;
import org.springframework.cloud.loadbalancer.blocking.client.BlockingLoadBalancerClient;
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;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
/**
* Configuration instantiating a {@link BlockingLoadBalancerClient}-based {@link Client}
@@ -45,10 +50,26 @@ class OkHttpFeignLoadBalancerConfiguration {
@Bean
@ConditionalOnMissingBean
@Conditional(OnRetryNotEnabledCondition.class)
public Client feignClient(okhttp3.OkHttpClient okHttpClient,
BlockingLoadBalancerClient loadBalancerClient) {
OkHttpClient delegate = new OkHttpClient(okHttpClient);
return new FeignBlockingLoadBalancerClient(delegate, loadBalancerClient);
}
@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(BlockingLoadBalancerClient loadBalancerClient,
okhttp3.OkHttpClient okHttpClient,
List<LoadBalancedRetryFactory> loadBalancedRetryFactories) {
AnnotationAwareOrderComparator.sort(loadBalancedRetryFactories);
OkHttpClient delegate = new OkHttpClient(okHttpClient);
return new RetryableFeignBlockingLoadBalancerClient(delegate, loadBalancerClient,
loadBalancedRetryFactories.get(0));
}
}
@@ -0,0 +1,56 @@
/*
* 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,185 @@
/*
* 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 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.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.RetryableStatusCodeException;
import org.springframework.cloud.loadbalancer.blocking.client.BlockingLoadBalancerClient;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpRequest;
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;
/**
* 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
*/
public class RetryableFeignBlockingLoadBalancerClient implements Client {
private static final Log LOG = LogFactory
.getLog(FeignBlockingLoadBalancerClient.class);
private final Client delegate;
private final BlockingLoadBalancerClient loadBalancerClient;
private final LoadBalancedRetryFactory loadBalancedRetryFactory;
public RetryableFeignBlockingLoadBalancerClient(Client delegate,
BlockingLoadBalancerClient loadBalancerClient,
LoadBalancedRetryFactory loadBalancedRetryFactory) {
this.delegate = delegate;
this.loadBalancerClient = loadBalancerClient;
this.loadBalancedRetryFactory = loadBalancedRetryFactory;
}
@Override
public Response execute(Request request, Request.Options options) throws IOException {
final URI originalUri = URI.create(request.url());
String serviceId = originalUri.getHost();
final LoadBalancedRetryPolicy retryPolicy = loadBalancedRetryFactory
.createRetryPolicy(serviceId, loadBalancerClient);
RetryTemplate retryTemplate = buildRetryTemplate(serviceId, request, retryPolicy);
return retryTemplate.execute(context -> {
Request feignRequest = null;
// 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) {
ServiceInstance serviceInstance = ((LoadBalancedRetryContext) context)
.getServiceInstance();
if (serviceInstance != null) {
if (LOG.isDebugEnabled()) {
LOG.debug(String.format(
"Using service instance from LoadBalancedRetryContext: %s",
serviceInstance));
}
String reconstructedUrl = loadBalancerClient
.reconstructURI(serviceInstance, originalUri).toString();
feignRequest = Request.create(request.httpMethod(), reconstructedUrl,
request.headers(), request.body(), request.charset(),
request.requestTemplate());
}
}
if (feignRequest == null) {
if (LOG.isWarnEnabled()) {
LOG.warn(
"Service instance was not resolved, executing the original request");
}
feignRequest = request;
}
Response response = delegate.execute(feignRequest, options);
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;
}
};
}
}
@@ -26,7 +26,6 @@ import java.util.List;
import java.util.Map;
import com.netflix.client.AbstractLoadBalancerAwareClient;
import com.netflix.client.ClientException;
import com.netflix.client.ClientRequest;
import com.netflix.client.IResponse;
import com.netflix.client.RequestSpecificRetryHandler;
@@ -169,7 +168,7 @@ public class FeignLoadBalancer extends
Map<String, Collection<String>> feignHeaders = RibbonRequest.this
.toRequest().headers();
for (String key : feignHeaders.keySet()) {
headers.put(key, new ArrayList<String>(feignHeaders.get(key)));
headers.put(key, new ArrayList<>(feignHeaders.get(key)));
}
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.putAll(headers);
@@ -206,7 +205,7 @@ public class FeignLoadBalancer extends
}
@Override
public Object getPayload() throws ClientException {
public Object getPayload() {
return this.response.body();
}
@@ -36,8 +36,6 @@ import org.springframework.cloud.client.loadbalancer.ServiceInstanceChooser;
import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient;
import org.springframework.cloud.netflix.ribbon.RibbonProperties;
import org.springframework.cloud.netflix.ribbon.ServerIntrospector;
import org.springframework.retry.RetryCallback;
import org.springframework.retry.RetryContext;
import org.springframework.retry.RetryListener;
import org.springframework.retry.backoff.BackOffPolicy;
import org.springframework.retry.backoff.NoBackOffPolicy;
@@ -91,39 +89,34 @@ public class RetryableFeignLoadBalancer extends FeignLoadBalancer
retryTemplate.setRetryPolicy(retryPolicy == null ? new NeverRetryPolicy()
: new FeignRetryPolicy(request.toHttpRequest(), retryPolicy, this,
this.getClientName()));
return retryTemplate.execute(new RetryCallback<RibbonResponse, IOException>() {
@Override
public RibbonResponse doWithRetry(RetryContext retryContext)
throws IOException {
Request feignRequest = null;
// on retries the policy will choose the server and set it in the context
// extract the server and update the request being made
if (retryContext instanceof LoadBalancedRetryContext) {
ServiceInstance service = ((LoadBalancedRetryContext) retryContext)
.getServiceInstance();
if (service != null) {
feignRequest = ((RibbonRequest) request
.replaceUri(reconstructURIWithServer(
new Server(service.getHost(), service.getPort()),
request.getUri()))).toRequest();
}
return retryTemplate.execute(retryContext -> {
Request feignRequest = null;
// on retries the policy will choose the server and set it in the context
// extract the server and update the request being made
if (retryContext instanceof LoadBalancedRetryContext) {
ServiceInstance service = ((LoadBalancedRetryContext) retryContext)
.getServiceInstance();
if (service != null) {
feignRequest = ((RibbonRequest) request
.replaceUri(reconstructURIWithServer(
new Server(service.getHost(), service.getPort()),
request.getUri()))).toRequest();
}
if (feignRequest == null) {
feignRequest = request.toRequest();
}
Response response = request.client().execute(feignRequest, options);
if (retryPolicy != null
&& retryPolicy.retryableStatusCode(response.status())) {
byte[] byteArray = response.body() == null ? new byte[] {}
: StreamUtils
.copyToByteArray(response.body().asInputStream());
response.close();
throw new RibbonResponseStatusCodeException(
RetryableFeignLoadBalancer.this.clientName, response,
byteArray, request.getUri());
}
return new RibbonResponse(request.getUri(), response);
}
if (feignRequest == null) {
feignRequest = request.toRequest();
}
Response response = request.client().execute(feignRequest, options);
if (retryPolicy != null
&& retryPolicy.retryableStatusCode(response.status())) {
byte[] byteArray = response.body() == null ? new byte[] {}
: StreamUtils.copyToByteArray(response.body().asInputStream());
response.close();
throw new RibbonResponseStatusCodeException(
RetryableFeignLoadBalancer.this.clientName, response, byteArray,
request.getUri());
}
return new RibbonResponse(request.getUri(), response);
}, new LoadBalancedRecoveryCallback<RibbonResponse, Response>() {
@Override
protected RibbonResponse createResponse(Response response, URI uri) {
@@ -37,6 +37,7 @@ import feign.Param;
import feign.Request;
import org.springframework.cloud.openfeign.AnnotatedParameterProcessor;
import org.springframework.cloud.openfeign.CollectionFormat;
import org.springframework.cloud.openfeign.annotation.MatrixVariableParameterProcessor;
import org.springframework.cloud.openfeign.annotation.PathVariableParameterProcessor;
import org.springframework.cloud.openfeign.annotation.QueryMapParameterProcessor;
@@ -56,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;
@@ -121,9 +123,9 @@ public class SpringMvcContract extends Contract.BaseContract
List<AnnotatedParameterProcessor> processors = getDefaultAnnotatedArgumentsProcessors();
processors.addAll(annotatedParameterProcessors);
this.annotatedArgumentProcessors = toAnnotatedArgumentProcessorMap(processors);
annotatedArgumentProcessors = toAnnotatedArgumentProcessorMap(processors);
this.conversionService = conversionService;
this.convertingExpanderFactory = new ConvertingExpanderFactory(conversionService);
convertingExpanderFactory = new ConvertingExpanderFactory(conversionService);
}
private static TypeDescriptor createTypeDescriptor(Method method, int paramIndex) {
@@ -172,14 +174,15 @@ public class SpringMvcContract extends Contract.BaseContract
if (clz.getInterfaces().length == 0) {
RequestMapping classAnnotation = findMergedAnnotation(clz,
RequestMapping.class);
if (classAnnotation != null && classAnnotation.value().length > 0) {
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);
}
}
}
@@ -187,7 +190,7 @@ public class SpringMvcContract extends Contract.BaseContract
@Override
public MethodMetadata parseAndValidateMetadata(Class<?> targetType, Method method) {
this.processedMethods.put(Feign.configKey(targetType, method), method);
processedMethods.put(Feign.configKey(targetType, method), method);
MethodMetadata md = super.parseAndValidateMetadata(targetType, method);
RequestMapping classAnnotation = findMergedAnnotation(targetType,
@@ -213,6 +216,12 @@ public class SpringMvcContract extends Contract.BaseContract
@Override
protected void processAnnotationOnMethod(MethodMetadata data,
Annotation methodAnnotation, Method method) {
if (CollectionFormat.class.isInstance(methodAnnotation)) {
CollectionFormat collectionFormat = findMergedAnnotation(method,
CollectionFormat.class);
data.template().collectionFormat(collectionFormat.value());
}
if (!RequestMapping.class.isInstance(methodAnnotation) && !methodAnnotation
.annotationType().isAnnotationPresent(RequestMapping.class)) {
return;
@@ -233,9 +242,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);
}
}
@@ -248,13 +259,13 @@ public class SpringMvcContract extends Contract.BaseContract
// headers
parseHeaders(data, method, methodMapping);
data.indexToExpander(new LinkedHashMap<Integer, Param.Expander>());
data.indexToExpander(new LinkedHashMap<>());
}
private String resolve(String value) {
if (StringUtils.hasText(value)
&& this.resourceLoader instanceof ConfigurableApplicationContext) {
return ((ConfigurableApplicationContext) this.resourceLoader).getEnvironment()
&& resourceLoader instanceof ConfigurableApplicationContext) {
return ((ConfigurableApplicationContext) resourceLoader).getEnvironment()
.resolvePlaceholders(value);
}
return value;
@@ -280,9 +291,9 @@ public class SpringMvcContract extends Contract.BaseContract
AnnotatedParameterProcessor.AnnotatedParameterContext context = new SimpleAnnotatedParameterContext(
data, paramIndex);
Method method = this.processedMethods.get(data.configKey());
Method method = processedMethods.get(data.configKey());
for (Annotation parameterAnnotation : annotations) {
AnnotatedParameterProcessor processor = this.annotatedArgumentProcessors
AnnotatedParameterProcessor processor = annotatedArgumentProcessors
.get(parameterAnnotation.annotationType());
if (processor != null) {
Annotation processParameterAnnotation;
@@ -298,9 +309,8 @@ public class SpringMvcContract extends Contract.BaseContract
if (!isMultipartFormData(data) && isHttpAnnotation
&& data.indexToExpander().get(paramIndex) == null) {
TypeDescriptor typeDescriptor = createTypeDescriptor(method, paramIndex);
if (this.conversionService.canConvert(typeDescriptor,
STRING_TYPE_DESCRIPTOR)) {
Param.Expander expander = this.convertingExpanderFactory
if (conversionService.canConvert(typeDescriptor, STRING_TYPE_DESCRIPTOR)) {
Param.Expander expander = convertingExpanderFactory
.getExpander(typeDescriptor);
if (expander != null) {
data.indexToExpander().put(paramIndex, expander);
@@ -399,7 +409,13 @@ public class SpringMvcContract extends Contract.BaseContract
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;
@@ -419,7 +435,7 @@ public class SpringMvcContract extends Contract.BaseContract
@Override
public String expand(Object value) {
return this.conversionService.convert(value, String.class);
return conversionService.convert(value, String.class);
}
}
@@ -434,7 +450,7 @@ public class SpringMvcContract extends Contract.BaseContract
Param.Expander getExpander(TypeDescriptor typeDescriptor) {
return value -> {
Object converted = this.conversionService.convert(value, typeDescriptor,
Object converted = conversionService.convert(value, typeDescriptor,
STRING_TYPE_DESCRIPTOR);
return (String) converted;
};
@@ -457,17 +473,17 @@ public class SpringMvcContract extends Contract.BaseContract
@Override
public MethodMetadata getMethodMetadata() {
return this.methodMetadata;
return methodMetadata;
}
@Override
public int getParameterIndex() {
return this.parameterIndex;
return parameterIndex;
}
@Override
public void setParameterName(String name) {
nameParam(this.methodMetadata, name, this.parameterIndex);
nameParam(methodMetadata, name, parameterIndex);
}
@Override
@@ -24,7 +24,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;
@@ -34,8 +33,7 @@ import feign.hystrix.HystrixFeign;
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.context.PropertyPlaceholderAutoConfiguration;
@@ -47,7 +45,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.SpringJUnit4ClassRunner;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@@ -56,10 +53,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;
@@ -71,92 +67,89 @@ 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))
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))
void overrideRetryer() {
assertThat(context.getInstance("foo", Retryer.class))
.isEqualTo(Retryer.NEVER_RETRY);
Retryer.Default.class.cast(this.context.getInstance("bar", Retryer.class));
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 overrideBuilder() {
HystrixFeign.Builder.class
.cast(this.context.getInstance("foo", Feign.Builder.class));
Feign.Builder.class.cast(this.context.getInstance("bar", Feign.Builder.class));
void overrideBuilder() {
HystrixFeign.Builder.class.cast(context.getInstance("foo", Feign.Builder.class));
Feign.Builder.class.cast(context.getInstance("bar", Feign.Builder.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() {
void overrideQueryMapEncoder() {
QueryMapEncoder.Default.class
.cast(this.context.getInstance("foo", QueryMapEncoder.class));
BeanQueryMapEncoder.class
.cast(this.context.getInstance("bar", QueryMapEncoder.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())
void addRequestInterceptor() {
assertThat(context.getInstances("foo", RequestInterceptor.class).size())
.isEqualTo(1);
assertThat(this.context.getInstances("bar", RequestInterceptor.class).size())
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);
}
@@ -186,10 +179,7 @@ public class FeignClientOverrideDefaultsTests {
@Bean
RequestInterceptor defaultRequestInterceptor() {
return new RequestInterceptor() {
@Override
public void apply(RequestTemplate template) {
}
return template -> {
};
}
@@ -17,13 +17,25 @@
package org.springframework.cloud.openfeign;
import java.io.IOException;
import java.lang.reflect.Method;
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;
import feign.InvocationHandlerFactory;
import feign.Request;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import feign.RetryableException;
@@ -47,8 +59,13 @@ import org.springframework.http.MediaType;
import org.springframework.test.annotation.DirtiesContext;
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;
@@ -57,7 +74,10 @@ 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)
@@ -82,46 +102,62 @@ public class FeignClientUsingPropertiesTests {
private FeignClientFactoryBean formFactoryBean;
private FeignClientFactoryBean defaultHeadersAndQuerySingleParamsFeignClientFactoryBean;
private FeignClientFactoryBean defaultHeadersAndQueryMultipleParamsFeignClientFactoryBean;
public FeignClientUsingPropertiesTests() {
this.fooFactoryBean = new FeignClientFactoryBean();
this.fooFactoryBean.setContextId("foo");
this.fooFactoryBean.setType(FeignClientFactoryBean.class);
fooFactoryBean = new FeignClientFactoryBean();
fooFactoryBean.setContextId("foo");
fooFactoryBean.setType(FeignClientFactoryBean.class);
this.barFactoryBean = new FeignClientFactoryBean();
this.barFactoryBean.setContextId("bar");
this.barFactoryBean.setType(FeignClientFactoryBean.class);
barFactoryBean = new FeignClientFactoryBean();
barFactoryBean.setContextId("bar");
barFactoryBean.setType(FeignClientFactoryBean.class);
this.unwrapFactoryBean = new FeignClientFactoryBean();
this.unwrapFactoryBean.setContextId("unwrap");
this.unwrapFactoryBean.setType(FeignClientFactoryBean.class);
unwrapFactoryBean = new FeignClientFactoryBean();
unwrapFactoryBean.setContextId("unwrap");
unwrapFactoryBean.setType(FeignClientFactoryBean.class);
this.formFactoryBean = new FeignClientFactoryBean();
this.formFactoryBean.setContextId("form");
this.formFactoryBean.setType(FeignClientFactoryBean.class);
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() {
this.fooFactoryBean.setApplicationContext(this.applicationContext);
return this.fooFactoryBean.feign(this.context).target(FooClient.class,
"http://localhost:" + this.port);
fooFactoryBean.setApplicationContext(applicationContext);
return fooFactoryBean.feign(context).target(FooClient.class,
"http://localhost:" + port);
}
public BarClient barClient() {
this.barFactoryBean.setApplicationContext(this.applicationContext);
return this.barFactoryBean.feign(this.context).target(BarClient.class,
"http://localhost:" + this.port);
barFactoryBean.setApplicationContext(applicationContext);
return barFactoryBean.feign(context).target(BarClient.class,
"http://localhost:" + port);
}
public UnwrapClient unwrapClient() {
this.unwrapFactoryBean.setApplicationContext(this.applicationContext);
return this.unwrapFactoryBean.feign(this.context).target(UnwrapClient.class,
"http://localhost:" + this.port);
unwrapFactoryBean.setApplicationContext(applicationContext);
return unwrapFactoryBean.feign(context).target(UnwrapClient.class,
"http://localhost:" + port);
}
public FormClient formClient() {
this.formFactoryBean.setApplicationContext(this.applicationContext);
return this.formFactoryBean.feign(this.context).target(FormClient.class,
"http://localhost:" + this.port);
formFactoryBean.setApplicationContext(applicationContext);
return formFactoryBean.feign(context).target(FormClient.class,
"http://localhost:" + port);
}
@Test
@@ -149,23 +185,93 @@ 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();
readTimeoutFactoryBean.setContextId("readTimeout");
readTimeoutFactoryBean.setType(FeignClientFactoryBean.class);
readTimeoutFactoryBean.setApplicationContext(applicationContext);
TimeoutClient client = readTimeoutFactoryBean.feign(context)
.target(TimeoutClient.class, "http://localhost:" + port);
Request.Options options = getRequestOptions((Proxy) client);
assertThat(options.readTimeoutMillis()).isEqualTo(1000);
assertThat(options.connectTimeoutMillis()).isEqualTo(5000);
}
@Test
public void connectTimeoutShouldWorkWhenReadTimeoutNotSet() {
FeignClientFactoryBean readTimeoutFactoryBean = new FeignClientFactoryBean();
readTimeoutFactoryBean.setContextId("connectTimeout");
readTimeoutFactoryBean.setType(FeignClientFactoryBean.class);
readTimeoutFactoryBean.setApplicationContext(applicationContext);
TimeoutClient client = readTimeoutFactoryBean.feign(context)
.target(TimeoutClient.class, "http://localhost:" + port);
Request.Options options = getRequestOptions((Proxy) client);
assertThat(options.connectTimeoutMillis()).isEqualTo(1000);
assertThat(options.readTimeoutMillis()).isEqualTo(5000);
}
private Request.Options getRequestOptions(Proxy client) {
Object invocationHandler = ReflectionTestUtils.getField(client, "h");
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");
}
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;
}
@@ -178,6 +284,27 @@ 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")
String timeouts();
}
@Configuration(proxyBeanMethods = false)
@EnableAutoConfiguration
@RestController
@@ -195,18 +322,33 @@ 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,
@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 {
@@ -20,7 +20,9 @@ import java.util.Collections;
import org.junit.Test;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.cloud.openfeign.test.TestAutoConfiguration;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.mock.env.MockEnvironment;
@@ -28,10 +30,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,6 +93,18 @@ public class FeignClientsRegistrarTests {
new AnnotationConfigApplicationContext(FallbackFactoryTestConfig.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 {
@@ -122,4 +138,12 @@ public class FeignClientsRegistrarTests {
}
@EnableFeignClients(clients = {
org.springframework.cloud.openfeign.feignclientsregistrar.TopLevelClient.class,
org.springframework.cloud.openfeign.feignclientsregistrar.sub.SubLevelClient.class })
@EnableAutoConfiguration(exclude = TestAutoConfiguration.class)
protected static class TopLevelSubLevelTestConfig {
}
}
@@ -0,0 +1,83 @@
/*
* 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.beans;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.GetMapping;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
/**
* @author Olga Maciaszek-Sharma
*/
@SpringBootTest(classes = FeignClientMockBeanTests.Config.class)
public class FeignClientMockBeanTests {
@MockBean
private RandomClient randomClient;
@Autowired
private TestService testService;
@Test
public void randomClientShouldBeMocked() {
String mockMessage = "Mocked Feign Client";
when(randomClient.getRandomString()).thenReturn(mockMessage);
String returnedMessage = testService.testMethod();
assertThat(returnedMessage).isEqualTo(mockMessage);
}
@FeignClient("random-test")
protected interface RandomClient {
@GetMapping("/random-test")
String getRandomString();
}
@Configuration
protected static class Config {
@Bean
TestService testService() {
return new TestService();
}
}
}
class TestService {
@Autowired
private FeignClientMockBeanTests.RandomClient randomClient;
public String testMethod() {
return randomClient.getRandomString();
}
}
@@ -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 {
}
@@ -45,7 +45,8 @@ class FeignLoadBalancerAutoConfigurationTests {
void shouldInstantiateDefaultFeignBlockingLoadBalancerClientWhenHttpClientDisabled() {
ConfigurableApplicationContext context = initContext(
"spring.cloud.loadbalancer.ribbon.enabled=false",
"feign.httpclient.enabled=false");
"feign.httpclient.enabled=false",
"spring.cloud.loadbalancer.retry.enabled=false");
assertThatOneBeanPresent(context, BlockingLoadBalancerClient.class);
assertLoadBalanced(context, Client.Default.class);
assertThatBeanNotPresent(context, LoadBalancerFeignClient.class);
@@ -54,7 +55,8 @@ class FeignLoadBalancerAutoConfigurationTests {
@Test
void shouldInstantiateHttpFeignClientWhenEnabled() {
ConfigurableApplicationContext context = initContext(
"spring.cloud.loadbalancer.ribbon.enabled=false");
"spring.cloud.loadbalancer.ribbon.enabled=false",
"spring.cloud.loadbalancer.retry.enabled=false");
assertThatOneBeanPresent(context, BlockingLoadBalancerClient.class);
assertLoadBalanced(context, ApacheHttpClient.class);
assertThatBeanNotPresent(context, LoadBalancerFeignClient.class);
@@ -64,16 +66,47 @@ class FeignLoadBalancerAutoConfigurationTests {
void shouldInstantiateOkHttpFeignClientWhenEnabled() {
ConfigurableApplicationContext context = initContext(
"spring.cloud.loadbalancer.ribbon.enabled=false",
"feign.httpclient.enabled=false", "feign.okhttp.enabled=true");
"feign.httpclient.enabled=false", "feign.okhttp.enabled=true",
"spring.cloud.loadbalancer.retry.enabled=false");
assertThatOneBeanPresent(context, BlockingLoadBalancerClient.class);
assertLoadBalanced(context, OkHttpClient.class);
assertThatBeanNotPresent(context, LoadBalancerFeignClient.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);
assertThatBeanNotPresent(context, LoadBalancerFeignClient.class);
}
@Test
void shouldInstantiateRetryableHttpFeignClientWhenEnabled() {
ConfigurableApplicationContext context = initContext(
"spring.cloud.loadbalancer.ribbon.enabled=false");
assertThatOneBeanPresent(context, BlockingLoadBalancerClient.class);
assertLoadBalancedWithRetries(context, ApacheHttpClient.class);
assertThatBeanNotPresent(context, LoadBalancerFeignClient.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);
assertThatBeanNotPresent(context, LoadBalancerFeignClient.class);
}
@Test
void shouldNotProcessLoadBalancerConfigurationWhenRibbonEnabled() {
ConfigurableApplicationContext context = initContext(
"spring.cloud.loadbalancer.ribbon.enabled=true");
"spring.cloud.loadbalancer.ribbon.enabled=true",
"spring.cloud.loadbalancer.retry.enabled=false");
assertThatOneBeanPresent(context, LoadBalancerFeignClient.class);
assertThatBeanNotPresent(context, BlockingLoadBalancerClient.class);
assertThatBeanNotPresent(context, FeignBlockingLoadBalancerClient.class);
@@ -104,6 +137,18 @@ class FeignLoadBalancerAutoConfigurationTests {
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);
}
private void assertThatBeanNotPresent(ConfigurableApplicationContext context,
Class<?> beanClass) {
Map<String, ?> beans = context.getBeansOfType(beanClass);
@@ -0,0 +1,197 @@
/*
* 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 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.LoadBalancedRetryFactory;
import org.springframework.cloud.client.loadbalancer.LoadBalancerRetryProperties;
import org.springframework.cloud.loadbalancer.blocking.client.BlockingLoadBalancerClient;
import org.springframework.cloud.loadbalancer.blocking.retry.BlockingLoadBalancedRetryPolicy;
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 LoadBalancerRetryProperties properties = new LoadBalancerRetryProperties();
private RetryableFeignBlockingLoadBalancerClient feignBlockingLoadBalancerClient = new RetryableFeignBlockingLoadBalancerClient(
delegate, loadBalancerClient, retryFactory);
private ServiceInstance serviceInstance = new DefaultServiceInstance("test-a", "test",
"testhost", 80, false);
@BeforeEach
void setUp() {
when(retryFactory.createRetryPolicy(any(), eq(loadBalancerClient)))
.thenReturn(new BlockingLoadBalancedRetryPolicy("test",
loadBalancerClient, properties));
when(loadBalancerClient.choose("test")).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("test",
loadBalancerClient, 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("test");
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("test")).thenReturn(null);
when(delegate.execute(any(), any())).thenReturn(response);
when(retryFactory.createRetryPolicy(any(), eq(loadBalancerClient)))
.thenReturn(new BlockingLoadBalancedRetryPolicy("test",
loadBalancerClient, properties));
feignBlockingLoadBalancerClient.execute(request, new Request.Options());
verify(delegate).execute(eq(request), any());
}
@Test
void shouldRetryOnRepeatableStatusCode() throws IOException {
properties.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("test",
loadBalancerClient, 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("test")).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("test",
loadBalancerClient, 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");
}
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;
}
}
@@ -0,0 +1,94 @@
/*
* 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 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.CollectionFormat;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.cloud.openfeign.test.NoSecurityConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.util.SocketUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Olga Maciaszek-Sharma
*/
@SpringBootTest(classes = PageableSupportTest.Config.class,
webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class PageableSupportTest {
@Autowired
private PageableFeignClient feignClient;
@BeforeAll
public static void beforeClass() {
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"))));
assertThat(direction).isEqualTo("DESC");
}
@FeignClient(name = "pageable", url = "http://localhost:${server.port}/")
protected interface PageableFeignClient {
@CollectionFormat(feign.CollectionFormat.CSV)
@GetMapping(path = "/page")
String performRequest(Pageable page);
}
@SuppressWarnings("ConstantConditions")
@Configuration(proxyBeanMethods = false)
@EnableAutoConfiguration
@RestController
@EnableFeignClients(clients = PageableFeignClient.class)
@Import(NoSecurityConfiguration.class)
protected static class Config {
@GetMapping(path = "/page")
String performRequest(Pageable page) {
return page.getSort().getOrderFor("property").getDirection().toString();
}
}
}
@@ -0,0 +1,116 @@
/*
* 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,12 +31,10 @@ 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;
import org.springframework.core.convert.ConversionService;
import org.springframework.format.annotation.DateTimeFormat;
@@ -62,6 +60,7 @@ import org.springframework.web.multipart.MultipartFile;
import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.ANY;
import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.NONE;
import static feign.CollectionFormat.SSV;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assume.assumeTrue;
@@ -71,8 +70,8 @@ import static org.junit.Assume.assumeTrue;
* @author Aram Peres
* @author Aaron Whiteside
* @author Artyom Romanenko
* @author Olga Maciaszek-Sharma
*/
@RunWith(JUnitParamsRunner.class)
public class SpringMvcContractTests {
private static final Class<?> EXECUTABLE_TYPE;
@@ -123,14 +122,14 @@ public class SpringMvcContractTests {
conversionServiceFactoryBean.afterPropertiesSet();
ConversionService conversionService = conversionServiceFactoryBean.getObject();
this.contract = new SpringMvcContract(Collections.emptyList(), conversionService);
contract = new SpringMvcContract(Collections.emptyList(), conversionService);
}
@Test
public void testProcessAnnotationOnMethod_Simple() throws Exception {
Method method = TestTemplate_Simple.class.getDeclaredMethod("getTest",
String.class);
MethodMetadata data = this.contract
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
assertThat(data.template().url()).isEqualTo("/test/{id}");
@@ -143,7 +142,7 @@ public class SpringMvcContractTests {
public void testProcessAnnotations_Simple() throws Exception {
Method method = TestTemplate_Simple.class.getDeclaredMethod("getTest",
String.class);
MethodMetadata data = this.contract
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
assertThat(data.template().url()).isEqualTo("/test/{id}");
@@ -158,7 +157,7 @@ public class SpringMvcContractTests {
public void testProcessAnnotations_SimpleGetMapping() throws Exception {
Method method = TestTemplate_Simple.class.getDeclaredMethod("getMappingTest",
String.class);
MethodMetadata data = this.contract
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
assertThat(data.template().url()).isEqualTo("/test/{id}");
@@ -174,7 +173,7 @@ public class SpringMvcContractTests {
throws Exception {
Method method = TestTemplate_Class_Annotations.class
.getDeclaredMethod("getSpecificTest", String.class, String.class);
MethodMetadata data = this.contract
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
assertThat(data.template().url()).isEqualTo("/prepend/{classId}/test/{testId}");
@@ -188,7 +187,7 @@ public class SpringMvcContractTests {
public void testProcessAnnotations_Class_AnnotationsGetAllTests() throws Exception {
Method method = TestTemplate_Class_Annotations.class
.getDeclaredMethod("getAllTests", String.class);
MethodMetadata data = this.contract
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
assertThat(data.template().url()).isEqualTo("/prepend/{classId}");
@@ -201,12 +200,12 @@ public class SpringMvcContractTests {
public void testProcessAnnotations_ExtendedInterface() throws Exception {
Method extendedMethod = TestTemplate_Extended.class.getMethod("getAllTests",
String.class);
MethodMetadata extendedData = this.contract.parseAndValidateMetadata(
MethodMetadata extendedData = contract.parseAndValidateMetadata(
extendedMethod.getDeclaringClass(), extendedMethod);
Method method = TestTemplate_Class_Annotations.class
.getDeclaredMethod("getAllTests", String.class);
MethodMetadata data = this.contract
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
assertThat(data.template().url()).isEqualTo(extendedData.template().url());
@@ -220,7 +219,7 @@ public class SpringMvcContractTests {
public void testProcessAnnotations_SimplePost() throws Exception {
Method method = TestTemplate_Simple.class.getDeclaredMethod("postTest",
TestObject.class);
MethodMetadata data = this.contract
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
assertThat(data.template().url()).isEqualTo("/");
@@ -234,7 +233,7 @@ public class SpringMvcContractTests {
public void testProcessAnnotations_SimplePostMapping() throws Exception {
Method method = TestTemplate_Simple.class.getDeclaredMethod("postMappingTest",
TestObject.class);
MethodMetadata data = this.contract
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
assertThat(data.template().url()).isEqualTo("/");
@@ -248,7 +247,7 @@ public class SpringMvcContractTests {
public void testProcessAnnotationsOnMethod_Advanced() throws Exception {
Method method = TestTemplate_Advanced.class.getDeclaredMethod("getTest",
String.class, String.class, Integer.class);
MethodMetadata data = this.contract
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
assertThat(data.template().url())
@@ -263,16 +262,28 @@ public class SpringMvcContractTests {
throws Exception {
Method method = TestTemplate_Advanced.class.getDeclaredMethod("getTest",
String.class, String.class, Integer.class);
this.contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
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");
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 = this.contract
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
assertThat(data.template().url())
@@ -297,7 +308,7 @@ public class SpringMvcContractTests {
public void testProcessAnnotations_Aliased() throws Exception {
Method method = TestTemplate_Advanced.class.getDeclaredMethod("getTest2",
String.class, Integer.class);
MethodMetadata data = this.contract
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
assertThat(data.template().url())
@@ -320,7 +331,7 @@ public class SpringMvcContractTests {
public void testProcessAnnotations_DateTimeFormatParam() throws Exception {
Method method = TestTemplate_DateTimeFormatParameter.class
.getDeclaredMethod("getTest", LocalDateTime.class);
MethodMetadata data = this.contract
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
Param.Expander expander = data.indexToExpander().get(0);
@@ -340,7 +351,7 @@ public class SpringMvcContractTests {
public void testProcessAnnotations_NumberFormatParam() throws Exception {
Method method = TestTemplate_NumberFormatParameter.class
.getDeclaredMethod("getTest", BigDecimal.class);
MethodMetadata data = this.contract
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
Param.Expander expander = data.indexToExpander().get(0);
@@ -360,7 +371,7 @@ public class SpringMvcContractTests {
@Test
public void testProcessAnnotations_Advanced2() throws Exception {
Method method = TestTemplate_Advanced.class.getDeclaredMethod("getTest");
MethodMetadata data = this.contract
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
assertThat(data.template().url()).isEqualTo("/advanced");
@@ -372,7 +383,7 @@ public class SpringMvcContractTests {
@Test
public void testProcessAnnotations_Advanced3() throws Exception {
Method method = TestTemplate_Simple.class.getDeclaredMethod("getTest");
MethodMetadata data = this.contract
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
assertThat(data.template().url()).isEqualTo("/");
@@ -385,7 +396,7 @@ public class SpringMvcContractTests {
public void testProcessAnnotations_ListParams() throws Exception {
Method method = TestTemplate_ListParams.class.getDeclaredMethod("getTest",
List.class);
MethodMetadata data = this.contract
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
assertThat(data.template().url()).isEqualTo("/test?id=" + "{id}");
@@ -398,7 +409,7 @@ public class SpringMvcContractTests {
public void testProcessAnnotations_ListParamsWithoutName() throws Exception {
Method method = TestTemplate_ListParamsWithoutName.class
.getDeclaredMethod("getTest", List.class);
MethodMetadata data = this.contract
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
assertThat(data.template().url()).isEqualTo("/test?id=" + "{id}");
@@ -411,7 +422,7 @@ public class SpringMvcContractTests {
public void testProcessAnnotations_MapParams() throws Exception {
Method method = TestTemplate_MapParams.class.getDeclaredMethod("getTest",
Map.class);
MethodMetadata data = this.contract
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
assertThat(data.template().url()).isEqualTo("/test");
@@ -424,12 +435,12 @@ public class SpringMvcContractTests {
public void testProcessHeaders() throws Exception {
Method method = TestTemplate_Headers.class.getDeclaredMethod("getTest",
String.class);
MethodMetadata data = this.contract
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())
assertThat(data.template().headers().get("x-Foo").iterator().next())
.isEqualTo("bar");
}
@@ -437,7 +448,7 @@ public class SpringMvcContractTests {
public void testProcessHeadersWithoutValues() throws Exception {
Method method = TestTemplate_HeadersWithoutValues.class
.getDeclaredMethod("getTest", String.class);
MethodMetadata data = this.contract
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
assertThat(data.template().url()).isEqualTo("/test/{id}");
@@ -453,7 +464,7 @@ public class SpringMvcContractTests {
assumeTrue("does not have java 8 parameter names",
hasJava8ParameterNames(method));
MethodMetadata data = this.contract
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
assertThat(data.template().url())
@@ -477,7 +488,7 @@ public class SpringMvcContractTests {
public void testProcessHeaderMap() throws Exception {
Method method = TestTemplate_HeaderMap.class.getDeclaredMethod("headerMap",
MultiValueMap.class, String.class);
MethodMetadata data = this.contract
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
assertThat(data.template().url()).isEqualTo("/headerMap");
@@ -491,14 +502,14 @@ public class SpringMvcContractTests {
public void testProcessHeaderMapMoreThanOnce() throws Exception {
Method method = TestTemplate_HeaderMap.class.getDeclaredMethod(
"headerMapMoreThanOnce", MultiValueMap.class, MultiValueMap.class);
this.contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
}
@Test
public void testProcessQueryMap() throws Exception {
Method method = TestTemplate_QueryMap.class.getDeclaredMethod("queryMap",
MultiValueMap.class, String.class);
MethodMetadata data = this.contract
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
assertThat(data.template().url()).isEqualTo("/queryMap?aParam=" + "{aParam}");
@@ -512,7 +523,7 @@ public class SpringMvcContractTests {
public void testProcessQueryMapObject() throws Exception {
Method method = TestTemplate_QueryMap.class.getDeclaredMethod("queryMapObject",
TestObject.class, String.class);
MethodMetadata data = this.contract
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
assertThat(data.template().url())
@@ -527,14 +538,14 @@ public class SpringMvcContractTests {
public void testProcessQueryMapMoreThanOnce() throws Exception {
Method method = TestTemplate_QueryMap.class.getDeclaredMethod(
"queryMapMoreThanOnce", MultiValueMap.class, MultiValueMap.class);
this.contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
}
@Test
public void testMatrixVariable_MapParam() throws Exception {
Method method = TestTemplate_MatrixVariable.class
.getDeclaredMethod("matrixVariable", Map.class);
MethodMetadata data = this.contract
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
Map<String, String> testMap = new HashMap<>();
@@ -550,7 +561,7 @@ public class SpringMvcContractTests {
public void testMatrixVariable_ObjectParam() throws Exception {
Method method = TestTemplate_MatrixVariable.class
.getDeclaredMethod("matrixVariableObject", Object.class);
MethodMetadata data = this.contract
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
assertThat(data.template().method()).isEqualTo("GET");
@@ -563,7 +574,7 @@ public class SpringMvcContractTests {
public void testMatrixVariableWithNoName() throws NoSuchMethodException {
Method method = TestTemplate_MatrixVariable.class
.getDeclaredMethod("matrixVariableNotNamed", Map.class);
MethodMetadata data = this.contract
MethodMetadata data = contract
.parseAndValidateMetadata(method.getDeclaringClass(), method);
Map<String, String> testMap = new HashMap<>();
@@ -587,53 +598,6 @@ public class SpringMvcContractTests {
"{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");
}
@Test
public void testMultipleRequestPartAnnotations() throws NoSuchMethodException {
Method method = TestTemplate_RequestPart.class.getDeclaredMethod(
@@ -774,6 +738,10 @@ public class SpringMvcContractTests {
@RequestMapping("/advanced")
public interface TestTemplate_Advanced {
@CollectionFormat(SSV)
@GetMapping
ResponseEntity<TestObject> getWithCollectionFormat();
@ExceptionHandler
@RequestMapping(path = "/test/{id}", method = RequestMethod.PUT,
produces = MediaType.APPLICATION_JSON_VALUE)
@@ -822,40 +790,6 @@ public class SpringMvcContractTests {
}
@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)
public class TestObject {
@@ -883,11 +817,10 @@ public class SpringMvcContractTests {
TestObject that = (TestObject) o;
if (this.number != null ? !this.number.equals(that.number)
: that.number != null) {
if (number != null ? !number.equals(that.number) : that.number != null) {
return false;
}
if (this.something != null ? !this.something.equals(that.something)
if (something != null ? !something.equals(that.something)
: that.something != null) {
return false;
}
@@ -897,16 +830,16 @@ public class SpringMvcContractTests {
@Override
public int hashCode() {
int result = (this.something != null ? this.something.hashCode() : 0);
result = 31 * result + (this.number != null ? this.number.hashCode() : 0);
int result = (something != null ? something.hashCode() : 0);
result = 31 * result + (number != null ? number.hashCode() : 0);
return result;
}
@Override
public String toString() {
return new StringBuilder("TestObject{").append("something='")
.append(this.something).append("', ").append("number=")
.append(this.number).append("}").toString();
.append(something).append("', ").append("number=").append(number)
.append("}").toString();
}
}
@@ -10,9 +10,15 @@ feign.client.config.default.retryer=org.springframework.cloud.openfeign.FeignCli
feign.client.config.default.decode404=true
feign.client.config.foo.requestInterceptors[0]=org.springframework.cloud.openfeign.FeignClientUsingPropertiesTests.FooRequestInterceptor
feign.client.config.foo.requestInterceptors[1]=org.springframework.cloud.openfeign.FeignClientUsingPropertiesTests.BarRequestInterceptor
feign.client.config.singleValue.defaultRequestHeaders[singleValueHeaders]=header
feign.client.config.singleValue.defaultQueryParameters[singleValueParameters]=parameter
feign.client.config.multipleValue.defaultRequestHeaders[multipleValueHeaders]=header1,header2
feign.client.config.multipleValue.defaultQueryParameters[multipleValueParameters]=parameter1,parameter2
feign.client.config.bar.connectTimeout=1000
feign.client.config.bar.readTimeout=1000
feign.client.config.form.encoder=org.springframework.cloud.openfeign.FeignClientUsingPropertiesTests.FormEncoder
feign.client.config.unwrap.connectTimeout=1000
feign.client.config.unwrap.readTimeout=1000
feign.client.config.unwrap.exceptionPropagationPolicy=unwrap
feign.client.config.readTimeout.readTimeout=1000
feign.client.config.connectTimeout.connectTimeout=1000
+2 -2
View File
@@ -6,11 +6,11 @@
<parent>
<artifactId>spring-cloud-dependencies-parent</artifactId>
<groupId>org.springframework.cloud</groupId>
<version>2.3.0.RELEASE</version>
<version>2.3.1.RELEASE</version>
<relativePath/>
</parent>
<artifactId>spring-cloud-openfeign-dependencies</artifactId>
<version>2.2.3.RELEASE</version>
<version>2.2.6.RELEASE</version>
<packaging>pom</packaging>
<name>spring-cloud-openfeign-dependencies</name>
<description>Spring Cloud OpenFeign Dependencies</description>
+1 -1
View File
@@ -5,7 +5,7 @@
<parent>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-openfeign</artifactId>
<version>2.2.3.RELEASE</version>
<version>2.2.6.RELEASE</version>
<relativePath>..</relativePath>
</parent>
<artifactId>spring-cloud-starter-openfeign</artifactId>