Reformat with updated JavaFormat plugin version.
This commit is contained in:
@@ -43,8 +43,7 @@ public interface AnnotatedParameterProcessor {
|
||||
* @param method the method that contains the annotation
|
||||
* @return whether the parameter is http
|
||||
*/
|
||||
boolean processArgument(AnnotatedParameterContext context, Annotation annotation,
|
||||
Method method);
|
||||
boolean processArgument(AnnotatedParameterContext context, Annotation annotation, Method method);
|
||||
|
||||
/**
|
||||
* Specifies the parameter context.
|
||||
|
||||
@@ -25,8 +25,8 @@ import feign.Target;
|
||||
class DefaultTargeter implements Targeter {
|
||||
|
||||
@Override
|
||||
public <T> T target(FeignClientFactoryBean factory, Feign.Builder feign,
|
||||
FeignContext context, Target.HardCodedTarget<T> target) {
|
||||
public <T> T target(FeignClientFactoryBean factory, Feign.Builder feign, FeignContext context,
|
||||
Target.HardCodedTarget<T> target) {
|
||||
return feign.target(target);
|
||||
}
|
||||
|
||||
|
||||
@@ -57,8 +57,7 @@ import org.springframework.context.annotation.Import;
|
||||
*/
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@ConditionalOnClass(Feign.class)
|
||||
@EnableConfigurationProperties({ FeignClientProperties.class,
|
||||
FeignHttpClientProperties.class })
|
||||
@EnableConfigurationProperties({ FeignClientProperties.class, FeignHttpClientProperties.class })
|
||||
@Import(DefaultGzipDecoderConfiguration.class)
|
||||
public class FeignAutoConfiguration {
|
||||
|
||||
@@ -111,13 +110,10 @@ public class FeignAutoConfiguration {
|
||||
public HttpClientConnectionManager connectionManager(
|
||||
ApacheHttpClientConnectionManagerFactory connectionManagerFactory,
|
||||
FeignHttpClientProperties httpClientProperties) {
|
||||
final HttpClientConnectionManager connectionManager = connectionManagerFactory
|
||||
.newConnectionManager(httpClientProperties.isDisableSslValidation(),
|
||||
httpClientProperties.getMaxConnections(),
|
||||
httpClientProperties.getMaxConnectionsPerRoute(),
|
||||
httpClientProperties.getTimeToLive(),
|
||||
httpClientProperties.getTimeToLiveUnit(),
|
||||
this.registryBuilder);
|
||||
final HttpClientConnectionManager connectionManager = connectionManagerFactory.newConnectionManager(
|
||||
httpClientProperties.isDisableSslValidation(), httpClientProperties.getMaxConnections(),
|
||||
httpClientProperties.getMaxConnectionsPerRoute(), httpClientProperties.getTimeToLive(),
|
||||
httpClientProperties.getTimeToLiveUnit(), this.registryBuilder);
|
||||
this.connectionManagerTimer.schedule(new TimerTask() {
|
||||
@Override
|
||||
public void run() {
|
||||
@@ -133,10 +129,8 @@ public class FeignAutoConfiguration {
|
||||
FeignHttpClientProperties httpClientProperties) {
|
||||
RequestConfig defaultRequestConfig = RequestConfig.custom()
|
||||
.setConnectTimeout(httpClientProperties.getConnectionTimeout())
|
||||
.setRedirectsEnabled(httpClientProperties.isFollowRedirects())
|
||||
.build();
|
||||
this.httpClient = httpClientFactory.createBuilder()
|
||||
.setConnectionManager(httpClientConnectionManager)
|
||||
.setRedirectsEnabled(httpClientProperties.isFollowRedirects()).build();
|
||||
this.httpClient = httpClientFactory.createBuilder().setConnectionManager(httpClientConnectionManager)
|
||||
.setDefaultRequestConfig(defaultRequestConfig).build();
|
||||
return this.httpClient;
|
||||
}
|
||||
@@ -167,8 +161,7 @@ public class FeignAutoConfiguration {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean(ConnectionPool.class)
|
||||
public ConnectionPool httpClientConnectionPool(
|
||||
FeignHttpClientProperties httpClientProperties,
|
||||
public ConnectionPool httpClientConnectionPool(FeignHttpClientProperties httpClientProperties,
|
||||
OkHttpClientConnectionPoolFactory connectionPoolFactory) {
|
||||
Integer maxTotalConnections = httpClientProperties.getMaxConnections();
|
||||
Long timeToLive = httpClientProperties.getTimeToLive();
|
||||
@@ -177,16 +170,14 @@ public class FeignAutoConfiguration {
|
||||
}
|
||||
|
||||
@Bean
|
||||
public okhttp3.OkHttpClient client(OkHttpClientFactory httpClientFactory,
|
||||
ConnectionPool connectionPool,
|
||||
public okhttp3.OkHttpClient client(OkHttpClientFactory httpClientFactory, ConnectionPool connectionPool,
|
||||
FeignHttpClientProperties httpClientProperties) {
|
||||
Boolean followRedirects = httpClientProperties.isFollowRedirects();
|
||||
Integer connectTimeout = httpClientProperties.getConnectionTimeout();
|
||||
Boolean disableSslValidation = httpClientProperties.isDisableSslValidation();
|
||||
this.okHttpClient = httpClientFactory.createBuilder(disableSslValidation)
|
||||
.connectTimeout(connectTimeout, TimeUnit.MILLISECONDS)
|
||||
.followRedirects(followRedirects).connectionPool(connectionPool)
|
||||
.build();
|
||||
.connectTimeout(connectTimeout, TimeUnit.MILLISECONDS).followRedirects(followRedirects)
|
||||
.connectionPool(connectionPool).build();
|
||||
return this.okHttpClient;
|
||||
}
|
||||
|
||||
|
||||
@@ -39,8 +39,8 @@ public class FeignClientBuilder {
|
||||
return new Builder<>(this.applicationContext, type, name);
|
||||
}
|
||||
|
||||
public <T> Builder<T> forType(final Class<T> type,
|
||||
final FeignClientFactoryBean clientFactoryBean, final String name) {
|
||||
public <T> Builder<T> forType(final Class<T> type, final FeignClientFactoryBean clientFactoryBean,
|
||||
final String name) {
|
||||
return new Builder<>(this.applicationContext, clientFactoryBean, type, name);
|
||||
}
|
||||
|
||||
@@ -53,14 +53,12 @@ public class FeignClientBuilder {
|
||||
|
||||
private FeignClientFactoryBean feignClientFactoryBean;
|
||||
|
||||
private Builder(final ApplicationContext applicationContext, final Class<T> type,
|
||||
final String name) {
|
||||
private Builder(final ApplicationContext applicationContext, final Class<T> type, final String name) {
|
||||
this(applicationContext, new FeignClientFactoryBean(), type, name);
|
||||
}
|
||||
|
||||
private Builder(final ApplicationContext applicationContext,
|
||||
final FeignClientFactoryBean clientFactoryBean, final Class<T> type,
|
||||
final String name) {
|
||||
private Builder(final ApplicationContext applicationContext, final FeignClientFactoryBean clientFactoryBean,
|
||||
final Class<T> type, final String name) {
|
||||
this.feignClientFactoryBean = clientFactoryBean;
|
||||
|
||||
this.feignClientFactoryBean.setApplicationContext(applicationContext);
|
||||
|
||||
@@ -55,8 +55,7 @@ import org.springframework.util.StringUtils;
|
||||
* @author Matt King
|
||||
* @author Olga Maciaszek-Sharma
|
||||
*/
|
||||
public class FeignClientFactoryBean
|
||||
implements FactoryBean<Object>, InitializingBean, ApplicationContextAware {
|
||||
public class FeignClientFactoryBean implements FactoryBean<Object>, InitializingBean, ApplicationContextAware {
|
||||
|
||||
/***********************************
|
||||
* WARNING! Nothing in this class should be @Autowired. It causes NPEs because of some
|
||||
@@ -113,37 +112,29 @@ public class FeignClientFactoryBean
|
||||
}
|
||||
|
||||
private void applyBuildCustomizers(FeignContext context, Feign.Builder builder) {
|
||||
Map<String, FeignBuilderCustomizer> customizerMap = context
|
||||
.getInstances(contextId, FeignBuilderCustomizer.class);
|
||||
Map<String, FeignBuilderCustomizer> customizerMap = context.getInstances(contextId,
|
||||
FeignBuilderCustomizer.class);
|
||||
|
||||
if (customizerMap != null) {
|
||||
customizerMap.values().stream()
|
||||
.sorted(AnnotationAwareOrderComparator.INSTANCE)
|
||||
.forEach(feignBuilderCustomizer -> feignBuilderCustomizer
|
||||
.customize(builder));
|
||||
customizerMap.values().stream().sorted(AnnotationAwareOrderComparator.INSTANCE)
|
||||
.forEach(feignBuilderCustomizer -> feignBuilderCustomizer.customize(builder));
|
||||
}
|
||||
}
|
||||
|
||||
protected void configureFeign(FeignContext context, Feign.Builder builder) {
|
||||
FeignClientProperties properties = applicationContext
|
||||
.getBean(FeignClientProperties.class);
|
||||
FeignClientProperties properties = applicationContext.getBean(FeignClientProperties.class);
|
||||
|
||||
FeignClientConfigurer feignClientConfigurer = getOptional(context,
|
||||
FeignClientConfigurer.class);
|
||||
FeignClientConfigurer feignClientConfigurer = getOptional(context, FeignClientConfigurer.class);
|
||||
setInheritParentContext(feignClientConfigurer.inheritParentConfiguration());
|
||||
|
||||
if (properties != null && inheritParentContext) {
|
||||
if (properties.isDefaultToProperties()) {
|
||||
configureUsingConfiguration(context, builder);
|
||||
configureUsingProperties(
|
||||
properties.getConfig().get(properties.getDefaultConfig()),
|
||||
builder);
|
||||
configureUsingProperties(properties.getConfig().get(properties.getDefaultConfig()), builder);
|
||||
configureUsingProperties(properties.getConfig().get(contextId), builder);
|
||||
}
|
||||
else {
|
||||
configureUsingProperties(
|
||||
properties.getConfig().get(properties.getDefaultConfig()),
|
||||
builder);
|
||||
configureUsingProperties(properties.getConfig().get(properties.getDefaultConfig()), builder);
|
||||
configureUsingProperties(properties.getConfig().get(contextId), builder);
|
||||
configureUsingConfiguration(context, builder);
|
||||
}
|
||||
@@ -153,8 +144,7 @@ public class FeignClientFactoryBean
|
||||
}
|
||||
}
|
||||
|
||||
protected void configureUsingConfiguration(FeignContext context,
|
||||
Feign.Builder builder) {
|
||||
protected void configureUsingConfiguration(FeignContext context, Feign.Builder builder) {
|
||||
Logger.Level level = getInheritedAwareOptional(context, Logger.Level.class);
|
||||
if (level != null) {
|
||||
builder.logLevel(level);
|
||||
@@ -163,48 +153,43 @@ public class FeignClientFactoryBean
|
||||
if (retryer != null) {
|
||||
builder.retryer(retryer);
|
||||
}
|
||||
ErrorDecoder errorDecoder = getInheritedAwareOptional(context,
|
||||
ErrorDecoder.class);
|
||||
ErrorDecoder errorDecoder = getInheritedAwareOptional(context, ErrorDecoder.class);
|
||||
if (errorDecoder != null) {
|
||||
builder.errorDecoder(errorDecoder);
|
||||
}
|
||||
else {
|
||||
FeignErrorDecoderFactory errorDecoderFactory = getOptional(context,
|
||||
FeignErrorDecoderFactory.class);
|
||||
FeignErrorDecoderFactory errorDecoderFactory = getOptional(context, FeignErrorDecoderFactory.class);
|
||||
if (errorDecoderFactory != null) {
|
||||
ErrorDecoder factoryErrorDecoder = errorDecoderFactory.create(type);
|
||||
builder.errorDecoder(factoryErrorDecoder);
|
||||
}
|
||||
}
|
||||
Request.Options options = getInheritedAwareOptional(context,
|
||||
Request.Options.class);
|
||||
Request.Options options = getInheritedAwareOptional(context, Request.Options.class);
|
||||
if (options != null) {
|
||||
builder.options(options);
|
||||
readTimeoutMillis = options.readTimeoutMillis();
|
||||
connectTimeoutMillis = options.connectTimeoutMillis();
|
||||
}
|
||||
Map<String, RequestInterceptor> requestInterceptors = getInheritedAwareInstances(
|
||||
context, RequestInterceptor.class);
|
||||
Map<String, RequestInterceptor> requestInterceptors = getInheritedAwareInstances(context,
|
||||
RequestInterceptor.class);
|
||||
if (requestInterceptors != null) {
|
||||
builder.requestInterceptors(requestInterceptors.values());
|
||||
}
|
||||
QueryMapEncoder queryMapEncoder = getInheritedAwareOptional(context,
|
||||
QueryMapEncoder.class);
|
||||
QueryMapEncoder queryMapEncoder = getInheritedAwareOptional(context, QueryMapEncoder.class);
|
||||
if (queryMapEncoder != null) {
|
||||
builder.queryMapEncoder(queryMapEncoder);
|
||||
}
|
||||
if (decode404) {
|
||||
builder.decode404();
|
||||
}
|
||||
ExceptionPropagationPolicy exceptionPropagationPolicy = getInheritedAwareOptional(
|
||||
context, ExceptionPropagationPolicy.class);
|
||||
ExceptionPropagationPolicy exceptionPropagationPolicy = getInheritedAwareOptional(context,
|
||||
ExceptionPropagationPolicy.class);
|
||||
if (exceptionPropagationPolicy != null) {
|
||||
builder.exceptionPropagationPolicy(exceptionPropagationPolicy);
|
||||
}
|
||||
}
|
||||
|
||||
protected void configureUsingProperties(
|
||||
FeignClientProperties.FeignClientConfiguration config,
|
||||
protected void configureUsingProperties(FeignClientProperties.FeignClientConfiguration config,
|
||||
Feign.Builder builder) {
|
||||
if (config == null) {
|
||||
return;
|
||||
@@ -214,13 +199,11 @@ public class FeignClientFactoryBean
|
||||
builder.logLevel(config.getLoggerLevel());
|
||||
}
|
||||
|
||||
connectTimeoutMillis = config.getConnectTimeout() != null
|
||||
? config.getConnectTimeout() : connectTimeoutMillis;
|
||||
readTimeoutMillis = config.getReadTimeout() != null ? config.getReadTimeout()
|
||||
: readTimeoutMillis;
|
||||
connectTimeoutMillis = config.getConnectTimeout() != null ? config.getConnectTimeout() : connectTimeoutMillis;
|
||||
readTimeoutMillis = config.getReadTimeout() != null ? config.getReadTimeout() : readTimeoutMillis;
|
||||
|
||||
builder.options(new Request.Options(connectTimeoutMillis, TimeUnit.MILLISECONDS,
|
||||
readTimeoutMillis, TimeUnit.MILLISECONDS, true));
|
||||
builder.options(new Request.Options(connectTimeoutMillis, TimeUnit.MILLISECONDS, readTimeoutMillis,
|
||||
TimeUnit.MILLISECONDS, true));
|
||||
|
||||
if (config.getRetryer() != null) {
|
||||
Retryer retryer = getOrInstantiate(config.getRetryer());
|
||||
@@ -232,8 +215,7 @@ public class FeignClientFactoryBean
|
||||
builder.errorDecoder(errorDecoder);
|
||||
}
|
||||
|
||||
if (config.getRequestInterceptors() != null
|
||||
&& !config.getRequestInterceptors().isEmpty()) {
|
||||
if (config.getRequestInterceptors() != null && !config.getRequestInterceptors().isEmpty()) {
|
||||
// this will add request interceptor to builder, not replace existing
|
||||
for (Class<RequestInterceptor> bean : config.getRequestInterceptors()) {
|
||||
RequestInterceptor interceptor = getOrInstantiate(bean);
|
||||
@@ -276,8 +258,7 @@ public class FeignClientFactoryBean
|
||||
protected <T> T get(FeignContext context, Class<T> type) {
|
||||
T instance = context.getInstance(contextId, type);
|
||||
if (instance == null) {
|
||||
throw new IllegalStateException(
|
||||
"No bean found of type " + type + " for " + contextId);
|
||||
throw new IllegalStateException("No bean found of type " + type + " for " + contextId);
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
@@ -295,8 +276,7 @@ public class FeignClientFactoryBean
|
||||
}
|
||||
}
|
||||
|
||||
protected <T> Map<String, T> getInheritedAwareInstances(FeignContext context,
|
||||
Class<T> type) {
|
||||
protected <T> Map<String, T> getInheritedAwareInstances(FeignContext context, Class<T> type) {
|
||||
if (inheritParentContext) {
|
||||
return context.getInstances(contextId, type);
|
||||
}
|
||||
@@ -305,8 +285,7 @@ public class FeignClientFactoryBean
|
||||
}
|
||||
}
|
||||
|
||||
protected <T> T loadBalance(Feign.Builder builder, FeignContext context,
|
||||
HardCodedTarget<T> target) {
|
||||
protected <T> T loadBalance(Feign.Builder builder, FeignContext context, HardCodedTarget<T> target) {
|
||||
Client client = getOptional(context, Client.class);
|
||||
if (client != null) {
|
||||
builder.client(client);
|
||||
@@ -340,8 +319,7 @@ public class FeignClientFactoryBean
|
||||
url = name;
|
||||
}
|
||||
url += cleanPath();
|
||||
return (T) loadBalance(builder, context,
|
||||
new HardCodedTarget<>(type, name, url));
|
||||
return (T) loadBalance(builder, context, new HardCodedTarget<>(type, name, url));
|
||||
}
|
||||
if (StringUtils.hasText(url) && !url.startsWith("http")) {
|
||||
url = "http://" + url;
|
||||
@@ -357,8 +335,7 @@ public class FeignClientFactoryBean
|
||||
builder.client(client);
|
||||
}
|
||||
Targeter targeter = get(context, Targeter.class);
|
||||
return (T) targeter.target(this, builder, context,
|
||||
new HardCodedTarget<>(type, name, url));
|
||||
return (T) targeter.target(this, builder, context, new HardCodedTarget<>(type, name, url));
|
||||
}
|
||||
|
||||
private String cleanPath() {
|
||||
@@ -474,32 +451,26 @@ public class FeignClientFactoryBean
|
||||
return false;
|
||||
}
|
||||
FeignClientFactoryBean that = (FeignClientFactoryBean) o;
|
||||
return Objects.equals(applicationContext, that.applicationContext)
|
||||
&& decode404 == that.decode404
|
||||
&& inheritParentContext == that.inheritParentContext
|
||||
&& Objects.equals(fallback, that.fallback)
|
||||
&& Objects.equals(fallbackFactory, that.fallbackFactory)
|
||||
&& Objects.equals(name, that.name) && Objects.equals(path, that.path)
|
||||
&& Objects.equals(type, that.type) && Objects.equals(url, that.url);
|
||||
return Objects.equals(applicationContext, that.applicationContext) && decode404 == that.decode404
|
||||
&& inheritParentContext == that.inheritParentContext && Objects.equals(fallback, that.fallback)
|
||||
&& Objects.equals(fallbackFactory, that.fallbackFactory) && Objects.equals(name, that.name)
|
||||
&& Objects.equals(path, that.path) && Objects.equals(type, that.type) && Objects.equals(url, that.url);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(applicationContext, decode404, inheritParentContext, fallback,
|
||||
fallbackFactory, name, path, type, url);
|
||||
return Objects.hash(applicationContext, decode404, inheritParentContext, fallback, fallbackFactory, name, path,
|
||||
type, url);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return new StringBuilder("FeignClientFactoryBean{").append("type=").append(type)
|
||||
.append(", ").append("name='").append(name).append("', ").append("url='")
|
||||
.append(url).append("', ").append("path='").append(path).append("', ")
|
||||
.append("decode404=").append(decode404).append(", ")
|
||||
.append("inheritParentContext=").append(inheritParentContext).append(", ")
|
||||
.append("applicationContext=").append(applicationContext).append(", ")
|
||||
.append("fallback=").append(fallback).append(", ")
|
||||
.append("fallbackFactory=").append(fallbackFactory).append("}")
|
||||
.toString();
|
||||
return new StringBuilder("FeignClientFactoryBean{").append("type=").append(type).append(", ").append("name='")
|
||||
.append(name).append("', ").append("url='").append(url).append("', ").append("path='").append(path)
|
||||
.append("', ").append("decode404=").append(decode404).append(", ").append("inheritParentContext=")
|
||||
.append(inheritParentContext).append(", ").append("applicationContext=").append(applicationContext)
|
||||
.append(", ").append("fallback=").append(fallback).append(", ").append("fallbackFactory=")
|
||||
.append(fallbackFactory).append("}").toString();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -78,8 +78,7 @@ public class FeignClientProperties {
|
||||
}
|
||||
FeignClientProperties that = (FeignClientProperties) o;
|
||||
return this.defaultToProperties == that.defaultToProperties
|
||||
&& Objects.equals(this.defaultConfig, that.defaultConfig)
|
||||
&& Objects.equals(this.config, that.config);
|
||||
&& Objects.equals(this.defaultConfig, that.defaultConfig) && Objects.equals(this.config, that.config);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -158,8 +157,7 @@ public class FeignClientProperties {
|
||||
return this.requestInterceptors;
|
||||
}
|
||||
|
||||
public void setRequestInterceptors(
|
||||
List<Class<RequestInterceptor>> requestInterceptors) {
|
||||
public void setRequestInterceptors(List<Class<RequestInterceptor>> requestInterceptors) {
|
||||
this.requestInterceptors = requestInterceptors;
|
||||
}
|
||||
|
||||
@@ -199,8 +197,7 @@ public class FeignClientProperties {
|
||||
return exceptionPropagationPolicy;
|
||||
}
|
||||
|
||||
public void setExceptionPropagationPolicy(
|
||||
ExceptionPropagationPolicy exceptionPropagationPolicy) {
|
||||
public void setExceptionPropagationPolicy(ExceptionPropagationPolicy exceptionPropagationPolicy) {
|
||||
this.exceptionPropagationPolicy = exceptionPropagationPolicy;
|
||||
}
|
||||
|
||||
@@ -213,26 +210,20 @@ public class FeignClientProperties {
|
||||
return false;
|
||||
}
|
||||
FeignClientConfiguration that = (FeignClientConfiguration) o;
|
||||
return this.loggerLevel == that.loggerLevel
|
||||
&& Objects.equals(this.connectTimeout, that.connectTimeout)
|
||||
&& Objects.equals(this.readTimeout, that.readTimeout)
|
||||
&& Objects.equals(this.retryer, that.retryer)
|
||||
return this.loggerLevel == that.loggerLevel && Objects.equals(this.connectTimeout, that.connectTimeout)
|
||||
&& Objects.equals(this.readTimeout, that.readTimeout) && Objects.equals(this.retryer, that.retryer)
|
||||
&& Objects.equals(this.errorDecoder, that.errorDecoder)
|
||||
&& Objects.equals(this.requestInterceptors, that.requestInterceptors)
|
||||
&& Objects.equals(this.decode404, that.decode404)
|
||||
&& Objects.equals(this.encoder, that.encoder)
|
||||
&& Objects.equals(this.decoder, that.decoder)
|
||||
&& Objects.equals(this.contract, that.contract)
|
||||
&& Objects.equals(this.exceptionPropagationPolicy,
|
||||
that.exceptionPropagationPolicy);
|
||||
&& Objects.equals(this.decode404, that.decode404) && Objects.equals(this.encoder, that.encoder)
|
||||
&& Objects.equals(this.decoder, that.decoder) && Objects.equals(this.contract, that.contract)
|
||||
&& Objects.equals(this.exceptionPropagationPolicy, that.exceptionPropagationPolicy);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(this.loggerLevel, this.connectTimeout, this.readTimeout,
|
||||
this.retryer, this.errorDecoder, this.requestInterceptors,
|
||||
this.decode404, this.encoder, this.decoder, this.contract,
|
||||
this.exceptionPropagationPolicy);
|
||||
return Objects.hash(this.loggerLevel, this.connectTimeout, this.readTimeout, this.retryer,
|
||||
this.errorDecoder, this.requestInterceptors, this.decode404, this.encoder, this.decoder,
|
||||
this.contract, this.exceptionPropagationPolicy);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -64,8 +64,7 @@ class FeignClientSpecification implements NamedContextFactory.Specification {
|
||||
return false;
|
||||
}
|
||||
FeignClientSpecification that = (FeignClientSpecification) o;
|
||||
return Objects.equals(this.name, that.name)
|
||||
&& Arrays.equals(this.configuration, that.configuration);
|
||||
return Objects.equals(this.name, that.name) && Arrays.equals(this.configuration, that.configuration);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -75,9 +74,8 @@ class FeignClientSpecification implements NamedContextFactory.Specification {
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return new StringBuilder("FeignClientSpecification{").append("name='")
|
||||
.append(this.name).append("', ").append("configuration=")
|
||||
.append(Arrays.toString(this.configuration)).append("}").toString();
|
||||
return new StringBuilder("FeignClientSpecification{").append("name='").append(this.name).append("', ")
|
||||
.append("configuration=").append(Arrays.toString(this.configuration)).append("}").toString();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -82,8 +82,7 @@ public class FeignClientsConfiguration {
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public Decoder feignDecoder() {
|
||||
return new OptionalDecoder(
|
||||
new ResponseEntityDecoder(new SpringDecoder(this.messageConverters)));
|
||||
return new OptionalDecoder(new ResponseEntityDecoder(new SpringDecoder(this.messageConverters)));
|
||||
}
|
||||
|
||||
@Bean
|
||||
@@ -96,18 +95,13 @@ public class FeignClientsConfiguration {
|
||||
@Bean
|
||||
@ConditionalOnClass(name = "org.springframework.data.domain.Pageable")
|
||||
@ConditionalOnMissingBean
|
||||
public Encoder feignEncoderPageable(
|
||||
ObjectProvider<AbstractFormWriter> formWriterProvider) {
|
||||
PageableSpringEncoder encoder = new PageableSpringEncoder(
|
||||
springEncoder(formWriterProvider));
|
||||
public Encoder feignEncoderPageable(ObjectProvider<AbstractFormWriter> formWriterProvider) {
|
||||
PageableSpringEncoder encoder = new PageableSpringEncoder(springEncoder(formWriterProvider));
|
||||
|
||||
if (springDataWebProperties != null) {
|
||||
encoder.setPageParameter(
|
||||
springDataWebProperties.getPageable().getPageParameter());
|
||||
encoder.setSizeParameter(
|
||||
springDataWebProperties.getPageable().getSizeParameter());
|
||||
encoder.setSortParameter(
|
||||
springDataWebProperties.getSort().getSortParameter());
|
||||
encoder.setPageParameter(springDataWebProperties.getPageable().getPageParameter());
|
||||
encoder.setSizeParameter(springDataWebProperties.getPageable().getSizeParameter());
|
||||
encoder.setSortParameter(springDataWebProperties.getSort().getSortParameter());
|
||||
}
|
||||
return encoder;
|
||||
}
|
||||
@@ -169,8 +163,7 @@ public class FeignClientsConfiguration {
|
||||
AbstractFormWriter formWriter = formWriterProvider.getIfAvailable();
|
||||
|
||||
if (formWriter != null) {
|
||||
return new SpringEncoder(new SpringPojoFormEncoder(formWriter),
|
||||
this.messageConverters);
|
||||
return new SpringEncoder(new SpringPojoFormEncoder(formWriter), this.messageConverters);
|
||||
}
|
||||
else {
|
||||
return new SpringEncoder(new SpringFormEncoder(), this.messageConverters);
|
||||
@@ -182,8 +175,7 @@ public class FeignClientsConfiguration {
|
||||
SpringPojoFormEncoder(AbstractFormWriter formWriter) {
|
||||
super();
|
||||
|
||||
MultipartFormContentProcessor processor = (MultipartFormContentProcessor) getContentProcessor(
|
||||
MULTIPART);
|
||||
MultipartFormContentProcessor processor = (MultipartFormContentProcessor) getContentProcessor(MULTIPART);
|
||||
processor.addFirstWriter(formWriter);
|
||||
}
|
||||
|
||||
|
||||
@@ -59,8 +59,7 @@ import org.springframework.util.StringUtils;
|
||||
* @author Venil Noronha
|
||||
* @author Gang Li
|
||||
*/
|
||||
class FeignClientsRegistrar
|
||||
implements ImportBeanDefinitionRegistrar, ResourceLoaderAware, EnvironmentAware {
|
||||
class FeignClientsRegistrar implements ImportBeanDefinitionRegistrar, ResourceLoaderAware, EnvironmentAware {
|
||||
|
||||
// patterned after Spring Integration IntegrationComponentScanRegistrar
|
||||
// and RibbonClientsConfigurationRegistgrar
|
||||
@@ -73,8 +72,7 @@ class FeignClientsRegistrar
|
||||
}
|
||||
|
||||
static void validateFallback(final Class clazz) {
|
||||
Assert.isTrue(!clazz.isInterface(),
|
||||
"Fallback class must implement the interface annotated by @FeignClient");
|
||||
Assert.isTrue(!clazz.isInterface(), "Fallback class must implement the interface annotated by @FeignClient");
|
||||
}
|
||||
|
||||
static void validateFallbackFactory(final Class clazz) {
|
||||
@@ -139,16 +137,13 @@ class FeignClientsRegistrar
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerBeanDefinitions(AnnotationMetadata metadata,
|
||||
BeanDefinitionRegistry registry) {
|
||||
public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
|
||||
registerDefaultConfiguration(metadata, registry);
|
||||
registerFeignClients(metadata, registry);
|
||||
}
|
||||
|
||||
private void registerDefaultConfiguration(AnnotationMetadata metadata,
|
||||
BeanDefinitionRegistry registry) {
|
||||
Map<String, Object> defaultAttrs = metadata
|
||||
.getAnnotationAttributes(EnableFeignClients.class.getName(), true);
|
||||
private void registerDefaultConfiguration(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
|
||||
Map<String, Object> defaultAttrs = metadata.getAnnotationAttributes(EnableFeignClients.class.getName(), true);
|
||||
|
||||
if (defaultAttrs != null && defaultAttrs.containsKey("defaultConfiguration")) {
|
||||
String name;
|
||||
@@ -158,24 +153,19 @@ class FeignClientsRegistrar
|
||||
else {
|
||||
name = "default." + metadata.getClassName();
|
||||
}
|
||||
registerClientConfiguration(registry, name,
|
||||
defaultAttrs.get("defaultConfiguration"));
|
||||
registerClientConfiguration(registry, name, defaultAttrs.get("defaultConfiguration"));
|
||||
}
|
||||
}
|
||||
|
||||
public void registerFeignClients(AnnotationMetadata metadata,
|
||||
BeanDefinitionRegistry registry) {
|
||||
public void registerFeignClients(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
|
||||
ClassPathScanningCandidateComponentProvider scanner = getScanner();
|
||||
scanner.setResourceLoader(this.resourceLoader);
|
||||
|
||||
Set<String> basePackages;
|
||||
|
||||
Map<String, Object> attrs = metadata
|
||||
.getAnnotationAttributes(EnableFeignClients.class.getName());
|
||||
AnnotationTypeFilter annotationTypeFilter = new AnnotationTypeFilter(
|
||||
FeignClient.class);
|
||||
final Class<?>[] clients = attrs == null ? null
|
||||
: (Class<?>[]) attrs.get("clients");
|
||||
Map<String, Object> attrs = metadata.getAnnotationAttributes(EnableFeignClients.class.getName());
|
||||
AnnotationTypeFilter annotationTypeFilter = new AnnotationTypeFilter(FeignClient.class);
|
||||
final Class<?>[] clients = attrs == null ? null : (Class<?>[]) attrs.get("clients");
|
||||
if (clients == null || clients.length == 0) {
|
||||
scanner.addIncludeFilter(annotationTypeFilter);
|
||||
basePackages = getBasePackages(metadata);
|
||||
@@ -194,13 +184,11 @@ class FeignClientsRegistrar
|
||||
return clientClasses.contains(cleaned);
|
||||
}
|
||||
};
|
||||
scanner.addIncludeFilter(
|
||||
new AllTypeFilter(Arrays.asList(filter, annotationTypeFilter)));
|
||||
scanner.addIncludeFilter(new AllTypeFilter(Arrays.asList(filter, annotationTypeFilter)));
|
||||
}
|
||||
|
||||
for (String basePackage : basePackages) {
|
||||
Set<BeanDefinition> candidateComponents = scanner
|
||||
.findCandidateComponents(basePackage);
|
||||
Set<BeanDefinition> candidateComponents = scanner.findCandidateComponents(basePackage);
|
||||
for (BeanDefinition candidateComponent : candidateComponents) {
|
||||
if (candidateComponent instanceof AnnotatedBeanDefinition) {
|
||||
// verify annotated class is an interface
|
||||
@@ -210,12 +198,10 @@ class FeignClientsRegistrar
|
||||
"@FeignClient can only be specified on an interface");
|
||||
|
||||
Map<String, Object> attributes = annotationMetadata
|
||||
.getAnnotationAttributes(
|
||||
FeignClient.class.getCanonicalName());
|
||||
.getAnnotationAttributes(FeignClient.class.getCanonicalName());
|
||||
|
||||
String name = getClientName(attributes);
|
||||
registerClientConfiguration(registry, name,
|
||||
attributes.get("configuration"));
|
||||
registerClientConfiguration(registry, name, attributes.get("configuration"));
|
||||
|
||||
registerFeignClient(registry, annotationMetadata, attributes);
|
||||
}
|
||||
@@ -223,11 +209,10 @@ class FeignClientsRegistrar
|
||||
}
|
||||
}
|
||||
|
||||
private void registerFeignClient(BeanDefinitionRegistry registry,
|
||||
AnnotationMetadata annotationMetadata, Map<String, Object> attributes) {
|
||||
private void registerFeignClient(BeanDefinitionRegistry registry, AnnotationMetadata annotationMetadata,
|
||||
Map<String, Object> attributes) {
|
||||
String className = annotationMetadata.getClassName();
|
||||
BeanDefinitionBuilder definition = BeanDefinitionBuilder
|
||||
.genericBeanDefinition(FeignClientFactoryBean.class);
|
||||
BeanDefinitionBuilder definition = BeanDefinitionBuilder.genericBeanDefinition(FeignClientFactoryBean.class);
|
||||
validate(attributes);
|
||||
definition.addPropertyValue("url", getUrl(attributes));
|
||||
definition.addPropertyValue("path", getPath(attributes));
|
||||
@@ -255,8 +240,7 @@ class FeignClientsRegistrar
|
||||
alias = qualifier;
|
||||
}
|
||||
|
||||
BeanDefinitionHolder holder = new BeanDefinitionHolder(beanDefinition, className,
|
||||
new String[] { alias });
|
||||
BeanDefinitionHolder holder = new BeanDefinitionHolder(beanDefinition, className, new String[] { alias });
|
||||
BeanDefinitionReaderUtils.registerBeanDefinition(holder, registry);
|
||||
}
|
||||
|
||||
@@ -310,8 +294,7 @@ class FeignClientsRegistrar
|
||||
protected ClassPathScanningCandidateComponentProvider getScanner() {
|
||||
return new ClassPathScanningCandidateComponentProvider(false, this.environment) {
|
||||
@Override
|
||||
protected boolean isCandidateComponent(
|
||||
AnnotatedBeanDefinition beanDefinition) {
|
||||
protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
|
||||
boolean isCandidate = false;
|
||||
if (beanDefinition.getMetadata().isIndependent()) {
|
||||
if (!beanDefinition.getMetadata().isAnnotation()) {
|
||||
@@ -343,8 +326,7 @@ class FeignClientsRegistrar
|
||||
}
|
||||
|
||||
if (basePackages.isEmpty()) {
|
||||
basePackages.add(
|
||||
ClassUtils.getPackageName(importingClassMetadata.getClassName()));
|
||||
basePackages.add(ClassUtils.getPackageName(importingClassMetadata.getClassName()));
|
||||
}
|
||||
return basePackages;
|
||||
}
|
||||
@@ -378,18 +360,15 @@ class FeignClientsRegistrar
|
||||
return value;
|
||||
}
|
||||
|
||||
throw new IllegalStateException("Either 'name' or 'value' must be provided in @"
|
||||
+ FeignClient.class.getSimpleName());
|
||||
throw new IllegalStateException(
|
||||
"Either 'name' or 'value' must be provided in @" + FeignClient.class.getSimpleName());
|
||||
}
|
||||
|
||||
private void registerClientConfiguration(BeanDefinitionRegistry registry, Object name,
|
||||
Object configuration) {
|
||||
BeanDefinitionBuilder builder = BeanDefinitionBuilder
|
||||
.genericBeanDefinition(FeignClientSpecification.class);
|
||||
private void registerClientConfiguration(BeanDefinitionRegistry registry, Object name, Object configuration) {
|
||||
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(FeignClientSpecification.class);
|
||||
builder.addConstructorArgValue(name);
|
||||
builder.addConstructorArgValue(configuration);
|
||||
registry.registerBeanDefinition(
|
||||
name + "." + FeignClientSpecification.class.getSimpleName(),
|
||||
registry.registerBeanDefinition(name + "." + FeignClientSpecification.class.getSimpleName(),
|
||||
builder.getBeanDefinition());
|
||||
}
|
||||
|
||||
@@ -418,8 +397,8 @@ class FeignClientsRegistrar
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean match(MetadataReader metadataReader,
|
||||
MetadataReaderFactory metadataReaderFactory) throws IOException {
|
||||
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory)
|
||||
throws IOException {
|
||||
|
||||
for (TypeFilter filter : this.delegates) {
|
||||
if (!filter.match(metadataReader, metadataReaderFactory)) {
|
||||
|
||||
@@ -24,7 +24,7 @@ import feign.Target;
|
||||
*/
|
||||
public interface Targeter {
|
||||
|
||||
<T> T target(FeignClientFactoryBean factory, Feign.Builder feign,
|
||||
FeignContext context, Target.HardCodedTarget<T> target);
|
||||
<T> T target(FeignClientFactoryBean factory, Feign.Builder feign, FeignContext context,
|
||||
Target.HardCodedTarget<T> target);
|
||||
|
||||
}
|
||||
|
||||
@@ -48,15 +48,13 @@ public class MatrixVariableParameterProcessor implements AnnotatedParameterProce
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean processArgument(AnnotatedParameterContext context,
|
||||
Annotation annotation, Method method) {
|
||||
public boolean processArgument(AnnotatedParameterContext context, Annotation annotation, Method method) {
|
||||
int parameterIndex = context.getParameterIndex();
|
||||
Class<?> parameterType = method.getParameterTypes()[parameterIndex];
|
||||
MethodMetadata data = context.getMethodMetadata();
|
||||
String name = ANNOTATION.cast(annotation).value();
|
||||
|
||||
checkState(emptyToNull(name) != null,
|
||||
"MatrixVariable annotation was empty on param %s.",
|
||||
checkState(emptyToNull(name) != null, "MatrixVariable annotation was empty on param %s.",
|
||||
context.getParameterIndex());
|
||||
|
||||
context.setParameterName(name);
|
||||
@@ -65,8 +63,7 @@ public class MatrixVariableParameterProcessor implements AnnotatedParameterProce
|
||||
data.indexToExpander().put(parameterIndex, this::expandMap);
|
||||
}
|
||||
else {
|
||||
data.indexToExpander().put(parameterIndex,
|
||||
object -> ";" + name + "=" + object.toString());
|
||||
data.indexToExpander().put(parameterIndex, object -> ";" + name + "=" + object.toString());
|
||||
}
|
||||
|
||||
return true;
|
||||
@@ -75,8 +72,7 @@ public class MatrixVariableParameterProcessor implements AnnotatedParameterProce
|
||||
private String expandMap(Object object) {
|
||||
Map<String, Object> paramMap = (Map) object;
|
||||
|
||||
return paramMap.keySet().stream()
|
||||
.map(key -> ";" + key + "=" + paramMap.get(key).toString())
|
||||
return paramMap.keySet().stream().map(key -> ";" + key + "=" + paramMap.get(key).toString())
|
||||
.collect(Collectors.joining());
|
||||
}
|
||||
|
||||
|
||||
@@ -46,18 +46,15 @@ public class PathVariableParameterProcessor implements AnnotatedParameterProcess
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean processArgument(AnnotatedParameterContext context,
|
||||
Annotation annotation, Method method) {
|
||||
public boolean processArgument(AnnotatedParameterContext context, Annotation annotation, Method method) {
|
||||
String name = ANNOTATION.cast(annotation).value();
|
||||
checkState(emptyToNull(name) != null,
|
||||
"PathVariable annotation was empty on param %s.",
|
||||
checkState(emptyToNull(name) != null, "PathVariable annotation was empty on param %s.",
|
||||
context.getParameterIndex());
|
||||
context.setParameterName(name);
|
||||
|
||||
MethodMetadata data = context.getMethodMetadata();
|
||||
String varName = '{' + name + '}';
|
||||
if (!data.template().url().contains(varName)
|
||||
&& !searchMapValues(data.template().queries(), varName)
|
||||
if (!data.template().url().contains(varName) && !searchMapValues(data.template().queries(), varName)
|
||||
&& !searchMapValues(data.template().headers(), varName)) {
|
||||
data.formParams().add(name);
|
||||
}
|
||||
|
||||
@@ -40,8 +40,7 @@ public class QueryMapParameterProcessor implements AnnotatedParameterProcessor {
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean processArgument(AnnotatedParameterContext context,
|
||||
Annotation annotation, Method method) {
|
||||
public boolean processArgument(AnnotatedParameterContext context, Annotation annotation, Method method) {
|
||||
int paramIndex = context.getParameterIndex();
|
||||
MethodMetadata metadata = context.getMethodMetadata();
|
||||
if (metadata.queryMapIndex() == null) {
|
||||
|
||||
@@ -46,27 +46,23 @@ public class RequestHeaderParameterProcessor implements AnnotatedParameterProces
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean processArgument(AnnotatedParameterContext context,
|
||||
Annotation annotation, Method method) {
|
||||
public boolean processArgument(AnnotatedParameterContext context, Annotation annotation, Method method) {
|
||||
int parameterIndex = context.getParameterIndex();
|
||||
Class<?> parameterType = method.getParameterTypes()[parameterIndex];
|
||||
MethodMetadata data = context.getMethodMetadata();
|
||||
|
||||
if (Map.class.isAssignableFrom(parameterType)) {
|
||||
checkState(data.headerMapIndex() == null,
|
||||
"Header map can only be present once.");
|
||||
checkState(data.headerMapIndex() == null, "Header map can only be present once.");
|
||||
data.headerMapIndex(parameterIndex);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
String name = ANNOTATION.cast(annotation).value();
|
||||
checkState(emptyToNull(name) != null,
|
||||
"RequestHeader.value() was empty on parameter %s", parameterIndex);
|
||||
checkState(emptyToNull(name) != null, "RequestHeader.value() was empty on parameter %s", parameterIndex);
|
||||
context.setParameterName(name);
|
||||
|
||||
Collection<String> header = context.setTemplateParameter(name,
|
||||
data.template().headers().get(name));
|
||||
Collection<String> header = context.setTemplateParameter(name, data.template().headers().get(name));
|
||||
data.template().header(name, header);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -46,15 +46,13 @@ public class RequestParamParameterProcessor implements AnnotatedParameterProcess
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean processArgument(AnnotatedParameterContext context,
|
||||
Annotation annotation, Method method) {
|
||||
public boolean processArgument(AnnotatedParameterContext context, Annotation annotation, Method method) {
|
||||
int parameterIndex = context.getParameterIndex();
|
||||
Class<?> parameterType = method.getParameterTypes()[parameterIndex];
|
||||
MethodMetadata data = context.getMethodMetadata();
|
||||
|
||||
if (Map.class.isAssignableFrom(parameterType)) {
|
||||
checkState(data.queryMapIndex() == null,
|
||||
"Query map can only be present once.");
|
||||
checkState(data.queryMapIndex() == null, "Query map can only be present once.");
|
||||
data.queryMapIndex(parameterIndex);
|
||||
|
||||
return true;
|
||||
@@ -62,12 +60,10 @@ public class RequestParamParameterProcessor implements AnnotatedParameterProcess
|
||||
|
||||
RequestParam requestParam = ANNOTATION.cast(annotation);
|
||||
String name = requestParam.value();
|
||||
checkState(emptyToNull(name) != null,
|
||||
"RequestParam.value() was empty on parameter %s", parameterIndex);
|
||||
checkState(emptyToNull(name) != null, "RequestParam.value() was empty on parameter %s", parameterIndex);
|
||||
context.setParameterName(name);
|
||||
|
||||
Collection<String> query = context.setTemplateParameter(name,
|
||||
data.template().queries().get(name));
|
||||
Collection<String> query = context.setTemplateParameter(name, data.template().queries().get(name));
|
||||
data.template().query(name, query);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -44,19 +44,16 @@ public class RequestPartParameterProcessor implements AnnotatedParameterProcesso
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean processArgument(AnnotatedParameterContext context,
|
||||
Annotation annotation, Method method) {
|
||||
public boolean processArgument(AnnotatedParameterContext context, Annotation annotation, Method method) {
|
||||
int parameterIndex = context.getParameterIndex();
|
||||
MethodMetadata data = context.getMethodMetadata();
|
||||
|
||||
String name = ANNOTATION.cast(annotation).value();
|
||||
checkState(emptyToNull(name) != null,
|
||||
"RequestPart.value() was empty on parameter %s", parameterIndex);
|
||||
checkState(emptyToNull(name) != null, "RequestPart.value() was empty on parameter %s", parameterIndex);
|
||||
context.setParameterName(name);
|
||||
|
||||
data.formParams().add(name);
|
||||
Collection<String> names = context.setTemplateParameter(name,
|
||||
data.indexToName().get(parameterIndex));
|
||||
Collection<String> names = context.setTemplateParameter(name, data.indexToName().get(parameterIndex));
|
||||
data.indexToName().put(parameterIndex, names);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -48,8 +48,8 @@ import org.springframework.context.annotation.Configuration;
|
||||
@ConditionalOnMissingBean(CloseableHttpClient.class)
|
||||
public class HttpClientFeignConfiguration {
|
||||
|
||||
private final Timer connectionManagerTimer = new Timer(
|
||||
"FeignApacheHttpClientConfiguration.connectionManagerTimer", true);
|
||||
private final Timer connectionManagerTimer = new Timer("FeignApacheHttpClientConfiguration.connectionManagerTimer",
|
||||
true);
|
||||
|
||||
private CloseableHttpClient httpClient;
|
||||
|
||||
@@ -61,12 +61,10 @@ public class HttpClientFeignConfiguration {
|
||||
public HttpClientConnectionManager connectionManager(
|
||||
ApacheHttpClientConnectionManagerFactory connectionManagerFactory,
|
||||
FeignHttpClientProperties httpClientProperties) {
|
||||
final HttpClientConnectionManager connectionManager = connectionManagerFactory
|
||||
.newConnectionManager(httpClientProperties.isDisableSslValidation(),
|
||||
httpClientProperties.getMaxConnections(),
|
||||
httpClientProperties.getMaxConnectionsPerRoute(),
|
||||
httpClientProperties.getTimeToLive(),
|
||||
httpClientProperties.getTimeToLiveUnit(), this.registryBuilder);
|
||||
final HttpClientConnectionManager connectionManager = connectionManagerFactory.newConnectionManager(
|
||||
httpClientProperties.isDisableSslValidation(), httpClientProperties.getMaxConnections(),
|
||||
httpClientProperties.getMaxConnectionsPerRoute(), httpClientProperties.getTimeToLive(),
|
||||
httpClientProperties.getTimeToLiveUnit(), this.registryBuilder);
|
||||
this.connectionManagerTimer.schedule(new TimerTask() {
|
||||
@Override
|
||||
public void run() {
|
||||
@@ -77,37 +75,29 @@ public class HttpClientFeignConfiguration {
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnProperty(value = "feign.compression.response.enabled",
|
||||
havingValue = "true")
|
||||
public CloseableHttpClient customHttpClient(
|
||||
HttpClientConnectionManager httpClientConnectionManager,
|
||||
@ConditionalOnProperty(value = "feign.compression.response.enabled", havingValue = "true")
|
||||
public CloseableHttpClient customHttpClient(HttpClientConnectionManager httpClientConnectionManager,
|
||||
FeignHttpClientProperties httpClientProperties) {
|
||||
HttpClientBuilder builder = HttpClientBuilder.create().disableCookieManagement()
|
||||
.useSystemProperties();
|
||||
this.httpClient = createClient(builder, httpClientConnectionManager,
|
||||
httpClientProperties);
|
||||
HttpClientBuilder builder = HttpClientBuilder.create().disableCookieManagement().useSystemProperties();
|
||||
this.httpClient = createClient(builder, httpClientConnectionManager, httpClientProperties);
|
||||
return this.httpClient;
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnProperty(value = "feign.compression.response.enabled",
|
||||
havingValue = "false", matchIfMissing = true)
|
||||
@ConditionalOnProperty(value = "feign.compression.response.enabled", havingValue = "false", matchIfMissing = true)
|
||||
public CloseableHttpClient httpClient(ApacheHttpClientFactory httpClientFactory,
|
||||
HttpClientConnectionManager httpClientConnectionManager,
|
||||
FeignHttpClientProperties httpClientProperties) {
|
||||
this.httpClient = createClient(httpClientFactory.createBuilder(),
|
||||
httpClientConnectionManager, httpClientProperties);
|
||||
HttpClientConnectionManager httpClientConnectionManager, FeignHttpClientProperties httpClientProperties) {
|
||||
this.httpClient = createClient(httpClientFactory.createBuilder(), httpClientConnectionManager,
|
||||
httpClientProperties);
|
||||
return this.httpClient;
|
||||
}
|
||||
|
||||
private CloseableHttpClient createClient(HttpClientBuilder builder,
|
||||
HttpClientConnectionManager httpClientConnectionManager,
|
||||
FeignHttpClientProperties httpClientProperties) {
|
||||
HttpClientConnectionManager httpClientConnectionManager, FeignHttpClientProperties httpClientProperties) {
|
||||
RequestConfig defaultRequestConfig = RequestConfig.custom()
|
||||
.setConnectTimeout(httpClientProperties.getConnectionTimeout())
|
||||
.setRedirectsEnabled(httpClientProperties.isFollowRedirects()).build();
|
||||
CloseableHttpClient httpClient = builder
|
||||
.setDefaultRequestConfig(defaultRequestConfig)
|
||||
CloseableHttpClient httpClient = builder.setDefaultRequestConfig(defaultRequestConfig)
|
||||
.setConnectionManager(httpClientConnectionManager).build();
|
||||
return httpClient;
|
||||
}
|
||||
|
||||
@@ -46,8 +46,7 @@ public class OkHttpFeignConfiguration {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean(ConnectionPool.class)
|
||||
public ConnectionPool httpClientConnectionPool(
|
||||
FeignHttpClientProperties httpClientProperties,
|
||||
public ConnectionPool httpClientConnectionPool(FeignHttpClientProperties httpClientProperties,
|
||||
OkHttpClientConnectionPoolFactory connectionPoolFactory) {
|
||||
Integer maxTotalConnections = httpClientProperties.getMaxConnections();
|
||||
Long timeToLive = httpClientProperties.getTimeToLive();
|
||||
@@ -56,15 +55,13 @@ public class OkHttpFeignConfiguration {
|
||||
}
|
||||
|
||||
@Bean
|
||||
public okhttp3.OkHttpClient client(OkHttpClientFactory httpClientFactory,
|
||||
ConnectionPool connectionPool,
|
||||
public okhttp3.OkHttpClient client(OkHttpClientFactory httpClientFactory, ConnectionPool connectionPool,
|
||||
FeignHttpClientProperties httpClientProperties) {
|
||||
Boolean followRedirects = httpClientProperties.isFollowRedirects();
|
||||
Integer connectTimeout = httpClientProperties.getConnectionTimeout();
|
||||
this.okHttpClient = httpClientFactory
|
||||
.createBuilder(httpClientProperties.isDisableSslValidation())
|
||||
.connectTimeout(connectTimeout, TimeUnit.MILLISECONDS)
|
||||
.followRedirects(followRedirects).connectionPool(connectionPool).build();
|
||||
this.okHttpClient = httpClientFactory.createBuilder(httpClientProperties.isDisableSslValidation())
|
||||
.connectTimeout(connectTimeout, TimeUnit.MILLISECONDS).followRedirects(followRedirects)
|
||||
.connectionPool(connectionPool).build();
|
||||
return this.okHttpClient;
|
||||
}
|
||||
|
||||
|
||||
@@ -48,8 +48,7 @@ public abstract class BaseRequestInterceptor implements RequestInterceptor {
|
||||
* @param name the header name
|
||||
* @param values the header values
|
||||
*/
|
||||
protected void addHeader(RequestTemplate requestTemplate, String name,
|
||||
String... values) {
|
||||
protected void addHeader(RequestTemplate requestTemplate, String name, String... values) {
|
||||
|
||||
if (!requestTemplate.headers().containsKey(name)) {
|
||||
requestTemplate.header(name, values);
|
||||
|
||||
@@ -39,8 +39,7 @@ import org.springframework.context.annotation.Configuration;
|
||||
@EnableConfigurationProperties(FeignClientEncodingProperties.class)
|
||||
@ConditionalOnClass(Feign.class)
|
||||
@ConditionalOnBean(Client.class)
|
||||
@ConditionalOnProperty(value = "feign.compression.response.enabled",
|
||||
matchIfMissing = false)
|
||||
@ConditionalOnProperty(value = "feign.compression.response.enabled", matchIfMissing = false)
|
||||
// The OK HTTP client uses "transparent" compression.
|
||||
// If the accept-encoding header is present it disable transparent compression
|
||||
@ConditionalOnMissingBean(type = "okhttp3.OkHttpClient")
|
||||
|
||||
@@ -33,8 +33,7 @@ public class FeignAcceptGzipEncodingInterceptor extends BaseRequestInterceptor {
|
||||
* Creates new instance of {@link FeignAcceptGzipEncodingInterceptor}.
|
||||
* @param properties the encoding properties
|
||||
*/
|
||||
protected FeignAcceptGzipEncodingInterceptor(
|
||||
FeignClientEncodingProperties properties) {
|
||||
protected FeignAcceptGzipEncodingInterceptor(FeignClientEncodingProperties properties) {
|
||||
super(properties);
|
||||
}
|
||||
|
||||
@@ -44,8 +43,8 @@ public class FeignAcceptGzipEncodingInterceptor extends BaseRequestInterceptor {
|
||||
@Override
|
||||
public void apply(RequestTemplate template) {
|
||||
|
||||
addHeader(template, HttpEncoding.ACCEPT_ENCODING_HEADER,
|
||||
HttpEncoding.GZIP_ENCODING, HttpEncoding.DEFLATE_ENCODING);
|
||||
addHeader(template, HttpEncoding.ACCEPT_ENCODING_HEADER, HttpEncoding.GZIP_ENCODING,
|
||||
HttpEncoding.DEFLATE_ENCODING);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -32,8 +32,7 @@ public class FeignClientEncodingProperties {
|
||||
/**
|
||||
* The list of supported mime types.
|
||||
*/
|
||||
private String[] mimeTypes = new String[] { "text/xml", "application/xml",
|
||||
"application/json" };
|
||||
private String[] mimeTypes = new String[] { "text/xml", "application/xml", "application/json" };
|
||||
|
||||
/**
|
||||
* The minimum threshold content size.
|
||||
@@ -77,9 +76,8 @@ public class FeignClientEncodingProperties {
|
||||
@Override
|
||||
public String toString() {
|
||||
return new StringBuilder("FeignClientEncodingProperties{").append("mimeTypes=")
|
||||
.append(Arrays.toString(this.mimeTypes)).append(", ")
|
||||
.append("minRequestSize=").append(this.minRequestSize).append("}")
|
||||
.toString();
|
||||
.append(Arrays.toString(this.mimeTypes)).append(", ").append("minRequestSize=")
|
||||
.append(this.minRequestSize).append("}").toString();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -33,8 +33,7 @@ public class FeignContentGzipEncodingInterceptor extends BaseRequestInterceptor
|
||||
* Creates new instance of {@link FeignContentGzipEncodingInterceptor}.
|
||||
* @param properties the encoding properties
|
||||
*/
|
||||
protected FeignContentGzipEncodingInterceptor(
|
||||
FeignClientEncodingProperties properties) {
|
||||
protected FeignContentGzipEncodingInterceptor(FeignClientEncodingProperties properties) {
|
||||
super(properties);
|
||||
}
|
||||
|
||||
@@ -45,8 +44,8 @@ public class FeignContentGzipEncodingInterceptor extends BaseRequestInterceptor
|
||||
public void apply(RequestTemplate template) {
|
||||
|
||||
if (requiresCompression(template)) {
|
||||
addHeader(template, HttpEncoding.CONTENT_ENCODING_HEADER,
|
||||
HttpEncoding.GZIP_ENCODING, HttpEncoding.DEFLATE_ENCODING);
|
||||
addHeader(template, HttpEncoding.CONTENT_ENCODING_HEADER, HttpEncoding.GZIP_ENCODING,
|
||||
HttpEncoding.DEFLATE_ENCODING);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -93,8 +92,7 @@ public class FeignContentGzipEncodingInterceptor extends BaseRequestInterceptor
|
||||
return false;
|
||||
}
|
||||
|
||||
if (getProperties().getMimeTypes() == null
|
||||
|| getProperties().getMimeTypes().length == 0) {
|
||||
if (getProperties().getMimeTypes() == null || getProperties().getMimeTypes().length == 0) {
|
||||
// no specific mime types has been set - matching everything
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -51,8 +51,7 @@ import static org.springframework.hateoas.MediaTypes.HAL_JSON;
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@ConditionalOnWebApplication
|
||||
@ConditionalOnClass(RepresentationModel.class)
|
||||
@AutoConfigureAfter({ JacksonAutoConfiguration.class,
|
||||
HttpMessageConvertersAutoConfiguration.class,
|
||||
@AutoConfigureAfter({ JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class,
|
||||
RepositoryRestMvcAutoConfiguration.class })
|
||||
@AutoConfigureBefore(HypermediaAutoConfiguration.class)
|
||||
public class FeignHalAutoConfiguration {
|
||||
@@ -60,24 +59,21 @@ public class FeignHalAutoConfiguration {
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public TypeConstrainedMappingJackson2HttpMessageConverter halJacksonHttpMessageConverter(
|
||||
ObjectProvider<ObjectMapper> objectMapper,
|
||||
ObjectProvider<HalConfiguration> halConfiguration,
|
||||
ObjectProvider<MessageResolver> messageResolver,
|
||||
ObjectProvider<CurieProvider> curieProvider,
|
||||
ObjectProvider<ObjectMapper> objectMapper, ObjectProvider<HalConfiguration> halConfiguration,
|
||||
ObjectProvider<MessageResolver> messageResolver, ObjectProvider<CurieProvider> curieProvider,
|
||||
ObjectProvider<LinkRelationProvider> linkRelationProvider) {
|
||||
|
||||
ObjectMapper mapper = objectMapper.getIfAvailable(ObjectMapper::new).copy();
|
||||
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
|
||||
|
||||
HalConfiguration configuration = halConfiguration
|
||||
.getIfAvailable(HalConfiguration::new);
|
||||
HalConfiguration configuration = halConfiguration.getIfAvailable(HalConfiguration::new);
|
||||
|
||||
CurieProvider curieProviderInstance = curieProvider
|
||||
.getIfAvailable(() -> new DefaultCurieProvider(Collections.emptyMap()));
|
||||
|
||||
Jackson2HalModule.HalHandlerInstantiator halHandlerInstantiator = new Jackson2HalModule.HalHandlerInstantiator(
|
||||
linkRelationProvider.getIfAvailable(), curieProviderInstance,
|
||||
messageResolver.getIfAvailable(), configuration);
|
||||
linkRelationProvider.getIfAvailable(), curieProviderInstance, messageResolver.getIfAvailable(),
|
||||
configuration);
|
||||
|
||||
mapper.setHandlerInstantiator(halHandlerInstantiator);
|
||||
|
||||
|
||||
@@ -36,8 +36,7 @@ class DefaultFeignLoadBalancerConfiguration {
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public Client feignClient(LoadBalancerClient loadBalancerClient) {
|
||||
return new FeignBlockingLoadBalancerClient(new Client.Default(null, null),
|
||||
loadBalancerClient);
|
||||
return new FeignBlockingLoadBalancerClient(new Client.Default(null, null), loadBalancerClient);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -40,15 +40,13 @@ import org.springframework.util.Assert;
|
||||
*/
|
||||
public class FeignBlockingLoadBalancerClient implements Client {
|
||||
|
||||
private static final Log LOG = LogFactory
|
||||
.getLog(FeignBlockingLoadBalancerClient.class);
|
||||
private static final Log LOG = LogFactory.getLog(FeignBlockingLoadBalancerClient.class);
|
||||
|
||||
private final Client delegate;
|
||||
|
||||
private final LoadBalancerClient loadBalancerClient;
|
||||
|
||||
public FeignBlockingLoadBalancerClient(Client delegate,
|
||||
LoadBalancerClient loadBalancerClient) {
|
||||
public FeignBlockingLoadBalancerClient(Client delegate, LoadBalancerClient loadBalancerClient) {
|
||||
this.delegate = delegate;
|
||||
this.loadBalancerClient = loadBalancerClient;
|
||||
}
|
||||
@@ -57,24 +55,19 @@ public class FeignBlockingLoadBalancerClient implements Client {
|
||||
public Response execute(Request request, Request.Options options) throws IOException {
|
||||
final URI originalUri = URI.create(request.url());
|
||||
String serviceId = originalUri.getHost();
|
||||
Assert.state(serviceId != null,
|
||||
"Request URI does not contain a valid hostname: " + originalUri);
|
||||
Assert.state(serviceId != null, "Request URI does not contain a valid hostname: " + originalUri);
|
||||
ServiceInstance instance = loadBalancerClient.choose(serviceId);
|
||||
if (instance == null) {
|
||||
String message = "Load balancer does not contain an instance for the service "
|
||||
+ serviceId;
|
||||
String message = "Load balancer does not contain an instance for the service " + serviceId;
|
||||
if (LOG.isWarnEnabled()) {
|
||||
LOG.warn(message);
|
||||
}
|
||||
return Response.builder().request(request)
|
||||
.status(HttpStatus.SERVICE_UNAVAILABLE.value())
|
||||
return Response.builder().request(request).status(HttpStatus.SERVICE_UNAVAILABLE.value())
|
||||
.body(message, StandardCharsets.UTF_8).build();
|
||||
}
|
||||
String reconstructedUrl = loadBalancerClient.reconstructURI(instance, originalUri)
|
||||
.toString();
|
||||
Request newRequest = Request.create(request.httpMethod(), reconstructedUrl,
|
||||
request.headers(), request.body(), request.charset(),
|
||||
request.requestTemplate());
|
||||
String reconstructedUrl = loadBalancerClient.reconstructURI(instance, originalUri).toString();
|
||||
Request newRequest = Request.create(request.httpMethod(), reconstructedUrl, request.headers(), request.body(),
|
||||
request.charset(), request.requestTemplate());
|
||||
return delegate.execute(newRequest, options);
|
||||
}
|
||||
|
||||
|
||||
@@ -44,8 +44,7 @@ import org.springframework.context.annotation.Import;
|
||||
// Order is important here, last should be the default, first should be optional
|
||||
// see
|
||||
// https://github.com/spring-cloud/spring-cloud-netflix/issues/2086#issuecomment-316281653
|
||||
@Import({ HttpClientFeignLoadBalancerConfiguration.class,
|
||||
OkHttpFeignLoadBalancerConfiguration.class,
|
||||
@Import({ HttpClientFeignLoadBalancerConfiguration.class, OkHttpFeignLoadBalancerConfiguration.class,
|
||||
DefaultFeignLoadBalancerConfiguration.class })
|
||||
public class FeignLoadBalancerAutoConfiguration {
|
||||
|
||||
|
||||
@@ -46,8 +46,7 @@ class HttpClientFeignLoadBalancerConfiguration {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public Client feignClient(LoadBalancerClient loadBalancerClient,
|
||||
HttpClient httpClient) {
|
||||
public Client feignClient(LoadBalancerClient loadBalancerClient, HttpClient httpClient) {
|
||||
ApacheHttpClient delegate = new ApacheHttpClient(httpClient);
|
||||
return new FeignBlockingLoadBalancerClient(delegate, loadBalancerClient);
|
||||
}
|
||||
|
||||
@@ -45,8 +45,7 @@ class OkHttpFeignLoadBalancerConfiguration {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public Client feignClient(okhttp3.OkHttpClient okHttpClient,
|
||||
LoadBalancerClient loadBalancerClient) {
|
||||
public Client feignClient(okhttp3.OkHttpClient okHttpClient, LoadBalancerClient loadBalancerClient) {
|
||||
OkHttpClient delegate = new OkHttpClient(okHttpClient);
|
||||
return new FeignBlockingLoadBalancerClient(delegate, loadBalancerClient);
|
||||
}
|
||||
|
||||
@@ -44,12 +44,10 @@ public abstract class AbstractFormWriter extends AbstractWriter {
|
||||
@Override
|
||||
public void write(Output output, String key, Object object) throws EncodeException {
|
||||
try {
|
||||
String string = new StringBuilder()
|
||||
.append("Content-Disposition: form-data; name=\"").append(key)
|
||||
.append('"').append(CRLF).append("Content-Type: ")
|
||||
.append(getContentType()).append("; charset=")
|
||||
.append(output.getCharset().name()).append(CRLF).append(CRLF)
|
||||
.append(writeAsString(object)).toString();
|
||||
String string = new StringBuilder().append("Content-Disposition: form-data; name=\"").append(key)
|
||||
.append('"').append(CRLF).append("Content-Type: ").append(getContentType()).append("; charset=")
|
||||
.append(output.getCharset().name()).append(CRLF).append(CRLF).append(writeAsString(object))
|
||||
.toString();
|
||||
|
||||
output.write(string);
|
||||
}
|
||||
|
||||
@@ -45,19 +45,15 @@ public class DefaultGzipDecoder implements Decoder {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object decode(final Response response, Type type)
|
||||
throws IOException, FeignException {
|
||||
Collection<String> encoding = response.headers()
|
||||
.containsKey(HttpEncoding.CONTENT_ENCODING_HEADER)
|
||||
? response.headers().get(HttpEncoding.CONTENT_ENCODING_HEADER)
|
||||
: null;
|
||||
public Object decode(final Response response, Type type) throws IOException, FeignException {
|
||||
Collection<String> encoding = response.headers().containsKey(HttpEncoding.CONTENT_ENCODING_HEADER)
|
||||
? response.headers().get(HttpEncoding.CONTENT_ENCODING_HEADER) : null;
|
||||
|
||||
if (encoding != null) {
|
||||
if (encoding.contains(HttpEncoding.GZIP_ENCODING)) {
|
||||
String decompressedBody = decompress(response);
|
||||
if (decompressedBody != null) {
|
||||
Response decompressedResponse = response.toBuilder()
|
||||
.body(decompressedBody.getBytes()).build();
|
||||
Response decompressedResponse = response.toBuilder().body(decompressedBody.getBytes()).build();
|
||||
return decoder.decode(decompressedResponse, type);
|
||||
}
|
||||
}
|
||||
@@ -69,8 +65,7 @@ public class DefaultGzipDecoder implements Decoder {
|
||||
if (response.body() == null) {
|
||||
return null;
|
||||
}
|
||||
try (GZIPInputStream gzipInputStream = new GZIPInputStream(
|
||||
response.body().asInputStream());
|
||||
try (GZIPInputStream gzipInputStream = new GZIPInputStream(response.body().asInputStream());
|
||||
BufferedReader reader = new BufferedReader(
|
||||
new InputStreamReader(gzipInputStream, StandardCharsets.UTF_8))) {
|
||||
String outputString = "";
|
||||
|
||||
@@ -43,8 +43,7 @@ public class DefaultGzipDecoderConfiguration {
|
||||
|
||||
private ObjectFactory<HttpMessageConverters> messageConverters;
|
||||
|
||||
public DefaultGzipDecoderConfiguration(
|
||||
ObjectFactory<HttpMessageConverters> messageConverters) {
|
||||
public DefaultGzipDecoderConfiguration(ObjectFactory<HttpMessageConverters> messageConverters) {
|
||||
this.messageConverters = messageConverters;
|
||||
}
|
||||
|
||||
@@ -52,8 +51,8 @@ public class DefaultGzipDecoderConfiguration {
|
||||
@ConditionalOnMissingBean
|
||||
@ConditionalOnProperty("feign.compression.response.useGzipDecoder")
|
||||
public Decoder defaultGzipDecoder() {
|
||||
return new OptionalDecoder(new ResponseEntityDecoder(
|
||||
new DefaultGzipDecoder(new SpringDecoder(messageConverters))));
|
||||
return new OptionalDecoder(
|
||||
new ResponseEntityDecoder(new DefaultGzipDecoder(new SpringDecoder(messageConverters))));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -54,10 +54,8 @@ public final class FeignUtils {
|
||||
return headers;
|
||||
}
|
||||
|
||||
static Collection<String> addTemplateParameter(Collection<String> possiblyNull,
|
||||
String paramName) {
|
||||
Collection<String> params = ofNullable(possiblyNull).map(ArrayList::new)
|
||||
.orElse(new ArrayList<>());
|
||||
static Collection<String> addTemplateParameter(Collection<String> possiblyNull, String paramName) {
|
||||
Collection<String> params = ofNullable(possiblyNull).map(ArrayList::new).orElse(new ArrayList<>());
|
||||
params.add(String.format("{%s}", paramName));
|
||||
return params;
|
||||
}
|
||||
|
||||
@@ -63,9 +63,8 @@ public class PageJacksonModule extends Module {
|
||||
|
||||
private final Page<T> delegate;
|
||||
|
||||
SimplePageImpl(@JsonProperty("content") List<T> content,
|
||||
@JsonProperty("number") int number, @JsonProperty("size") int size,
|
||||
@JsonProperty("totalElements") long totalElements,
|
||||
SimplePageImpl(@JsonProperty("content") List<T> content, @JsonProperty("number") int number,
|
||||
@JsonProperty("size") int size, @JsonProperty("totalElements") long totalElements,
|
||||
@JsonProperty("sort") Sort sort) {
|
||||
PageRequest pageRequest;
|
||||
if (sort != null) {
|
||||
|
||||
@@ -75,8 +75,7 @@ public class PageableSpringEncoder implements Encoder {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void encode(Object object, Type bodyType, RequestTemplate template)
|
||||
throws EncodeException {
|
||||
public void encode(Object object, Type bodyType, RequestTemplate template) throws EncodeException {
|
||||
|
||||
if (supports(object)) {
|
||||
if (object instanceof Pageable) {
|
||||
@@ -101,18 +100,15 @@ public class PageableSpringEncoder implements Encoder {
|
||||
delegate.encode(object, bodyType, template);
|
||||
}
|
||||
else {
|
||||
throw new EncodeException(
|
||||
"PageableSpringEncoder does not support the given object "
|
||||
+ object.getClass()
|
||||
+ " and no delegate was provided for fallback!");
|
||||
throw new EncodeException("PageableSpringEncoder does not support the given object " + object.getClass()
|
||||
+ " and no delegate was provided for fallback!");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void applySort(RequestTemplate template, Sort sort) {
|
||||
Collection<String> existingSorts = template.queries().get("sort");
|
||||
List<String> sortQueries = existingSorts != null ? new ArrayList<>(existingSorts)
|
||||
: new ArrayList<>();
|
||||
List<String> sortQueries = existingSorts != null ? new ArrayList<>(existingSorts) : new ArrayList<>();
|
||||
if (!sortParameter.equals("sort")) {
|
||||
existingSorts = template.queries().get(sortParameter);
|
||||
if (existingSorts != null) {
|
||||
|
||||
@@ -46,8 +46,7 @@ public class ResponseEntityDecoder implements Decoder {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object decode(final Response response, Type type)
|
||||
throws IOException, FeignException {
|
||||
public Object decode(final Response response, Type type) throws IOException, FeignException {
|
||||
|
||||
if (isParameterizeHttpEntity(type)) {
|
||||
type = ((ParameterizedType) type).getActualTypeArguments()[0];
|
||||
@@ -86,8 +85,7 @@ public class ResponseEntityDecoder implements Decoder {
|
||||
headers.put(key, new LinkedList<>(response.headers().get(key)));
|
||||
}
|
||||
|
||||
return new ResponseEntity<>((T) instance, headers,
|
||||
HttpStatus.valueOf(response.status()));
|
||||
return new ResponseEntity<>((T) instance, headers, HttpStatus.valueOf(response.status()));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -48,8 +48,7 @@ public class SortJacksonModule extends Module {
|
||||
context.addSerializers(serializers);
|
||||
|
||||
SimpleDeserializers deserializers = new SimpleDeserializers();
|
||||
deserializers.addDeserializer(Sort.class,
|
||||
new SortJsonComponent.SortDeserializer());
|
||||
deserializers.addDeserializer(Sort.class, new SortJsonComponent.SortDeserializer());
|
||||
context.addDeserializers(deserializers);
|
||||
}
|
||||
|
||||
|
||||
@@ -44,8 +44,7 @@ public class SortJsonComponent {
|
||||
public static class SortSerializer extends JsonSerializer<Sort> {
|
||||
|
||||
@Override
|
||||
public void serialize(Sort value, JsonGenerator gen,
|
||||
SerializerProvider serializers) throws IOException {
|
||||
public void serialize(Sort value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
|
||||
gen.writeStartArray();
|
||||
value.iterator().forEachRemaining(v -> {
|
||||
try {
|
||||
@@ -68,15 +67,14 @@ public class SortJsonComponent {
|
||||
public static class SortDeserializer extends JsonDeserializer<Sort> {
|
||||
|
||||
@Override
|
||||
public Sort deserialize(JsonParser jsonParser,
|
||||
DeserializationContext deserializationContext) throws IOException {
|
||||
public Sort deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
|
||||
throws IOException {
|
||||
TreeNode treeNode = jsonParser.getCodec().readTree(jsonParser);
|
||||
if (treeNode.isArray()) {
|
||||
ArrayNode arrayNode = (ArrayNode) treeNode;
|
||||
List<Sort.Order> orders = new ArrayList<>();
|
||||
for (JsonNode jsonNode : arrayNode) {
|
||||
Sort.Order order = new Sort.Order(
|
||||
Sort.Direction.valueOf(jsonNode.get("direction").textValue()),
|
||||
Sort.Order order = new Sort.Order(Sort.Direction.valueOf(jsonNode.get("direction").textValue()),
|
||||
jsonNode.get("property").textValue());
|
||||
orders.add(order);
|
||||
}
|
||||
|
||||
@@ -48,18 +48,15 @@ public class SpringDecoder implements Decoder {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object decode(final Response response, Type type)
|
||||
throws IOException, FeignException {
|
||||
if (type instanceof Class || type instanceof ParameterizedType
|
||||
|| type instanceof WildcardType) {
|
||||
public Object decode(final Response response, Type type) throws IOException, FeignException {
|
||||
if (type instanceof Class || type instanceof ParameterizedType || type instanceof WildcardType) {
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
HttpMessageConverterExtractor<?> extractor = new HttpMessageConverterExtractor(
|
||||
type, this.messageConverters.getObject().getConverters());
|
||||
HttpMessageConverterExtractor<?> extractor = new HttpMessageConverterExtractor(type,
|
||||
this.messageConverters.getObject().getConverters());
|
||||
|
||||
return extractor.extractData(new FeignResponseAdapter(response));
|
||||
}
|
||||
throw new DecodeException(response.status(),
|
||||
"type is not an instance of Class or ParameterizedType: " + type,
|
||||
throw new DecodeException(response.status(), "type is not an instance of Class or ParameterizedType: " + type,
|
||||
response.request());
|
||||
}
|
||||
|
||||
|
||||
@@ -69,19 +69,16 @@ public class SpringEncoder implements Encoder {
|
||||
this.messageConverters = messageConverters;
|
||||
}
|
||||
|
||||
public SpringEncoder(SpringFormEncoder springFormEncoder,
|
||||
ObjectFactory<HttpMessageConverters> messageConverters) {
|
||||
public SpringEncoder(SpringFormEncoder springFormEncoder, ObjectFactory<HttpMessageConverters> messageConverters) {
|
||||
this.springFormEncoder = springFormEncoder;
|
||||
this.messageConverters = messageConverters;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void encode(Object requestBody, Type bodyType, RequestTemplate request)
|
||||
throws EncodeException {
|
||||
public void encode(Object requestBody, Type bodyType, RequestTemplate request) throws EncodeException {
|
||||
// template.body(conversionService.convert(object, String.class));
|
||||
if (requestBody != null) {
|
||||
Collection<String> contentTypes = request.headers()
|
||||
.get(HttpEncoding.CONTENT_TYPE);
|
||||
Collection<String> contentTypes = request.headers().get(HttpEncoding.CONTENT_TYPE);
|
||||
|
||||
MediaType requestContentType = null;
|
||||
if (contentTypes != null && !contentTypes.isEmpty()) {
|
||||
@@ -95,24 +92,20 @@ public class SpringEncoder implements Encoder {
|
||||
}
|
||||
else {
|
||||
if (bodyType == MultipartFile.class) {
|
||||
log.warn(
|
||||
"For MultipartFile to be handled correctly, the 'consumes' parameter of @RequestMapping "
|
||||
+ "should be specified as MediaType.MULTIPART_FORM_DATA_VALUE");
|
||||
log.warn("For MultipartFile to be handled correctly, the 'consumes' parameter of @RequestMapping "
|
||||
+ "should be specified as MediaType.MULTIPART_FORM_DATA_VALUE");
|
||||
}
|
||||
}
|
||||
|
||||
for (HttpMessageConverter messageConverter : this.messageConverters
|
||||
.getObject().getConverters()) {
|
||||
for (HttpMessageConverter messageConverter : this.messageConverters.getObject().getConverters()) {
|
||||
FeignOutputMessage outputMessage;
|
||||
try {
|
||||
if (messageConverter instanceof GenericHttpMessageConverter) {
|
||||
outputMessage = checkAndWrite(requestBody, bodyType,
|
||||
requestContentType,
|
||||
outputMessage = checkAndWrite(requestBody, bodyType, requestContentType,
|
||||
(GenericHttpMessageConverter) messageConverter, request);
|
||||
}
|
||||
else {
|
||||
outputMessage = checkAndWrite(requestBody, requestContentType,
|
||||
messageConverter, request);
|
||||
outputMessage = checkAndWrite(requestBody, requestContentType, messageConverter, request);
|
||||
}
|
||||
}
|
||||
catch (IOException | HttpMessageConversionException ex) {
|
||||
@@ -131,20 +124,19 @@ public class SpringEncoder implements Encoder {
|
||||
charset = null;
|
||||
}
|
||||
else if (messageConverter instanceof ProtobufHttpMessageConverter
|
||||
&& ProtobufHttpMessageConverter.PROTOBUF.isCompatibleWith(
|
||||
outputMessage.getHeaders().getContentType())) {
|
||||
&& ProtobufHttpMessageConverter.PROTOBUF
|
||||
.isCompatibleWith(outputMessage.getHeaders().getContentType())) {
|
||||
charset = null;
|
||||
}
|
||||
else {
|
||||
charset = StandardCharsets.UTF_8;
|
||||
}
|
||||
request.body(Request.Body.encoded(
|
||||
outputMessage.getOutputStream().toByteArray(), charset));
|
||||
request.body(Request.Body.encoded(outputMessage.getOutputStream().toByteArray(), charset));
|
||||
return;
|
||||
}
|
||||
}
|
||||
String message = "Could not write request: no suitable HttpMessageConverter "
|
||||
+ "found for request type [" + requestBody.getClass().getName() + "]";
|
||||
String message = "Could not write request: no suitable HttpMessageConverter " + "found for request type ["
|
||||
+ requestBody.getClass().getName() + "]";
|
||||
if (requestContentType != null) {
|
||||
message += " and content type [" + requestContentType + "]";
|
||||
}
|
||||
@@ -153,8 +145,8 @@ public class SpringEncoder implements Encoder {
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private FeignOutputMessage checkAndWrite(Object body, MediaType contentType,
|
||||
HttpMessageConverter converter, RequestTemplate request) throws IOException {
|
||||
private FeignOutputMessage checkAndWrite(Object body, MediaType contentType, HttpMessageConverter converter,
|
||||
RequestTemplate request) throws IOException {
|
||||
if (converter.canWrite(body.getClass(), contentType)) {
|
||||
logBeforeWrite(body, contentType, converter);
|
||||
FeignOutputMessage outputMessage = new FeignOutputMessage(request);
|
||||
@@ -167,9 +159,8 @@ public class SpringEncoder implements Encoder {
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private FeignOutputMessage checkAndWrite(Object body, Type genericType,
|
||||
MediaType contentType, GenericHttpMessageConverter converter,
|
||||
RequestTemplate request) throws IOException {
|
||||
private FeignOutputMessage checkAndWrite(Object body, Type genericType, MediaType contentType,
|
||||
GenericHttpMessageConverter converter, RequestTemplate request) throws IOException {
|
||||
if (converter.canWrite(genericType, body.getClass(), contentType)) {
|
||||
logBeforeWrite(body, contentType, converter);
|
||||
FeignOutputMessage outputMessage = new FeignOutputMessage(request);
|
||||
@@ -185,12 +176,11 @@ public class SpringEncoder implements Encoder {
|
||||
HttpMessageConverter messageConverter) {
|
||||
if (log.isDebugEnabled()) {
|
||||
if (requestContentType != null) {
|
||||
log.debug("Writing [" + requestBody + "] as \"" + requestContentType
|
||||
+ "\" using [" + messageConverter + "]");
|
||||
log.debug("Writing [" + requestBody + "] as \"" + requestContentType + "\" using [" + messageConverter
|
||||
+ "]");
|
||||
}
|
||||
else {
|
||||
log.debug(
|
||||
"Writing [" + requestBody + "] using [" + messageConverter + "]");
|
||||
log.debug("Writing [" + requestBody + "] using [" + messageConverter + "]");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -79,18 +79,15 @@ import static org.springframework.core.annotation.AnnotatedElementUtils.findMerg
|
||||
* @author Artyom Romanenko
|
||||
* @author Darren Foong
|
||||
*/
|
||||
public class SpringMvcContract extends Contract.BaseContract
|
||||
implements ResourceLoaderAware {
|
||||
public class SpringMvcContract extends Contract.BaseContract implements ResourceLoaderAware {
|
||||
|
||||
private static final String ACCEPT = "Accept";
|
||||
|
||||
private static final String CONTENT_TYPE = "Content-Type";
|
||||
|
||||
private static final TypeDescriptor STRING_TYPE_DESCRIPTOR = TypeDescriptor
|
||||
.valueOf(String.class);
|
||||
private static final TypeDescriptor STRING_TYPE_DESCRIPTOR = TypeDescriptor.valueOf(String.class);
|
||||
|
||||
private static final TypeDescriptor ITERABLE_TYPE_DESCRIPTOR = TypeDescriptor
|
||||
.valueOf(Iterable.class);
|
||||
private static final TypeDescriptor ITERABLE_TYPE_DESCRIPTOR = TypeDescriptor.valueOf(Iterable.class);
|
||||
|
||||
private static final ParameterNameDiscoverer PARAMETER_NAME_DISCOVERER = new DefaultParameterNameDiscoverer();
|
||||
|
||||
@@ -108,16 +105,13 @@ public class SpringMvcContract extends Contract.BaseContract
|
||||
this(Collections.emptyList());
|
||||
}
|
||||
|
||||
public SpringMvcContract(
|
||||
List<AnnotatedParameterProcessor> annotatedParameterProcessors) {
|
||||
public SpringMvcContract(List<AnnotatedParameterProcessor> annotatedParameterProcessors) {
|
||||
this(annotatedParameterProcessors, new DefaultConversionService());
|
||||
}
|
||||
|
||||
public SpringMvcContract(
|
||||
List<AnnotatedParameterProcessor> annotatedParameterProcessors,
|
||||
public SpringMvcContract(List<AnnotatedParameterProcessor> annotatedParameterProcessors,
|
||||
ConversionService conversionService) {
|
||||
Assert.notNull(annotatedParameterProcessors,
|
||||
"Parameter processors can not be null.");
|
||||
Assert.notNull(annotatedParameterProcessors, "Parameter processors can not be null.");
|
||||
Assert.notNull(conversionService, "ConversionService can not be null.");
|
||||
|
||||
List<AnnotatedParameterProcessor> processors = getDefaultAnnotatedArgumentsProcessors();
|
||||
@@ -136,26 +130,21 @@ public class SpringMvcContract extends Contract.BaseContract
|
||||
// Feign applies the Param.Expander to each element of an Iterable, so in those
|
||||
// cases we need to provide a TypeDescriptor of the element.
|
||||
if (typeDescriptor.isAssignableTo(ITERABLE_TYPE_DESCRIPTOR)) {
|
||||
TypeDescriptor elementTypeDescriptor = getElementTypeDescriptor(
|
||||
typeDescriptor);
|
||||
TypeDescriptor elementTypeDescriptor = getElementTypeDescriptor(typeDescriptor);
|
||||
|
||||
checkState(elementTypeDescriptor != null,
|
||||
"Could not resolve element type of Iterable type %s. Not declared?",
|
||||
typeDescriptor);
|
||||
"Could not resolve element type of Iterable type %s. Not declared?", typeDescriptor);
|
||||
|
||||
typeDescriptor = elementTypeDescriptor;
|
||||
}
|
||||
return typeDescriptor;
|
||||
}
|
||||
|
||||
private static TypeDescriptor getElementTypeDescriptor(
|
||||
TypeDescriptor typeDescriptor) {
|
||||
private static TypeDescriptor getElementTypeDescriptor(TypeDescriptor typeDescriptor) {
|
||||
TypeDescriptor elementTypeDescriptor = typeDescriptor.getElementTypeDescriptor();
|
||||
// that means it's not a collection but it is iterable, gh-135
|
||||
if (elementTypeDescriptor == null
|
||||
&& Iterable.class.isAssignableFrom(typeDescriptor.getType())) {
|
||||
ResolvableType type = typeDescriptor.getResolvableType().as(Iterable.class)
|
||||
.getGeneric(0);
|
||||
if (elementTypeDescriptor == null && Iterable.class.isAssignableFrom(typeDescriptor.getType())) {
|
||||
ResolvableType type = typeDescriptor.getResolvableType().as(Iterable.class).getGeneric(0);
|
||||
if (type.resolve() == null) {
|
||||
return null;
|
||||
}
|
||||
@@ -172,8 +161,7 @@ public class SpringMvcContract extends Contract.BaseContract
|
||||
@Override
|
||||
protected void processAnnotationOnClass(MethodMetadata data, Class<?> clz) {
|
||||
if (clz.getInterfaces().length == 0) {
|
||||
RequestMapping classAnnotation = findMergedAnnotation(clz,
|
||||
RequestMapping.class);
|
||||
RequestMapping classAnnotation = findMergedAnnotation(clz, RequestMapping.class);
|
||||
if (classAnnotation != null) {
|
||||
// Prepend path from class annotation if specified
|
||||
if (classAnnotation.value().length > 0) {
|
||||
@@ -193,8 +181,7 @@ public class SpringMvcContract extends Contract.BaseContract
|
||||
processedMethods.put(Feign.configKey(targetType, method), method);
|
||||
MethodMetadata md = super.parseAndValidateMetadata(targetType, method);
|
||||
|
||||
RequestMapping classAnnotation = findMergedAnnotation(targetType,
|
||||
RequestMapping.class);
|
||||
RequestMapping classAnnotation = findMergedAnnotation(targetType, RequestMapping.class);
|
||||
if (classAnnotation != null) {
|
||||
// produces - use from class annotation only if method has not specified this
|
||||
if (!md.template().headers().containsKey(ACCEPT)) {
|
||||
@@ -214,16 +201,14 @@ public class SpringMvcContract extends Contract.BaseContract
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void processAnnotationOnMethod(MethodMetadata data,
|
||||
Annotation methodAnnotation, Method method) {
|
||||
protected void processAnnotationOnMethod(MethodMetadata data, Annotation methodAnnotation, Method method) {
|
||||
if (CollectionFormat.class.isInstance(methodAnnotation)) {
|
||||
CollectionFormat collectionFormat = findMergedAnnotation(method,
|
||||
CollectionFormat.class);
|
||||
CollectionFormat collectionFormat = findMergedAnnotation(method, CollectionFormat.class);
|
||||
data.template().collectionFormat(collectionFormat.value());
|
||||
}
|
||||
|
||||
if (!RequestMapping.class.isInstance(methodAnnotation) && !methodAnnotation
|
||||
.annotationType().isAnnotationPresent(RequestMapping.class)) {
|
||||
if (!RequestMapping.class.isInstance(methodAnnotation)
|
||||
&& !methodAnnotation.annotationType().isAnnotationPresent(RequestMapping.class)) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -263,34 +248,29 @@ public class SpringMvcContract extends Contract.BaseContract
|
||||
}
|
||||
|
||||
private String resolve(String value) {
|
||||
if (StringUtils.hasText(value)
|
||||
&& resourceLoader instanceof ConfigurableApplicationContext) {
|
||||
return ((ConfigurableApplicationContext) resourceLoader).getEnvironment()
|
||||
.resolvePlaceholders(value);
|
||||
if (StringUtils.hasText(value) && resourceLoader instanceof ConfigurableApplicationContext) {
|
||||
return ((ConfigurableApplicationContext) resourceLoader).getEnvironment().resolvePlaceholders(value);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private void checkAtMostOne(Method method, Object[] values, String fieldName) {
|
||||
checkState(values != null && (values.length == 0 || values.length == 1),
|
||||
"Method %s can only contain at most 1 %s field. Found: %s",
|
||||
method.getName(), fieldName,
|
||||
"Method %s can only contain at most 1 %s field. Found: %s", method.getName(), fieldName,
|
||||
values == null ? null : Arrays.asList(values));
|
||||
}
|
||||
|
||||
private void checkOne(Method method, Object[] values, String fieldName) {
|
||||
checkState(values != null && values.length == 1,
|
||||
"Method %s can only contain 1 %s field. Found: %s", method.getName(),
|
||||
fieldName, values == null ? null : Arrays.asList(values));
|
||||
checkState(values != null && values.length == 1, "Method %s can only contain 1 %s field. Found: %s",
|
||||
method.getName(), fieldName, values == null ? null : Arrays.asList(values));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean processAnnotationsOnParameter(MethodMetadata data,
|
||||
Annotation[] annotations, int paramIndex) {
|
||||
protected boolean processAnnotationsOnParameter(MethodMetadata data, Annotation[] annotations, int paramIndex) {
|
||||
boolean isHttpAnnotation = false;
|
||||
|
||||
AnnotatedParameterProcessor.AnnotatedParameterContext context = new SimpleAnnotatedParameterContext(
|
||||
data, paramIndex);
|
||||
AnnotatedParameterProcessor.AnnotatedParameterContext context = new SimpleAnnotatedParameterContext(data,
|
||||
paramIndex);
|
||||
Method method = processedMethods.get(data.configKey());
|
||||
for (Annotation parameterAnnotation : annotations) {
|
||||
AnnotatedParameterProcessor processor = annotatedArgumentProcessors
|
||||
@@ -299,19 +279,16 @@ public class SpringMvcContract extends Contract.BaseContract
|
||||
Annotation processParameterAnnotation;
|
||||
// synthesize, handling @AliasFor, while falling back to parameter name on
|
||||
// missing String #value():
|
||||
processParameterAnnotation = synthesizeWithMethodParameterNameAsFallbackValue(
|
||||
parameterAnnotation, method, paramIndex);
|
||||
isHttpAnnotation |= processor.processArgument(context,
|
||||
processParameterAnnotation, method);
|
||||
processParameterAnnotation = synthesizeWithMethodParameterNameAsFallbackValue(parameterAnnotation,
|
||||
method, paramIndex);
|
||||
isHttpAnnotation |= processor.processArgument(context, processParameterAnnotation, method);
|
||||
}
|
||||
}
|
||||
|
||||
if (!isMultipartFormData(data) && isHttpAnnotation
|
||||
&& data.indexToExpander().get(paramIndex) == null) {
|
||||
if (!isMultipartFormData(data) && isHttpAnnotation && data.indexToExpander().get(paramIndex) == null) {
|
||||
TypeDescriptor typeDescriptor = createTypeDescriptor(method, paramIndex);
|
||||
if (conversionService.canConvert(typeDescriptor, STRING_TYPE_DESCRIPTOR)) {
|
||||
Param.Expander expander = convertingExpanderFactory
|
||||
.getExpander(typeDescriptor);
|
||||
Param.Expander expander = convertingExpanderFactory.getExpander(typeDescriptor);
|
||||
if (expander != null) {
|
||||
data.indexToExpander().put(paramIndex, expander);
|
||||
}
|
||||
@@ -320,28 +297,23 @@ public class SpringMvcContract extends Contract.BaseContract
|
||||
return isHttpAnnotation;
|
||||
}
|
||||
|
||||
private void parseProduces(MethodMetadata md, Method method,
|
||||
RequestMapping annotation) {
|
||||
private void parseProduces(MethodMetadata md, Method method, RequestMapping annotation) {
|
||||
String[] serverProduces = annotation.produces();
|
||||
String clientAccepts = serverProduces.length == 0 ? null
|
||||
: emptyToNull(serverProduces[0]);
|
||||
String clientAccepts = serverProduces.length == 0 ? null : emptyToNull(serverProduces[0]);
|
||||
if (clientAccepts != null) {
|
||||
md.template().header(ACCEPT, clientAccepts);
|
||||
}
|
||||
}
|
||||
|
||||
private void parseConsumes(MethodMetadata md, Method method,
|
||||
RequestMapping annotation) {
|
||||
private void parseConsumes(MethodMetadata md, Method method, RequestMapping annotation) {
|
||||
String[] serverConsumes = annotation.consumes();
|
||||
String clientProduces = serverConsumes.length == 0 ? null
|
||||
: emptyToNull(serverConsumes[0]);
|
||||
String clientProduces = serverConsumes.length == 0 ? null : emptyToNull(serverConsumes[0]);
|
||||
if (clientProduces != null) {
|
||||
md.template().header(CONTENT_TYPE, clientProduces);
|
||||
}
|
||||
}
|
||||
|
||||
private void parseHeaders(MethodMetadata md, Method method,
|
||||
RequestMapping annotation) {
|
||||
private void parseHeaders(MethodMetadata md, Method method, RequestMapping annotation) {
|
||||
// TODO: only supports one header value per key
|
||||
if (annotation.headers() != null && annotation.headers().length > 0) {
|
||||
for (String header : annotation.headers()) {
|
||||
@@ -377,26 +349,21 @@ public class SpringMvcContract extends Contract.BaseContract
|
||||
return annotatedArgumentResolvers;
|
||||
}
|
||||
|
||||
private Annotation synthesizeWithMethodParameterNameAsFallbackValue(
|
||||
Annotation parameterAnnotation, Method method, int parameterIndex) {
|
||||
Map<String, Object> annotationAttributes = AnnotationUtils
|
||||
.getAnnotationAttributes(parameterAnnotation);
|
||||
private Annotation synthesizeWithMethodParameterNameAsFallbackValue(Annotation parameterAnnotation, Method method,
|
||||
int parameterIndex) {
|
||||
Map<String, Object> annotationAttributes = AnnotationUtils.getAnnotationAttributes(parameterAnnotation);
|
||||
Object defaultValue = AnnotationUtils.getDefaultValue(parameterAnnotation);
|
||||
if (defaultValue instanceof String
|
||||
&& defaultValue.equals(annotationAttributes.get(AnnotationUtils.VALUE))) {
|
||||
if (defaultValue instanceof String && defaultValue.equals(annotationAttributes.get(AnnotationUtils.VALUE))) {
|
||||
Type[] parameterTypes = method.getGenericParameterTypes();
|
||||
String[] parameterNames = PARAMETER_NAME_DISCOVERER.getParameterNames(method);
|
||||
if (shouldAddParameterName(parameterIndex, parameterTypes, parameterNames)) {
|
||||
annotationAttributes.put(AnnotationUtils.VALUE,
|
||||
parameterNames[parameterIndex]);
|
||||
annotationAttributes.put(AnnotationUtils.VALUE, parameterNames[parameterIndex]);
|
||||
}
|
||||
}
|
||||
return AnnotationUtils.synthesizeAnnotation(annotationAttributes,
|
||||
parameterAnnotation.annotationType(), null);
|
||||
return AnnotationUtils.synthesizeAnnotation(annotationAttributes, parameterAnnotation.annotationType(), null);
|
||||
}
|
||||
|
||||
private boolean shouldAddParameterName(int parameterIndex, Type[] parameterTypes,
|
||||
String[] parameterNames) {
|
||||
private boolean shouldAddParameterName(int parameterIndex, Type[] parameterTypes, String[] parameterNames) {
|
||||
// has a parameter name
|
||||
return parameterNames != null && parameterNames.length > parameterIndex
|
||||
// has a type
|
||||
@@ -404,14 +371,12 @@ public class SpringMvcContract extends Contract.BaseContract
|
||||
}
|
||||
|
||||
private boolean isMultipartFormData(MethodMetadata data) {
|
||||
Collection<String> contentTypes = data.template().headers()
|
||||
.get(HttpEncoding.CONTENT_TYPE);
|
||||
Collection<String> contentTypes = data.template().headers().get(HttpEncoding.CONTENT_TYPE);
|
||||
|
||||
if (contentTypes != null && !contentTypes.isEmpty()) {
|
||||
String type = contentTypes.iterator().next();
|
||||
try {
|
||||
return Objects.equals(MediaType.valueOf(type),
|
||||
MediaType.MULTIPART_FORM_DATA);
|
||||
return Objects.equals(MediaType.valueOf(type), MediaType.MULTIPART_FORM_DATA);
|
||||
}
|
||||
catch (InvalidMediaTypeException ignored) {
|
||||
return false;
|
||||
@@ -450,23 +415,20 @@ public class SpringMvcContract extends Contract.BaseContract
|
||||
|
||||
Param.Expander getExpander(TypeDescriptor typeDescriptor) {
|
||||
return value -> {
|
||||
Object converted = conversionService.convert(value, typeDescriptor,
|
||||
STRING_TYPE_DESCRIPTOR);
|
||||
Object converted = conversionService.convert(value, typeDescriptor, STRING_TYPE_DESCRIPTOR);
|
||||
return (String) converted;
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private class SimpleAnnotatedParameterContext
|
||||
implements AnnotatedParameterProcessor.AnnotatedParameterContext {
|
||||
private class SimpleAnnotatedParameterContext implements AnnotatedParameterProcessor.AnnotatedParameterContext {
|
||||
|
||||
private final MethodMetadata methodMetadata;
|
||||
|
||||
private final int parameterIndex;
|
||||
|
||||
SimpleAnnotatedParameterContext(MethodMetadata methodMetadata,
|
||||
int parameterIndex) {
|
||||
SimpleAnnotatedParameterContext(MethodMetadata methodMetadata, int parameterIndex) {
|
||||
this.methodMetadata = methodMetadata;
|
||||
this.parameterIndex = parameterIndex;
|
||||
}
|
||||
@@ -487,8 +449,7 @@ public class SpringMvcContract extends Contract.BaseContract
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<String> setTemplateParameter(String name,
|
||||
Collection<String> rest) {
|
||||
public Collection<String> setTemplateParameter(String name, Collection<String> rest) {
|
||||
return addTemplateParameter(rest, name);
|
||||
}
|
||||
|
||||
|
||||
@@ -43,10 +43,8 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@SpringBootTest(classes = DefaultGzipDecoderTests.Application.class,
|
||||
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
|
||||
value = { "spring.application.name=defaultGzipDecoderTests",
|
||||
"feign.compression.response.enabled=true",
|
||||
"feign.compression.response.useGzipDecoder=true",
|
||||
"feign.client.config.default.loggerLevel=full",
|
||||
value = { "spring.application.name=defaultGzipDecoderTests", "feign.compression.response.enabled=true",
|
||||
"feign.compression.response.useGzipDecoder=true", "feign.client.config.default.loggerLevel=full",
|
||||
"logging.level.org.springframework.cloud.openfeign=DEBUG" })
|
||||
@DirtiesContext
|
||||
public class DefaultGzipDecoderTests extends FeignClientFactoryBean {
|
||||
@@ -71,20 +69,17 @@ public class DefaultGzipDecoderTests extends FeignClientFactoryBean {
|
||||
public void testBodyDecompress() {
|
||||
ResponseEntity<Hello> response = testClient().getGzipResponse();
|
||||
assertThat(response).as("response was null").isNotNull();
|
||||
assertThat(response.getStatusCode()).as("wrong status code")
|
||||
.isEqualTo(HttpStatus.OK);
|
||||
assertThat(response.getStatusCode()).as("wrong status code").isEqualTo(HttpStatus.OK);
|
||||
Hello hello = response.getBody();
|
||||
assertThat(hello).as("hello was null").isNotNull();
|
||||
assertThat(hello).as("first hello didn't match")
|
||||
.isEqualTo(new Hello("hello world via response"));
|
||||
assertThat(hello).as("first hello didn't match").isEqualTo(new Hello("hello world via response"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNullBodyDecompress() {
|
||||
ResponseEntity<Hello> response = testClient().getNullResponse();
|
||||
assertThat(response).as("response was null").isNotNull();
|
||||
assertThat(response.getStatusCode()).as("wrong status code")
|
||||
.isEqualTo(HttpStatus.OK);
|
||||
assertThat(response.getStatusCode()).as("wrong status code").isEqualTo(HttpStatus.OK);
|
||||
Hello hello = response.getBody();
|
||||
assertThat(hello).as("hello was not null").isNull();
|
||||
assertThat(hello).as("null hello didn't match").isEqualTo(null);
|
||||
@@ -94,12 +89,10 @@ public class DefaultGzipDecoderTests extends FeignClientFactoryBean {
|
||||
public void testCharsetDecompress() {
|
||||
ResponseEntity<Hello> response = testClient().getUtf8Response();
|
||||
assertThat(response).as("response was null").isNotNull();
|
||||
assertThat(response.getStatusCode()).as("wrong status code")
|
||||
.isEqualTo(HttpStatus.OK);
|
||||
assertThat(response.getStatusCode()).as("wrong status code").isEqualTo(HttpStatus.OK);
|
||||
Hello hello = response.getBody();
|
||||
assertThat(hello).as("hello was null").isNotNull();
|
||||
assertThat(hello).as("utf8 hello didn't match")
|
||||
.isEqualTo(new Hello("안녕하세요 means Hello in Korean"));
|
||||
assertThat(hello).as("utf8 hello didn't match").isEqualTo(new Hello("안녕하세요 means Hello in Korean"));
|
||||
}
|
||||
|
||||
private static class Hello {
|
||||
|
||||
@@ -42,8 +42,7 @@ public class EnableFeignClientsSpringDataTests {
|
||||
@Test
|
||||
public void encoderDefaultCorrect() {
|
||||
|
||||
PageableSpringEncoder.class
|
||||
.cast(this.feignContext.getInstance("foo", Encoder.class));
|
||||
PageableSpringEncoder.class.cast(this.feignContext.getInstance("foo", Encoder.class));
|
||||
}
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
|
||||
@@ -41,8 +41,7 @@ public class FeignBuilderCustomizerTests {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
|
||||
FeignBuilderCustomizerTests.SampleConfiguration2.class);
|
||||
|
||||
FeignClientFactoryBean clientFactoryBean = context
|
||||
.getBean(FeignClientFactoryBean.class);
|
||||
FeignClientFactoryBean clientFactoryBean = context.getBean(FeignClientFactoryBean.class);
|
||||
FeignContext feignContext = context.getBean(FeignContext.class);
|
||||
|
||||
Feign.Builder builder = clientFactoryBean.feign(feignContext);
|
||||
@@ -52,14 +51,12 @@ public class FeignBuilderCustomizerTests {
|
||||
context.close();
|
||||
}
|
||||
|
||||
private void assertFeignBuilderField(Feign.Builder builder, String fieldName,
|
||||
Object expectedValue) {
|
||||
private void assertFeignBuilderField(Feign.Builder builder, String fieldName, Object expectedValue) {
|
||||
Field builderField = ReflectionUtils.findField(Feign.Builder.class, fieldName);
|
||||
ReflectionUtils.makeAccessible(builderField);
|
||||
|
||||
Object value = ReflectionUtils.getField(builderField, builder);
|
||||
assertThat(value).as("Expected value for the field '" + fieldName + "':")
|
||||
.isEqualTo(expectedValue);
|
||||
assertThat(value).as("Expected value for the field '" + fieldName + "':").isEqualTo(expectedValue);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -67,8 +64,7 @@ public class FeignBuilderCustomizerTests {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
|
||||
FeignBuilderCustomizerTests.SampleConfiguration3.class);
|
||||
|
||||
FeignClientFactoryBean clientFactoryBean = context
|
||||
.getBean(FeignClientFactoryBean.class);
|
||||
FeignClientFactoryBean clientFactoryBean = context.getBean(FeignClientFactoryBean.class);
|
||||
FeignContext feignContext = context.getBean(FeignContext.class);
|
||||
|
||||
Feign.Builder builder = clientFactoryBean.feign(feignContext);
|
||||
|
||||
@@ -49,26 +49,23 @@ public class FeignClientBuilderTests {
|
||||
|
||||
private ApplicationContext applicationContext;
|
||||
|
||||
private static Object getDefaultValueFromFeignClientAnnotation(
|
||||
final String methodName) {
|
||||
private static Object getDefaultValueFromFeignClientAnnotation(final String methodName) {
|
||||
final Method method = ReflectionUtils.findMethod(FeignClient.class, methodName);
|
||||
return method.getDefaultValue();
|
||||
}
|
||||
|
||||
private static void assertFactoryBeanField(final FeignClientBuilder.Builder builder,
|
||||
final String fieldName, final Object expectedValue) {
|
||||
final Field factoryBeanField = ReflectionUtils
|
||||
.findField(FeignClientBuilder.Builder.class, "feignClientFactoryBean");
|
||||
private static void assertFactoryBeanField(final FeignClientBuilder.Builder builder, final String fieldName,
|
||||
final Object expectedValue) {
|
||||
final Field factoryBeanField = ReflectionUtils.findField(FeignClientBuilder.Builder.class,
|
||||
"feignClientFactoryBean");
|
||||
ReflectionUtils.makeAccessible(factoryBeanField);
|
||||
final FeignClientFactoryBean factoryBean = (FeignClientFactoryBean) ReflectionUtils
|
||||
.getField(factoryBeanField, builder);
|
||||
final FeignClientFactoryBean factoryBean = (FeignClientFactoryBean) ReflectionUtils.getField(factoryBeanField,
|
||||
builder);
|
||||
|
||||
final Field field = ReflectionUtils.findField(FeignClientFactoryBean.class,
|
||||
fieldName);
|
||||
final Field field = ReflectionUtils.findField(FeignClientFactoryBean.class, fieldName);
|
||||
ReflectionUtils.makeAccessible(field);
|
||||
final Object value = ReflectionUtils.getField(field, factoryBean);
|
||||
assertThat(value).as("Expected value for the field '" + fieldName + "':")
|
||||
.isEqualTo(expectedValue);
|
||||
assertThat(value).as("Expected value for the field '" + fieldName + "':").isEqualTo(expectedValue);
|
||||
}
|
||||
|
||||
@Before
|
||||
@@ -83,9 +80,8 @@ public class FeignClientBuilderTests {
|
||||
for (final Method method : FeignClient.class.getMethods()) {
|
||||
methodNames.add(method.getName());
|
||||
}
|
||||
methodNames.removeAll(
|
||||
Arrays.asList("annotationType", "value", "serviceId", "qualifier",
|
||||
"configuration", "primary", "equals", "hashCode", "toString"));
|
||||
methodNames.removeAll(Arrays.asList("annotationType", "value", "serviceId", "qualifier", "configuration",
|
||||
"primary", "equals", "hashCode", "toString"));
|
||||
Collections.sort(methodNames);
|
||||
// If this safety check fails the Builder has to be updated.
|
||||
// (1) Either a field was removed from the FeignClient annotation and so it has to
|
||||
@@ -93,15 +89,14 @@ public class FeignClientBuilderTests {
|
||||
// on this builder class.
|
||||
// (2) Or a new field was added and the builder class has to be extended with this
|
||||
// new field.
|
||||
assertThat(methodNames).containsExactly("contextId", "decode404", "fallback",
|
||||
"fallbackFactory", "name", "path", "url");
|
||||
assertThat(methodNames).containsExactly("contextId", "decode404", "fallback", "fallbackFactory", "name", "path",
|
||||
"url");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void forType_preinitializedBuilder() {
|
||||
// when:
|
||||
final FeignClientBuilder.Builder builder = this.feignClientBuilder
|
||||
.forType(TestFeignClient.class, "TestClient");
|
||||
final FeignClientBuilder.Builder builder = this.feignClientBuilder.forType(TestFeignClient.class, "TestClient");
|
||||
|
||||
// then:
|
||||
assertFactoryBeanField(builder, "applicationContext", this.applicationContext);
|
||||
@@ -110,24 +105,18 @@ public class FeignClientBuilderTests {
|
||||
assertFactoryBeanField(builder, "contextId", "TestClient");
|
||||
|
||||
// and:
|
||||
assertFactoryBeanField(builder, "url",
|
||||
getDefaultValueFromFeignClientAnnotation("url"));
|
||||
assertFactoryBeanField(builder, "path",
|
||||
getDefaultValueFromFeignClientAnnotation("path"));
|
||||
assertFactoryBeanField(builder, "decode404",
|
||||
getDefaultValueFromFeignClientAnnotation("decode404"));
|
||||
assertFactoryBeanField(builder, "fallback",
|
||||
getDefaultValueFromFeignClientAnnotation("fallback"));
|
||||
assertFactoryBeanField(builder, "fallbackFactory",
|
||||
getDefaultValueFromFeignClientAnnotation("fallbackFactory"));
|
||||
assertFactoryBeanField(builder, "url", getDefaultValueFromFeignClientAnnotation("url"));
|
||||
assertFactoryBeanField(builder, "path", getDefaultValueFromFeignClientAnnotation("path"));
|
||||
assertFactoryBeanField(builder, "decode404", getDefaultValueFromFeignClientAnnotation("decode404"));
|
||||
assertFactoryBeanField(builder, "fallback", getDefaultValueFromFeignClientAnnotation("fallback"));
|
||||
assertFactoryBeanField(builder, "fallbackFactory", getDefaultValueFromFeignClientAnnotation("fallbackFactory"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void forType_allFieldsSetOnBuilder() {
|
||||
// when:
|
||||
final FeignClientBuilder.Builder builder = this.feignClientBuilder
|
||||
.forType(TestFeignClient.class, "TestClient").decode404(true).url("Url/")
|
||||
.path("/Path").contextId("TestContext");
|
||||
final FeignClientBuilder.Builder builder = this.feignClientBuilder.forType(TestFeignClient.class, "TestClient")
|
||||
.decode404(true).url("Url/").path("/Path").contextId("TestContext");
|
||||
|
||||
// then:
|
||||
assertFactoryBeanField(builder, "applicationContext", this.applicationContext);
|
||||
@@ -146,9 +135,8 @@ public class FeignClientBuilderTests {
|
||||
public void forType_clientFactoryBeanProvided() {
|
||||
// when:
|
||||
final FeignClientBuilder.Builder builder = this.feignClientBuilder
|
||||
.forType(TestFeignClient.class, new FeignClientFactoryBean(),
|
||||
"TestClient")
|
||||
.decode404(true).path("Path/").url("Url/").contextId("TestContext");
|
||||
.forType(TestFeignClient.class, new FeignClientFactoryBean(), "TestClient").decode404(true)
|
||||
.path("Path/").url("Url/").contextId("TestContext");
|
||||
|
||||
// then:
|
||||
assertFactoryBeanField(builder, "applicationContext", this.applicationContext);
|
||||
@@ -165,12 +153,14 @@ public class FeignClientBuilderTests {
|
||||
@Test
|
||||
public void forType_build() {
|
||||
// given:
|
||||
Mockito.when(this.applicationContext.getBean(FeignContext.class))
|
||||
.thenThrow(new ClosedFileSystemException()); // throw an unusual exception
|
||||
// in the
|
||||
// FeignClientFactoryBean
|
||||
final FeignClientBuilder.Builder builder = this.feignClientBuilder
|
||||
.forType(TestClient.class, "TestClient");
|
||||
Mockito.when(this.applicationContext.getBean(FeignContext.class)).thenThrow(new ClosedFileSystemException()); // throw
|
||||
// an
|
||||
// unusual
|
||||
// exception
|
||||
// in
|
||||
// the
|
||||
// FeignClientFactoryBean
|
||||
final FeignClientBuilder.Builder builder = this.feignClientBuilder.forType(TestClient.class, "TestClient");
|
||||
|
||||
// expect: 'the build will fail right after calling build() with the mocked
|
||||
// unusual exception'
|
||||
|
||||
@@ -67,8 +67,7 @@ public class FeignClientErrorDecoderTests {
|
||||
|
||||
@Test
|
||||
public void errorDecoderInConfiguration() {
|
||||
assertThat(this.context.getInstance("foo", ErrorDecoder.class))
|
||||
.isInstanceOf(ErrorDecoder.Default.class);
|
||||
assertThat(this.context.getInstance("foo", ErrorDecoder.class)).isInstanceOf(ErrorDecoder.Default.class);
|
||||
assertThat(this.context.getInstance("bar", ErrorDecoder.class)).isNull();
|
||||
}
|
||||
|
||||
@@ -90,8 +89,7 @@ public class FeignClientErrorDecoderTests {
|
||||
Map<Method, InvocationHandlerFactory.MethodHandler> dispatch = (Map<Method, InvocationHandlerFactory.MethodHandler>) ReflectionTestUtils
|
||||
.getField(invocationHandler, "dispatch");
|
||||
Method key = new ArrayList<>(dispatch.keySet()).get(0);
|
||||
return ReflectionTestUtils.getField(
|
||||
ReflectionTestUtils.getField(dispatch.get(key), "asyncResponseHandler"),
|
||||
return ReflectionTestUtils.getField(ReflectionTestUtils.getField(dispatch.get(key), "asyncResponseHandler"),
|
||||
"errorDecoder");
|
||||
}
|
||||
|
||||
|
||||
@@ -53,8 +53,7 @@ public class FeignClientFactoryTests {
|
||||
parent.refresh();
|
||||
FeignContext context = new FeignContext();
|
||||
context.setApplicationContext(parent);
|
||||
context.setConfigurations(Arrays.asList(getSpec("foo", FooConfig.class),
|
||||
getSpec("bar", BarConfig.class)));
|
||||
context.setConfigurations(Arrays.asList(getSpec("foo", FooConfig.class), getSpec("bar", BarConfig.class)));
|
||||
|
||||
Foo foo = context.getInstance("foo", Foo.class);
|
||||
assertThat(foo).as("foo was null").isNotNull();
|
||||
@@ -68,8 +67,7 @@ public class FeignClientFactoryTests {
|
||||
|
||||
@Test
|
||||
public void shouldRedirectToDelegateWhenUrlSet() {
|
||||
new ApplicationContextRunner().withUserConfiguration(TestConfig.class)
|
||||
.run(this::defaultClientUsed);
|
||||
new ApplicationContextRunner().withUserConfiguration(TestConfig.class).run(this::defaultClientUsed);
|
||||
}
|
||||
|
||||
@SuppressWarnings({ "unchecked", "ConstantConditions" })
|
||||
@@ -99,16 +97,14 @@ public class FeignClientFactoryTests {
|
||||
|
||||
@Bean
|
||||
BlockingLoadBalancerClient loadBalancerClient() {
|
||||
return new BlockingLoadBalancerClient(new LoadBalancerClientFactory(),
|
||||
new LoadBalancerProperties());
|
||||
return new BlockingLoadBalancerClient(new LoadBalancerClientFactory(), new LoadBalancerProperties());
|
||||
}
|
||||
|
||||
@Bean
|
||||
FeignContext feignContext() {
|
||||
FeignContext feignContext = new FeignContext();
|
||||
feignContext.setConfigurations(
|
||||
Collections.singletonList(new FeignClientSpecification("test",
|
||||
new Class[] { LoadBalancerAutoConfiguration.class })));
|
||||
feignContext.setConfigurations(Collections.singletonList(
|
||||
new FeignClientSpecification("test", new Class[] { LoadBalancerAutoConfiguration.class })));
|
||||
return feignContext;
|
||||
}
|
||||
|
||||
|
||||
@@ -95,14 +95,12 @@ class FeignClientOverrideDefaultsTests {
|
||||
@Test
|
||||
void overrideLoggerLevel() {
|
||||
assertThat(context.getInstance("foo", Logger.Level.class)).isNull();
|
||||
assertThat(context.getInstance("bar", Logger.Level.class))
|
||||
.isEqualTo(Logger.Level.HEADERS);
|
||||
assertThat(context.getInstance("bar", Logger.Level.class)).isEqualTo(Logger.Level.HEADERS);
|
||||
}
|
||||
|
||||
@Test
|
||||
void overrideRetryer() {
|
||||
assertThat(context.getInstance("foo", Retryer.class))
|
||||
.isEqualTo(Retryer.NEVER_RETRY);
|
||||
assertThat(context.getInstance("foo", Retryer.class)).isEqualTo(Retryer.NEVER_RETRY);
|
||||
Retryer.Default.class.cast(context.getInstance("bar", Retryer.class));
|
||||
}
|
||||
|
||||
@@ -122,29 +120,24 @@ class FeignClientOverrideDefaultsTests {
|
||||
|
||||
@Test
|
||||
void overrideQueryMapEncoder() {
|
||||
QueryMapEncoder.Default.class
|
||||
.cast(context.getInstance("foo", QueryMapEncoder.class));
|
||||
QueryMapEncoder.Default.class.cast(context.getInstance("foo", QueryMapEncoder.class));
|
||||
BeanQueryMapEncoder.class.cast(context.getInstance("bar", QueryMapEncoder.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void addRequestInterceptor() {
|
||||
assertThat(context.getInstances("foo", RequestInterceptor.class).size())
|
||||
.isEqualTo(1);
|
||||
assertThat(context.getInstances("bar", RequestInterceptor.class).size())
|
||||
.isEqualTo(2);
|
||||
assertThat(context.getInstances("foo", RequestInterceptor.class).size()).isEqualTo(1);
|
||||
assertThat(context.getInstances("bar", RequestInterceptor.class).size()).isEqualTo(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
void exceptionPropagationPolicy() {
|
||||
assertThat(context.getInstances("foo", ExceptionPropagationPolicy.class))
|
||||
.isEmpty();
|
||||
assertThat(context.getInstances("foo", ExceptionPropagationPolicy.class)).isEmpty();
|
||||
assertThat(context.getInstances("bar", ExceptionPropagationPolicy.class))
|
||||
.containsValues(ExceptionPropagationPolicy.UNWRAP);
|
||||
}
|
||||
|
||||
@FeignClient(name = "foo", url = "https://foo",
|
||||
configuration = FooConfiguration.class)
|
||||
@FeignClient(name = "foo", url = "https://foo", configuration = FooConfiguration.class)
|
||||
interface FooClient {
|
||||
|
||||
@RequestLine("GET /")
|
||||
@@ -152,8 +145,7 @@ class FeignClientOverrideDefaultsTests {
|
||||
|
||||
}
|
||||
|
||||
@FeignClient(name = "bar", url = "https://bar",
|
||||
configuration = BarConfiguration.class)
|
||||
@FeignClient(name = "bar", url = "https://bar", configuration = BarConfiguration.class)
|
||||
interface BarClient {
|
||||
|
||||
@RequestMapping(value = "/", method = RequestMethod.GET)
|
||||
|
||||
@@ -63,11 +63,9 @@ public class FeignClientUsingConfigurerTest {
|
||||
.getBean(BEAN_NAME_PREFIX + "TestFeignClient");
|
||||
Feign.Builder builder = factoryBean.feign(context);
|
||||
|
||||
List<RequestInterceptor> interceptors = (List) getBuilderValue(builder,
|
||||
"requestInterceptors");
|
||||
List<RequestInterceptor> interceptors = (List) getBuilderValue(builder, "requestInterceptors");
|
||||
assertThat(interceptors.size()).as("interceptors not set").isEqualTo(3);
|
||||
assertThat(getBuilderValue(builder, "logLevel")).as("log level not set")
|
||||
.isEqualTo(Logger.Level.FULL);
|
||||
assertThat(getBuilderValue(builder, "logLevel")).as("log level not set").isEqualTo(Logger.Level.FULL);
|
||||
}
|
||||
|
||||
private Object getBuilderValue(Feign.Builder builder, String member) {
|
||||
@@ -83,12 +81,10 @@ public class FeignClientUsingConfigurerTest {
|
||||
.getBean(BEAN_NAME_PREFIX + "NoInheritFeignClient");
|
||||
Feign.Builder builder = factoryBean.feign(context);
|
||||
|
||||
List<RequestInterceptor> interceptors = (List) getBuilderValue(builder,
|
||||
"requestInterceptors");
|
||||
List<RequestInterceptor> interceptors = (List) getBuilderValue(builder, "requestInterceptors");
|
||||
|
||||
assertThat(interceptors).as("interceptors not set").isEmpty();
|
||||
assertThat(factoryBean.isInheritParentContext())
|
||||
.as("is inheriting from parent configuration").isFalse();
|
||||
assertThat(factoryBean.isInheritParentContext()).as("is inheriting from parent configuration").isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -97,8 +93,7 @@ public class FeignClientUsingConfigurerTest {
|
||||
.getBean(BEAN_NAME_PREFIX + "NoInheritFeignClient");
|
||||
Feign.Builder builder = factoryBean.feign(context);
|
||||
|
||||
assertThat(getBuilderValue(builder, "logLevel")).as("log level not set")
|
||||
.isEqualTo(Logger.Level.HEADERS);
|
||||
assertThat(getBuilderValue(builder, "logLevel")).as("log level not set").isEqualTo(Logger.Level.HEADERS);
|
||||
}
|
||||
|
||||
@EnableAutoConfiguration
|
||||
@@ -140,8 +135,7 @@ public class FeignClientUsingConfigurerTest {
|
||||
|
||||
}
|
||||
|
||||
@FeignClient(name = "noInheritFeignClient",
|
||||
configuration = NoInheritConfiguration.class)
|
||||
@FeignClient(name = "noInheritFeignClient", configuration = NoInheritConfiguration.class)
|
||||
interface NoInheritFeignClient {
|
||||
|
||||
}
|
||||
|
||||
@@ -69,8 +69,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
|
||||
*/
|
||||
@SuppressWarnings("FieldMayBeFinal")
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@SpringBootTest(classes = FeignClientUsingPropertiesTests.Application.class,
|
||||
webEnvironment = RANDOM_PORT)
|
||||
@SpringBootTest(classes = FeignClientUsingPropertiesTests.Application.class, webEnvironment = RANDOM_PORT)
|
||||
@TestPropertySource("classpath:feign-properties.properties")
|
||||
@DirtiesContext
|
||||
public class FeignClientUsingPropertiesTests {
|
||||
@@ -112,26 +111,22 @@ public class FeignClientUsingPropertiesTests {
|
||||
|
||||
public FooClient fooClient() {
|
||||
fooFactoryBean.setApplicationContext(applicationContext);
|
||||
return fooFactoryBean.feign(context).target(FooClient.class,
|
||||
"http://localhost:" + port);
|
||||
return fooFactoryBean.feign(context).target(FooClient.class, "http://localhost:" + port);
|
||||
}
|
||||
|
||||
public BarClient barClient() {
|
||||
barFactoryBean.setApplicationContext(applicationContext);
|
||||
return barFactoryBean.feign(context).target(BarClient.class,
|
||||
"http://localhost:" + port);
|
||||
return barFactoryBean.feign(context).target(BarClient.class, "http://localhost:" + port);
|
||||
}
|
||||
|
||||
public UnwrapClient unwrapClient() {
|
||||
unwrapFactoryBean.setApplicationContext(applicationContext);
|
||||
return unwrapFactoryBean.feign(context).target(UnwrapClient.class,
|
||||
"http://localhost:" + port);
|
||||
return unwrapFactoryBean.feign(context).target(UnwrapClient.class, "http://localhost:" + port);
|
||||
}
|
||||
|
||||
public FormClient formClient() {
|
||||
formFactoryBean.setApplicationContext(applicationContext);
|
||||
return formFactoryBean.feign(context).target(FormClient.class,
|
||||
"http://localhost:" + port);
|
||||
return formFactoryBean.feign(context).target(FormClient.class, "http://localhost:" + port);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -166,8 +161,8 @@ public class FeignClientUsingPropertiesTests {
|
||||
readTimeoutFactoryBean.setType(FeignClientFactoryBean.class);
|
||||
readTimeoutFactoryBean.setApplicationContext(applicationContext);
|
||||
|
||||
TimeoutClient client = readTimeoutFactoryBean.feign(context)
|
||||
.target(TimeoutClient.class, "http://localhost:" + port);
|
||||
TimeoutClient client = readTimeoutFactoryBean.feign(context).target(TimeoutClient.class,
|
||||
"http://localhost:" + port);
|
||||
|
||||
Request.Options options = getRequestOptions((Proxy) client);
|
||||
|
||||
@@ -182,8 +177,8 @@ public class FeignClientUsingPropertiesTests {
|
||||
readTimeoutFactoryBean.setType(FeignClientFactoryBean.class);
|
||||
readTimeoutFactoryBean.setApplicationContext(applicationContext);
|
||||
|
||||
TimeoutClient client = readTimeoutFactoryBean.feign(context)
|
||||
.target(TimeoutClient.class, "http://localhost:" + port);
|
||||
TimeoutClient client = readTimeoutFactoryBean.feign(context).target(TimeoutClient.class,
|
||||
"http://localhost:" + port);
|
||||
|
||||
Request.Options options = getRequestOptions((Proxy) client);
|
||||
|
||||
@@ -196,8 +191,7 @@ public class FeignClientUsingPropertiesTests {
|
||||
Map<Method, InvocationHandlerFactory.MethodHandler> dispatch = (Map<Method, InvocationHandlerFactory.MethodHandler>) ReflectionTestUtils
|
||||
.getField(Objects.requireNonNull(invocationHandler), "dispatch");
|
||||
Method key = new ArrayList<>(dispatch.keySet()).get(0);
|
||||
return (Request.Options) ReflectionTestUtils.getField(dispatch.get(key),
|
||||
"options");
|
||||
return (Request.Options) ReflectionTestUtils.getField(dispatch.get(key), "options");
|
||||
}
|
||||
|
||||
protected interface FooClient {
|
||||
@@ -244,8 +238,7 @@ public class FeignClientUsingPropertiesTests {
|
||||
|
||||
@RequestMapping(method = RequestMethod.GET, value = "/foo")
|
||||
public String foo(HttpServletRequest request) throws IllegalAccessException {
|
||||
if ("Foo".equals(request.getHeader("Foo"))
|
||||
&& "Bar".equals(request.getHeader("Bar"))) {
|
||||
if ("Foo".equals(request.getHeader("Foo")) && "Bar".equals(request.getHeader("Bar"))) {
|
||||
return "OK";
|
||||
}
|
||||
else {
|
||||
@@ -306,16 +299,14 @@ public class FeignClientUsingPropertiesTests {
|
||||
public static class FormEncoder implements Encoder {
|
||||
|
||||
@Override
|
||||
public void encode(Object o, Type type, RequestTemplate requestTemplate)
|
||||
throws EncodeException {
|
||||
public void encode(Object o, Type type, RequestTemplate requestTemplate) throws EncodeException {
|
||||
Map<String, String> form = (Map<String, String>) o;
|
||||
StringBuilder builder = new StringBuilder();
|
||||
form.forEach((key, value) -> {
|
||||
builder.append(key + "=" + value + "&");
|
||||
});
|
||||
|
||||
requestTemplate.header(HttpHeaders.CONTENT_TYPE,
|
||||
MediaType.APPLICATION_FORM_URLENCODED_VALUE);
|
||||
requestTemplate.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE);
|
||||
requestTemplate.body(builder.toString());
|
||||
}
|
||||
|
||||
|
||||
@@ -89,8 +89,7 @@ public class FeignClientsRegistrarTests {
|
||||
new AnnotationConfigApplicationContext(FallbackFactoryTestConfig.class);
|
||||
}
|
||||
|
||||
@FeignClient(name = "fallbackTestClient", url = "http://localhost:8080/",
|
||||
fallback = FallbackClient.class)
|
||||
@FeignClient(name = "fallbackTestClient", url = "http://localhost:8080/", fallback = FallbackClient.class)
|
||||
protected interface FallbackClient {
|
||||
|
||||
@RequestMapping(method = RequestMethod.GET, value = "/hello")
|
||||
@@ -116,8 +115,7 @@ public class FeignClientsRegistrarTests {
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@EnableAutoConfiguration
|
||||
@EnableFeignClients(
|
||||
clients = { FeignClientsRegistrarTests.FallbackFactoryClient.class })
|
||||
@EnableFeignClients(clients = { FeignClientsRegistrarTests.FallbackFactoryClient.class })
|
||||
protected static class FallbackFactoryTestConfig {
|
||||
|
||||
}
|
||||
|
||||
@@ -50,17 +50,15 @@ public class FeignCompressionTests {
|
||||
@Test
|
||||
public void testInterceptors() {
|
||||
new ApplicationContextRunner()
|
||||
.withPropertyValues("feign.compression.response.enabled=true",
|
||||
"feign.compression.request.enabled=true",
|
||||
.withPropertyValues("feign.compression.response.enabled=true", "feign.compression.request.enabled=true",
|
||||
"feign.okhttp.enabled=false")
|
||||
.withConfiguration(AutoConfigurations.of(FeignAutoConfiguration.class,
|
||||
FeignContentGzipEncodingAutoConfiguration.class,
|
||||
FeignAcceptGzipEncodingAutoConfiguration.class,
|
||||
FeignContentGzipEncodingAutoConfiguration.class, FeignAcceptGzipEncodingAutoConfiguration.class,
|
||||
HttpClientConfiguration.class, PlainConfig.class))
|
||||
.run(context -> {
|
||||
FeignContext feignContext = context.getBean(FeignContext.class);
|
||||
Map<String, RequestInterceptor> interceptors = feignContext
|
||||
.getInstances("foo", RequestInterceptor.class);
|
||||
Map<String, RequestInterceptor> interceptors = feignContext.getInstances("foo",
|
||||
RequestInterceptor.class);
|
||||
assertThat(interceptors.size()).isEqualTo(2);
|
||||
assertThat(interceptors.get("feignAcceptGzipEncodingInterceptor"))
|
||||
.isInstanceOf(FeignAcceptGzipEncodingInterceptor.class);
|
||||
|
||||
@@ -39,11 +39,9 @@ public class FeignContextTest {
|
||||
|
||||
FeignContext feignContext = new FeignContext();
|
||||
feignContext.setApplicationContext(parent);
|
||||
feignContext.setConfigurations(
|
||||
Lists.newArrayList(getSpec("empty", EmptyConfiguration.class)));
|
||||
feignContext.setConfigurations(Lists.newArrayList(getSpec("empty", EmptyConfiguration.class)));
|
||||
|
||||
Logger.Level level = feignContext.getInstanceWithoutAncestors("empty",
|
||||
Logger.Level.class);
|
||||
Logger.Level level = feignContext.getInstanceWithoutAncestors("empty", Logger.Level.class);
|
||||
|
||||
assertThat(level).as("Logger was not null").isNull();
|
||||
}
|
||||
@@ -59,8 +57,7 @@ public class FeignContextTest {
|
||||
|
||||
FeignContext feignContext = new FeignContext();
|
||||
feignContext.setApplicationContext(parent);
|
||||
feignContext.setConfigurations(
|
||||
Lists.newArrayList(getSpec("empty", EmptyConfiguration.class)));
|
||||
feignContext.setConfigurations(Lists.newArrayList(getSpec("empty", EmptyConfiguration.class)));
|
||||
|
||||
Collection<RequestInterceptor> interceptors = feignContext
|
||||
.getInstancesWithoutAncestors("empty", RequestInterceptor.class).values();
|
||||
@@ -75,11 +72,9 @@ public class FeignContextTest {
|
||||
|
||||
FeignContext feignContext = new FeignContext();
|
||||
feignContext.setApplicationContext(parent);
|
||||
feignContext.setConfigurations(
|
||||
Lists.newArrayList(getSpec("demo", DemoConfiguration.class)));
|
||||
feignContext.setConfigurations(Lists.newArrayList(getSpec("demo", DemoConfiguration.class)));
|
||||
|
||||
Logger.Level level = feignContext.getInstanceWithoutAncestors("demo",
|
||||
Logger.Level.class);
|
||||
Logger.Level level = feignContext.getInstanceWithoutAncestors("demo", Logger.Level.class);
|
||||
|
||||
assertThat(level).isEqualTo(Logger.Level.FULL);
|
||||
}
|
||||
@@ -91,8 +86,7 @@ public class FeignContextTest {
|
||||
|
||||
FeignContext feignContext = new FeignContext();
|
||||
feignContext.setApplicationContext(parent);
|
||||
feignContext.setConfigurations(
|
||||
Lists.newArrayList(getSpec("demo", DemoConfiguration.class)));
|
||||
feignContext.setConfigurations(Lists.newArrayList(getSpec("demo", DemoConfiguration.class)));
|
||||
|
||||
Collection<RequestInterceptor> interceptors = feignContext
|
||||
.getInstancesWithoutAncestors("demo", RequestInterceptor.class).values();
|
||||
|
||||
@@ -34,20 +34,16 @@ public class FeignErrorDecoderFactoryTests {
|
||||
|
||||
@Test
|
||||
public void testNoDefaultFactory() {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
|
||||
SampleConfiguration1.class);
|
||||
String[] beanNamesForType = context
|
||||
.getBeanNamesForType(FeignErrorDecoderFactory.class);
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SampleConfiguration1.class);
|
||||
String[] beanNamesForType = context.getBeanNamesForType(FeignErrorDecoderFactory.class);
|
||||
assertThat(beanNamesForType).isEmpty();
|
||||
context.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCustomErrorDecoderFactory() {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
|
||||
SampleConfiguration2.class);
|
||||
FeignErrorDecoderFactory errorDecoderFactory = context
|
||||
.getBean(FeignErrorDecoderFactory.class);
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SampleConfiguration2.class);
|
||||
FeignErrorDecoderFactory errorDecoderFactory = context.getBean(FeignErrorDecoderFactory.class);
|
||||
assertThat(errorDecoderFactory).isNotNull();
|
||||
ErrorDecoder errorDecoder = errorDecoderFactory.create(Object.class);
|
||||
assertThat(errorDecoder).isNotNull();
|
||||
@@ -57,10 +53,8 @@ public class FeignErrorDecoderFactoryTests {
|
||||
|
||||
@Test
|
||||
public void testCustomErrorDecoderFactoryNotOverwritingErrorDecoder() {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
|
||||
SampleConfiguration3.class);
|
||||
FeignErrorDecoderFactory errorDecoderFactory = context
|
||||
.getBean(FeignErrorDecoderFactory.class);
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SampleConfiguration3.class);
|
||||
FeignErrorDecoderFactory errorDecoderFactory = context.getBean(FeignErrorDecoderFactory.class);
|
||||
assertThat(errorDecoderFactory).isNotNull();
|
||||
ErrorDecoder errorDecoderFromFactory = errorDecoderFactory.create(Object.class);
|
||||
assertThat(errorDecoderFromFactory).isNotNull();
|
||||
|
||||
@@ -53,10 +53,8 @@ public class FeignHttpClientConfigurationTests {
|
||||
@Before
|
||||
public void setUp() {
|
||||
this.context = new SpringApplicationBuilder()
|
||||
.properties("debug=true", "feign.httpclient.disableSslValidation=true")
|
||||
.web(WebApplicationType.NONE)
|
||||
.sources(HttpClientConfiguration.class, FeignAutoConfiguration.class)
|
||||
.run();
|
||||
.properties("debug=true", "feign.httpclient.disableSslValidation=true").web(WebApplicationType.NONE)
|
||||
.sources(HttpClientConfiguration.class, FeignAutoConfiguration.class).run();
|
||||
}
|
||||
|
||||
@After
|
||||
@@ -68,13 +66,10 @@ public class FeignHttpClientConfigurationTests {
|
||||
|
||||
@Test
|
||||
public void disableSslTest() throws Exception {
|
||||
HttpClientConnectionManager connectionManager = this.context
|
||||
.getBean(HttpClientConnectionManager.class);
|
||||
Lookup<ConnectionSocketFactory> socketFactoryRegistry = getConnectionSocketFactoryLookup(
|
||||
connectionManager);
|
||||
HttpClientConnectionManager connectionManager = this.context.getBean(HttpClientConnectionManager.class);
|
||||
Lookup<ConnectionSocketFactory> socketFactoryRegistry = getConnectionSocketFactoryLookup(connectionManager);
|
||||
assertThat(socketFactoryRegistry.lookup("https")).isNotNull();
|
||||
assertThat(this.getX509TrustManager(socketFactoryRegistry).getAcceptedIssuers())
|
||||
.isNull();
|
||||
assertThat(this.getX509TrustManager(socketFactoryRegistry).getAcceptedIssuers()).isNull();
|
||||
}
|
||||
|
||||
private Lookup<ConnectionSocketFactory> getConnectionSocketFactoryLookup(
|
||||
@@ -84,14 +79,11 @@ public class FeignHttpClientConfigurationTests {
|
||||
return (Lookup) this.getField(connectionOperator, "socketFactoryRegistry");
|
||||
}
|
||||
|
||||
private X509TrustManager getX509TrustManager(
|
||||
Lookup<ConnectionSocketFactory> socketFactoryRegistry) {
|
||||
private X509TrustManager getX509TrustManager(Lookup<ConnectionSocketFactory> socketFactoryRegistry) {
|
||||
ConnectionSocketFactory connectionSocketFactory = (ConnectionSocketFactory) socketFactoryRegistry
|
||||
.lookup("https");
|
||||
SSLSocketFactory sslSocketFactory = (SSLSocketFactory) this
|
||||
.getField(connectionSocketFactory, "socketfactory");
|
||||
SSLContextSpi sslContext = (SSLContextSpi) this.getField(sslSocketFactory,
|
||||
"context");
|
||||
SSLSocketFactory sslSocketFactory = (SSLSocketFactory) this.getField(connectionSocketFactory, "socketfactory");
|
||||
SSLContextSpi sslContext = (SSLContextSpi) this.getField(sslSocketFactory, "context");
|
||||
return (X509TrustManager) this.getField(sslContext, "trustManager");
|
||||
}
|
||||
|
||||
|
||||
@@ -50,10 +50,8 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
|
||||
* @author Spencer Gibb
|
||||
*/
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = FeignHttpClientUrlTests.TestConfig.class,
|
||||
webEnvironment = DEFINED_PORT,
|
||||
value = { "spring.application.name=feignclienturltest",
|
||||
"feign.hystrix.enabled=false", "feign.okhttp.enabled=false" })
|
||||
@SpringBootTest(classes = FeignHttpClientUrlTests.TestConfig.class, webEnvironment = DEFINED_PORT, value = {
|
||||
"spring.application.name=feignclienturltest", "feign.hystrix.enabled=false", "feign.okhttp.enabled=false" })
|
||||
@DirtiesContext
|
||||
public class FeignHttpClientUrlTests {
|
||||
|
||||
@@ -84,24 +82,21 @@ public class FeignHttpClientUrlTests {
|
||||
assertThat(this.urlClient).as("UrlClient was null").isNotNull();
|
||||
Hello hello = this.urlClient.getHello();
|
||||
assertThat(hello).as("hello was null").isNotNull();
|
||||
assertThat(hello).as("first hello didn't match")
|
||||
.isEqualTo(new Hello("hello world 1"));
|
||||
assertThat(hello).as("first hello didn't match").isEqualTo(new Hello("hello world 1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBeanUrl() {
|
||||
Hello hello = this.beanClient.getHello();
|
||||
assertThat(hello).as("hello was null").isNotNull();
|
||||
assertThat(hello).as("first hello didn't match")
|
||||
.isEqualTo(new Hello("hello world 1"));
|
||||
assertThat(hello).as("first hello didn't match").isEqualTo(new Hello("hello world 1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBeanUrlNoProtocol() {
|
||||
Hello hello = this.beanClientNoProtocol.getHello();
|
||||
assertThat(hello).as("hello was null").isNotNull();
|
||||
assertThat(hello).as("first hello didn't match")
|
||||
.isEqualTo(new Hello("hello world 1"));
|
||||
assertThat(hello).as("first hello didn't match").isEqualTo(new Hello("hello world 1"));
|
||||
}
|
||||
|
||||
// this tests that
|
||||
@@ -132,8 +127,7 @@ public class FeignHttpClientUrlTests {
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@EnableAutoConfiguration
|
||||
@RestController
|
||||
@EnableFeignClients(clients = { UrlClient.class, BeanUrlClient.class,
|
||||
BeanUrlClientNoProtocol.class })
|
||||
@EnableFeignClients(clients = { UrlClient.class, BeanUrlClient.class, BeanUrlClientNoProtocol.class })
|
||||
@Import(NoSecurityConfiguration.class)
|
||||
protected static class TestConfig {
|
||||
|
||||
@@ -161,15 +155,13 @@ public class FeignHttpClientUrlTests {
|
||||
public Targeter feignTargeter() {
|
||||
return new Targeter() {
|
||||
@Override
|
||||
public <T> T target(FeignClientFactoryBean factory, Feign.Builder feign,
|
||||
FeignContext context, Target.HardCodedTarget<T> target) {
|
||||
Field field = ReflectionUtils.findField(Feign.Builder.class,
|
||||
"client");
|
||||
public <T> T target(FeignClientFactoryBean factory, Feign.Builder feign, FeignContext context,
|
||||
Target.HardCodedTarget<T> target) {
|
||||
Field field = ReflectionUtils.findField(Feign.Builder.class, "client");
|
||||
ReflectionUtils.makeAccessible(field);
|
||||
Client client = (Client) ReflectionUtils.getField(field, feign);
|
||||
if (target.name().equals("localappurl")) {
|
||||
assertThat(client).isInstanceOf(ApacheHttpClient.class)
|
||||
.as("client was wrong type");
|
||||
assertThat(client).isInstanceOf(ApacheHttpClient.class).as("client was wrong type");
|
||||
}
|
||||
return feign.target(target);
|
||||
}
|
||||
|
||||
@@ -34,8 +34,7 @@ public class FeignLoggerFactoryTests {
|
||||
|
||||
@Test
|
||||
public void testDefaultLogger() {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
|
||||
SampleConfiguration1.class);
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SampleConfiguration1.class);
|
||||
FeignLoggerFactory loggerFactory = context.getBean(FeignLoggerFactory.class);
|
||||
assertThat(loggerFactory).isNotNull();
|
||||
Logger logger = loggerFactory.create(Object.class);
|
||||
@@ -46,8 +45,7 @@ public class FeignLoggerFactoryTests {
|
||||
|
||||
@Test
|
||||
public void testCustomLogger() {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
|
||||
SampleConfiguration2.class);
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SampleConfiguration2.class);
|
||||
FeignLoggerFactory loggerFactory = context.getBean(FeignLoggerFactory.class);
|
||||
assertThat(loggerFactory).isNotNull();
|
||||
Logger logger = loggerFactory.create(Object.class);
|
||||
@@ -58,8 +56,7 @@ public class FeignLoggerFactoryTests {
|
||||
|
||||
@Test
|
||||
public void testCustomLoggerFactory() {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
|
||||
SampleConfiguration3.class);
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SampleConfiguration3.class);
|
||||
FeignLoggerFactory loggerFactory = context.getBean(FeignLoggerFactory.class);
|
||||
assertThat(loggerFactory).isNotNull();
|
||||
assertThat(loggerFactory instanceof LoggerFactoryImpl).isTrue();
|
||||
|
||||
@@ -49,10 +49,9 @@ public class FeignOkHttpConfigurationTests {
|
||||
@Before
|
||||
public void setUp() {
|
||||
this.context = new SpringApplicationBuilder()
|
||||
.properties("debug=true", "feign.httpclient.disableSslValidation=true",
|
||||
"feign.okhttp.enabled=true", "feign.httpclient.enabled=false")
|
||||
.web(WebApplicationType.NONE)
|
||||
.sources(HttpClientConfiguration.class, FeignAutoConfiguration.class)
|
||||
.properties("debug=true", "feign.httpclient.disableSslValidation=true", "feign.okhttp.enabled=true",
|
||||
"feign.httpclient.enabled=false")
|
||||
.web(WebApplicationType.NONE).sources(HttpClientConfiguration.class, FeignAutoConfiguration.class)
|
||||
.run();
|
||||
}
|
||||
|
||||
@@ -66,11 +65,8 @@ public class FeignOkHttpConfigurationTests {
|
||||
@Test
|
||||
public void disableSslTest() throws Exception {
|
||||
OkHttpClient httpClient = this.context.getBean(OkHttpClient.class);
|
||||
HostnameVerifier hostnameVerifier = (HostnameVerifier) this.getField(httpClient,
|
||||
"hostnameVerifier");
|
||||
assertThat(
|
||||
OkHttpClientFactory.TrustAllHostnames.class.isInstance(hostnameVerifier))
|
||||
.isTrue();
|
||||
HostnameVerifier hostnameVerifier = (HostnameVerifier) this.getField(httpClient, "hostnameVerifier");
|
||||
assertThat(OkHttpClientFactory.TrustAllHostnames.class.isInstance(hostnameVerifier)).isTrue();
|
||||
}
|
||||
|
||||
protected <T> Object getField(Object target, String name) {
|
||||
|
||||
@@ -47,9 +47,8 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
* @author Spencer Gibb
|
||||
*/
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@SpringBootTest(classes = SpringDecoderTests.Application.class,
|
||||
webEnvironment = WebEnvironment.RANDOM_PORT, value = {
|
||||
"spring.application.name=springdecodertest", "spring.jmx.enabled=false" })
|
||||
@SpringBootTest(classes = SpringDecoderTests.Application.class, webEnvironment = WebEnvironment.RANDOM_PORT,
|
||||
value = { "spring.application.name=springdecodertest", "spring.jmx.enabled=false" })
|
||||
@DirtiesContext
|
||||
public class SpringDecoderTests extends FeignClientFactoryBean {
|
||||
|
||||
@@ -71,28 +70,24 @@ public class SpringDecoderTests extends FeignClientFactoryBean {
|
||||
public TestClient testClient(boolean decode404) {
|
||||
setType(this.getClass());
|
||||
setDecode404(decode404);
|
||||
return feign(this.context).target(TestClient.class,
|
||||
"http://localhost:" + this.port);
|
||||
return feign(this.context).target(TestClient.class, "http://localhost:" + this.port);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testResponseEntity() {
|
||||
ResponseEntity<Hello> response = testClient().getHelloResponse();
|
||||
assertThat(response).as("response was null").isNotNull();
|
||||
assertThat(response.getStatusCode()).as("wrong status code")
|
||||
.isEqualTo(HttpStatus.OK);
|
||||
assertThat(response.getStatusCode()).as("wrong status code").isEqualTo(HttpStatus.OK);
|
||||
Hello hello = response.getBody();
|
||||
assertThat(hello).as("hello was null").isNotNull();
|
||||
assertThat(hello).as("first hello didn't match")
|
||||
.isEqualTo(new Hello("hello world via response"));
|
||||
assertThat(hello).as("first hello didn't match").isEqualTo(new Hello("hello world via response"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSimpleType() {
|
||||
Hello hello = testClient().getHello();
|
||||
assertThat(hello).as("hello was null").isNotNull();
|
||||
assertThat(hello).as("first hello didn't match")
|
||||
.isEqualTo(new Hello("hello world 1"));
|
||||
assertThat(hello).as("first hello didn't match").isEqualTo(new Hello("hello world 1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -100,8 +95,7 @@ public class SpringDecoderTests extends FeignClientFactoryBean {
|
||||
List<Hello> hellos = testClient().getHellos();
|
||||
assertThat(hellos).as("hellos was null").isNotNull();
|
||||
assertThat(hellos.size()).as("hellos was not the right size").isEqualTo(2);
|
||||
assertThat(hellos.get(0)).as("first hello didn't match")
|
||||
.isEqualTo(new Hello("hello world 1"));
|
||||
assertThat(hellos.get(0)).as("first hello didn't match").isEqualTo(new Hello("hello world 1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -109,8 +103,7 @@ public class SpringDecoderTests extends FeignClientFactoryBean {
|
||||
List<String> hellos = testClient().getHelloStrings();
|
||||
assertThat(hellos).as("hellos was null").isNotNull();
|
||||
assertThat(hellos.size()).as("hellos was not the right size").isEqualTo(2);
|
||||
assertThat(hellos.get(0)).as("first hello didn't match")
|
||||
.isEqualTo("hello world 1");
|
||||
assertThat(hellos.get(0)).as("first hello didn't match").isEqualTo("hello world 1");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -118,15 +111,12 @@ public class SpringDecoderTests extends FeignClientFactoryBean {
|
||||
public void testWildcardTypeDecode() {
|
||||
ResponseEntity<?> wildcard = testClient().getWildcard();
|
||||
assertThat(wildcard).as("wildcard was null").isNotNull();
|
||||
assertThat(wildcard.getStatusCode()).as("wrong status code")
|
||||
.isEqualTo(HttpStatus.OK);
|
||||
assertThat(wildcard.getStatusCode()).as("wrong status code").isEqualTo(HttpStatus.OK);
|
||||
Object wildcardBody = wildcard.getBody();
|
||||
assertThat(wildcardBody).as("wildcardBody was null").isNotNull();
|
||||
assertThat(wildcardBody instanceof Map).as("wildcard not an instance of Map")
|
||||
.isTrue();
|
||||
assertThat(wildcardBody instanceof Map).as("wildcard not an instance of Map").isTrue();
|
||||
Map<String, String> hello = (Map<String, String>) wildcardBody;
|
||||
assertThat(hello.get("message")).as("first hello didn't match")
|
||||
.isEqualTo("wildcard");
|
||||
assertThat(hello.get("message")).as("first hello didn't match").isEqualTo("wildcard");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -54,11 +54,10 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
* @author Aaron Whiteside
|
||||
*/
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@SpringBootTest(classes = BeansFeignClientTests.Application.class,
|
||||
webEnvironment = WebEnvironment.RANDOM_PORT,
|
||||
@SpringBootTest(classes = BeansFeignClientTests.Application.class, webEnvironment = WebEnvironment.RANDOM_PORT,
|
||||
value = { "spring.application.name=feignclienttest",
|
||||
"logging.level.org.springframework.cloud.openfeign.valid=DEBUG",
|
||||
"feign.httpclient.enabled=false", "feign.okhttp.enabled=false" })
|
||||
"logging.level.org.springframework.cloud.openfeign.valid=DEBUG", "feign.httpclient.enabled=false",
|
||||
"feign.okhttp.enabled=false" })
|
||||
@DirtiesContext
|
||||
public class BeansFeignClientTests {
|
||||
|
||||
@@ -81,18 +80,15 @@ public class BeansFeignClientTests {
|
||||
|
||||
@Test
|
||||
public void testAnnotations() {
|
||||
Map<String, Object> beans = this.context
|
||||
.getBeansWithAnnotation(FeignClient.class);
|
||||
assertThat(beans.containsKey(TestClient.class.getName()))
|
||||
.as("Wrong clients: " + beans).isTrue();
|
||||
Map<String, Object> beans = this.context.getBeansWithAnnotation(FeignClient.class);
|
||||
assertThat(beans.containsKey(TestClient.class.getName())).as("Wrong clients: " + beans).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testClient() {
|
||||
assertThat(this.testClient).as("testClient was null").isNotNull();
|
||||
assertThat(this.extraClient).as("extraClient was null").isNotNull();
|
||||
assertThat(Proxy.isProxyClass(this.testClient.getClass()))
|
||||
.as("testClient is not a java Proxy").isTrue();
|
||||
assertThat(Proxy.isProxyClass(this.testClient.getClass())).as("testClient is not a java Proxy").isTrue();
|
||||
InvocationHandler invocationHandler = Proxy.getInvocationHandler(this.testClient);
|
||||
assertThat(invocationHandler).as("invocationHandler was null").isNotNull();
|
||||
}
|
||||
@@ -100,20 +96,17 @@ public class BeansFeignClientTests {
|
||||
@Test
|
||||
public void extraClient() {
|
||||
assertThat(this.extraClient).as("extraClient was null").isNotNull();
|
||||
assertThat(Proxy.isProxyClass(this.extraClient.getClass()))
|
||||
.as("extraClient is not a java Proxy").isTrue();
|
||||
InvocationHandler invocationHandler = Proxy
|
||||
.getInvocationHandler(this.extraClient);
|
||||
assertThat(Proxy.isProxyClass(this.extraClient.getClass())).as("extraClient is not a java Proxy").isTrue();
|
||||
InvocationHandler invocationHandler = Proxy.getInvocationHandler(this.extraClient);
|
||||
assertThat(invocationHandler).as("invocationHandler was null").isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void buildByBuilder() {
|
||||
assertThat(this.buildByBuilder).as("buildByBuilder was null").isNotNull();
|
||||
assertThat(Proxy.isProxyClass(this.buildByBuilder.getClass()))
|
||||
.as("buildByBuilder is not a java Proxy").isTrue();
|
||||
InvocationHandler invocationHandler = Proxy
|
||||
.getInvocationHandler(this.buildByBuilder);
|
||||
assertThat(Proxy.isProxyClass(this.buildByBuilder.getClass())).as("buildByBuilder is not a java Proxy")
|
||||
.isTrue();
|
||||
InvocationHandler invocationHandler = Proxy.getInvocationHandler(this.buildByBuilder);
|
||||
assertThat(invocationHandler).as("invocationHandler was null").isNotNull();
|
||||
}
|
||||
|
||||
|
||||
@@ -48,8 +48,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
|
||||
*
|
||||
* @author Jakub Narloch
|
||||
*/
|
||||
@SpringBootTest(classes = FeignAcceptEncodingTests.Application.class,
|
||||
webEnvironment = RANDOM_PORT,
|
||||
@SpringBootTest(classes = FeignAcceptEncodingTests.Application.class, webEnvironment = RANDOM_PORT,
|
||||
value = { "feign.compression.response.enabled=true" })
|
||||
@RunWith(SpringRunner.class)
|
||||
@DirtiesContext
|
||||
@@ -74,8 +73,7 @@ public class FeignAcceptEncodingTests {
|
||||
|
||||
@EnableFeignClients(clients = InvoiceClient.class)
|
||||
@LoadBalancerClient(name = "local", configuration = LocalClientConfiguration.class)
|
||||
@SpringBootApplication(
|
||||
scanBasePackages = "org.springframework.cloud.openfeign.encoding.app")
|
||||
@SpringBootApplication(scanBasePackages = "org.springframework.cloud.openfeign.encoding.app")
|
||||
@Import(NoSecurityConfiguration.class)
|
||||
public static class Application {
|
||||
|
||||
@@ -88,8 +86,7 @@ public class FeignAcceptEncodingTests {
|
||||
private int port = 0;
|
||||
|
||||
@Bean
|
||||
public ServiceInstanceListSupplier staticServiceInstanceListSupplier(
|
||||
Environment env) {
|
||||
public ServiceInstanceListSupplier staticServiceInstanceListSupplier(Environment env) {
|
||||
return ServiceInstanceListSupplier.fixed(env).instance(port, "local").build();
|
||||
}
|
||||
|
||||
|
||||
@@ -47,8 +47,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
|
||||
*
|
||||
* @author Jakub Narloch
|
||||
*/
|
||||
@SpringBootTest(classes = FeignContentEncodingTests.Application.class,
|
||||
webEnvironment = RANDOM_PORT,
|
||||
@SpringBootTest(classes = FeignContentEncodingTests.Application.class, webEnvironment = RANDOM_PORT,
|
||||
value = { "feign.compression.request.enabled=true",
|
||||
"hystrix.command.default.execution.isolation.strategy=SEMAPHORE",
|
||||
"ribbon.OkToRetryOnAllOperations=false" })
|
||||
@@ -65,8 +64,7 @@ public class FeignContentEncodingTests {
|
||||
final List<Invoice> invoices = Invoices.createInvoiceList(50);
|
||||
|
||||
// when
|
||||
final ResponseEntity<List<Invoice>> response = this.invoiceClient
|
||||
.saveInvoices(invoices);
|
||||
final ResponseEntity<List<Invoice>> response = this.invoiceClient.saveInvoices(invoices);
|
||||
|
||||
// then
|
||||
assertThat(response).isNotNull();
|
||||
@@ -78,8 +76,7 @@ public class FeignContentEncodingTests {
|
||||
|
||||
@EnableFeignClients(clients = InvoiceClient.class)
|
||||
@LoadBalancerClient(name = "local", configuration = LocalClientConfiguration.class)
|
||||
@SpringBootApplication(
|
||||
scanBasePackages = "org.springframework.cloud.openfeign.encoding.app")
|
||||
@SpringBootApplication(scanBasePackages = "org.springframework.cloud.openfeign.encoding.app")
|
||||
@Import(NoSecurityConfiguration.class)
|
||||
public static class Application {
|
||||
|
||||
@@ -92,8 +89,7 @@ public class FeignContentEncodingTests {
|
||||
private int port = 0;
|
||||
|
||||
@Bean
|
||||
public ServiceInstanceListSupplier staticServiceInstanceListSupplier(
|
||||
Environment env) {
|
||||
public ServiceInstanceListSupplier staticServiceInstanceListSupplier(Environment env) {
|
||||
return ServiceInstanceListSupplier.fixed(env).instance(port, "local").build();
|
||||
}
|
||||
|
||||
|
||||
@@ -54,8 +54,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
|
||||
*
|
||||
* @author Charlie Mordant.
|
||||
*/
|
||||
@SpringBootTest(classes = FeignPageableEncodingTests.Application.class,
|
||||
webEnvironment = RANDOM_PORT,
|
||||
@SpringBootTest(classes = FeignPageableEncodingTests.Application.class, webEnvironment = RANDOM_PORT,
|
||||
value = { "feign.compression.request.enabled=true",
|
||||
"hystrix.command.default.execution.isolation.strategy=SEMAPHORE",
|
||||
"ribbon.OkToRetryOnAllOperations=false" })
|
||||
@@ -72,8 +71,7 @@ public class FeignPageableEncodingTests {
|
||||
Pageable pageable = PageRequest.of(0, 10, Sort.Direction.ASC, "sortProperty");
|
||||
|
||||
// when
|
||||
final ResponseEntity<Page<Invoice>> response = this.invoiceClient
|
||||
.getInvoicesPaged(pageable);
|
||||
final ResponseEntity<Page<Invoice>> response = this.invoiceClient.getInvoicesPaged(pageable);
|
||||
|
||||
// then
|
||||
assertThat(response).isNotNull();
|
||||
@@ -81,8 +79,7 @@ public class FeignPageableEncodingTests {
|
||||
assertThat(response.getBody()).isNotNull();
|
||||
assertThat(pageable.getPageSize()).isEqualTo(response.getBody().getSize());
|
||||
assertThat(response.getBody().getPageable().getSort()).hasSize(1);
|
||||
Optional<Sort.Order> optionalOrder = response.getBody().getPageable().getSort()
|
||||
.get().findFirst();
|
||||
Optional<Sort.Order> optionalOrder = response.getBody().getPageable().getSort().get().findFirst();
|
||||
if (optionalOrder.isPresent()) {
|
||||
Sort.Order order = optionalOrder.get();
|
||||
assertThat(order.getDirection()).isEqualTo(Sort.Direction.ASC);
|
||||
@@ -93,8 +90,7 @@ public class FeignPageableEncodingTests {
|
||||
|
||||
@EnableFeignClients(clients = InvoiceClient.class)
|
||||
@LoadBalancerClient(name = "local", configuration = LocalClientConfiguration.class)
|
||||
@SpringBootApplication(
|
||||
scanBasePackages = "org.springframework.cloud.openfeign.encoding.app",
|
||||
@SpringBootApplication(scanBasePackages = "org.springframework.cloud.openfeign.encoding.app",
|
||||
exclude = { RepositoryRestMvcAutoConfiguration.class })
|
||||
@EnableSpringDataWebSupport
|
||||
@Import({ NoSecurityConfiguration.class, FeignClientsConfiguration.class })
|
||||
@@ -109,8 +105,7 @@ public class FeignPageableEncodingTests {
|
||||
private int port = 0;
|
||||
|
||||
@Bean
|
||||
public ServiceInstanceListSupplier staticServiceInstanceListSupplier(
|
||||
Environment env) {
|
||||
public ServiceInstanceListSupplier staticServiceInstanceListSupplier(Environment env) {
|
||||
return ServiceInstanceListSupplier.fixed(env).instance(port, "local").build();
|
||||
}
|
||||
|
||||
|
||||
@@ -35,8 +35,7 @@ final class Invoices {
|
||||
for (int ind = 0; ind < count; ind++) {
|
||||
final Invoice invoice = new Invoice();
|
||||
invoice.setTitle("Invoice " + (ind + 1));
|
||||
invoice.setAmount(new BigDecimal(
|
||||
String.format(Locale.US, "%.2f", Math.random() * 1000)));
|
||||
invoice.setAmount(new BigDecimal(String.format(Locale.US, "%.2f", Math.random() * 1000)));
|
||||
invoices.add(invoice);
|
||||
}
|
||||
return invoices;
|
||||
|
||||
@@ -34,17 +34,13 @@ import org.springframework.web.bind.annotation.RequestMethod;
|
||||
@FeignClient("local")
|
||||
public interface InvoiceClient {
|
||||
|
||||
@RequestMapping(value = "invoicesPaged", method = RequestMethod.GET,
|
||||
produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
ResponseEntity<Page<Invoice>> getInvoicesPaged(
|
||||
org.springframework.data.domain.Pageable pageable);
|
||||
@RequestMapping(value = "invoicesPaged", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
ResponseEntity<Page<Invoice>> getInvoicesPaged(org.springframework.data.domain.Pageable pageable);
|
||||
|
||||
@RequestMapping(value = "invoices", method = RequestMethod.GET,
|
||||
produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
@RequestMapping(value = "invoices", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
ResponseEntity<List<Invoice>> getInvoices();
|
||||
|
||||
@RequestMapping(value = "invoices", method = RequestMethod.POST,
|
||||
consumes = MediaType.APPLICATION_JSON_VALUE,
|
||||
@RequestMapping(value = "invoices", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE,
|
||||
produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
ResponseEntity<List<Invoice>> saveInvoices(List<Invoice> invoices);
|
||||
|
||||
|
||||
@@ -39,27 +39,22 @@ import org.springframework.web.bind.annotation.RestController;
|
||||
@RestController
|
||||
public class InvoiceResource {
|
||||
|
||||
@RequestMapping(value = "invoices", method = RequestMethod.GET,
|
||||
produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
@RequestMapping(value = "invoices", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
public ResponseEntity<List<Invoice>> getInvoices() {
|
||||
|
||||
return ResponseEntity.ok(createInvoiceList(100));
|
||||
}
|
||||
|
||||
@RequestMapping(value = "invoices", method = RequestMethod.POST,
|
||||
consumes = MediaType.APPLICATION_JSON_VALUE,
|
||||
@RequestMapping(value = "invoices", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE,
|
||||
produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
ResponseEntity<List<Invoice>> saveInvoices(@RequestBody List<Invoice> invoices) {
|
||||
|
||||
return ResponseEntity.ok(invoices);
|
||||
}
|
||||
|
||||
@RequestMapping(value = "invoicesPaged", method = RequestMethod.GET,
|
||||
produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
public ResponseEntity<Page<Invoice>> getInvoicesPaged(
|
||||
org.springframework.data.domain.Pageable pageable) {
|
||||
Page<Invoice> page = new PageImpl<>(createInvoiceList(pageable.getPageSize()),
|
||||
pageable, 100);
|
||||
@RequestMapping(value = "invoicesPaged", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
public ResponseEntity<Page<Invoice>> getInvoicesPaged(org.springframework.data.domain.Pageable pageable) {
|
||||
Page<Invoice> page = new PageImpl<>(createInvoiceList(pageable.getPageSize()), pageable, 100);
|
||||
return ResponseEntity.ok(page);
|
||||
}
|
||||
|
||||
@@ -68,8 +63,7 @@ public class InvoiceResource {
|
||||
for (int ind = 0; ind < count; ind++) {
|
||||
final Invoice invoice = new Invoice();
|
||||
invoice.setTitle("Invoice " + (ind + 1));
|
||||
invoice.setAmount(new BigDecimal(
|
||||
String.format(Locale.US, "%.2f", Math.random() * 1000)));
|
||||
invoice.setAmount(new BigDecimal(String.format(Locale.US, "%.2f", Math.random() * 1000)));
|
||||
invoices.add(invoice);
|
||||
}
|
||||
return invoices;
|
||||
|
||||
@@ -68,9 +68,8 @@ public class ProtobufSpringEncoderTest {
|
||||
|
||||
// a protobuf object with some content
|
||||
private org.springframework.cloud.openfeign.encoding.proto.Request request = org.springframework.cloud.openfeign.encoding.proto.Request
|
||||
.newBuilder().setId(1000000).setMsg("Erlang/OTP 最初是爱立信为开发电信设备系统设计的编程语言平台,"
|
||||
+ "电信设备(路由器、接入网关、…)典型设计是通过背板连接主控板卡与多块业务板卡的分布式系统。")
|
||||
.build();
|
||||
.newBuilder().setId(1000000)
|
||||
.setMsg("Erlang/OTP 最初是爱立信为开发电信设备系统设计的编程语言平台," + "电信设备(路由器、接入网关、…)典型设计是通过背板连接主控板卡与多块业务板卡的分布式系统。").build();
|
||||
|
||||
@Test
|
||||
public void testProtobuf() throws IOException, URISyntaxException {
|
||||
@@ -92,8 +91,7 @@ public class ProtobufSpringEncoderTest {
|
||||
RequestTemplate requestTemplate = newRequestTemplate();
|
||||
newEncoder().encode(this.request, Request.class, requestTemplate);
|
||||
// set a charset
|
||||
requestTemplate.body(
|
||||
encoded(requestTemplate.requestBody().asBytes(), StandardCharsets.UTF_8));
|
||||
requestTemplate.body(encoded(requestTemplate.requestBody().asBytes(), StandardCharsets.UTF_8));
|
||||
HttpEntity entity = toApacheHttpEntity(requestTemplate);
|
||||
byte[] bytes = read(entity.getContent(), (int) entity.getContentLength());
|
||||
|
||||
@@ -125,21 +123,17 @@ public class ProtobufSpringEncoderTest {
|
||||
return requestTemplate;
|
||||
}
|
||||
|
||||
private HttpEntity toApacheHttpEntity(RequestTemplate requestTemplate)
|
||||
throws IOException, URISyntaxException {
|
||||
private HttpEntity toApacheHttpEntity(RequestTemplate requestTemplate) throws IOException, URISyntaxException {
|
||||
final List<HttpUriRequest> request = new ArrayList<>(1);
|
||||
BDDMockito.given(this.httpClient.execute(ArgumentMatchers.<HttpUriRequest>any()))
|
||||
.will(new Answer<HttpResponse>() {
|
||||
@Override
|
||||
public HttpResponse answer(InvocationOnMock invocationOnMock)
|
||||
throws Throwable {
|
||||
public HttpResponse answer(InvocationOnMock invocationOnMock) throws Throwable {
|
||||
request.add((HttpUriRequest) invocationOnMock.getArguments()[0]);
|
||||
return new BasicHttpResponse(new BasicStatusLine(
|
||||
new ProtocolVersion("http", 1, 1), 200, null));
|
||||
return new BasicHttpResponse(new BasicStatusLine(new ProtocolVersion("http", 1, 1), 200, null));
|
||||
}
|
||||
});
|
||||
new ApacheHttpClient(this.httpClient).execute(
|
||||
requestTemplate.resolve(new HashMap<>()).request(),
|
||||
new ApacheHttpClient(this.httpClient).execute(requestTemplate.resolve(new HashMap<>()).request(),
|
||||
new feign.Request.Options());
|
||||
HttpUriRequest httpUriRequest = request.get(0);
|
||||
return ((HttpEntityEnclosingRequestBase) httpUriRequest).getEntity();
|
||||
|
||||
@@ -27,10 +27,8 @@ public final class ProtobufTest {
|
||||
private static com.google.protobuf.Descriptors.FileDescriptor descriptor;
|
||||
|
||||
static {
|
||||
String[] descriptorData = {
|
||||
"\n\023protobuf_test.proto\"\"\n\007Request\022\n\n\002id\030\001"
|
||||
+ " \001(\005\022\013\n\003msg\030\002 \001(\tB\024\n\020feign.httpclientP\001b"
|
||||
+ "\006proto3" };
|
||||
String[] descriptorData = { "\n\023protobuf_test.proto\"\"\n\007Request\022\n\n\002id\030\001"
|
||||
+ " \001(\005\022\013\n\003msg\030\002 \001(\tB\024\n\020feign.httpclientP\001b" + "\006proto3" };
|
||||
com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() {
|
||||
public com.google.protobuf.ExtensionRegistry assignDescriptors(
|
||||
com.google.protobuf.Descriptors.FileDescriptor root) {
|
||||
@@ -38,9 +36,8 @@ public final class ProtobufTest {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom(
|
||||
descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] {},
|
||||
assigner);
|
||||
com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom(descriptorData,
|
||||
new com.google.protobuf.Descriptors.FileDescriptor[] {}, assigner);
|
||||
internal_static_Request_descriptor = getDescriptor().getMessageTypes().get(0);
|
||||
internal_static_Request_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
|
||||
internal_static_Request_descriptor, new String[] { "Id", "Msg", });
|
||||
@@ -49,12 +46,10 @@ public final class ProtobufTest {
|
||||
private ProtobufTest() {
|
||||
}
|
||||
|
||||
public static void registerAllExtensions(
|
||||
com.google.protobuf.ExtensionRegistryLite registry) {
|
||||
public static void registerAllExtensions(com.google.protobuf.ExtensionRegistryLite registry) {
|
||||
}
|
||||
|
||||
public static void registerAllExtensions(
|
||||
com.google.protobuf.ExtensionRegistry registry) {
|
||||
public static void registerAllExtensions(com.google.protobuf.ExtensionRegistry registry) {
|
||||
registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry);
|
||||
}
|
||||
|
||||
|
||||
@@ -68,8 +68,7 @@ public final class Request extends com.google.protobuf.GeneratedMessageV3 implem
|
||||
throws com.google.protobuf.InvalidProtocolBufferException {
|
||||
this();
|
||||
int mutable_bitField0_ = 0;
|
||||
com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet
|
||||
.newBuilder();
|
||||
com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder();
|
||||
try {
|
||||
boolean done = false;
|
||||
while (!done) {
|
||||
@@ -79,8 +78,7 @@ public final class Request extends com.google.protobuf.GeneratedMessageV3 implem
|
||||
done = true;
|
||||
break;
|
||||
default:
|
||||
if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry,
|
||||
tag)) {
|
||||
if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry, tag)) {
|
||||
done = true;
|
||||
}
|
||||
break;
|
||||
@@ -98,8 +96,7 @@ public final class Request extends com.google.protobuf.GeneratedMessageV3 implem
|
||||
throw e.setUnfinishedMessage(this);
|
||||
}
|
||||
catch (java.io.IOException e) {
|
||||
throw new com.google.protobuf.InvalidProtocolBufferException(e)
|
||||
.setUnfinishedMessage(this);
|
||||
throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this);
|
||||
}
|
||||
finally {
|
||||
this.unknownFields = unknownFields.build();
|
||||
@@ -133,52 +130,40 @@ public final class Request extends com.google.protobuf.GeneratedMessageV3 implem
|
||||
return PARSER.parseFrom(data, extensionRegistry);
|
||||
}
|
||||
|
||||
public static Request parseFrom(byte[] data)
|
||||
throws com.google.protobuf.InvalidProtocolBufferException {
|
||||
public static Request parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
|
||||
return PARSER.parseFrom(data);
|
||||
}
|
||||
|
||||
public static Request parseFrom(byte[] data,
|
||||
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
|
||||
public static Request parseFrom(byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
|
||||
throws com.google.protobuf.InvalidProtocolBufferException {
|
||||
return PARSER.parseFrom(data, extensionRegistry);
|
||||
}
|
||||
|
||||
public static Request parseFrom(java.io.InputStream input)
|
||||
throws java.io.IOException {
|
||||
public static Request parseFrom(java.io.InputStream input) throws java.io.IOException {
|
||||
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
|
||||
}
|
||||
|
||||
public static Request parseFrom(java.io.InputStream input,
|
||||
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
|
||||
throws java.io.IOException {
|
||||
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input,
|
||||
extensionRegistry);
|
||||
com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException {
|
||||
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, extensionRegistry);
|
||||
}
|
||||
|
||||
public static Request parseDelimitedFrom(java.io.InputStream input)
|
||||
throws java.io.IOException {
|
||||
return com.google.protobuf.GeneratedMessageV3
|
||||
.parseDelimitedWithIOException(PARSER, input);
|
||||
public static Request parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException {
|
||||
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
|
||||
}
|
||||
|
||||
public static Request parseDelimitedFrom(java.io.InputStream input,
|
||||
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
|
||||
throws java.io.IOException {
|
||||
return com.google.protobuf.GeneratedMessageV3
|
||||
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
|
||||
com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException {
|
||||
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
|
||||
}
|
||||
|
||||
public static Request parseFrom(com.google.protobuf.CodedInputStream input)
|
||||
throws java.io.IOException {
|
||||
public static Request parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException {
|
||||
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
|
||||
}
|
||||
|
||||
public static Request parseFrom(com.google.protobuf.CodedInputStream input,
|
||||
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
|
||||
throws java.io.IOException {
|
||||
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input,
|
||||
extensionRegistry);
|
||||
com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException {
|
||||
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, extensionRegistry);
|
||||
}
|
||||
|
||||
public static Builder newBuilder() {
|
||||
@@ -236,8 +221,7 @@ public final class Request extends com.google.protobuf.GeneratedMessageV3 implem
|
||||
public com.google.protobuf.ByteString getMsgBytes() {
|
||||
Object ref = this.msg_;
|
||||
if (ref instanceof String) {
|
||||
com.google.protobuf.ByteString b = com.google.protobuf.ByteString
|
||||
.copyFromUtf8((String) ref);
|
||||
com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((String) ref);
|
||||
this.msg_ = b;
|
||||
return b;
|
||||
}
|
||||
@@ -258,8 +242,7 @@ public final class Request extends com.google.protobuf.GeneratedMessageV3 implem
|
||||
return true;
|
||||
}
|
||||
|
||||
public void writeTo(com.google.protobuf.CodedOutputStream output)
|
||||
throws java.io.IOException {
|
||||
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
|
||||
if (this.id_ != 0) {
|
||||
output.writeInt32(1, this.id_);
|
||||
}
|
||||
@@ -280,8 +263,7 @@ public final class Request extends com.google.protobuf.GeneratedMessageV3 implem
|
||||
size += com.google.protobuf.CodedOutputStream.computeInt32Size(1, this.id_);
|
||||
}
|
||||
if (!getMsgBytes().isEmpty()) {
|
||||
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2,
|
||||
this.msg_);
|
||||
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, this.msg_);
|
||||
}
|
||||
size += this.unknownFields.getSerializedSize();
|
||||
this.memoizedSize = size;
|
||||
@@ -347,8 +329,7 @@ public final class Request extends com.google.protobuf.GeneratedMessageV3 implem
|
||||
/**
|
||||
* Protobuf type {@code Request}
|
||||
*/
|
||||
public static final class Builder
|
||||
extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
|
||||
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
|
||||
// @@protoc_insertion_point(builder_implements:Request)
|
||||
org.springframework.cloud.openfeign.encoding.proto.RequestOrBuilder {
|
||||
|
||||
@@ -373,8 +354,7 @@ public final class Request extends com.google.protobuf.GeneratedMessageV3 implem
|
||||
|
||||
protected FieldAccessorTable internalGetFieldAccessorTable() {
|
||||
return org.springframework.cloud.openfeign.encoding.proto.ProtobufTest.internal_static_Request_fieldAccessorTable
|
||||
.ensureFieldAccessorsInitialized(Request.class,
|
||||
Request.Builder.class);
|
||||
.ensureFieldAccessorsInitialized(Request.class, Request.Builder.class);
|
||||
}
|
||||
|
||||
private void maybeForceBuilderInitialization() {
|
||||
@@ -418,8 +398,7 @@ public final class Request extends com.google.protobuf.GeneratedMessageV3 implem
|
||||
return (Builder) super.clone();
|
||||
}
|
||||
|
||||
public Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field,
|
||||
Object value) {
|
||||
public Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field, Object value) {
|
||||
return (Builder) super.setField(field, value);
|
||||
}
|
||||
|
||||
@@ -431,14 +410,12 @@ public final class Request extends com.google.protobuf.GeneratedMessageV3 implem
|
||||
return (Builder) super.clearOneof(oneof);
|
||||
}
|
||||
|
||||
public Builder setRepeatedField(
|
||||
com.google.protobuf.Descriptors.FieldDescriptor field, int index,
|
||||
public Builder setRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, int index,
|
||||
Object value) {
|
||||
return (Builder) super.setRepeatedField(field, index, value);
|
||||
}
|
||||
|
||||
public Builder addRepeatedField(
|
||||
com.google.protobuf.Descriptors.FieldDescriptor field, Object value) {
|
||||
public Builder addRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, Object value) {
|
||||
return (Builder) super.addRepeatedField(field, value);
|
||||
}
|
||||
|
||||
@@ -473,8 +450,7 @@ public final class Request extends com.google.protobuf.GeneratedMessageV3 implem
|
||||
}
|
||||
|
||||
public Builder mergeFrom(com.google.protobuf.CodedInputStream input,
|
||||
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
|
||||
throws java.io.IOException {
|
||||
com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException {
|
||||
Request parsedMessage = null;
|
||||
try {
|
||||
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
|
||||
@@ -553,8 +529,7 @@ public final class Request extends com.google.protobuf.GeneratedMessageV3 implem
|
||||
public com.google.protobuf.ByteString getMsgBytes() {
|
||||
Object ref = this.msg_;
|
||||
if (ref instanceof String) {
|
||||
com.google.protobuf.ByteString b = com.google.protobuf.ByteString
|
||||
.copyFromUtf8((String) ref);
|
||||
com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((String) ref);
|
||||
this.msg_ = b;
|
||||
return b;
|
||||
}
|
||||
@@ -587,13 +562,11 @@ public final class Request extends com.google.protobuf.GeneratedMessageV3 implem
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder setUnknownFields(
|
||||
final com.google.protobuf.UnknownFieldSet unknownFields) {
|
||||
public Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
|
||||
return super.setUnknownFieldsProto3(unknownFields);
|
||||
}
|
||||
|
||||
public Builder mergeUnknownFields(
|
||||
final com.google.protobuf.UnknownFieldSet unknownFields) {
|
||||
public Builder mergeUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
|
||||
return super.mergeUnknownFields(unknownFields);
|
||||
}
|
||||
|
||||
|
||||
@@ -42,34 +42,29 @@ public class FeignHalAutoConfigurationContextTests {
|
||||
public void setUp() {
|
||||
contextRunner = new WebApplicationContextRunner()
|
||||
.withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class,
|
||||
HttpMessageConvertersAutoConfiguration.class,
|
||||
HypermediaAutoConfiguration.class,
|
||||
RepositoryRestMvcAutoConfiguration.class,
|
||||
FeignHalAutoConfiguration.class))
|
||||
HttpMessageConvertersAutoConfiguration.class, HypermediaAutoConfiguration.class,
|
||||
RepositoryRestMvcAutoConfiguration.class, FeignHalAutoConfiguration.class))
|
||||
.withPropertyValues("debug=true");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHalJacksonHttpMessageConverterIsNotLoaded() {
|
||||
FilteredClassLoader filteredClassLoader = new FilteredClassLoader(
|
||||
RepositoryRestMvcConfiguration.class, RepresentationModel.class);
|
||||
FilteredClassLoader filteredClassLoader = new FilteredClassLoader(RepositoryRestMvcConfiguration.class,
|
||||
RepresentationModel.class);
|
||||
contextRunner.withClassLoader(filteredClassLoader)
|
||||
.run(context -> assertThat(context)
|
||||
.doesNotHaveBean("halJacksonHttpMessageConverter"));
|
||||
.run(context -> assertThat(context).doesNotHaveBean("halJacksonHttpMessageConverter"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHalJacksonHttpMessageConverterIsLoaded() {
|
||||
FilteredClassLoader filteredClassLoader = new FilteredClassLoader(
|
||||
RepositoryRestMvcConfiguration.class);
|
||||
contextRunner.withClassLoader(filteredClassLoader).run(
|
||||
context -> assertThat(context).hasBean("halJacksonHttpMessageConverter"));
|
||||
FilteredClassLoader filteredClassLoader = new FilteredClassLoader(RepositoryRestMvcConfiguration.class);
|
||||
contextRunner.withClassLoader(filteredClassLoader)
|
||||
.run(context -> assertThat(context).hasBean("halJacksonHttpMessageConverter"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHalJacksonHttpMessageConverterIsNotLoadedUseRestDataMessageConverterInstead() {
|
||||
contextRunner.run(
|
||||
context -> assertThat(context).hasBean("halJacksonHttpMessageConverter"));
|
||||
contextRunner.run(context -> assertThat(context).hasBean("halJacksonHttpMessageConverter"));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -68,22 +68,20 @@ public class FeignHalAutoConfigurationTests {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
when(objectMapper.getIfAvailable(any())).thenReturn(mapper);
|
||||
|
||||
when(halConfiguration.getIfAvailable(any()))
|
||||
.thenReturn(mock(HalConfiguration.class));
|
||||
when(halConfiguration.getIfAvailable(any())).thenReturn(mock(HalConfiguration.class));
|
||||
when(relProvider.getIfAvailable()).thenReturn(mock(LinkRelationProvider.class));
|
||||
when(curieProvider.getIfAvailable(any())).thenReturn(mock(CurieProvider.class));
|
||||
when(messageResolver.getIfAvailable()).thenReturn(mock(MessageResolver.class));
|
||||
|
||||
TypeConstrainedMappingJackson2HttpMessageConverter converter = feignHalAutoConfiguration
|
||||
.halJacksonHttpMessageConverter(objectMapper, halConfiguration,
|
||||
messageResolver, curieProvider, relProvider);
|
||||
.halJacksonHttpMessageConverter(objectMapper, halConfiguration, messageResolver, curieProvider,
|
||||
relProvider);
|
||||
|
||||
assertThat(converter).isNotNull();
|
||||
assertThat(converter.getObjectMapper()).isNotNull();
|
||||
assertThat(converter.getSupportedMediaTypes()).isEqualTo(Arrays.asList(HAL_JSON));
|
||||
|
||||
assertThat(Jackson2HalModule.isAlreadyRegisteredIn(converter.getObjectMapper()))
|
||||
.isTrue();
|
||||
assertThat(Jackson2HalModule.isAlreadyRegisteredIn(converter.getObjectMapper())).isTrue();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -41,8 +41,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
|
||||
*
|
||||
* @author Hector Espert
|
||||
*/
|
||||
@SpringBootTest(classes = FeignHalApplication.class, webEnvironment = RANDOM_PORT,
|
||||
value = "debug=true")
|
||||
@SpringBootTest(classes = FeignHalApplication.class, webEnvironment = RANDOM_PORT, value = "debug=true")
|
||||
@RunWith(SpringRunner.class)
|
||||
@DirtiesContext
|
||||
public class FeignHalTests {
|
||||
@@ -74,8 +73,7 @@ public class FeignHalTests {
|
||||
assertThat(collectionModel.hasLinks()).isTrue();
|
||||
assertThat(collectionModel.hasLink("self")).isTrue();
|
||||
|
||||
assertThat(collectionModel.getLink("self")).map(Link::getHref)
|
||||
.contains("/collection");
|
||||
assertThat(collectionModel.getLink("self")).map(Link::getHref).contains("/collection");
|
||||
|
||||
Collection<MarsRover> collection = collectionModel.getContent();
|
||||
assertThat(collection).isNotEmpty();
|
||||
|
||||
@@ -33,8 +33,7 @@ import org.springframework.core.env.Environment;
|
||||
* @author Hector Espert
|
||||
*/
|
||||
@EnableFeignClients(clients = FeignHalClient.class)
|
||||
@SpringBootApplication(
|
||||
scanBasePackages = "org.springframework.cloud.openfeign.hateoas.app",
|
||||
@SpringBootApplication(scanBasePackages = "org.springframework.cloud.openfeign.hateoas.app",
|
||||
exclude = RepositoryRestMvcAutoConfiguration.class)
|
||||
@LoadBalancerClient(name = "local", configuration = LocalHalClientConfiguration.class)
|
||||
@Import(NoSecurityConfiguration.class)
|
||||
@@ -50,8 +49,7 @@ class LocalHalClientConfiguration {
|
||||
private int port = 0;
|
||||
|
||||
@Bean
|
||||
public ServiceInstanceListSupplier staticServiceInstanceListSupplier(
|
||||
Environment env) {
|
||||
public ServiceInstanceListSupplier staticServiceInstanceListSupplier(Environment env) {
|
||||
return ServiceInstanceListSupplier.fixed(env).instance(port, "local").build();
|
||||
}
|
||||
|
||||
|
||||
@@ -45,8 +45,7 @@ public class FeignClientValidationTests {
|
||||
public void testServiceIdAndValue() {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
|
||||
LoadBalancerAutoConfiguration.class, NameAndServiceIdConfiguration.class);
|
||||
assertThat(context.getBean(NameAndServiceIdConfiguration.Client.class))
|
||||
.isNotNull();
|
||||
assertThat(context.getBean(NameAndServiceIdConfiguration.Client.class)).isNotNull();
|
||||
context.close();
|
||||
}
|
||||
|
||||
@@ -54,15 +53,10 @@ public class FeignClientValidationTests {
|
||||
public void testDuplicatedClientNames() {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
|
||||
context.setAllowBeanDefinitionOverriding(false);
|
||||
context.register(LoadBalancerAutoConfiguration.class,
|
||||
DuplicatedFeignClientNamesConfiguration.class);
|
||||
context.register(LoadBalancerAutoConfiguration.class, DuplicatedFeignClientNamesConfiguration.class);
|
||||
context.refresh();
|
||||
assertThat(
|
||||
context.getBean(DuplicatedFeignClientNamesConfiguration.FooClient.class))
|
||||
.isNotNull();
|
||||
assertThat(
|
||||
context.getBean(DuplicatedFeignClientNamesConfiguration.BarClient.class))
|
||||
.isNotNull();
|
||||
assertThat(context.getBean(DuplicatedFeignClientNamesConfiguration.FooClient.class)).isNotNull();
|
||||
assertThat(context.getBean(DuplicatedFeignClientNamesConfiguration.BarClient.class)).isNotNull();
|
||||
context.close();
|
||||
}
|
||||
|
||||
@@ -89,9 +83,8 @@ public class FeignClientValidationTests {
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@Import({ FeignAutoConfiguration.class, HttpClientConfiguration.class })
|
||||
@EnableFeignClients(
|
||||
clients = { DuplicatedFeignClientNamesConfiguration.FooClient.class,
|
||||
DuplicatedFeignClientNamesConfiguration.BarClient.class })
|
||||
@EnableFeignClients(clients = { DuplicatedFeignClientNamesConfiguration.FooClient.class,
|
||||
DuplicatedFeignClientNamesConfiguration.BarClient.class })
|
||||
protected static class DuplicatedFeignClientNamesConfiguration {
|
||||
|
||||
@FeignClient(contextId = "foo", name = "bar")
|
||||
|
||||
@@ -62,8 +62,7 @@ class FeignBlockingLoadBalancerClientTests {
|
||||
|
||||
private Client delegate = mock(Client.class);
|
||||
|
||||
private BlockingLoadBalancerClient loadBalancerClient = mock(
|
||||
BlockingLoadBalancerClient.class);
|
||||
private BlockingLoadBalancerClient loadBalancerClient = mock(BlockingLoadBalancerClient.class);
|
||||
|
||||
private FeignBlockingLoadBalancerClient feignBlockingLoadBalancerClient = new FeignBlockingLoadBalancerClient(
|
||||
delegate, loadBalancerClient);
|
||||
@@ -82,22 +81,19 @@ class FeignBlockingLoadBalancerClientTests {
|
||||
Request request = testRequest("");
|
||||
|
||||
assertThatIllegalStateException()
|
||||
.isThrownBy(() -> feignBlockingLoadBalancerClient.execute(request,
|
||||
new Request.Options()))
|
||||
.withMessage(
|
||||
"Request URI does not contain a valid hostname: http:///path");
|
||||
.isThrownBy(() -> feignBlockingLoadBalancerClient.execute(request, new Request.Options()))
|
||||
.withMessage("Request URI does not contain a valid hostname: http:///path");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRespondWithServiceUnavailableIfInstanceNotFound() throws IOException {
|
||||
Request request = testRequest();
|
||||
|
||||
Response response = feignBlockingLoadBalancerClient.execute(request,
|
||||
new Request.Options());
|
||||
Response response = feignBlockingLoadBalancerClient.execute(request, new Request.Options());
|
||||
|
||||
assertThat(response.status()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE.value());
|
||||
assertThat(response.body().toString()).isEqualTo(
|
||||
"Load balancer does not contain an instance for the service test");
|
||||
assertThat(response.body().toString())
|
||||
.isEqualTo("Load balancer does not contain an instance for the service test");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -105,11 +101,10 @@ class FeignBlockingLoadBalancerClientTests {
|
||||
Request request = testRequest();
|
||||
Request.Options options = new Request.Options();
|
||||
String url = "http://127.0.0.1/path";
|
||||
ServiceInstance serviceInstance = new DefaultServiceInstance("test-1", "test",
|
||||
"test-host", 8888, false);
|
||||
ServiceInstance serviceInstance = new DefaultServiceInstance("test-1", "test", "test-host", 8888, false);
|
||||
when(loadBalancerClient.choose("test")).thenReturn(serviceInstance);
|
||||
when(loadBalancerClient.reconstructURI(serviceInstance,
|
||||
URI.create("http://test/path"))).thenReturn(URI.create(url));
|
||||
when(loadBalancerClient.reconstructURI(serviceInstance, URI.create("http://test/path")))
|
||||
.thenReturn(URI.create(url));
|
||||
|
||||
feignBlockingLoadBalancerClient.execute(request, options);
|
||||
|
||||
@@ -129,14 +124,13 @@ class FeignBlockingLoadBalancerClientTests {
|
||||
}
|
||||
|
||||
private Request testRequest(String host) {
|
||||
return Request.create(Request.HttpMethod.GET, "http://" + host + "/path",
|
||||
testHeaders(), "hello".getBytes(), StandardCharsets.UTF_8, null);
|
||||
return Request.create(Request.HttpMethod.GET, "http://" + host + "/path", testHeaders(), "hello".getBytes(),
|
||||
StandardCharsets.UTF_8, null);
|
||||
}
|
||||
|
||||
private Map<String, Collection<String>> testHeaders() {
|
||||
Map<String, Collection<String>> feignHeaders = new HashMap<>();
|
||||
feignHeaders.put(HttpHeaders.CONTENT_TYPE,
|
||||
Collections.singletonList(MediaType.APPLICATION_JSON_VALUE));
|
||||
feignHeaders.put(HttpHeaders.CONTENT_TYPE, Collections.singletonList(MediaType.APPLICATION_JSON_VALUE));
|
||||
return feignHeaders;
|
||||
|
||||
}
|
||||
|
||||
@@ -40,46 +40,39 @@ public class FeignLoadBalancerAutoConfigurationTests {
|
||||
|
||||
@Test
|
||||
public void shouldInstantiateDefaultFeignBlockingLoadBalancerClientWhenHttpClientDisabled() {
|
||||
ConfigurableApplicationContext context = initContext(
|
||||
"feign.httpclient.enabled=false");
|
||||
ConfigurableApplicationContext context = initContext("feign.httpclient.enabled=false");
|
||||
assertThatOneBeanPresent(context, BlockingLoadBalancerClient.class);
|
||||
assertLoadBalanced(context, Client.Default.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldInstantiateHttpFeignClientWhenEnabled() {
|
||||
ConfigurableApplicationContext context = initContext(
|
||||
"spring.cloud.loadbalancer.ribbon.enabled=false");
|
||||
ConfigurableApplicationContext context = initContext("spring.cloud.loadbalancer.ribbon.enabled=false");
|
||||
assertThatOneBeanPresent(context, BlockingLoadBalancerClient.class);
|
||||
assertLoadBalanced(context, ApacheHttpClient.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldInstantiateOkHttpFeignClientWhenEnabled() {
|
||||
ConfigurableApplicationContext context = initContext(
|
||||
"feign.httpclient.enabled=false", "feign.okhttp.enabled=true");
|
||||
ConfigurableApplicationContext context = initContext("feign.httpclient.enabled=false",
|
||||
"feign.okhttp.enabled=true");
|
||||
assertThatOneBeanPresent(context, BlockingLoadBalancerClient.class);
|
||||
assertLoadBalanced(context, OkHttpClient.class);
|
||||
}
|
||||
|
||||
private ConfigurableApplicationContext initContext(String... properties) {
|
||||
return new SpringApplicationBuilder().web(WebApplicationType.NONE)
|
||||
.properties(properties)
|
||||
.sources(HttpClientConfiguration.class,
|
||||
LoadBalancerAutoConfiguration.class,
|
||||
BlockingLoadBalancerClientAutoConfiguration.class,
|
||||
FeignLoadBalancerAutoConfiguration.class)
|
||||
return new SpringApplicationBuilder().web(WebApplicationType.NONE).properties(properties)
|
||||
.sources(HttpClientConfiguration.class, LoadBalancerAutoConfiguration.class,
|
||||
BlockingLoadBalancerClientAutoConfiguration.class, FeignLoadBalancerAutoConfiguration.class)
|
||||
.run();
|
||||
}
|
||||
|
||||
private void assertThatOneBeanPresent(ConfigurableApplicationContext context,
|
||||
Class<?> beanClass) {
|
||||
private void assertThatOneBeanPresent(ConfigurableApplicationContext context, Class<?> beanClass) {
|
||||
Map<String, ?> beans = context.getBeansOfType(beanClass);
|
||||
assertThat(beans).as("Missing bean of type %s", beanClass).hasSize(1);
|
||||
}
|
||||
|
||||
private void assertLoadBalanced(ConfigurableApplicationContext context,
|
||||
Class delegateClass) {
|
||||
private void assertLoadBalanced(ConfigurableApplicationContext context, Class delegateClass) {
|
||||
Map<String, FeignBlockingLoadBalancerClient> beans = context
|
||||
.getBeansOfType(FeignBlockingLoadBalancerClient.class);
|
||||
assertThat(beans).as("Missing bean of type %s", delegateClass).hasSize(1);
|
||||
|
||||
@@ -52,26 +52,22 @@ public class FeignHttpClientPropertiesTests {
|
||||
setupContext();
|
||||
assertThat(getProperties().getConnectionTimeout())
|
||||
.isEqualTo(FeignHttpClientProperties.DEFAULT_CONNECTION_TIMEOUT);
|
||||
assertThat(getProperties().getMaxConnections())
|
||||
.isEqualTo(FeignHttpClientProperties.DEFAULT_MAX_CONNECTIONS);
|
||||
assertThat(getProperties().getMaxConnections()).isEqualTo(FeignHttpClientProperties.DEFAULT_MAX_CONNECTIONS);
|
||||
assertThat(getProperties().getMaxConnectionsPerRoute())
|
||||
.isEqualTo(FeignHttpClientProperties.DEFAULT_MAX_CONNECTIONS_PER_ROUTE);
|
||||
assertThat(getProperties().getTimeToLive())
|
||||
.isEqualTo(FeignHttpClientProperties.DEFAULT_TIME_TO_LIVE);
|
||||
assertThat(getProperties().getTimeToLive()).isEqualTo(FeignHttpClientProperties.DEFAULT_TIME_TO_LIVE);
|
||||
assertThat(getProperties().isDisableSslValidation())
|
||||
.isEqualTo(FeignHttpClientProperties.DEFAULT_DISABLE_SSL_VALIDATION);
|
||||
assertThat(getProperties().isFollowRedirects())
|
||||
.isEqualTo(FeignHttpClientProperties.DEFAULT_FOLLOW_REDIRECTS);
|
||||
assertThat(getProperties().isFollowRedirects()).isEqualTo(FeignHttpClientProperties.DEFAULT_FOLLOW_REDIRECTS);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCustomization() {
|
||||
TestPropertyValues.of("feign.httpclient.maxConnections=2",
|
||||
"feign.httpclient.connectionTimeout=2",
|
||||
"feign.httpclient.maxConnectionsPerRoute=2",
|
||||
"feign.httpclient.timeToLive=2",
|
||||
"feign.httpclient.disableSslValidation=true",
|
||||
"feign.httpclient.followRedirects=false").applyTo(this.context);
|
||||
TestPropertyValues
|
||||
.of("feign.httpclient.maxConnections=2", "feign.httpclient.connectionTimeout=2",
|
||||
"feign.httpclient.maxConnectionsPerRoute=2", "feign.httpclient.timeToLive=2",
|
||||
"feign.httpclient.disableSslValidation=true", "feign.httpclient.followRedirects=false")
|
||||
.applyTo(this.context);
|
||||
setupContext();
|
||||
assertThat(getProperties().getMaxConnections()).isEqualTo(2);
|
||||
assertThat(getProperties().getConnectionTimeout()).isEqualTo(2);
|
||||
@@ -82,8 +78,7 @@ public class FeignHttpClientPropertiesTests {
|
||||
}
|
||||
|
||||
private void setupContext() {
|
||||
this.context.register(PropertyPlaceholderAutoConfiguration.class,
|
||||
TestConfiguration.class);
|
||||
this.context.register(PropertyPlaceholderAutoConfiguration.class, TestConfiguration.class);
|
||||
this.context.refresh();
|
||||
}
|
||||
|
||||
|
||||
@@ -39,9 +39,8 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
|
||||
* @author Charlie Mordant.
|
||||
*/
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@SpringBootTest(classes = SpringEncoderTests.Application.class,
|
||||
webEnvironment = RANDOM_PORT, value = {
|
||||
"spring.application.name=springencodertest", "spring.jmx.enabled=false" })
|
||||
@SpringBootTest(classes = SpringEncoderTests.Application.class, webEnvironment = RANDOM_PORT,
|
||||
value = { "spring.application.name=springencodertest", "spring.jmx.enabled=false" })
|
||||
@DirtiesContext
|
||||
public class PageableEncoderTests {
|
||||
|
||||
|
||||
@@ -41,8 +41,7 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
/**
|
||||
* @author Olga Maciaszek-Sharma
|
||||
*/
|
||||
@SpringBootTest(classes = PageableSupportTest.Config.class,
|
||||
webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
|
||||
@SpringBootTest(classes = PageableSupportTest.Config.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
|
||||
public class PageableSupportTest {
|
||||
|
||||
@Autowired
|
||||
@@ -50,8 +49,7 @@ public class PageableSupportTest {
|
||||
|
||||
@BeforeAll
|
||||
public static void beforeClass() {
|
||||
System.setProperty("server.port",
|
||||
String.valueOf(SocketUtils.findAvailableTcpPort()));
|
||||
System.setProperty("server.port", String.valueOf(SocketUtils.findAvailableTcpPort()));
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
@@ -61,8 +59,7 @@ public class PageableSupportTest {
|
||||
|
||||
@Test
|
||||
void shouldProperlyFormatPageable() {
|
||||
String direction = feignClient.performRequest(
|
||||
PageRequest.of(1, 10, Sort.by(Sort.Order.desc("property"))));
|
||||
String direction = feignClient.performRequest(PageRequest.of(1, 10, Sort.by(Sort.Order.desc("property"))));
|
||||
|
||||
assertThat(direction).isEqualTo("DESC");
|
||||
}
|
||||
|
||||
@@ -67,8 +67,7 @@ class SortJacksonModuleTests {
|
||||
assertThat(result.getPageable().getPageSize(), is(2));
|
||||
assertThat(result.getPageable().getSort(), notNullValue());
|
||||
result.getPageable().getSort();
|
||||
Optional<Sort.Order> optionalOrder = result.getPageable().getSort().get()
|
||||
.findFirst();
|
||||
Optional<Sort.Order> optionalOrder = result.getPageable().getSort().get().findFirst();
|
||||
if (optionalOrder.isPresent()) {
|
||||
Sort.Order order = optionalOrder.get();
|
||||
assertThat(order, hasProperty("property", is("field")));
|
||||
|
||||
@@ -66,9 +66,8 @@ import static org.springframework.http.MediaType.MULTIPART_FORM_DATA_VALUE;
|
||||
* @author Ahmad Mozafarnia
|
||||
*/
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@SpringBootTest(classes = SpringEncoderTests.Application.class,
|
||||
webEnvironment = WebEnvironment.RANDOM_PORT, value = {
|
||||
"spring.application.name=springencodertest", "spring.jmx.enabled=false" })
|
||||
@SpringBootTest(classes = SpringEncoderTests.Application.class, webEnvironment = WebEnvironment.RANDOM_PORT,
|
||||
value = { "spring.application.name=springencodertest", "spring.jmx.enabled=false" })
|
||||
@DirtiesContext
|
||||
public class SpringEncoderTests {
|
||||
|
||||
@@ -93,16 +92,13 @@ public class SpringEncoderTests {
|
||||
|
||||
Collection<String> contentTypeHeader = request.headers().get("Content-Type");
|
||||
assertThat(contentTypeHeader).as("missing content type header").isNotNull();
|
||||
assertThat(contentTypeHeader.isEmpty()).as("missing content type header")
|
||||
.isFalse();
|
||||
assertThat(contentTypeHeader.isEmpty()).as("missing content type header").isFalse();
|
||||
|
||||
String header = contentTypeHeader.iterator().next();
|
||||
assertThat(header).as("content type header is wrong")
|
||||
.isEqualTo("application/mytype");
|
||||
assertThat(header).as("content type header is wrong").isEqualTo("application/mytype");
|
||||
|
||||
assertThat(request.requestCharset()).as("request charset is null").isNotNull();
|
||||
assertThat(request.requestCharset()).as("request charset is wrong")
|
||||
.isEqualTo(StandardCharsets.UTF_8);
|
||||
assertThat(request.requestCharset()).as("request charset is wrong").isEqualTo(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
// gh-225
|
||||
@@ -116,21 +112,17 @@ public class SpringEncoderTests {
|
||||
};
|
||||
|
||||
request.header(HttpEncoding.CONTENT_TYPE, "application/mygenerictype");
|
||||
encoder.encode(Collections.singletonList("hi"), stringListType.getType(),
|
||||
request);
|
||||
encoder.encode(Collections.singletonList("hi"), stringListType.getType(), request);
|
||||
|
||||
Collection<String> contentTypeHeader = request.headers().get("Content-Type");
|
||||
assertThat(contentTypeHeader).as("missing content type header").isNotNull();
|
||||
assertThat(contentTypeHeader.isEmpty()).as("missing content type header")
|
||||
.isFalse();
|
||||
assertThat(contentTypeHeader.isEmpty()).as("missing content type header").isFalse();
|
||||
|
||||
String header = contentTypeHeader.iterator().next();
|
||||
assertThat(header).as("content type header is wrong")
|
||||
.isEqualTo("application/mygenerictype");
|
||||
assertThat(header).as("content type header is wrong").isEqualTo("application/mygenerictype");
|
||||
|
||||
assertThat(request.requestCharset()).as("request charset is null").isNotNull();
|
||||
assertThat(request.requestCharset()).as("request charset is wrong")
|
||||
.isEqualTo(StandardCharsets.UTF_8);
|
||||
assertThat(request.requestCharset()).as("request charset is wrong").isEqualTo(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -142,8 +134,7 @@ public class SpringEncoderTests {
|
||||
|
||||
encoder.encode("hi".getBytes(), null, request);
|
||||
|
||||
assertThat(((List) request.headers().get(CONTENT_TYPE)).get(0))
|
||||
.as("Request Content-Type is not octet-stream")
|
||||
assertThat(((List) request.headers().get(CONTENT_TYPE)).get(0)).as("Request Content-Type is not octet-stream")
|
||||
.isEqualTo(APPLICATION_OCTET_STREAM_VALUE);
|
||||
}
|
||||
|
||||
@@ -153,8 +144,7 @@ public class SpringEncoderTests {
|
||||
assertThat(encoder).isNotNull();
|
||||
RequestTemplate request = new RequestTemplate();
|
||||
|
||||
MultipartFile multipartFile = new MockMultipartFile("test_multipart_file",
|
||||
"hi".getBytes());
|
||||
MultipartFile multipartFile = new MockMultipartFile("test_multipart_file", "hi".getBytes());
|
||||
encoder.encode(multipartFile, MultipartFile.class, request);
|
||||
}
|
||||
|
||||
@@ -167,22 +157,19 @@ public class SpringEncoderTests {
|
||||
request.header(ACCEPT, MediaType.MULTIPART_FORM_DATA_VALUE);
|
||||
request.header(CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE);
|
||||
|
||||
MultipartFile multipartFile = new MockMultipartFile("test_multipart_file",
|
||||
"hi".getBytes());
|
||||
MultipartFile multipartFile = new MockMultipartFile("test_multipart_file", "hi".getBytes());
|
||||
encoder.encode(multipartFile, MultipartFile.class, request);
|
||||
|
||||
assertThat((String) ((List) request.headers().get(CONTENT_TYPE)).get(0))
|
||||
.as("Request Content-Type is not multipart/form-data")
|
||||
.contains("multipart/form-data; charset=UTF-8; boundary=");
|
||||
assertThat(request.headers().get(CONTENT_TYPE).size())
|
||||
.as("There is more than one Content-Type request header").isEqualTo(1);
|
||||
assertThat(((List) request.headers().get(ACCEPT)).get(0))
|
||||
.as("Request Accept header is not multipart/form-data")
|
||||
assertThat(request.headers().get(CONTENT_TYPE).size()).as("There is more than one Content-Type request header")
|
||||
.isEqualTo(1);
|
||||
assertThat(((List) request.headers().get(ACCEPT)).get(0)).as("Request Accept header is not multipart/form-data")
|
||||
.isEqualTo(MULTIPART_FORM_DATA_VALUE);
|
||||
assertThat(((List) request.headers().get(CONTENT_LENGTH)).get(0))
|
||||
.as("Request Content-Length is not equal to 186").isEqualTo("186");
|
||||
assertThat(new String(request.requestBody().asBytes()))
|
||||
.as("Body content cannot be decoded").contains("hi");
|
||||
assertThat(new String(request.requestBody().asBytes())).as("Body content cannot be decoded").contains("hi");
|
||||
}
|
||||
|
||||
protected interface TestClient {
|
||||
@@ -218,8 +205,7 @@ public class SpringEncoderTests {
|
||||
return new MyGenericHttpMessageConverter();
|
||||
}
|
||||
|
||||
private static class MyHttpMessageConverter
|
||||
extends AbstractGenericHttpMessageConverter<Object> {
|
||||
private static class MyHttpMessageConverter extends AbstractGenericHttpMessageConverter<Object> {
|
||||
|
||||
MyHttpMessageConverter() {
|
||||
super(new MediaType("application", "mytype"));
|
||||
@@ -241,8 +227,7 @@ public class SpringEncoderTests {
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void writeInternal(Object o, Type type,
|
||||
HttpOutputMessage outputMessage)
|
||||
protected void writeInternal(Object o, Type type, HttpOutputMessage outputMessage)
|
||||
throws HttpMessageNotWritableException {
|
||||
|
||||
}
|
||||
@@ -254,16 +239,14 @@ public class SpringEncoderTests {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object read(Type type, Class<?> contextClass,
|
||||
HttpInputMessage inputMessage)
|
||||
public Object read(Type type, Class<?> contextClass, HttpInputMessage inputMessage)
|
||||
throws HttpMessageNotReadableException {
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private static class MyGenericHttpMessageConverter
|
||||
extends AbstractGenericHttpMessageConverter<Object> {
|
||||
private static class MyGenericHttpMessageConverter extends AbstractGenericHttpMessageConverter<Object> {
|
||||
|
||||
MyGenericHttpMessageConverter() {
|
||||
super(new MediaType("application", "mygenerictype"));
|
||||
@@ -273,8 +256,7 @@ public class SpringEncoderTests {
|
||||
if (type instanceof ParameterizedType) {
|
||||
ParameterizedType parameterizedType = (ParameterizedType) type;
|
||||
return parameterizedType.getRawType() == List.class
|
||||
&& parameterizedType
|
||||
.getActualTypeArguments()[0] == String.class;
|
||||
&& parameterizedType.getActualTypeArguments()[0] == String.class;
|
||||
}
|
||||
else {
|
||||
return false;
|
||||
@@ -292,21 +274,18 @@ public class SpringEncoderTests {
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canRead(Type type, Class<?> contextClass,
|
||||
MediaType mediaType) {
|
||||
public boolean canRead(Type type, Class<?> contextClass, MediaType mediaType) {
|
||||
return canRead(mediaType) && isStringList(type);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void writeInternal(Object o, Type type,
|
||||
HttpOutputMessage outputMessage)
|
||||
protected void writeInternal(Object o, Type type, HttpOutputMessage outputMessage)
|
||||
throws HttpMessageNotWritableException {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object read(Type type, Class<?> contextClass,
|
||||
HttpInputMessage inputMessage)
|
||||
public Object read(Type type, Class<?> contextClass, HttpInputMessage inputMessage)
|
||||
throws HttpMessageNotReadableException {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -56,8 +56,7 @@ public class SpringMvcContractIntegrationTests {
|
||||
|
||||
@BeforeAll
|
||||
public static void beforeClass() {
|
||||
System.setProperty("server.port",
|
||||
String.valueOf(SocketUtils.findAvailableTcpPort()));
|
||||
System.setProperty("server.port", String.valueOf(SocketUtils.findAvailableTcpPort()));
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
@@ -67,8 +66,7 @@ public class SpringMvcContractIntegrationTests {
|
||||
|
||||
@Test
|
||||
public void shouldNotThrowInvalidMediaTypeExceptionWhenContentTypeTemplateUsed() {
|
||||
assertThatCode(() -> client.sendMessage("test", "text/markdown"))
|
||||
.doesNotThrowAnyException();
|
||||
assertThatCode(() -> client.sendMessage("test", "text/markdown")).doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
@FeignClient(name = "test", url = "http://localhost:${server.port}/",
|
||||
@@ -76,8 +74,7 @@ public class SpringMvcContractIntegrationTests {
|
||||
interface TestClient {
|
||||
|
||||
@PostMapping("/test")
|
||||
Object sendMessage(@RequestBody String message,
|
||||
@RequestHeader(HttpHeaders.CONTENT_TYPE) String acceptHeader);
|
||||
Object sendMessage(@RequestBody String message, @RequestHeader(HttpHeaders.CONTENT_TYPE) String acceptHeader);
|
||||
|
||||
}
|
||||
|
||||
@@ -89,8 +86,7 @@ public class SpringMvcContractIntegrationTests {
|
||||
protected static class Config {
|
||||
|
||||
@PostMapping("/test")
|
||||
Object sendMessage(@RequestBody String message,
|
||||
@RequestHeader(HttpHeaders.CONTENT_TYPE) String acceptHeader) {
|
||||
Object sendMessage(@RequestBody String message, @RequestHeader(HttpHeaders.CONTENT_TYPE) String acceptHeader) {
|
||||
return message;
|
||||
}
|
||||
|
||||
@@ -107,8 +103,7 @@ public class SpringMvcContractIntegrationTests {
|
||||
|
||||
@Bean
|
||||
public Encoder encoder() {
|
||||
return (object, bodyType, request) -> request
|
||||
.body(object.toString().getBytes(), Charset.defaultCharset());
|
||||
return (object, bodyType, request) -> request.body(object.toString().getBytes(), Charset.defaultCharset());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -98,19 +98,15 @@ public class SpringMvcContractTests {
|
||||
* @throws IllegalArgumentException if method has no parameters
|
||||
*/
|
||||
private static boolean hasJava8ParameterNames(Method m) {
|
||||
org.springframework.util.Assert.isTrue(m.getParameterTypes().length > 0,
|
||||
"method has no parameters");
|
||||
org.springframework.util.Assert.isTrue(m.getParameterTypes().length > 0, "method has no parameters");
|
||||
if (EXECUTABLE_TYPE != null) {
|
||||
Method getParameters = ReflectionUtils.findMethod(EXECUTABLE_TYPE,
|
||||
"getParameters");
|
||||
Method getParameters = ReflectionUtils.findMethod(EXECUTABLE_TYPE, "getParameters");
|
||||
try {
|
||||
Object[] parameters = (Object[]) getParameters.invoke(m);
|
||||
Method isNamePresent = ReflectionUtils
|
||||
.findMethod(parameters[0].getClass(), "isNamePresent");
|
||||
Method isNamePresent = ReflectionUtils.findMethod(parameters[0].getClass(), "isNamePresent");
|
||||
return Boolean.TRUE.equals(isNamePresent.invoke(parameters[0]));
|
||||
}
|
||||
catch (IllegalAccessException | IllegalArgumentException
|
||||
| InvocationTargetException ex) {
|
||||
catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
|
||||
}
|
||||
}
|
||||
return false;
|
||||
@@ -127,10 +123,8 @@ public class SpringMvcContractTests {
|
||||
|
||||
@Test
|
||||
public void testProcessAnnotationOnMethod_Simple() throws Exception {
|
||||
Method method = TestTemplate_Simple.class.getDeclaredMethod("getTest",
|
||||
String.class);
|
||||
MethodMetadata data = contract
|
||||
.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
Method method = TestTemplate_Simple.class.getDeclaredMethod("getTest", String.class);
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
|
||||
assertThat(data.template().url()).isEqualTo("/test/{id}");
|
||||
assertThat(data.template().method()).isEqualTo("GET");
|
||||
@@ -140,10 +134,8 @@ public class SpringMvcContractTests {
|
||||
|
||||
@Test
|
||||
public void testProcessAnnotations_Simple() throws Exception {
|
||||
Method method = TestTemplate_Simple.class.getDeclaredMethod("getTest",
|
||||
String.class);
|
||||
MethodMetadata data = contract
|
||||
.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
Method method = TestTemplate_Simple.class.getDeclaredMethod("getTest", String.class);
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
|
||||
assertThat(data.template().url()).isEqualTo("/test/{id}");
|
||||
assertThat(data.template().method()).isEqualTo("GET");
|
||||
@@ -155,10 +147,8 @@ public class SpringMvcContractTests {
|
||||
|
||||
@Test
|
||||
public void testProcessAnnotations_SimpleGetMapping() throws Exception {
|
||||
Method method = TestTemplate_Simple.class.getDeclaredMethod("getMappingTest",
|
||||
String.class);
|
||||
MethodMetadata data = contract
|
||||
.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
Method method = TestTemplate_Simple.class.getDeclaredMethod("getMappingTest", String.class);
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
|
||||
assertThat(data.template().url()).isEqualTo("/test/{id}");
|
||||
assertThat(data.template().method()).isEqualTo("GET");
|
||||
@@ -169,12 +159,10 @@ public class SpringMvcContractTests {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testProcessAnnotations_Class_AnnotationsGetSpecificTest()
|
||||
throws Exception {
|
||||
Method method = TestTemplate_Class_Annotations.class
|
||||
.getDeclaredMethod("getSpecificTest", String.class, String.class);
|
||||
MethodMetadata data = contract
|
||||
.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
public void testProcessAnnotations_Class_AnnotationsGetSpecificTest() throws Exception {
|
||||
Method method = TestTemplate_Class_Annotations.class.getDeclaredMethod("getSpecificTest", String.class,
|
||||
String.class);
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
|
||||
assertThat(data.template().url()).isEqualTo("/prepend/{classId}/test/{testId}");
|
||||
assertThat(data.template().method()).isEqualTo("GET");
|
||||
@@ -185,10 +173,8 @@ public class SpringMvcContractTests {
|
||||
|
||||
@Test
|
||||
public void testProcessAnnotations_Class_AnnotationsGetAllTests() throws Exception {
|
||||
Method method = TestTemplate_Class_Annotations.class
|
||||
.getDeclaredMethod("getAllTests", String.class);
|
||||
MethodMetadata data = contract
|
||||
.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
Method method = TestTemplate_Class_Annotations.class.getDeclaredMethod("getAllTests", String.class);
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
|
||||
assertThat(data.template().url()).isEqualTo("/prepend/{classId}");
|
||||
assertThat(data.template().method()).isEqualTo("GET");
|
||||
@@ -198,29 +184,23 @@ public class SpringMvcContractTests {
|
||||
|
||||
@Test
|
||||
public void testProcessAnnotations_ExtendedInterface() throws Exception {
|
||||
Method extendedMethod = TestTemplate_Extended.class.getMethod("getAllTests",
|
||||
String.class);
|
||||
MethodMetadata extendedData = contract.parseAndValidateMetadata(
|
||||
extendedMethod.getDeclaringClass(), extendedMethod);
|
||||
Method extendedMethod = TestTemplate_Extended.class.getMethod("getAllTests", String.class);
|
||||
MethodMetadata extendedData = contract.parseAndValidateMetadata(extendedMethod.getDeclaringClass(),
|
||||
extendedMethod);
|
||||
|
||||
Method method = TestTemplate_Class_Annotations.class
|
||||
.getDeclaredMethod("getAllTests", String.class);
|
||||
MethodMetadata data = contract
|
||||
.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
Method method = TestTemplate_Class_Annotations.class.getDeclaredMethod("getAllTests", String.class);
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
|
||||
assertThat(data.template().url()).isEqualTo(extendedData.template().url());
|
||||
assertThat(data.template().method()).isEqualTo(extendedData.template().method());
|
||||
|
||||
assertThat(data.indexToName().get(0).iterator().next())
|
||||
.isEqualTo(data.indexToName().get(0).iterator().next());
|
||||
assertThat(data.indexToName().get(0).iterator().next()).isEqualTo(data.indexToName().get(0).iterator().next());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testProcessAnnotations_SimplePost() throws Exception {
|
||||
Method method = TestTemplate_Simple.class.getDeclaredMethod("postTest",
|
||||
TestObject.class);
|
||||
MethodMetadata data = contract
|
||||
.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
Method method = TestTemplate_Simple.class.getDeclaredMethod("postTest", TestObject.class);
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
|
||||
assertThat(data.template().url()).isEqualTo("/");
|
||||
assertThat(data.template().method()).isEqualTo("POST");
|
||||
@@ -231,10 +211,8 @@ public class SpringMvcContractTests {
|
||||
|
||||
@Test
|
||||
public void testProcessAnnotations_SimplePostMapping() throws Exception {
|
||||
Method method = TestTemplate_Simple.class.getDeclaredMethod("postMappingTest",
|
||||
TestObject.class);
|
||||
MethodMetadata data = contract
|
||||
.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
Method method = TestTemplate_Simple.class.getDeclaredMethod("postMappingTest", TestObject.class);
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
|
||||
assertThat(data.template().url()).isEqualTo("/");
|
||||
assertThat(data.template().method()).isEqualTo("POST");
|
||||
@@ -245,102 +223,82 @@ public class SpringMvcContractTests {
|
||||
|
||||
@Test
|
||||
public void testProcessAnnotationsOnMethod_Advanced() throws Exception {
|
||||
Method method = TestTemplate_Advanced.class.getDeclaredMethod("getTest",
|
||||
String.class, String.class, Integer.class);
|
||||
MethodMetadata data = contract
|
||||
.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
Method method = TestTemplate_Advanced.class.getDeclaredMethod("getTest", String.class, String.class,
|
||||
Integer.class);
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
|
||||
assertThat(data.template().url())
|
||||
.isEqualTo("/advanced/test/{id}?amount=" + "{amount}");
|
||||
assertThat(data.template().url()).isEqualTo("/advanced/test/{id}?amount=" + "{amount}");
|
||||
assertThat(data.template().method()).isEqualTo("PUT");
|
||||
assertThat(data.template().headers().get("Accept").iterator().next())
|
||||
.isEqualTo(MediaType.APPLICATION_JSON_VALUE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testProcessAnnotationsOnMethod_Advanced_UnknownAnnotation()
|
||||
throws Exception {
|
||||
Method method = TestTemplate_Advanced.class.getDeclaredMethod("getTest",
|
||||
String.class, String.class, Integer.class);
|
||||
public void testProcessAnnotationsOnMethod_Advanced_UnknownAnnotation() throws Exception {
|
||||
Method method = TestTemplate_Advanced.class.getDeclaredMethod("getTest", String.class, String.class,
|
||||
Integer.class);
|
||||
contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
|
||||
// Don't throw an exception and this passes
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testProcessAnnotationsOnMethod_CollectionFormat()
|
||||
throws NoSuchMethodException {
|
||||
Method method = TestTemplate_Advanced.class
|
||||
.getDeclaredMethod("getWithCollectionFormat");
|
||||
public void testProcessAnnotationsOnMethod_CollectionFormat() throws NoSuchMethodException {
|
||||
Method method = TestTemplate_Advanced.class.getDeclaredMethod("getWithCollectionFormat");
|
||||
|
||||
MethodMetadata data = contract
|
||||
.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
|
||||
assertThat(data.template().collectionFormat()).isEqualTo(SSV);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testProcessAnnotations_Advanced() throws Exception {
|
||||
Method method = TestTemplate_Advanced.class.getDeclaredMethod("getTest",
|
||||
String.class, String.class, Integer.class);
|
||||
MethodMetadata data = contract
|
||||
.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
Method method = TestTemplate_Advanced.class.getDeclaredMethod("getTest", String.class, String.class,
|
||||
Integer.class);
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
|
||||
assertThat(data.template().url())
|
||||
.isEqualTo("/advanced/test/{id}?amount=" + "{amount}");
|
||||
assertThat(data.template().url()).isEqualTo("/advanced/test/{id}?amount=" + "{amount}");
|
||||
assertThat(data.template().method()).isEqualTo("PUT");
|
||||
assertThat(data.template().headers().get("Accept").iterator().next())
|
||||
.isEqualTo(MediaType.APPLICATION_JSON_VALUE);
|
||||
|
||||
assertThat(data.indexToName().get(0).iterator().next())
|
||||
.isEqualTo("Authorization");
|
||||
assertThat(data.indexToName().get(0).iterator().next()).isEqualTo("Authorization");
|
||||
assertThat(data.indexToName().get(1).iterator().next()).isEqualTo("id");
|
||||
assertThat(data.indexToName().get(2).iterator().next()).isEqualTo("amount");
|
||||
assertThat(data.indexToExpander().get(2)).isNotNull();
|
||||
|
||||
assertThat(data.template().headers().get("Authorization").iterator().next())
|
||||
.isEqualTo("{Authorization}");
|
||||
assertThat(data.template().queries().get("amount").iterator().next())
|
||||
.isEqualTo("{amount}");
|
||||
assertThat(data.template().headers().get("Authorization").iterator().next()).isEqualTo("{Authorization}");
|
||||
assertThat(data.template().queries().get("amount").iterator().next()).isEqualTo("{amount}");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testProcessAnnotations_Aliased() throws Exception {
|
||||
Method method = TestTemplate_Advanced.class.getDeclaredMethod("getTest2",
|
||||
String.class, Integer.class);
|
||||
MethodMetadata data = contract
|
||||
.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
Method method = TestTemplate_Advanced.class.getDeclaredMethod("getTest2", String.class, Integer.class);
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
|
||||
assertThat(data.template().url())
|
||||
.isEqualTo("/advanced/test2?amount=" + "{amount}");
|
||||
assertThat(data.template().url()).isEqualTo("/advanced/test2?amount=" + "{amount}");
|
||||
assertThat(data.template().method()).isEqualTo("PUT");
|
||||
assertThat(data.template().headers().get("Accept").iterator().next())
|
||||
.isEqualTo(MediaType.APPLICATION_JSON_VALUE);
|
||||
|
||||
assertThat(data.indexToName().get(0).iterator().next())
|
||||
.isEqualTo("Authorization");
|
||||
assertThat(data.indexToName().get(0).iterator().next()).isEqualTo("Authorization");
|
||||
assertThat(data.indexToName().get(1).iterator().next()).isEqualTo("amount");
|
||||
|
||||
assertThat(data.template().headers().get("Authorization").iterator().next())
|
||||
.isEqualTo("{Authorization}");
|
||||
assertThat(data.template().queries().get("amount").iterator().next())
|
||||
.isEqualTo("{amount}");
|
||||
assertThat(data.template().headers().get("Authorization").iterator().next()).isEqualTo("{Authorization}");
|
||||
assertThat(data.template().queries().get("amount").iterator().next()).isEqualTo("{amount}");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testProcessAnnotations_DateTimeFormatParam() throws Exception {
|
||||
Method method = TestTemplate_DateTimeFormatParameter.class
|
||||
.getDeclaredMethod("getTest", LocalDateTime.class);
|
||||
MethodMetadata data = contract
|
||||
.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
Method method = TestTemplate_DateTimeFormatParameter.class.getDeclaredMethod("getTest", LocalDateTime.class);
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
|
||||
Param.Expander expander = data.indexToExpander().get(0);
|
||||
assertThat(expander).isNotNull();
|
||||
|
||||
LocalDateTime input = LocalDateTime.of(2001, 10, 12, 23, 56, 3);
|
||||
|
||||
DateTimeFormatter formatter = DateTimeFormatter
|
||||
.ofPattern(TestTemplate_DateTimeFormatParameter.CUSTOM_PATTERN);
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(TestTemplate_DateTimeFormatParameter.CUSTOM_PATTERN);
|
||||
|
||||
String expected = formatter.format(input);
|
||||
|
||||
@@ -349,16 +307,13 @@ public class SpringMvcContractTests {
|
||||
|
||||
@Test
|
||||
public void testProcessAnnotations_NumberFormatParam() throws Exception {
|
||||
Method method = TestTemplate_NumberFormatParameter.class
|
||||
.getDeclaredMethod("getTest", BigDecimal.class);
|
||||
MethodMetadata data = contract
|
||||
.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
Method method = TestTemplate_NumberFormatParameter.class.getDeclaredMethod("getTest", BigDecimal.class);
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
|
||||
Param.Expander expander = data.indexToExpander().get(0);
|
||||
assertThat(expander).isNotNull();
|
||||
|
||||
NumberStyleFormatter formatter = new NumberStyleFormatter(
|
||||
TestTemplate_NumberFormatParameter.CUSTOM_PATTERN);
|
||||
NumberStyleFormatter formatter = new NumberStyleFormatter(TestTemplate_NumberFormatParameter.CUSTOM_PATTERN);
|
||||
|
||||
BigDecimal input = BigDecimal.valueOf(1220.345);
|
||||
|
||||
@@ -371,8 +326,7 @@ public class SpringMvcContractTests {
|
||||
@Test
|
||||
public void testProcessAnnotations_Advanced2() throws Exception {
|
||||
Method method = TestTemplate_Advanced.class.getDeclaredMethod("getTest");
|
||||
MethodMetadata data = contract
|
||||
.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
|
||||
assertThat(data.template().url()).isEqualTo("/advanced");
|
||||
assertThat(data.template().method()).isEqualTo("GET");
|
||||
@@ -383,8 +337,7 @@ public class SpringMvcContractTests {
|
||||
@Test
|
||||
public void testProcessAnnotations_Advanced3() throws Exception {
|
||||
Method method = TestTemplate_Simple.class.getDeclaredMethod("getTest");
|
||||
MethodMetadata data = contract
|
||||
.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
|
||||
assertThat(data.template().url()).isEqualTo("/");
|
||||
assertThat(data.template().method()).isEqualTo("GET");
|
||||
@@ -394,10 +347,8 @@ public class SpringMvcContractTests {
|
||||
|
||||
@Test
|
||||
public void testProcessAnnotations_ListParams() throws Exception {
|
||||
Method method = TestTemplate_ListParams.class.getDeclaredMethod("getTest",
|
||||
List.class);
|
||||
MethodMetadata data = contract
|
||||
.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
Method method = TestTemplate_ListParams.class.getDeclaredMethod("getTest", List.class);
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
|
||||
assertThat(data.template().url()).isEqualTo("/test?id=" + "{id}");
|
||||
assertThat(data.template().method()).isEqualTo("GET");
|
||||
@@ -407,10 +358,8 @@ public class SpringMvcContractTests {
|
||||
|
||||
@Test
|
||||
public void testProcessAnnotations_ListParamsWithoutName() throws Exception {
|
||||
Method method = TestTemplate_ListParamsWithoutName.class
|
||||
.getDeclaredMethod("getTest", List.class);
|
||||
MethodMetadata data = contract
|
||||
.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
Method method = TestTemplate_ListParamsWithoutName.class.getDeclaredMethod("getTest", List.class);
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
|
||||
assertThat(data.template().url()).isEqualTo("/test?id=" + "{id}");
|
||||
assertThat(data.template().method()).isEqualTo("GET");
|
||||
@@ -420,10 +369,8 @@ public class SpringMvcContractTests {
|
||||
|
||||
@Test
|
||||
public void testProcessAnnotations_MapParams() throws Exception {
|
||||
Method method = TestTemplate_MapParams.class.getDeclaredMethod("getTest",
|
||||
Map.class);
|
||||
MethodMetadata data = contract
|
||||
.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
Method method = TestTemplate_MapParams.class.getDeclaredMethod("getTest", Map.class);
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
|
||||
assertThat(data.template().url()).isEqualTo("/test");
|
||||
assertThat(data.template().method()).isEqualTo("GET");
|
||||
@@ -433,23 +380,18 @@ public class SpringMvcContractTests {
|
||||
|
||||
@Test
|
||||
public void testProcessHeaders() throws Exception {
|
||||
Method method = TestTemplate_Headers.class.getDeclaredMethod("getTest",
|
||||
String.class);
|
||||
MethodMetadata data = contract
|
||||
.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
Method method = TestTemplate_Headers.class.getDeclaredMethod("getTest", String.class);
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
|
||||
assertThat(data.template().url()).isEqualTo("/test/{id}");
|
||||
assertThat(data.template().method()).isEqualTo("GET");
|
||||
assertThat(data.template().headers().get("x-Foo").iterator().next())
|
||||
.isEqualTo("bar");
|
||||
assertThat(data.template().headers().get("x-Foo").iterator().next()).isEqualTo("bar");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testProcessHeadersWithoutValues() throws Exception {
|
||||
Method method = TestTemplate_HeadersWithoutValues.class
|
||||
.getDeclaredMethod("getTest", String.class);
|
||||
MethodMetadata data = contract
|
||||
.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
Method method = TestTemplate_HeadersWithoutValues.class.getDeclaredMethod("getTest", String.class);
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
|
||||
assertThat(data.template().url()).isEqualTo("/test/{id}");
|
||||
assertThat(data.template().method()).isEqualTo("GET");
|
||||
@@ -458,38 +400,30 @@ public class SpringMvcContractTests {
|
||||
|
||||
@Test
|
||||
public void testProcessAnnotations_Fallback() throws Exception {
|
||||
Method method = TestTemplate_Advanced.class.getDeclaredMethod("getTestFallback",
|
||||
String.class, String.class, Integer.class);
|
||||
Method method = TestTemplate_Advanced.class.getDeclaredMethod("getTestFallback", String.class, String.class,
|
||||
Integer.class);
|
||||
|
||||
assumeTrue("does not have java 8 parameter names",
|
||||
hasJava8ParameterNames(method));
|
||||
assumeTrue("does not have java 8 parameter names", hasJava8ParameterNames(method));
|
||||
|
||||
MethodMetadata data = contract
|
||||
.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
|
||||
assertThat(data.template().url())
|
||||
.isEqualTo("/advanced/testfallback/{id}?amount=" + "{amount}");
|
||||
assertThat(data.template().url()).isEqualTo("/advanced/testfallback/{id}?amount=" + "{amount}");
|
||||
assertThat(data.template().method()).isEqualTo("PUT");
|
||||
assertThat(data.template().headers().get("Accept").iterator().next())
|
||||
.isEqualTo(MediaType.APPLICATION_JSON_VALUE);
|
||||
|
||||
assertThat(data.indexToName().get(0).iterator().next())
|
||||
.isEqualTo("Authorization");
|
||||
assertThat(data.indexToName().get(0).iterator().next()).isEqualTo("Authorization");
|
||||
assertThat(data.indexToName().get(1).iterator().next()).isEqualTo("id");
|
||||
assertThat(data.indexToName().get(2).iterator().next()).isEqualTo("amount");
|
||||
|
||||
assertThat(data.template().headers().get("Authorization").iterator().next())
|
||||
.isEqualTo("{Authorization}");
|
||||
assertThat(data.template().queries().get("amount").iterator().next())
|
||||
.isEqualTo("{amount}");
|
||||
assertThat(data.template().headers().get("Authorization").iterator().next()).isEqualTo("{Authorization}");
|
||||
assertThat(data.template().queries().get("amount").iterator().next()).isEqualTo("{amount}");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testProcessHeaderMap() throws Exception {
|
||||
Method method = TestTemplate_HeaderMap.class.getDeclaredMethod("headerMap",
|
||||
MultiValueMap.class, String.class);
|
||||
MethodMetadata data = contract
|
||||
.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
Method method = TestTemplate_HeaderMap.class.getDeclaredMethod("headerMap", MultiValueMap.class, String.class);
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
|
||||
assertThat(data.template().url()).isEqualTo("/headerMap");
|
||||
assertThat(data.template().method()).isEqualTo("GET");
|
||||
@@ -500,17 +434,15 @@ public class SpringMvcContractTests {
|
||||
|
||||
@Test(expected = IllegalStateException.class)
|
||||
public void testProcessHeaderMapMoreThanOnce() throws Exception {
|
||||
Method method = TestTemplate_HeaderMap.class.getDeclaredMethod(
|
||||
"headerMapMoreThanOnce", MultiValueMap.class, MultiValueMap.class);
|
||||
Method method = TestTemplate_HeaderMap.class.getDeclaredMethod("headerMapMoreThanOnce", MultiValueMap.class,
|
||||
MultiValueMap.class);
|
||||
contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testProcessQueryMap() throws Exception {
|
||||
Method method = TestTemplate_QueryMap.class.getDeclaredMethod("queryMap",
|
||||
MultiValueMap.class, String.class);
|
||||
MethodMetadata data = contract
|
||||
.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
Method method = TestTemplate_QueryMap.class.getDeclaredMethod("queryMap", MultiValueMap.class, String.class);
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
|
||||
assertThat(data.template().url()).isEqualTo("/queryMap?aParam=" + "{aParam}");
|
||||
assertThat(data.template().method()).isEqualTo("GET");
|
||||
@@ -521,13 +453,10 @@ public class SpringMvcContractTests {
|
||||
|
||||
@Test
|
||||
public void testProcessQueryMapObject() throws Exception {
|
||||
Method method = TestTemplate_QueryMap.class.getDeclaredMethod("queryMapObject",
|
||||
TestObject.class, String.class);
|
||||
MethodMetadata data = contract
|
||||
.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
Method method = TestTemplate_QueryMap.class.getDeclaredMethod("queryMapObject", TestObject.class, String.class);
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
|
||||
assertThat(data.template().url())
|
||||
.isEqualTo("/queryMapObject?aParam=" + "{aParam}");
|
||||
assertThat(data.template().url()).isEqualTo("/queryMapObject?aParam=" + "{aParam}");
|
||||
assertThat(data.template().method()).isEqualTo("GET");
|
||||
assertThat(data.queryMapIndex().intValue()).isEqualTo(0);
|
||||
Map<String, Collection<String>> params = data.template().queries();
|
||||
@@ -536,93 +465,77 @@ public class SpringMvcContractTests {
|
||||
|
||||
@Test(expected = IllegalStateException.class)
|
||||
public void testProcessQueryMapMoreThanOnce() throws Exception {
|
||||
Method method = TestTemplate_QueryMap.class.getDeclaredMethod(
|
||||
"queryMapMoreThanOnce", MultiValueMap.class, MultiValueMap.class);
|
||||
Method method = TestTemplate_QueryMap.class.getDeclaredMethod("queryMapMoreThanOnce", MultiValueMap.class,
|
||||
MultiValueMap.class);
|
||||
contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMatrixVariable_MapParam() throws Exception {
|
||||
Method method = TestTemplate_MatrixVariable.class
|
||||
.getDeclaredMethod("matrixVariable", Map.class);
|
||||
MethodMetadata data = contract
|
||||
.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
Method method = TestTemplate_MatrixVariable.class.getDeclaredMethod("matrixVariable", Map.class);
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
|
||||
Map<String, String> testMap = new HashMap<>();
|
||||
testMap.put("param", "value");
|
||||
|
||||
assertThat(data.template().method()).isEqualTo("GET");
|
||||
assertThat(data.template().url()).isEqualTo("/matrixVariable/{params}");
|
||||
assertThat(";param=value")
|
||||
.isEqualTo(data.indexToExpander().get(0).expand(testMap));
|
||||
assertThat(";param=value").isEqualTo(data.indexToExpander().get(0).expand(testMap));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMatrixVariable_ObjectParam() throws Exception {
|
||||
Method method = TestTemplate_MatrixVariable.class
|
||||
.getDeclaredMethod("matrixVariableObject", Object.class);
|
||||
MethodMetadata data = contract
|
||||
.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
Method method = TestTemplate_MatrixVariable.class.getDeclaredMethod("matrixVariableObject", Object.class);
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
|
||||
assertThat(data.template().method()).isEqualTo("GET");
|
||||
assertThat(data.template().url()).isEqualTo("/matrixVariableObject/{param}");
|
||||
assertThat(";param=value")
|
||||
.isEqualTo(data.indexToExpander().get(0).expand("value"));
|
||||
assertThat(";param=value").isEqualTo(data.indexToExpander().get(0).expand("value"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMatrixVariableWithNoName() throws NoSuchMethodException {
|
||||
Method method = TestTemplate_MatrixVariable.class
|
||||
.getDeclaredMethod("matrixVariableNotNamed", Map.class);
|
||||
MethodMetadata data = contract
|
||||
.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
Method method = TestTemplate_MatrixVariable.class.getDeclaredMethod("matrixVariableNotNamed", Map.class);
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
Map<String, String> testMap = new HashMap<>();
|
||||
|
||||
testMap.put("param", "value");
|
||||
|
||||
assertThat(data.template().method()).isEqualTo("GET");
|
||||
assertThat(data.template().url()).isEqualTo("/matrixVariable/{params}");
|
||||
assertThat(";param=value")
|
||||
.isEqualTo(data.indexToExpander().get(0).expand(testMap));
|
||||
assertThat(";param=value").isEqualTo(data.indexToExpander().get(0).expand(testMap));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAddingTemplatedParameterWithTheSameKey()
|
||||
throws NoSuchMethodException {
|
||||
Method method = TestTemplate_Advanced.class.getDeclaredMethod(
|
||||
"testAddingTemplatedParamForExistingKey", String.class);
|
||||
MethodMetadata data = contract
|
||||
.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
public void testAddingTemplatedParameterWithTheSameKey() throws NoSuchMethodException {
|
||||
Method method = TestTemplate_Advanced.class.getDeclaredMethod("testAddingTemplatedParamForExistingKey",
|
||||
String.class);
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
|
||||
assertThat(data.template().headers().get("Accept")).contains("application/json",
|
||||
"{Accept}");
|
||||
assertThat(data.template().headers().get("Accept")).contains("application/json", "{Accept}");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMultipleRequestPartAnnotations() throws NoSuchMethodException {
|
||||
Method method = TestTemplate_RequestPart.class.getDeclaredMethod(
|
||||
"requestWithMultipleParts", MultipartFile.class, String.class);
|
||||
Method method = TestTemplate_RequestPart.class.getDeclaredMethod("requestWithMultipleParts",
|
||||
MultipartFile.class, String.class);
|
||||
|
||||
MethodMetadata data = contract
|
||||
.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
MethodMetadata data = contract.parseAndValidateMetadata(method.getDeclaringClass(), method);
|
||||
assertThat(data.formParams()).contains("file", "id");
|
||||
}
|
||||
|
||||
public interface TestTemplate_Simple {
|
||||
|
||||
@RequestMapping(value = "/test/{id}", method = RequestMethod.GET,
|
||||
produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
@RequestMapping(value = "/test/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
ResponseEntity<TestObject> getTest(@PathVariable("id") String id);
|
||||
|
||||
@RequestMapping(method = RequestMethod.GET,
|
||||
produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
@RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
TestObject getTest();
|
||||
|
||||
@GetMapping(value = "/test/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
ResponseEntity<TestObject> getMappingTest(@PathVariable("id") String id);
|
||||
|
||||
@RequestMapping(method = RequestMethod.POST,
|
||||
produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
@RequestMapping(method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
TestObject postTest(@RequestBody TestObject object);
|
||||
|
||||
@PostMapping(produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
@@ -634,8 +547,7 @@ public class SpringMvcContractTests {
|
||||
public interface TestTemplate_Class_Annotations {
|
||||
|
||||
@RequestMapping(value = "/test/{testId}", method = RequestMethod.GET)
|
||||
TestObject getSpecificTest(@PathVariable("classId") String classId,
|
||||
@PathVariable("testId") String testId);
|
||||
TestObject getSpecificTest(@PathVariable("classId") String classId, @PathVariable("testId") String testId);
|
||||
|
||||
@RequestMapping(method = RequestMethod.GET)
|
||||
TestObject getAllTests(@PathVariable("classId") String classId);
|
||||
@@ -648,8 +560,7 @@ public class SpringMvcContractTests {
|
||||
|
||||
public interface TestTemplate_Headers {
|
||||
|
||||
@RequestMapping(value = "/test/{id}", method = RequestMethod.GET,
|
||||
headers = "X-Foo=bar")
|
||||
@RequestMapping(value = "/test/{id}", method = RequestMethod.GET, headers = "X-Foo=bar")
|
||||
ResponseEntity<TestObject> getTest(@PathVariable("id") String id);
|
||||
|
||||
}
|
||||
@@ -690,8 +601,7 @@ public class SpringMvcContractTests {
|
||||
@RequestHeader(name = "aHeader") String aHeader);
|
||||
|
||||
@RequestMapping(path = "/headerMapMoreThanOnce")
|
||||
String headerMapMoreThanOnce(
|
||||
@RequestHeader MultiValueMap<String, String> headerMap1,
|
||||
String headerMapMoreThanOnce(@RequestHeader MultiValueMap<String, String> headerMap1,
|
||||
@RequestHeader MultiValueMap<String, String> headerMap2);
|
||||
|
||||
}
|
||||
@@ -707,8 +617,7 @@ public class SpringMvcContractTests {
|
||||
@RequestParam MultiValueMap<String, String> queryMap2);
|
||||
|
||||
@RequestMapping(path = "/queryMapObject")
|
||||
String queryMapObject(@SpringQueryMap TestObject queryMap,
|
||||
@RequestParam(name = "aParam") String aParam);
|
||||
String queryMapObject(@SpringQueryMap TestObject queryMap, @RequestParam(name = "aParam") String aParam);
|
||||
|
||||
}
|
||||
|
||||
@@ -716,8 +625,7 @@ public class SpringMvcContractTests {
|
||||
|
||||
@RequestMapping(path = "/requestPart", method = RequestMethod.POST,
|
||||
consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
|
||||
void requestWithMultipleParts(@RequestPart("file") MultipartFile file,
|
||||
@RequestPart("id") String identifier);
|
||||
void requestWithMultipleParts(@RequestPart("file") MultipartFile file, @RequestPart("id") String identifier);
|
||||
|
||||
}
|
||||
|
||||
@@ -743,30 +651,25 @@ public class SpringMvcContractTests {
|
||||
ResponseEntity<TestObject> getWithCollectionFormat();
|
||||
|
||||
@ExceptionHandler
|
||||
@RequestMapping(path = "/test/{id}", method = RequestMethod.PUT,
|
||||
produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
ResponseEntity<TestObject> getTest(@RequestHeader("Authorization") String auth,
|
||||
@PathVariable("id") String id, @RequestParam("amount") Integer amount);
|
||||
@RequestMapping(path = "/test/{id}", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
ResponseEntity<TestObject> getTest(@RequestHeader("Authorization") String auth, @PathVariable("id") String id,
|
||||
@RequestParam("amount") Integer amount);
|
||||
|
||||
@RequestMapping(path = "/test2", method = RequestMethod.PUT,
|
||||
produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
ResponseEntity<TestObject> getTest2(
|
||||
@RequestHeader(name = "Authorization") String auth,
|
||||
@RequestMapping(path = "/test2", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
ResponseEntity<TestObject> getTest2(@RequestHeader(name = "Authorization") String auth,
|
||||
@RequestParam(name = "amount") Integer amount);
|
||||
|
||||
@ExceptionHandler
|
||||
@RequestMapping(path = "/testfallback/{id}", method = RequestMethod.PUT,
|
||||
produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
ResponseEntity<TestObject> getTestFallback(@RequestHeader String Authorization,
|
||||
@PathVariable String id, @RequestParam Integer amount);
|
||||
ResponseEntity<TestObject> getTestFallback(@RequestHeader String Authorization, @PathVariable String id,
|
||||
@RequestParam Integer amount);
|
||||
|
||||
@RequestMapping(method = RequestMethod.GET,
|
||||
produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
@RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
TestObject getTest();
|
||||
|
||||
@GetMapping(produces = "application/json")
|
||||
String testAddingTemplatedParamForExistingKey(
|
||||
@RequestHeader("Accept") String accept);
|
||||
String testAddingTemplatedParamForExistingKey(@RequestHeader("Accept") String accept);
|
||||
|
||||
}
|
||||
|
||||
@@ -785,13 +688,11 @@ public class SpringMvcContractTests {
|
||||
String CUSTOM_PATTERN = "$###,###.###";
|
||||
|
||||
@RequestMapping(method = RequestMethod.GET)
|
||||
String getTest(@RequestParam("amount") @NumberFormat(
|
||||
pattern = CUSTOM_PATTERN) BigDecimal amount);
|
||||
String getTest(@RequestParam("amount") @NumberFormat(pattern = CUSTOM_PATTERN) BigDecimal amount);
|
||||
|
||||
}
|
||||
|
||||
@JsonAutoDetect(fieldVisibility = ANY, getterVisibility = NONE,
|
||||
setterVisibility = NONE)
|
||||
@JsonAutoDetect(fieldVisibility = ANY, getterVisibility = NONE, setterVisibility = NONE)
|
||||
public class TestObject {
|
||||
|
||||
public String something;
|
||||
@@ -820,8 +721,7 @@ public class SpringMvcContractTests {
|
||||
if (number != null ? !number.equals(that.number) : that.number != null) {
|
||||
return false;
|
||||
}
|
||||
if (something != null ? !something.equals(that.something)
|
||||
: that.something != null) {
|
||||
if (something != null ? !something.equals(that.something) : that.something != null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -837,9 +737,8 @@ public class SpringMvcContractTests {
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return new StringBuilder("TestObject{").append("something='")
|
||||
.append(something).append("', ").append("number=").append(number)
|
||||
.append("}").toString();
|
||||
return new StringBuilder("TestObject{").append("something='").append(something).append("', ")
|
||||
.append("number=").append(number).append("}").toString();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -80,13 +80,12 @@ public class ApacheHttpClientConfigurationTests {
|
||||
|
||||
@Test
|
||||
public void testFactories() {
|
||||
assertThat(this.connectionManagerFactory).isInstanceOf(ApacheHttpClientConnectionManagerFactory.class);
|
||||
assertThat(this.connectionManagerFactory)
|
||||
.isInstanceOf(ApacheHttpClientConnectionManagerFactory.class);
|
||||
assertThat(this.connectionManagerFactory).isInstanceOf(
|
||||
ApacheHttpClientConfigurationTestApp.MyApacheHttpClientConnectionManagerFactory.class);
|
||||
.isInstanceOf(ApacheHttpClientConfigurationTestApp.MyApacheHttpClientConnectionManagerFactory.class);
|
||||
assertThat(this.httpClientFactory).isInstanceOf(ApacheHttpClientFactory.class);
|
||||
assertThat(this.httpClientFactory).isInstanceOf(
|
||||
ApacheHttpClientConfigurationTestApp.MyApacheHttpClientFactory.class);
|
||||
assertThat(this.httpClientFactory)
|
||||
.isInstanceOf(ApacheHttpClientConfigurationTestApp.MyApacheHttpClientFactory.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -108,8 +107,7 @@ public class ApacheHttpClientConfigurationTests {
|
||||
|
||||
@SpringBootConfiguration
|
||||
@EnableAutoConfiguration
|
||||
@EnableFeignClients(
|
||||
clients = { ApacheHttpClientConfigurationTestApp.FooClient.class })
|
||||
@EnableFeignClients(clients = { ApacheHttpClientConfigurationTestApp.FooClient.class })
|
||||
static class ApacheHttpClientConfigurationTestApp {
|
||||
|
||||
@FeignClient(name = "foo", serviceId = "foo")
|
||||
@@ -121,9 +119,8 @@ public class ApacheHttpClientConfigurationTests {
|
||||
extends DefaultApacheHttpClientConnectionManagerFactory {
|
||||
|
||||
@Override
|
||||
public HttpClientConnectionManager newConnectionManager(
|
||||
boolean disableSslValidation, int maxTotalConnections,
|
||||
int maxConnectionsPerRoute, long timeToLive, TimeUnit timeUnit,
|
||||
public HttpClientConnectionManager newConnectionManager(boolean disableSslValidation,
|
||||
int maxTotalConnections, int maxConnectionsPerRoute, long timeToLive, TimeUnit timeUnit,
|
||||
RegistryBuilder registry) {
|
||||
return mock(PoolingHttpClientConnectionManager.class);
|
||||
}
|
||||
@@ -146,8 +143,7 @@ public class ApacheHttpClientConfigurationTests {
|
||||
Header[] headers = new BasicHeader[0];
|
||||
doReturn(headers).when(response).getAllHeaders();
|
||||
try {
|
||||
Mockito.doReturn(response).when(client)
|
||||
.execute(any(HttpUriRequest.class));
|
||||
Mockito.doReturn(response).when(client).execute(any(HttpUriRequest.class));
|
||||
}
|
||||
catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
@@ -163,8 +159,7 @@ public class ApacheHttpClientConfigurationTests {
|
||||
static class MyConfig {
|
||||
|
||||
@Bean
|
||||
public ApacheHttpClientFactory apacheHttpClientFactory(
|
||||
HttpClientBuilder builder) {
|
||||
public ApacheHttpClientFactory apacheHttpClientFactory(HttpClientBuilder builder) {
|
||||
return new MyApacheHttpClientFactory(builder);
|
||||
}
|
||||
|
||||
|
||||
@@ -48,11 +48,9 @@ import static org.mockito.Mockito.mockingDetails;
|
||||
* @author Ryan Baxter
|
||||
*/
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(properties = { "feign.okhttp.enabled: true",
|
||||
"spring.cloud.httpclientfactories.ok.enabled: true",
|
||||
"ribbon.eureka.enabled = false", "ribbon.okhttp.enabled: true",
|
||||
"feign.okhttp.enabled: true", "ribbon.httpclient.enabled: false",
|
||||
"feign.httpclient.enabled: false" })
|
||||
@SpringBootTest(properties = { "feign.okhttp.enabled: true", "spring.cloud.httpclientfactories.ok.enabled: true",
|
||||
"ribbon.eureka.enabled = false", "ribbon.okhttp.enabled: true", "feign.okhttp.enabled: true",
|
||||
"ribbon.httpclient.enabled: false", "feign.httpclient.enabled: false" })
|
||||
@DirtiesContext
|
||||
public class OkHttpClientConfigurationTests {
|
||||
|
||||
@@ -67,13 +65,10 @@ public class OkHttpClientConfigurationTests {
|
||||
|
||||
@Test
|
||||
public void testFactories() {
|
||||
assertThat(this.connectionPoolFactory)
|
||||
.isInstanceOf(OkHttpClientConnectionPoolFactory.class);
|
||||
assertThat(this.connectionPoolFactory)
|
||||
.isInstanceOf(TestConfig.MyOkHttpClientConnectionPoolFactory.class);
|
||||
assertThat(this.connectionPoolFactory).isInstanceOf(OkHttpClientConnectionPoolFactory.class);
|
||||
assertThat(this.connectionPoolFactory).isInstanceOf(TestConfig.MyOkHttpClientConnectionPoolFactory.class);
|
||||
assertThat(this.okHttpClientFactory).isInstanceOf(OkHttpClientFactory.class);
|
||||
assertThat(this.okHttpClientFactory)
|
||||
.isInstanceOf(TestConfig.MyOkHttpClientFactory.class);
|
||||
assertThat(this.okHttpClientFactory).isInstanceOf(TestConfig.MyOkHttpClientFactory.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -115,12 +110,10 @@ public class OkHttpClientConfigurationTests {
|
||||
return mock(OkHttpClient.class);
|
||||
}
|
||||
|
||||
static class MyOkHttpClientConnectionPoolFactory
|
||||
extends DefaultOkHttpClientConnectionPoolFactory {
|
||||
static class MyOkHttpClientConnectionPoolFactory extends DefaultOkHttpClientConnectionPoolFactory {
|
||||
|
||||
@Override
|
||||
public ConnectionPool create(int maxIdleConnections, long keepAliveDuration,
|
||||
TimeUnit timeUnit) {
|
||||
public ConnectionPool create(int maxIdleConnections, long keepAliveDuration, TimeUnit timeUnit) {
|
||||
return new ConnectionPool();
|
||||
}
|
||||
|
||||
|
||||
@@ -44,8 +44,7 @@ public class TestAutoConfiguration {
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@Order(Ordered.HIGHEST_PRECEDENCE)
|
||||
protected static class TestSecurityConfiguration
|
||||
extends WebSecurityConfigurerAdapter {
|
||||
protected static class TestSecurityConfiguration extends WebSecurityConfigurerAdapter {
|
||||
|
||||
TestSecurityConfiguration() {
|
||||
super(true);
|
||||
@@ -54,16 +53,14 @@ public class TestAutoConfiguration {
|
||||
@Bean
|
||||
public UserDetailsService userDetailsService() {
|
||||
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
|
||||
manager.createUser(
|
||||
User.withUsername(USER).password(PASSWORD).roles("USER").build());
|
||||
manager.createUser(User.withUsername(USER).password(PASSWORD).roles("USER").build());
|
||||
return manager;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
// super.configure(http);
|
||||
http.antMatcher("/proxy-username").httpBasic().and().authorizeRequests()
|
||||
.antMatchers("/**").permitAll();
|
||||
http.antMatcher("/proxy-username").httpBasic().and().authorizeRequests().antMatchers("/**").permitAll();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -48,11 +48,10 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
|
||||
* @author Jakub Narloch
|
||||
*/
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@SpringBootTest(classes = FeignClientNotPrimaryTests.Application.class,
|
||||
webEnvironment = RANDOM_PORT,
|
||||
@SpringBootTest(classes = FeignClientNotPrimaryTests.Application.class, webEnvironment = RANDOM_PORT,
|
||||
value = { "spring.application.name=feignclientnotprimarytest",
|
||||
"logging.level.org.springframework.cloud.openfeign.valid=DEBUG",
|
||||
"feign.httpclient.enabled=false", "feign.okhttp.enabled=false" })
|
||||
"logging.level.org.springframework.cloud.openfeign.valid=DEBUG", "feign.httpclient.enabled=false",
|
||||
"feign.okhttp.enabled=false" })
|
||||
@DirtiesContext
|
||||
public class FeignClientNotPrimaryTests {
|
||||
|
||||
@@ -66,8 +65,7 @@ public class FeignClientNotPrimaryTests {
|
||||
|
||||
@Test
|
||||
public void testClientType() {
|
||||
assertThat(this.testClient).as("testClient was of wrong type")
|
||||
.isInstanceOf(PrimaryTestClient.class);
|
||||
assertThat(this.testClient).as("testClient was of wrong type").isInstanceOf(PrimaryTestClient.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -92,8 +90,7 @@ public class FeignClientNotPrimaryTests {
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@EnableAutoConfiguration
|
||||
@RestController
|
||||
@EnableFeignClients(clients = { TestClient.class },
|
||||
defaultConfiguration = TestDefaultFeignConfig.class)
|
||||
@EnableFeignClients(clients = { TestClient.class }, defaultConfiguration = TestDefaultFeignConfig.class)
|
||||
@LoadBalancerClient(name = "localapp", configuration = LocalClientConfiguration.class)
|
||||
protected static class Application {
|
||||
|
||||
@@ -158,10 +155,8 @@ public class FeignClientNotPrimaryTests {
|
||||
private int port = 0;
|
||||
|
||||
@Bean
|
||||
public ServiceInstanceListSupplier staticServiceInstanceListSupplier(
|
||||
Environment env) {
|
||||
return ServiceInstanceListSupplier.fixed(env).instance(port, "localapp")
|
||||
.build();
|
||||
public ServiceInstanceListSupplier staticServiceInstanceListSupplier(Environment env) {
|
||||
return ServiceInstanceListSupplier.fixed(env).instance(port, "localapp").build();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -39,8 +39,7 @@ public class FeignClientValidationTests {
|
||||
|
||||
@Test
|
||||
public void validNotLoadBalanced() {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
|
||||
GoodUrlConfiguration.class);
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(GoodUrlConfiguration.class);
|
||||
assertThat(context.getBean(GoodUrlConfiguration.Client.class)).isNotNull();
|
||||
context.close();
|
||||
}
|
||||
@@ -58,8 +57,7 @@ public class FeignClientValidationTests {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
|
||||
LoadBalancerAutoConfiguration.class,
|
||||
org.springframework.cloud.loadbalancer.config.LoadBalancerAutoConfiguration.class,
|
||||
FeignLoadBalancerAutoConfiguration.class,
|
||||
GoodServiceIdConfiguration.class);
|
||||
FeignLoadBalancerAutoConfiguration.class, GoodServiceIdConfiguration.class);
|
||||
assertThat(context.getBean(GoodServiceIdConfiguration.Client.class)).isNotNull();
|
||||
context.close();
|
||||
}
|
||||
|
||||
@@ -55,10 +55,8 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
* @author Spencer Gibb
|
||||
*/
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = FeignHttpClientTests.Application.class,
|
||||
webEnvironment = WebEnvironment.RANDOM_PORT,
|
||||
value = { "spring.application.name=feignclienttest",
|
||||
"feign.hystrix.enabled=false", "feign.okhttp.enabled=false" })
|
||||
@SpringBootTest(classes = FeignHttpClientTests.Application.class, webEnvironment = WebEnvironment.RANDOM_PORT, value = {
|
||||
"spring.application.name=feignclienttest", "feign.hystrix.enabled=false", "feign.okhttp.enabled=false" })
|
||||
@DirtiesContext
|
||||
public class FeignHttpClientTests {
|
||||
|
||||
@@ -78,8 +76,7 @@ public class FeignHttpClientTests {
|
||||
public void testSimpleType() {
|
||||
Hello hello = this.testClient.getHello();
|
||||
assertThat(hello).as("hello was null").isNotNull();
|
||||
assertThat(hello).as("first hello didn't match")
|
||||
.isEqualTo(new Hello("hello world 1"));
|
||||
assertThat(hello).as("first hello didn't match").isEqualTo(new Hello("hello world 1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -113,20 +110,17 @@ public class FeignHttpClientTests {
|
||||
|
||||
protected interface BaseTestClient {
|
||||
|
||||
@RequestMapping(method = RequestMethod.GET, value = "/hello",
|
||||
produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
@RequestMapping(method = RequestMethod.GET, value = "/hello", produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
Hello getHello();
|
||||
|
||||
@RequestMapping(method = RequestMethod.PATCH, value = "/hellop",
|
||||
consumes = "application/json")
|
||||
@RequestMapping(method = RequestMethod.PATCH, value = "/hellop", consumes = "application/json")
|
||||
ResponseEntity<Void> patchHello(Hello hello);
|
||||
|
||||
}
|
||||
|
||||
protected interface UserService {
|
||||
|
||||
@RequestMapping(method = RequestMethod.GET, value = "/users/{id}",
|
||||
produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
@RequestMapping(method = RequestMethod.GET, value = "/users/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
User getUser(@PathVariable("id") long id);
|
||||
|
||||
}
|
||||
@@ -140,11 +134,8 @@ public class FeignHttpClientTests {
|
||||
@EnableAutoConfiguration
|
||||
@RestController
|
||||
@EnableFeignClients(clients = { TestClient.class, UserClient.class })
|
||||
@LoadBalancerClients({
|
||||
@LoadBalancerClient(name = "localapp",
|
||||
configuration = LocalClientConfiguration.class),
|
||||
@LoadBalancerClient(name = "localapp1",
|
||||
configuration = LocalClientConfiguration.class) })
|
||||
@LoadBalancerClients({ @LoadBalancerClient(name = "localapp", configuration = LocalClientConfiguration.class),
|
||||
@LoadBalancerClient(name = "localapp1", configuration = LocalClientConfiguration.class) })
|
||||
@Import(NoSecurityConfiguration.class)
|
||||
protected static class Application implements UserService {
|
||||
|
||||
@@ -157,12 +148,10 @@ public class FeignHttpClientTests {
|
||||
public ResponseEntity<Void> patchHello(@RequestBody Hello hello,
|
||||
@RequestHeader("Content-Length") int contentLength) {
|
||||
if (contentLength <= 0) {
|
||||
throw new IllegalArgumentException(
|
||||
"Invalid Content-Length " + contentLength);
|
||||
throw new IllegalArgumentException("Invalid Content-Length " + contentLength);
|
||||
}
|
||||
if (!hello.getMessage().equals("foo")) {
|
||||
throw new IllegalArgumentException(
|
||||
"Invalid Hello: " + hello.getMessage());
|
||||
throw new IllegalArgumentException("Invalid Hello: " + hello.getMessage());
|
||||
}
|
||||
return ResponseEntity.ok().header("X-Hello", "hello world patch").build();
|
||||
}
|
||||
@@ -258,8 +247,7 @@ public class FeignHttpClientTests {
|
||||
private int port = 0;
|
||||
|
||||
@Bean
|
||||
public ServiceInstanceListSupplier staticServiceInstanceListSupplier(
|
||||
Environment env) {
|
||||
public ServiceInstanceListSupplier staticServiceInstanceListSupplier(Environment env) {
|
||||
return ServiceInstanceListSupplier.fixed(env).instance(port, "local").build();
|
||||
}
|
||||
|
||||
|
||||
@@ -55,11 +55,9 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
* @author Spencer Gibb
|
||||
*/
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@SpringBootTest(classes = FeignOkHttpTests.Application.class,
|
||||
webEnvironment = WebEnvironment.RANDOM_PORT,
|
||||
value = { "spring.application.name=feignclienttest",
|
||||
"feign.hystrix.enabled=false", "feign.httpclient.enabled=false",
|
||||
"feign.okhttp.enabled=true",
|
||||
@SpringBootTest(classes = FeignOkHttpTests.Application.class, webEnvironment = WebEnvironment.RANDOM_PORT,
|
||||
value = { "spring.application.name=feignclienttest", "feign.hystrix.enabled=false",
|
||||
"feign.httpclient.enabled=false", "feign.okhttp.enabled=true",
|
||||
"spring.cloud.httpclientfactories.ok.enabled=true" })
|
||||
@DirtiesContext
|
||||
public class FeignOkHttpTests {
|
||||
@@ -80,8 +78,7 @@ public class FeignOkHttpTests {
|
||||
public void testSimpleType() {
|
||||
Hello hello = this.testClient.getHello();
|
||||
assertThat(hello).as("hello was null").isNotNull();
|
||||
assertThat(hello).as("first hello didn't match")
|
||||
.isEqualTo(new Hello("hello world 1"));
|
||||
assertThat(hello).as("first hello didn't match").isEqualTo(new Hello("hello world 1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -118,8 +115,7 @@ public class FeignOkHttpTests {
|
||||
@RequestMapping(method = RequestMethod.GET, value = "/hello")
|
||||
Hello getHello();
|
||||
|
||||
@RequestMapping(method = RequestMethod.PATCH, value = "/hellop",
|
||||
consumes = "application/json")
|
||||
@RequestMapping(method = RequestMethod.PATCH, value = "/hellop", consumes = "application/json")
|
||||
ResponseEntity<Void> patchHello(Hello hello);
|
||||
|
||||
}
|
||||
@@ -141,8 +137,7 @@ public class FeignOkHttpTests {
|
||||
@RestController
|
||||
@EnableFeignClients(clients = { TestClient.class, UserClient.class })
|
||||
@LoadBalancerClients({
|
||||
@LoadBalancerClient(name = "localapp",
|
||||
configuration = FeignHttpClientTests.LocalClientConfiguration.class),
|
||||
@LoadBalancerClient(name = "localapp", configuration = FeignHttpClientTests.LocalClientConfiguration.class),
|
||||
@LoadBalancerClient(name = "localapp1",
|
||||
configuration = FeignHttpClientTests.LocalClientConfiguration.class) })
|
||||
@Import(NoSecurityConfiguration.class)
|
||||
@@ -157,12 +152,10 @@ public class FeignOkHttpTests {
|
||||
public ResponseEntity<Void> patchHello(@RequestBody Hello hello,
|
||||
@RequestHeader("Content-Length") int contentLength) {
|
||||
if (contentLength <= 0) {
|
||||
throw new IllegalArgumentException(
|
||||
"Invalid Content-Length " + contentLength);
|
||||
throw new IllegalArgumentException("Invalid Content-Length " + contentLength);
|
||||
}
|
||||
if (!hello.getMessage().equals("foo")) {
|
||||
throw new IllegalArgumentException(
|
||||
"Invalid Hello: " + hello.getMessage());
|
||||
throw new IllegalArgumentException("Invalid Hello: " + hello.getMessage());
|
||||
}
|
||||
return ResponseEntity.ok().header("X-Hello", "hello world patch").build();
|
||||
}
|
||||
@@ -258,8 +251,7 @@ public class FeignOkHttpTests {
|
||||
private int port = 0;
|
||||
|
||||
@Bean
|
||||
public ServiceInstanceListSupplier staticServiceInstanceListSupplier(
|
||||
Environment env) {
|
||||
public ServiceInstanceListSupplier staticServiceInstanceListSupplier(Environment env) {
|
||||
return ServiceInstanceListSupplier.fixed(env).instance(port, "local").build();
|
||||
}
|
||||
|
||||
|
||||
@@ -47,12 +47,10 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
* @author Spencer Gibb
|
||||
*/
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@SpringBootTest(classes = IterableParameterTests.Application.class,
|
||||
webEnvironment = WebEnvironment.RANDOM_PORT,
|
||||
@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.hystrix.enabled=false" })
|
||||
"logging.level.org.springframework.cloud.openfeign.valid=DEBUG", "feign.httpclient.enabled=false",
|
||||
"feign.okhttp.enabled=false", "feign.hystrix.enabled=false" })
|
||||
@DirtiesContext
|
||||
public class IterableParameterTests {
|
||||
|
||||
@@ -78,8 +76,7 @@ public class IterableParameterTests {
|
||||
@EnableAutoConfiguration
|
||||
@RestController
|
||||
@EnableFeignClients(clients = TestClient.class)
|
||||
@LoadBalancerClient(name = "localapp",
|
||||
configuration = LocalRibbonClientConfiguration.class)
|
||||
@LoadBalancerClient(name = "localapp", configuration = LocalRibbonClientConfiguration.class)
|
||||
@Import(NoSecurityConfiguration.class)
|
||||
protected static class Application {
|
||||
|
||||
@@ -97,10 +94,8 @@ public class IterableParameterTests {
|
||||
private int port = 0;
|
||||
|
||||
@Bean
|
||||
public ServiceInstanceListSupplier staticServiceInstanceListSupplier(
|
||||
Environment env) {
|
||||
return ServiceInstanceListSupplier.fixed(env).instance(port, "localapp")
|
||||
.build();
|
||||
public ServiceInstanceListSupplier staticServiceInstanceListSupplier(Environment env) {
|
||||
return ServiceInstanceListSupplier.fixed(env).instance(port, "localapp").build();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -98,12 +98,10 @@ import static org.hamcrest.Matchers.instanceOf;
|
||||
* @author Darren Foong
|
||||
*/
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@SpringBootTest(classes = ValidFeignClientTests.Application.class,
|
||||
webEnvironment = WebEnvironment.RANDOM_PORT,
|
||||
@SpringBootTest(classes = ValidFeignClientTests.Application.class, webEnvironment = WebEnvironment.RANDOM_PORT,
|
||||
value = { "spring.application.name=feignclienttest",
|
||||
"logging.level.org.springframework.cloud.openfeign.valid=DEBUG",
|
||||
"feign.httpclient.enabled=false", "feign.okhttp.enabled=false",
|
||||
"feign.hystrix.enabled=true" })
|
||||
"logging.level.org.springframework.cloud.openfeign.valid=DEBUG", "feign.httpclient.enabled=false",
|
||||
"feign.okhttp.enabled=false", "feign.hystrix.enabled=true" })
|
||||
@DirtiesContext
|
||||
public class ValidFeignClientTests {
|
||||
|
||||
@@ -150,8 +148,7 @@ public class ValidFeignClientTests {
|
||||
@Test
|
||||
public void testClient() {
|
||||
assertThat(this.testClient).as("testClient was null").isNotNull();
|
||||
assertThat(Proxy.isProxyClass(this.testClient.getClass()))
|
||||
.as("testClient is not a java Proxy").isTrue();
|
||||
assertThat(Proxy.isProxyClass(this.testClient.getClass())).as("testClient is not a java Proxy").isTrue();
|
||||
InvocationHandler invocationHandler = Proxy.getInvocationHandler(this.testClient);
|
||||
assertThat(invocationHandler).as("invocationHandler was null").isNotNull();
|
||||
}
|
||||
@@ -167,8 +164,7 @@ public class ValidFeignClientTests {
|
||||
public void testSimpleType() {
|
||||
Hello hello = this.testClient.getHello();
|
||||
assertThat(hello).as("hello was null").isNotNull();
|
||||
assertThat(hello).as("first hello didn't match")
|
||||
.isEqualTo(new Hello(HELLO_WORLD_1));
|
||||
assertThat(hello).as("first hello didn't match").isEqualTo(new Hello(HELLO_WORLD_1));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -188,10 +184,8 @@ public class ValidFeignClientTests {
|
||||
public void testRequestInterceptors() {
|
||||
List<String> headers = this.testClient.getHelloHeaders();
|
||||
assertThat(headers).as("headers was null").isNotNull();
|
||||
assertThat(headers.contains("myheader1value"))
|
||||
.as("headers didn't contain myheader1value").isTrue();
|
||||
assertThat(headers.contains("myheader2value"))
|
||||
.as("headers didn't contain myheader2value").isTrue();
|
||||
assertThat(headers.contains("myheader1value")).as("headers didn't contain myheader1value").isTrue();
|
||||
assertThat(headers.contains("myheader2value")).as("headers didn't contain myheader2value").isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -211,12 +205,10 @@ public class ValidFeignClientTests {
|
||||
|
||||
@Test
|
||||
public void testServiceId() {
|
||||
assertThat(this.testClientServiceId).as("testClientServiceId was null")
|
||||
.isNotNull();
|
||||
assertThat(this.testClientServiceId).as("testClientServiceId was null").isNotNull();
|
||||
final Hello hello = this.testClientServiceId.getHello();
|
||||
assertThat(hello).as("The hello response was null").isNotNull();
|
||||
assertThat(hello).as("first hello didn't match")
|
||||
.isEqualTo(new Hello(HELLO_WORLD_1));
|
||||
assertThat(hello).as("first hello didn't match").isEqualTo(new Hello(HELLO_WORLD_1));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -229,8 +221,7 @@ public class ValidFeignClientTests {
|
||||
|
||||
@Test
|
||||
public void testFormattedParams() {
|
||||
List<LocalDate> list = Arrays.asList(LocalDate.of(2001, 1, 1),
|
||||
LocalDate.of(2018, 6, 10));
|
||||
List<LocalDate> list = Arrays.asList(LocalDate.of(2001, 1, 1), LocalDate.of(2018, 6, 10));
|
||||
List<LocalDate> params = this.testClient.getFormattedParams(list);
|
||||
assertThat(params).as("params was null").isNotNull();
|
||||
assertThat(params).as("params not converted correctly").isEqualTo(list);
|
||||
@@ -240,16 +231,14 @@ public class ValidFeignClientTests {
|
||||
public void testNoContentResponse() {
|
||||
ResponseEntity<Void> response = this.testClient.noContent();
|
||||
assertThat(response).as("response was null").isNotNull();
|
||||
assertThat(response.getStatusCode()).as("status code was wrong")
|
||||
.isEqualTo(HttpStatus.NO_CONTENT);
|
||||
assertThat(response.getStatusCode()).as("status code was wrong").isEqualTo(HttpStatus.NO_CONTENT);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHeadResponse() {
|
||||
ResponseEntity<Void> response = this.testClient.head();
|
||||
assertThat(response).as("response was null").isNotNull();
|
||||
assertThat(response.getStatusCode()).as("status code was wrong")
|
||||
.isEqualTo(HttpStatus.OK);
|
||||
assertThat(response.getStatusCode()).as("status code was wrong").isEqualTo(HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -258,24 +247,21 @@ public class ValidFeignClientTests {
|
||||
assertThat(entity).as("entity was null").isNotNull();
|
||||
Hello hello = entity.getBody();
|
||||
assertThat(hello).as("hello was null").isNotNull();
|
||||
assertThat(hello).as("first hello didn't match")
|
||||
.isEqualTo(new Hello(HELLO_WORLD_1));
|
||||
assertThat(hello).as("first hello didn't match").isEqualTo(new Hello(HELLO_WORLD_1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMoreComplexHeader() {
|
||||
String response = this.testClient.moreComplexContentType("{\"value\":\"OK\"}");
|
||||
assertThat(response).as("response was null").isNotNull();
|
||||
assertThat(response).as("didn't respond with {\"value\":\"OK\"}")
|
||||
.isEqualTo("{\"value\":\"OK\"}");
|
||||
assertThat(response).as("didn't respond with {\"value\":\"OK\"}").isEqualTo("{\"value\":\"OK\"}");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDecodeNotFound() {
|
||||
ResponseEntity<String> response = this.decodingTestClient.notFound();
|
||||
assertThat(response).as("response was null").isNotNull();
|
||||
assertThat(response.getStatusCode()).as("status code was wrong")
|
||||
.isEqualTo(HttpStatus.NOT_FOUND);
|
||||
assertThat(response.getStatusCode()).as("status code was wrong").isEqualTo(HttpStatus.NOT_FOUND);
|
||||
assertThat(response.getBody()).as("response body was not null").isNull();
|
||||
}
|
||||
|
||||
@@ -319,8 +305,7 @@ public class ValidFeignClientTests {
|
||||
|
||||
@Test
|
||||
public void testMultipleRequestParts() {
|
||||
MockMultipartFile file = new MockMultipartFile("file", "hello.bin", null,
|
||||
"hello".getBytes());
|
||||
MockMultipartFile file = new MockMultipartFile("file", "hello.bin", null, "hello".getBytes());
|
||||
String response = this.multipartClient.multipart("abc", "123", file);
|
||||
assertThat(response).isEqualTo("abc123hello.bin");
|
||||
}
|
||||
@@ -329,10 +314,8 @@ public class ValidFeignClientTests {
|
||||
public void testMultiplePojoRequestParts() {
|
||||
Hello pojo1 = new Hello(HELLO_WORLD_1);
|
||||
Hello pojo2 = new Hello(OI_TERRA_2);
|
||||
MockMultipartFile file = new MockMultipartFile("file", "hello.bin", null,
|
||||
"hello".getBytes());
|
||||
String response = this.multipartClient.multipartPojo("abc", "123", pojo1, pojo2,
|
||||
file);
|
||||
MockMultipartFile file = new MockMultipartFile("file", "hello.bin", null, "hello".getBytes());
|
||||
String response = this.multipartClient.multipartPojo("abc", "123", pojo1, pojo2, file);
|
||||
assertThat(response).isEqualTo("abc123hello world 1oi terra 2hello.bin");
|
||||
}
|
||||
|
||||
@@ -341,11 +324,9 @@ public class ValidFeignClientTests {
|
||||
List<MultipartFile> multipartFiles = Arrays.asList(
|
||||
new MockMultipartFile("file1", "hello1.bin", null, "hello".getBytes()),
|
||||
new MockMultipartFile("file2", "hello2.bin", null, "hello".getBytes()));
|
||||
String partNames = this.multipartClient
|
||||
.requestPartListOfMultipartFilesReturnsPartNames(multipartFiles);
|
||||
String partNames = this.multipartClient.requestPartListOfMultipartFilesReturnsPartNames(multipartFiles);
|
||||
assertThat(partNames).isEqualTo("files,files");
|
||||
String fileNames = this.multipartClient
|
||||
.requestPartListOfMultipartFilesReturnsFileNames(multipartFiles);
|
||||
String fileNames = this.multipartClient.requestPartListOfMultipartFilesReturnsFileNames(multipartFiles);
|
||||
assertThat(fileNames).contains("hello1.bin", "hello2.bin");
|
||||
}
|
||||
|
||||
@@ -353,42 +334,33 @@ public class ValidFeignClientTests {
|
||||
public void testRequestPartWithListOfPojosAndListOfMultipartFiles() {
|
||||
Hello pojo1 = new Hello(HELLO_WORLD_1);
|
||||
Hello pojo2 = new Hello(OI_TERRA_2);
|
||||
MockMultipartFile file1 = new MockMultipartFile("file1", "hello1.bin", null,
|
||||
"hello".getBytes());
|
||||
MockMultipartFile file2 = new MockMultipartFile("file2", "hello2.bin", null,
|
||||
"hello".getBytes());
|
||||
String response = this.multipartClient
|
||||
.requestPartListOfPojosAndListOfMultipartFiles(
|
||||
Arrays.asList(pojo1, pojo2), Arrays.asList(file1, file2));
|
||||
MockMultipartFile file1 = new MockMultipartFile("file1", "hello1.bin", null, "hello".getBytes());
|
||||
MockMultipartFile file2 = new MockMultipartFile("file2", "hello2.bin", null, "hello".getBytes());
|
||||
String response = this.multipartClient.requestPartListOfPojosAndListOfMultipartFiles(
|
||||
Arrays.asList(pojo1, pojo2), Arrays.asList(file1, file2));
|
||||
assertThat(response).isEqualTo("hello world 1oi terra 2hello1.binhello2.bin");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRequestBodyWithSingleMultipartFile() {
|
||||
String partName = UUID.randomUUID().toString();
|
||||
MockMultipartFile file1 = new MockMultipartFile(partName, "hello1.bin", null,
|
||||
"hello".getBytes());
|
||||
MockMultipartFile file1 = new MockMultipartFile(partName, "hello1.bin", null, "hello".getBytes());
|
||||
String response = this.multipartClient.requestBodySingleMultipartFile(file1);
|
||||
assertThat(response).isEqualTo(partName);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRequestBodyWithListOfMultipartFiles() {
|
||||
MockMultipartFile file1 = new MockMultipartFile("file1", "hello1.bin", null,
|
||||
"hello".getBytes());
|
||||
MockMultipartFile file2 = new MockMultipartFile("file2", "hello2.bin", null,
|
||||
"hello".getBytes());
|
||||
String response = this.multipartClient
|
||||
.requestBodyListOfMultipartFiles(Arrays.asList(file1, file2));
|
||||
MockMultipartFile file1 = new MockMultipartFile("file1", "hello1.bin", null, "hello".getBytes());
|
||||
MockMultipartFile file2 = new MockMultipartFile("file2", "hello2.bin", null, "hello".getBytes());
|
||||
String response = this.multipartClient.requestBodyListOfMultipartFiles(Arrays.asList(file1, file2));
|
||||
assertThat(response).contains("file1", "file2");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRequestBodyWithMap() {
|
||||
MockMultipartFile file1 = new MockMultipartFile("file1", "hello1.bin", null,
|
||||
"hello".getBytes());
|
||||
MockMultipartFile file2 = new MockMultipartFile("file2", "hello2.bin", null,
|
||||
"hello".getBytes());
|
||||
MockMultipartFile file1 = new MockMultipartFile("file1", "hello1.bin", null, "hello".getBytes());
|
||||
MockMultipartFile file2 = new MockMultipartFile("file2", "hello2.bin", null, "hello".getBytes());
|
||||
Map<String, Object> form = new HashMap<>();
|
||||
form.put("file1", file1);
|
||||
form.put("file2", file2);
|
||||
@@ -399,8 +371,7 @@ public class ValidFeignClientTests {
|
||||
|
||||
@Test
|
||||
public void testInvalidMultipartFile() {
|
||||
MockMultipartFile file = new MockMultipartFile("file1", "hello1.bin", null,
|
||||
"hello".getBytes());
|
||||
MockMultipartFile file = new MockMultipartFile("file1", "hello1.bin", null, "hello".getBytes());
|
||||
expected.expect(instanceOf(EncodeException.class));
|
||||
this.multipartClient.invalid(file);
|
||||
}
|
||||
@@ -420,67 +391,51 @@ public class ValidFeignClientTests {
|
||||
protected interface MultipartClient {
|
||||
|
||||
@RequestMapping(method = RequestMethod.POST, path = "/singlePart",
|
||||
consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
|
||||
produces = MediaType.TEXT_PLAIN_VALUE)
|
||||
consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.TEXT_PLAIN_VALUE)
|
||||
String singlePart(@RequestPart("hello") String hello);
|
||||
|
||||
@RequestMapping(method = RequestMethod.POST, path = "/singlePojoPart",
|
||||
consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
|
||||
produces = MediaType.TEXT_PLAIN_VALUE)
|
||||
consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.TEXT_PLAIN_VALUE)
|
||||
String singlePojoPart(@RequestPart("hello") Hello hello);
|
||||
|
||||
@RequestMapping(method = RequestMethod.POST, path = "/multipart",
|
||||
consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
|
||||
produces = MediaType.TEXT_PLAIN_VALUE)
|
||||
String multipart(@RequestPart("hello") String hello,
|
||||
@RequestPart("world") String world,
|
||||
consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.TEXT_PLAIN_VALUE)
|
||||
String multipart(@RequestPart("hello") String hello, @RequestPart("world") String world,
|
||||
@RequestPart("file") MultipartFile file);
|
||||
|
||||
@RequestMapping(method = RequestMethod.POST, path = "/multipartPojo",
|
||||
consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
|
||||
produces = MediaType.TEXT_PLAIN_VALUE)
|
||||
String multipartPojo(@RequestPart("hello") String hello,
|
||||
@RequestPart("world") String world, @RequestPart("pojo1") Hello pojo1,
|
||||
@RequestPart("pojo2") Hello pojo2,
|
||||
consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.TEXT_PLAIN_VALUE)
|
||||
String multipartPojo(@RequestPart("hello") String hello, @RequestPart("world") String world,
|
||||
@RequestPart("pojo1") Hello pojo1, @RequestPart("pojo2") Hello pojo2,
|
||||
@RequestPart("file") MultipartFile file);
|
||||
|
||||
@RequestMapping(method = RequestMethod.POST, path = "/multipartNames",
|
||||
consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
|
||||
produces = MediaType.TEXT_PLAIN_VALUE)
|
||||
String requestPartListOfMultipartFilesReturnsPartNames(
|
||||
@RequestPart("files") List<MultipartFile> files);
|
||||
consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.TEXT_PLAIN_VALUE)
|
||||
String requestPartListOfMultipartFilesReturnsPartNames(@RequestPart("files") List<MultipartFile> files);
|
||||
|
||||
@RequestMapping(method = RequestMethod.POST, path = "/multipartFilenames",
|
||||
consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
|
||||
produces = MediaType.TEXT_PLAIN_VALUE)
|
||||
String requestPartListOfMultipartFilesReturnsFileNames(
|
||||
@RequestPart("files") List<MultipartFile> files);
|
||||
consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.TEXT_PLAIN_VALUE)
|
||||
String requestPartListOfMultipartFilesReturnsFileNames(@RequestPart("files") List<MultipartFile> files);
|
||||
|
||||
@RequestMapping(method = RequestMethod.POST, path = "/multipartPojosFiles",
|
||||
consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
|
||||
produces = MediaType.TEXT_PLAIN_VALUE)
|
||||
String requestPartListOfPojosAndListOfMultipartFiles(
|
||||
@RequestPart("pojos") List<Hello> pojos,
|
||||
consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.TEXT_PLAIN_VALUE)
|
||||
String requestPartListOfPojosAndListOfMultipartFiles(@RequestPart("pojos") List<Hello> pojos,
|
||||
@RequestPart("files") List<MultipartFile> files);
|
||||
|
||||
@RequestMapping(method = RequestMethod.POST, path = "/multipartNames",
|
||||
consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
|
||||
produces = MediaType.TEXT_PLAIN_VALUE)
|
||||
consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.TEXT_PLAIN_VALUE)
|
||||
String requestBodyListOfMultipartFiles(@RequestBody List<MultipartFile> files);
|
||||
|
||||
@RequestMapping(method = RequestMethod.POST, path = "/multipartNames",
|
||||
consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
|
||||
produces = MediaType.TEXT_PLAIN_VALUE)
|
||||
consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.TEXT_PLAIN_VALUE)
|
||||
String requestBodySingleMultipartFile(@RequestBody MultipartFile file);
|
||||
|
||||
@RequestMapping(method = RequestMethod.POST, path = "/multipartNames",
|
||||
consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
|
||||
produces = MediaType.TEXT_PLAIN_VALUE)
|
||||
consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.TEXT_PLAIN_VALUE)
|
||||
String requestBodyMap(@RequestBody Map<String, ?> form);
|
||||
|
||||
@RequestMapping(method = RequestMethod.POST, path = "/invalid",
|
||||
consumes = MediaType.APPLICATION_OCTET_STREAM_VALUE,
|
||||
produces = MediaType.TEXT_PLAIN_VALUE)
|
||||
consumes = MediaType.APPLICATION_OCTET_STREAM_VALUE, produces = MediaType.TEXT_PLAIN_VALUE)
|
||||
String invalid(@RequestBody MultipartFile file);
|
||||
|
||||
}
|
||||
@@ -494,8 +449,7 @@ public class ValidFeignClientTests {
|
||||
@RequestMapping(method = RequestMethod.GET, path = "/hello")
|
||||
Optional<Hello> getOptionalHello();
|
||||
|
||||
@RequestMapping(method = RequestMethod.GET,
|
||||
path = "${feignClient.methodLevelRequestMappingPath}")
|
||||
@RequestMapping(method = RequestMethod.GET, path = "${feignClient.methodLevelRequestMappingPath}")
|
||||
Hello getHelloUsingPropertyPlaceHolder();
|
||||
|
||||
@RequestMapping(method = RequestMethod.GET, path = "/hellos")
|
||||
@@ -515,8 +469,8 @@ public class ValidFeignClientTests {
|
||||
List<String> getParams(@RequestParam("params") List<String> params);
|
||||
|
||||
@RequestMapping(method = RequestMethod.GET, path = "/formattedparams")
|
||||
List<LocalDate> getFormattedParams(@RequestParam("params") @DateTimeFormat(
|
||||
pattern = "dd-MM-yyyy") List<LocalDate> params);
|
||||
List<LocalDate> getFormattedParams(
|
||||
@RequestParam("params") @DateTimeFormat(pattern = "dd-MM-yyyy") List<LocalDate> params);
|
||||
|
||||
@RequestMapping(method = RequestMethod.GET, path = "/noContent")
|
||||
ResponseEntity<Void> noContent();
|
||||
@@ -527,10 +481,8 @@ public class ValidFeignClientTests {
|
||||
@RequestMapping(method = RequestMethod.GET, path = "/hello")
|
||||
HttpEntity<Hello> getHelloEntity();
|
||||
|
||||
@RequestMapping(method = RequestMethod.POST,
|
||||
consumes = "application/vnd.io.spring.cloud.test.v1+json",
|
||||
produces = "application/vnd.io.spring.cloud.test.v1+json",
|
||||
path = "/complex")
|
||||
@RequestMapping(method = RequestMethod.POST, consumes = "application/vnd.io.spring.cloud.test.v1+json",
|
||||
produces = "application/vnd.io.spring.cloud.test.v1+json", path = "/complex")
|
||||
String moreComplexContentType(String body);
|
||||
|
||||
@RequestMapping(method = RequestMethod.GET, path = "/tostring")
|
||||
@@ -606,29 +558,22 @@ public class ValidFeignClientTests {
|
||||
@EnableAutoConfiguration
|
||||
@RestController
|
||||
@EnableFeignClients(
|
||||
clients = { TestClientServiceId.class, TestClient.class,
|
||||
DecodingTestClient.class, MultipartClient.class },
|
||||
clients = { TestClientServiceId.class, TestClient.class, DecodingTestClient.class, MultipartClient.class },
|
||||
defaultConfiguration = TestDefaultFeignConfig.class)
|
||||
@LoadBalancerClients({
|
||||
|
||||
@LoadBalancerClient(name = "localapp",
|
||||
configuration = LocalLoadBalancerClientConfiguration.class),
|
||||
@LoadBalancerClient(name = "localapp", configuration = LocalLoadBalancerClientConfiguration.class),
|
||||
|
||||
@LoadBalancerClient(name = "localapp1",
|
||||
configuration = LocalLoadBalancerClientConfiguration.class),
|
||||
@LoadBalancerClient(name = "localapp1", configuration = LocalLoadBalancerClientConfiguration.class),
|
||||
|
||||
@LoadBalancerClient(name = "localapp2",
|
||||
configuration = LocalLoadBalancerClientConfiguration.class),
|
||||
@LoadBalancerClient(name = "localapp8",
|
||||
configuration = LocalLoadBalancerClientConfiguration.class) })
|
||||
@LoadBalancerClient(name = "localapp2", configuration = LocalLoadBalancerClientConfiguration.class),
|
||||
@LoadBalancerClient(name = "localapp8", configuration = LocalLoadBalancerClientConfiguration.class) })
|
||||
@Import(NoSecurityConfiguration.class)
|
||||
protected static class Application {
|
||||
|
||||
public static void main(String[] args) {
|
||||
new SpringApplicationBuilder(Application.class)
|
||||
.properties("spring.application.name=feignclienttest",
|
||||
"management.contextPath=/admin")
|
||||
.run(args);
|
||||
.properties("spring.application.name=feignclienttest", "management.contextPath=/admin").run(args);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@@ -648,8 +593,7 @@ public class ValidFeignClientTests {
|
||||
}
|
||||
|
||||
@Override
|
||||
public OtherArg parse(String text, Locale locale)
|
||||
throws ParseException {
|
||||
public OtherArg parse(String text, Locale locale) throws ParseException {
|
||||
return new OtherArg(text);
|
||||
}
|
||||
});
|
||||
@@ -696,8 +640,7 @@ public class ValidFeignClientTests {
|
||||
}
|
||||
|
||||
@RequestMapping(method = RequestMethod.GET, path = "/helloheadersplaceholders")
|
||||
public String getHelloHeadersPlaceholders(
|
||||
@RequestHeader("myPlaceholderHeader") String myPlaceholderHeader) {
|
||||
public String getHelloHeadersPlaceholders(@RequestHeader("myPlaceholderHeader") String myPlaceholderHeader) {
|
||||
return myPlaceholderHeader;
|
||||
}
|
||||
|
||||
@@ -707,8 +650,8 @@ public class ValidFeignClientTests {
|
||||
}
|
||||
|
||||
@RequestMapping(method = RequestMethod.GET, path = "/formattedparams")
|
||||
public List<LocalDate> getFormattedParams(@RequestParam("params") @DateTimeFormat(
|
||||
pattern = "dd-MM-yyyy") List<LocalDate> params) {
|
||||
public List<LocalDate> getFormattedParams(
|
||||
@RequestParam("params") @DateTimeFormat(pattern = "dd-MM-yyyy") List<LocalDate> params) {
|
||||
return params;
|
||||
}
|
||||
|
||||
@@ -732,15 +675,11 @@ public class ValidFeignClientTests {
|
||||
return ResponseEntity.status(HttpStatus.NOT_FOUND).body((String) null);
|
||||
}
|
||||
|
||||
@RequestMapping(method = RequestMethod.POST,
|
||||
consumes = "application/vnd.io.spring.cloud.test.v1+json",
|
||||
produces = "application/vnd.io.spring.cloud.test.v1+json",
|
||||
path = "/complex")
|
||||
String complex(@RequestBody String body,
|
||||
@RequestHeader("Content-Length") int contentLength) {
|
||||
@RequestMapping(method = RequestMethod.POST, consumes = "application/vnd.io.spring.cloud.test.v1+json",
|
||||
produces = "application/vnd.io.spring.cloud.test.v1+json", path = "/complex")
|
||||
String complex(@RequestBody String body, @RequestHeader("Content-Length") int contentLength) {
|
||||
if (contentLength <= 0) {
|
||||
throw new IllegalArgumentException(
|
||||
"Invalid Content-Length " + contentLength);
|
||||
throw new IllegalArgumentException("Invalid Content-Length " + contentLength);
|
||||
}
|
||||
return body;
|
||||
}
|
||||
@@ -765,60 +704,47 @@ public class ValidFeignClientTests {
|
||||
}
|
||||
|
||||
@RequestMapping(method = RequestMethod.POST, path = "/singlePart",
|
||||
consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
|
||||
produces = MediaType.TEXT_PLAIN_VALUE)
|
||||
consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.TEXT_PLAIN_VALUE)
|
||||
String singlePart(@RequestPart("hello") String hello) {
|
||||
return hello;
|
||||
}
|
||||
|
||||
@RequestMapping(method = RequestMethod.POST, path = "/singlePojoPart",
|
||||
consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
|
||||
produces = MediaType.TEXT_PLAIN_VALUE)
|
||||
consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.TEXT_PLAIN_VALUE)
|
||||
String singlePojoPart(@RequestPart("hello") Hello hello) {
|
||||
return hello.getMessage();
|
||||
}
|
||||
|
||||
@RequestMapping(method = RequestMethod.POST, path = "/multipart",
|
||||
consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
|
||||
produces = MediaType.TEXT_PLAIN_VALUE)
|
||||
String multipart(@RequestPart("hello") String hello,
|
||||
@RequestPart("world") String world,
|
||||
consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.TEXT_PLAIN_VALUE)
|
||||
String multipart(@RequestPart("hello") String hello, @RequestPart("world") String world,
|
||||
@RequestPart("file") MultipartFile file) {
|
||||
return hello + world + file.getOriginalFilename();
|
||||
}
|
||||
|
||||
@RequestMapping(method = RequestMethod.POST, path = "/multipartPojo",
|
||||
consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
|
||||
produces = MediaType.TEXT_PLAIN_VALUE)
|
||||
String multipartPojo(@RequestPart("hello") String hello,
|
||||
@RequestPart("world") String world, @RequestPart("pojo1") Hello pojo1,
|
||||
@RequestPart("pojo2") Hello pojo2,
|
||||
consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.TEXT_PLAIN_VALUE)
|
||||
String multipartPojo(@RequestPart("hello") String hello, @RequestPart("world") String world,
|
||||
@RequestPart("pojo1") Hello pojo1, @RequestPart("pojo2") Hello pojo2,
|
||||
@RequestPart("file") MultipartFile file) {
|
||||
return hello + world + pojo1.getMessage() + pojo2.getMessage()
|
||||
+ file.getOriginalFilename();
|
||||
return hello + world + pojo1.getMessage() + pojo2.getMessage() + file.getOriginalFilename();
|
||||
}
|
||||
|
||||
@RequestMapping(method = RequestMethod.POST, path = "/multipartNames",
|
||||
consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
|
||||
produces = MediaType.TEXT_PLAIN_VALUE)
|
||||
consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.TEXT_PLAIN_VALUE)
|
||||
String multipartNames(HttpServletRequest request) throws Exception {
|
||||
return request.getParts().stream().map(Part::getName)
|
||||
.collect(Collectors.joining(","));
|
||||
return request.getParts().stream().map(Part::getName).collect(Collectors.joining(","));
|
||||
}
|
||||
|
||||
@RequestMapping(method = RequestMethod.POST, path = "/multipartFilenames",
|
||||
consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
|
||||
produces = MediaType.TEXT_PLAIN_VALUE)
|
||||
consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.TEXT_PLAIN_VALUE)
|
||||
String multipartFilenames(HttpServletRequest request) throws Exception {
|
||||
return request.getParts().stream().map(Part::getSubmittedFileName)
|
||||
.collect(Collectors.joining(","));
|
||||
return request.getParts().stream().map(Part::getSubmittedFileName).collect(Collectors.joining(","));
|
||||
}
|
||||
|
||||
@RequestMapping(method = RequestMethod.POST, path = "/multipartPojosFiles",
|
||||
consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
|
||||
produces = MediaType.TEXT_PLAIN_VALUE)
|
||||
String requestPartListOfPojosAndListOfMultipartFiles(
|
||||
@RequestPart("pojos") List<Hello> pojos,
|
||||
consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.TEXT_PLAIN_VALUE)
|
||||
String requestPartListOfPojosAndListOfMultipartFiles(@RequestPart("pojos") List<Hello> pojos,
|
||||
@RequestPart("files") List<MultipartFile> files) {
|
||||
StringBuilder result = new StringBuilder();
|
||||
|
||||
@@ -891,8 +817,7 @@ public class ValidFeignClientTests {
|
||||
private int port = 0;
|
||||
|
||||
@Bean
|
||||
public ServiceInstanceListSupplier staticServiceInstanceListSupplier(
|
||||
Environment env) {
|
||||
public ServiceInstanceListSupplier staticServiceInstanceListSupplier(Environment env) {
|
||||
return ServiceInstanceListSupplier.fixed(env).instance(port, "local").build();
|
||||
}
|
||||
|
||||
|
||||
@@ -45,10 +45,8 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
|
||||
* @author Ryan Baxter
|
||||
*/
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@SpringBootTest(classes = FeignClientEnvVarTests.Application.class,
|
||||
webEnvironment = RANDOM_PORT,
|
||||
value = { "spring.application.name=feignclienttest",
|
||||
"feign.httpclient.enabled=false",
|
||||
@SpringBootTest(classes = FeignClientEnvVarTests.Application.class, webEnvironment = RANDOM_PORT,
|
||||
value = { "spring.application.name=feignclienttest", "feign.httpclient.enabled=false",
|
||||
"basepackage=org.springframework.cloud.openfeign.testclients" })
|
||||
@DirtiesContext
|
||||
public class FeignClientEnvVarTests {
|
||||
@@ -86,10 +84,8 @@ public class FeignClientEnvVarTests {
|
||||
private int port = 0;
|
||||
|
||||
@Bean
|
||||
public ServiceInstanceListSupplier staticServiceInstanceListSupplier(
|
||||
Environment env) {
|
||||
return ServiceInstanceListSupplier.fixed(env).instance(port, "localapp")
|
||||
.build();
|
||||
public ServiceInstanceListSupplier staticServiceInstanceListSupplier(Environment env) {
|
||||
return ServiceInstanceListSupplier.fixed(env).instance(port, "localapp").build();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -47,9 +47,8 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
|
||||
* @author Spencer Gibb
|
||||
*/
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@SpringBootTest(classes = FeignClientScanningTests.Application.class,
|
||||
webEnvironment = RANDOM_PORT, value = { "spring.application.name=feignclienttest",
|
||||
"feign.httpclient.enabled=false" })
|
||||
@SpringBootTest(classes = FeignClientScanningTests.Application.class, webEnvironment = RANDOM_PORT,
|
||||
value = { "spring.application.name=feignclienttest", "feign.httpclient.enabled=false" })
|
||||
@DirtiesContext
|
||||
public class FeignClientScanningTests {
|
||||
|
||||
@@ -119,8 +118,7 @@ public class FeignClientScanningTests {
|
||||
private int port = 0;
|
||||
|
||||
@Bean
|
||||
public ServiceInstanceListSupplier staticServiceInstanceListSupplier(
|
||||
Environment env) {
|
||||
public ServiceInstanceListSupplier staticServiceInstanceListSupplier(Environment env) {
|
||||
return ServiceInstanceListSupplier.fixed(env).instance(port, "local").build();
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user