Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e321e72e3d | ||
|
|
ae63aae6eb | ||
|
|
10fefea29b | ||
|
|
24d9b08d5c | ||
|
|
d4832788f6 | ||
|
|
ff96850ec0 | ||
|
|
9023cc2dc5 | ||
|
|
6c3b8c257e | ||
|
|
fe43b6c52b |
@@ -5,9 +5,9 @@ name: Build
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ main ]
|
||||
branches: [ 3.0.x ]
|
||||
pull_request:
|
||||
branches: [ main ]
|
||||
branches: [ 3.0.x ]
|
||||
|
||||
jobs:
|
||||
build:
|
||||
|
||||
@@ -20,4 +20,5 @@ _site/
|
||||
*.swo
|
||||
.vscode/
|
||||
.flattened-pom.xml
|
||||
.sdkmanrc
|
||||
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
# Enable auto-env through the sdkman_auto_env config
|
||||
# Add key=value pairs of SDKs to use below
|
||||
java=8.0.292.hs-adpt
|
||||
+1
-3
@@ -6,7 +6,7 @@
|
||||
<parent>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-openfeign</artifactId>
|
||||
<version>3.1.3</version>
|
||||
<version>3.0.7</version>
|
||||
</parent>
|
||||
<artifactId>spring-cloud-openfeign-docs</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
@@ -17,8 +17,6 @@
|
||||
<main.basedir>${basedir}/..</main.basedir>
|
||||
<configprops.inclusionPattern>feign.*</configprops.inclusionPattern>
|
||||
<upload-docs-zip.phase>deploy</upload-docs-zip.phase>
|
||||
<!-- Don't upload docs jar to central / repo.spring.io -->
|
||||
<maven-deploy-plugin-default.phase>none</maven-deploy-plugin-default.phase>
|
||||
</properties>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
|Name | Default | Description
|
||||
|
||||
|feign.autoconfiguration.jackson.enabled | `false` | If true, PageJacksonModule and SortJacksonModule bean will be provided for Jackson page decoding.
|
||||
|feign.circuitbreaker.alphanumeric-ids.enabled | `false` | If true, Circuit Breaker ids will only contain alphanumeric characters to allow for configuration via configuration properties.
|
||||
|feign.circuitbreaker.enabled | `false` | If true, an OpenFeign client will be wrapped with a Spring Cloud CircuitBreaker circuit breaker.
|
||||
|feign.circuitbreaker.group.enabled | `false` | If true, an OpenFeign client will be wrapped with a Spring Cloud CircuitBreaker circuit breaker with with group.
|
||||
|feign.client.config | |
|
||||
@@ -14,6 +13,7 @@
|
||||
|feign.compression.request.mime-types | `[text/xml, application/xml, application/json]` | The list of supported mime types.
|
||||
|feign.compression.request.min-request-size | `2048` | The minimum threshold content size.
|
||||
|feign.compression.response.enabled | `false` | Enables the response from Feign to be compressed.
|
||||
|feign.compression.response.useGzipDecoder | `false` | Enables the default gzip decoder to be used.
|
||||
|feign.encoder.charset-from-content-type | `false` | Indicates whether the charset should be derived from the {@code Content-Type} header.
|
||||
|feign.httpclient.connection-timeout | `2000` |
|
||||
|feign.httpclient.connection-timer-repeat | `3000` |
|
||||
@@ -27,12 +27,9 @@
|
||||
|feign.httpclient.hc5.socket-timeout-unit | | Default value for socket timeout unit.
|
||||
|feign.httpclient.max-connections | `200` |
|
||||
|feign.httpclient.max-connections-per-route | `50` |
|
||||
|feign.httpclient.ok-http.read-timeout | `60s` | {@link OkHttpClient} read timeout; defaults to 60 seconds.
|
||||
|feign.httpclient.time-to-live | `900` |
|
||||
|feign.httpclient.time-to-live-unit | |
|
||||
|feign.metrics.enabled | `true` | Enables metrics capability for Feign.
|
||||
|feign.oauth2.enabled | `false` | Enables feign interceptor for managing oauth2 access token.
|
||||
|feign.oauth2.load-balanced | `false` | Enables load balancing for oauth2 access token provider.
|
||||
|feign.okhttp.enabled | `false` | Enables the use of the OK HTTP Client by Feign.
|
||||
|
||||
|===
|
||||
@@ -1 +0,0 @@
|
||||
include::spring-cloud-openfeign.adoc[]
|
||||
+1
@@ -0,0 +1 @@
|
||||
spring-cloud-openfeign.adoc
|
||||
@@ -52,9 +52,6 @@ public interface StoreClient {
|
||||
|
||||
@RequestMapping(method = RequestMethod.POST, value = "/stores/{storeId}", consumes = "application/json")
|
||||
Store update(@PathVariable("storeId") Long storeId, Store store);
|
||||
|
||||
@RequestMapping(method = RequestMethod.DELETE, value = "/stores/{storeId:\\d+}")
|
||||
void delete(@PathVariable Long storeId);
|
||||
}
|
||||
----
|
||||
|
||||
@@ -122,7 +119,6 @@ Spring Cloud OpenFeign provides the following beans by default for feign (`BeanT
|
||||
* `Encoder` feignEncoder: `SpringEncoder`
|
||||
* `Logger` feignLogger: `Slf4jLogger`
|
||||
* `MicrometerCapability` micrometerCapability: If `feign-micrometer` is on the classpath and `MeterRegistry` is available
|
||||
* `CachingCapability` cachingCapability: If `@EnableCaching` annotation is used. Can be disabled via `feign.cache.enabled`.
|
||||
* `Contract` feignContract: `SpringMvcContract`
|
||||
* `Feign.Builder` feignBuilder: `FeignCircuitBreaker.Builder`
|
||||
* `Client` feignClient: If Spring Cloud LoadBalancer is on the classpath, `FeignBlockingLoadBalancerClient` is used.
|
||||
@@ -142,7 +138,7 @@ Spring Cloud OpenFeign _does not_ provide the following beans by default for fei
|
||||
* `Collection<RequestInterceptor>`
|
||||
* `SetterFactory`
|
||||
* `QueryMapEncoder`
|
||||
* `Capability` (`MicrometerCapability` and `CachingCapability` are provided by default)
|
||||
* `Capability` (`MicrometerCapability` is provided by default)
|
||||
|
||||
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,
|
||||
@@ -196,7 +192,6 @@ feign:
|
||||
capabilities:
|
||||
- com.example.FooCapability
|
||||
- com.example.BarCapability
|
||||
queryMapEncoder: com.example.SimpleQueryMapEncoder
|
||||
metrics.enabled: false
|
||||
----
|
||||
|
||||
@@ -372,47 +367,6 @@ public class FooConfiguration {
|
||||
|
||||
To enable Spring Cloud CircuitBreaker group set the `feign.circuitbreaker.group.enabled` property to `true` (by default `false`).
|
||||
|
||||
[[spring-clou-feign-circuitbreaker-configurationproperties]]
|
||||
=== Configuring CircuitBreakers With Configuration Properties
|
||||
|
||||
You can configure CircuitBreakers via configuration properties. To do set
|
||||
`feign.circuitbreaker.alphanumeric-ids.enabled` to `true`. Since
|
||||
you cannot use characters like `#`, `(`, `)` `,` in configuration property names we need to
|
||||
change the naming convention for the ids of the circuit breakers generated by OpenFeign. The above
|
||||
property will do this for you.
|
||||
|
||||
For example, if you had this Feign client
|
||||
|
||||
[source,java,indent=0]
|
||||
----
|
||||
@FeignClienturl = "http://localhost:8080")
|
||||
public interface DemoClient {
|
||||
|
||||
@GetMapping("demo")
|
||||
String getDemo();
|
||||
}
|
||||
----
|
||||
|
||||
You could configure it using configuration properties by doing the following
|
||||
|
||||
[source,yaml,indent=0]
|
||||
----
|
||||
feign:
|
||||
circuitbreaker:
|
||||
enabled: true
|
||||
alphanumeric-ids:
|
||||
enabled: true
|
||||
resilience4j:
|
||||
circuitbreaker:
|
||||
instances:
|
||||
DemoClientgetDemo:
|
||||
minimumNumberOfCalls: 69
|
||||
timelimiter:
|
||||
instances:
|
||||
DemoClientgetDemo:
|
||||
timeoutDuration: 10s
|
||||
----
|
||||
|
||||
|
||||
[[spring-cloud-feign-circuitbreaker-fallback]]
|
||||
=== Feign Spring Cloud CircuitBreaker Fallbacks
|
||||
@@ -561,6 +515,14 @@ feign.compression.request.min-request-size=2048
|
||||
|
||||
These properties allow you to be selective about the compressed media types and minimum request threshold length.
|
||||
|
||||
For http clients except OkHttpClient, default gzip decoder can be enabled to decode gzip response in UTF-8 encoding:
|
||||
|
||||
[source,java]
|
||||
----
|
||||
feign.compression.response.enabled=true
|
||||
feign.compression.response.useGzipDecoder=true
|
||||
----
|
||||
|
||||
=== Feign logging
|
||||
|
||||
A logger is created for each Feign client created. By default the name of the logger is the full class name of the interface used to create the Feign client. Feign logging only responds to the `DEBUG` level.
|
||||
@@ -645,22 +607,6 @@ public class FooConfiguration {
|
||||
}
|
||||
----
|
||||
|
||||
=== Feign Caching
|
||||
|
||||
If `@EnableCaching` annotation is used, a `CachingCapability` bean is created and registered so that your Feign client recognizes `@Cache*` annotations on its interface:
|
||||
|
||||
[source,java,indent=0]
|
||||
----
|
||||
public interface DemoClient {
|
||||
|
||||
@GetMapping("/demo/{filterParam}")
|
||||
@Cacheable(cacheNames = "demo-cache", key = "#keyParam")
|
||||
String demoEndpoint(String keyParam, @PathVariable String filterParam);
|
||||
}
|
||||
----
|
||||
|
||||
You can also disable the feature via property `feign.cache.enabled=false`.
|
||||
|
||||
=== Feign @QueryMap support
|
||||
|
||||
The OpenFeign `@QueryMap` annotation provides support for POJOs to be used as
|
||||
@@ -748,21 +694,20 @@ public interface DemoTemplate {
|
||||
----
|
||||
|
||||
=== Feign `CollectionFormat` support
|
||||
We support `feign.CollectionFormat` by providing the `@CollectionFormat` annotation.
|
||||
You can annotate a Feign client method (or the whole class to affect all methods) with it by passing the desired `feign.CollectionFormat` as annotation value.
|
||||
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 {
|
||||
protected interface PageableFeignClient {
|
||||
|
||||
@CollectionFormat(feign.CollectionFormat.CSV)
|
||||
@GetMapping(path = "/page")
|
||||
ResponseEntity performRequest(Pageable page);
|
||||
@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.
|
||||
@@ -780,7 +725,7 @@ To work around this problem you can use an `ObjectProvider` when autowiring your
|
||||
[source,java,indent=0]
|
||||
----
|
||||
@Autowired
|
||||
ObjectProvider<TestFeignClient> testFeignClient;
|
||||
ObjectProvider<TestFeginClient> testFeginClient;
|
||||
----
|
||||
|
||||
=== Spring Data Support
|
||||
@@ -802,16 +747,6 @@ feign.client.refresh-enabled=true
|
||||
----
|
||||
TIP: DO NOT annotate the `@FeignClient` interface with the `@RefreshScope` annotation.
|
||||
|
||||
=== OAuth2 Support
|
||||
OAuth2 support can be enabled by setting following flag:
|
||||
----
|
||||
feign.oauth2.enabled=true
|
||||
----
|
||||
When the flag is set to true, and the oauth2 client context resource details are present, a bean of class `OAuth2FeignRequestInterceptor` is created. Before each request, the interceptor resolves the required access token and includes it as a header.
|
||||
Sometimes, when load balancing is enabled for Feign clients, you may want to use load balancing for fetching access tokens, too. To do so, you should ensure that the load balancer is on the classpath (spring-cloud-starter-loadbalancer) and explicitly enable load balancing for OAuth2FeignRequestInterceptor by setting the following flag:
|
||||
----
|
||||
feign.oauth2.load-balanced=true
|
||||
----
|
||||
|
||||
== Configuration properties
|
||||
|
||||
|
||||
@@ -4,14 +4,14 @@
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>spring-cloud-openfeign</artifactId>
|
||||
<version>3.1.3</version>
|
||||
<version>3.0.7</version>
|
||||
<packaging>pom</packaging>
|
||||
<name>Spring Cloud OpenFeign</name>
|
||||
<description>Spring Cloud OpenFeign</description>
|
||||
<parent>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-build</artifactId>
|
||||
<version>3.1.3</version>
|
||||
<version>3.0.5</version>
|
||||
<relativePath/>
|
||||
</parent>
|
||||
<scm>
|
||||
@@ -26,7 +26,7 @@
|
||||
<properties>
|
||||
<main.basedir>${basedir}</main.basedir>
|
||||
<jackson.version>2.11.3</jackson.version>
|
||||
<spring-cloud-commons.version>3.1.3</spring-cloud-commons.version>
|
||||
<spring-cloud-commons.version>3.0.6</spring-cloud-commons.version>
|
||||
|
||||
<!-- Plugin versions -->
|
||||
<maven-eclipse-plugin.version>2.10</maven-eclipse-plugin.version>
|
||||
@@ -79,15 +79,6 @@
|
||||
<groupId>io.spring.javaformat</groupId>
|
||||
<artifactId>spring-javaformat-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.basepom.maven</groupId>
|
||||
<artifactId>duplicate-finder-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<ignoredResourcePatterns>
|
||||
<ignoredResourcePattern>mozilla/public-suffix-list.txt</ignoredResourcePattern>
|
||||
</ignoredResourcePatterns>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
<parent>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-openfeign</artifactId>
|
||||
<version>3.1.3</version>
|
||||
<version>3.0.7</version>
|
||||
<relativePath>..</relativePath> <!-- lookup parent from repository -->
|
||||
</parent>
|
||||
<artifactId>spring-cloud-openfeign-core</artifactId>
|
||||
@@ -70,12 +70,6 @@
|
||||
<groupId>org.springframework.retry</groupId>
|
||||
<artifactId>spring-retry</artifactId>
|
||||
<optional>true</optional>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>javax.annotation</groupId>
|
||||
<artifactId>javax.annotation-api</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
@@ -139,16 +133,6 @@
|
||||
<groupId>org.springframework.security.oauth.boot</groupId>
|
||||
<artifactId>spring-security-oauth2-autoconfigure</artifactId>
|
||||
<optional>true</optional>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>javax.xml.bind</groupId>
|
||||
<artifactId>jaxb-api</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>javax.activation</groupId>
|
||||
<artifactId>javax.activation-api</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
@@ -165,6 +149,11 @@
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.vintage</groupId>
|
||||
<artifactId>junit-vintage-engine</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-test-support</artifactId>
|
||||
@@ -194,7 +183,7 @@
|
||||
<dependency>
|
||||
<groupId>com.google.protobuf</groupId>
|
||||
<artifactId>protobuf-java</artifactId>
|
||||
<version>3.19.3</version>
|
||||
<version>3.19.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
|
||||
-42
@@ -1,42 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2022 the original author 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 feign.Capability;
|
||||
import feign.InvocationHandlerFactory;
|
||||
|
||||
import org.springframework.cache.interceptor.CacheInterceptor;
|
||||
|
||||
/**
|
||||
* Allows Spring's @Cache* annotations to be declared on the feign client's methods.
|
||||
*
|
||||
* @author Sam Kruglov
|
||||
*/
|
||||
public class CachingCapability implements Capability {
|
||||
|
||||
private final CacheInterceptor cacheInterceptor;
|
||||
|
||||
public CachingCapability(CacheInterceptor cacheInterceptor) {
|
||||
this.cacheInterceptor = cacheInterceptor;
|
||||
}
|
||||
|
||||
@Override
|
||||
public InvocationHandlerFactory enrich(InvocationHandlerFactory invocationHandlerFactory) {
|
||||
return new FeignCachingInvocationHandlerFactory(invocationHandlerFactory, cacheInterceptor);
|
||||
}
|
||||
|
||||
}
|
||||
+1
-2
@@ -25,10 +25,9 @@ import java.lang.annotation.Target;
|
||||
* Indicates which collection format should be used while processing the annotated method.
|
||||
*
|
||||
* @author Olga Maciaszek-Sharma
|
||||
* @author Sam Kruglov
|
||||
* @see feign.CollectionFormat
|
||||
*/
|
||||
@Target({ ElementType.METHOD, ElementType.TYPE })
|
||||
@Target(ElementType.METHOD)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface CollectionFormat {
|
||||
|
||||
|
||||
+11
-62
@@ -18,7 +18,6 @@ package org.springframework.cloud.openfeign;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Timer;
|
||||
@@ -28,7 +27,6 @@ import java.util.concurrent.TimeUnit;
|
||||
import javax.annotation.PreDestroy;
|
||||
|
||||
import com.fasterxml.jackson.databind.Module;
|
||||
import feign.Capability;
|
||||
import feign.Client;
|
||||
import feign.Feign;
|
||||
import feign.RequestInterceptor;
|
||||
@@ -52,18 +50,15 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.cache.interceptor.CacheInterceptor;
|
||||
import org.springframework.cloud.client.actuator.HasFeatures;
|
||||
import org.springframework.cloud.client.circuitbreaker.CircuitBreaker;
|
||||
import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory;
|
||||
import org.springframework.cloud.client.loadbalancer.LoadBalancerInterceptor;
|
||||
import org.springframework.cloud.client.loadbalancer.RetryLoadBalancerInterceptor;
|
||||
import org.springframework.cloud.commons.httpclient.ApacheHttpClientConnectionManagerFactory;
|
||||
import org.springframework.cloud.commons.httpclient.ApacheHttpClientFactory;
|
||||
import org.springframework.cloud.commons.httpclient.OkHttpClientConnectionPoolFactory;
|
||||
import org.springframework.cloud.commons.httpclient.OkHttpClientFactory;
|
||||
import org.springframework.cloud.openfeign.security.OAuth2FeignRequestInterceptor;
|
||||
import org.springframework.cloud.openfeign.security.OAuth2FeignRequestInterceptorConfigurer;
|
||||
import org.springframework.cloud.openfeign.support.DefaultGzipDecoderConfiguration;
|
||||
import org.springframework.cloud.openfeign.support.FeignEncoderProperties;
|
||||
import org.springframework.cloud.openfeign.support.FeignHttpClientProperties;
|
||||
import org.springframework.cloud.openfeign.support.PageJacksonModule;
|
||||
@@ -77,8 +72,6 @@ import org.springframework.data.domain.Sort;
|
||||
import org.springframework.security.oauth2.client.OAuth2ClientContext;
|
||||
import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails;
|
||||
|
||||
import static org.springframework.cloud.openfeign.security.OAuth2FeignRequestInterceptorBuilder.buildWithConfigurers;
|
||||
|
||||
/**
|
||||
* @author Spencer Gibb
|
||||
* @author Julien Roy
|
||||
@@ -89,13 +82,12 @@ import static org.springframework.cloud.openfeign.security.OAuth2FeignRequestInt
|
||||
* @author Nguyen Ky Thanh
|
||||
* @author Andrii Bohutskyi
|
||||
* @author Kwangyong Kim
|
||||
* @author Sam Kruglov
|
||||
* @author Wojciech Mąka
|
||||
*/
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@ConditionalOnClass(Feign.class)
|
||||
@EnableConfigurationProperties({ FeignClientProperties.class, FeignHttpClientProperties.class,
|
||||
FeignEncoderProperties.class })
|
||||
@Import(DefaultGzipDecoderConfiguration.class)
|
||||
public class FeignAutoConfiguration {
|
||||
|
||||
private static final Log LOG = LogFactory.getLog(FeignAutoConfiguration.class);
|
||||
@@ -115,13 +107,6 @@ public class FeignAutoConfiguration {
|
||||
return context;
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnProperty(value = "feign.cache.enabled", matchIfMissing = true)
|
||||
@ConditionalOnBean(CacheInterceptor.class)
|
||||
public Capability cachingCapability(CacheInterceptor cacheInterceptor) {
|
||||
return new CachingCapability(cacheInterceptor);
|
||||
}
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@ConditionalOnClass({ Module.class, Page.class, Sort.class })
|
||||
@ConditionalOnProperty(value = "feign.autoconfiguration.jackson.enabled", havingValue = "true")
|
||||
@@ -166,19 +151,10 @@ public class FeignAutoConfiguration {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean(CircuitBreakerNameResolver.class)
|
||||
@ConditionalOnProperty(value = "feign.circuitbreaker.alphanumeric-ids.enabled", havingValue = "false",
|
||||
matchIfMissing = true)
|
||||
public CircuitBreakerNameResolver circuitBreakerNameResolver() {
|
||||
return new DefaultCircuitBreakerNameResolver();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean(CircuitBreakerNameResolver.class)
|
||||
@ConditionalOnProperty(value = "feign.circuitbreaker.alphanumeric-ids.enabled", havingValue = "true")
|
||||
public CircuitBreakerNameResolver alphanumericCircuitBreakerNameResolver() {
|
||||
return new AlphanumericCircuitBreakerNameResolver();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
@ConditionalOnBean(CircuitBreakerFactory.class)
|
||||
@@ -198,15 +174,6 @@ public class FeignAutoConfiguration {
|
||||
|
||||
}
|
||||
|
||||
static class AlphanumericCircuitBreakerNameResolver extends DefaultCircuitBreakerNameResolver {
|
||||
|
||||
@Override
|
||||
public String resolveCircuitBreakerName(String feignClientName, Target<?> target, Method method) {
|
||||
return super.resolveCircuitBreakerName(feignClientName, target, method).replaceAll("[^a-zA-Z0-9]", "");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// the following configuration is for alternate feign clients if
|
||||
@@ -293,8 +260,8 @@ public class FeignAutoConfiguration {
|
||||
@ConditionalOnMissingBean(ConnectionPool.class)
|
||||
public ConnectionPool httpClientConnectionPool(FeignHttpClientProperties httpClientProperties,
|
||||
OkHttpClientConnectionPoolFactory connectionPoolFactory) {
|
||||
int maxTotalConnections = httpClientProperties.getMaxConnections();
|
||||
long timeToLive = httpClientProperties.getTimeToLive();
|
||||
Integer maxTotalConnections = httpClientProperties.getMaxConnections();
|
||||
Long timeToLive = httpClientProperties.getTimeToLive();
|
||||
TimeUnit ttlUnit = httpClientProperties.getTimeToLiveUnit();
|
||||
return connectionPoolFactory.create(maxTotalConnections, timeToLive, ttlUnit);
|
||||
}
|
||||
@@ -302,13 +269,12 @@ public class FeignAutoConfiguration {
|
||||
@Bean
|
||||
public okhttp3.OkHttpClient client(OkHttpClientFactory httpClientFactory, ConnectionPool connectionPool,
|
||||
FeignHttpClientProperties httpClientProperties) {
|
||||
boolean followRedirects = httpClientProperties.isFollowRedirects();
|
||||
int connectTimeout = httpClientProperties.getConnectionTimeout();
|
||||
boolean disableSslValidation = httpClientProperties.isDisableSslValidation();
|
||||
Duration readTimeout = httpClientProperties.getOkHttp().getReadTimeout();
|
||||
Boolean followRedirects = httpClientProperties.isFollowRedirects();
|
||||
Integer connectTimeout = httpClientProperties.getConnectionTimeout();
|
||||
Boolean disableSslValidation = httpClientProperties.isDisableSslValidation();
|
||||
this.okHttpClient = httpClientFactory.createBuilder(disableSslValidation)
|
||||
.connectTimeout(connectTimeout, TimeUnit.MILLISECONDS).followRedirects(followRedirects)
|
||||
.readTimeout(readTimeout).connectionPool(connectionPool).build();
|
||||
.connectionPool(connectionPool).build();
|
||||
return this.okHttpClient;
|
||||
}
|
||||
|
||||
@@ -346,32 +312,15 @@ public class FeignAutoConfiguration {
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@ConditionalOnClass(OAuth2ClientContext.class)
|
||||
@ConditionalOnProperty("feign.oauth2.enabled")
|
||||
@Deprecated // spring-security-oauth2 reached EOL
|
||||
protected static class Oauth2FeignConfiguration {
|
||||
|
||||
@ConditionalOnBean({ RetryLoadBalancerInterceptor.class, OAuth2ClientContext.class,
|
||||
OAuth2ProtectedResourceDetails.class })
|
||||
@ConditionalOnProperty(value = "feign.oauth2.load-balanced", havingValue = "true")
|
||||
@Bean
|
||||
public OAuth2FeignRequestInterceptorConfigurer retryLoadBalancerInterceptorInjectingConfigurer(
|
||||
final RetryLoadBalancerInterceptor loadBalancerInterceptor) {
|
||||
return builder -> builder.withAccessTokenProviderInterceptors(loadBalancerInterceptor);
|
||||
}
|
||||
|
||||
@ConditionalOnBean({ LoadBalancerInterceptor.class, OAuth2ClientContext.class,
|
||||
OAuth2ProtectedResourceDetails.class })
|
||||
@ConditionalOnProperty(value = "feign.oauth2.load-balanced", havingValue = "true")
|
||||
@Bean
|
||||
public OAuth2FeignRequestInterceptorConfigurer loadBalancerInterceptorInjectingConfigurer(
|
||||
final LoadBalancerInterceptor loadBalancerInterceptor) {
|
||||
return builder -> builder.withAccessTokenProviderInterceptors(loadBalancerInterceptor);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean(OAuth2FeignRequestInterceptor.class)
|
||||
@ConditionalOnBean({ OAuth2ClientContext.class, OAuth2ProtectedResourceDetails.class })
|
||||
public RequestInterceptor oauth2FeignRequestInterceptor(OAuth2ClientContext oAuth2ClientContext,
|
||||
OAuth2ProtectedResourceDetails resource, List<OAuth2FeignRequestInterceptorConfigurer> configurers) {
|
||||
return buildWithConfigurers(oAuth2ClientContext, resource, configurers);
|
||||
OAuth2ProtectedResourceDetails resource) {
|
||||
return new OAuth2FeignRequestInterceptor(oAuth2ClientContext, resource);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
-82
@@ -1,82 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2022 the original author 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.reflect.AccessibleObject;
|
||||
import java.lang.reflect.InvocationHandler;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import feign.InvocationHandlerFactory;
|
||||
import feign.Target;
|
||||
import org.aopalliance.intercept.MethodInvocation;
|
||||
|
||||
import org.springframework.cache.interceptor.CacheInterceptor;
|
||||
|
||||
/**
|
||||
* Allows Spring's @Cache* annotations to be declared on the feign client's methods.
|
||||
*
|
||||
* @author Sam Kruglov
|
||||
*/
|
||||
public class FeignCachingInvocationHandlerFactory implements InvocationHandlerFactory {
|
||||
|
||||
private final InvocationHandlerFactory delegateFactory;
|
||||
|
||||
private final CacheInterceptor cacheInterceptor;
|
||||
|
||||
public FeignCachingInvocationHandlerFactory(InvocationHandlerFactory delegateFactory,
|
||||
CacheInterceptor cacheInterceptor) {
|
||||
this.delegateFactory = delegateFactory;
|
||||
this.cacheInterceptor = cacheInterceptor;
|
||||
}
|
||||
|
||||
@Override
|
||||
public InvocationHandler create(Target target, Map<Method, MethodHandler> dispatch) {
|
||||
final InvocationHandler delegateHandler = delegateFactory.create(target, dispatch);
|
||||
return (proxy, method, argsNullable) -> {
|
||||
Object[] args = Optional.ofNullable(argsNullable).orElseGet(() -> new Object[0]);
|
||||
return cacheInterceptor.invoke(new MethodInvocation() {
|
||||
@Override
|
||||
public Method getMethod() {
|
||||
return method;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object[] getArguments() {
|
||||
return args;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object proceed() throws Throwable {
|
||||
return delegateHandler.invoke(proxy, method, args);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getThis() {
|
||||
return target;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AccessibleObject getStaticPart() {
|
||||
return method;
|
||||
}
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
+1
-10
@@ -68,8 +68,6 @@ import org.springframework.util.StringUtils;
|
||||
* @author Jonatan Ivanov
|
||||
* @author Sam Kruglov
|
||||
* @author Jasbir Singh
|
||||
* @author Hyeonmin Park
|
||||
* @author Felix Dittrich
|
||||
*/
|
||||
public class FeignClientFactoryBean
|
||||
implements FactoryBean<Object>, InitializingBean, ApplicationContextAware, BeanFactoryAware {
|
||||
@@ -133,6 +131,7 @@ public class FeignClientFactoryBean
|
||||
// @formatter:on
|
||||
|
||||
configureFeign(context, builder);
|
||||
applyBuildCustomizers(context, builder);
|
||||
|
||||
return builder;
|
||||
}
|
||||
@@ -296,10 +295,6 @@ public class FeignClientFactoryBean
|
||||
if (config.getCapabilities() != null) {
|
||||
config.getCapabilities().stream().map(this::getOrInstantiate).forEach(builder::addCapability);
|
||||
}
|
||||
|
||||
if (config.getQueryMapEncoder() != null) {
|
||||
builder.queryMapEncoder(getOrInstantiate(config.getQueryMapEncoder()));
|
||||
}
|
||||
}
|
||||
|
||||
private void addDefaultQueryParams(FeignClientProperties.FeignClientConfiguration config, Feign.Builder builder) {
|
||||
@@ -374,7 +369,6 @@ public class FeignClientFactoryBean
|
||||
Client client = getOptional(context, Client.class);
|
||||
if (client != null) {
|
||||
builder.client(client);
|
||||
applyBuildCustomizers(context, builder);
|
||||
Targeter targeter = get(context, Targeter.class);
|
||||
return targeter.target(this, builder, context, target);
|
||||
}
|
||||
@@ -444,9 +438,6 @@ public class FeignClientFactoryBean
|
||||
}
|
||||
builder.client(client);
|
||||
}
|
||||
|
||||
applyBuildCustomizers(context, builder);
|
||||
|
||||
Targeter targeter = get(context, Targeter.class);
|
||||
return (T) targeter.target(this, builder, context, new HardCodedTarget<>(type, name, url));
|
||||
}
|
||||
|
||||
+2
-15
@@ -26,7 +26,6 @@ import feign.Capability;
|
||||
import feign.Contract;
|
||||
import feign.ExceptionPropagationPolicy;
|
||||
import feign.Logger;
|
||||
import feign.QueryMapEncoder;
|
||||
import feign.RequestInterceptor;
|
||||
import feign.Retryer;
|
||||
import feign.codec.Decoder;
|
||||
@@ -41,7 +40,6 @@ import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
* @author Ram Anaswara
|
||||
* @author Jonatan Ivanov
|
||||
* @author Olga Maciaszek-Sharma
|
||||
* @author Hyeonmin Park
|
||||
*/
|
||||
@ConfigurationProperties("feign.client")
|
||||
public class FeignClientProperties {
|
||||
@@ -141,8 +139,6 @@ public class FeignClientProperties {
|
||||
|
||||
private List<Class<Capability>> capabilities;
|
||||
|
||||
private Class<QueryMapEncoder> queryMapEncoder;
|
||||
|
||||
private MetricsProperties metrics;
|
||||
|
||||
private Boolean followRedirects;
|
||||
@@ -259,14 +255,6 @@ public class FeignClientProperties {
|
||||
this.capabilities = capabilities;
|
||||
}
|
||||
|
||||
public Class<QueryMapEncoder> getQueryMapEncoder() {
|
||||
return queryMapEncoder;
|
||||
}
|
||||
|
||||
public void setQueryMapEncoder(Class<QueryMapEncoder> queryMapEncoder) {
|
||||
this.queryMapEncoder = queryMapEncoder;
|
||||
}
|
||||
|
||||
public MetricsProperties getMetrics() {
|
||||
return metrics;
|
||||
}
|
||||
@@ -301,8 +289,7 @@ public class FeignClientProperties {
|
||||
&& Objects.equals(exceptionPropagationPolicy, that.exceptionPropagationPolicy)
|
||||
&& Objects.equals(defaultRequestHeaders, that.defaultRequestHeaders)
|
||||
&& Objects.equals(defaultQueryParameters, that.defaultQueryParameters)
|
||||
&& Objects.equals(capabilities, that.capabilities)
|
||||
&& Objects.equals(queryMapEncoder, that.queryMapEncoder) && Objects.equals(metrics, that.metrics)
|
||||
&& Objects.equals(capabilities, that.capabilities) && Objects.equals(metrics, that.metrics)
|
||||
&& Objects.equals(followRedirects, that.followRedirects);
|
||||
}
|
||||
|
||||
@@ -310,7 +297,7 @@ public class FeignClientProperties {
|
||||
public int hashCode() {
|
||||
return Objects.hash(loggerLevel, connectTimeout, readTimeout, retryer, errorDecoder, requestInterceptors,
|
||||
decode404, encoder, decoder, contract, exceptionPropagationPolicy, defaultQueryParameters,
|
||||
defaultRequestHeaders, capabilities, queryMapEncoder, metrics, followRedirects);
|
||||
defaultRequestHeaders, capabilities, metrics, followRedirects);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+2
-2
@@ -25,7 +25,7 @@ import org.springframework.cloud.context.named.NamedContextFactory;
|
||||
* @author Dave Syer
|
||||
* @author Gregor Zurowski
|
||||
*/
|
||||
public class FeignClientSpecification implements NamedContextFactory.Specification {
|
||||
class FeignClientSpecification implements NamedContextFactory.Specification {
|
||||
|
||||
private String name;
|
||||
|
||||
@@ -34,7 +34,7 @@ public class FeignClientSpecification implements NamedContextFactory.Specificati
|
||||
FeignClientSpecification() {
|
||||
}
|
||||
|
||||
public FeignClientSpecification(String name, Class<?>[] configuration) {
|
||||
FeignClientSpecification(String name, Class<?>[] configuration) {
|
||||
this.name = name;
|
||||
this.configuration = configuration;
|
||||
}
|
||||
|
||||
+13
-25
@@ -47,7 +47,6 @@ import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory;
|
||||
import org.springframework.cloud.openfeign.clientconfig.FeignClientConfigurer;
|
||||
import org.springframework.cloud.openfeign.support.AbstractFormWriter;
|
||||
import org.springframework.cloud.openfeign.support.FeignEncoderProperties;
|
||||
import org.springframework.cloud.openfeign.support.HttpMessageConverterCustomizer;
|
||||
import org.springframework.cloud.openfeign.support.PageableSpringEncoder;
|
||||
import org.springframework.cloud.openfeign.support.PageableSpringQueryMapEncoder;
|
||||
import org.springframework.cloud.openfeign.support.ResponseEntityDecoder;
|
||||
@@ -71,7 +70,6 @@ import static feign.form.ContentType.MULTIPART;
|
||||
* @author Jonatan Ivanov
|
||||
* @author Olga Maciaszek-Sharma
|
||||
* @author Hyeonmin Park
|
||||
* @author Yanming Zhou
|
||||
*/
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
public class FeignClientsConfiguration {
|
||||
@@ -99,25 +97,22 @@ public class FeignClientsConfiguration {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public Decoder feignDecoder(ObjectProvider<HttpMessageConverterCustomizer> customizers) {
|
||||
return new OptionalDecoder(new ResponseEntityDecoder(new SpringDecoder(messageConverters, customizers)));
|
||||
public Decoder feignDecoder() {
|
||||
return new OptionalDecoder(new ResponseEntityDecoder(new SpringDecoder(this.messageConverters)));
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
@ConditionalOnMissingClass("org.springframework.data.domain.Pageable")
|
||||
public Encoder feignEncoder(ObjectProvider<AbstractFormWriter> formWriterProvider,
|
||||
ObjectProvider<HttpMessageConverterCustomizer> customizers) {
|
||||
return springEncoder(formWriterProvider, encoderProperties, customizers);
|
||||
public Encoder feignEncoder(ObjectProvider<AbstractFormWriter> formWriterProvider) {
|
||||
return springEncoder(formWriterProvider, encoderProperties);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnClass(name = "org.springframework.data.domain.Pageable")
|
||||
@ConditionalOnMissingBean
|
||||
public Encoder feignEncoderPageable(ObjectProvider<AbstractFormWriter> formWriterProvider,
|
||||
ObjectProvider<HttpMessageConverterCustomizer> customizers) {
|
||||
PageableSpringEncoder encoder = new PageableSpringEncoder(
|
||||
springEncoder(formWriterProvider, encoderProperties, customizers));
|
||||
public Encoder feignEncoderPageable(ObjectProvider<AbstractFormWriter> formWriterProvider) {
|
||||
PageableSpringEncoder encoder = new PageableSpringEncoder(springEncoder(formWriterProvider, encoderProperties));
|
||||
|
||||
if (springDataWebProperties != null) {
|
||||
encoder.setPageParameter(springDataWebProperties.getPageable().getPageParameter());
|
||||
@@ -131,26 +126,20 @@ public class FeignClientsConfiguration {
|
||||
@ConditionalOnClass(name = "org.springframework.data.domain.Pageable")
|
||||
@ConditionalOnMissingBean
|
||||
public QueryMapEncoder feignQueryMapEncoderPageable() {
|
||||
PageableSpringQueryMapEncoder queryMapEncoder = new PageableSpringQueryMapEncoder();
|
||||
if (springDataWebProperties != null) {
|
||||
queryMapEncoder.setPageParameter(springDataWebProperties.getPageable().getPageParameter());
|
||||
queryMapEncoder.setSizeParameter(springDataWebProperties.getPageable().getSizeParameter());
|
||||
queryMapEncoder.setSortParameter(springDataWebProperties.getSort().getSortParameter());
|
||||
}
|
||||
return queryMapEncoder;
|
||||
return new PageableSpringQueryMapEncoder();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public Contract feignContract(ConversionService feignConversionService) {
|
||||
boolean decodeSlash = feignClientProperties == null || feignClientProperties.isDecodeSlash();
|
||||
return new SpringMvcContract(parameterProcessors, feignConversionService, decodeSlash);
|
||||
return new SpringMvcContract(this.parameterProcessors, feignConversionService, decodeSlash);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public FormattingConversionService feignConversionService() {
|
||||
FormattingConversionService conversionService = new DefaultFormattingConversionService();
|
||||
for (FeignFormatterRegistrar feignFormatterRegistrar : feignFormatterRegistrars) {
|
||||
for (FeignFormatterRegistrar feignFormatterRegistrar : this.feignFormatterRegistrars) {
|
||||
feignFormatterRegistrar.registerFormatters(conversionService);
|
||||
}
|
||||
return conversionService;
|
||||
@@ -165,7 +154,7 @@ public class FeignClientsConfiguration {
|
||||
@Bean
|
||||
@ConditionalOnMissingBean(FeignLoggerFactory.class)
|
||||
public FeignLoggerFactory feignLoggerFactory() {
|
||||
return new DefaultFeignLoggerFactory(logger);
|
||||
return new DefaultFeignLoggerFactory(this.logger);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@@ -176,15 +165,14 @@ public class FeignClientsConfiguration {
|
||||
}
|
||||
|
||||
private Encoder springEncoder(ObjectProvider<AbstractFormWriter> formWriterProvider,
|
||||
FeignEncoderProperties encoderProperties, ObjectProvider<HttpMessageConverterCustomizer> customizers) {
|
||||
FeignEncoderProperties encoderProperties) {
|
||||
AbstractFormWriter formWriter = formWriterProvider.getIfAvailable();
|
||||
|
||||
if (formWriter != null) {
|
||||
return new SpringEncoder(new SpringPojoFormEncoder(formWriter), messageConverters, encoderProperties,
|
||||
customizers);
|
||||
return new SpringEncoder(new SpringPojoFormEncoder(formWriter), this.messageConverters, encoderProperties);
|
||||
}
|
||||
else {
|
||||
return new SpringEncoder(new SpringFormEncoder(), messageConverters, encoderProperties, customizers);
|
||||
return new SpringEncoder(new SpringFormEncoder(), this.messageConverters, encoderProperties);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
-67
@@ -1,67 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2022 the original author 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.annotation;
|
||||
|
||||
import java.lang.annotation.Annotation;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Arrays;
|
||||
|
||||
import feign.MethodMetadata;
|
||||
|
||||
import org.springframework.cloud.openfeign.AnnotatedParameterProcessor;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.web.bind.annotation.CookieValue;
|
||||
|
||||
import static feign.Util.checkState;
|
||||
import static feign.Util.emptyToNull;
|
||||
|
||||
/**
|
||||
* @{link CookieValue} annotation processor.
|
||||
* @author Gong Yi
|
||||
*
|
||||
*/
|
||||
public class CookieValueParameterProcessor implements AnnotatedParameterProcessor {
|
||||
|
||||
private static final Class<CookieValue> ANNOTATION = CookieValue.class;
|
||||
|
||||
@Override
|
||||
public Class<? extends Annotation> getAnnotationType() {
|
||||
return ANNOTATION;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean processArgument(AnnotatedParameterContext context, Annotation annotation, Method method) {
|
||||
int parameterIndex = context.getParameterIndex();
|
||||
MethodMetadata data = context.getMethodMetadata();
|
||||
CookieValue cookie = ANNOTATION.cast(annotation);
|
||||
String name = cookie.value().trim();
|
||||
checkState(emptyToNull(name) != null, "Cookie.name() was empty on parameter %s", parameterIndex);
|
||||
context.setParameterName(name);
|
||||
String cookieExpression = data.template().headers().getOrDefault(HttpHeaders.COOKIE, Arrays.asList("")).stream()
|
||||
.findFirst().orElse("");
|
||||
if (cookieExpression.length() == 0) {
|
||||
cookieExpression = String.format("%s={%s}", name, name);
|
||||
}
|
||||
else {
|
||||
cookieExpression += String.format("; %s={%s}", name, name);
|
||||
}
|
||||
data.template().removeHeader(HttpHeaders.COOKIE);
|
||||
data.template().header(HttpHeaders.COOKIE, cookieExpression);
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
+1
-3
@@ -34,7 +34,6 @@ import static feign.Util.emptyToNull;
|
||||
*
|
||||
* @author Jakub Narloch
|
||||
* @author Abhijit Sarkar
|
||||
* @author Yanming Zhou
|
||||
* @see AnnotatedParameterProcessor
|
||||
*/
|
||||
public class PathVariableParameterProcessor implements AnnotatedParameterProcessor {
|
||||
@@ -55,8 +54,7 @@ public class PathVariableParameterProcessor implements AnnotatedParameterProcess
|
||||
|
||||
MethodMetadata data = context.getMethodMetadata();
|
||||
String varName = '{' + name + '}';
|
||||
String varNameRegex = ".*\\{" + name + "(:[^}]+)?\\}.*";
|
||||
if (!data.template().url().matches(varNameRegex) && !searchMapValues(data.template().queries(), varName)
|
||||
if (!data.template().url().contains(varName) && !searchMapValues(data.template().queries(), varName)
|
||||
&& !searchMapValues(data.template().headers(), varName)) {
|
||||
data.formParams().add(name);
|
||||
}
|
||||
|
||||
+5
-7
@@ -16,7 +16,6 @@
|
||||
|
||||
package org.springframework.cloud.openfeign.clientconfig;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import javax.annotation.PreDestroy;
|
||||
@@ -49,8 +48,8 @@ public class OkHttpFeignConfiguration {
|
||||
@ConditionalOnMissingBean(ConnectionPool.class)
|
||||
public ConnectionPool httpClientConnectionPool(FeignHttpClientProperties httpClientProperties,
|
||||
OkHttpClientConnectionPoolFactory connectionPoolFactory) {
|
||||
int maxTotalConnections = httpClientProperties.getMaxConnections();
|
||||
long timeToLive = httpClientProperties.getTimeToLive();
|
||||
Integer maxTotalConnections = httpClientProperties.getMaxConnections();
|
||||
Long timeToLive = httpClientProperties.getTimeToLive();
|
||||
TimeUnit ttlUnit = httpClientProperties.getTimeToLiveUnit();
|
||||
return connectionPoolFactory.create(maxTotalConnections, timeToLive, ttlUnit);
|
||||
}
|
||||
@@ -58,12 +57,11 @@ public class OkHttpFeignConfiguration {
|
||||
@Bean
|
||||
public okhttp3.OkHttpClient client(OkHttpClientFactory httpClientFactory, ConnectionPool connectionPool,
|
||||
FeignHttpClientProperties httpClientProperties) {
|
||||
boolean followRedirects = httpClientProperties.isFollowRedirects();
|
||||
int connectTimeout = httpClientProperties.getConnectionTimeout();
|
||||
Duration reaTimeout = httpClientProperties.getOkHttp().getReadTimeout();
|
||||
Boolean followRedirects = httpClientProperties.isFollowRedirects();
|
||||
Integer connectTimeout = httpClientProperties.getConnectionTimeout();
|
||||
this.okHttpClient = httpClientFactory.createBuilder(httpClientProperties.isDisableSslValidation())
|
||||
.connectTimeout(connectTimeout, TimeUnit.MILLISECONDS).followRedirects(followRedirects)
|
||||
.readTimeout(reaTimeout).connectionPool(connectionPool).build();
|
||||
.connectionPool(connectionPool).build();
|
||||
return this.okHttpClient;
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -83,7 +83,7 @@ public class FeignContentGzipEncodingInterceptor extends BaseRequestInterceptor
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether the content mime types matches the configured mime types.
|
||||
* Returns whether the content mime types matches the configures mime types.
|
||||
* @param contentTypes the content types
|
||||
* @return true if any specified content type matches the request content types
|
||||
*/
|
||||
|
||||
+24
-8
@@ -16,18 +16,26 @@
|
||||
|
||||
package org.springframework.cloud.openfeign.hateoas;
|
||||
|
||||
import java.util.Collections;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
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.ConditionalOnWebApplication;
|
||||
import org.springframework.boot.autoconfigure.data.rest.RepositoryRestMvcAutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration;
|
||||
import org.springframework.cloud.openfeign.support.HttpMessageConverterCustomizer;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.hateoas.config.HateoasConfiguration;
|
||||
import org.springframework.hateoas.config.WebConverters;
|
||||
import org.springframework.hateoas.RepresentationModel;
|
||||
import org.springframework.hateoas.mediatype.hal.HalMediaTypeConfiguration;
|
||||
import org.springframework.hateoas.server.mvc.TypeConstrainedMappingJackson2HttpMessageConverter;
|
||||
|
||||
import static org.springframework.hateoas.MediaTypes.HAL_JSON;
|
||||
|
||||
/**
|
||||
* @author Hector Espert
|
||||
@@ -35,15 +43,23 @@ import org.springframework.hateoas.config.WebConverters;
|
||||
*/
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@ConditionalOnWebApplication
|
||||
@ConditionalOnClass(WebConverters.class)
|
||||
@ConditionalOnClass(RepresentationModel.class)
|
||||
@AutoConfigureAfter({ JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class,
|
||||
RepositoryRestMvcAutoConfiguration.class, HateoasConfiguration.class })
|
||||
RepositoryRestMvcAutoConfiguration.class })
|
||||
public class FeignHalAutoConfiguration {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnBean(WebConverters.class)
|
||||
HttpMessageConverterCustomizer webConvertersCustomizer(WebConverters webConverters) {
|
||||
return new WebConvertersCustomizer(webConverters);
|
||||
@ConditionalOnBean(HalMediaTypeConfiguration.class)
|
||||
@ConditionalOnMissingBean
|
||||
public TypeConstrainedMappingJackson2HttpMessageConverter halJacksonHttpMessageConverter(
|
||||
ObjectProvider<ObjectMapper> objectMapper, HalMediaTypeConfiguration halConfiguration) {
|
||||
ObjectMapper mapper = objectMapper.getIfAvailable(ObjectMapper::new).copy();
|
||||
halConfiguration.configureObjectMapper(mapper);
|
||||
TypeConstrainedMappingJackson2HttpMessageConverter converter = new TypeConstrainedMappingJackson2HttpMessageConverter(
|
||||
RepresentationModel.class);
|
||||
converter.setSupportedMediaTypes(Collections.singletonList(HAL_JSON));
|
||||
converter.setObjectMapper(mapper);
|
||||
return converter;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
-41
@@ -1,41 +0,0 @@
|
||||
/*
|
||||
* Copyright 2016-2021 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.cloud.openfeign.hateoas;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.cloud.openfeign.support.HttpMessageConverterCustomizer;
|
||||
import org.springframework.hateoas.config.WebConverters;
|
||||
import org.springframework.http.converter.HttpMessageConverter;
|
||||
|
||||
/**
|
||||
* @author Olga Maciaszek-Sharma
|
||||
*/
|
||||
public class WebConvertersCustomizer implements HttpMessageConverterCustomizer {
|
||||
|
||||
private final WebConverters webConverters;
|
||||
|
||||
public WebConvertersCustomizer(WebConverters webConverters) {
|
||||
this.webConverters = webConverters;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void accept(List<HttpMessageConverter<?>> httpMessageConverters) {
|
||||
webConverters.augmentClient(httpMessageConverters);
|
||||
}
|
||||
|
||||
}
|
||||
+7
-6
@@ -25,7 +25,7 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory;
|
||||
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
|
||||
import org.springframework.cloud.client.loadbalancer.LoadBalancerClientsProperties;
|
||||
import org.springframework.cloud.client.loadbalancer.LoadBalancerProperties;
|
||||
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Conditional;
|
||||
@@ -39,15 +39,15 @@ import org.springframework.context.annotation.Configuration;
|
||||
* @since 2.2.0
|
||||
*/
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@EnableConfigurationProperties(LoadBalancerClientsProperties.class)
|
||||
@EnableConfigurationProperties(LoadBalancerProperties.class)
|
||||
class DefaultFeignLoadBalancerConfiguration {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
@Conditional(OnRetryNotEnabledCondition.class)
|
||||
public Client feignClient(LoadBalancerClient loadBalancerClient,
|
||||
public Client feignClient(LoadBalancerClient loadBalancerClient, LoadBalancerProperties properties,
|
||||
LoadBalancerClientFactory loadBalancerClientFactory) {
|
||||
return new FeignBlockingLoadBalancerClient(new Client.Default(null, null), loadBalancerClient,
|
||||
return new FeignBlockingLoadBalancerClient(new Client.Default(null, null), loadBalancerClient, properties,
|
||||
loadBalancerClientFactory);
|
||||
}
|
||||
|
||||
@@ -58,9 +58,10 @@ class DefaultFeignLoadBalancerConfiguration {
|
||||
@ConditionalOnProperty(value = "spring.cloud.loadbalancer.retry.enabled", havingValue = "true",
|
||||
matchIfMissing = true)
|
||||
public Client feignRetryClient(LoadBalancerClient loadBalancerClient,
|
||||
LoadBalancedRetryFactory loadBalancedRetryFactory, LoadBalancerClientFactory loadBalancerClientFactory) {
|
||||
LoadBalancedRetryFactory loadBalancedRetryFactory, LoadBalancerProperties properties,
|
||||
LoadBalancerClientFactory loadBalancerClientFactory) {
|
||||
return new RetryableFeignBlockingLoadBalancerClient(new Client.Default(null, null), loadBalancerClient,
|
||||
loadBalancedRetryFactory, loadBalancerClientFactory);
|
||||
loadBalancedRetryFactory, properties, loadBalancerClientFactory);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+4
-15
@@ -60,24 +60,15 @@ public class FeignBlockingLoadBalancerClient implements Client {
|
||||
|
||||
private final LoadBalancerClient loadBalancerClient;
|
||||
|
||||
private final LoadBalancerProperties properties;
|
||||
|
||||
private final LoadBalancerClientFactory loadBalancerClientFactory;
|
||||
|
||||
/**
|
||||
* @deprecated in favour of
|
||||
* {@link FeignBlockingLoadBalancerClient#FeignBlockingLoadBalancerClient(Client, LoadBalancerClient, LoadBalancerClientFactory)}
|
||||
*/
|
||||
@Deprecated
|
||||
public FeignBlockingLoadBalancerClient(Client delegate, LoadBalancerClient loadBalancerClient,
|
||||
LoadBalancerProperties properties, LoadBalancerClientFactory loadBalancerClientFactory) {
|
||||
this.delegate = delegate;
|
||||
this.loadBalancerClient = loadBalancerClient;
|
||||
this.loadBalancerClientFactory = loadBalancerClientFactory;
|
||||
}
|
||||
|
||||
public FeignBlockingLoadBalancerClient(Client delegate, LoadBalancerClient loadBalancerClient,
|
||||
LoadBalancerClientFactory loadBalancerClientFactory) {
|
||||
this.delegate = delegate;
|
||||
this.loadBalancerClient = loadBalancerClient;
|
||||
this.properties = properties;
|
||||
this.loadBalancerClientFactory = loadBalancerClientFactory;
|
||||
}
|
||||
|
||||
@@ -110,9 +101,8 @@ public class FeignBlockingLoadBalancerClient implements Client {
|
||||
}
|
||||
String reconstructedUrl = loadBalancerClient.reconstructURI(instance, originalUri).toString();
|
||||
Request newRequest = buildRequest(request, reconstructedUrl);
|
||||
LoadBalancerProperties loadBalancerProperties = loadBalancerClientFactory.getProperties(serviceId);
|
||||
return executeWithLoadBalancerLifecycleProcessing(delegate, options, newRequest, lbRequest, lbResponse,
|
||||
supportedLifecycleProcessors, loadBalancerProperties.isUseRawStatusCodeInResponseData());
|
||||
supportedLifecycleProcessors);
|
||||
}
|
||||
|
||||
protected Request buildRequest(Request request, String reconstructedUrl) {
|
||||
@@ -126,7 +116,6 @@ public class FeignBlockingLoadBalancerClient implements Client {
|
||||
}
|
||||
|
||||
private String getHint(String serviceId) {
|
||||
LoadBalancerProperties properties = loadBalancerClientFactory.getProperties(serviceId);
|
||||
String defaultHint = properties.getHint().getOrDefault("default", "default");
|
||||
String hintPropertyValue = properties.getHint().get(serviceId);
|
||||
return hintPropertyValue != null ? hintPropertyValue : defaultHint;
|
||||
|
||||
+7
-6
@@ -27,7 +27,7 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory;
|
||||
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
|
||||
import org.springframework.cloud.client.loadbalancer.LoadBalancerClientsProperties;
|
||||
import org.springframework.cloud.client.loadbalancer.LoadBalancerProperties;
|
||||
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
|
||||
import org.springframework.cloud.openfeign.clientconfig.HttpClient5FeignConfiguration;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
@@ -46,16 +46,16 @@ import org.springframework.context.annotation.Import;
|
||||
@ConditionalOnBean({ LoadBalancerClient.class, LoadBalancerClientFactory.class })
|
||||
@ConditionalOnProperty(value = "feign.httpclient.hc5.enabled", havingValue = "true")
|
||||
@Import(HttpClient5FeignConfiguration.class)
|
||||
@EnableConfigurationProperties(LoadBalancerClientsProperties.class)
|
||||
@EnableConfigurationProperties(LoadBalancerProperties.class)
|
||||
class HttpClient5FeignLoadBalancerConfiguration {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
@Conditional(OnRetryNotEnabledCondition.class)
|
||||
public Client feignClient(LoadBalancerClient loadBalancerClient, HttpClient httpClient5,
|
||||
LoadBalancerClientFactory loadBalancerClientFactory) {
|
||||
LoadBalancerProperties properties, LoadBalancerClientFactory loadBalancerClientFactory) {
|
||||
Client delegate = new ApacheHttp5Client(httpClient5);
|
||||
return new FeignBlockingLoadBalancerClient(delegate, loadBalancerClient, loadBalancerClientFactory);
|
||||
return new FeignBlockingLoadBalancerClient(delegate, loadBalancerClient, properties, loadBalancerClientFactory);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@@ -65,10 +65,11 @@ class HttpClient5FeignLoadBalancerConfiguration {
|
||||
@ConditionalOnProperty(value = "spring.cloud.loadbalancer.retry.enabled", havingValue = "true",
|
||||
matchIfMissing = true)
|
||||
public Client feignRetryClient(LoadBalancerClient loadBalancerClient, HttpClient httpClient5,
|
||||
LoadBalancedRetryFactory loadBalancedRetryFactory, LoadBalancerClientFactory loadBalancerClientFactory) {
|
||||
LoadBalancedRetryFactory loadBalancedRetryFactory, LoadBalancerProperties properties,
|
||||
LoadBalancerClientFactory loadBalancerClientFactory) {
|
||||
Client delegate = new ApacheHttp5Client(httpClient5);
|
||||
return new RetryableFeignBlockingLoadBalancerClient(delegate, loadBalancerClient, loadBalancedRetryFactory,
|
||||
loadBalancerClientFactory);
|
||||
properties, loadBalancerClientFactory);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+7
-6
@@ -27,7 +27,7 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory;
|
||||
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
|
||||
import org.springframework.cloud.client.loadbalancer.LoadBalancerClientsProperties;
|
||||
import org.springframework.cloud.client.loadbalancer.LoadBalancerProperties;
|
||||
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
|
||||
import org.springframework.cloud.openfeign.HttpClient5DisabledConditions;
|
||||
import org.springframework.cloud.openfeign.clientconfig.HttpClientFeignConfiguration;
|
||||
@@ -50,16 +50,16 @@ import org.springframework.context.annotation.Import;
|
||||
@ConditionalOnProperty(value = "feign.httpclient.enabled", matchIfMissing = true)
|
||||
@Conditional(HttpClient5DisabledConditions.class)
|
||||
@Import(HttpClientFeignConfiguration.class)
|
||||
@EnableConfigurationProperties(LoadBalancerClientsProperties.class)
|
||||
@EnableConfigurationProperties(LoadBalancerProperties.class)
|
||||
class HttpClientFeignLoadBalancerConfiguration {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
@Conditional(OnRetryNotEnabledCondition.class)
|
||||
public Client feignClient(LoadBalancerClient loadBalancerClient, HttpClient httpClient,
|
||||
LoadBalancerClientFactory loadBalancerClientFactory) {
|
||||
LoadBalancerProperties properties, LoadBalancerClientFactory loadBalancerClientFactory) {
|
||||
ApacheHttpClient delegate = new ApacheHttpClient(httpClient);
|
||||
return new FeignBlockingLoadBalancerClient(delegate, loadBalancerClient, loadBalancerClientFactory);
|
||||
return new FeignBlockingLoadBalancerClient(delegate, loadBalancerClient, properties, loadBalancerClientFactory);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@@ -69,10 +69,11 @@ class HttpClientFeignLoadBalancerConfiguration {
|
||||
@ConditionalOnProperty(value = "spring.cloud.loadbalancer.retry.enabled", havingValue = "true",
|
||||
matchIfMissing = true)
|
||||
public Client feignRetryClient(LoadBalancerClient loadBalancerClient, HttpClient httpClient,
|
||||
LoadBalancedRetryFactory loadBalancedRetryFactory, LoadBalancerClientFactory loadBalancerClientFactory) {
|
||||
LoadBalancedRetryFactory loadBalancedRetryFactory, LoadBalancerProperties properties,
|
||||
LoadBalancerClientFactory loadBalancerClientFactory) {
|
||||
ApacheHttpClient delegate = new ApacheHttpClient(httpClient);
|
||||
return new RetryableFeignBlockingLoadBalancerClient(delegate, loadBalancerClient, loadBalancedRetryFactory,
|
||||
loadBalancerClientFactory);
|
||||
properties, loadBalancerClientFactory);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+5
-9
@@ -50,15 +50,14 @@ final class LoadBalancerUtils {
|
||||
static Response executeWithLoadBalancerLifecycleProcessing(Client feignClient, Request.Options options,
|
||||
Request feignRequest, org.springframework.cloud.client.loadbalancer.Request lbRequest,
|
||||
org.springframework.cloud.client.loadbalancer.Response<ServiceInstance> lbResponse,
|
||||
Set<LoadBalancerLifecycle> supportedLifecycleProcessors, boolean loadBalanced, boolean useRawStatusCodes)
|
||||
throws IOException {
|
||||
Set<LoadBalancerLifecycle> supportedLifecycleProcessors, boolean loadBalanced) throws IOException {
|
||||
supportedLifecycleProcessors.forEach(lifecycle -> lifecycle.onStartRequest(lbRequest, lbResponse));
|
||||
try {
|
||||
Response response = feignClient.execute(feignRequest, options);
|
||||
if (loadBalanced) {
|
||||
supportedLifecycleProcessors.forEach(
|
||||
lifecycle -> lifecycle.onComplete(new CompletionContext<>(CompletionContext.Status.SUCCESS,
|
||||
lbRequest, lbResponse, buildResponseData(response, useRawStatusCodes))));
|
||||
lbRequest, lbResponse, buildResponseData(response))));
|
||||
}
|
||||
return response;
|
||||
}
|
||||
@@ -71,12 +70,9 @@ final class LoadBalancerUtils {
|
||||
}
|
||||
}
|
||||
|
||||
static ResponseData buildResponseData(Response response, boolean useRawStatusCodes) {
|
||||
static ResponseData buildResponseData(Response response) {
|
||||
HttpHeaders responseHeaders = new HttpHeaders();
|
||||
response.headers().forEach((key, value) -> responseHeaders.put(key, new ArrayList<>(value)));
|
||||
if (useRawStatusCodes) {
|
||||
return new ResponseData(responseHeaders, null, buildRequestData(response.request()), response.status());
|
||||
}
|
||||
return new ResponseData(HttpStatus.resolve(response.status()), responseHeaders, null,
|
||||
buildRequestData(response.request()));
|
||||
}
|
||||
@@ -91,9 +87,9 @@ final class LoadBalancerUtils {
|
||||
static Response executeWithLoadBalancerLifecycleProcessing(Client feignClient, Request.Options options,
|
||||
Request feignRequest, org.springframework.cloud.client.loadbalancer.Request lbRequest,
|
||||
org.springframework.cloud.client.loadbalancer.Response<ServiceInstance> lbResponse,
|
||||
Set<LoadBalancerLifecycle> supportedLifecycleProcessors, boolean useRawStatusCodes) throws IOException {
|
||||
Set<LoadBalancerLifecycle> supportedLifecycleProcessors) throws IOException {
|
||||
return executeWithLoadBalancerLifecycleProcessing(feignClient, options, feignRequest, lbRequest, lbResponse,
|
||||
supportedLifecycleProcessors, true, useRawStatusCodes);
|
||||
supportedLifecycleProcessors, true);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+7
-6
@@ -26,7 +26,7 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory;
|
||||
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
|
||||
import org.springframework.cloud.client.loadbalancer.LoadBalancerClientsProperties;
|
||||
import org.springframework.cloud.client.loadbalancer.LoadBalancerProperties;
|
||||
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
|
||||
import org.springframework.cloud.openfeign.clientconfig.OkHttpFeignConfiguration;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
@@ -46,16 +46,16 @@ import org.springframework.context.annotation.Import;
|
||||
@ConditionalOnProperty("feign.okhttp.enabled")
|
||||
@ConditionalOnBean({ LoadBalancerClient.class, LoadBalancerClientFactory.class })
|
||||
@Import(OkHttpFeignConfiguration.class)
|
||||
@EnableConfigurationProperties(LoadBalancerClientsProperties.class)
|
||||
@EnableConfigurationProperties(LoadBalancerProperties.class)
|
||||
class OkHttpFeignLoadBalancerConfiguration {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
@Conditional(OnRetryNotEnabledCondition.class)
|
||||
public Client feignClient(okhttp3.OkHttpClient okHttpClient, LoadBalancerClient loadBalancerClient,
|
||||
LoadBalancerClientFactory loadBalancerClientFactory) {
|
||||
LoadBalancerProperties properties, LoadBalancerClientFactory loadBalancerClientFactory) {
|
||||
OkHttpClient delegate = new OkHttpClient(okHttpClient);
|
||||
return new FeignBlockingLoadBalancerClient(delegate, loadBalancerClient, loadBalancerClientFactory);
|
||||
return new FeignBlockingLoadBalancerClient(delegate, loadBalancerClient, properties, loadBalancerClientFactory);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@@ -65,10 +65,11 @@ class OkHttpFeignLoadBalancerConfiguration {
|
||||
@ConditionalOnProperty(value = "spring.cloud.loadbalancer.retry.enabled", havingValue = "true",
|
||||
matchIfMissing = true)
|
||||
public Client feignRetryClient(LoadBalancerClient loadBalancerClient, okhttp3.OkHttpClient okHttpClient,
|
||||
LoadBalancedRetryFactory loadBalancedRetryFactory, LoadBalancerClientFactory loadBalancerClientFactory) {
|
||||
LoadBalancedRetryFactory loadBalancedRetryFactory, LoadBalancerProperties properties,
|
||||
LoadBalancerClientFactory loadBalancerClientFactory) {
|
||||
OkHttpClient delegate = new OkHttpClient(okHttpClient);
|
||||
return new RetryableFeignBlockingLoadBalancerClient(delegate, loadBalancerClient, loadBalancedRetryFactory,
|
||||
loadBalancerClientFactory);
|
||||
properties, loadBalancerClientFactory);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+5
-17
@@ -78,27 +78,17 @@ public class RetryableFeignBlockingLoadBalancerClient implements Client {
|
||||
|
||||
private final LoadBalancedRetryFactory loadBalancedRetryFactory;
|
||||
|
||||
private final LoadBalancerProperties properties;
|
||||
|
||||
private final LoadBalancerClientFactory loadBalancerClientFactory;
|
||||
|
||||
/**
|
||||
* @deprecated in favour of
|
||||
* {@link RetryableFeignBlockingLoadBalancerClient#RetryableFeignBlockingLoadBalancerClient(Client, LoadBalancerClient, LoadBalancedRetryFactory, LoadBalancerClientFactory)}
|
||||
*/
|
||||
@Deprecated
|
||||
public RetryableFeignBlockingLoadBalancerClient(Client delegate, LoadBalancerClient loadBalancerClient,
|
||||
LoadBalancedRetryFactory loadBalancedRetryFactory, LoadBalancerProperties properties,
|
||||
LoadBalancerClientFactory loadBalancerClientFactory) {
|
||||
this.delegate = delegate;
|
||||
this.loadBalancerClient = loadBalancerClient;
|
||||
this.loadBalancedRetryFactory = loadBalancedRetryFactory;
|
||||
this.loadBalancerClientFactory = loadBalancerClientFactory;
|
||||
}
|
||||
|
||||
public RetryableFeignBlockingLoadBalancerClient(Client delegate, LoadBalancerClient loadBalancerClient,
|
||||
LoadBalancedRetryFactory loadBalancedRetryFactory, LoadBalancerClientFactory loadBalancerClientFactory) {
|
||||
this.delegate = delegate;
|
||||
this.loadBalancerClient = loadBalancerClient;
|
||||
this.loadBalancedRetryFactory = loadBalancedRetryFactory;
|
||||
this.properties = properties;
|
||||
this.loadBalancerClientFactory = loadBalancerClientFactory;
|
||||
}
|
||||
|
||||
@@ -163,10 +153,9 @@ public class RetryableFeignBlockingLoadBalancerClient implements Client {
|
||||
}
|
||||
org.springframework.cloud.client.loadbalancer.Response<ServiceInstance> lbResponse = new DefaultResponse(
|
||||
retrievedServiceInstance);
|
||||
LoadBalancerProperties loadBalancerProperties = loadBalancerClientFactory.getProperties(serviceId);
|
||||
Response response = LoadBalancerUtils.executeWithLoadBalancerLifecycleProcessing(delegate, options,
|
||||
feignRequest, lbRequest, lbResponse, supportedLifecycleProcessors, retrievedServiceInstance != null,
|
||||
loadBalancerProperties.isUseRawStatusCodeInResponseData());
|
||||
feignRequest, lbRequest, lbResponse, supportedLifecycleProcessors,
|
||||
retrievedServiceInstance != null);
|
||||
int responseStatus = response.status();
|
||||
if (retryPolicy != null && retryPolicy.retryableStatusCode(responseStatus)) {
|
||||
if (LOG.isDebugEnabled()) {
|
||||
@@ -243,7 +232,6 @@ public class RetryableFeignBlockingLoadBalancerClient implements Client {
|
||||
}
|
||||
|
||||
private String getHint(String serviceId) {
|
||||
LoadBalancerProperties properties = loadBalancerClientFactory.getProperties(serviceId);
|
||||
String defaultHint = properties.getHint().getOrDefault("default", "default");
|
||||
String hintPropertyValue = properties.getHint().get(serviceId);
|
||||
return hintPropertyValue != null ? hintPropertyValue : defaultHint;
|
||||
|
||||
+1
@@ -43,6 +43,7 @@ import org.springframework.security.oauth2.common.OAuth2AccessToken;
|
||||
* @author Tim Ysewyn
|
||||
* @since 3.0.0
|
||||
*/
|
||||
@Deprecated // spring-security-oauth2 reached EOL
|
||||
public class OAuth2FeignRequestInterceptor implements RequestInterceptor {
|
||||
|
||||
/**
|
||||
|
||||
-81
@@ -1,81 +0,0 @@
|
||||
/*
|
||||
* Copyright 2015-2021 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.cloud.openfeign.security;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.http.client.ClientHttpRequestInterceptor;
|
||||
import org.springframework.security.oauth2.client.OAuth2ClientContext;
|
||||
import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails;
|
||||
import org.springframework.security.oauth2.client.token.AccessTokenProvider;
|
||||
import org.springframework.security.oauth2.client.token.AccessTokenProviderChain;
|
||||
import org.springframework.security.oauth2.client.token.OAuth2AccessTokenSupport;
|
||||
import org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsAccessTokenProvider;
|
||||
import org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeAccessTokenProvider;
|
||||
import org.springframework.security.oauth2.client.token.grant.implicit.ImplicitAccessTokenProvider;
|
||||
import org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordAccessTokenProvider;
|
||||
|
||||
/**
|
||||
* Allows to customize pre-defined {@link OAuth2FeignRequestInterceptor} using configurer
|
||||
* beans of class {@link OAuth2FeignRequestInterceptorConfigurer}. Each configurer
|
||||
* instance can add {@link AccessTokenProvider} new {@link ClientHttpRequestInterceptor}
|
||||
* instances.
|
||||
*
|
||||
* @author Wojciech Mąka
|
||||
* @since 3.1.1
|
||||
*/
|
||||
public class OAuth2FeignRequestInterceptorBuilder {
|
||||
|
||||
private AccessTokenProvider accessTokenProvider;
|
||||
|
||||
private final List<ClientHttpRequestInterceptor> accessTokenProviderInterceptors = new ArrayList<>();
|
||||
|
||||
public OAuth2FeignRequestInterceptorBuilder() {
|
||||
accessTokenProvider = new AccessTokenProviderChain(Arrays.<AccessTokenProvider>asList(
|
||||
new AuthorizationCodeAccessTokenProvider(), new ImplicitAccessTokenProvider(),
|
||||
new ResourceOwnerPasswordAccessTokenProvider(), new ClientCredentialsAccessTokenProvider()));
|
||||
}
|
||||
|
||||
public OAuth2FeignRequestInterceptorBuilder withAccessTokenProviderInterceptors(
|
||||
ClientHttpRequestInterceptor... interceptors) {
|
||||
accessTokenProviderInterceptors.addAll(Arrays.asList(interceptors));
|
||||
return this;
|
||||
}
|
||||
|
||||
OAuth2FeignRequestInterceptor build(OAuth2ClientContext oAuth2ClientContext,
|
||||
OAuth2ProtectedResourceDetails resource) {
|
||||
if (OAuth2AccessTokenSupport.class.isAssignableFrom(accessTokenProvider.getClass())) {
|
||||
((OAuth2AccessTokenSupport) accessTokenProvider).setInterceptors(accessTokenProviderInterceptors);
|
||||
}
|
||||
final OAuth2FeignRequestInterceptor feignRequestInterceptor = new OAuth2FeignRequestInterceptor(
|
||||
oAuth2ClientContext, resource);
|
||||
feignRequestInterceptor.setAccessTokenProvider(accessTokenProvider);
|
||||
return feignRequestInterceptor;
|
||||
}
|
||||
|
||||
public static OAuth2FeignRequestInterceptor buildWithConfigurers(OAuth2ClientContext oAuth2ClientContext,
|
||||
OAuth2ProtectedResourceDetails resource, List<OAuth2FeignRequestInterceptorConfigurer> buildConfigurers) {
|
||||
final OAuth2FeignRequestInterceptorBuilder builder = new OAuth2FeignRequestInterceptorBuilder();
|
||||
for (OAuth2FeignRequestInterceptorConfigurer configurer : buildConfigurers) {
|
||||
configurer.customize(builder);
|
||||
}
|
||||
return builder.build(oAuth2ClientContext, resource);
|
||||
}
|
||||
|
||||
}
|
||||
-35
@@ -1,35 +0,0 @@
|
||||
/*
|
||||
* Copyright 2015-2022 the original author 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.security;
|
||||
|
||||
import org.springframework.security.oauth2.client.token.AccessTokenProvider;
|
||||
|
||||
/**
|
||||
* Interface for configurer beans working with
|
||||
* {@link OAuth2FeignRequestInterceptorBuilder} in order to provide custom interceptors
|
||||
* for {@link AccessTokenProvider} managed internally by
|
||||
* {@link OAuth2FeignRequestInterceptor}.
|
||||
*
|
||||
* @author Wojciech Mąka
|
||||
* @since 3.1.1
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface OAuth2FeignRequestInterceptorConfigurer {
|
||||
|
||||
void customize(OAuth2FeignRequestInterceptorBuilder requestInterceptorBuilder);
|
||||
|
||||
}
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
/*
|
||||
* Copyright 2013-2022 the original author 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.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.lang.reflect.Type;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Collection;
|
||||
import java.util.zip.GZIPInputStream;
|
||||
|
||||
import feign.FeignException;
|
||||
import feign.Response;
|
||||
import feign.codec.Decoder;
|
||||
|
||||
import org.springframework.cloud.openfeign.encoding.HttpEncoding;
|
||||
|
||||
/**
|
||||
* When response is compressed as gzip, this decompresses and uses {@link SpringDecoder}
|
||||
* to decode.
|
||||
*
|
||||
* @author Jaesik Kim
|
||||
*/
|
||||
public class DefaultGzipDecoder implements Decoder {
|
||||
|
||||
private Decoder decoder;
|
||||
|
||||
public DefaultGzipDecoder(Decoder decoder) {
|
||||
this.decoder = decoder;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object decode(final Response response, Type type) throws IOException, FeignException {
|
||||
Collection<String> encoding = response.headers().containsKey(HttpEncoding.CONTENT_ENCODING_HEADER)
|
||||
? response.headers().get(HttpEncoding.CONTENT_ENCODING_HEADER) : null;
|
||||
|
||||
if (encoding != null) {
|
||||
if (encoding.contains(HttpEncoding.GZIP_ENCODING)) {
|
||||
String decompressedBody = decompress(response);
|
||||
if (decompressedBody != null) {
|
||||
Response decompressedResponse = response.toBuilder().body(decompressedBody.getBytes()).build();
|
||||
return decoder.decode(decompressedResponse, type);
|
||||
}
|
||||
}
|
||||
}
|
||||
return decoder.decode(response, type);
|
||||
}
|
||||
|
||||
private String decompress(Response response) throws IOException {
|
||||
if (response.body() == null) {
|
||||
return null;
|
||||
}
|
||||
try (GZIPInputStream gzipInputStream = new GZIPInputStream(response.body().asInputStream());
|
||||
BufferedReader reader = new BufferedReader(
|
||||
new InputStreamReader(gzipInputStream, StandardCharsets.UTF_8))) {
|
||||
String outputString = "";
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
outputString += line;
|
||||
}
|
||||
return outputString;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
/*
|
||||
* Copyright 2013-2022 the original author 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 feign.codec.Decoder;
|
||||
import feign.optionals.OptionalDecoder;
|
||||
|
||||
import org.springframework.beans.factory.ObjectFactory;
|
||||
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
|
||||
import org.springframework.cloud.openfeign.FeignAutoConfiguration;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* Configures Default Gzip Decoder.
|
||||
*
|
||||
* @author Jaesik Kim
|
||||
*/
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@ConditionalOnProperty("feign.compression.response.enabled")
|
||||
// The OK HTTP client uses "transparent" compression.
|
||||
// If the accept-encoding header is present, it disables transparent compression
|
||||
@ConditionalOnMissingBean(type = "okhttp3.OkHttpClient")
|
||||
@AutoConfigureAfter(FeignAutoConfiguration.class)
|
||||
public class DefaultGzipDecoderConfiguration {
|
||||
|
||||
private ObjectFactory<HttpMessageConverters> messageConverters;
|
||||
|
||||
public DefaultGzipDecoderConfiguration(ObjectFactory<HttpMessageConverters> messageConverters) {
|
||||
this.messageConverters = messageConverters;
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
@ConditionalOnProperty("feign.compression.response.useGzipDecoder")
|
||||
public Decoder defaultGzipDecoder() {
|
||||
return new OptionalDecoder(
|
||||
new ResponseEntityDecoder(new DefaultGzipDecoder(new SpringDecoder(messageConverters))));
|
||||
}
|
||||
|
||||
}
|
||||
-54
@@ -1,54 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2022 the original author 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.util.function.Consumer;
|
||||
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
|
||||
/**
|
||||
* @author Olga Maciaszek-Sharma
|
||||
*/
|
||||
class EmptyObjectProvider<T> implements ObjectProvider<T> {
|
||||
|
||||
@Override
|
||||
public T getObject(Object... args) throws BeansException {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public T getIfAvailable() throws BeansException {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public T getIfUnique() throws BeansException {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public T getObject() throws BeansException {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void forEach(Consumer action) {
|
||||
// do nothing
|
||||
}
|
||||
|
||||
}
|
||||
+9
-46
@@ -16,17 +16,13 @@
|
||||
|
||||
package org.springframework.cloud.openfeign.support;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import feign.okhttp.OkHttpClient;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
/**
|
||||
* @author Ryan Baxter
|
||||
* @author Nguyen Ky Thanh
|
||||
* @author Olga Maciaszek-Sharma
|
||||
*/
|
||||
@ConfigurationProperties(prefix = "feign.httpclient")
|
||||
public class FeignHttpClientProperties {
|
||||
@@ -92,13 +88,8 @@ public class FeignHttpClientProperties {
|
||||
*/
|
||||
private Hc5Properties hc5 = new Hc5Properties();
|
||||
|
||||
/**
|
||||
* Additional {@link OkHttpClient}-specific properties.
|
||||
*/
|
||||
private OkHttp okHttp = new OkHttp();
|
||||
|
||||
public int getConnectionTimerRepeat() {
|
||||
return connectionTimerRepeat;
|
||||
return this.connectionTimerRepeat;
|
||||
}
|
||||
|
||||
public void setConnectionTimerRepeat(int connectionTimerRepeat) {
|
||||
@@ -106,7 +97,7 @@ public class FeignHttpClientProperties {
|
||||
}
|
||||
|
||||
public boolean isDisableSslValidation() {
|
||||
return disableSslValidation;
|
||||
return this.disableSslValidation;
|
||||
}
|
||||
|
||||
public void setDisableSslValidation(boolean disableSslValidation) {
|
||||
@@ -114,7 +105,7 @@ public class FeignHttpClientProperties {
|
||||
}
|
||||
|
||||
public int getMaxConnections() {
|
||||
return maxConnections;
|
||||
return this.maxConnections;
|
||||
}
|
||||
|
||||
public void setMaxConnections(int maxConnections) {
|
||||
@@ -122,7 +113,7 @@ public class FeignHttpClientProperties {
|
||||
}
|
||||
|
||||
public int getMaxConnectionsPerRoute() {
|
||||
return maxConnectionsPerRoute;
|
||||
return this.maxConnectionsPerRoute;
|
||||
}
|
||||
|
||||
public void setMaxConnectionsPerRoute(int maxConnectionsPerRoute) {
|
||||
@@ -130,7 +121,7 @@ public class FeignHttpClientProperties {
|
||||
}
|
||||
|
||||
public long getTimeToLive() {
|
||||
return timeToLive;
|
||||
return this.timeToLive;
|
||||
}
|
||||
|
||||
public void setTimeToLive(long timeToLive) {
|
||||
@@ -138,7 +129,7 @@ public class FeignHttpClientProperties {
|
||||
}
|
||||
|
||||
public TimeUnit getTimeToLiveUnit() {
|
||||
return timeToLiveUnit;
|
||||
return this.timeToLiveUnit;
|
||||
}
|
||||
|
||||
public void setTimeToLiveUnit(TimeUnit timeToLiveUnit) {
|
||||
@@ -146,7 +137,7 @@ public class FeignHttpClientProperties {
|
||||
}
|
||||
|
||||
public boolean isFollowRedirects() {
|
||||
return followRedirects;
|
||||
return this.followRedirects;
|
||||
}
|
||||
|
||||
public void setFollowRedirects(boolean followRedirects) {
|
||||
@@ -154,7 +145,7 @@ public class FeignHttpClientProperties {
|
||||
}
|
||||
|
||||
public int getConnectionTimeout() {
|
||||
return connectionTimeout;
|
||||
return this.connectionTimeout;
|
||||
}
|
||||
|
||||
public void setConnectionTimeout(int connectionTimeout) {
|
||||
@@ -169,14 +160,6 @@ public class FeignHttpClientProperties {
|
||||
this.hc5 = hc5;
|
||||
}
|
||||
|
||||
public OkHttp getOkHttp() {
|
||||
return okHttp;
|
||||
}
|
||||
|
||||
public void setOkHttp(OkHttp okHttp) {
|
||||
this.okHttp = okHttp;
|
||||
}
|
||||
|
||||
public static class Hc5Properties {
|
||||
|
||||
/**
|
||||
@@ -220,7 +203,7 @@ public class FeignHttpClientProperties {
|
||||
private TimeUnit socketTimeoutUnit = DEFAULT_SOCKET_TIMEOUT_UNIT;
|
||||
|
||||
public PoolConcurrencyPolicy getPoolConcurrencyPolicy() {
|
||||
return poolConcurrencyPolicy;
|
||||
return this.poolConcurrencyPolicy;
|
||||
}
|
||||
|
||||
public void setPoolConcurrencyPolicy(PoolConcurrencyPolicy poolConcurrencyPolicy) {
|
||||
@@ -289,24 +272,4 @@ public class FeignHttpClientProperties {
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* {@link OkHttpClient}-specific properties.
|
||||
*/
|
||||
public static class OkHttp {
|
||||
|
||||
/**
|
||||
* {@link OkHttpClient} read timeout; defaults to 60 seconds.
|
||||
*/
|
||||
private Duration readTimeout = Duration.ofSeconds(60);
|
||||
|
||||
public Duration getReadTimeout() {
|
||||
return readTimeout;
|
||||
}
|
||||
|
||||
public void setReadTimeout(Duration readTimeout) {
|
||||
this.readTimeout = readTimeout;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
-33
@@ -1,33 +0,0 @@
|
||||
/*
|
||||
* Copyright 2016-2021 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.cloud.openfeign.support;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import org.springframework.http.converter.HttpMessageConverter;
|
||||
|
||||
/**
|
||||
* Allows customising {@link HttpMessageConverter} objects passed via {@link Consumer}
|
||||
* parameter.
|
||||
*
|
||||
* @author Olga Maciaszek-Sharma
|
||||
* @since 3.1.0
|
||||
*/
|
||||
public interface HttpMessageConverterCustomizer extends Consumer<List<HttpMessageConverter<?>>> {
|
||||
|
||||
}
|
||||
+4
-6
@@ -22,7 +22,6 @@ import java.util.function.Function;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonAlias;
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.core.Version;
|
||||
import com.fasterxml.jackson.databind.Module;
|
||||
@@ -60,7 +59,6 @@ public class PageJacksonModule extends Module {
|
||||
}
|
||||
|
||||
@JsonDeserialize(as = SimplePageImpl.class)
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
private interface PageMixIn {
|
||||
|
||||
}
|
||||
@@ -88,7 +86,7 @@ public class PageJacksonModule extends Module {
|
||||
}
|
||||
}
|
||||
|
||||
@JsonProperty
|
||||
@JsonIgnore
|
||||
@Override
|
||||
public int getTotalPages() {
|
||||
return delegate.getTotalPages();
|
||||
@@ -112,7 +110,7 @@ public class PageJacksonModule extends Module {
|
||||
return delegate.getSize();
|
||||
}
|
||||
|
||||
@JsonProperty
|
||||
@JsonIgnore
|
||||
@Override
|
||||
public int getNumberOfElements() {
|
||||
return delegate.getNumberOfElements();
|
||||
@@ -136,13 +134,13 @@ public class PageJacksonModule extends Module {
|
||||
return delegate.getSort();
|
||||
}
|
||||
|
||||
@JsonProperty
|
||||
@JsonIgnore
|
||||
@Override
|
||||
public boolean isFirst() {
|
||||
return delegate.isFirst();
|
||||
}
|
||||
|
||||
@JsonProperty
|
||||
@JsonIgnore
|
||||
@Override
|
||||
public boolean isLast() {
|
||||
return delegate.isLast();
|
||||
|
||||
+2
-3
@@ -32,7 +32,6 @@ import org.springframework.data.domain.Sort;
|
||||
* Provides support for encoding spring Pageable via composition.
|
||||
*
|
||||
* @author Pascal Büttiker
|
||||
* @author Yanming Zhou
|
||||
*/
|
||||
public class PageableSpringEncoder implements Encoder {
|
||||
|
||||
@@ -83,8 +82,8 @@ public class PageableSpringEncoder implements Encoder {
|
||||
Pageable pageable = (Pageable) object;
|
||||
|
||||
if (pageable.isPaged()) {
|
||||
template.query(pageParameter, String.valueOf(pageable.getPageNumber()));
|
||||
template.query(sizeParameter, String.valueOf(pageable.getPageSize()));
|
||||
template.query(pageParameter, pageable.getPageNumber() + "");
|
||||
template.query(sizeParameter, pageable.getPageSize() + "");
|
||||
}
|
||||
|
||||
if (pageable.getSort() != null) {
|
||||
|
||||
+3
-31
@@ -31,38 +31,10 @@ import org.springframework.data.domain.Sort;
|
||||
* {@link org.springframework.cloud.openfeign.SpringQueryMap}.
|
||||
*
|
||||
* @author Hyeonmin Park
|
||||
* @author Yanming Zhou
|
||||
* @since 2.2.8
|
||||
*/
|
||||
public class PageableSpringQueryMapEncoder extends BeanQueryMapEncoder {
|
||||
|
||||
/**
|
||||
* Page index parameter name.
|
||||
*/
|
||||
private String pageParameter = "page";
|
||||
|
||||
/**
|
||||
* Page size parameter name.
|
||||
*/
|
||||
private String sizeParameter = "size";
|
||||
|
||||
/**
|
||||
* Sort parameter name.
|
||||
*/
|
||||
private String sortParameter = "sort";
|
||||
|
||||
public void setPageParameter(String pageParameter) {
|
||||
this.pageParameter = pageParameter;
|
||||
}
|
||||
|
||||
public void setSizeParameter(String sizeParameter) {
|
||||
this.sizeParameter = sizeParameter;
|
||||
}
|
||||
|
||||
public void setSortParameter(String sortParameter) {
|
||||
this.sortParameter = sortParameter;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Object> encode(Object object) {
|
||||
if (supports(object)) {
|
||||
@@ -72,8 +44,8 @@ public class PageableSpringQueryMapEncoder extends BeanQueryMapEncoder {
|
||||
Pageable pageable = (Pageable) object;
|
||||
|
||||
if (pageable.isPaged()) {
|
||||
queryMap.put(pageParameter, pageable.getPageNumber());
|
||||
queryMap.put(sizeParameter, pageable.getPageSize());
|
||||
queryMap.put("page", pageable.getPageNumber());
|
||||
queryMap.put("size", pageable.getPageSize());
|
||||
}
|
||||
|
||||
if (pageable.getSort() != null) {
|
||||
@@ -97,7 +69,7 @@ public class PageableSpringQueryMapEncoder extends BeanQueryMapEncoder {
|
||||
sortQueries.add(order.getProperty() + "%2C" + order.getDirection());
|
||||
}
|
||||
if (!sortQueries.isEmpty()) {
|
||||
queryMap.put(sortParameter, sortQueries);
|
||||
queryMap.put("sort", sortQueries);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+9
-27
@@ -21,7 +21,6 @@ import java.io.InputStream;
|
||||
import java.lang.reflect.ParameterizedType;
|
||||
import java.lang.reflect.Type;
|
||||
import java.lang.reflect.WildcardType;
|
||||
import java.util.List;
|
||||
|
||||
import feign.FeignException;
|
||||
import feign.Response;
|
||||
@@ -29,48 +28,31 @@ import feign.codec.DecodeException;
|
||||
import feign.codec.Decoder;
|
||||
|
||||
import org.springframework.beans.factory.ObjectFactory;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.client.ClientHttpResponse;
|
||||
import org.springframework.http.converter.HttpMessageConverter;
|
||||
import org.springframework.web.client.HttpMessageConverterExtractor;
|
||||
|
||||
import static org.springframework.cloud.openfeign.support.FeignUtils.getHttpHeaders;
|
||||
|
||||
/**
|
||||
* @author Spencer Gibb
|
||||
* @author Olga Maciaszek-Sharma
|
||||
*/
|
||||
public class SpringDecoder implements Decoder {
|
||||
|
||||
private final ObjectFactory<HttpMessageConverters> messageConverters;
|
||||
private ObjectFactory<HttpMessageConverters> messageConverters;
|
||||
|
||||
private final ObjectProvider<HttpMessageConverterCustomizer> customizers;
|
||||
|
||||
/**
|
||||
* @deprecated in favour of
|
||||
* {@link SpringDecoder#SpringDecoder(ObjectFactory, ObjectProvider)}
|
||||
*/
|
||||
@Deprecated
|
||||
public SpringDecoder(ObjectFactory<HttpMessageConverters> messageConverters) {
|
||||
this(messageConverters, new EmptyObjectProvider<>());
|
||||
}
|
||||
|
||||
public SpringDecoder(ObjectFactory<HttpMessageConverters> messageConverters,
|
||||
ObjectProvider<HttpMessageConverterCustomizer> customizers) {
|
||||
this.messageConverters = messageConverters;
|
||||
this.customizers = customizers;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object decode(final Response response, Type type) throws IOException, FeignException {
|
||||
if (type instanceof Class || type instanceof ParameterizedType || type instanceof WildcardType) {
|
||||
List<HttpMessageConverter<?>> converters = messageConverters.getObject().getConverters();
|
||||
customizers.forEach(customizer -> customizer.accept(converters));
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
HttpMessageConverterExtractor<?> extractor = new HttpMessageConverterExtractor(type, converters);
|
||||
HttpMessageConverterExtractor<?> extractor = new HttpMessageConverterExtractor(type,
|
||||
this.messageConverters.getObject().getConverters());
|
||||
|
||||
return extractor.extractData(new FeignResponseAdapter(response));
|
||||
}
|
||||
@@ -88,23 +70,23 @@ public class SpringDecoder implements Decoder {
|
||||
|
||||
@Override
|
||||
public HttpStatus getStatusCode() throws IOException {
|
||||
return HttpStatus.valueOf(response.status());
|
||||
return HttpStatus.valueOf(this.response.status());
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getRawStatusCode() throws IOException {
|
||||
return response.status();
|
||||
return this.response.status();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getStatusText() throws IOException {
|
||||
return response.reason();
|
||||
return this.response.reason();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
try {
|
||||
response.body().close();
|
||||
this.response.body().close();
|
||||
}
|
||||
catch (IOException ex) {
|
||||
// Ignore exception on close...
|
||||
@@ -113,12 +95,12 @@ public class SpringDecoder implements Decoder {
|
||||
|
||||
@Override
|
||||
public InputStream getBody() throws IOException {
|
||||
return response.body().asInputStream();
|
||||
return this.response.body().asInputStream();
|
||||
}
|
||||
|
||||
@Override
|
||||
public HttpHeaders getHeaders() {
|
||||
return getHttpHeaders(response.headers());
|
||||
return getHttpHeaders(this.response.headers());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+1
-23
@@ -24,7 +24,6 @@ import java.nio.charset.Charset;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
@@ -36,7 +35,6 @@ import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import org.springframework.beans.factory.ObjectFactory;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
|
||||
import org.springframework.cloud.openfeign.encoding.HttpEncoding;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
@@ -76,37 +74,19 @@ public class SpringEncoder implements Encoder {
|
||||
|
||||
private final FeignEncoderProperties encoderProperties;
|
||||
|
||||
private final ObjectProvider<HttpMessageConverterCustomizer> customizers;
|
||||
|
||||
public SpringEncoder(ObjectFactory<HttpMessageConverters> messageConverters) {
|
||||
this(new SpringFormEncoder(), messageConverters);
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated in favour of
|
||||
* {@link SpringEncoder#SpringEncoder(SpringFormEncoder, ObjectFactory, FeignEncoderProperties, ObjectProvider)}
|
||||
*/
|
||||
@Deprecated
|
||||
public SpringEncoder(SpringFormEncoder springFormEncoder, ObjectFactory<HttpMessageConverters> messageConverters) {
|
||||
this(springFormEncoder, messageConverters, new FeignEncoderProperties());
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated in favour of
|
||||
* {@link SpringEncoder#SpringEncoder(SpringFormEncoder, ObjectFactory, FeignEncoderProperties, ObjectProvider)}
|
||||
*/
|
||||
@Deprecated
|
||||
public SpringEncoder(SpringFormEncoder springFormEncoder, ObjectFactory<HttpMessageConverters> messageConverters,
|
||||
FeignEncoderProperties encoderProperties) {
|
||||
this(springFormEncoder, messageConverters, encoderProperties, new EmptyObjectProvider<>());
|
||||
}
|
||||
|
||||
public SpringEncoder(SpringFormEncoder springFormEncoder, ObjectFactory<HttpMessageConverters> messageConverters,
|
||||
FeignEncoderProperties encoderProperties, ObjectProvider<HttpMessageConverterCustomizer> customizers) {
|
||||
this.springFormEncoder = springFormEncoder;
|
||||
this.messageConverters = messageConverters;
|
||||
this.encoderProperties = encoderProperties;
|
||||
this.customizers = customizers;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -137,9 +117,7 @@ public class SpringEncoder implements Encoder {
|
||||
|
||||
private void encodeWithMessageConverter(Object requestBody, Type bodyType, RequestTemplate request,
|
||||
MediaType requestContentType) {
|
||||
List<HttpMessageConverter<?>> converters = messageConverters.getObject().getConverters();
|
||||
customizers.forEach(customizer -> customizer.accept(converters));
|
||||
for (HttpMessageConverter messageConverter : converters) {
|
||||
for (HttpMessageConverter messageConverter : this.messageConverters.getObject().getConverters()) {
|
||||
FeignOutputMessage outputMessage;
|
||||
try {
|
||||
if (messageConverter instanceof GenericHttpMessageConverter) {
|
||||
|
||||
-7
@@ -40,7 +40,6 @@ import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import org.springframework.cloud.openfeign.AnnotatedParameterProcessor;
|
||||
import org.springframework.cloud.openfeign.CollectionFormat;
|
||||
import org.springframework.cloud.openfeign.annotation.CookieValueParameterProcessor;
|
||||
import org.springframework.cloud.openfeign.annotation.MatrixVariableParameterProcessor;
|
||||
import org.springframework.cloud.openfeign.annotation.PathVariableParameterProcessor;
|
||||
import org.springframework.cloud.openfeign.annotation.QueryMapParameterProcessor;
|
||||
@@ -82,7 +81,6 @@ import static org.springframework.core.annotation.AnnotatedElementUtils.findMerg
|
||||
* @author Artyom Romanenko
|
||||
* @author Darren Foong
|
||||
* @author Ram Anaswara
|
||||
* @author Sam Kruglov
|
||||
*/
|
||||
public class SpringMvcContract extends Contract.BaseContract implements ResourceLoaderAware {
|
||||
|
||||
@@ -181,10 +179,6 @@ public class SpringMvcContract extends Contract.BaseContract implements Resource
|
||||
+ ". @RequestMapping annotation is not allowed on @FeignClient interfaces.");
|
||||
throw new IllegalArgumentException("@RequestMapping annotation not allowed on @FeignClient interfaces");
|
||||
}
|
||||
CollectionFormat collectionFormat = findMergedAnnotation(clz, CollectionFormat.class);
|
||||
if (collectionFormat != null) {
|
||||
data.template().collectionFormat(collectionFormat.value());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -341,7 +335,6 @@ public class SpringMvcContract extends Contract.BaseContract implements Resource
|
||||
annotatedArgumentResolvers.add(new RequestHeaderParameterProcessor());
|
||||
annotatedArgumentResolvers.add(new QueryMapParameterProcessor());
|
||||
annotatedArgumentResolvers.add(new RequestPartParameterProcessor());
|
||||
annotatedArgumentResolvers.add(new CookieValueParameterProcessor());
|
||||
|
||||
return annotatedArgumentResolvers;
|
||||
}
|
||||
|
||||
+6
-18
@@ -14,12 +14,6 @@
|
||||
"description": "If true, an OpenFeign client will be wrapped with a Spring Cloud CircuitBreaker circuit breaker.",
|
||||
"defaultValue": "false"
|
||||
},
|
||||
{
|
||||
"name": "feign.circuitbreaker.alphanumeric-ids.enabled",
|
||||
"type": "java.lang.Boolean",
|
||||
"description": "If true, Circuit Breaker ids will only contain alphanumeric characters to allow for configuration via configuration properties.",
|
||||
"defaultValue": "false"
|
||||
},
|
||||
{
|
||||
"name": "feign.circuitbreaker.group.enabled",
|
||||
"type": "java.lang.Boolean",
|
||||
@@ -50,6 +44,12 @@
|
||||
"description": "Enables the response from Feign to be compressed.",
|
||||
"defaultValue": "false"
|
||||
},
|
||||
{
|
||||
"name": "feign.compression.response.useGzipDecoder",
|
||||
"type": "java.lang.Boolean",
|
||||
"description": "Enables the default gzip decoder to be used.",
|
||||
"defaultValue": "false"
|
||||
},
|
||||
{
|
||||
"name": "feign.compression.request.enabled",
|
||||
"type": "java.lang.Boolean",
|
||||
@@ -67,18 +67,6 @@
|
||||
"type": "java.lang.Boolean",
|
||||
"description": "Enables options value refresh capability for Feign.",
|
||||
"defaultValue": "false"
|
||||
},
|
||||
{
|
||||
"name": "feign.oauth2.enabled",
|
||||
"type": "java.lang.Boolean",
|
||||
"description": "Enables feign interceptor for managing oauth2 access token.",
|
||||
"defaultValue": "false"
|
||||
},
|
||||
{
|
||||
"name": "feign.oauth2.load-balanced",
|
||||
"type": "java.lang.Boolean",
|
||||
"description": "Enables load balancing for oauth2 access token provider.",
|
||||
"defaultValue": "false"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
+11
-9
@@ -18,7 +18,8 @@ package org.springframework.cloud.openfeign;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
@@ -30,6 +31,7 @@ import org.springframework.context.annotation.Import;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.test.annotation.DirtiesContext;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@@ -37,15 +39,15 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* @author Jaesik Kim
|
||||
* @author Olga Maciaszek-Sharma
|
||||
*/
|
||||
@SpringBootTest(classes = GzipDecodingTests.Application.class,
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@SpringBootTest(classes = DefaultGzipDecoderTests.Application.class,
|
||||
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
|
||||
value = { "spring.application.name=defaultGzipDecoderTests", "feign.compression.response.enabled=true",
|
||||
"feign.client.config.default.loggerLevel=none", "feign.metrics.enabled=false",
|
||||
"feign.compression.response.useGzipDecoder=true", "feign.client.config.default.loggerLevel=full",
|
||||
"logging.level.org.springframework.cloud.openfeign=DEBUG" })
|
||||
@DirtiesContext
|
||||
class GzipDecodingTests extends FeignClientFactoryBean {
|
||||
public class DefaultGzipDecoderTests extends FeignClientFactoryBean {
|
||||
|
||||
@Autowired
|
||||
FeignContext context;
|
||||
@@ -53,7 +55,7 @@ class GzipDecodingTests extends FeignClientFactoryBean {
|
||||
@Value("${local.server.port}")
|
||||
private int port = 0;
|
||||
|
||||
GzipDecodingTests() {
|
||||
public DefaultGzipDecoderTests() {
|
||||
setName("tests");
|
||||
setContextId("test");
|
||||
}
|
||||
@@ -64,7 +66,7 @@ class GzipDecodingTests extends FeignClientFactoryBean {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testBodyDecompress() {
|
||||
public void testBodyDecompress() {
|
||||
ResponseEntity<Hello> response = testClient().getGzipResponse();
|
||||
assertThat(response).as("response was null").isNotNull();
|
||||
assertThat(response.getStatusCode()).as("wrong status code").isEqualTo(HttpStatus.OK);
|
||||
@@ -74,7 +76,7 @@ class GzipDecodingTests extends FeignClientFactoryBean {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testNullBodyDecompress() {
|
||||
public void testNullBodyDecompress() {
|
||||
ResponseEntity<Hello> response = testClient().getNullResponse();
|
||||
assertThat(response).as("response was null").isNotNull();
|
||||
assertThat(response.getStatusCode()).as("wrong status code").isEqualTo(HttpStatus.OK);
|
||||
@@ -84,7 +86,7 @@ class GzipDecodingTests extends FeignClientFactoryBean {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCharsetDecompress() {
|
||||
public void testCharsetDecompress() {
|
||||
ResponseEntity<Hello> response = testClient().getUtf8Response();
|
||||
assertThat(response).as("response was null").isNotNull();
|
||||
assertThat(response.getStatusCode()).as("wrong status code").isEqualTo(HttpStatus.OK);
|
||||
+7
-3
@@ -17,7 +17,8 @@
|
||||
package org.springframework.cloud.openfeign;
|
||||
|
||||
import feign.codec.Encoder;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||
@@ -25,19 +26,22 @@ import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.cloud.openfeign.support.PageableSpringEncoder;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.test.annotation.DirtiesContext;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
|
||||
/**
|
||||
* @author Spencer Gibb
|
||||
*/
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@SpringBootTest(classes = EnableFeignClientsSpringDataTests.PlainConfiguration.class)
|
||||
@DirtiesContext
|
||||
class EnableFeignClientsSpringDataTests {
|
||||
public class EnableFeignClientsSpringDataTests {
|
||||
|
||||
@Autowired
|
||||
private FeignContext feignContext;
|
||||
|
||||
@Test
|
||||
void encoderDefaultCorrect() {
|
||||
public void encoderDefaultCorrect() {
|
||||
|
||||
PageableSpringEncoder.class.cast(this.feignContext.getInstance("foo", Encoder.class));
|
||||
}
|
||||
|
||||
|
||||
+16
-13
@@ -23,15 +23,17 @@ import feign.codec.Decoder;
|
||||
import feign.codec.Encoder;
|
||||
import feign.optionals.OptionalDecoder;
|
||||
import feign.slf4j.Slf4jLogger;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
import org.springframework.boot.WebApplicationType;
|
||||
import org.springframework.boot.builder.SpringApplicationBuilder;
|
||||
import org.springframework.cloud.openfeign.support.SpringEncoder;
|
||||
import org.springframework.cloud.openfeign.support.SpringMvcContract;
|
||||
import org.springframework.cloud.test.ClassPathExclusions;
|
||||
import org.springframework.cloud.test.ModifiedClassPathRunner;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Import;
|
||||
@@ -39,47 +41,48 @@ import org.springframework.context.annotation.Import;
|
||||
/**
|
||||
* @author Spencer Gibb
|
||||
*/
|
||||
@RunWith(ModifiedClassPathRunner.class)
|
||||
@ClassPathExclusions({ "spring-data-commons-*.jar" })
|
||||
class EnableFeignClientsTests {
|
||||
public class EnableFeignClientsTests {
|
||||
|
||||
private ConfigurableApplicationContext context;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
@Before
|
||||
public void setUp() {
|
||||
context = new SpringApplicationBuilder().web(WebApplicationType.NONE)
|
||||
.properties("debug=true", "feign.httpclient.enabled=false")
|
||||
.sources(EnableFeignClientsTests.PlainConfiguration.class).run();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
@After
|
||||
public void tearDown() {
|
||||
if (context != null) {
|
||||
context.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void decoderDefaultCorrect() {
|
||||
public void decoderDefaultCorrect() {
|
||||
OptionalDecoder.class.cast(this.context.getBeansOfType(Decoder.class).get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void encoderDefaultCorrect() {
|
||||
public void encoderDefaultCorrect() {
|
||||
SpringEncoder.class.cast(this.context.getBeansOfType(Encoder.class).get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void loggerDefaultCorrect() {
|
||||
public void loggerDefaultCorrect() {
|
||||
Slf4jLogger.class.cast(this.context.getBeansOfType(Logger.class).get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void contractDefaultCorrect() {
|
||||
public void contractDefaultCorrect() {
|
||||
SpringMvcContract.class.cast(this.context.getBeansOfType(Contract.class).get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void builderDefaultCorrect() {
|
||||
public void builderDefaultCorrect() {
|
||||
Feign.Builder.class.cast(this.context.getBeansOfType(Feign.Builder.class).get(0));
|
||||
}
|
||||
|
||||
|
||||
-80
@@ -23,19 +23,10 @@ import org.assertj.core.api.Condition;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import org.springframework.boot.autoconfigure.AutoConfigurations;
|
||||
import org.springframework.boot.test.context.assertj.AssertableApplicationContext;
|
||||
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
|
||||
import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory;
|
||||
import org.springframework.cloud.client.loadbalancer.LoadBalancerInterceptor;
|
||||
import org.springframework.cloud.openfeign.FeignAutoConfiguration.CircuitBreakerPresentFeignTargeterConfiguration.DefaultCircuitBreakerNameResolver;
|
||||
import org.springframework.cloud.openfeign.security.MockOAuth2ClientContext;
|
||||
import org.springframework.cloud.openfeign.security.OAuth2FeignRequestInterceptor;
|
||||
import org.springframework.cloud.openfeign.security.OAuth2FeignRequestInterceptorBuilder;
|
||||
import org.springframework.cloud.openfeign.security.OAuth2FeignRequestInterceptorConfigurer;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
import org.springframework.http.client.ClientHttpRequestInterceptor;
|
||||
import org.springframework.http.client.support.BasicAuthenticationInterceptor;
|
||||
import org.springframework.security.oauth2.client.resource.BaseOAuth2ProtectedResourceDetails;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.mock;
|
||||
@@ -45,7 +36,6 @@ import static org.mockito.Mockito.mock;
|
||||
* @author Olga Maciaszek-Sharma
|
||||
* @author Andrii Bohutskyi
|
||||
* @author Kwangyong Kim
|
||||
* @author Wojciech Mąka
|
||||
*/
|
||||
class FeignAutoConfigurationTests {
|
||||
|
||||
@@ -91,66 +81,6 @@ class FeignAutoConfigurationTests {
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldInstantiateFeignOAuth2FeignRequestInterceptorWithoutInterceptors() {
|
||||
runner.withPropertyValues("feign.oauth2.enabled=true").withBean(MockOAuth2ClientContext.class, "token")
|
||||
.withBean(BaseOAuth2ProtectedResourceDetails.class)
|
||||
.withBean(LoadBalancerInterceptor.class, () -> mock(LoadBalancerInterceptor.class)).run(ctx -> {
|
||||
assertOauth2FeignRequestInterceptorExists(ctx);
|
||||
assertAccessTokenProviderInterceptorNotExists(ctx, LoadBalancerInterceptor.class);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldInstantiateFeignOAuth2FeignRequestInterceptorWithLoadBalancedInterceptor() {
|
||||
runner.withPropertyValues("feign.oauth2.enabled=true", "feign.oauth2.load-balanced=true")
|
||||
.withBean(MockOAuth2ClientContext.class, "token").withBean(BaseOAuth2ProtectedResourceDetails.class)
|
||||
.withBean(LoadBalancerInterceptor.class, () -> mock(LoadBalancerInterceptor.class)).run(ctx -> {
|
||||
assertOauth2FeignRequestInterceptorExists(ctx);
|
||||
assertAccessTokenProviderInterceptorExists(ctx, LoadBalancerInterceptor.class);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldInstantiateFeignOAuth2FeignRequestInterceptorWithoutLoadBalancedInterceptorIfNoBeanPresent() {
|
||||
runner.withPropertyValues("feign.oauth2.enabled=true", "feign.oauth2.load-balanced=true")
|
||||
.withBean(MockOAuth2ClientContext.class, "token").withBean(BaseOAuth2ProtectedResourceDetails.class)
|
||||
.run(ctx -> {
|
||||
assertOauth2FeignRequestInterceptorExists(ctx);
|
||||
assertAccessTokenProviderInterceptorNotExists(ctx, LoadBalancerInterceptor.class);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldInstantiateFeignOAuth2FeignRequestInterceptorWithCustomAccessTokenProviderInterceptor() {
|
||||
runner.withPropertyValues("feign.oauth2.enabled=true").withBean(MockOAuth2ClientContext.class, "token")
|
||||
.withBean(BaseOAuth2ProtectedResourceDetails.class)
|
||||
.withBean(CustomOAuth2FeignRequestInterceptorConfigurer.class).run(ctx -> {
|
||||
assertOauth2FeignRequestInterceptorExists(ctx);
|
||||
assertAccessTokenProviderInterceptorExists(ctx, BasicAuthenticationInterceptor.class);
|
||||
});
|
||||
}
|
||||
|
||||
private void assertOauth2FeignRequestInterceptorExists(ConfigurableApplicationContext ctx) {
|
||||
AssertableApplicationContext context = AssertableApplicationContext.get(() -> ctx);
|
||||
assertThat(context).hasSingleBean(OAuth2FeignRequestInterceptor.class);
|
||||
}
|
||||
|
||||
private void assertAccessTokenProviderInterceptorExists(ConfigurableApplicationContext ctx,
|
||||
Class<? extends ClientHttpRequestInterceptor> clazz) {
|
||||
AssertableApplicationContext context = AssertableApplicationContext.get(() -> ctx);
|
||||
assertThat(context).getBean(OAuth2FeignRequestInterceptor.class).extracting("accessTokenProvider")
|
||||
.extracting("interceptors").asList().first().isInstanceOf(clazz);
|
||||
}
|
||||
|
||||
private void assertAccessTokenProviderInterceptorNotExists(ConfigurableApplicationContext ctx,
|
||||
Class<? extends ClientHttpRequestInterceptor> clazz) {
|
||||
AssertableApplicationContext context = AssertableApplicationContext.get(() -> ctx);
|
||||
assertThat(context).getBean(OAuth2FeignRequestInterceptor.class).extracting("accessTokenProvider")
|
||||
.extracting("interceptors").asList().filteredOn(obj -> clazz.isAssignableFrom(obj.getClass()))
|
||||
.isEmpty();
|
||||
}
|
||||
|
||||
private void assertOnlyOneTargeterPresent(ConfigurableApplicationContext ctx, Class<?> beanClass) {
|
||||
assertThat(ctx.getBeansOfType(Targeter.class)).hasSize(1).hasValueSatisfying(new Condition<>(
|
||||
beanClass::isInstance, String.format("Targeter should be an instance of %s", beanClass)));
|
||||
@@ -178,14 +108,4 @@ class FeignAutoConfigurationTests {
|
||||
|
||||
}
|
||||
|
||||
static class CustomOAuth2FeignRequestInterceptorConfigurer implements OAuth2FeignRequestInterceptorConfigurer {
|
||||
|
||||
@Override
|
||||
public void customize(OAuth2FeignRequestInterceptorBuilder requestInterceptorBuilder) {
|
||||
requestInterceptorBuilder
|
||||
.withAccessTokenProviderInterceptors(new BasicAuthenticationInterceptor("username", "password"));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+15
-96
@@ -17,56 +17,35 @@
|
||||
package org.springframework.cloud.openfeign;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import feign.Client;
|
||||
import feign.Feign;
|
||||
import feign.Logger;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.junit.Test;
|
||||
|
||||
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Import;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.util.ReflectionUtils;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.doCallRealMethod;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.spy;
|
||||
|
||||
/**
|
||||
* @author Matt King
|
||||
* @author Sam Kruglov
|
||||
* @author Felix Dittrich
|
||||
* @author Olga Maciaszek-Sharma
|
||||
*/
|
||||
class FeignBuilderCustomizerTests {
|
||||
|
||||
private static final Targeter targeterSpy = spy(DefaultTargeter.class);
|
||||
|
||||
private static final Client defaultClient = mock(Client.class);
|
||||
public class FeignBuilderCustomizerTests {
|
||||
|
||||
@Test
|
||||
void testBuilderCustomizer() {
|
||||
ArgumentCaptor<Feign.Builder> feignBuilderCaptor = ArgumentCaptor.forClass(Feign.Builder.class);
|
||||
doCallRealMethod().when(targeterSpy).target(any(), feignBuilderCaptor.capture(), any(), any());
|
||||
|
||||
public void testBuilderCustomizer() {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
|
||||
FeignBuilderCustomizerTests.SampleConfiguration2.class);
|
||||
|
||||
FeignClientFactoryBean clientFactoryBean = context.getBean(FeignClientFactoryBean.class);
|
||||
clientFactoryBean.getTarget();
|
||||
FeignContext feignContext = context.getBean(FeignContext.class);
|
||||
|
||||
Assertions.assertNotNull(feignBuilderCaptor.getValue());
|
||||
Feign.Builder builder = feignBuilderCaptor.getValue();
|
||||
Feign.Builder builder = clientFactoryBean.feign(feignContext);
|
||||
assertFeignBuilderField(builder, "logLevel", Logger.Level.HEADERS);
|
||||
assertFeignBuilderField(builder, "decode404", true);
|
||||
|
||||
@@ -82,18 +61,14 @@ class FeignBuilderCustomizerTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testBuildCustomizerOrdered() {
|
||||
ArgumentCaptor<Feign.Builder> feignBuilderCaptor = ArgumentCaptor.forClass(Feign.Builder.class);
|
||||
doCallRealMethod().when(targeterSpy).target(any(), feignBuilderCaptor.capture(), any(), any());
|
||||
|
||||
public void testBuildCustomizerOrdered() {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
|
||||
FeignBuilderCustomizerTests.SampleConfiguration3.class);
|
||||
|
||||
FeignClientFactoryBean clientFactoryBean = context.getBean(FeignClientFactoryBean.class);
|
||||
clientFactoryBean.getTarget();
|
||||
FeignContext feignContext = context.getBean(FeignContext.class);
|
||||
|
||||
Assertions.assertNotNull(feignBuilderCaptor.getValue());
|
||||
Feign.Builder builder = feignBuilderCaptor.getValue();
|
||||
Feign.Builder builder = clientFactoryBean.feign(feignContext);
|
||||
assertFeignBuilderField(builder, "logLevel", Logger.Level.FULL);
|
||||
assertFeignBuilderField(builder, "decode404", true);
|
||||
|
||||
@@ -101,20 +76,16 @@ class FeignBuilderCustomizerTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testBuildCustomizerOrderedWithAdditional() {
|
||||
ArgumentCaptor<Feign.Builder> feignBuilderCaptor = ArgumentCaptor.forClass(Feign.Builder.class);
|
||||
doCallRealMethod().when(targeterSpy).target(any(), feignBuilderCaptor.capture(), any(), any());
|
||||
|
||||
public void testBuildCustomizerOrderedWithAdditional() {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
|
||||
FeignBuilderCustomizerTests.SampleConfiguration3.class);
|
||||
|
||||
FeignClientFactoryBean clientFactoryBean = context.getBean(FeignClientFactoryBean.class);
|
||||
clientFactoryBean.addCustomizer(builder -> builder.logLevel(Logger.Level.BASIC));
|
||||
clientFactoryBean.addCustomizer(Feign.Builder::doNotCloseAfterDecode);
|
||||
clientFactoryBean.getTarget();
|
||||
FeignContext feignContext = context.getBean(FeignContext.class);
|
||||
|
||||
Assertions.assertNotNull(feignBuilderCaptor.getValue());
|
||||
Feign.Builder builder = feignBuilderCaptor.getValue();
|
||||
Feign.Builder builder = clientFactoryBean.feign(feignContext);
|
||||
assertFeignBuilderField(builder, "logLevel", Logger.Level.BASIC);
|
||||
assertFeignBuilderField(builder, "decode404", true);
|
||||
assertFeignBuilderField(builder, "closeAfterDecode", false);
|
||||
@@ -122,41 +93,16 @@ class FeignBuilderCustomizerTests {
|
||||
context.close();
|
||||
}
|
||||
|
||||
@ParameterizedTest(name = "should use custom HttpClient with config: {0}")
|
||||
@MethodSource("testConfiguration")
|
||||
void testBuildCustomizerWithCustomHttpClient(Class configClass) {
|
||||
ArgumentCaptor<Feign.Builder> feignBuilderCaptor = ArgumentCaptor.forClass(Feign.Builder.class);
|
||||
doCallRealMethod().when(targeterSpy).target(any(), feignBuilderCaptor.capture(), any(), any());
|
||||
Client customClientMock = mock(Client.class);
|
||||
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(configClass);
|
||||
FeignClientFactoryBean clientFactoryBean = context.getBean(FeignClientFactoryBean.class);
|
||||
clientFactoryBean.addCustomizer(builder -> builder.client(customClientMock));
|
||||
clientFactoryBean.getTarget();
|
||||
|
||||
Assertions.assertNotNull(feignBuilderCaptor.getValue());
|
||||
Feign.Builder builder = feignBuilderCaptor.getValue();
|
||||
assertFeignBuilderField(builder, "client", customClientMock);
|
||||
|
||||
context.close();
|
||||
}
|
||||
|
||||
private static FeignClientFactoryBean defaultFeignClientFactoryBean(String url) {
|
||||
private static FeignClientFactoryBean defaultFeignClientFactoryBean() {
|
||||
FeignClientFactoryBean feignClientFactoryBean = new FeignClientFactoryBean();
|
||||
feignClientFactoryBean.setContextId("test");
|
||||
feignClientFactoryBean.setName("test");
|
||||
feignClientFactoryBean.setType(FeignClientFactoryTests.TestType.class);
|
||||
feignClientFactoryBean.setPath("");
|
||||
if (url != null) {
|
||||
feignClientFactoryBean.setUrl(url);
|
||||
}
|
||||
feignClientFactoryBean.setUrl("http://some.absolute.url");
|
||||
return feignClientFactoryBean;
|
||||
}
|
||||
|
||||
private static Stream<Class> testConfiguration() {
|
||||
return Stream.of(SampleConfiguration3.class, LoadBalancedSampleConfiguration.class);
|
||||
}
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@Import(FeignClientsConfiguration.class)
|
||||
protected static class SampleConfiguration2 {
|
||||
@@ -183,12 +129,7 @@ class FeignBuilderCustomizerTests {
|
||||
|
||||
@Bean
|
||||
FeignClientFactoryBean feignClientFactoryBean() {
|
||||
return defaultFeignClientFactoryBean("http://some.absolute.url");
|
||||
}
|
||||
|
||||
@Bean
|
||||
Targeter targeter() {
|
||||
return targeterSpy;
|
||||
return defaultFeignClientFactoryBean();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -226,29 +167,7 @@ class FeignBuilderCustomizerTests {
|
||||
|
||||
@Bean
|
||||
FeignClientFactoryBean feignClientFactoryBean() {
|
||||
return defaultFeignClientFactoryBean("http://some.absolute.url");
|
||||
}
|
||||
|
||||
@Bean
|
||||
Targeter targeter() {
|
||||
return targeterSpy;
|
||||
}
|
||||
|
||||
@Bean
|
||||
Client client() {
|
||||
return defaultClient;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@Import(SampleConfiguration3.class)
|
||||
protected static class LoadBalancedSampleConfiguration {
|
||||
|
||||
@Primary
|
||||
@Bean
|
||||
FeignClientFactoryBean feignClientFactoryBean() {
|
||||
return defaultFeignClientFactoryBean(null);
|
||||
return defaultFeignClientFactoryBean();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+25
-19
@@ -25,8 +25,11 @@ import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import feign.Feign;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.hamcrest.Matchers;
|
||||
import org.junit.Before;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.rules.ExpectedException;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import org.springframework.cloud.openfeign.testclients.TestClient;
|
||||
@@ -34,14 +37,15 @@ import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.util.ReflectionUtils;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
|
||||
|
||||
/**
|
||||
* @author Sven Döring
|
||||
* @author Sam Kruglov
|
||||
* @author Szymon Linowski
|
||||
*/
|
||||
class FeignClientBuilderTests {
|
||||
public class FeignClientBuilderTests {
|
||||
|
||||
@Rule
|
||||
public ExpectedException thrown = ExpectedException.none();
|
||||
|
||||
private FeignClientBuilder feignClientBuilder;
|
||||
|
||||
@@ -71,14 +75,14 @@ class FeignClientBuilderTests {
|
||||
return (T) ReflectionUtils.getField(field, factoryBean);
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
@Before
|
||||
public void setUp() {
|
||||
this.applicationContext = Mockito.mock(ApplicationContext.class);
|
||||
this.feignClientBuilder = new FeignClientBuilder(this.applicationContext);
|
||||
}
|
||||
|
||||
@Test
|
||||
void safetyCheckForNewFieldsOnTheFeignClientAnnotation() {
|
||||
public void safetyCheckForNewFieldsOnTheFeignClientAnnotation() {
|
||||
final List<String> methodNames = new ArrayList();
|
||||
for (final Method method : FeignClient.class.getMethods()) {
|
||||
methodNames.add(method.getName());
|
||||
@@ -97,7 +101,7 @@ class FeignClientBuilderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void forType_preinitializedBuilder() {
|
||||
public void forType_preinitializedBuilder() {
|
||||
// when:
|
||||
final FeignClientBuilder.Builder builder = this.feignClientBuilder.forType(TestFeignClient.class, "TestClient");
|
||||
|
||||
@@ -116,7 +120,7 @@ class FeignClientBuilderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void forType_allFieldsSetOnBuilder() {
|
||||
public void forType_allFieldsSetOnBuilder() {
|
||||
// when:
|
||||
final FeignClientBuilder.Builder builder = this.feignClientBuilder.forType(TestFeignClient.class, "TestClient")
|
||||
.decode404(true).url("Url/").path("/Path").contextId("TestContext");
|
||||
@@ -135,7 +139,7 @@ class FeignClientBuilderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void forType_clientFactoryBeanProvided() {
|
||||
public void forType_clientFactoryBeanProvided() {
|
||||
// when:
|
||||
final FeignClientBuilder.Builder builder = this.feignClientBuilder
|
||||
.forType(TestFeignClient.class, new FeignClientFactoryBean(), "TestClient").decode404(true)
|
||||
@@ -156,19 +160,21 @@ class FeignClientBuilderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void forType_build() {
|
||||
public void forType_build() {
|
||||
// given:
|
||||
Mockito.when(this.applicationContext.getBean(FeignContext.class)).thenThrow(new ClosedFileSystemException()); // throw
|
||||
// an
|
||||
// unusual
|
||||
// exception
|
||||
// in
|
||||
// the
|
||||
// FeignClientFactoryBean
|
||||
// an
|
||||
// unusual
|
||||
// exception
|
||||
// in
|
||||
// the
|
||||
// FeignClientFactoryBean
|
||||
final FeignClientBuilder.Builder builder = this.feignClientBuilder.forType(TestClient.class, "TestClient");
|
||||
|
||||
// expect: 'the build will fail right after calling build() with the mocked
|
||||
// unusual exception'
|
||||
assertThatExceptionOfType(ClosedFileSystemException.class).isThrownBy(() -> builder.build());
|
||||
this.thrown.expect(Matchers.isA(ClosedFileSystemException.class));
|
||||
builder.build();
|
||||
}
|
||||
|
||||
private interface TestFeignClient {
|
||||
|
||||
-123
@@ -1,123 +0,0 @@
|
||||
/*
|
||||
* Copyright 2020-2022 the original author 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.net.UnknownHostException;
|
||||
|
||||
import feign.Contract;
|
||||
import feign.RequestLine;
|
||||
import feign.RetryableException;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
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.cache.CacheManager;
|
||||
import org.springframework.cache.annotation.Cacheable;
|
||||
import org.springframework.cache.annotation.EnableCaching;
|
||||
import org.springframework.cache.interceptor.SimpleKey;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.test.annotation.DirtiesContext;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
|
||||
|
||||
/**
|
||||
* @author Sam Kruglov
|
||||
*/
|
||||
@SpringBootTest(classes = FeignClientCacheTests.TestConfiguration.class)
|
||||
@DirtiesContext
|
||||
public class FeignClientCacheTests {
|
||||
|
||||
private static final String CACHE_NAME = "foo-cache";
|
||||
|
||||
@Autowired
|
||||
private FooClient foo;
|
||||
|
||||
@Test
|
||||
void cacheExists(@Autowired CacheManager cacheManager) {
|
||||
assertThat(cacheManager.getCache(CACHE_NAME)).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void interceptedCallsReal() {
|
||||
assertThatExceptionOfType(RetryableException.class).isThrownBy(foo::getWithCache)
|
||||
.withRootCauseInstanceOf(UnknownHostException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void nonInterceptedCallsReal() {
|
||||
assertThatExceptionOfType(RetryableException.class).isThrownBy(foo::getWithoutCache)
|
||||
.withRootCauseInstanceOf(UnknownHostException.class);
|
||||
}
|
||||
|
||||
@Nested
|
||||
class givenCached {
|
||||
|
||||
String cachedValue = "cached";
|
||||
|
||||
@BeforeEach
|
||||
void setUp(@Autowired CacheManager cacheManager) {
|
||||
cacheManager.getCache(CACHE_NAME).put(SimpleKey.EMPTY, cachedValue);
|
||||
}
|
||||
|
||||
@Test
|
||||
void interceptedReturnsCached() {
|
||||
assertThat(foo.getWithCache()).isSameAs(cachedValue);
|
||||
}
|
||||
|
||||
@Test
|
||||
void nonInterceptedCallsReal() {
|
||||
assertThatExceptionOfType(RetryableException.class).isThrownBy(foo::getWithoutCache)
|
||||
.withRootCauseInstanceOf(UnknownHostException.class);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@EnableFeignClients(clients = FooClient.class)
|
||||
@EnableAutoConfiguration
|
||||
@EnableCaching
|
||||
protected static class TestConfiguration {
|
||||
|
||||
}
|
||||
|
||||
@FeignClient(name = "foo", url = "http://foo", configuration = FooConfiguration.class)
|
||||
interface FooClient {
|
||||
|
||||
@RequestLine("GET /with-cache")
|
||||
@Cacheable(cacheNames = CACHE_NAME)
|
||||
String getWithCache();
|
||||
|
||||
@RequestLine("GET /without-cache")
|
||||
String getWithoutCache();
|
||||
|
||||
}
|
||||
|
||||
public static class FooConfiguration {
|
||||
|
||||
@Bean
|
||||
Contract feignContract() {
|
||||
return new Contract.Default();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
-5
@@ -24,7 +24,6 @@ import feign.Capability;
|
||||
import feign.Contract;
|
||||
import feign.ExceptionPropagationPolicy;
|
||||
import feign.Logger;
|
||||
import feign.QueryMapEncoder;
|
||||
import feign.RequestInterceptor;
|
||||
import feign.Retryer;
|
||||
import feign.codec.Decoder;
|
||||
@@ -44,7 +43,6 @@ import static org.springframework.cloud.openfeign.test.EqualsAndHashCodeAssert.a
|
||||
|
||||
/**
|
||||
* @author Jonatan Ivanov
|
||||
* @author Hyeonmin Park
|
||||
*/
|
||||
class FeignClientConfigurationTests {
|
||||
|
||||
@@ -66,7 +64,6 @@ class FeignClientConfigurationTests {
|
||||
assertThat(config.getContract()).isNull();
|
||||
assertThat(config.getExceptionPropagationPolicy()).isNull();
|
||||
assertThat(config.getCapabilities()).isNull();
|
||||
assertThat(config.getQueryMapEncoder()).isNull();
|
||||
assertThat(config.getMetrics()).isNull();
|
||||
}
|
||||
|
||||
@@ -91,7 +88,6 @@ class FeignClientConfigurationTests {
|
||||
config.setExceptionPropagationPolicy(ExceptionPropagationPolicy.UNWRAP);
|
||||
List<Class<Capability>> capabilities = Lists.list(Capability.class);
|
||||
config.setCapabilities(capabilities);
|
||||
config.setQueryMapEncoder(QueryMapEncoder.class);
|
||||
FeignClientProperties.MetricsProperties metrics = new FeignClientProperties.MetricsProperties();
|
||||
config.setMetrics(metrics);
|
||||
|
||||
@@ -109,7 +105,6 @@ class FeignClientConfigurationTests {
|
||||
assertThat(config.getContract()).isSameAs(Contract.class);
|
||||
assertThat(config.getExceptionPropagationPolicy()).isSameAs(ExceptionPropagationPolicy.UNWRAP);
|
||||
assertThat(config.getCapabilities()).isSameAs(capabilities);
|
||||
assertThat(config.getQueryMapEncoder()).isSameAs(QueryMapEncoder.class);
|
||||
assertThat(config.getMetrics()).isSameAs(metrics);
|
||||
}
|
||||
|
||||
|
||||
+8
-5
@@ -24,7 +24,8 @@ import feign.Feign;
|
||||
import feign.Logger;
|
||||
import feign.RequestInterceptor;
|
||||
import feign.micrometer.MicrometerCapability;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
|
||||
@@ -34,6 +35,7 @@ import org.springframework.cloud.openfeign.clientconfig.FeignClientConfigurer;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.test.annotation.DirtiesContext;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.util.ReflectionUtils;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
@@ -43,11 +45,12 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
* @author Jonatan Ivanov
|
||||
*/
|
||||
@DirtiesContext
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@SpringBootTest(classes = FeignClientUsingConfigurerTest.Application.class, value = {
|
||||
"feign.client.config.default.loggerLevel=full",
|
||||
"feign.client.config.default.requestInterceptors[0]=org.springframework.cloud.openfeign.FeignClientUsingPropertiesTests.FooRequestInterceptor",
|
||||
"feign.client.config.default.requestInterceptors[1]=org.springframework.cloud.openfeign.FeignClientUsingPropertiesTests.BarRequestInterceptor" })
|
||||
class FeignClientUsingConfigurerTest {
|
||||
public class FeignClientUsingConfigurerTest {
|
||||
|
||||
private static final String BEAN_NAME_PREFIX = "org.springframework.cloud.openfeign.FeignClientUsingConfigurerTest$";
|
||||
|
||||
@@ -58,7 +61,7 @@ class FeignClientUsingConfigurerTest {
|
||||
private FeignContext context;
|
||||
|
||||
@Test
|
||||
void testFeignClient() {
|
||||
public void testFeignClient() {
|
||||
FeignClientFactoryBean factoryBean = (FeignClientFactoryBean) beanFactory
|
||||
.getBeanDefinition(BEAN_NAME_PREFIX + "TestFeignClient")
|
||||
.getAttribute("feignClientsRegistrarFactoryBean");
|
||||
@@ -81,7 +84,7 @@ class FeignClientUsingConfigurerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testNoInheritFeignClient() {
|
||||
public void testNoInheritFeignClient() {
|
||||
FeignClientFactoryBean factoryBean = (FeignClientFactoryBean) beanFactory
|
||||
.getBeanDefinition(BEAN_NAME_PREFIX + "NoInheritFeignClient")
|
||||
.getAttribute("feignClientsRegistrarFactoryBean");
|
||||
@@ -97,7 +100,7 @@ class FeignClientUsingConfigurerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testNoInheritFeignClient_ignoreProperties() {
|
||||
public void testNoInheritFeignClient_ignoreProperties() {
|
||||
FeignClientFactoryBean factoryBean = (FeignClientFactoryBean) beanFactory
|
||||
.getBeanDefinition(BEAN_NAME_PREFIX + "NoInheritFeignClient")
|
||||
.getAttribute("feignClientsRegistrarFactoryBean");
|
||||
|
||||
-24
@@ -37,7 +37,6 @@ import javax.servlet.http.HttpServletRequest;
|
||||
import feign.Capability;
|
||||
import feign.Feign;
|
||||
import feign.InvocationHandlerFactory;
|
||||
import feign.QueryMapEncoder;
|
||||
import feign.Request;
|
||||
import feign.RequestInterceptor;
|
||||
import feign.RequestTemplate;
|
||||
@@ -79,7 +78,6 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
|
||||
* @author Olga Maciaszek-Sharma
|
||||
* @author Ilia Ilinykh
|
||||
* @author Jonatan Ivanov
|
||||
* @author Hyeonmin Park
|
||||
*/
|
||||
@SuppressWarnings("FieldMayBeFinal")
|
||||
@SpringBootTest(classes = FeignClientUsingPropertiesTests.Application.class, webEnvironment = RANDOM_PORT)
|
||||
@@ -248,19 +246,6 @@ public class FeignClientUsingPropertiesTests {
|
||||
.hasAtLeastOneElementOfType(MicrometerCapability.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void clientShouldContainQueryMapEncoder() {
|
||||
fooFactoryBean.setApplicationContext(applicationContext);
|
||||
Feign.Builder feignBuilder = fooFactoryBean.feign(context);
|
||||
FooClient fooClient = feignBuilder.target(FooClient.class, "http://localhost:" + port);
|
||||
|
||||
String response = fooClient.foo();
|
||||
assertThat(response).isEqualTo("OK");
|
||||
QueryMapEncoder queryMapEncoder = (QueryMapEncoder) ReflectionTestUtils.getField(feignBuilder,
|
||||
"queryMapEncoder");
|
||||
assertThat(queryMapEncoder).isInstanceOf(NoOpQueryMapEncoder.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisabledForJreRange(min = JRE.JAVA_16)
|
||||
public void shouldSetFollowRedirects() {
|
||||
@@ -433,13 +418,4 @@ public class FeignClientUsingPropertiesTests {
|
||||
|
||||
}
|
||||
|
||||
public static class NoOpQueryMapEncoder implements QueryMapEncoder {
|
||||
|
||||
@Override
|
||||
public Map<String, Object> encode(Object o) {
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+37
-60
@@ -18,22 +18,17 @@ package org.springframework.cloud.openfeign;
|
||||
|
||||
import java.util.Collections;
|
||||
|
||||
import feign.Target;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.condition.DisabledForJreRange;
|
||||
import org.junit.jupiter.api.condition.JRE;
|
||||
import org.junit.Test;
|
||||
|
||||
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
|
||||
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.mock.env.MockEnvironment;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatCode;
|
||||
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
|
||||
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
|
||||
|
||||
/**
|
||||
@@ -43,42 +38,42 @@ import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
|
||||
* @author Szymon Linowski
|
||||
* @author Olga Maciaszek-Sharma
|
||||
*/
|
||||
class FeignClientsRegistrarTests {
|
||||
public class FeignClientsRegistrarTests {
|
||||
|
||||
@Test
|
||||
void badNameHttpPrefix() {
|
||||
assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() -> testGetName("http://bad_hostname"));
|
||||
@Test(expected = IllegalStateException.class)
|
||||
public void badNameHttpPrefix() {
|
||||
testGetName("https://bad_hostname");
|
||||
}
|
||||
|
||||
@Test(expected = IllegalStateException.class)
|
||||
public void badNameHttpsPrefix() {
|
||||
testGetName("https://bad_hostname");
|
||||
}
|
||||
|
||||
@Test(expected = IllegalStateException.class)
|
||||
public void badName() {
|
||||
testGetName("bad_hostname");
|
||||
}
|
||||
|
||||
@Test(expected = IllegalStateException.class)
|
||||
public void badNameStartsWithHttp() {
|
||||
testGetName("http_bad_hostname");
|
||||
}
|
||||
|
||||
@Test
|
||||
void badNameHttpsPrefix() {
|
||||
assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() -> testGetName("https://bad_hostname"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void badName() {
|
||||
assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() -> testGetName("bad_hostname"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void badNameStartsWithHttp() {
|
||||
assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() -> testGetName("http_bad_hostname"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void goodName() {
|
||||
public void goodName() {
|
||||
String name = testGetName("good-name");
|
||||
assertThat(name).as("name was wrong").isEqualTo("good-name");
|
||||
}
|
||||
|
||||
@Test
|
||||
void goodNameHttpPrefix() {
|
||||
public void goodNameHttpPrefix() {
|
||||
String name = testGetName("https://good-name");
|
||||
assertThat(name).as("name was wrong").isEqualTo("https://good-name");
|
||||
}
|
||||
|
||||
@Test
|
||||
void goodNameHttpsPrefix() {
|
||||
public void goodNameHttpsPrefix() {
|
||||
String name = testGetName("https://goodname");
|
||||
assertThat(name).as("name was wrong").isEqualTo("https://goodname");
|
||||
}
|
||||
@@ -89,46 +84,28 @@ class FeignClientsRegistrarTests {
|
||||
return registrar.getName(Collections.singletonMap("name", name));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testFallback() {
|
||||
assertThatExceptionOfType(IllegalArgumentException.class)
|
||||
.isThrownBy(() -> new AnnotationConfigApplicationContext(FallbackTestConfig.class));
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testFallback() {
|
||||
new AnnotationConfigApplicationContext(FallbackTestConfig.class);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testFallbackFactory() {
|
||||
new AnnotationConfigApplicationContext(FallbackFactoryTestConfig.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testFallbackFactory() {
|
||||
assertThatExceptionOfType(IllegalArgumentException.class)
|
||||
.isThrownBy(() -> new AnnotationConfigApplicationContext(FallbackFactoryTestConfig.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldPassSubLevelFeignClient() {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
|
||||
((DefaultListableBeanFactory) context.getBeanFactory()).setAllowBeanDefinitionOverriding(false);
|
||||
context.register(TopLevelSubLevelTestConfig.class);
|
||||
assertThatCode(context::refresh)
|
||||
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();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisabledForJreRange(min = JRE.JAVA_16)
|
||||
void shouldResolveNullUrl() {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
|
||||
context.register(NullUrlFeignClientTestConfig.class);
|
||||
context.refresh();
|
||||
|
||||
Object feignClientBean = context.getBean(NullUrlFeignClient.class);
|
||||
|
||||
Object invocationHandlerLambda = ReflectionTestUtils.getField(feignClientBean, "h");
|
||||
Target.HardCodedTarget<NullUrlFeignClient> target = (Target.HardCodedTarget<NullUrlFeignClient>) ReflectionTestUtils
|
||||
.getField(invocationHandlerLambda, "arg$3");
|
||||
assertThat(target.name()).isEqualTo("nullUrlFeignClient");
|
||||
assertThat(target.url()).isEqualTo("http://nullUrlFeignClient");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldResolveAndValidateNullName() {
|
||||
public void shouldResolveAndValidateNullName() {
|
||||
assertThatIllegalStateException().isThrownBy(() -> {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
|
||||
context.register(NullExpressionNameFeignClientTestConfig.class);
|
||||
|
||||
+8
-3
@@ -21,7 +21,8 @@ import java.util.Map;
|
||||
import feign.Client;
|
||||
import feign.RequestInterceptor;
|
||||
import feign.httpclient.ApacheHttpClient;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.autoconfigure.AutoConfigurations;
|
||||
@@ -31,6 +32,8 @@ import org.springframework.cloud.openfeign.encoding.FeignAcceptGzipEncodingAutoC
|
||||
import org.springframework.cloud.openfeign.encoding.FeignAcceptGzipEncodingInterceptor;
|
||||
import org.springframework.cloud.openfeign.encoding.FeignContentGzipEncodingAutoConfiguration;
|
||||
import org.springframework.cloud.openfeign.encoding.FeignContentGzipEncodingInterceptor;
|
||||
import org.springframework.cloud.test.ClassPathExclusions;
|
||||
import org.springframework.cloud.test.ModifiedClassPathRunner;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@@ -40,10 +43,12 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
* @author Ryan Baxter
|
||||
* @author Biju Kunjummen
|
||||
*/
|
||||
class FeignCompressionTests {
|
||||
@RunWith(ModifiedClassPathRunner.class)
|
||||
@ClassPathExclusions({ "ribbon-loadbalancer-{version:\\d.*}.jar" })
|
||||
public class FeignCompressionTests {
|
||||
|
||||
@Test
|
||||
void testInterceptors() {
|
||||
public void testInterceptors() {
|
||||
new ApplicationContextRunner()
|
||||
.withPropertyValues("feign.compression.response.enabled=true", "feign.compression.request.enabled=true",
|
||||
"feign.okhttp.enabled=false")
|
||||
|
||||
+6
-6
@@ -21,7 +21,7 @@ import java.util.Collection;
|
||||
import feign.Logger;
|
||||
import feign.RequestInterceptor;
|
||||
import org.assertj.core.util.Lists;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.Test;
|
||||
|
||||
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
@@ -30,10 +30,10 @@ import org.springframework.context.annotation.Import;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class FeignContextTest {
|
||||
public class FeignContextTest {
|
||||
|
||||
@Test
|
||||
void getInstanceWithoutAncestors_verifyNullForMissing() {
|
||||
public void getInstanceWithoutAncestors_verifyNullForMissing() {
|
||||
AnnotationConfigApplicationContext parent = new AnnotationConfigApplicationContext();
|
||||
parent.refresh();
|
||||
|
||||
@@ -51,7 +51,7 @@ class FeignContextTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void getInstancesWithoutAncestors_verifyEmptyForMissing() {
|
||||
public void getInstancesWithoutAncestors_verifyEmptyForMissing() {
|
||||
AnnotationConfigApplicationContext parent = new AnnotationConfigApplicationContext();
|
||||
parent.refresh();
|
||||
|
||||
@@ -66,7 +66,7 @@ class FeignContextTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void getInstanceWithoutAncestors() {
|
||||
public void getInstanceWithoutAncestors() {
|
||||
AnnotationConfigApplicationContext parent = new AnnotationConfigApplicationContext();
|
||||
parent.refresh();
|
||||
|
||||
@@ -80,7 +80,7 @@ class FeignContextTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void getInstancesWithoutAncestors() {
|
||||
public void getInstancesWithoutAncestors() {
|
||||
AnnotationConfigApplicationContext parent = new AnnotationConfigApplicationContext();
|
||||
parent.refresh();
|
||||
|
||||
|
||||
+5
-5
@@ -18,7 +18,7 @@ package org.springframework.cloud.openfeign;
|
||||
|
||||
import feign.Response;
|
||||
import feign.codec.ErrorDecoder;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.Test;
|
||||
|
||||
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
@@ -30,10 +30,10 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
/**
|
||||
* @author Michael Cramer
|
||||
*/
|
||||
class FeignErrorDecoderFactoryTests {
|
||||
public class FeignErrorDecoderFactoryTests {
|
||||
|
||||
@Test
|
||||
void testNoDefaultFactory() {
|
||||
public void testNoDefaultFactory() {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SampleConfiguration1.class);
|
||||
String[] beanNamesForType = context.getBeanNamesForType(FeignErrorDecoderFactory.class);
|
||||
assertThat(beanNamesForType).isEmpty();
|
||||
@@ -41,7 +41,7 @@ class FeignErrorDecoderFactoryTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCustomErrorDecoderFactory() {
|
||||
public void testCustomErrorDecoderFactory() {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SampleConfiguration2.class);
|
||||
FeignErrorDecoderFactory errorDecoderFactory = context.getBean(FeignErrorDecoderFactory.class);
|
||||
assertThat(errorDecoderFactory).isNotNull();
|
||||
@@ -52,7 +52,7 @@ class FeignErrorDecoderFactoryTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCustomErrorDecoderFactoryNotOverwritingErrorDecoder() {
|
||||
public void testCustomErrorDecoderFactoryNotOverwritingErrorDecoder() {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SampleConfiguration3.class);
|
||||
FeignErrorDecoderFactory errorDecoderFactory = context.getBean(FeignErrorDecoderFactory.class);
|
||||
assertThat(errorDecoderFactory).isNotNull();
|
||||
|
||||
+59
-50
@@ -22,12 +22,14 @@ import feign.httpclient.ApacheHttpClient;
|
||||
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
|
||||
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
|
||||
import org.apache.hc.client5.http.io.HttpClientConnectionManager;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
import org.springframework.boot.WebApplicationType;
|
||||
import org.springframework.boot.builder.SpringApplicationBuilder;
|
||||
import org.springframework.cloud.commons.httpclient.HttpClientConfiguration;
|
||||
import org.springframework.cloud.test.ClassPathExclusions;
|
||||
import org.springframework.cloud.test.ModifiedClassPathRunner;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
@@ -35,7 +37,7 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
/**
|
||||
* @author Nguyen Ky Thanh
|
||||
*/
|
||||
class FeignHttpClient5ConfigurationTests {
|
||||
public class FeignHttpClient5ConfigurationTests {
|
||||
|
||||
private static void verifyHc4BeansAvailable(ConfigurableApplicationContext context) {
|
||||
org.apache.http.impl.client.CloseableHttpClient httpClient4 = context
|
||||
@@ -57,55 +59,62 @@ class FeignHttpClient5ConfigurationTests {
|
||||
assertThat(client).isInstanceOf(ApacheHttp5Client.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void verifyHttpClient5AutoConfig() {
|
||||
ConfigurableApplicationContext context = new SpringApplicationBuilder()
|
||||
.properties("feign.httpclient.hc5.enabled=true", "feign.httpclient.enabled=false")
|
||||
.web(WebApplicationType.NONE).sources(HttpClientConfiguration.class, FeignAutoConfiguration.class)
|
||||
.run();
|
||||
|
||||
verifyHc5BeansAvailable(context);
|
||||
|
||||
if (context != null) {
|
||||
context.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void hc5ShouldWinIfTheBothVersionsAvailable() {
|
||||
ConfigurableApplicationContext context = new SpringApplicationBuilder()
|
||||
.properties("feign.httpclient.hc5.enabled=true", "feign.httpclient.enabled=true")
|
||||
.web(WebApplicationType.NONE).sources(HttpClientConfiguration.class, FeignAutoConfiguration.class)
|
||||
.run();
|
||||
|
||||
Client client = context.getBean(Client.class);
|
||||
assertThat(client).isInstanceOf(ApacheHttp5Client.class);
|
||||
|
||||
if (context != null) {
|
||||
context.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void hc4ShouldBeTheDefaultIfHc5NotEnabled() {
|
||||
ConfigurableApplicationContext context = new SpringApplicationBuilder()
|
||||
.properties("feign.httpclient.hc5.enabled=false", "feign.httpclient.enabled=true")
|
||||
.web(WebApplicationType.NONE).sources(HttpClientConfiguration.class, FeignAutoConfiguration.class)
|
||||
.run();
|
||||
|
||||
verifyHc4BeansAvailable(context);
|
||||
|
||||
if (context != null) {
|
||||
context.close();
|
||||
}
|
||||
}
|
||||
|
||||
@ClassPathExclusions({ "feign-hc5-{version:\\d.*}.jar", "httpclient5-{version:\\d.*}.jar",
|
||||
"httpcore5-{version:\\d.*}.jar", "httpcore5-h2-{version:\\d.*}.jar" })
|
||||
static class WithoutLoadBalancerAndHc5InClasspath {
|
||||
@RunWith(ModifiedClassPathRunner.class)
|
||||
@ClassPathExclusions("ribbon-loadbalancer-{version:\\d.*}.jar")
|
||||
public static class WithoutLoadBalancerInClasspath {
|
||||
|
||||
@Test
|
||||
void hc4ShouldWinEvenHc5ConfigEnabled() {
|
||||
public void verifyHttpClient5AutoConfig() {
|
||||
ConfigurableApplicationContext context = new SpringApplicationBuilder()
|
||||
.properties("feign.httpclient.hc5.enabled=true", "feign.httpclient.enabled=false")
|
||||
.web(WebApplicationType.NONE).sources(HttpClientConfiguration.class, FeignAutoConfiguration.class)
|
||||
.run();
|
||||
|
||||
verifyHc5BeansAvailable(context);
|
||||
|
||||
if (context != null) {
|
||||
context.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void hc5ShouldWinIfTheBothVersionsAvailable() {
|
||||
ConfigurableApplicationContext context = new SpringApplicationBuilder()
|
||||
.properties("feign.httpclient.hc5.enabled=true", "feign.httpclient.enabled=true")
|
||||
.web(WebApplicationType.NONE).sources(HttpClientConfiguration.class, FeignAutoConfiguration.class)
|
||||
.run();
|
||||
|
||||
Client client = context.getBean(Client.class);
|
||||
assertThat(client).isInstanceOf(ApacheHttp5Client.class);
|
||||
|
||||
if (context != null) {
|
||||
context.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void hc4ShouldBeTheDefaultIfHc5NotEnabled() {
|
||||
ConfigurableApplicationContext context = new SpringApplicationBuilder()
|
||||
.properties("feign.httpclient.hc5.enabled=false", "feign.httpclient.enabled=true")
|
||||
.web(WebApplicationType.NONE).sources(HttpClientConfiguration.class, FeignAutoConfiguration.class)
|
||||
.run();
|
||||
|
||||
verifyHc4BeansAvailable(context);
|
||||
|
||||
if (context != null) {
|
||||
context.close();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@RunWith(ModifiedClassPathRunner.class)
|
||||
@ClassPathExclusions({ "ribbon-loadbalancer-{version:\\d.*}.jar", "feign-hc5-{version:\\d.*}.jar",
|
||||
"httpclient5-{version:\\d.*}.jar", "httpcore5-{version:\\d.*}.jar", "httpcore5-h2-{version:\\d.*}.jar" })
|
||||
public static class WithoutLoadBalancerAndHc5InClasspath {
|
||||
|
||||
@Test
|
||||
public void hc4ShouldWinEvenHc5ConfigEnabled() {
|
||||
ConfigurableApplicationContext context = new SpringApplicationBuilder()
|
||||
.properties("feign.httpclient.hc5.enabled=true").web(WebApplicationType.NONE)
|
||||
.sources(HttpClientConfiguration.class, FeignAutoConfiguration.class).run();
|
||||
@@ -118,7 +127,7 @@ class FeignHttpClient5ConfigurationTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void hc4ShouldBeTheDefault() {
|
||||
public void hc4ShouldBeTheDefault() {
|
||||
ConfigurableApplicationContext context = new SpringApplicationBuilder().web(WebApplicationType.NONE)
|
||||
.sources(HttpClientConfiguration.class, FeignAutoConfiguration.class).run();
|
||||
|
||||
|
||||
+14
-9
@@ -26,13 +26,16 @@ import org.apache.http.config.Lookup;
|
||||
import org.apache.http.conn.HttpClientConnectionManager;
|
||||
import org.apache.http.conn.socket.ConnectionSocketFactory;
|
||||
import org.apache.http.impl.conn.DefaultHttpClientConnectionOperator;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
import org.springframework.boot.WebApplicationType;
|
||||
import org.springframework.boot.builder.SpringApplicationBuilder;
|
||||
import org.springframework.cloud.commons.httpclient.HttpClientConfiguration;
|
||||
import org.springframework.cloud.test.ClassPathExclusions;
|
||||
import org.springframework.cloud.test.ModifiedClassPathRunner;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
import org.springframework.util.ReflectionUtils;
|
||||
|
||||
@@ -41,26 +44,28 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
/**
|
||||
* @author Ryan Baxter
|
||||
*/
|
||||
class FeignHttpClientConfigurationTests {
|
||||
@RunWith(ModifiedClassPathRunner.class)
|
||||
@ClassPathExclusions({ "ribbon-loadbalancer-{version:\\d.*}.jar" })
|
||||
public class FeignHttpClientConfigurationTests {
|
||||
|
||||
private ConfigurableApplicationContext context;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
@Before
|
||||
public void setUp() {
|
||||
this.context = new SpringApplicationBuilder()
|
||||
.properties("debug=true", "feign.httpclient.disableSslValidation=true").web(WebApplicationType.NONE)
|
||||
.sources(HttpClientConfiguration.class, FeignAutoConfiguration.class).run();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
@After
|
||||
public void tearDown() {
|
||||
if (this.context != null) {
|
||||
this.context.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void disableSslTest() {
|
||||
public void disableSslTest() throws Exception {
|
||||
try {
|
||||
HttpClientConnectionManager connectionManager = this.context.getBean(HttpClientConnectionManager.class);
|
||||
Lookup<ConnectionSocketFactory> socketFactoryRegistry = getConnectionSocketFactoryLookup(connectionManager);
|
||||
|
||||
+3
-2
@@ -48,8 +48,9 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
|
||||
* @author Olga Maciaszek-Sharma
|
||||
*/
|
||||
@SpringBootTest(classes = FeignHttpClientUrlTestsWithRetryableLoadBalancer.TestConfig.class,
|
||||
webEnvironment = DEFINED_PORT, value = { "spring.application.name=feignclienturlwithretryableloadbalancertest",
|
||||
"feign.hystrix.enabled=false", "feign.okhttp.enabled=false" })
|
||||
webEnvironment = DEFINED_PORT,
|
||||
value = { "spring.application.name=feignclienturlwithretryableloadbalancertest", "feign.hystrix.enabled=false",
|
||||
"feign.okhttp.enabled=false", "spring.cloud.loadbalancer.ribbon.enabled=false" })
|
||||
@DirtiesContext
|
||||
class FeignHttpClientUrlTestsWithRetryableLoadBalancer {
|
||||
|
||||
|
||||
+5
-5
@@ -18,7 +18,7 @@ package org.springframework.cloud.openfeign;
|
||||
|
||||
import feign.Logger;
|
||||
import feign.slf4j.Slf4jLogger;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.Test;
|
||||
|
||||
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
@@ -30,10 +30,10 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
/**
|
||||
* @author Venil Noronha
|
||||
*/
|
||||
class FeignLoggerFactoryTests {
|
||||
public class FeignLoggerFactoryTests {
|
||||
|
||||
@Test
|
||||
void testDefaultLogger() {
|
||||
public void testDefaultLogger() {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SampleConfiguration1.class);
|
||||
FeignLoggerFactory loggerFactory = context.getBean(FeignLoggerFactory.class);
|
||||
assertThat(loggerFactory).isNotNull();
|
||||
@@ -44,7 +44,7 @@ class FeignLoggerFactoryTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCustomLogger() {
|
||||
public void testCustomLogger() {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SampleConfiguration2.class);
|
||||
FeignLoggerFactory loggerFactory = context.getBean(FeignLoggerFactory.class);
|
||||
assertThat(loggerFactory).isNotNull();
|
||||
@@ -55,7 +55,7 @@ class FeignLoggerFactoryTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCustomLoggerFactory() {
|
||||
public void testCustomLoggerFactory() {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SampleConfiguration3.class);
|
||||
FeignLoggerFactory loggerFactory = context.getBean(FeignLoggerFactory.class);
|
||||
assertThat(loggerFactory).isNotNull();
|
||||
|
||||
+20
-22
@@ -21,14 +21,17 @@ import java.lang.reflect.Field;
|
||||
import javax.net.ssl.HostnameVerifier;
|
||||
|
||||
import okhttp3.OkHttpClient;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
import org.springframework.boot.WebApplicationType;
|
||||
import org.springframework.boot.builder.SpringApplicationBuilder;
|
||||
import org.springframework.cloud.commons.httpclient.HttpClientConfiguration;
|
||||
import org.springframework.cloud.commons.httpclient.OkHttpClientFactory;
|
||||
import org.springframework.cloud.test.ClassPathExclusions;
|
||||
import org.springframework.cloud.test.ModifiedClassPathRunner;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
import org.springframework.util.ReflectionUtils;
|
||||
|
||||
@@ -37,41 +40,36 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
/**
|
||||
* @author Ryan Baxter
|
||||
*/
|
||||
class FeignOkHttpConfigurationTests {
|
||||
@RunWith(ModifiedClassPathRunner.class)
|
||||
@ClassPathExclusions({ "ribbon-loadbalancer-{version:\\d.*}.jar" })
|
||||
public class FeignOkHttpConfigurationTests {
|
||||
|
||||
private ConfigurableApplicationContext context;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
@Before
|
||||
public void setUp() {
|
||||
this.context = new SpringApplicationBuilder()
|
||||
.properties("debug=true", "feign.httpclient.disableSslValidation=true", "feign.okhttp.enabled=true",
|
||||
"feign.httpclient.enabled=false", "feign.httpclient.okhttp.read-timeout=9s")
|
||||
"feign.httpclient.enabled=false")
|
||||
.web(WebApplicationType.NONE).sources(HttpClientConfiguration.class, FeignAutoConfiguration.class)
|
||||
.run();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
if (context != null) {
|
||||
context.close();
|
||||
@After
|
||||
public void tearDown() {
|
||||
if (this.context != null) {
|
||||
this.context.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void disableSslTest() {
|
||||
OkHttpClient httpClient = context.getBean(OkHttpClient.class);
|
||||
public void disableSslTest() throws Exception {
|
||||
OkHttpClient httpClient = this.context.getBean(OkHttpClient.class);
|
||||
HostnameVerifier hostnameVerifier = (HostnameVerifier) this.getField(httpClient, "hostnameVerifier");
|
||||
assertThat(hostnameVerifier instanceof OkHttpClientFactory.TrustAllHostnames).isTrue();
|
||||
assertThat(OkHttpClientFactory.TrustAllHostnames.class.isInstance(hostnameVerifier)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldConfigureReadTimeout() {
|
||||
OkHttpClient httpClient = context.getBean(OkHttpClient.class);
|
||||
|
||||
assertThat(httpClient.readTimeoutMillis()).isEqualTo(9000);
|
||||
}
|
||||
|
||||
protected Object getField(Object target, String name) {
|
||||
protected <T> Object getField(Object target, String name) {
|
||||
Field field = ReflectionUtils.findField(target.getClass(), name);
|
||||
ReflectionUtils.makeAccessible(field);
|
||||
Object value = ReflectionUtils.getField(field, target);
|
||||
|
||||
+19
-18
@@ -21,8 +21,8 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
import org.assertj.core.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||
@@ -37,6 +37,7 @@ import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.test.annotation.DirtiesContext;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@@ -45,12 +46,12 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
/**
|
||||
* @author Spencer Gibb
|
||||
* @author Olga Maciaszek-Sharma
|
||||
* @author Szymon Linowski
|
||||
*/
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@SpringBootTest(classes = SpringDecoderTests.Application.class, webEnvironment = WebEnvironment.RANDOM_PORT,
|
||||
value = { "spring.application.name=springdecodertest", "spring.jmx.enabled=false" })
|
||||
@DirtiesContext
|
||||
class SpringDecoderTests extends FeignClientFactoryBean {
|
||||
public class SpringDecoderTests extends FeignClientFactoryBean {
|
||||
|
||||
@Autowired
|
||||
FeignContext context;
|
||||
@@ -58,7 +59,7 @@ class SpringDecoderTests extends FeignClientFactoryBean {
|
||||
@LocalServerPort
|
||||
private int port = 0;
|
||||
|
||||
SpringDecoderTests() {
|
||||
public SpringDecoderTests() {
|
||||
setName("test");
|
||||
setContextId("test");
|
||||
}
|
||||
@@ -74,7 +75,7 @@ class SpringDecoderTests extends FeignClientFactoryBean {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testResponseEntity() {
|
||||
public void testResponseEntity() {
|
||||
ResponseEntity<Hello> response = testClient().getHelloResponse();
|
||||
assertThat(response).as("response was null").isNotNull();
|
||||
assertThat(response.getStatusCode()).as("wrong status code").isEqualTo(HttpStatus.OK);
|
||||
@@ -84,14 +85,14 @@ class SpringDecoderTests extends FeignClientFactoryBean {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSimpleType() {
|
||||
public void testSimpleType() {
|
||||
Hello hello = testClient().getHello();
|
||||
assertThat(hello).as("hello was null").isNotNull();
|
||||
assertThat(hello).as("first hello didn't match").isEqualTo(new Hello("hello world 1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testUserParameterizedTypeDecode() {
|
||||
public void testUserParameterizedTypeDecode() {
|
||||
List<Hello> hellos = testClient().getHellos();
|
||||
assertThat(hellos).as("hellos was null").isNotNull();
|
||||
assertThat(hellos.size()).as("hellos was not the right size").isEqualTo(2);
|
||||
@@ -99,7 +100,7 @@ class SpringDecoderTests extends FeignClientFactoryBean {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSimpleParameterizedTypeDecode() {
|
||||
public void testSimpleParameterizedTypeDecode() {
|
||||
List<String> hellos = testClient().getHelloStrings();
|
||||
assertThat(hellos).as("hellos was null").isNotNull();
|
||||
assertThat(hellos.size()).as("hellos was not the right size").isEqualTo(2);
|
||||
@@ -108,7 +109,7 @@ class SpringDecoderTests extends FeignClientFactoryBean {
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void testWildcardTypeDecode() {
|
||||
public void testWildcardTypeDecode() {
|
||||
ResponseEntity<?> wildcard = testClient().getWildcard();
|
||||
assertThat(wildcard).as("wildcard was null").isNotNull();
|
||||
assertThat(wildcard.getStatusCode()).as("wrong status code").isEqualTo(HttpStatus.OK);
|
||||
@@ -120,7 +121,7 @@ class SpringDecoderTests extends FeignClientFactoryBean {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testResponseEntityVoid() {
|
||||
public void testResponseEntityVoid() {
|
||||
ResponseEntity<Void> response = testClient().getHelloVoid();
|
||||
assertThat(response).as("response was null").isNotNull();
|
||||
List<String> headerVals = response.getHeaders().get("x-test-header");
|
||||
@@ -130,13 +131,13 @@ class SpringDecoderTests extends FeignClientFactoryBean {
|
||||
assertThat(header).as("header was wrong").isEqualTo("myval");
|
||||
}
|
||||
|
||||
@Test
|
||||
void test404() {
|
||||
Assertions.assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> testClient().getNotFound());
|
||||
@Test(expected = RuntimeException.class)
|
||||
public void test404() {
|
||||
testClient().getNotFound();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDecodes404() {
|
||||
public void testDecodes404() {
|
||||
final ResponseEntity<String> response = testClient(true).getNotFound();
|
||||
assertThat(response).as("response was null").isNotNull();
|
||||
assertThat(response.getBody()).as("response body was not null").isNull();
|
||||
@@ -144,7 +145,7 @@ class SpringDecoderTests extends FeignClientFactoryBean {
|
||||
|
||||
@Test
|
||||
// Issue: https://github.com/spring-cloud/spring-cloud-openfeign/issues/456
|
||||
void testResponseEntityHeaders() {
|
||||
public void testResponseEntityHeaders() {
|
||||
ResponseEntity<String> response = testClient().getContentType();
|
||||
assertThat(response.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_JSON);
|
||||
}
|
||||
@@ -181,10 +182,10 @@ class SpringDecoderTests extends FeignClientFactoryBean {
|
||||
|
||||
private String message;
|
||||
|
||||
Hello() {
|
||||
public Hello() {
|
||||
}
|
||||
|
||||
Hello(String message) {
|
||||
public Hello(String message) {
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
|
||||
+10
-7
@@ -21,7 +21,8 @@ import java.lang.reflect.Proxy;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
@@ -37,6 +38,7 @@ 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.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@@ -50,6 +52,7 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
* @author Halvdan Hoem Grelland
|
||||
* @author Aaron Whiteside
|
||||
*/
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@SpringBootTest(classes = BeansFeignClientTests.Application.class, webEnvironment = WebEnvironment.RANDOM_PORT,
|
||||
value = { "spring.application.name=feignclienttest",
|
||||
"logging.level.org.springframework.cloud.openfeign.valid=DEBUG", "feign.httpclient.enabled=false",
|
||||
@@ -75,13 +78,13 @@ public class BeansFeignClientTests {
|
||||
private TestClient buildByBuilder;
|
||||
|
||||
@Test
|
||||
void testAnnotations() {
|
||||
public void testAnnotations() {
|
||||
Map<String, Object> beans = this.context.getBeansWithAnnotation(FeignClient.class);
|
||||
assertThat(beans.containsKey(TestClient.class.getName())).as("Wrong clients: " + beans).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testClient() {
|
||||
public void testClient() {
|
||||
assertThat(this.testClient).as("testClient was null").isNotNull();
|
||||
assertThat(this.extraClient).as("extraClient was null").isNotNull();
|
||||
assertThat(Proxy.isProxyClass(this.testClient.getClass())).as("testClient is not a java Proxy").isTrue();
|
||||
@@ -90,7 +93,7 @@ public class BeansFeignClientTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void extraClient() {
|
||||
public void extraClient() {
|
||||
assertThat(this.extraClient).as("extraClient was null").isNotNull();
|
||||
assertThat(Proxy.isProxyClass(this.extraClient.getClass())).as("extraClient is not a java Proxy").isTrue();
|
||||
InvocationHandler invocationHandler = Proxy.getInvocationHandler(this.extraClient);
|
||||
@@ -98,7 +101,7 @@ public class BeansFeignClientTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void buildByBuilder() {
|
||||
public void buildByBuilder() {
|
||||
assertThat(this.buildByBuilder).as("buildByBuilder was null").isNotNull();
|
||||
assertThat(Proxy.isProxyClass(this.buildByBuilder.getClass())).as("buildByBuilder is not a java Proxy")
|
||||
.isTrue();
|
||||
@@ -129,10 +132,10 @@ public class BeansFeignClientTests {
|
||||
|
||||
private String message;
|
||||
|
||||
Hello() {
|
||||
public Hello() {
|
||||
}
|
||||
|
||||
Hello(String message) {
|
||||
public Hello(String message) {
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
|
||||
-78
@@ -1,78 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2022 the original author 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.circuitbreaker;
|
||||
|
||||
import feign.Target;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.cloud.openfeign.CircuitBreakerNameResolver;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* @author Ryan Baxter
|
||||
*/
|
||||
public class CircuitBreakerAutoConfigurationTests {
|
||||
|
||||
@SpringBootTest(classes = CircuitBreakerTests.Application.class,
|
||||
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
|
||||
value = { "spring.application.name=springcircuittest", "spring.jmx.enabled=false",
|
||||
"feign.circuitbreaker.enabled=true" })
|
||||
@Nested
|
||||
class DefaultNamingStrategy {
|
||||
|
||||
@Autowired
|
||||
CircuitBreakerNameResolver nameResolver;
|
||||
|
||||
@Test
|
||||
public void assertDefaultNamingStrategy() throws Exception {
|
||||
Target target = mock(Target.class);
|
||||
when(target.type()).thenReturn(CircuitBreakerTests.TestClientWithFactory.class);
|
||||
assertThat(nameResolver.resolveCircuitBreakerName("foo", target,
|
||||
CircuitBreakerTests.TestClientWithFactory.class.getMethod("getHello")))
|
||||
.isEqualTo("TestClientWithFactory#getHello()");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@SpringBootTest(classes = CircuitBreakerTests.Application.class,
|
||||
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
|
||||
value = { "spring.application.name=springcircuittest", "spring.jmx.enabled=false",
|
||||
"feign.circuitbreaker.enabled=true", "feign.circuitbreaker.alphanumeric-ids.enabled=true" })
|
||||
@Nested
|
||||
class AlphanumericNamingStrategy {
|
||||
|
||||
@Autowired
|
||||
CircuitBreakerNameResolver nameResolver;
|
||||
|
||||
@Test
|
||||
public void assertAlphanumericNamingStrategy() throws Exception {
|
||||
Target target = mock(Target.class);
|
||||
when(target.type()).thenReturn(CircuitBreakerTests.TestClientWithFactory.class);
|
||||
assertThat(nameResolver.resolveCircuitBreakerName("foo", target,
|
||||
CircuitBreakerTests.TestClientWithFactory.class.getMethod("getHello")))
|
||||
.isEqualTo("TestClientWithFactorygetHello");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
+16
-13
@@ -21,10 +21,11 @@ import java.util.function.Function;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||
@@ -43,6 +44,7 @@ import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Import;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.test.annotation.DirtiesContext;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.util.SocketUtils;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
@@ -53,10 +55,11 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
|
||||
/**
|
||||
* @author Spencer Gibb
|
||||
*/
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@SpringBootTest(classes = CircuitBreakerTests.Application.class, webEnvironment = WebEnvironment.DEFINED_PORT, value = {
|
||||
"spring.application.name=springcircuittest", "spring.jmx.enabled=false", "feign.circuitbreaker.enabled=true" })
|
||||
@DirtiesContext
|
||||
class CircuitBreakerTests {
|
||||
public class CircuitBreakerTests {
|
||||
|
||||
@Autowired
|
||||
MyCircuitBreaker myCircuitBreaker;
|
||||
@@ -71,22 +74,22 @@ class CircuitBreakerTests {
|
||||
TestClientWithFactory testClientWithFactory;
|
||||
|
||||
@BeforeAll
|
||||
static void beforeClass() {
|
||||
public static void beforeClass() {
|
||||
System.setProperty("server.port", String.valueOf(SocketUtils.findAvailableTcpPort()));
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void afterClass() {
|
||||
public static void afterClass() {
|
||||
System.clearProperty("server.port");
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
@Before
|
||||
public void setup() {
|
||||
this.myCircuitBreaker.clear();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSimpleTypeWithFallback() {
|
||||
public void testSimpleTypeWithFallback() {
|
||||
Hello hello = testClient.getHello();
|
||||
|
||||
assertThat(hello).as("hello was null").isNotNull();
|
||||
@@ -95,12 +98,12 @@ class CircuitBreakerTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void test404WithFallback() {
|
||||
public void test404WithFallback() {
|
||||
assertThat(testClient.getException()).isEqualTo("Fixed response");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSimpleTypeWithFallbackFactory() {
|
||||
public void testSimpleTypeWithFallbackFactory() {
|
||||
Hello hello = testClientWithFactory.getHello();
|
||||
|
||||
assertThat(hello).as("hello was null").isNotNull();
|
||||
@@ -109,18 +112,18 @@ class CircuitBreakerTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void test404WithFallbackFactory() {
|
||||
public void test404WithFallbackFactory() {
|
||||
assertThat(testClientWithFactory.getException()).isEqualTo("Fixed response");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRuntimeExceptionUnwrapped() {
|
||||
public void testRuntimeExceptionUnwrapped() {
|
||||
assertThatExceptionOfType(UnsupportedOperationException.class)
|
||||
.isThrownBy(() -> exceptionClient.getRuntimeException());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCheckedExceptionWrapped() {
|
||||
public void testCheckedExceptionWrapped() {
|
||||
assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() -> exceptionClient.getCheckedException());
|
||||
}
|
||||
|
||||
|
||||
+6
-3
@@ -18,7 +18,8 @@ package org.springframework.cloud.openfeign.encoding;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
@@ -38,6 +39,7 @@ import org.springframework.context.annotation.Import;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.test.annotation.DirtiesContext;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
|
||||
@@ -49,14 +51,15 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
|
||||
*/
|
||||
@SpringBootTest(classes = FeignAcceptEncodingTests.Application.class, webEnvironment = RANDOM_PORT,
|
||||
value = { "feign.compression.response.enabled=true" })
|
||||
@RunWith(SpringRunner.class)
|
||||
@DirtiesContext
|
||||
class FeignAcceptEncodingTests {
|
||||
public class FeignAcceptEncodingTests {
|
||||
|
||||
@Autowired
|
||||
private InvoiceClient invoiceClient;
|
||||
|
||||
@Test
|
||||
void compressedResponse() {
|
||||
public void compressedResponse() {
|
||||
|
||||
// when
|
||||
final ResponseEntity<List<Invoice>> invoices = this.invoiceClient.getInvoices();
|
||||
|
||||
+7
-4
@@ -18,7 +18,8 @@ package org.springframework.cloud.openfeign.encoding;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
@@ -37,6 +38,7 @@ import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Import;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
|
||||
@@ -47,14 +49,15 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
|
||||
* @author Jakub Narloch
|
||||
*/
|
||||
@SpringBootTest(classes = FeignContentEncodingTests.Application.class, webEnvironment = RANDOM_PORT,
|
||||
value = { "feign.compression.request.enabled=true" })
|
||||
class FeignContentEncodingTests {
|
||||
value = { "feign.compression.request.enabled=true", "ribbon.OkToRetryOnAllOperations=false" })
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
public class FeignContentEncodingTests {
|
||||
|
||||
@Autowired
|
||||
private InvoiceClient invoiceClient;
|
||||
|
||||
@Test
|
||||
void compressedResponse() {
|
||||
public void compressedResponse() {
|
||||
|
||||
// given
|
||||
final List<Invoice> invoices = Invoices.createInvoiceList(50);
|
||||
|
||||
+13
-10
@@ -19,7 +19,8 @@ package org.springframework.cloud.openfeign.encoding;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
@@ -44,6 +45,7 @@ import org.springframework.data.domain.Sort;
|
||||
import org.springframework.data.web.config.EnableSpringDataWebSupport;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
|
||||
@@ -56,13 +58,14 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
|
||||
*/
|
||||
@SpringBootTest(classes = FeignPageableEncodingTests.Application.class, webEnvironment = RANDOM_PORT,
|
||||
value = { "feign.compression.request.enabled=true", "feign.autoconfiguration.jackson.enabled=true" })
|
||||
class FeignPageableEncodingTests {
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
public class FeignPageableEncodingTests {
|
||||
|
||||
@Autowired
|
||||
private InvoiceClient invoiceClient;
|
||||
|
||||
@Test
|
||||
void testPageable() {
|
||||
public void testPageable() {
|
||||
// given
|
||||
Pageable pageable = PageRequest.of(0, 10, Sort.Direction.ASC, "sortProperty");
|
||||
|
||||
@@ -84,7 +87,7 @@ class FeignPageableEncodingTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testPageableWithDescDirection() {
|
||||
public void testPageableWithDescDirection() {
|
||||
// given
|
||||
Pageable pageable = PageRequest.of(0, 10, Sort.Direction.DESC, "sortProperty");
|
||||
|
||||
@@ -110,7 +113,7 @@ class FeignPageableEncodingTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testPageableWithMultipleSort() {
|
||||
public void testPageableWithMultipleSort() {
|
||||
// given
|
||||
Pageable pageable = PageRequest.of(0, 10,
|
||||
Sort.by(Sort.Order.desc("sortProperty1"), Sort.Order.asc("sortProperty2")));
|
||||
@@ -140,7 +143,7 @@ class FeignPageableEncodingTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testPageableWithoutSort() {
|
||||
public void testPageableWithoutSort() {
|
||||
// given
|
||||
Pageable pageable = PageRequest.of(0, 10);
|
||||
|
||||
@@ -159,7 +162,7 @@ class FeignPageableEncodingTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testPageableWithoutSortWithBody() {
|
||||
public void testPageableWithoutSortWithBody() {
|
||||
// given
|
||||
Pageable pageable = PageRequest.of(0, 10);
|
||||
|
||||
@@ -181,7 +184,7 @@ class FeignPageableEncodingTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testPageableWithBody() {
|
||||
public void testPageableWithBody() {
|
||||
// given
|
||||
Pageable pageable = PageRequest.of(0, 10,
|
||||
Sort.by(Sort.Order.desc("sortProperty1"), Sort.Order.asc("sortProperty2")));
|
||||
@@ -218,7 +221,7 @@ class FeignPageableEncodingTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testUnpagedWithBody() {
|
||||
public void testUnpagedWithBody() {
|
||||
// given
|
||||
Pageable unpaged = Pageable.unpaged();
|
||||
|
||||
@@ -239,7 +242,7 @@ class FeignPageableEncodingTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSortWithBody() {
|
||||
public void testSortWithBody() {
|
||||
// given
|
||||
Sort sort = Sort.by(Sort.Order.desc("amount"));
|
||||
|
||||
|
||||
+6
-3
@@ -17,12 +17,14 @@
|
||||
package org.springframework.cloud.openfeign.encoding.proto;
|
||||
|
||||
import feign.RequestTemplate;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
import org.springframework.beans.factory.ObjectFactory;
|
||||
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
|
||||
import org.springframework.cloud.openfeign.support.SpringEncoder;
|
||||
import org.springframework.cloud.test.ClassPathExclusions;
|
||||
import org.springframework.cloud.test.ModifiedClassPathRunner;
|
||||
import org.springframework.http.converter.StringHttpMessageConverter;
|
||||
|
||||
import static feign.Request.HttpMethod.POST;
|
||||
@@ -32,11 +34,12 @@ import static feign.Request.HttpMethod.POST;
|
||||
*
|
||||
* @author ScienJus
|
||||
*/
|
||||
@RunWith(ModifiedClassPathRunner.class)
|
||||
@ClassPathExclusions("protobuf-*.jar")
|
||||
class ProtobufNotInClasspathTest {
|
||||
public class ProtobufNotInClasspathTest {
|
||||
|
||||
@Test
|
||||
void testEncodeWhenProtobufNotInClasspath() {
|
||||
public void testEncodeWhenProtobufNotInClasspath() {
|
||||
ObjectFactory<HttpMessageConverters> converters = () -> new HttpMessageConverters(
|
||||
new StringHttpMessageConverter());
|
||||
RequestTemplate requestTemplate = new RequestTemplate();
|
||||
|
||||
+8
-7
@@ -18,6 +18,7 @@ package org.springframework.cloud.openfeign.encoding.proto;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.URISyntaxException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
@@ -34,12 +35,12 @@ import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
|
||||
import org.apache.http.client.methods.HttpUriRequest;
|
||||
import org.apache.http.message.BasicHttpResponse;
|
||||
import org.apache.http.message.BasicStatusLine;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.ArgumentMatchers;
|
||||
import org.mockito.BDDMockito;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.mockito.stubbing.Answer;
|
||||
|
||||
import org.springframework.beans.factory.ObjectFactory;
|
||||
@@ -57,8 +58,8 @@ import static org.assertj.core.api.Assertions.fail;
|
||||
*
|
||||
* @author ScienJus
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class ProtobufSpringEncoderTest {
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class ProtobufSpringEncoderTest {
|
||||
|
||||
@Mock
|
||||
private HttpClient httpClient;
|
||||
@@ -69,7 +70,7 @@ class ProtobufSpringEncoderTest {
|
||||
.setMsg("Erlang/OTP 最初是爱立信为开发电信设备系统设计的编程语言平台," + "电信设备(路由器、接入网关、…)典型设计是通过背板连接主控板卡与多块业务板卡的分布式系统。").build();
|
||||
|
||||
@Test
|
||||
void testProtobuf() throws IOException {
|
||||
public void testProtobuf() throws IOException {
|
||||
// protobuf convert to request by feign and ProtobufHttpMessageConverter
|
||||
RequestTemplate requestTemplate = newRequestTemplate();
|
||||
newEncoder().encode(this.request, Request.class, requestTemplate);
|
||||
@@ -83,7 +84,7 @@ class ProtobufSpringEncoderTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testProtobufWithCharsetWillFail() throws IOException {
|
||||
public void testProtobufWithCharsetWillFail() throws IOException, URISyntaxException {
|
||||
// protobuf convert to request by feign and ProtobufHttpMessageConverter
|
||||
RequestTemplate requestTemplate = newRequestTemplate();
|
||||
newEncoder().encode(this.request, Request.class, requestTemplate);
|
||||
|
||||
+16
-12
@@ -16,8 +16,8 @@
|
||||
|
||||
package org.springframework.cloud.openfeign.hateoas;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import org.springframework.boot.autoconfigure.AutoConfigurations;
|
||||
import org.springframework.boot.autoconfigure.data.rest.RepositoryRestMvcAutoConfiguration;
|
||||
@@ -27,20 +27,19 @@ import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration;
|
||||
import org.springframework.boot.test.context.FilteredClassLoader;
|
||||
import org.springframework.boot.test.context.runner.WebApplicationContextRunner;
|
||||
import org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration;
|
||||
import org.springframework.hateoas.config.WebConverters;
|
||||
import org.springframework.hateoas.RepresentationModel;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* @author Hector Espert
|
||||
* @author Olga Maciaszek-Sharma
|
||||
*/
|
||||
class FeignHalAutoConfigurationContextTests {
|
||||
public class FeignHalAutoConfigurationContextTests {
|
||||
|
||||
private WebApplicationContextRunner contextRunner;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
@Before
|
||||
public void setUp() {
|
||||
contextRunner = new WebApplicationContextRunner()
|
||||
.withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class,
|
||||
HttpMessageConvertersAutoConfiguration.class, HypermediaAutoConfiguration.class,
|
||||
@@ -49,18 +48,23 @@ class FeignHalAutoConfigurationContextTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldNotLoadWebConvertersCustomizerWhenNotWebConvertersNotInClasspath() {
|
||||
public void testHalJacksonHttpMessageConverterIsNotLoaded() {
|
||||
FilteredClassLoader filteredClassLoader = new FilteredClassLoader(RepositoryRestMvcConfiguration.class,
|
||||
WebConverters.class);
|
||||
RepresentationModel.class);
|
||||
contextRunner.withClassLoader(filteredClassLoader)
|
||||
.run(context -> assertThat(context).doesNotHaveBean("webConvertersCustomizer"));
|
||||
.run(context -> assertThat(context).doesNotHaveBean("halJacksonHttpMessageConverter"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldLoadWebConvertersCustomizer() {
|
||||
public void testHalJacksonHttpMessageConverterIsLoaded() {
|
||||
FilteredClassLoader filteredClassLoader = new FilteredClassLoader(RepositoryRestMvcConfiguration.class);
|
||||
contextRunner.withClassLoader(filteredClassLoader)
|
||||
.run(context -> assertThat(context).hasBean("webConvertersCustomizer"));
|
||||
.run(context -> assertThat(context).hasBean("halJacksonHttpMessageConverter"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHalJacksonHttpMessageConverterIsNotLoadedUseRestDataMessageConverterInstead() {
|
||||
contextRunner.run(context -> assertThat(context).hasBean("halJacksonHttpMessageConverter"));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
/*
|
||||
* Copyright 2016-2022 the original author 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.hateoas;
|
||||
|
||||
import java.util.Collections;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
|
||||
import org.springframework.hateoas.mediatype.MessageResolver;
|
||||
import org.springframework.hateoas.mediatype.hal.CurieProvider;
|
||||
import org.springframework.hateoas.mediatype.hal.HalConfiguration;
|
||||
import org.springframework.hateoas.mediatype.hal.HalMediaTypeConfiguration;
|
||||
import org.springframework.hateoas.mediatype.hal.Jackson2HalModule;
|
||||
import org.springframework.hateoas.server.LinkRelationProvider;
|
||||
import org.springframework.hateoas.server.mvc.TypeConstrainedMappingJackson2HttpMessageConverter;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.springframework.hateoas.MediaTypes.HAL_JSON;
|
||||
|
||||
/**
|
||||
* @author Hector Espert
|
||||
* @author Olga Maciaszek-Sharma
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class FeignHalAutoConfigurationTests {
|
||||
|
||||
@Mock
|
||||
private ObjectProvider<HalConfiguration> halConfiguration;
|
||||
|
||||
@Mock
|
||||
private ObjectProvider<ObjectMapper> objectMapper;
|
||||
|
||||
@Mock
|
||||
private LinkRelationProvider relProvider;
|
||||
|
||||
@Mock
|
||||
private ObjectProvider<CurieProvider> curieProvider;
|
||||
|
||||
@Mock
|
||||
private MessageResolver messageResolver;
|
||||
|
||||
@InjectMocks
|
||||
private FeignHalAutoConfiguration feignHalAutoConfiguration;
|
||||
|
||||
@Test
|
||||
public void halJacksonHttpMessageConverter() {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
when(objectMapper.getIfAvailable(any())).thenReturn(mapper);
|
||||
|
||||
when(halConfiguration.getIfAvailable(any())).thenReturn(mock(HalConfiguration.class));
|
||||
when(curieProvider.getIfAvailable(any())).thenReturn(mock(CurieProvider.class));
|
||||
|
||||
HalMediaTypeConfiguration halMediaTypeConfiguration = new HalMediaTypeConfiguration(relProvider, curieProvider,
|
||||
halConfiguration, messageResolver, new DefaultListableBeanFactory());
|
||||
|
||||
TypeConstrainedMappingJackson2HttpMessageConverter converter = feignHalAutoConfiguration
|
||||
.halJacksonHttpMessageConverter(objectMapper, halMediaTypeConfiguration);
|
||||
|
||||
assertThat(converter).isNotNull();
|
||||
assertThat(converter.getObjectMapper()).isNotNull();
|
||||
assertThat(converter.getSupportedMediaTypes()).isEqualTo(Collections.singletonList(HAL_JSON));
|
||||
|
||||
assertThat(Jackson2HalModule.isAlreadyRegisteredIn(converter.getObjectMapper())).isTrue();
|
||||
}
|
||||
|
||||
}
|
||||
+8
-5
@@ -18,7 +18,8 @@ package org.springframework.cloud.openfeign.hateoas;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
@@ -30,6 +31,7 @@ import org.springframework.hateoas.EntityModel;
|
||||
import org.springframework.hateoas.Link;
|
||||
import org.springframework.hateoas.PagedModel;
|
||||
import org.springframework.test.annotation.DirtiesContext;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
|
||||
@@ -40,14 +42,15 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
|
||||
* @author Hector Espert
|
||||
*/
|
||||
@SpringBootTest(classes = FeignHalApplication.class, webEnvironment = RANDOM_PORT, value = "debug=true")
|
||||
@RunWith(SpringRunner.class)
|
||||
@DirtiesContext
|
||||
class FeignHalTests {
|
||||
public class FeignHalTests {
|
||||
|
||||
@Autowired
|
||||
private FeignHalClient feignHalClient;
|
||||
|
||||
@Test
|
||||
void testEntityModel() {
|
||||
public void testEntityModel() {
|
||||
EntityModel<MarsRover> entity = feignHalClient.entity();
|
||||
assertThat(entity).isNotNull();
|
||||
|
||||
@@ -62,7 +65,7 @@ class FeignHalTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCollectionModel() {
|
||||
public void testCollectionModel() {
|
||||
CollectionModel<MarsRover> collectionModel = feignHalClient.collection();
|
||||
assertThat(collectionModel).isNotNull();
|
||||
assertThat(collectionModel).isNotEmpty();
|
||||
@@ -81,7 +84,7 @@ class FeignHalTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testPagedModel() {
|
||||
public void testPagedModel() {
|
||||
PagedModel<MarsRover> paged = feignHalClient.paged();
|
||||
assertThat(paged).isNotNull();
|
||||
assertThat(paged).isNotEmpty();
|
||||
|
||||
+6
-6
@@ -35,25 +35,25 @@ public class FeignHalController {
|
||||
public EntityModel<MarsRover> getEntity() {
|
||||
MarsRover marsRover = new MarsRover();
|
||||
marsRover.setName("Sojourner");
|
||||
Link link = Link.of("/entity", "self");
|
||||
return EntityModel.of(marsRover, link);
|
||||
Link link = new Link("/entity", "self");
|
||||
return new EntityModel<>(marsRover, link);
|
||||
}
|
||||
|
||||
@GetMapping("/collection")
|
||||
public CollectionModel<MarsRover> getCollection() {
|
||||
MarsRover marsRover = new MarsRover();
|
||||
marsRover.setName("Opportunity");
|
||||
Link link = Link.of("/collection", "self");
|
||||
return CollectionModel.of(Collections.singleton(marsRover), link);
|
||||
Link link = new Link("/collection", "self");
|
||||
return new CollectionModel<>(Collections.singleton(marsRover), link);
|
||||
}
|
||||
|
||||
@GetMapping("/paged")
|
||||
public CollectionModel<MarsRover> getPaged() {
|
||||
MarsRover marsRover = new MarsRover();
|
||||
marsRover.setName("Curiosity");
|
||||
Link link = Link.of("/paged", "self");
|
||||
Link link = new Link("/paged", "self");
|
||||
PagedModel.PageMetadata metadata = new PagedModel.PageMetadata(1, 1, 1);
|
||||
return PagedModel.of(Collections.singleton(marsRover), metadata, link);
|
||||
return new PagedModel<>(Collections.singleton(marsRover), metadata, link);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+1
-1
@@ -21,7 +21,7 @@ import org.springframework.beans.factory.annotation.Value;
|
||||
/**
|
||||
* @author Hector Espert
|
||||
*/
|
||||
public class FeignHalConfiguration {
|
||||
public class FeignHalRibbonConfiguration {
|
||||
|
||||
@Value("${local.server.port}")
|
||||
private int serverPort = 0;
|
||||
+12
-10
@@ -16,7 +16,9 @@
|
||||
|
||||
package org.springframework.cloud.openfeign.invalid;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.rules.ExpectedException;
|
||||
|
||||
import org.springframework.cloud.client.loadbalancer.LoadBalancerAutoConfiguration;
|
||||
import org.springframework.cloud.commons.httpclient.HttpClientConfiguration;
|
||||
@@ -29,16 +31,17 @@ import org.springframework.context.annotation.Import;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
|
||||
|
||||
/**
|
||||
* @author Dave Syer
|
||||
* @author Szymon Linowski
|
||||
*/
|
||||
class FeignClientValidationTests {
|
||||
public class FeignClientValidationTests {
|
||||
|
||||
@Rule
|
||||
public ExpectedException expected = ExpectedException.none();
|
||||
|
||||
@Test
|
||||
void testServiceIdAndValue() {
|
||||
public void testServiceIdAndValue() {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
|
||||
LoadBalancerAutoConfiguration.class, NameAndServiceIdConfiguration.class);
|
||||
assertThat(context.getBean(NameAndServiceIdConfiguration.Client.class)).isNotNull();
|
||||
@@ -46,7 +49,7 @@ class FeignClientValidationTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDuplicatedClientNames() {
|
||||
public void testDuplicatedClientNames() {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
|
||||
context.setAllowBeanDefinitionOverriding(false);
|
||||
context.register(LoadBalancerAutoConfiguration.class, DuplicatedFeignClientNamesConfiguration.class);
|
||||
@@ -57,10 +60,9 @@ class FeignClientValidationTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testNotLegalHostname() {
|
||||
assertThatExceptionOfType(IllegalStateException.class)
|
||||
.isThrownBy(() -> new AnnotationConfigApplicationContext(BadHostnameConfiguration.class))
|
||||
.withMessage("Service id not legal hostname (foo_bar)");
|
||||
public void testNotLegalHostname() {
|
||||
this.expected.expectMessage("not legal hostname (foo_bar)");
|
||||
new AnnotationConfigApplicationContext(BadHostnameConfiguration.class);
|
||||
}
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
|
||||
+6
-24
@@ -16,9 +16,7 @@
|
||||
|
||||
package org.springframework.cloud.openfeign.loadbalancer;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Collection;
|
||||
@@ -31,7 +29,6 @@ import java.util.concurrent.ConcurrentHashMap;
|
||||
import feign.Client;
|
||||
import feign.Request;
|
||||
import feign.Response;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
@@ -72,21 +69,16 @@ import static org.mockito.Mockito.when;
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class FeignBlockingLoadBalancerClientTests {
|
||||
|
||||
private final Client delegate = mock(Client.class);
|
||||
private Client delegate = mock(Client.class);
|
||||
|
||||
private final BlockingLoadBalancerClient loadBalancerClient = mock(BlockingLoadBalancerClient.class);
|
||||
private BlockingLoadBalancerClient loadBalancerClient = mock(BlockingLoadBalancerClient.class);
|
||||
|
||||
private final LoadBalancerClientFactory loadBalancerClientFactory = mock(LoadBalancerClientFactory.class);
|
||||
|
||||
private final LoadBalancerProperties loadBalancerProperties = new LoadBalancerProperties();
|
||||
|
||||
private final FeignBlockingLoadBalancerClient feignBlockingLoadBalancerClient = new FeignBlockingLoadBalancerClient(
|
||||
delegate, loadBalancerClient, loadBalancerClientFactory);
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
when(loadBalancerClientFactory.getProperties(any(String.class))).thenReturn(loadBalancerProperties);
|
||||
}
|
||||
private FeignBlockingLoadBalancerClient feignBlockingLoadBalancerClient = new FeignBlockingLoadBalancerClient(
|
||||
delegate, loadBalancerClient, loadBalancerProperties, loadBalancerClientFactory);
|
||||
|
||||
@Test
|
||||
void shouldExtractServiceIdFromRequestUrl() throws IOException {
|
||||
@@ -113,7 +105,8 @@ class FeignBlockingLoadBalancerClientTests {
|
||||
Response response = feignBlockingLoadBalancerClient.execute(request, new Request.Options());
|
||||
|
||||
assertThat(response.status()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE.value());
|
||||
assertThat(read(response)).isEqualTo("Load balancer does not contain an instance for the service test");
|
||||
assertThat(response.body().toString())
|
||||
.isEqualTo("Load balancer does not contain an instance for the service test");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -174,17 +167,6 @@ class FeignBlockingLoadBalancerClientTests {
|
||||
.contains(HttpStatus.OK);
|
||||
}
|
||||
|
||||
private String read(Response response) throws IOException {
|
||||
BufferedReader reader = new BufferedReader(
|
||||
new InputStreamReader(response.body().asInputStream(), StandardCharsets.UTF_8));
|
||||
String outputString = "";
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
outputString += line;
|
||||
}
|
||||
return outputString;
|
||||
}
|
||||
|
||||
private Request testRequest() {
|
||||
return testRequest("test");
|
||||
}
|
||||
|
||||
+2
-12
@@ -33,7 +33,6 @@ import org.springframework.cloud.loadbalancer.config.LoadBalancerAutoConfigurati
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.springframework.test.util.ReflectionTestUtils.getField;
|
||||
|
||||
/**
|
||||
* @author Olga Maciaszek-Sharma
|
||||
@@ -59,18 +58,9 @@ class FeignLoadBalancerAutoConfigurationTests {
|
||||
@Test
|
||||
void shouldInstantiateOkHttpFeignClientWhenEnabled() {
|
||||
ConfigurableApplicationContext context = initContext("feign.httpclient.enabled=false",
|
||||
"feign.okhttp.enabled=true", "spring.cloud.loadbalancer.retry.enabled=false",
|
||||
"feign.httpclient.okhttp.read-timeout=9s");
|
||||
"feign.okhttp.enabled=true", "spring.cloud.loadbalancer.retry.enabled=false");
|
||||
assertThatOneBeanPresent(context, BlockingLoadBalancerClient.class);
|
||||
Map<String, FeignBlockingLoadBalancerClient> beans = context
|
||||
.getBeansOfType(FeignBlockingLoadBalancerClient.class);
|
||||
assertThat(beans).as("Missing bean of type %s", OkHttpClient.class).hasSize(1);
|
||||
Client client = beans.get("feignClient").getDelegate();
|
||||
assertThat(client).isInstanceOf(OkHttpClient.class);
|
||||
OkHttpClient okHttpClient = (OkHttpClient) client;
|
||||
okhttp3.OkHttpClient httpClient = (okhttp3.OkHttpClient) getField(okHttpClient, "delegate");
|
||||
assertThat(httpClient.readTimeoutMillis()).isEqualTo(9000);
|
||||
|
||||
assertLoadBalanced(context, OkHttpClient.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+6
-7
@@ -76,24 +76,23 @@ import static org.mockito.Mockito.when;
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class RetryableFeignBlockingLoadBalancerClientTests {
|
||||
|
||||
private final Client delegate = mock(Client.class);
|
||||
private Client delegate = mock(Client.class);
|
||||
|
||||
private final LoadBalancedRetryFactory retryFactory = mock(LoadBalancedRetryFactory.class);
|
||||
private LoadBalancedRetryFactory retryFactory = mock(LoadBalancedRetryFactory.class);
|
||||
|
||||
private final BlockingLoadBalancerClient loadBalancerClient = mock(BlockingLoadBalancerClient.class);
|
||||
private BlockingLoadBalancerClient loadBalancerClient = mock(BlockingLoadBalancerClient.class);
|
||||
|
||||
private final LoadBalancerClientFactory loadBalancerClientFactory = mock(LoadBalancerClientFactory.class);
|
||||
|
||||
private final LoadBalancerProperties properties = new LoadBalancerProperties();
|
||||
private LoadBalancerProperties properties = new LoadBalancerProperties();
|
||||
|
||||
private final RetryableFeignBlockingLoadBalancerClient feignBlockingLoadBalancerClient = new RetryableFeignBlockingLoadBalancerClient(
|
||||
private RetryableFeignBlockingLoadBalancerClient feignBlockingLoadBalancerClient = new RetryableFeignBlockingLoadBalancerClient(
|
||||
delegate, loadBalancerClient, retryFactory, properties, loadBalancerClientFactory);
|
||||
|
||||
private final ServiceInstance serviceInstance = new DefaultServiceInstance("test-a", "test", "testhost", 80, false);
|
||||
private ServiceInstance serviceInstance = new DefaultServiceInstance("test-a", "test", "testhost", 80, false);
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
when(loadBalancerClientFactory.getProperties(any(String.class))).thenReturn(properties);
|
||||
when(retryFactory.createRetryPolicy(any(), eq(loadBalancerClient)))
|
||||
.thenReturn(new BlockingLoadBalancedRetryPolicy(properties));
|
||||
when(loadBalancerClient.choose(eq("test"), any())).thenReturn(serviceInstance);
|
||||
|
||||
-95
@@ -1,95 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2022 the original author 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.security;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
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.boot.test.context.assertj.AssertableApplicationContext;
|
||||
import org.springframework.cloud.client.loadbalancer.RetryLoadBalancerInterceptor;
|
||||
import org.springframework.cloud.openfeign.EnableFeignClients;
|
||||
import org.springframework.cloud.openfeign.FeignClient;
|
||||
import org.springframework.cloud.openfeign.FeignContext;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.test.annotation.DirtiesContext;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
|
||||
|
||||
/**
|
||||
* @author Wojciech Mąka
|
||||
*/
|
||||
@SpringBootTest(classes = AccessTokenProviderWithLoadBalancerInterceptorTests.Application.class,
|
||||
webEnvironment = RANDOM_PORT,
|
||||
value = { "security.oauth2.client.id=test-service", "security.oauth2.client.client-id=test-service",
|
||||
"security.oauth2.client.client-secret=test-service",
|
||||
"security.oauth2.client.grant-type=client_credentials", "feign.oauth2.enabled=true",
|
||||
"feign.oauth2.load-balanced=true" })
|
||||
@DirtiesContext
|
||||
public class AccessTokenProviderWithLoadBalancerInterceptorTests {
|
||||
|
||||
@Autowired
|
||||
FeignContext context;
|
||||
|
||||
@Autowired
|
||||
private ConfigurableApplicationContext applicationContext;
|
||||
|
||||
@Test
|
||||
void testOAuth2RequestInterceptorIsLoadBalanced() {
|
||||
AssertableApplicationContext assertableContext = AssertableApplicationContext.get(() -> applicationContext);
|
||||
assertThat(assertableContext).hasSingleBean(Application.SampleClient.class);
|
||||
assertThat(assertableContext).hasSingleBean(OAuth2FeignRequestInterceptor.class);
|
||||
assertThat(assertableContext).getBean(OAuth2FeignRequestInterceptor.class).extracting("accessTokenProvider")
|
||||
.extracting("interceptors").asList()
|
||||
.filteredOn(obj -> RetryLoadBalancerInterceptor.class.equals(obj.getClass())).hasSize(1);
|
||||
}
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@EnableAutoConfiguration
|
||||
@RestController
|
||||
@EnableFeignClients(
|
||||
clients = { AccessTokenProviderWithLoadBalancerInterceptorTests.Application.SampleClient.class })
|
||||
protected static class Application {
|
||||
|
||||
@GetMapping("/foo")
|
||||
public String foo(HttpServletRequest request) throws IllegalAccessException {
|
||||
if ("Foo".equals(request.getHeader("Foo")) && "Bar".equals(request.getHeader("Bar"))) {
|
||||
return "OK";
|
||||
}
|
||||
else {
|
||||
throw new IllegalAccessException("It should has Foo and Bar header");
|
||||
}
|
||||
}
|
||||
|
||||
@FeignClient(name = "sampleClient")
|
||||
protected interface SampleClient {
|
||||
|
||||
@GetMapping("/foo")
|
||||
String foo();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
-95
@@ -1,95 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2022 the original author 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.security;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
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.boot.test.context.assertj.AssertableApplicationContext;
|
||||
import org.springframework.cloud.client.loadbalancer.RetryLoadBalancerInterceptor;
|
||||
import org.springframework.cloud.openfeign.EnableFeignClients;
|
||||
import org.springframework.cloud.openfeign.FeignClient;
|
||||
import org.springframework.cloud.openfeign.FeignContext;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.test.annotation.DirtiesContext;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
|
||||
|
||||
/**
|
||||
* @author Wojciech Mąka
|
||||
*/
|
||||
@SpringBootTest(classes = AccessTokenProviderWithoutLoadBalancerInterceptorTests.Application.class,
|
||||
webEnvironment = RANDOM_PORT,
|
||||
value = { "security.oauth2.client.id=test-service", "security.oauth2.client.client-id=test-service",
|
||||
"security.oauth2.client.client-secret=test-service",
|
||||
"security.oauth2.client.grant-type=client_credentials", "feign.oauth2.enabled=true" })
|
||||
@DirtiesContext
|
||||
public class AccessTokenProviderWithoutLoadBalancerInterceptorTests {
|
||||
|
||||
@Autowired
|
||||
FeignContext context;
|
||||
|
||||
@Autowired
|
||||
private ConfigurableApplicationContext applicationContext;
|
||||
|
||||
@Test
|
||||
void testOAuth2RequestInterceptorIsNotLoadBalanced() {
|
||||
AssertableApplicationContext assertableContext = AssertableApplicationContext.get(() -> applicationContext);
|
||||
assertThat(assertableContext)
|
||||
.hasSingleBean(AccessTokenProviderWithoutLoadBalancerInterceptorTests.Application.SampleClient.class);
|
||||
assertThat(assertableContext).hasSingleBean(OAuth2FeignRequestInterceptor.class);
|
||||
assertThat(assertableContext).getBean(OAuth2FeignRequestInterceptor.class).extracting("accessTokenProvider")
|
||||
.extracting("interceptors").asList()
|
||||
.filteredOn(obj -> RetryLoadBalancerInterceptor.class.equals(obj.getClass())).isEmpty();
|
||||
}
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@EnableAutoConfiguration
|
||||
@RestController
|
||||
@EnableFeignClients(
|
||||
clients = { AccessTokenProviderWithoutLoadBalancerInterceptorTests.Application.SampleClient.class })
|
||||
protected static class Application {
|
||||
|
||||
@GetMapping("/foo")
|
||||
public String foo(HttpServletRequest request) throws IllegalAccessException {
|
||||
if ("Foo".equals(request.getHeader("Foo")) && "Bar".equals(request.getHeader("Bar"))) {
|
||||
return "OK";
|
||||
}
|
||||
else {
|
||||
throw new IllegalAccessException("It should has Foo and Bar header");
|
||||
}
|
||||
}
|
||||
|
||||
@FeignClient(name = "sampleClient")
|
||||
protected interface SampleClient {
|
||||
|
||||
@GetMapping("/foo")
|
||||
String foo();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
+1
-1
@@ -29,7 +29,7 @@ import org.springframework.security.oauth2.common.OAuth2AccessToken;
|
||||
*
|
||||
* @author João Pedro Evangelista
|
||||
*/
|
||||
public final class MockOAuth2ClientContext implements OAuth2ClientContext {
|
||||
final class MockOAuth2ClientContext implements OAuth2ClientContext {
|
||||
|
||||
private final String value;
|
||||
|
||||
|
||||
+24
-30
@@ -21,9 +21,9 @@ import java.util.Map;
|
||||
|
||||
import feign.Request.HttpMethod;
|
||||
import feign.RequestTemplate;
|
||||
import org.assertj.core.api.Assertions;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import org.springframework.security.oauth2.client.DefaultOAuth2ClientContext;
|
||||
import org.springframework.security.oauth2.client.OAuth2ClientContext;
|
||||
@@ -32,60 +32,55 @@ import org.springframework.security.oauth2.client.resource.OAuth2AccessDeniedExc
|
||||
import org.springframework.security.oauth2.client.token.AccessTokenRequest;
|
||||
import org.springframework.security.oauth2.common.OAuth2AccessToken;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.hamcrest.Matchers.contains;
|
||||
import static org.hamcrest.Matchers.hasSize;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* @author João Pedro Evangelista
|
||||
* @author Tim Ysewyn
|
||||
* @author Szymon Linowski
|
||||
*/
|
||||
class OAuth2FeignRequestInterceptorTests {
|
||||
public class OAuth2FeignRequestInterceptorTests {
|
||||
|
||||
private OAuth2FeignRequestInterceptor oAuth2FeignRequestInterceptor;
|
||||
|
||||
private RequestTemplate requestTemplate;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
@Before
|
||||
public void setUp() {
|
||||
oAuth2FeignRequestInterceptor = new OAuth2FeignRequestInterceptor(new MockOAuth2ClientContext("Fancy"),
|
||||
new BaseOAuth2ProtectedResourceDetails());
|
||||
requestTemplate = new RequestTemplate().method(HttpMethod.GET);
|
||||
}
|
||||
|
||||
@Test
|
||||
void applyAuthorizationHeader() {
|
||||
public void applyAuthorizationHeader() {
|
||||
oAuth2FeignRequestInterceptor.apply(requestTemplate);
|
||||
Map<String, Collection<String>> headers = requestTemplate.headers();
|
||||
|
||||
assertThat(headers.containsKey("Authorization")).describedAs("RequestTemplate must have a Authorization header")
|
||||
.isTrue();
|
||||
Assertions.assertThat(headers.get("Authorization")).describedAs("Authorization must have a extract of Fancy")
|
||||
.contains("Bearer Fancy");
|
||||
Assert.assertTrue("RequestTemplate must have a Authorization header", headers.containsKey("Authorization"));
|
||||
Assert.assertThat("Authorization must have a extract of Fancy", headers.get("Authorization"),
|
||||
contains("Bearer Fancy"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void tryToAcquireToken() {
|
||||
@Test(expected = OAuth2AccessDeniedException.class)
|
||||
public void tryToAcquireToken() {
|
||||
oAuth2FeignRequestInterceptor = new OAuth2FeignRequestInterceptor(new DefaultOAuth2ClientContext(),
|
||||
new BaseOAuth2ProtectedResourceDetails());
|
||||
|
||||
Assertions.assertThatExceptionOfType(OAuth2AccessDeniedException.class)
|
||||
.isThrownBy(() -> oAuth2FeignRequestInterceptor.getToken()).withMessage(
|
||||
"Unable to obtain a new access token for resource 'null'. The provider manager is not configured to support it.");
|
||||
OAuth2AccessToken oAuth2AccessToken = oAuth2FeignRequestInterceptor.getToken();
|
||||
Assert.assertTrue(oAuth2AccessToken.getValue() + " Must be null", oAuth2AccessToken.getValue() == null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void configureAccessTokenProvider() {
|
||||
public void configureAccessTokenProvider() {
|
||||
OAuth2AccessToken mockedToken = new MockOAuth2AccessToken("MOCKED_TOKEN");
|
||||
oAuth2FeignRequestInterceptor.setAccessTokenProvider(new MockAccessTokenProvider(mockedToken));
|
||||
|
||||
assertThat(oAuth2FeignRequestInterceptor.acquireAccessToken())
|
||||
.describedAs("Should return same mocked token instance").isEqualTo(mockedToken);
|
||||
Assert.assertEquals("Should return same mocked token instance", mockedToken,
|
||||
oAuth2FeignRequestInterceptor.acquireAccessToken());
|
||||
}
|
||||
|
||||
@Test
|
||||
void applyAuthorizationHeaderOnlyOnce() {
|
||||
public void applyAuthorizationHeaderOnlyOnce() {
|
||||
OAuth2ClientContext oAuth2ClientContext = mock(OAuth2ClientContext.class);
|
||||
when(oAuth2ClientContext.getAccessToken()).thenReturn(new MockOAuth2AccessToken("MOCKED_TOKEN"));
|
||||
|
||||
@@ -108,11 +103,10 @@ class OAuth2FeignRequestInterceptorTests {
|
||||
oAuth2FeignRequestInterceptor.apply(requestTemplate);
|
||||
|
||||
Map<String, Collection<String>> headers = requestTemplate.headers();
|
||||
assertThat(headers.containsKey("Authorization")).describedAs("RequestTemplate must have a Authorization header")
|
||||
.isTrue();
|
||||
assertThat(headers.get("Authorization")).describedAs("Authorization must have a extract of Fancy").hasSize(1);
|
||||
assertThat(headers.get("Authorization")).describedAs("Authorization must have a extract of Fancy")
|
||||
.contains("Bearer Fancy");
|
||||
Assert.assertTrue("RequestTemplate must have a Authorization header", headers.containsKey("Authorization"));
|
||||
Assert.assertThat("Authorization must have a extract of Fancy", headers.get("Authorization"), hasSize(1));
|
||||
Assert.assertThat("Authorization must have a extract of Fancy", headers.get("Authorization"),
|
||||
contains("Bearer Fancy"));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+10
-7
@@ -18,8 +18,9 @@ package org.springframework.cloud.openfeign.support;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.After;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
@@ -30,6 +31,7 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.test.annotation.DirtiesContext;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.springframework.cloud.openfeign.support.FeignHttpClientProperties.Hc5Properties.DEFAULT_SOCKET_TIMEOUT;
|
||||
@@ -39,20 +41,21 @@ import static org.springframework.cloud.openfeign.support.FeignHttpClientPropert
|
||||
* @author Ryan Baxter
|
||||
* @author Nguyen Ky Thanh
|
||||
*/
|
||||
@RunWith(SpringRunner.class)
|
||||
@DirtiesContext
|
||||
class FeignHttpClientPropertiesTests {
|
||||
public class FeignHttpClientPropertiesTests {
|
||||
|
||||
private AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
|
||||
|
||||
@AfterEach
|
||||
void clear() {
|
||||
@After
|
||||
public void clear() {
|
||||
if (this.context != null) {
|
||||
this.context.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDefaults() {
|
||||
public void testDefaults() {
|
||||
setupContext();
|
||||
assertThat(getProperties().getConnectionTimeout())
|
||||
.isEqualTo(FeignHttpClientProperties.DEFAULT_CONNECTION_TIMEOUT);
|
||||
@@ -70,7 +73,7 @@ class FeignHttpClientPropertiesTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCustomization() {
|
||||
public void testCustomization() {
|
||||
TestPropertyValues
|
||||
.of("feign.httpclient.maxConnections=2", "feign.httpclient.connectionTimeout=2",
|
||||
"feign.httpclient.maxConnectionsPerRoute=2", "feign.httpclient.timeToLive=2",
|
||||
|
||||
+4
-57
@@ -82,10 +82,10 @@ public class PageJacksonModuleTests {
|
||||
@Test
|
||||
public void serializeAndDeserializeFilledMultiple() throws JsonProcessingException {
|
||||
// Given
|
||||
ArrayList<Object> pageElements = new ArrayList<>();
|
||||
pageElements.add("first element");
|
||||
pageElements.add("second element");
|
||||
PageImpl<Object> objects = new PageImpl<>(pageElements, PageRequest.of(6, 2), 100);
|
||||
ArrayList<Object> strings0 = new ArrayList<>();
|
||||
strings0.add("first element");
|
||||
strings0.add("second element");
|
||||
PageImpl<Object> objects = new PageImpl<>(strings0, PageRequest.of(6, 2), 100);
|
||||
assertThat(objects.getContent()).hasSize(2);
|
||||
assertThat(objects.getPageable().getPageSize()).isEqualTo(2);
|
||||
|
||||
@@ -102,57 +102,4 @@ public class PageJacksonModuleTests {
|
||||
assertThat(result.getPageable().getPageNumber()).isEqualTo(6);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void serializeAndDeserializeEmptyCascade() throws JsonProcessingException {
|
||||
// Given
|
||||
PageImpl<Object> objects = new PageImpl<>(new ArrayList<>());
|
||||
String pageJson = objectMapper.writeValueAsString(objects);
|
||||
// When
|
||||
Page<?> result = objectMapper.readValue(pageJson, Page.class);
|
||||
// Then
|
||||
assertThat(result).isNotNull();
|
||||
assertThat(result.getTotalElements()).isEqualTo(0);
|
||||
assertThat(result.getContent()).hasSize(0);
|
||||
|
||||
String cascadedPageJson = objectMapper.writeValueAsString(result);
|
||||
Page<?> cascadedResult = objectMapper.readValue(cascadedPageJson, Page.class);
|
||||
assertThat(cascadedResult).isNotNull();
|
||||
assertThat(cascadedResult.getTotalElements()).isEqualTo(0);
|
||||
assertThat(cascadedResult.getContent()).hasSize(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void serializeAndDeserializeFilledMultipleCascade() throws JsonProcessingException {
|
||||
// Given
|
||||
ArrayList<Object> pageElements = new ArrayList<>();
|
||||
pageElements.add("first element in cascaded serialization");
|
||||
pageElements.add("second element in cascaded serialization");
|
||||
PageImpl<Object> objects = new PageImpl<>(pageElements, PageRequest.of(6, 2), 100);
|
||||
assertThat(objects.getContent()).hasSize(2);
|
||||
assertThat(objects.getPageable().getPageSize()).isEqualTo(2);
|
||||
|
||||
String pageJson = objectMapper.writeValueAsString(objects);
|
||||
// When
|
||||
Page<?> result = objectMapper.readValue(pageJson, Page.class);
|
||||
// Then
|
||||
assertThat(result).isNotNull();
|
||||
assertThat(result.getTotalElements()).isEqualTo(100);
|
||||
assertThat(result.getContent()).hasSize(2);
|
||||
assertThat(result.getContent().get(0)).isEqualTo("first element in cascaded serialization");
|
||||
assertThat(result.getContent().get(1)).isEqualTo("second element in cascaded serialization");
|
||||
assertThat(result.getPageable().getPageSize()).isEqualTo(2);
|
||||
assertThat(result.getPageable().getPageNumber()).isEqualTo(6);
|
||||
|
||||
String cascadedPageJson = objectMapper.writeValueAsString(result);
|
||||
Page<?> cascadedResult = objectMapper.readValue(cascadedPageJson, Page.class);
|
||||
// Then
|
||||
assertThat(cascadedResult).isNotNull();
|
||||
assertThat(cascadedResult.getTotalElements()).isEqualTo(100);
|
||||
assertThat(cascadedResult.getContent()).hasSize(2);
|
||||
assertThat(cascadedResult.getContent().get(0)).isEqualTo("first element in cascaded serialization");
|
||||
assertThat(cascadedResult.getContent().get(1)).isEqualTo("second element in cascaded serialization");
|
||||
assertThat(cascadedResult.getPageable().getPageSize()).isEqualTo(2);
|
||||
assertThat(cascadedResult.getPageable().getPageNumber()).isEqualTo(6);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+16
-26
@@ -18,7 +18,8 @@ package org.springframework.cloud.openfeign.support;
|
||||
|
||||
import feign.RequestTemplate;
|
||||
import feign.codec.Encoder;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
@@ -27,6 +28,7 @@ import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.test.annotation.DirtiesContext;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
|
||||
@@ -35,12 +37,12 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
|
||||
* Tests the pagination encoding and sorting.
|
||||
*
|
||||
* @author Charlie Mordant.
|
||||
* @author Yanming Zhou
|
||||
*/
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@SpringBootTest(classes = SpringEncoderTests.Application.class, webEnvironment = RANDOM_PORT,
|
||||
value = { "spring.application.name=springencodertest", "spring.jmx.enabled=false" })
|
||||
@DirtiesContext
|
||||
class PageableEncoderTests {
|
||||
public class PageableEncoderTests {
|
||||
|
||||
public static final int PAGE = 1;
|
||||
|
||||
@@ -53,20 +55,8 @@ class PageableEncoderTests {
|
||||
@Autowired
|
||||
private FeignContext context;
|
||||
|
||||
protected String getPageParameter() {
|
||||
return "page";
|
||||
}
|
||||
|
||||
protected String getSizeParameter() {
|
||||
return "size";
|
||||
}
|
||||
|
||||
protected String getSortParameter() {
|
||||
return "sort";
|
||||
}
|
||||
|
||||
@Test
|
||||
void testPaginationAndSortingRequest() {
|
||||
public void testPaginationAndSortingRequest() {
|
||||
Encoder encoder = this.context.getInstance("foo", Encoder.class);
|
||||
assertThat(encoder).isNotNull();
|
||||
RequestTemplate request = new RequestTemplate();
|
||||
@@ -75,11 +65,11 @@ class PageableEncoderTests {
|
||||
// Request queries shall contain three entries
|
||||
assertThat(request.queries()).hasSize(3);
|
||||
// Request page shall contain page
|
||||
assertThat(request.queries().get(getPageParameter())).contains(String.valueOf(PAGE));
|
||||
assertThat(request.queries().get("page")).contains(String.valueOf(PAGE));
|
||||
// Request size shall contain size
|
||||
assertThat(request.queries().get(getSizeParameter())).contains(String.valueOf(SIZE));
|
||||
assertThat(request.queries().get("size")).contains(String.valueOf(SIZE));
|
||||
// Request sort size shall contain sort entries
|
||||
assertThat(request.queries().get(getSortParameter())).hasSize(2);
|
||||
assertThat(request.queries().get("sort")).hasSize(2);
|
||||
}
|
||||
|
||||
private Pageable createPageAndSortRequest() {
|
||||
@@ -87,18 +77,18 @@ class PageableEncoderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testPaginationRequest() {
|
||||
public void testPaginationRequest() {
|
||||
Encoder encoder = this.context.getInstance("foo", Encoder.class);
|
||||
assertThat(encoder).isNotNull();
|
||||
RequestTemplate request = new RequestTemplate();
|
||||
encoder.encode(createPageAndRequest(), null, request);
|
||||
assertThat(request.queries().size()).isEqualTo(2);
|
||||
// Request page shall contain page
|
||||
assertThat(request.queries().get(getPageParameter())).contains(String.valueOf(PAGE));
|
||||
assertThat(request.queries().get("page")).contains(String.valueOf(PAGE));
|
||||
// Request size shall contain size
|
||||
assertThat(request.queries().get(getSizeParameter())).contains(String.valueOf(SIZE));
|
||||
assertThat(request.queries().get("size")).contains(String.valueOf(SIZE));
|
||||
// Request sort size shall contain sort entries
|
||||
assertThat(request.queries()).doesNotContainKey(getSortParameter());
|
||||
assertThat(request.queries()).doesNotContainKey("sort");
|
||||
}
|
||||
|
||||
private Pageable createPageAndRequest() {
|
||||
@@ -106,7 +96,7 @@ class PageableEncoderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSortingRequest() {
|
||||
public void testSortingRequest() {
|
||||
Encoder encoder = this.context.getInstance("foo", Encoder.class);
|
||||
assertThat(encoder).isNotNull();
|
||||
RequestTemplate request = new RequestTemplate();
|
||||
@@ -115,7 +105,7 @@ class PageableEncoderTests {
|
||||
// Request queries shall contain three entries
|
||||
assertThat(request.queries().size()).isEqualTo(1);
|
||||
// Request sort size shall contain sort entries
|
||||
assertThat(request.queries().get(getSortParameter())).hasSize(2);
|
||||
assertThat(request.queries().get("sort")).hasSize(2);
|
||||
}
|
||||
|
||||
private Sort createSort() {
|
||||
@@ -123,7 +113,7 @@ class PageableEncoderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testUnpagedRequest() {
|
||||
public void testUnpagedRequest() {
|
||||
Encoder encoder = this.context.getInstance("foo", Encoder.class);
|
||||
assertThat(encoder).isNotNull();
|
||||
RequestTemplate request = new RequestTemplate();
|
||||
|
||||
-52
@@ -1,52 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2022 the original author 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.springframework.boot.autoconfigure.data.web.SpringDataWebProperties;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
|
||||
|
||||
/**
|
||||
* Tests the pagination encoding and sorting.
|
||||
*
|
||||
* @author Yanming Zhou
|
||||
*/
|
||||
@EnableConfigurationProperties(SpringDataWebProperties.class)
|
||||
@SpringBootTest(classes = SpringEncoderTests.Application.class, webEnvironment = RANDOM_PORT,
|
||||
value = { "spring.application.name=springencodertest", "spring.jmx.enabled=false",
|
||||
"spring.data.web.pageable.pageParameter=pageNo", "spring.data.web.pageable.sizeParameter=pageSize",
|
||||
"spring.data.web.sort.sortParameter=orderBy" })
|
||||
public class PageableEncoderWithSpringDataWebTests extends PageableEncoderTests {
|
||||
|
||||
@Override
|
||||
protected String getPageParameter() {
|
||||
return "pageNo";
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String getSizeParameter() {
|
||||
return "pageSize";
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String getSortParameter() {
|
||||
return "orderBy";
|
||||
}
|
||||
|
||||
}
|
||||
-124
@@ -1,124 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2022 the original author 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.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import feign.QueryMapEncoder;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.cloud.openfeign.FeignContext;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.test.annotation.DirtiesContext;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
|
||||
|
||||
/**
|
||||
* Tests the pagination encoding and sorting.
|
||||
*
|
||||
* @author Yanming Zhou
|
||||
*/
|
||||
@SpringBootTest(classes = SpringEncoderTests.Application.class, webEnvironment = RANDOM_PORT,
|
||||
value = { "spring.application.name=springencodertest", "spring.jmx.enabled=false" })
|
||||
@DirtiesContext
|
||||
class PageableSpringQueryMapEncoderTests {
|
||||
|
||||
public static final int PAGE = 1;
|
||||
|
||||
public static final int SIZE = 10;
|
||||
|
||||
public static final String SORT_2 = "sort2";
|
||||
|
||||
public static final String SORT_1 = "sort1";
|
||||
|
||||
@Autowired
|
||||
private FeignContext context;
|
||||
|
||||
protected String getPageParameter() {
|
||||
return "page";
|
||||
}
|
||||
|
||||
protected String getSizeParameter() {
|
||||
return "size";
|
||||
}
|
||||
|
||||
protected String getSortParameter() {
|
||||
return "sort";
|
||||
}
|
||||
|
||||
@Test
|
||||
void testPaginationAndSortingRequest() {
|
||||
QueryMapEncoder encoder = this.context.getInstance("foo", QueryMapEncoder.class);
|
||||
assertThat(encoder).isNotNull();
|
||||
|
||||
Map<String, Object> map = encoder.encode(createPageAndSortRequest());
|
||||
assertThat(map).hasSize(3);
|
||||
assertThat((Integer) map.get(getPageParameter())).isEqualTo(PAGE);
|
||||
assertThat((Integer) map.get(getSizeParameter())).isEqualTo(SIZE);
|
||||
assertThat((List<?>) map.get(getSortParameter())).hasSize(2);
|
||||
}
|
||||
|
||||
private Pageable createPageAndSortRequest() {
|
||||
return PageRequest.of(PAGE, SIZE, Sort.Direction.ASC, SORT_1, SORT_2);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testPaginationRequest() {
|
||||
QueryMapEncoder encoder = this.context.getInstance("foo", QueryMapEncoder.class);
|
||||
assertThat(encoder).isNotNull();
|
||||
|
||||
Map<String, Object> map = encoder.encode(createPageAndRequest());
|
||||
assertThat(map).hasSize(2);
|
||||
assertThat((Integer) map.get(getPageParameter())).isEqualTo(PAGE);
|
||||
assertThat((Integer) map.get(getSizeParameter())).isEqualTo(SIZE);
|
||||
assertThat(map).doesNotContainKey(getSortParameter());
|
||||
}
|
||||
|
||||
private Pageable createPageAndRequest() {
|
||||
return PageRequest.of(PAGE, SIZE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSortingRequest() {
|
||||
QueryMapEncoder encoder = this.context.getInstance("foo", QueryMapEncoder.class);
|
||||
assertThat(encoder).isNotNull();
|
||||
|
||||
Map<String, Object> map = encoder.encode(createSort());
|
||||
assertThat(map).hasSize(1);
|
||||
assertThat((List<?>) map.get(getSortParameter())).hasSize(2);
|
||||
}
|
||||
|
||||
private Sort createSort() {
|
||||
return Sort.by(SORT_1, SORT_2).ascending();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testUnpagedRequest() {
|
||||
QueryMapEncoder encoder = this.context.getInstance("foo", QueryMapEncoder.class);
|
||||
assertThat(encoder).isNotNull();
|
||||
|
||||
Map<String, Object> map = encoder.encode(Pageable.unpaged());
|
||||
assertThat(map).isEmpty();
|
||||
}
|
||||
|
||||
}
|
||||
-52
@@ -1,52 +0,0 @@
|
||||
/*
|
||||
* Copyright 2013-2022 the original author 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.springframework.boot.autoconfigure.data.web.SpringDataWebProperties;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
|
||||
|
||||
/**
|
||||
* Tests the pagination encoding and sorting.
|
||||
*
|
||||
* @author Yanming Zhou
|
||||
*/
|
||||
@EnableConfigurationProperties(SpringDataWebProperties.class)
|
||||
@SpringBootTest(classes = SpringEncoderTests.Application.class, webEnvironment = RANDOM_PORT,
|
||||
value = { "spring.application.name=springencodertest", "spring.jmx.enabled=false",
|
||||
"spring.data.web.pageable.pageParameter=pageNo", "spring.data.web.pageable.sizeParameter=pageSize",
|
||||
"spring.data.web.sort.sortParameter=orderBy" })
|
||||
public class PageableSpringQueryMapEncoderWithSpringDataWebTests extends PageableSpringQueryMapEncoderTests {
|
||||
|
||||
@Override
|
||||
protected String getPageParameter() {
|
||||
return "pageNo";
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String getSizeParameter() {
|
||||
return "pageSize";
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String getSortParameter() {
|
||||
return "orderBy";
|
||||
}
|
||||
|
||||
}
|
||||
+15
-16
@@ -26,8 +26,8 @@ import java.util.List;
|
||||
import feign.RequestTemplate;
|
||||
import feign.codec.EncodeException;
|
||||
import feign.codec.Encoder;
|
||||
import org.assertj.core.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
@@ -52,6 +52,7 @@ import org.springframework.http.converter.HttpMessageNotWritableException;
|
||||
import org.springframework.http.converter.ResourceHttpMessageConverter;
|
||||
import org.springframework.mock.web.MockMultipartFile;
|
||||
import org.springframework.test.annotation.DirtiesContext;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
@@ -69,12 +70,12 @@ import static org.springframework.http.MediaType.TEXT_PLAIN_VALUE;
|
||||
* @author Olga Maciaszek-Sharma
|
||||
* @author Ahmad Mozafarnia
|
||||
* @author Can Bezmen
|
||||
* @author Szymon Linowski
|
||||
*/
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@SpringBootTest(classes = SpringEncoderTests.Application.class, webEnvironment = WebEnvironment.RANDOM_PORT,
|
||||
value = { "spring.application.name=springencodertest", "spring.jmx.enabled=false" })
|
||||
@DirtiesContext
|
||||
class SpringEncoderTests {
|
||||
public class SpringEncoderTests {
|
||||
|
||||
@Autowired
|
||||
private FeignContext context;
|
||||
@@ -91,7 +92,7 @@ class SpringEncoderTests {
|
||||
private GenericHttpMessageConverter<?> myGenericConverter;
|
||||
|
||||
@Test
|
||||
void testCustomHttpMessageConverter() {
|
||||
public void testCustomHttpMessageConverter() {
|
||||
Encoder encoder = this.context.getInstance("foo", Encoder.class);
|
||||
assertThat(encoder).isNotNull();
|
||||
RequestTemplate request = new RequestTemplate();
|
||||
@@ -111,7 +112,7 @@ class SpringEncoderTests {
|
||||
|
||||
// gh-225
|
||||
@Test
|
||||
void testCustomGenericHttpMessageConverter() {
|
||||
public void testCustomGenericHttpMessageConverter() {
|
||||
Encoder encoder = this.context.getInstance("foo", Encoder.class);
|
||||
assertThat(encoder).isNotNull();
|
||||
RequestTemplate request = new RequestTemplate();
|
||||
@@ -134,7 +135,7 @@ class SpringEncoderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testBinaryData() {
|
||||
public void testBinaryData() {
|
||||
Encoder encoder = this.context.getInstance("foo", Encoder.class);
|
||||
assertThat(encoder).isNotNull();
|
||||
|
||||
@@ -146,21 +147,19 @@ class SpringEncoderTests {
|
||||
.isEqualTo(APPLICATION_OCTET_STREAM_VALUE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testMultipartFile1() {
|
||||
@Test(expected = EncodeException.class)
|
||||
public void testMultipartFile1() {
|
||||
Encoder encoder = this.context.getInstance("foo", Encoder.class);
|
||||
assertThat(encoder).isNotNull();
|
||||
RequestTemplate request = new RequestTemplate();
|
||||
|
||||
MultipartFile multipartFile = new MockMultipartFile("test_multipart_file", "hi".getBytes());
|
||||
|
||||
Assertions.assertThatExceptionOfType(EncodeException.class)
|
||||
.isThrownBy(() -> encoder.encode(multipartFile, MultipartFile.class, request));
|
||||
encoder.encode(multipartFile, MultipartFile.class, request);
|
||||
}
|
||||
|
||||
// gh-105, gh-107
|
||||
@Test
|
||||
void testMultipartFile2() {
|
||||
public void testMultipartFile2() {
|
||||
Encoder encoder = this.context.getInstance("foo", Encoder.class);
|
||||
assertThat(encoder).isNotNull();
|
||||
RequestTemplate request = new RequestTemplate();
|
||||
@@ -183,7 +182,7 @@ class SpringEncoderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testFromURLEncodedValue() {
|
||||
public void testFromURLEncodedValue() {
|
||||
Encoder encoder = context.getInstance("formUrlEncoded", Encoder.class);
|
||||
assertThat(encoder).isNotNull();
|
||||
RequestTemplate request = new RequestTemplate();
|
||||
@@ -194,7 +193,7 @@ class SpringEncoderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testNoCharsetForBinaryFiles() {
|
||||
public void testNoCharsetForBinaryFiles() {
|
||||
Encoder encoder = context.getInstance("test", Encoder.class);
|
||||
assertThat(encoder).isNotNull();
|
||||
RequestTemplate request = new RequestTemplate();
|
||||
@@ -207,7 +206,7 @@ class SpringEncoderTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testUTF8CharsetForTextFiles() {
|
||||
public void testUTF8CharsetForTextFiles() {
|
||||
Encoder encoder = context.getInstance("test", Encoder.class);
|
||||
assertThat(encoder).isNotNull();
|
||||
RequestTemplate request = new RequestTemplate();
|
||||
|
||||
+49
-152
@@ -31,8 +31,8 @@ import java.util.Map;
|
||||
import com.fasterxml.jackson.annotation.JsonAutoDetect;
|
||||
import feign.MethodMetadata;
|
||||
import feign.Param;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import org.springframework.cloud.openfeign.CollectionFormat;
|
||||
import org.springframework.cloud.openfeign.SpringQueryMap;
|
||||
@@ -45,7 +45,6 @@ import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.util.MultiValueMap;
|
||||
import org.springframework.util.ReflectionUtils;
|
||||
import org.springframework.web.bind.annotation.CookieValue;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.MatrixVariable;
|
||||
@@ -62,12 +61,10 @@ 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.CSV;
|
||||
import static feign.CollectionFormat.SSV;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
|
||||
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
|
||||
import static org.junit.jupiter.api.Assumptions.assumeTrue;
|
||||
import static org.junit.Assume.assumeTrue;
|
||||
|
||||
/**
|
||||
* @author chadjaros
|
||||
@@ -76,12 +73,8 @@ import static org.junit.jupiter.api.Assumptions.assumeTrue;
|
||||
* @author Aaron Whiteside
|
||||
* @author Artyom Romanenko
|
||||
* @author Olga Maciaszek-Sharma
|
||||
* @author Szymon Linowski
|
||||
* @author Sam Kruglov
|
||||
* @author Bhavya Agrawal
|
||||
**/
|
||||
|
||||
class SpringMvcContractTests {
|
||||
*/
|
||||
public class SpringMvcContractTests {
|
||||
|
||||
private static final Class<?> EXECUTABLE_TYPE;
|
||||
|
||||
@@ -121,13 +114,13 @@ class SpringMvcContractTests {
|
||||
return false;
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
@Before
|
||||
public void setup() {
|
||||
contract = new SpringMvcContract(Collections.emptyList(), getConversionService());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testProcessAnnotationOnMethod_Simple() throws Exception {
|
||||
public void testProcessAnnotationOnMethod_Simple() throws Exception {
|
||||
Method method = TestTemplate_Simple.class.getDeclaredMethod("getTest", String.class);
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
|
||||
@@ -139,17 +132,7 @@ class SpringMvcContractTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testProcessAnnotationOnMethod_Simple_RegexPathVariable() throws Exception {
|
||||
Method method = TestTemplate_Simple.class.getDeclaredMethod("getTestWithDigitalId", String.class);
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
|
||||
assertThat(data.template().url()).isEqualTo("/test/{id:\\d+}");
|
||||
assertThat(data.template().method()).isEqualTo("GET");
|
||||
assertThat(data.formParams()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testProcessAnnotationOnMethod_Simple_SlashEncoded() throws Exception {
|
||||
public void testProcessAnnotationOnMethod_Simple_SlashEncoded() throws Exception {
|
||||
contract = new SpringMvcContract(Collections.emptyList(), getConversionService(), false);
|
||||
|
||||
Method method = TestTemplate_Simple.class.getDeclaredMethod("getTest", String.class);
|
||||
@@ -161,7 +144,7 @@ class SpringMvcContractTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testProcessAnnotations_Simple() throws Exception {
|
||||
public void testProcessAnnotations_Simple() throws Exception {
|
||||
Method method = TestTemplate_Simple.class.getDeclaredMethod("getTest", String.class);
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
|
||||
@@ -174,40 +157,7 @@ class SpringMvcContractTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testProcessAnnotations_SimpleNoPath() throws Exception {
|
||||
Method method = TestTemplate_Simple.class.getDeclaredMethod("getTest");
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
|
||||
assertThat(data.template().url()).isEqualTo("/");
|
||||
assertThat(data.template().method()).isEqualTo("GET");
|
||||
assertThat(data.template().headers().get("Accept").iterator().next())
|
||||
.isEqualTo(MediaType.APPLICATION_JSON_VALUE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testProcessAnnotations_SimplePathIsOnlyASlash() throws Exception {
|
||||
Method method = TestTemplate_Simple.class.getDeclaredMethod("getSlashPath", String.class);
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
|
||||
assertThat(data.template().url()).isEqualTo("/?id=" + "{id}");
|
||||
assertThat(data.template().method()).isEqualTo("GET");
|
||||
assertThat(data.template().headers().get("Accept").iterator().next())
|
||||
.isEqualTo(MediaType.APPLICATION_JSON_VALUE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testProcessAnnotations_MissingLeadingSlashInPath() throws Exception {
|
||||
Method method = TestTemplate_Simple.class.getDeclaredMethod("getTestNoLeadingSlash", String.class);
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
|
||||
assertThat(data.template().url()).isEqualTo("/test?name=" + "{name}");
|
||||
assertThat(data.template().method()).isEqualTo("GET");
|
||||
assertThat(data.template().headers().get("Accept").iterator().next())
|
||||
.isEqualTo(MediaType.APPLICATION_JSON_VALUE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testProcessAnnotations_SimpleGetMapping() throws Exception {
|
||||
public void testProcessAnnotations_SimpleGetMapping() throws Exception {
|
||||
Method method = TestTemplate_Simple.class.getDeclaredMethod("getMappingTest", String.class);
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
|
||||
@@ -220,7 +170,7 @@ class SpringMvcContractTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testProcessAnnotations_Class_Annotations_RequestMapping() {
|
||||
public void testProcessAnnotations_Class_Annotations_RequestMapping() {
|
||||
assertThatIllegalArgumentException().isThrownBy(() -> {
|
||||
Method method = TestTemplate_Class_RequestMapping.class.getDeclaredMethod("getSpecificTest", String.class,
|
||||
String.class);
|
||||
@@ -229,7 +179,7 @@ class SpringMvcContractTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testProcessAnnotations_Class_AnnotationsGetAllTests() throws Exception {
|
||||
public void testProcessAnnotations_Class_AnnotationsGetAllTests() throws Exception {
|
||||
Method method = TestTemplate_Class_Annotations.class.getDeclaredMethod("getAllTests", String.class);
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
|
||||
@@ -241,7 +191,7 @@ class SpringMvcContractTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testProcessAnnotations_ExtendedInterface() throws Exception {
|
||||
public void testProcessAnnotations_ExtendedInterface() throws Exception {
|
||||
Method extendedMethod = TestTemplate_Extended.class.getMethod("getAllTests", String.class);
|
||||
MethodMetadata extendedData = contract.parseAndValidateMetadata(extendedMethod.getDeclaringClass(),
|
||||
extendedMethod);
|
||||
@@ -257,7 +207,7 @@ class SpringMvcContractTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testProcessAnnotations_SimplePost() throws Exception {
|
||||
public void testProcessAnnotations_SimplePost() throws Exception {
|
||||
Method method = TestTemplate_Simple.class.getDeclaredMethod("postTest", TestObject.class);
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
|
||||
@@ -269,7 +219,7 @@ class SpringMvcContractTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testProcessAnnotations_SimplePostMapping() throws Exception {
|
||||
public void testProcessAnnotations_SimplePostMapping() throws Exception {
|
||||
Method method = TestTemplate_Simple.class.getDeclaredMethod("postMappingTest", TestObject.class);
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
|
||||
@@ -281,7 +231,7 @@ class SpringMvcContractTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testProcessAnnotationsOnMethod_Advanced() throws Exception {
|
||||
public void testProcessAnnotationsOnMethod_Advanced() throws Exception {
|
||||
Method method = TestTemplate_Advanced.class.getDeclaredMethod("getTest", String.class, String.class,
|
||||
Integer.class);
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
@@ -293,7 +243,7 @@ class SpringMvcContractTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testProcessAnnotationsOnMethod_Advanced_UnknownAnnotation() throws Exception {
|
||||
public void testProcessAnnotationsOnMethod_Advanced_UnknownAnnotation() throws Exception {
|
||||
Method method = TestTemplate_Advanced.class.getDeclaredMethod("getTest", String.class, String.class,
|
||||
Integer.class);
|
||||
contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
@@ -302,7 +252,7 @@ class SpringMvcContractTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testProcessAnnotationsOnMethod_CollectionFormat() throws NoSuchMethodException {
|
||||
public void testProcessAnnotationsOnMethod_CollectionFormat() throws NoSuchMethodException {
|
||||
Method method = TestTemplate_Advanced.class.getDeclaredMethod("getWithCollectionFormat");
|
||||
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
@@ -311,16 +261,7 @@ class SpringMvcContractTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void processAnnotationOnClass_CollectionFormat() throws NoSuchMethodException {
|
||||
Method method = TestTemplate_Advanced.class.getDeclaredMethod("getWithoutCollectionFormat");
|
||||
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
|
||||
assertThat(data.template().collectionFormat()).isEqualTo(CSV);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testProcessAnnotations_Advanced() throws Exception {
|
||||
public void testProcessAnnotations_Advanced() throws Exception {
|
||||
Method method = TestTemplate_Advanced.class.getDeclaredMethod("getTest", String.class, String.class,
|
||||
Integer.class);
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
@@ -340,7 +281,7 @@ class SpringMvcContractTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testProcessAnnotations_Aliased() throws Exception {
|
||||
public void testProcessAnnotations_Aliased() throws Exception {
|
||||
Method method = TestTemplate_Advanced.class.getDeclaredMethod("getTest2", String.class, Integer.class);
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
|
||||
@@ -357,7 +298,7 @@ class SpringMvcContractTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testProcessAnnotations_DateTimeFormatParam() throws Exception {
|
||||
public void testProcessAnnotations_DateTimeFormatParam() throws Exception {
|
||||
Method method = TestTemplate_DateTimeFormatParameter.class.getDeclaredMethod("getTest", LocalDateTime.class);
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
|
||||
@@ -374,7 +315,7 @@ class SpringMvcContractTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testProcessAnnotations_NumberFormatParam() throws Exception {
|
||||
public void testProcessAnnotations_NumberFormatParam() throws Exception {
|
||||
Method method = TestTemplate_NumberFormatParameter.class.getDeclaredMethod("getTest", BigDecimal.class);
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
|
||||
@@ -392,7 +333,7 @@ class SpringMvcContractTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testProcessAnnotations_Advanced2() throws Exception {
|
||||
public void testProcessAnnotations_Advanced2() throws Exception {
|
||||
Method method = TestTemplate_Advanced.class.getDeclaredMethod("getTest");
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
|
||||
@@ -403,7 +344,7 @@ class SpringMvcContractTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testProcessAnnotations_Advanced3() throws Exception {
|
||||
public void testProcessAnnotations_Advanced3() throws Exception {
|
||||
Method method = TestTemplate_Simple.class.getDeclaredMethod("getTest");
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
|
||||
@@ -415,7 +356,7 @@ class SpringMvcContractTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testProcessAnnotations_Advanced3_DecodeSlashFlagNotModified() throws Exception {
|
||||
public void testProcessAnnotations_Advanced3_DecodeSlashFlagNotModified() throws Exception {
|
||||
contract = new SpringMvcContract(Collections.emptyList(), getConversionService(), false);
|
||||
|
||||
Method method = TestTemplate_Simple.class.getDeclaredMethod("getTest");
|
||||
@@ -427,7 +368,7 @@ class SpringMvcContractTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testProcessAnnotations_ListParams() throws Exception {
|
||||
public void testProcessAnnotations_ListParams() throws Exception {
|
||||
Method method = TestTemplate_ListParams.class.getDeclaredMethod("getTest", List.class);
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
|
||||
@@ -438,7 +379,7 @@ class SpringMvcContractTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testProcessAnnotations_ListParamsWithoutName() throws Exception {
|
||||
public void testProcessAnnotations_ListParamsWithoutName() throws Exception {
|
||||
Method method = TestTemplate_ListParamsWithoutName.class.getDeclaredMethod("getTest", List.class);
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
|
||||
@@ -449,7 +390,7 @@ class SpringMvcContractTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testProcessAnnotations_MapParams() throws Exception {
|
||||
public void testProcessAnnotations_MapParams() throws Exception {
|
||||
Method method = TestTemplate_MapParams.class.getDeclaredMethod("getTest", Map.class);
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
|
||||
@@ -460,7 +401,7 @@ class SpringMvcContractTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testProcessHeaders() throws Exception {
|
||||
public void testProcessHeaders() throws Exception {
|
||||
Method method = TestTemplate_Headers.class.getDeclaredMethod("getTest", String.class);
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
|
||||
@@ -470,7 +411,7 @@ class SpringMvcContractTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testProcessHeadersWithoutValues() throws Exception {
|
||||
public void testProcessHeadersWithoutValues() throws Exception {
|
||||
Method method = TestTemplate_HeadersWithoutValues.class.getDeclaredMethod("getTest", String.class);
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
|
||||
@@ -480,11 +421,11 @@ class SpringMvcContractTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testProcessAnnotations_Fallback() throws Exception {
|
||||
public void testProcessAnnotations_Fallback() throws Exception {
|
||||
Method method = TestTemplate_Advanced.class.getDeclaredMethod("getTestFallback", String.class, String.class,
|
||||
Integer.class);
|
||||
|
||||
assumeTrue(hasJava8ParameterNames(method), "does not have java 8 parameter names");
|
||||
assumeTrue("does not have java 8 parameter names", hasJava8ParameterNames(method));
|
||||
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
|
||||
@@ -502,7 +443,7 @@ class SpringMvcContractTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testProcessHeaderMap() throws Exception {
|
||||
public void testProcessHeaderMap() throws Exception {
|
||||
Method method = TestTemplate_HeaderMap.class.getDeclaredMethod("headerMap", MultiValueMap.class, String.class);
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
|
||||
@@ -513,16 +454,15 @@ class SpringMvcContractTests {
|
||||
assertThat(headers.get("aHeader").iterator().next()).isEqualTo("{aHeader}");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testProcessHeaderMapMoreThanOnce() throws Exception {
|
||||
@Test(expected = IllegalStateException.class)
|
||||
public void testProcessHeaderMapMoreThanOnce() throws Exception {
|
||||
Method method = TestTemplate_HeaderMap.class.getDeclaredMethod("headerMapMoreThanOnce", MultiValueMap.class,
|
||||
MultiValueMap.class);
|
||||
assertThatExceptionOfType(IllegalStateException.class)
|
||||
.isThrownBy(() -> contract.parseAndValidateMetadata(method.getDeclaringClass(), method));
|
||||
contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testProcessQueryMap() throws Exception {
|
||||
public void testProcessQueryMap() throws Exception {
|
||||
Method method = TestTemplate_QueryMap.class.getDeclaredMethod("queryMap", MultiValueMap.class, String.class);
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
|
||||
@@ -534,7 +474,7 @@ class SpringMvcContractTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testProcessQueryMapObject() throws Exception {
|
||||
public void testProcessQueryMapObject() throws Exception {
|
||||
Method method = TestTemplate_QueryMap.class.getDeclaredMethod("queryMapObject", TestObject.class, String.class);
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
|
||||
@@ -545,16 +485,15 @@ class SpringMvcContractTests {
|
||||
assertThat(params.get("aParam").iterator().next()).isEqualTo("{aParam}");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testProcessQueryMapMoreThanOnce() throws Exception {
|
||||
@Test(expected = IllegalStateException.class)
|
||||
public void testProcessQueryMapMoreThanOnce() throws Exception {
|
||||
Method method = TestTemplate_QueryMap.class.getDeclaredMethod("queryMapMoreThanOnce", MultiValueMap.class,
|
||||
MultiValueMap.class);
|
||||
assertThatExceptionOfType(IllegalStateException.class)
|
||||
.isThrownBy(() -> contract.parseAndValidateMetadata(method.getDeclaringClass(), method));
|
||||
contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testMatrixVariable_MapParam() throws Exception {
|
||||
public void testMatrixVariable_MapParam() throws Exception {
|
||||
Method method = TestTemplate_MatrixVariable.class.getDeclaredMethod("matrixVariable", Map.class);
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
|
||||
@@ -567,7 +506,7 @@ class SpringMvcContractTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testMatrixVariable_ObjectParam() throws Exception {
|
||||
public void testMatrixVariable_ObjectParam() throws Exception {
|
||||
Method method = TestTemplate_MatrixVariable.class.getDeclaredMethod("matrixVariableObject", Object.class);
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
|
||||
@@ -577,7 +516,7 @@ class SpringMvcContractTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testMatrixVariableWithNoName() throws NoSuchMethodException {
|
||||
public void testMatrixVariableWithNoName() throws NoSuchMethodException {
|
||||
Method method = TestTemplate_MatrixVariable.class.getDeclaredMethod("matrixVariableNotNamed", Map.class);
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
Map<String, String> testMap = new HashMap<>();
|
||||
@@ -590,7 +529,7 @@ class SpringMvcContractTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testAddingTemplatedParameterWithTheSameKey() throws NoSuchMethodException {
|
||||
public void testAddingTemplatedParameterWithTheSameKey() throws NoSuchMethodException {
|
||||
Method method = TestTemplate_Advanced.class.getDeclaredMethod("testAddingTemplatedParamForExistingKey",
|
||||
String.class);
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
@@ -599,7 +538,7 @@ class SpringMvcContractTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testMultipleRequestPartAnnotations() throws NoSuchMethodException {
|
||||
public void testMultipleRequestPartAnnotations() throws NoSuchMethodException {
|
||||
Method method = TestTemplate_RequestPart.class.getDeclaredMethod("requestWithMultipleParts",
|
||||
MultipartFile.class, String.class);
|
||||
|
||||
@@ -607,24 +546,6 @@ class SpringMvcContractTests {
|
||||
assertThat(data.formParams()).contains("file", "id");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSingleCookieAnnotation() throws NoSuchMethodException {
|
||||
Method method = TestTemplate_Cookies.class.getDeclaredMethod("singleCookie", String.class, String.class);
|
||||
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
assertThat(data.template().headers().get("cookie").iterator().next()).isEqualTo("cookie1={cookie1}");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testMultipleCookiesAnnotation() throws NoSuchMethodException {
|
||||
Method method = TestTemplate_Cookies.class.getDeclaredMethod("multipleCookies", String.class, String.class,
|
||||
String.class);
|
||||
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
assertThat(data.template().headers().get("cookie").iterator().next())
|
||||
.isEqualTo("cookie1={cookie1}; cookie2={cookie2}");
|
||||
}
|
||||
|
||||
private ConversionService getConversionService() {
|
||||
FormattingConversionServiceFactoryBean conversionServiceFactoryBean = new FormattingConversionServiceFactoryBean();
|
||||
conversionServiceFactoryBean.afterPropertiesSet();
|
||||
@@ -636,9 +557,6 @@ class SpringMvcContractTests {
|
||||
@RequestMapping(value = "/test/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
ResponseEntity<TestObject> getTest(@PathVariable("id") String id);
|
||||
|
||||
@GetMapping("/test/{id:\\d+}")
|
||||
ResponseEntity<TestObject> getTestWithDigitalId(@PathVariable("id") String id);
|
||||
|
||||
@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
TestObject getTest();
|
||||
|
||||
@@ -651,12 +569,6 @@ class SpringMvcContractTests {
|
||||
@PostMapping(produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
TestObject postMappingTest(@RequestBody TestObject object);
|
||||
|
||||
@GetMapping(value = "/", produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
ResponseEntity<TestObject> getSlashPath(@RequestParam("id") String id);
|
||||
|
||||
@GetMapping(path = "test", produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
ResponseEntity<TestObject> getTestNoLeadingSlash(@RequestParam("name") String name);
|
||||
|
||||
}
|
||||
|
||||
@RequestMapping("/prepend/{classId}")
|
||||
@@ -688,17 +600,6 @@ class SpringMvcContractTests {
|
||||
|
||||
}
|
||||
|
||||
public interface TestTemplate_Cookies {
|
||||
|
||||
@GetMapping("/test/{id}")
|
||||
ResponseEntity<TestObject> singleCookie(@PathVariable("id") String id, @CookieValue("cookie1") String cookie1);
|
||||
|
||||
@GetMapping("/test/{id}")
|
||||
ResponseEntity<TestObject> multipleCookies(@PathVariable("id") String id,
|
||||
@CookieValue("cookie1") String cookie1, @CookieValue("cookie2") String cookie2);
|
||||
|
||||
}
|
||||
|
||||
public interface TestTemplate_HeadersWithoutValues {
|
||||
|
||||
@GetMapping(value = "/test/{id}", headers = { "X-Foo", "!X-Bar", "X-Baz!=fooBar" })
|
||||
@@ -775,16 +676,12 @@ class SpringMvcContractTests {
|
||||
}
|
||||
|
||||
@JsonAutoDetect
|
||||
@CollectionFormat(CSV)
|
||||
public interface TestTemplate_Advanced {
|
||||
|
||||
@CollectionFormat(SSV)
|
||||
@GetMapping
|
||||
ResponseEntity<TestObject> getWithCollectionFormat();
|
||||
|
||||
@GetMapping
|
||||
ResponseEntity<TestObject> getWithoutCollectionFormat();
|
||||
|
||||
@ExceptionHandler
|
||||
@PutMapping(path = "/test/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
ResponseEntity<TestObject> getTest(@RequestHeader("Authorization") String auth, @PathVariable("id") String id,
|
||||
@@ -833,10 +730,10 @@ class SpringMvcContractTests {
|
||||
|
||||
public Double number;
|
||||
|
||||
TestObject() {
|
||||
public TestObject() {
|
||||
}
|
||||
|
||||
TestObject(String something, Double number) {
|
||||
public TestObject(String something, Double number) {
|
||||
this.something = something;
|
||||
this.number = number;
|
||||
}
|
||||
|
||||
+1
-1
@@ -99,7 +99,7 @@ public class EqualsAndHashCodeAssert {
|
||||
*/
|
||||
public static void assertEqualsAndHashCodeConsistency(Object objectOne, Object objectTwo) {
|
||||
assertThat(objectOne.equals(objectTwo)).isTrue();
|
||||
assertThat(objectOne).hasSameHashCodeAs(objectTwo);
|
||||
assertThat(objectOne.hashCode()).isEqualTo(objectTwo.hashCode());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+2
-1
@@ -47,7 +47,8 @@ import static org.mockito.Mockito.mockingDetails;
|
||||
* @author Olga Maciaszek-Sharma
|
||||
*/
|
||||
@SpringBootTest(properties = { "feign.okhttp.enabled: true", "spring.cloud.httpclientfactories.ok.enabled: true",
|
||||
"feign.okhttp.enabled: true", "feign.httpclient.enabled: false",
|
||||
"ribbon.eureka.enabled = false", "ribbon.okhttp.enabled: true", "feign.okhttp.enabled: true",
|
||||
"ribbon.httpclient.enabled: false", "feign.httpclient.enabled: false",
|
||||
"spring.cloud.loadbalancer.retry.enabled=false" })
|
||||
@DirtiesContext
|
||||
class OkHttpClientConfigurationTests {
|
||||
|
||||
+10
-7
@@ -19,7 +19,8 @@ package org.springframework.cloud.openfeign.valid;
|
||||
import java.util.List;
|
||||
|
||||
import feign.Logger;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||
@@ -35,6 +36,7 @@ import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
import org.springframework.test.annotation.DirtiesContext;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@@ -45,12 +47,13 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
|
||||
* @author Spencer Gibb
|
||||
* @author Jakub Narloch
|
||||
*/
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@SpringBootTest(classes = FeignClientNotPrimaryTests.Application.class, webEnvironment = RANDOM_PORT,
|
||||
value = { "spring.application.name=feignclientnotprimarytest",
|
||||
"logging.level.org.springframework.cloud.openfeign.valid=DEBUG", "feign.httpclient.enabled=false",
|
||||
"feign.okhttp.enabled=false" })
|
||||
@DirtiesContext
|
||||
class FeignClientNotPrimaryTests {
|
||||
public class FeignClientNotPrimaryTests {
|
||||
|
||||
public static final String HELLO_WORLD_1 = "hello world 1";
|
||||
|
||||
@@ -61,17 +64,17 @@ class FeignClientNotPrimaryTests {
|
||||
private List<TestClient> testClients;
|
||||
|
||||
@Test
|
||||
void testClientType() {
|
||||
public void testClientType() {
|
||||
assertThat(this.testClient).as("testClient was of wrong type").isInstanceOf(PrimaryTestClient.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testClientCount() {
|
||||
public void testClientCount() {
|
||||
assertThat(this.testClients).as("testClients was wrong").hasSize(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSimpleType() {
|
||||
public void testSimpleType() {
|
||||
Hello hello = this.testClient.getHello();
|
||||
assertThat(hello).as("hello was null").isNull();
|
||||
}
|
||||
@@ -117,10 +120,10 @@ class FeignClientNotPrimaryTests {
|
||||
|
||||
private String message;
|
||||
|
||||
Hello() {
|
||||
public Hello() {
|
||||
}
|
||||
|
||||
Hello(String message) {
|
||||
public Hello(String message) {
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
|
||||
+5
-5
@@ -16,7 +16,7 @@
|
||||
|
||||
package org.springframework.cloud.openfeign.valid;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.Test;
|
||||
|
||||
import org.springframework.cloud.client.loadbalancer.LoadBalancerAutoConfiguration;
|
||||
import org.springframework.cloud.commons.httpclient.HttpClientConfiguration;
|
||||
@@ -34,17 +34,17 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
/**
|
||||
* @author Dave Syer
|
||||
*/
|
||||
class FeignClientValidationTests {
|
||||
public class FeignClientValidationTests {
|
||||
|
||||
@Test
|
||||
void validNotLoadBalanced() {
|
||||
public void validNotLoadBalanced() {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(GoodUrlConfiguration.class);
|
||||
assertThat(context.getBean(GoodUrlConfiguration.Client.class)).isNotNull();
|
||||
context.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
void validPlaceholder() {
|
||||
public void validPlaceholder() {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
|
||||
PlaceholderUrlConfiguration.class);
|
||||
assertThat(context.getBean(PlaceholderUrlConfiguration.Client.class)).isNotNull();
|
||||
@@ -52,7 +52,7 @@ class FeignClientValidationTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
void validLoadBalanced() {
|
||||
public void validLoadBalanced() {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
|
||||
LoadBalancerAutoConfiguration.class,
|
||||
org.springframework.cloud.loadbalancer.config.LoadBalancerAutoConfiguration.class,
|
||||
|
||||
+8
-5
@@ -18,7 +18,8 @@ package org.springframework.cloud.openfeign.valid;
|
||||
|
||||
import io.vavr.collection.HashSet;
|
||||
import io.vavr.collection.Set;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||
@@ -36,6 +37,7 @@ 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.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
@@ -45,18 +47,19 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
/**
|
||||
* @author Spencer Gibb
|
||||
*/
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@SpringBootTest(classes = IterableParameterTests.Application.class, webEnvironment = WebEnvironment.RANDOM_PORT,
|
||||
value = { "spring.application.name=iterableparametertest",
|
||||
"logging.level.org.springframework.cloud.openfeign.valid=DEBUG", "feign.httpclient.enabled=false",
|
||||
"feign.okhttp.enabled=false", "feign.circuitbreaker.enabled=false" })
|
||||
@DirtiesContext
|
||||
class IterableParameterTests {
|
||||
public class IterableParameterTests {
|
||||
|
||||
@Autowired
|
||||
private TestClient testClient;
|
||||
|
||||
@Test
|
||||
void testClient() {
|
||||
public void testClient() {
|
||||
assertThat(this.testClient).as("testClient was null").isNotNull();
|
||||
String results = this.testClient.echo(HashSet.of("a", "b"));
|
||||
assertThat(results).isEqualTo("a,b");
|
||||
@@ -74,7 +77,7 @@ class IterableParameterTests {
|
||||
@EnableAutoConfiguration
|
||||
@RestController
|
||||
@EnableFeignClients(clients = TestClient.class)
|
||||
@LoadBalancerClient(name = "localapp", configuration = LocalLoadBalancerConfiguration.class)
|
||||
@LoadBalancerClient(name = "localapp", configuration = LocalRibbonClientConfiguration.class)
|
||||
@Import(NoSecurityConfiguration.class)
|
||||
protected static class Application {
|
||||
|
||||
@@ -86,7 +89,7 @@ class IterableParameterTests {
|
||||
}
|
||||
|
||||
// Load balancer with fixed server list for "local" pointing to localhost
|
||||
public static class LocalLoadBalancerConfiguration {
|
||||
public static class LocalRibbonClientConfiguration {
|
||||
|
||||
@LocalServerPort
|
||||
private int port = 0;
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user