Skip to content

Commit 7dcab43

Browse files
author
Adrian Cole
committed
Merge pull request OpenFeign#46 from Netflix/enforce-jaxrs
ensure jax-rs annotations are processed from POV of server interfaces
2 parents c323209 + 8a4d5da commit 7dcab43

4 files changed

Lines changed: 151 additions & 44 deletions

File tree

‎CHANGES.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
### Version 4.2/3.3
2+
* Document and enforce JAX-RS annotation processing from server POV
3+
14
### Version 4.1/3.2
25
* update to dagger 1.1
36
* Add wikipedia search example

‎feign-jaxrs/README.md‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# Feign JAXRS
2+
This module overrides annotation processing to instead use standard ones supplied by the JAX-RS specification. This is currently targeted at the 1.1 spec.
3+
4+
## Limitations
5+
While it may appear possible to reuse the same interface across client and server, bear in mind that JAX-RS resource
6+
annotations were not designed to be processed by clients. Moreover, JAX-RS 2.0 has a different package hierarchy for
7+
client invocation. Finally, JAX-RS is a large spec and attempts to implement it completely would be a project larger
8+
than feign itself. In other words, this implementation is *best efforts* and concedes far from 100% compatibility with
9+
server interface behavior.
10+
11+
## Currently Supported Annotation Processing
12+
Feign only supports processing java interfaces (not abstract or concrete classes).
13+
14+
ISE is raised when any annotation's value is empty or null. Ex. `Path("")` raises an ISE.
15+
16+
Here are a list of behaviors currently supported.
17+
### Type Annotations
18+
#### `@Path`
19+
Appends the value to `Target.url()`. Can have tokens corresponding to `@PathParam` annotations.
20+
### Method Annotations
21+
#### `@HttpMethod` meta-annotation (present on `@GET`, `@POST`, etc.)
22+
Sets the request method.
23+
#### `@Path`
24+
Appends the value to `Target.url()`. Can have tokens corresponding to `@PathParam` annotations.
25+
#### `@Produces`
26+
Adds the first value as the `Accept` header.
27+
#### `@Consumes`
28+
Adds the first value as the `Content-Type` header.
29+
### Parameter Annotations
30+
#### `@PathParam`
31+
Links the value of the corresponding parameter to a template variable declared in the path.
32+
#### `@QueryParam`
33+
Links the value of the corresponding parameter to a query parameter.
34+
#### `@HeaderParam`
35+
Links the value of the corresponding parameter to a header.
36+
#### `@FormParam`
37+
Links the value of the corresponding parameter to a key passed to `Encoder.Text<Map<String, Object>>.encode()`.

‎feign-jaxrs/src/main/java/feign/jaxrs/JAXRSModule.java‎

Lines changed: 22 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,12 @@
3333
import java.util.Collection;
3434

3535
import static feign.Util.checkState;
36+
import static feign.Util.emptyToNull;
3637

38+
/**
39+
* Please refer to the
40+
* <a href="https://github.com/Netflix/feign/tree/master/feign-jaxrs">Feign JAX-RS README</a>.
41+
*/
3742
@dagger.Module(library = true, overrides = true)
3843
public final class JAXRSModule {
3944
static final String ACCEPT = "Accept";
@@ -50,7 +55,9 @@ public MethodMetadata parseAndValidatateMetadata(Method method) {
5055
MethodMetadata md = super.parseAndValidatateMetadata(method);
5156
Path path = method.getDeclaringClass().getAnnotation(Path.class);
5257
if (path != null) {
53-
md.template().insert(0, path.value());
58+
String pathValue = emptyToNull(path.value());
59+
checkState(pathValue != null, "Path.value() was empty on type %s", method.getDeclaringClass().getName());
60+
md.template().insert(0, pathValue);
5461
}
5562
return md;
5663
}
@@ -64,19 +71,20 @@ protected void processAnnotationOnMethod(MethodMetadata data, Annotation methodA
6471
"Method %s contains multiple HTTP methods. Found: %s and %s", method.getName(), data.template()
6572
.method(), http.value());
6673
data.template().method(http.value());
67-
} else if (annotationType == Body.class) {
68-
String body = Body.class.cast(methodAnnotation).value();
69-
if (body.indexOf('{') == -1) {
70-
data.template().body(body);
71-
} else {
72-
data.template().bodyTemplate(body);
73-
}
7474
} else if (annotationType == Path.class) {
75+
String pathValue = emptyToNull(Path.class.cast(methodAnnotation).value());
76+
checkState(pathValue != null, "Path.value() was empty on method %s", method.getName());
7577
data.template().append(Path.class.cast(methodAnnotation).value());
7678
} else if (annotationType == Produces.class) {
77-
data.template().header(CONTENT_TYPE, join(',', ((Produces) methodAnnotation).value()));
79+
String[] serverProduces = ((Produces) methodAnnotation).value();
80+
String clientAccepts = serverProduces.length == 0 ? null: emptyToNull(serverProduces[0]);
81+
checkState(clientAccepts != null, "Produces.value() was empty on method %s", method.getName());
82+
data.template().header(ACCEPT, clientAccepts);
7883
} else if (annotationType == Consumes.class) {
79-
data.template().header(ACCEPT, join(',', ((Consumes) methodAnnotation).value()));
84+
String[] serverConsumes = ((Consumes) methodAnnotation).value();
85+
String clientProduces = serverConsumes.length == 0 ? null: emptyToNull(serverConsumes[0]);
86+
checkState(clientProduces != null, "Consumes.value() was empty on method %s", method.getName());
87+
data.template().header(CONTENT_TYPE, clientProduces);
8088
}
8189
}
8290

