Skip to content

Commit 8aeeed6

Browse files
committed
Add QueryMap annotation
Support annotating a Map parameter with QueryMap to specify that its contents should be used as the query parameters for a request.
1 parent 4b9fd73 commit 8aeeed6

8 files changed

Lines changed: 276 additions & 6 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
### Version 8.16
2+
* Adds `@QueryMap` annotation to support dynamic query parameters
3+
14
### Version 8.15
25
* Supports PUT without a body parameter
36
* Supports substitutions in `@Headers` like in `@Body`. (#326)
@@ -53,7 +56,7 @@
5356
It is suggested that you simply return a new instance of your Retryer class.
5457

5558
### Version 8.3
56-
* Adds client implementation for Apache Http Client
59+
* Adds client implementation for Apache Http Client
5760

5861
### Version 8.2
5962
* Allows customized request construction by exposing `Request.create()`
@@ -187,7 +190,7 @@
187190
* Default Encoder and Form Encoder is `Encoder.Text<Object>`
188191
* Default Decoder is `Decoder.TextStream<Object>`
189192
* ErrorDecoder now returns Exception, not fallback.
190-
* There can only be one `ErrorDecoder` and `Request.Options` binding now.
193+
* There can only be one `ErrorDecoder` and `Request.Options` binding now.
191194

192195
### Version 2.0.0
193196
* removes guava and jax-rs dependencies

‎README.md‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,7 @@ interface GitHub {
130130
```java
131131
GitHub github = Feign.builder()
132132
.contract(new JAXRSContract())
133-
.target(GitHub.class, "https://api.github.com");
133+
.target(GitHub.class, "https://api.github.com");
134134
```
135135
### OkHttp
136136
[OkHttpClient](https://github.com/Netflix/feign/tree/master/okhttp) directs Feign's http requests to [OkHttp](http://square.github.io/okhttp/), which enables SPDY and better network control.
@@ -339,3 +339,11 @@ for example formatting dates.
339339
```java
340340
@RequestLine("GET /?since={date}") Result list(@Param(value = "date", expander = DateToMillis.class) Date date);
341341
```
342+
343+
#### Dynamic Query Parameters
344+
A Map parameter can be annotated with `QueryMap` to construct a query that uses the contents of the map as its query parameters.
345+
346+
```java
347+
@RequestLine("GET /find")
348+
V find(@QueryMap Map<String, Object>);
349+
```

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

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,12 @@ protected MethodMetadata parseAndValidateMetadata(Class<?> targetType, Method me
113113
data.bodyType(Types.resolve(targetType, targetType, method.getGenericParameterTypes()[i]));
114114
}
115115
}
116+
117+
if (data.queryMapIndex() != null) {
118+
checkState(Map.class.isAssignableFrom(parameterTypes[data.queryMapIndex()]),
119+
"QueryMap parameter must be a Map: %s", parameterTypes[data.queryMapIndex()]);
120+
}
121+
116122
return data;
117123
}
118124

@@ -248,6 +254,10 @@ protected boolean processAnnotationsOnParameter(MethodMetadata data, Annotation[
248254
!searchMapValuesContainsSubstring(data.template().headers(), varName)) {
249255
data.formParams().add(name);
250256
}
257+
} else if (annotationType == QueryMap.class) {
258+
checkState(data.queryMapIndex() == null, "QueryMap annotation was present on multiple parameters.");
259+
data.queryMapIndex(paramIndex);
260+
isHttpAnnotation = true;
251261
}
252262
}
253263
return isHttpAnnotation;

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

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@
2222
import java.util.LinkedHashMap;
2323
import java.util.List;
2424
import java.util.Map;
25+
import java.util.Set;
26+
import java.util.TreeSet;
2527

2628
import feign.Param.Expander;
2729

