-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathWebResourceFactory.java
More file actions
434 lines (394 loc) · 18.7 KB
/
WebResourceFactory.java
File metadata and controls
434 lines (394 loc) · 18.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 2012-2015 Oracle and/or its affiliates. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can
* obtain a copy of the License at
* http://glassfish.java.net/public/CDDL+GPL_1_1.html
* or packager/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at packager/legal/LICENSE.txt.
*
* GPL Classpath Exception:
* Oracle designates this particular file as subject to the "Classpath"
* exception as provided by Oracle in the GPL Version 2 section of the License
* file that accompanied this code.
*
* Modifications:
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyright [year] [name of copyright owner]"
*
* Contributor(s):
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*
* Mirth Corporation elects to include this software in this distribution
* under the CDDL license.
*/
package org.glassfish.jersey.client.proxy;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Proxy;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.ws.rs.Consumes;
import javax.ws.rs.CookieParam;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.FormParam;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.HttpMethod;
import javax.ws.rs.MatrixParam;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Cookie;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedHashMap;
import javax.ws.rs.core.MultivaluedMap;
import org.glassfish.jersey.media.multipart.Boundary;
import org.glassfish.jersey.media.multipart.FormDataMultiPart;
import org.glassfish.jersey.media.multipart.FormDataParam;
/**
* Factory for client-side representation of a resource.
* See the <a href="package-summary.html">package overview</a>
* for an example on how to use this class.
*
* @author Martin Matula
*/
public final class WebResourceFactory implements InvocationHandler {
private static final String[] EMPTY = {};
private final WebTarget target;
private final MultivaluedMap<String, Object> headers;
private final List<Cookie> cookies;
private final Form form;
private static final MultivaluedMap<String, Object> EMPTY_HEADERS = new MultivaluedHashMap<>();
private static final Form EMPTY_FORM = new Form();
private static final List<Class> PARAM_ANNOTATION_CLASSES = Arrays.<Class>asList(PathParam.class, QueryParam.class,
HeaderParam.class, CookieParam.class, MatrixParam.class, FormParam.class, FormDataParam.class);
/**
* Creates a new client-side representation of a resource described by
* the interface passed in the first argument.
* <p/>
* Calling this method has the same effect as calling {@code WebResourceFactory.newResource(resourceInterface, rootTarget,
*false)}.
*
* @param <C> Type of the resource to be created.
* @param resourceInterface Interface describing the resource to be created.
* @param target WebTarget pointing to the resource or the parent of the resource.
* @return Instance of a class implementing the resource interface that can
* be used for making requests to the server.
*/
public static <C> C newResource(final Class<C> resourceInterface, final WebTarget target) {
return newResource(resourceInterface, target, false, EMPTY_HEADERS, Collections.<Cookie>emptyList(), EMPTY_FORM);
}
/**
* Creates a new client-side representation of a resource described by
* the interface passed in the first argument.
*
* @param <C> Type of the resource to be created.
* @param resourceInterface Interface describing the resource to be created.
* @param target WebTarget pointing to the resource or the parent of the resource.
* @param ignoreResourcePath If set to true, ignores path annotation on the resource interface (this is used when creating
* sub-resources)
* @param headers Header params collected from parent resources (used when creating a sub-resource)
* @param cookies Cookie params collected from parent resources (used when creating a sub-resource)
* @param form Form params collected from parent resources (used when creating a sub-resource)
* @return Instance of a class implementing the resource interface that can
* be used for making requests to the server.
*/
@SuppressWarnings("unchecked")
public static <C> C newResource(final Class<C> resourceInterface,
final WebTarget target,
final boolean ignoreResourcePath,
final MultivaluedMap<String, Object> headers,
final List<Cookie> cookies,
final Form form) {
return (C) Proxy.newProxyInstance(resourceInterface.getClassLoader(),
new Class[] {resourceInterface},
new WebResourceFactory(ignoreResourcePath ? target : addPathFromAnnotation(resourceInterface, target),
headers, cookies, form));
}
private WebResourceFactory(final WebTarget target, final MultivaluedMap<String, Object> headers,
final List<Cookie> cookies, final Form form) {
this.target = target;
this.headers = headers;
this.cookies = cookies;
this.form = form;
}
@Override
@SuppressWarnings("unchecked")
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
if (args == null && method.getName().equals("toString")) {
return toString();
}
// get the interface describing the resource
final Class<?> proxyIfc = proxy.getClass().getInterfaces()[0];
// response type
final Class<?> responseType = method.getReturnType();
// determine method name
String httpMethod = getHttpMethodName(method);
if (httpMethod == null) {
for (final Annotation ann : method.getAnnotations()) {
httpMethod = getHttpMethodName(ann.annotationType());
if (httpMethod != null) {
break;
}
}
}
// create a new UriBuilder appending the @Path attached to the method
WebTarget newTarget = addPathFromAnnotation(method, target);
if (httpMethod == null) {
if (newTarget == target) {
// no path annotation on the method -> fail
throw new UnsupportedOperationException("Not a resource method.");
} else if (!responseType.isInterface()) {
// the method is a subresource locator, but returns class,
// not interface - can't help here
throw new UnsupportedOperationException("Return type not an interface");
}
}
Consumes parentConsumes = proxyIfc.getAnnotation(Consumes.class);
Consumes consumes = method.getAnnotation(Consumes.class);
if (consumes == null) {
consumes = parentConsumes;
}
boolean isMultiPart = false;
MediaType multiPartType = MediaType.MULTIPART_FORM_DATA_TYPE;
MediaType partType = null;
for (String consumesValue : consumes.value()) {
try {
MediaType mediaType = MediaType.valueOf(consumesValue);
if (multiPartType.isCompatible(mediaType)) {
isMultiPart = true;
multiPartType = Boundary.addBoundary(mediaType);
partType = MediaType.APPLICATION_OCTET_STREAM_TYPE;
if (parentConsumes != null && parentConsumes.value().length > 0) {
try {
partType = MediaType.valueOf(parentConsumes.value()[0]);
} catch (IllegalArgumentException e) {
}
}
break;
}
} catch (IllegalArgumentException e) {
}
}
// process method params (build maps of (Path|Form|FormData|Cookie|Matrix|Header..)Params
// and extract entity type
final MultivaluedHashMap<String, Object> headers = new MultivaluedHashMap<String, Object>(this.headers);
final LinkedList<Cookie> cookies = new LinkedList<>(this.cookies);
final Form form = new Form();
form.asMap().putAll(this.form.asMap());
final Annotation[][] paramAnns = method.getParameterAnnotations();
Object entity = null;
Type entityType = null;
for (int i = 0; i < paramAnns.length; i++) {
final Map<Class, Annotation> anns = new HashMap<>();
for (final Annotation ann : paramAnns[i]) {
anns.put(ann.annotationType(), ann);
}
Annotation ann;
Object value = args[i];
if (!hasAnyParamAnnotation(anns)) {
entityType = method.getGenericParameterTypes()[i];
entity = value;
} else {
if (value == null && (ann = anns.get(DefaultValue.class)) != null) {
value = ((DefaultValue) ann).value();
}
if (value != null) {
if ((ann = anns.get(PathParam.class)) != null) {
newTarget = newTarget.resolveTemplate(((PathParam) ann).value(), value);
} else if ((ann = anns.get((QueryParam.class))) != null) {
if (value instanceof Collection) {
newTarget = newTarget.queryParam(((QueryParam) ann).value(), encodeQueryParams(convert((Collection) value)));
} else {
newTarget = newTarget.queryParam(((QueryParam) ann).value(), encodeQueryParam(value));
}
} else if ((ann = anns.get((HeaderParam.class))) != null) {
if (value instanceof Collection) {
headers.addAll(((HeaderParam) ann).value(), convert((Collection) value));
} else {
headers.addAll(((HeaderParam) ann).value(), value);
}
} else if ((ann = anns.get((CookieParam.class))) != null) {
final String name = ((CookieParam) ann).value();
Cookie c;
if (value instanceof Collection) {
for (final Object v : ((Collection) value)) {
if (!(v instanceof Cookie)) {
c = new Cookie(name, v.toString());
} else {
c = (Cookie) v;
if (!name.equals(((Cookie) v).getName())) {
// is this the right thing to do? or should I fail? or ignore the difference?
c = new Cookie(name, c.getValue(), c.getPath(), c.getDomain(), c.getVersion());
}
}
cookies.add(c);
}
} else {
if (!(value instanceof Cookie)) {
cookies.add(new Cookie(name, value.toString()));
} else {
c = (Cookie) value;
if (!name.equals(((Cookie) value).getName())) {
// is this the right thing to do? or should I fail? or ignore the difference?
cookies.add(new Cookie(name, c.getValue(), c.getPath(), c.getDomain(), c.getVersion()));
}
}
}
} else if ((ann = anns.get((MatrixParam.class))) != null) {
if (value instanceof Collection) {
newTarget = newTarget.matrixParam(((MatrixParam) ann).value(), convert((Collection) value));
} else {
newTarget = newTarget.matrixParam(((MatrixParam) ann).value(), value);
}
} else if ((ann = anns.get((FormParam.class))) != null) {
if (value instanceof Collection) {
for (final Object v : ((Collection) value)) {
form.param(((FormParam) ann).value(), v.toString());
}
} else {
form.param(((FormParam) ann).value(), value.toString());
}
} else if (isMultiPart && (ann = anns.get((FormDataParam.class))) != null) {
if (entity == null || !FormDataMultiPart.class.isAssignableFrom(entity.getClass())) {
entity = new FormDataMultiPart();
}
((FormDataMultiPart) entity).field(((FormDataParam) ann).value(), value, partType);
}
}
}
}
if (httpMethod == null) {
// the method is a subresource locator
return WebResourceFactory.newResource(responseType, newTarget, true, headers, cookies, form);
}
// accepted media types
Produces produces = method.getAnnotation(Produces.class);
if (produces == null) {
produces = proxyIfc.getAnnotation(Produces.class);
}
final String[] accepts = (produces == null) ? EMPTY : produces.value();
// determine content type
String contentType = null;
if (entity != null) {
final List<Object> contentTypeEntries = headers.get(HttpHeaders.CONTENT_TYPE);
if ((contentTypeEntries != null) && (!contentTypeEntries.isEmpty())) {
contentType = contentTypeEntries.get(0).toString();
} else if (isMultiPart) {
contentType = multiPartType.toString();
} else if (consumes != null && consumes.value().length > 0) {
contentType = consumes.value()[0];
}
}
Invocation.Builder builder = newTarget.request()
.headers(headers) // this resets all headers so do this first
.accept(accepts); // if @Produces is defined, propagate values into Accept header; empty array is NO-OP
for (final Cookie c : cookies) {
builder = builder.cookie(c);
}
final Object result;
if (entity == null && !form.asMap().isEmpty()) {
entity = form;
contentType = MediaType.APPLICATION_FORM_URLENCODED;
} else {
if (contentType == null) {
contentType = MediaType.APPLICATION_OCTET_STREAM;
}
if (!form.asMap().isEmpty()) {
if (entity instanceof Form) {
((Form) entity).asMap().putAll(form.asMap());
} else {
// TODO: should at least log some warning here
}
}
}
final GenericType responseGenericType = new GenericType(method.getGenericReturnType());
if (entity != null) {
if (entityType instanceof ParameterizedType) {
entity = new GenericEntity(entity, entityType);
}
result = builder.method(httpMethod, Entity.entity(entity, contentType), responseGenericType);
} else {
result = builder.method(httpMethod, responseGenericType);
}
return result;
}
private boolean hasAnyParamAnnotation(final Map<Class, Annotation> anns) {
for (final Class paramAnnotationClass : PARAM_ANNOTATION_CLASSES) {
if (anns.containsKey(paramAnnotationClass)) {
return true;
}
}
return false;
}
private Object[] convert(final Collection value) {
return value.toArray();
}
private static WebTarget addPathFromAnnotation(final AnnotatedElement ae, WebTarget target) {
final Path p = ae.getAnnotation(Path.class);
if (p != null) {
target = target.path(p.value());
}
return target;
}
@Override
public String toString() {
return target.toString();
}
private static String getHttpMethodName(final AnnotatedElement ae) {
final HttpMethod a = ae.getAnnotation(HttpMethod.class);
return a == null ? null : a.value();
}
private Object[] encodeQueryParams(Object[] values) {
if (values != null) {
for (int i = 0; i < values.length; i++) {
values[i] = encodeQueryParam(values[i]);
}
}
return values;
}
private Object encodeQueryParam(Object value) {
if (value != null) {
String val = value.toString();
if (val != null) {
value = val.replace("{", "%7B").replace("}", "%7D");
}
}
return value;
}
}