@@ -87,22 +95,26 @@ protected boolean processAnnotationsOnParameter(MethodMetadata data, Annotation[
8795
Class<? extends Annotation> annotationType = parameterAnnotation.annotationType();
8896
if (annotationType == PathParam.class) {
8997
String name = PathParam.class.cast(parameterAnnotation).value();
98+
checkState(emptyToNull(name) != null, "PathParam.value() was empty on parameter %s", paramIndex);
9099
nameParam(data, name, paramIndex);
91100
isHttpParam = true;
92101
} else if (annotationType == QueryParam.class) {
93102
String name = QueryParam.class.cast(parameterAnnotation).value();
103+
checkState(emptyToNull(name) != null, "QueryParam.value() was empty on parameter %s", paramIndex);
94104
Collection<String> query = addTemplatedParam(data.template().queries().get(name), name);
95105
data.template().query(name, query);
96106
nameParam(data, name, paramIndex);
97107
isHttpParam = true;
98108
} else if (annotationType == HeaderParam.class) {
99109
String name = HeaderParam.class.cast(parameterAnnotation).value();
110+
checkState(emptyToNull(name) != null, "HeaderParam.value() was empty on parameter %s", paramIndex);
100111
Collection<String> header = addTemplatedParam(data.template().headers().get(name), name);
101112
data.template().header(name, header);
102113
nameParam(data, name, paramIndex);
103114
isHttpParam = true;
104115
} else if (annotationType == FormParam.class) {
105116
String name = FormParam.class.cast(parameterAnnotation).value();
117+
checkState(emptyToNull(name) != null, "FormParam.value() was empty on parameter %s", paramIndex);
106118
data.formParams().add(name);
107119
nameParam(data, name, paramIndex);
108120
isHttpParam = true;
@@ -111,17 +123,4 @@ protected boolean processAnnotationsOnParameter(MethodMetadata data, Annotation[
111123
return isHttpParam;
112124
}
113125
}
114-
115-
private static String join(char separator, String... parts) {
116-
if (parts == null || parts.length == 0)
117-
return "";
118-
StringBuilder to = new StringBuilder();
119-
for (int i = 0; i < parts.length; i++) {
120-
to.append(parts[i]);
121-
if (i + 1 < parts.length) {
122-
to.append(separator);
123-
}
124-
}
125-
return to.toString();
126-
}
127126
}

‎feign-jaxrs/src/test/java/feign/jaxrs/JAXRSContractTest.java‎

Lines changed: 89 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -18,13 +18,13 @@
1818
import com.google.common.collect.ImmutableList;
1919
import com.google.common.collect.ImmutableSet;
2020
import com.google.gson.reflect.TypeToken;
21-
import feign.Body;
2221
import feign.MethodMetadata;
2322
import feign.Observable;
2423
import feign.Observer;
2524
import feign.Response;
2625
import org.testng.annotations.Test;
2726

27+
import javax.ws.rs.Consumes;
2828
import javax.ws.rs.DELETE;
2929
import javax.ws.rs.FormParam;
3030
import javax.ws.rs.GET;
@@ -44,14 +44,15 @@
4444
import java.net.URI;
4545
import java.util.List;
4646

47+
import static feign.jaxrs.JAXRSModule.ACCEPT;
4748
import static feign.jaxrs.JAXRSModule.CONTENT_TYPE;
4849
import static javax.ws.rs.HttpMethod.DELETE;
4950
import static javax.ws.rs.HttpMethod.GET;
5051
import static javax.ws.rs.HttpMethod.POST;
5152
import static javax.ws.rs.HttpMethod.PUT;
53+
import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
5254
import static javax.ws.rs.core.MediaType.APPLICATION_XML;
5355
import static org.testng.Assert.assertEquals;
54-
import static org.testng.Assert.assertFalse;
5556
import static org.testng.Assert.assertNull;
5657
import static org.testng.Assert.assertTrue;
5758

@@ -154,21 +155,48 @@ interface WithQueryParamsInPath {
154155
}
155156
}
156157

157-
interface BodyWithoutParameters {
158-
@POST @Produces(APPLICATION_XML) @Body("<v01:getAccountsListOfUser/>") Response post();
158+
interface ProducesAndConsumes {
159+
@GET @Produces(APPLICATION_XML) Response produces();
160+
161+
@GET @Produces({}) Response producesNada();
162+
163+
@GET @Produces({""}) Response producesEmpty();
164+
165+
@POST @Consumes(APPLICATION_JSON) Response consumes();
166+
167+
@POST @Consumes({}) Response consumesNada();
168+
169+
@POST @Consumes({""}) Response consumesEmpty();
170+
}
171+
172+
@Test public void producesAddsAcceptHeader() throws Exception {
173+
MethodMetadata md = contract.parseAndValidatateMetadata(ProducesAndConsumes.class.getDeclaredMethod("produces"));
174+
assertEquals(md.template().headers().get(ACCEPT), ImmutableSet.of(APPLICATION_XML));
175+
}
176+
177+
@Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = "Produces.value\\(\\) was empty on method producesNada")
178+
public void producesNada() throws Exception {
179+
contract.parseAndValidatateMetadata(ProducesAndConsumes.class.getDeclaredMethod("producesNada"));
159180
}
160181

161-
@Test public void bodyWithoutParameters() throws Exception {
162-
MethodMetadata md = contract.parseAndValidatateMetadata(BodyWithoutParameters.class.getDeclaredMethod("post"));
163-
assertEquals(md.template().body(), "<v01:getAccountsListOfUser/>");
164-
assertFalse(md.template().bodyTemplate() != null);
165-
assertTrue(md.formParams().isEmpty());
166-
assertTrue(md.indexToName().isEmpty());
182+
@Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = "Produces.value\\(\\) was empty on method producesEmpty")
183+
public void producesEmpty() throws Exception {
184+
contract.parseAndValidatateMetadata(ProducesAndConsumes.class.getDeclaredMethod("producesEmpty"));
167185
}
168186

169-
@Test public void producesAddsContentTypeHeader() throws Exception {
170-
MethodMetadata md = contract.parseAndValidatateMetadata(BodyWithoutParameters.class.getDeclaredMethod("post"));
171-
assertEquals(md.template().headers().get(CONTENT_TYPE), ImmutableSet.of(APPLICATION_XML));
187+
@Test public void consumesAddsContentTypeHeader() throws Exception {
188+
MethodMetadata md = contract.parseAndValidatateMetadata(ProducesAndConsumes.class.getDeclaredMethod("consumes"));
189+
assertEquals(md.template().headers().get(CONTENT_TYPE), ImmutableSet.of(APPLICATION_JSON));
190+
}
191+
192+
@Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = "Consumes.value\\(\\) was empty on method consumesNada")
193+
public void consumesNada() throws Exception {
194+
contract.parseAndValidatateMetadata(ProducesAndConsumes.class.getDeclaredMethod("consumesNada"));
195+
}
196+
197+
@Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = "Consumes.value\\(\\) was empty on method consumesEmpty")
198+
public void consumesEmpty() throws Exception {
199+
contract.parseAndValidatateMetadata(ProducesAndConsumes.class.getDeclaredMethod("consumesEmpty"));
172200
}
173201

