Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add CollectionFormat support #371

Merged
merged 3 commits into from
Jul 17, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions docs/src/main/asciidoc/spring-cloud-openfeign.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -586,6 +586,25 @@ public interface DemoTemplate {
}
----

=== Feign `CollectionFormat` support
We support `feign.CollectionFormat` by providing the `@CollectionFormat` annotation. You can annotate a Feign client method with it by passing the desired `feign.CollectionFormat` as annotation value.

In the following example, the `CSV` format is used instead of the default `EXPLODED` to process the method.

[source,java,indent=0]
----
@FeignClient(name = "demo")
protected interface PageableFeignClient {

@CollectionFormat(feign.CollectionFormat.CSV)
@GetMapping(path = "/page")
ResponseEntity performRequest(Pageable page);

}
----

TIP: Set the `CSV` format while sending `Pageable` as a query parameter in order for it to be encoded correctly.

=== Reactive Support
As the https://github.com/OpenFeign/feign[OpenFeign project] does not currently support reactive clients, such as https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/reactive/function/client/WebClient.html[Spring WebClient], neither does Spring Cloud OpenFeign. We will add support for it here as soon as it becomes available in the core project.

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/*
* Copyright 2013-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.springframework.cloud.openfeign;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
* Indicates which collection format should be used while processing the annotated method.
*
* @author Olga Maciaszek-Sharma
* @see feign.CollectionFormat
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CollectionFormat {

/**
* Allows setting the {@link feign.CollectionFormat} to be used while processing the
* annotated method.
* @return the {@link feign.CollectionFormat} to be used
*/
feign.CollectionFormat value();

}
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
import feign.Request;

import org.springframework.cloud.openfeign.AnnotatedParameterProcessor;
import org.springframework.cloud.openfeign.CollectionFormat;
import org.springframework.cloud.openfeign.annotation.MatrixVariableParameterProcessor;
import org.springframework.cloud.openfeign.annotation.PathVariableParameterProcessor;
import org.springframework.cloud.openfeign.annotation.QueryMapParameterProcessor;
Expand Down Expand Up @@ -121,9 +122,9 @@ public SpringMvcContract(
List<AnnotatedParameterProcessor> processors = getDefaultAnnotatedArgumentsProcessors();
processors.addAll(annotatedParameterProcessors);

this.annotatedArgumentProcessors = toAnnotatedArgumentProcessorMap(processors);
annotatedArgumentProcessors = toAnnotatedArgumentProcessorMap(processors);
this.conversionService = conversionService;
this.convertingExpanderFactory = new ConvertingExpanderFactory(conversionService);
convertingExpanderFactory = new ConvertingExpanderFactory(conversionService);
}

