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

Modifying Contract to support passing all parameters to encoders #1448 #1459

Merged
merged 6 commits into from
Jul 20, 2021
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
31 changes: 31 additions & 0 deletions core/src/main/java/feign/AlwaysEncodeBodyContract.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/**
* Copyright 2012-2021 The Feign 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
*
* http://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 feign;

/**
* {@link DeclarativeContract} extension that allows user provided custom encoders to define the
* request message payload using only the request template and the method parameters, not requiring
* a specific and unique body object.
*
* This type of contract is useful when an application needs a Feign client whose request payload is
* defined entirely by a custom Feign encoder regardless of how many parameters are declared at the
* client method. In this case, even with no presence of body parameter the provided encoder will
* have to know how to define the request payload (for example, based on the method name, method
* return type, and other metadata provided by custom annotations, all available via the provided
* {@link RequestTemplate} object).
*
* @author fabiocarvalho777@gmail.com
*/
public abstract class AlwaysEncodeBodyContract extends DeclarativeContract {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since the purpose of this class is to allow the body always to be defined by the encoder, there was no need to add alwaysEncodeBody field here.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Notice this class extends DeclarativeContract, instead of BaseContract. That is necessary to take advantage of the annotations processors, which is required for extensions of AlwaysEncodeBodyContract.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

makes sense.

}
5 changes: 4 additions & 1 deletion core/src/main/java/feign/Contract.java
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,9 @@ protected MethodMetadata parseAndValidateMetadata(Class<?> targetType, Method me
data.returnType(
Types.resolve(targetType, targetType, method.getGenericReturnType()));
data.configKey(Feign.configKey(targetType, method));
if (AlwaysEncodeBodyContract.class.isAssignableFrom(this.getClass())) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can't you override this method on the subclass?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

na, I don't think it's possible.
ok, nvm

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This setting is necessary here to avoid having to override this whole method (a copy plus this setting) under AlwaysEncodeBodyContract.

data.alwaysEncodeBody(true);
}