174202
interface BodyParams {
@@ -193,11 +221,23 @@ public void tooManyBodies() throws Exception {
193221
contract.parseAndValidatateMetadata(BodyParams.class.getDeclaredMethod("tooMany", List.class, List.class));
194222
}
195223

196-
@Path("/base")
197-
interface PathOnType {
224+
@Path("") interface EmptyPathOnType {
225+
@GET Response base();
226+
}
227+
228+
@Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = "Path.value\\(\\) was empty on type .*")
229+
public void emptyPathOnType() throws Exception {
230+
contract.parseAndValidatateMetadata(EmptyPathOnType.class.getDeclaredMethod("base"));
231+
}
232+
233+
@Path("/base") interface PathOnType {
198234
@GET Response base();
199235

200236
@GET @Path("/specific") Response get();
237+
238+
@GET @Path("") Response emptyPath();
239+
240+
@GET @Path("/{param}") Response emptyPathParam(@PathParam("") String empty);
201241
}
202242

203243
@Test public void pathOnType() throws Exception {
@@ -207,6 +247,16 @@ interface PathOnType {
207247
assertEquals(md.template().url(), "/base/specific");
208248
}
209249

250+
@Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = "Path.value\\(\\) was empty on method emptyPath")
251+
public void emptyPathOnMethod() throws Exception {
252+
contract.parseAndValidatateMetadata(PathOnType.class.getDeclaredMethod("emptyPath"));
253+
}
254+
255+
@Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = "PathParam.value\\(\\) was empty on parameter 0")
256+
public void emptyPathParam() throws Exception {
257+
contract.parseAndValidatateMetadata(PathOnType.class.getDeclaredMethod("emptyPathParam", String.class));
258+
}
259+
210260
interface WithURIParam {
211261
@GET @Path("/{1}/{2}") Response uriParam(@PathParam("1") String one, URI endpoint, @PathParam("2") String two);
212262
}
@@ -229,6 +279,8 @@ interface WithPathAndQueryParams {
229279
@GET @Path("/domains/{domainId}/records")
230280
Response recordsByNameAndType(@PathParam("domainId") int id, @QueryParam("name") String nameFilter,
231281
@QueryParam("type") String typeFilter);
282+
283+
@GET Response emptyQueryParam(@QueryParam("") String empty);
232284
}
233285

