Skip to content

Commit aa96dda

Browse files
Modifying Contract to support passing all parameters to encoders OpenFeign#1448 (OpenFeign#1459)
* Modifying Contract to support passing all parameters to encoders * Formatting license * Adding unit tests * Adding AlwaysEncodeBodyContract abstract class (OpenFeign#1)
1 parent f47ce52 commit aa96dda

6 files changed

Lines changed: 183 additions & 8 deletions

File tree

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* Copyright 2012-2021 The Feign Authors
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5+
* in compliance with the License. You may obtain a copy of the License at
6+
*
7+
* http://www.apache.org/licenses/LICENSE-2.0
8+
*
9+
* Unless required by applicable law or agreed to in writing, software distributed under the License
10+
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11+
* or implied. See the License for the specific language governing permissions and limitations under
12+
* the License.
13+
*/
14+
package feign;
15+
16+
/**
17+
* {@link DeclarativeContract} extension that allows user provided custom encoders to define the
18+
* request message payload using only the request template and the method parameters, not requiring
19+
* a specific and unique body object.
20+
*
21+
* This type of contract is useful when an application needs a Feign client whose request payload is
22+
* defined entirely by a custom Feign encoder regardless of how many parameters are declared at the
23+
* client method. In this case, even with no presence of body parameter the provided encoder will
24+
* have to know how to define the request payload (for example, based on the method name, method
25+
* return type, and other metadata provided by custom annotations, all available via the provided
26+
* {@link RequestTemplate} object).
27+
*
28+
* @author fabiocarvalho777@gmail.com
29+
*/
30+
public abstract class AlwaysEncodeBodyContract extends DeclarativeContract {
31+
}

core/src/main/java/feign/Contract.java

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,9 @@ protected MethodMetadata parseAndValidateMetadata(Class<?> targetType, Method me
9696
data.returnType(
9797
Types.resolve(targetType, targetType, method.getGenericReturnType()));
9898
data.configKey(Feign.configKey(targetType, method));
99+
if (AlwaysEncodeBodyContract.class.isAssignableFrom(this.getClass())) {
100+
data.alwaysEncodeBody(true);
101+
}
99102

100103
if (targetType.getInterfaces().length == 1) {
101104
processAnnotationOnClass(data, targetType.getInterfaces()[0]);
@@ -133,7 +136,7 @@ protected MethodMetadata parseAndValidateMetadata(Class<?> targetType, Method me
133136
if (data.isAlreadyProcessed(i)) {
134137
checkState(data.formParams().isEmpty() || data.bodyIndex() == null,
135138
"Body parameters cannot be used with form parameters.%s", data.warnings());
136-
} else {
139+
} else if (!data.alwaysEncodeBody()) {
137140
checkState(data.formParams().isEmpty(),
138141
"Body parameters cannot be used with form parameters.%s", data.warnings());
139142
checkState(data.bodyIndex() == null,

core/src/main/java/feign/DeclarativeContract.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ public final List<MethodMetadata> parseAndValidateMetadata(Class<?> targetType)
4343
* (unless they are the same).
4444
*
4545
* @param data metadata collected so far relating to the current java method.
46-
* @param clz the class to process
46+
* @param targetType the class to process
4747
*/
4848
@Override
4949
protected final void processAnnotationOnClass(MethodMetadata data, Class<?> targetType) {

core/src/main/java/feign/MethodMetadata.java

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/**
2-
* Copyright 2012-2020 The Feign Authors
2+
* Copyright 2012-2021 The Feign Authors
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
55
* in compliance with the License. You may obtain a copy of the License at
@@ -30,6 +30,7 @@ public final class MethodMetadata implements Serializable {
3030
private Integer headerMapIndex;
3131
private Integer queryMapIndex;
3232
private boolean queryMapEncoded;
33+
private boolean alwaysEncodeBody;
3334
private transient Type bodyType;
3435
private final RequestTemplate template = new RequestTemplate();
3536
private final List<String> formParams = new ArrayList<String>();
@@ -118,6 +119,17 @@ public MethodMetadata queryMapEncoded(boolean queryMapEncoded) {
118119
return this;
119120
}
120121

122+
@Experimental
123+
public boolean alwaysEncodeBody() {
124+
return alwaysEncodeBody;
125+
}
126+
127+
@Experimental
128+
MethodMetadata alwaysEncodeBody(boolean alwaysEncodeBody) {
129+
this.alwaysEncodeBody = alwaysEncodeBody;
130+
return this;
131+
}
132+
121133
/**
122134
* Type corresponding to {@link #bodyIndex()}.
123135
*/

core/src/main/java/feign/ReflectiveFeign.java

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/**
2-
* Copyright 2012-2020 The Feign Authors
2+
* Copyright 2012-2021 The Feign Authors
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
55
* in compliance with the License. You may obtain a copy of the License at
@@ -155,7 +155,7 @@ public Map<String, MethodHandler> apply(Target target) {
155155
if (!md.formParams().isEmpty() && md.template().bodyTemplate() == null) {
156156
buildTemplate =
157157
new BuildFormEncodedTemplateFromArgs(md, encoder, queryMapEncoder, target);
158-
} else if (md.bodyIndex() != null) {
158+
} else if (md.bodyIndex() != null || md.alwaysEncodeBody()) {
159159
buildTemplate = new BuildEncodedTemplateFromArgs(md, encoder, queryMapEncoder, target);
160160
} else {
161161
buildTemplate = new BuildTemplateByResolvingArgs(md, queryMapEncoder, target);
@@ -379,10 +379,22 @@ private BuildEncodedTemplateFromArgs(MethodMetadata metadata, Encoder encoder,
379379
protected RequestTemplate resolve(Object[] argv,
380380
RequestTemplate mutable,
381381
Map<String, Object> variables) {
382-
Object body = argv[metadata.bodyIndex()];
383-
checkArgument(body != null, "Body parameter %s was null", metadata.bodyIndex());
382+
383+
boolean alwaysEncodeBody = mutable.methodMetadata().alwaysEncodeBody();
384+
385+
Object body = null;
386+
if (!alwaysEncodeBody) {
387+
body = argv[metadata.bodyIndex()];
388+
checkArgument(body != null, "Body parameter %s was null", metadata.bodyIndex());
389+
}
390+
384391
try {
385-
encoder.encode(body, metadata.bodyType(), mutable);
392+
if (alwaysEncodeBody) {
393+
body = argv == null ? new Object[0] : argv;
394+
encoder.encode(body, Object[].class, mutable);
395+
} else {
396+
encoder.encode(body, metadata.bodyType(), mutable);
397+
}
386398
} catch (EncodeException e) {
387399
throw e;
388400
} catch (RuntimeException e) {
Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
/**
2+
* Copyright 2012-2021 The Feign Authors
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5+
* in compliance with the License. You may obtain a copy of the License at
6+
*
7+
* http://www.apache.org/licenses/LICENSE-2.0
8+
*
9+
* Unless required by applicable law or agreed to in writing, software distributed under the License
10+
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11+
* or implied. See the License for the specific language governing permissions and limitations under
12+
* the License.
13+
*/
14+
package feign;
15+
16+
import feign.codec.EncodeException;
17+
import feign.codec.Encoder;
18+
import org.junit.Assert;
19+
import org.junit.Test;
20+
import java.io.IOException;
21+
import java.lang.annotation.ElementType;
22+
import java.lang.annotation.Retention;
23+
import java.lang.annotation.Target;
24+
import java.lang.reflect.Type;
25+
import java.util.Arrays;
26+
import java.util.stream.Collectors;
27+
import static java.lang.annotation.RetentionPolicy.RUNTIME;
28+
29+
public class AlwaysEncodeBodyContractTest {
30+
31+
@Retention(RUNTIME)
32+
@Target(ElementType.METHOD)
33+
private @interface SampleMethodAnnotation {
34+
}
35+
36+
private static class SampleContract extends AlwaysEncodeBodyContract {
37+
SampleContract() {
38+
AnnotationProcessor<SampleMethodAnnotation> annotationProcessor =
39+
(annotation, metadata) -> metadata.template().method(Request.HttpMethod.POST);
40+
super.registerMethodAnnotation(SampleMethodAnnotation.class, annotationProcessor);
41+
}
42+
}
43+
44+
private interface SampleTargetMultipleNonAnnotatedParameters {
45+
@SampleMethodAnnotation
46+
String concatenate(String word1, String word2, String word3);
47+
}
48+
49+
private interface SampleTargetNoParameters {
50+
@SampleMethodAnnotation
51+
String concatenate();
52+
}
53+
54+
private interface SampleTargetOneParameter {
55+
@SampleMethodAnnotation
56+
String concatenate(String word1);
57+
}
58+
59+
private static class AllParametersSampleEncoder implements Encoder {
60+
@Override
61+
public void encode(Object object, Type bodyType, RequestTemplate template)
62+
throws EncodeException {
63+
Object[] methodParameters = (Object[]) object;
64+
String body =
65+
Arrays.stream(methodParameters).map(String::valueOf).collect(Collectors.joining());
66+
template.body(body);
67+
}
68+
}
69+
70+
private static class BodyParameterSampleEncoder implements Encoder {
71+
@Override
72+
public void encode(Object object, Type bodyType, RequestTemplate template)
73+
throws EncodeException {
74+
template.body(String.valueOf(object));
75+
}
76+
}
77+
78+
private static class SampleClient implements Client {
79+
@Override
80+
public Response execute(Request request, Request.Options options) throws IOException {
81+
return Response.builder()
82+
.status(200)
83+
.request(request)
84+
.body(request.body())
85+
.build();
86+
}
87+
}
88+
89+
/**
90+
* This test makes sure Feign calls the client provided encoder regardless of how many
91+
* non-annotated parameters the client method has, as alwaysEncodeBody is set to true.
92+
*/
93+
@Test
94+
public void alwaysEncodeBodyTrueTest() {
95+
SampleTargetMultipleNonAnnotatedParameters sampleClient1 = Feign.builder()
96+
.contract(new SampleContract())
97+
.encoder(new AllParametersSampleEncoder())
98+
.client(new SampleClient())
99+
.target(SampleTargetMultipleNonAnnotatedParameters.class, "http://localhost");
100+
Assert.assertEquals("foobarchar", sampleClient1.concatenate("foo", "bar", "char"));
101+
102+
SampleTargetNoParameters sampleClient2 = Feign.builder()
103+
.contract(new SampleContract())
104+
.encoder(new AllParametersSampleEncoder())
105+
.client(new SampleClient())
106+
.target(SampleTargetNoParameters.class, "http://localhost");
107+
Assert.assertEquals("", sampleClient2.concatenate());
108+
109+
SampleTargetOneParameter sampleClient3 = Feign.builder()
110+
.contract(new SampleContract())
111+
.encoder(new AllParametersSampleEncoder())
112+
.client(new SampleClient())
113+
.target(SampleTargetOneParameter.class, "http://localhost");
114+
Assert.assertEquals("moo", sampleClient3.concatenate("moo"));
115+
}
116+
117+
}

0 commit comments

Comments
 (0)