private static TypeDescriptor createTypeDescriptor(Method method, int paramIndex) {
Expand Down Expand Up @@ -187,7 +188,7 @@ protected void processAnnotationOnClass(MethodMetadata data, Class<?> clz) {

@Override
public MethodMetadata parseAndValidateMetadata(Class<?> targetType, Method method) {
this.processedMethods.put(Feign.configKey(targetType, method), method);
processedMethods.put(Feign.configKey(targetType, method), method);
MethodMetadata md = super.parseAndValidateMetadata(targetType, method);

RequestMapping classAnnotation = findMergedAnnotation(targetType,
Expand All @@ -213,6 +214,12 @@ public MethodMetadata parseAndValidateMetadata(Class<?> targetType, Method metho
@Override
protected void processAnnotationOnMethod(MethodMetadata data,
Annotation methodAnnotation, Method method) {
if (CollectionFormat.class.isInstance(methodAnnotation)) {
CollectionFormat collectionFormat = findMergedAnnotation(method,
CollectionFormat.class);
data.template().collectionFormat(collectionFormat.value());
}

if (!RequestMapping.class.isInstance(methodAnnotation) && !methodAnnotation
.annotationType().isAnnotationPresent(RequestMapping.class)) {
return;
Expand Down Expand Up @@ -248,13 +255,13 @@ protected void processAnnotationOnMethod(MethodMetadata data,
// headers
parseHeaders(data, method, methodMapping);

data.indexToExpander(new LinkedHashMap<Integer, Param.Expander>());
data.indexToExpander(new LinkedHashMap<>());
}

private String resolve(String value) {
if (StringUtils.hasText(value)
&& this.resourceLoader instanceof ConfigurableApplicationContext) {
return ((ConfigurableApplicationContext) this.resourceLoader).getEnvironment()
&& resourceLoader instanceof ConfigurableApplicationContext) {
return ((ConfigurableApplicationContext) resourceLoader).getEnvironment()
.resolvePlaceholders(value);
}
return value;
Expand All @@ -280,9 +287,9 @@ protected boolean processAnnotationsOnParameter(MethodMetadata data,

AnnotatedParameterProcessor.AnnotatedParameterContext context = new SimpleAnnotatedParameterContext(
data, paramIndex);
Method method = this.processedMethods.get(data.configKey());
Method method = processedMethods.get(data.configKey());
for (Annotation parameterAnnotation : annotations) {
AnnotatedParameterProcessor processor = this.annotatedArgumentProcessors
AnnotatedParameterProcessor processor = annotatedArgumentProcessors
.get(parameterAnnotation.annotationType());
if (processor != null) {
Annotation processParameterAnnotation;
Expand All @@ -298,9 +305,8 @@ protected boolean processAnnotationsOnParameter(MethodMetadata data,
if (!isMultipartFormData(data) && isHttpAnnotation
&& data.indexToExpander().get(paramIndex) == null) {
TypeDescriptor typeDescriptor = createTypeDescriptor(method, paramIndex);
if (this.conversionService.canConvert(typeDescriptor,
STRING_TYPE_DESCRIPTOR)) {
Param.Expander expander = this.convertingExpanderFactory
if (conversionService.canConvert(typeDescriptor, STRING_TYPE_DESCRIPTOR)) {
Param.Expander expander = convertingExpanderFactory
.getExpander(typeDescriptor);
if (expander != null) {
data.indexToExpander().put(paramIndex, expander);
Expand Down Expand Up @@ -419,7 +425,7 @@ public ConvertingExpander(ConversionService conversionService) {

@Override
public String expand(Object value) {
return this.conversionService.convert(value, String.class);
return conversionService.convert(value, String.class);
}

}
Expand All @@ -434,7 +440,7 @@ private static class ConvertingExpanderFactory {

Param.Expander getExpander(TypeDescriptor typeDescriptor) {
return value -> {
Object converted = this.conversionService.convert(value, typeDescriptor,
Object converted = conversionService.convert(value, typeDescriptor,
STRING_TYPE_DESCRIPTOR);
return (String) converted;
};
Expand All @@ -457,17 +463,17 @@ private class SimpleAnnotatedParameterContext

@Override
public MethodMetadata getMethodMetadata() {
return this.methodMetadata;
return methodMetadata;
}

@Override
public int getParameterIndex() {
return this.parameterIndex;
return parameterIndex;
}

@Override
public void setParameterName(String name) {
nameParam(this.methodMetadata, name, this.parameterIndex);
nameParam(methodMetadata, name, parameterIndex);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
/*
* Copyright 2013-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.springframework.cloud.openfeign.support;

import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.openfeign.CollectionFormat;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.cloud.openfeign.test.NoSecurityConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.util.SocketUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import static org.assertj.core.api.Assertions.assertThat;

/**
* @author Olga Maciaszek-Sharma
*/
@SpringBootTest(classes = PageableSupportTest.Config.class,
webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class PageableSupportTest {

@Autowired
private PageableFeignClient feignClient;

@BeforeAll
public static void beforeClass() {
System.setProperty("server.port",
String.valueOf(SocketUtils.findAvailableTcpPort()));
}

@Test
void shouldProperlyFormatPageable() {
String direction = feignClient.performRequest(
PageRequest.of(1, 10, Sort.by(Sort.Order.desc("property"))));

assertThat(direction).isEqualTo("DESC");
}

@FeignClient(name = "pageable", url = "http://localhost:${server.port}/")
protected interface PageableFeignClient {

@CollectionFormat(feign.CollectionFormat.CSV)
@GetMapping(path = "/page")
String performRequest(Pageable page);

}

@SuppressWarnings("ConstantConditions")
@Configuration(proxyBeanMethods = false)
@EnableAutoConfiguration
@RestController
@EnableFeignClients(clients = PageableFeignClient.class)
@Import(NoSecurityConfiguration.class)
protected static class Config {

@GetMapping(path = "/page")
String performRequest(Pageable page) {
return page.getSort().getOrderFor("property").getDirection().toString();
}

}

}
Loading