234286
@Test public void mixedRequestLineParams() throws Exception {
@@ -246,29 +298,40 @@ Response recordsByNameAndType(@PathParam("domainId") int id, @QueryParam("name")
246298
assertEquals(md.template().toString(), "GET /domains/{domainId}/records?name={name}&type={type} HTTP/1.1\n");
247299
}
248300

301+
@Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = "QueryParam.value\\(\\) was empty on parameter 0")
302+
public void emptyQueryParam() throws Exception {
303+
contract.parseAndValidatateMetadata(WithPathAndQueryParams.class.getDeclaredMethod("emptyQueryParam", String.class));
304+
}
305+
249306
interface FormParams {
250-
@POST
251-
@Body("%7B\"customer_name\": \"{customer_name}\", \"user_name\": \"{user_name}\", \"password\": \"{password}\"%7D")
252-
void login(
307+
@POST void login(
253308
@FormParam("customer_name") String customer,
254309
@FormParam("user_name") String user, @FormParam("password") String password);
310+
311+
@GET Response emptyFormParam(@FormParam("") String empty);
255312
}
256313

257314
@Test public void formParamsParseIntoIndexToName() throws Exception {
258315
MethodMetadata md = contract.parseAndValidatateMetadata(FormParams.class.getDeclaredMethod("login", String.class,
259316
String.class, String.class));
260317

261-
assertFalse(md.template().body() != null);
262-
assertEquals(md.template().bodyTemplate(),
263-
"%7B\"customer_name\": \"{customer_name}\", \"user_name\": \"{user_name}\", \"password\": \"{password}\"%7D");
318+
assertNull(md.template().body());
319+
assertNull(md.template().bodyTemplate());
264320
assertEquals(md.formParams(), ImmutableList.of("customer_name", "user_name", "password"));
265321
assertEquals(md.indexToName().get(0), ImmutableSet.of("customer_name"));
266322
assertEquals(md.indexToName().get(1), ImmutableSet.of("user_name"));
267323
assertEquals(md.indexToName().get(2), ImmutableSet.of("password"));
268324
}
269325

326+
@Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = "FormParam.value\\(\\) was empty on parameter 0")
327+
public void emptyFormParam() throws Exception {
328+
contract.parseAndValidatateMetadata(FormParams.class.getDeclaredMethod("emptyFormParam", String.class));
329+
}
330+
270331
interface HeaderParams {
271332
@POST void logout(@HeaderParam("Auth-Token") String token);
333+
334+
@GET Response emptyHeaderParam(@HeaderParam("") String empty);
272335
}
273336

274337
@Test public void headerParamsParseIntoIndexToName() throws Exception {
@@ -278,6 +341,11 @@ interface HeaderParams {
278341
assertEquals(md.indexToName().get(0), ImmutableSet.of("Auth-Token"));
279342
}
280343

344+
@Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = "HeaderParam.value\\(\\) was empty on parameter 0")
345+
public void emptyHeaderParam() throws Exception {
346+
contract.parseAndValidatateMetadata(HeaderParams.class.getDeclaredMethod("emptyHeaderParam", String.class));
347+
}
348+
281349
interface WithObservable {
282350
@GET @Path("/") Observable<List<String>> valid();
283351

0 commit comments

Comments
 (0)