@@ -32,6 +34,7 @@ public final class MethodMetadata implements Serializable {
3234
private transient Type returnType;
3335
private Integer urlIndex;
3436
private Integer bodyIndex;
37+
private Integer queryMapIndex;
3538
private transient Type bodyType;
3639
private RequestTemplate template = new RequestTemplate();
3740
private List<String> formParams = new ArrayList<String>();
@@ -82,6 +85,15 @@ public MethodMetadata bodyIndex(Integer bodyIndex) {
8285
return this;
8386
}
8487

88+
public Integer queryMapIndex() {
89+
return queryMapIndex;
90+
}
91+
92+
public MethodMetadata queryMapIndex(Integer queryMapIndex) {
93+
this.queryMapIndex = queryMapIndex;
94+
return this;
95+
}
96+
8597
/**
8698
* Type corresponding to {@link #bodyIndex()}.
8799
*/
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
/*
2+
* Copyright 2015 Netflix, Inc.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package feign;
17+
18+
import java.lang.annotation.Retention;
19+
import java.util.List;
20+
import java.util.Map;
21+
22+
import static java.lang.annotation.ElementType.PARAMETER;
23+
import static java.lang.annotation.RetentionPolicy.RUNTIME;
24+
25+
/**
26+
* A template parameter that can be applied to a Map that contains query
27+
* parameters, where the keys are Strings that are the parameter names and the
28+
* values are the parameter values. The queries specified by the map will be
29+
* applied to the request after all other processing, and will take precedence
30+
* over any previously specified query parameters. It is not necessary to
31+
* reference the parameter map as a variable. <br>
32+
* <br>
33+
* <pre>
34+
* ...
35+
* &#64;RequestLine("POST /servers")
36+
* void servers(&#64;QueryMap Map<String, String>);
37+
* ...
38+
*
39+
* &#64;RequestLine("GET /servers/{serverId}?count={count}")
40+
* void get(&#64;Param("serverId") String serverId, &#64;Param("count") int count, &#64;QueryMap Map<String, Object>);
41+
* ...
42+
* </pre>
43+
* The annotated parameter must be an instance of {@link Map}, and the keys must
44+
* be Strings. The query value of a key will be the value of its toString
45+
* method, except in the following cases:
46+
* <br>
47+
* <br>
48+
* <ul>
49+
* <li>if the value is null, the value will remain null (rather than converting
50+
* to the String "null")
51+
* <li>if the value is an {@link Iterable}, it is converted to a {@link List} of
52+
* String objects where each value in the list is either null if the original
53+
* value was null or the value's toString representation otherwise.
54+
* </ul>
55+
* <br>
56+
* Once this conversion is applied, the query keys and resulting String values
57+
* follow the same contract as if they were set using
58+
* {@link RequestTemplate#query(String, String...)}.
59+
*/
60+
@Retention(RUNTIME)
61+
@java.lang.annotation.Target(PARAMETER)
62+
public @interface QueryMap {
63+
}

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

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,9 @@
1818
import java.lang.reflect.InvocationHandler;
1919
import java.lang.reflect.Method;
2020
import java.lang.reflect.Proxy;
21+
import java.util.ArrayList;
2122
import java.util.Collection;
23+
import java.util.Iterator;
2224
import java.util.LinkedHashMap;
2325
import java.util.List;
2426
import java.util.Map;
@@ -34,6 +36,7 @@
3436

3537
import static feign.Util.checkArgument;
3638
import static feign.Util.checkNotNull;
39+
import static feign.Util.checkState;
3740

3841
public class ReflectiveFeign extends Feign {
3942

@@ -196,7 +199,39 @@ public RequestTemplate create(Object[] argv) {
196199
}
197200
}
198201
}
199-
return resolve(argv, mutable, varBuilder);
202+
203+
RequestTemplate template = resolve(argv, mutable, varBuilder);
204+
if (metadata.queryMapIndex() != null) {
205+
// add query map parameters after initial resolve so that they take
206+
// precedence over any predefined values
207+
template = addQueryMapQueryParameters(argv, template);
208+
}
209+
210+
return template;
211+
}
212+
213+
@SuppressWarnings("unchecked")
214+
private RequestTemplate addQueryMapQueryParameters(Object[] argv, RequestTemplate mutable) {
215+
Map<Object, Object> queryMap = (Map<Object, Object>) argv[metadata.queryMapIndex()];
216+
for (Entry<Object, Object> currEntry : queryMap.entrySet()) {
217+
checkState(currEntry.getKey().getClass() == String.class, "QueryMap key must be a String: %s", currEntry.getKey());
218+
219+
Collection<String> values = new ArrayList<String>();
220+
221+
Object currValue = currEntry.getValue();
222+
if (currValue instanceof Iterable<?>) {
223+
Iterator<?> iter = ((Iterable<?>) currValue).iterator();
224+
while (iter.hasNext()) {
225+
Object nextObject = iter.next();
226+
values.add(nextObject == null ? null : nextObject.toString());
227+
}
228+
} else {
229+
values.add(currValue == null ? null : currValue.toString());
230+
}
231+
232+
mutable.query((String) currEntry.getKey(), values);
233+
}
234+
return mutable;
200235
}
201236