if (targetType.getInterfaces().length == 1) {
processAnnotationOnClass(data, targetType.getInterfaces()[0]);
Expand Down Expand Up @@ -133,7 +136,7 @@ protected MethodMetadata parseAndValidateMetadata(Class<?> targetType, Method me
if (data.isAlreadyProcessed(i)) {
checkState(data.formParams().isEmpty() || data.bodyIndex() == null,
"Body parameters cannot be used with form parameters.%s", data.warnings());
} else {
} else if (!data.alwaysEncodeBody()) {
checkState(data.formParams().isEmpty(),
"Body parameters cannot be used with form parameters.%s", data.warnings());
checkState(data.bodyIndex() == null,
Expand Down
2 changes: 1 addition & 1 deletion core/src/main/java/feign/DeclarativeContract.java
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public final List<MethodMetadata> parseAndValidateMetadata(Class<?> targetType)
* (unless they are the same).
*
* @param data metadata collected so far relating to the current java method.
* @param clz the class to process
* @param targetType the class to process
*/
@Override
protected final void processAnnotationOnClass(MethodMetadata data, Class<?> targetType) {
Expand Down
14 changes: 13 additions & 1 deletion core/src/main/java/feign/MethodMetadata.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/**
* Copyright 2012-2020 The Feign Authors
* Copyright 2012-2021 The Feign 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
Expand Down Expand Up @@ -30,6 +30,7 @@ public final class MethodMetadata implements Serializable {
private Integer headerMapIndex;
private Integer queryMapIndex;
private boolean queryMapEncoded;
private boolean alwaysEncodeBody;
private transient Type bodyType;
private final RequestTemplate template = new RequestTemplate();
private final List<String> formParams = new ArrayList<String>();
Expand Down Expand Up @@ -118,6 +119,17 @@ public MethodMetadata queryMapEncoded(boolean queryMapEncoded) {
return this;
}

@Experimental
public boolean alwaysEncodeBody() {
return alwaysEncodeBody;
}

@Experimental
MethodMetadata alwaysEncodeBody(boolean alwaysEncodeBody) {
velo marked this conversation as resolved.
Show resolved Hide resolved
this.alwaysEncodeBody = alwaysEncodeBody;
return this;
}

/**
* Type corresponding to {@link #bodyIndex()}.
*/
Expand Down
22 changes: 17 additions & 5 deletions core/src/main/java/feign/ReflectiveFeign.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/**
* Copyright 2012-2020 The Feign Authors
* Copyright 2012-2021 The Feign 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
Expand Down Expand Up @@ -155,7 +155,7 @@ public Map<String, MethodHandler> apply(Target target) {
if (!md.formParams().isEmpty() && md.template().bodyTemplate() == null) {
buildTemplate =
new BuildFormEncodedTemplateFromArgs(md, encoder, queryMapEncoder, target);
} else if (md.bodyIndex() != null) {
} else if (md.bodyIndex() != null || md.alwaysEncodeBody()) {
buildTemplate = new BuildEncodedTemplateFromArgs(md, encoder, queryMapEncoder, target);
} else {
buildTemplate = new BuildTemplateByResolvingArgs(md, queryMapEncoder, target);
Expand Down Expand Up @@ -379,10 +379,22 @@ private BuildEncodedTemplateFromArgs(MethodMetadata metadata, Encoder encoder,
protected RequestTemplate resolve(Object[] argv,
RequestTemplate mutable,
Map<String, Object> variables) {
Object body = argv[metadata.bodyIndex()];
checkArgument(body != null, "Body parameter %s was null", metadata.bodyIndex());

boolean alwaysEncodeBody = mutable.methodMetadata().alwaysEncodeBody();

Object body = null;
if (!alwaysEncodeBody) {
body = argv[metadata.bodyIndex()];
checkArgument(body != null, "Body parameter %s was null", metadata.bodyIndex());
}

try {
encoder.encode(body, metadata.bodyType(), mutable);
if (alwaysEncodeBody) {
body = argv == null ? new Object[0] : argv;
encoder.encode(body, Object[].class, mutable);
} else {
encoder.encode(body, metadata.bodyType(), mutable);
}
} catch (EncodeException e) {
throw e;
} catch (RuntimeException e) {
Expand Down
117 changes: 117 additions & 0 deletions core/src/test/java/feign/AlwaysEncodeBodyContractTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
/**
* Copyright 2012-2021 The Feign 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
*
* http://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 feign;

import feign.codec.EncodeException;
import feign.codec.Encoder;
import org.junit.Assert;
import org.junit.Test;
import java.io.IOException;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.stream.Collectors;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

public class AlwaysEncodeBodyContractTest {

@Retention(RUNTIME)
@Target(ElementType.METHOD)
private @interface SampleMethodAnnotation {
}

private static class SampleContract extends AlwaysEncodeBodyContract {
SampleContract() {
AnnotationProcessor<SampleMethodAnnotation> annotationProcessor =
(annotation, metadata) -> metadata.template().method(Request.HttpMethod.POST);
super.registerMethodAnnotation(SampleMethodAnnotation.class, annotationProcessor);
}
}

private interface SampleTargetMultipleNonAnnotatedParameters {
@SampleMethodAnnotation
String concatenate(String word1, String word2, String word3);
}

private interface SampleTargetNoParameters {
@SampleMethodAnnotation
String concatenate();
}

private interface SampleTargetOneParameter {
@SampleMethodAnnotation
String concatenate(String word1);
}

private static class AllParametersSampleEncoder implements Encoder {
@Override
public void encode(Object object, Type bodyType, RequestTemplate template)
throws EncodeException {
Object[] methodParameters = (Object[]) object;
String body =
Arrays.stream(methodParameters).map(String::valueOf).collect(Collectors.joining());
template.body(body);
}
}

private static class BodyParameterSampleEncoder implements Encoder {
@Override
public void encode(Object object, Type bodyType, RequestTemplate template)
throws EncodeException {
template.body(String.valueOf(object));
}
}

private static class SampleClient implements Client {
@Override
public Response execute(Request request, Request.Options options) throws IOException {
return Response.builder()
.status(200)
.request(request)
.body(request.body())
.build();
}
}

/**
* This test makes sure Feign calls the client provided encoder regardless of how many
* non-annotated parameters the client method has, as alwaysEncodeBody is set to true.
*/
@Test
public void alwaysEncodeBodyTrueTest() {
SampleTargetMultipleNonAnnotatedParameters sampleClient1 = Feign.builder()
.contract(new SampleContract())
.encoder(new AllParametersSampleEncoder())
.client(new SampleClient())
.target(SampleTargetMultipleNonAnnotatedParameters.class, "http://localhost");
Assert.assertEquals("foobarchar", sampleClient1.concatenate("foo", "bar", "char"));

SampleTargetNoParameters sampleClient2 = Feign.builder()
.contract(new SampleContract())
.encoder(new AllParametersSampleEncoder())
.client(new SampleClient())
.target(SampleTargetNoParameters.class, "http://localhost");
Assert.assertEquals("", sampleClient2.concatenate());

SampleTargetOneParameter sampleClient3 = Feign.builder()
.contract(new SampleContract())
.encoder(new AllParametersSampleEncoder())
.client(new SampleClient())
.target(SampleTargetOneParameter.class, "http://localhost");
Assert.assertEquals("moo", sampleClient3.concatenate("moo"));
}

}