202237
protected RequestTemplate resolve(Object[] argv, RequestTemplate mutable,

‎core/src/test/java/feign/DefaultContractTest.java‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717

1818
import com.google.gson.reflect.TypeToken;
1919

20+
import org.assertj.core.api.Fail;
2021
import org.junit.Rule;
2122
import org.junit.Test;
2223
import org.junit.rules.ExpectedException;
@@ -26,6 +27,7 @@
2627
import java.util.LinkedHashMap;
2728
import java.util.List;
2829
import java.util.Map;
30+
import java.util.SortedMap;
2931

3032
import static feign.assertj.FeignAssertions.assertThat;
3133
import static java.util.Arrays.asList;
@@ -260,6 +262,40 @@ public void customExpander() throws Exception {
260262
.containsExactly(entry(0, DateToMillis.class));
261263
}
262264

265+
@Test
266+
public void queryMap() throws Exception {
267+
MethodMetadata md = parseAndValidateMetadata(QueryMapTestInterface.class, "queryMap", Map.class);
268+
269+
assertThat(md.queryMapIndex()).isEqualTo(0);
270+
}
271+
272+
@Test
273+
public void queryMapMapSubclass() throws Exception {
274+
MethodMetadata md = parseAndValidateMetadata(QueryMapTestInterface.class, "queryMapMapSubclass", SortedMap.class);
275+
276+
assertThat(md.queryMapIndex()).isEqualTo(0);
277+
}
278+
279+
@Test
280+
public void onlyOneQueryMapAnnotationPermitted() throws Exception {
281+
try {
282+
parseAndValidateMetadata(QueryMapTestInterface.class, "multipleQueryMap", Map.class, Map.class);
283+
Fail.failBecauseExceptionWasNotThrown(IllegalStateException.class);
284+
} catch (IllegalStateException ex) {
285+
assertThat(ex).hasMessage("QueryMap annotation was present on multiple parameters.");
286+
}
287+
}
288+
289+
@Test
290+
public void queryMapMustBeInstanceOfMap() throws Exception {
291+
try {
292+
parseAndValidateMetadata(QueryMapTestInterface.class, "nonMapQueryMap", String.class);
293+
Fail.failBecauseExceptionWasNotThrown(IllegalStateException.class);
294+
} catch (IllegalStateException ex) {
295+
assertThat(ex).hasMessage("QueryMap parameter must be a Map: class java.lang.String");
296+
}
297+
}
298+
263299
@Test
264300
public void slashAreEncodedWhenNeeded() throws Exception {
265301
MethodMetadata md = parseAndValidateMetadata(SlashNeedToBeEncoded.class,
@@ -392,6 +428,23 @@ public String expand(Object value) {
392428
}
393429
}
394430

431+
interface QueryMapTestInterface {
432+
433+
@RequestLine("POST /")
434+
void queryMap(@QueryMap Map<String, String> queryMap);
435+
436+
@RequestLine("POST /")
437+
void queryMapMapSubclass(@QueryMap SortedMap<String, String> queryMap);
438+
439+
// invalid
440+
@RequestLine("POST /")
441+
void multipleQueryMap(@QueryMap Map<String, String> mapOne, @QueryMap Map<String, String> mapTwo);
442+
443+
// invalid
444+
@RequestLine("POST /")
445+
void nonMapQueryMap(@QueryMap String notAMap);
446+
}
447+
395448
interface SlashNeedToBeEncoded {
396449
@RequestLine(value = "GET /api/queues/{vhost}", decodeSlash = false)
397450
String getQueues(@Param("vhost") String vhost);

0 commit comments

Comments
 (0)