/
MethodModel.java
681 lines (618 loc) · 31 KB
/
MethodModel.java
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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
/*
* Copyright (c) 2019 Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2019 Payara Foundation and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0, which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the
* Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
* version 2 with the GNU Classpath Exception, which is available at
* https://www.gnu.org/software/classpath/license.html.
*
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
package org.glassfish.jersey.microprofile.restclient;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Proxy;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import javax.enterprise.inject.spi.BeanManager;
import javax.enterprise.inject.spi.InterceptionType;
import javax.enterprise.inject.spi.Interceptor;
import javax.json.JsonValue;
import javax.ws.rs.Consumes;
import javax.ws.rs.CookieParam;
import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
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.WebApplicationException;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Form;
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 javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import org.eclipse.microprofile.rest.client.RestClientDefinitionException;
import org.eclipse.microprofile.rest.client.annotation.ClientHeaderParam;
import org.eclipse.microprofile.rest.client.ext.AsyncInvocationInterceptor;
import org.eclipse.microprofile.rest.client.ext.ResponseExceptionMapper;
/**
* Method model contains all information about method defined in rest client interface.
*
* @author David Kral
* @author Patrik Dudits
* @author Tomas Langer
*/
class MethodModel {
private static final String INVOKED_METHOD = "org.eclipse.microprofile.rest.client.invokedMethod";
private final InterfaceModel interfaceModel;
private final Method method;
private final GenericType<?> returnType;
private final String httpMethod;
private final String path;
private final String[] produces;
private final String[] consumes;
private final List<ParamModel> parameterModels;
private final List<ClientHeaderParamModel> clientHeaders;
private final List<InterceptorInvocationContext.InvocationInterceptor> invocationInterceptors;
private final RestClientModel subResourceModel;
/**
* Processes interface method and creates new instance of the model.
*
* @param interfaceModel
* @param method
* @return
*/
static MethodModel from(InterfaceModel interfaceModel, Method method) {
return new Builder(interfaceModel, method).build();
}
private MethodModel(Builder builder) {
this.method = builder.method;
this.interfaceModel = builder.interfaceModel;
this.returnType = builder.returnType;
this.httpMethod = builder.httpMethod;
this.path = builder.pathValue;
this.produces = builder.produces;
this.consumes = builder.consumes;
this.parameterModels = builder.parameterModels;
this.clientHeaders = builder.clientHeaders;
this.invocationInterceptors = builder.invocationInterceptors;
if (httpMethod.isEmpty()) {
subResourceModel = RestClientModel.from(returnType.getRawType(),
interfaceModel.getResponseExceptionMappers(),
interfaceModel.getParamConverterProviders(),
interfaceModel.getAsyncInterceptors(),
interfaceModel.getInjectionManager(),
interfaceModel.getBeanManager());
} else {
subResourceModel = null;
}
}
/**
* Returns all registered cdi interceptors to this method.
*
* @return registered interceptors
*/
List<InterceptorInvocationContext.InvocationInterceptor> getInvocationInterceptors() {
return invocationInterceptors;
}
/**
* Invokes corresponding method according to
*
* @param classLevelTarget
* @param method
* @param args
* @return
*/
@SuppressWarnings("unchecked")
//I am checking the type of parameter and I know it should handle instance I am sending
Object invokeMethod(WebTarget classLevelTarget, Method method, Object[] args) {
WebTarget methodLevelTarget = classLevelTarget.path(path);
AtomicReference<Object> entity = new AtomicReference<>();
AtomicReference<WebTarget> webTargetAtomicReference = new AtomicReference<>(methodLevelTarget);
parameterModels.stream()
.filter(parameterModel -> parameterModel.handles(PathParam.class))
.forEach(parameterModel ->
webTargetAtomicReference.set((WebTarget)
parameterModel
.handleParameter(webTargetAtomicReference.get(),
PathParam.class,
args[parameterModel
.getParamPosition()])));
parameterModels.stream()
.filter(ParamModel::isEntity)
.findFirst()
.ifPresent(parameterModel -> entity.set(args[parameterModel.getParamPosition()]));
Form form = handleForm(args);
WebTarget webTarget = webTargetAtomicReference.get();
if (httpMethod.isEmpty()) {
//sub resource method
return subResourceProxy(webTarget, returnType.getRawType());
}
webTarget = addQueryParams(webTarget, args);
webTarget = addMatrixParams(webTarget, args);
Invocation.Builder builder = webTarget
.request(produces)
.property(INVOKED_METHOD, method)
.headers(addCustomHeaders(args));
builder = addCookies(builder, args);
Object entityToUse = entity.get();
if (entityToUse == null && !form.asMap().isEmpty()) {
entityToUse = form;
}
Object response;
if (CompletionStage.class.isAssignableFrom(method.getReturnType())) {
response = asynchronousCall(builder, entityToUse, method);
} else {
response = synchronousCall(builder, entityToUse, method);
}
return response;
}
@SuppressWarnings("unchecked")
private Form handleForm(Object[] args) {
final Form form = new Form();
parameterModels.stream()
.filter(parameterModel -> parameterModel.handles(FormParam.class))
.forEach(parameterModel -> parameterModel.handleParameter(form,
FormParam.class,
args[parameterModel.getParamPosition()]));
return form;
}
private Object synchronousCall(Invocation.Builder builder, Object entity, Method method) {
Response response;
if (entity != null
&& !httpMethod.equals(GET.class.getSimpleName())
&& !httpMethod.equals(DELETE.class.getSimpleName())) {
response = builder.method(httpMethod, Entity.entity(entity, consumes[0]));
} else {
response = builder.method(httpMethod);
}
evaluateResponse(response, method);
if (returnType.getType().equals(Void.class)) {
return null;
} else if (returnType.getType().equals(Response.class)) {
return response;
}
return response.readEntity(returnType);
}
private CompletableFuture asynchronousCall(Invocation.Builder builder, Object entity, Method method) {
CompletableFuture<Object> result = new CompletableFuture<>();
Future<Response> theFuture;
if (entity != null
&& !httpMethod.equals(GET.class.getSimpleName())
&& !httpMethod.equals(DELETE.class.getSimpleName())) {
theFuture = builder.async().method(httpMethod, Entity.entity(entity, consumes[0]));
} else {
theFuture = builder.async().method(httpMethod);
}
CompletableFuture<Response> completableFuture = (CompletableFuture<Response>) theFuture;
completableFuture.thenAccept(response -> {
interfaceModel.getAsyncInterceptors().forEach(AsyncInvocationInterceptor::removeContext);
try {
evaluateResponse(response, method);
if (returnType.getType().equals(Void.class)) {
result.complete(null);
} else if (returnType.getType().equals(Response.class)) {
result.complete(response);
} else {
result.complete(response.readEntity(returnType));
}
} catch (Exception e) {
result.completeExceptionally(e);
}
}).exceptionally(throwable -> {
interfaceModel.getAsyncInterceptors().forEach(AsyncInvocationInterceptor::removeContext);
result.completeExceptionally(throwable);
return null;
});
return result;
}
@SuppressWarnings("unchecked")
private <T> T subResourceProxy(WebTarget webTarget, Class<T> subResourceType) {
return (T) Proxy.newProxyInstance(subResourceType.getClassLoader(),
new Class[] {subResourceType},
new ProxyInvocationHandler(webTarget, subResourceModel)
);
}
@SuppressWarnings("unchecked") //I am checking the type of parameter and I know it should handle instance I am sending
private WebTarget addQueryParams(WebTarget webTarget, Object[] args) {
Map<String, Object[]> queryParams = new HashMap<>();
WebTarget toReturn = webTarget;
parameterModels.stream()
.filter(parameterModel -> parameterModel.handles(QueryParam.class))
.forEach(parameterModel -> parameterModel.handleParameter(queryParams,
QueryParam.class,
args[parameterModel.getParamPosition()]));
for (Map.Entry<String, Object[]> entry : queryParams.entrySet()) {
toReturn = toReturn.queryParam(entry.getKey(), entry.getValue());
}
return toReturn;
}
@SuppressWarnings("unchecked") //I am checking the type of parameter and I know it should handle instance I am sending
private WebTarget addMatrixParams(WebTarget webTarget, Object[] args) {
AtomicReference<WebTarget> toReturn = new AtomicReference<>(webTarget);
parameterModels.stream()
.filter(parameterModel -> parameterModel.handles(MatrixParam.class))
.forEach(parameterModel -> toReturn
.set((WebTarget) parameterModel.handleParameter(toReturn.get(),
MatrixParam.class,
args[parameterModel.getParamPosition()])));
return toReturn.get();
}
@SuppressWarnings("unchecked") //I am checking the type of parameter and I know it should handle instance I am sending
private Invocation.Builder addCookies(Invocation.Builder builder, Object[] args) {
Map<String, String> cookies = new HashMap<>();
Invocation.Builder toReturn = builder;
parameterModels.stream()
.filter(parameterModel -> parameterModel.handles(CookieParam.class))
.forEach(parameterModel -> parameterModel.handleParameter(cookies,
CookieParam.class,
args[parameterModel.getParamPosition()]));
for (Map.Entry<String, String> entry : cookies.entrySet()) {
toReturn = toReturn.cookie(entry.getKey(), entry.getValue());
}
return toReturn;
}
private MultivaluedMap<String, Object> addCustomHeaders(Object[] args) {
MultivaluedMap<String, Object> result = new MultivaluedHashMap<>();
for (Map.Entry<String, List<String>> entry : resolveCustomHeaders(args).entrySet()) {
entry.getValue().forEach(val -> result.add(entry.getKey(), val));
}
for (String produce : produces) {
result.add(HttpHeaders.ACCEPT, produce);
}
result.add(HttpHeaders.CONTENT_TYPE, consumes[0]);
return result;
}
@SuppressWarnings("unchecked") //I am checking the type of parameter and I know it should handle instance I am sending
private MultivaluedMap<String, String> resolveCustomHeaders(Object[] args) {
MultivaluedMap<String, String> customHeaders = new MultivaluedHashMap<>();
customHeaders.putAll(createMultivaluedHeadersMap(interfaceModel.getClientHeaders()));
customHeaders.putAll(createMultivaluedHeadersMap(clientHeaders));
parameterModels.stream()
.filter(parameterModel -> parameterModel.handles(HeaderParam.class))
.forEach(parameterModel -> parameterModel.handleParameter(customHeaders,
HeaderParam.class,
args[parameterModel.getParamPosition()]));
MultivaluedMap<String, String> inbound = new MultivaluedHashMap<>();
HeadersContext.get().ifPresent(headersContext -> inbound.putAll(headersContext.inboundHeaders()));
AtomicReference<MultivaluedMap<String, String>> toReturn = new AtomicReference<>(customHeaders);
interfaceModel.getClientHeadersFactory().ifPresent(clientHeadersFactory -> toReturn
.set(clientHeadersFactory.update(inbound, customHeaders)));
return toReturn.get();
}
private <T> MultivaluedMap<String, String> createMultivaluedHeadersMap(List<ClientHeaderParamModel> clientHeaders) {
MultivaluedMap<String, String> customHeaders = new MultivaluedHashMap<>();
for (ClientHeaderParamModel clientHeaderParamModel : clientHeaders) {
if (clientHeaderParamModel.getComputeMethod() == null) {
customHeaders
.put(clientHeaderParamModel.getHeaderName(), Arrays.asList(clientHeaderParamModel.getHeaderValue()));
} else {
try {
Method method = clientHeaderParamModel.getComputeMethod();
if (method.isDefault()) {
//method is interface default
//we need to create instance of the interface to be able to call default method
T instance = (T) ReflectionUtil.createProxyInstance(interfaceModel.getRestClientClass());
if (method.getParameterCount() > 0) {
customHeaders.put(clientHeaderParamModel.getHeaderName(),
createList(method.invoke(instance, clientHeaderParamModel.getHeaderName())));
} else {
customHeaders.put(clientHeaderParamModel.getHeaderName(),
createList(method.invoke(instance, null)));
}
} else {
//Method is static
if (method.getParameterCount() > 0) {
customHeaders.put(clientHeaderParamModel.getHeaderName(),
createList(method.invoke(null, clientHeaderParamModel.getHeaderName())));
} else {
customHeaders.put(clientHeaderParamModel.getHeaderName(),
createList(method.invoke(null, null)));
}
}
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
if (clientHeaderParamModel.isRequired()) {
if (e.getCause() instanceof RuntimeException) {
throw (RuntimeException) e.getCause();
}
throw new RuntimeException(e.getCause());
}
}
}
}
return customHeaders;
}
private static List<String> createList(Object value) {
if (value instanceof String[]) {
String[] array = (String[]) value;
return Arrays.asList(array);
}
String s = (String) value;
return Collections.singletonList(s);
}
/**
* Evaluation of {@link Response} if it is applicable for any of the registered {@link ResponseExceptionMapper} providers.
*
* @param response obtained response
* @param method called method
*/
private void evaluateResponse(Response response, Method method) {
ResponseExceptionMapper lowestMapper = null;
Throwable throwable = null;
for (ResponseExceptionMapper responseExceptionMapper : interfaceModel.getResponseExceptionMappers()) {
if (responseExceptionMapper.handles(response.getStatus(), response.getHeaders())) {
if (lowestMapper == null
|| throwable == null
|| lowestMapper.getPriority() > responseExceptionMapper.getPriority()) {
lowestMapper = responseExceptionMapper;
Throwable tmp = lowestMapper.toThrowable(response);
if (tmp != null) {
throwable = tmp;
}
}
}
}
if (throwable != null) {
if (throwable instanceof RuntimeException) {
throw (RuntimeException) throwable;
} else if (throwable instanceof Error) {
throw (Error) throwable;
}
for (Class<?> exception : method.getExceptionTypes()) {
if (throwable.getClass().isAssignableFrom(exception)) {
throw new WebApplicationException(throwable);
}
}
}
}
private static String parseHttpMethod(InterfaceModel classModel, Method method) {
List<Class<?>> httpAnnotations = InterfaceUtil.getHttpAnnotations(method);
if (httpAnnotations.size() > 1) {
throw new RestClientDefinitionException("Method can't have more then one annotation of @HttpMethod type. "
+ "See " + classModel.getRestClientClass().getName()
+ "::" + method.getName());
}
if (httpAnnotations.isEmpty()) {
//Sub resource method
return "";
}
return httpAnnotations.get(0).getSimpleName();
}
private static List<ParamModel> parameterModels(InterfaceModel classModel, Method method) {
List<ParamModel> parameterModels = new ArrayList<>();
final List<org.glassfish.jersey.model.Parameter> jerseyParameters = org.glassfish.jersey.model.Parameter
.create(classModel.getRestClientClass(), classModel.getRestClientClass(),
method, false);
Parameter[] parameters = method.getParameters();
for (int i = 0; i < parameters.length; i++) {
parameterModels.add(ParamModel.from(classModel, parameters[i].getType(), parameters[i], jerseyParameters.get(i), i));
}
return parameterModels;
}
private static class Builder {
private final InterfaceModel interfaceModel;
private final Method method;
private GenericType<?> returnType;
private String httpMethod;
private String pathValue;
private String[] produces;
private String[] consumes;
private List<ParamModel> parameterModels;
private List<ClientHeaderParamModel> clientHeaders;
private List<InterceptorInvocationContext.InvocationInterceptor> invocationInterceptors;
private Builder(InterfaceModel interfaceModel, Method method) {
this.interfaceModel = interfaceModel;
this.method = method;
filterAllInterceptorAnnotations();
}
private void filterAllInterceptorAnnotations() {
invocationInterceptors = new ArrayList<>();
BeanManager beanManager = interfaceModel.getBeanManager();
if (beanManager != null) {
Set<Annotation> interceptorAnnotations = new HashSet<>();
for (Annotation annotation : method.getAnnotations()) {
if (beanManager.isInterceptorBinding(annotation.annotationType())) {
interceptorAnnotations.add(annotation);
}
}
interceptorAnnotations.addAll(interfaceModel.getInterceptorAnnotations());
Annotation[] allInterceptorAnnotations = interceptorAnnotations.toArray(new Annotation[0]);
if (allInterceptorAnnotations.length == 0) {
return;
}
List<Interceptor<?>> interceptors = beanManager.resolveInterceptors(InterceptionType.AROUND_INVOKE,
allInterceptorAnnotations);
if (!interceptors.isEmpty()) {
for (Interceptor<?> interceptor : interceptors) {
Object interceptorInstance = beanManager.getReference(interceptor,
interceptor.getBeanClass(),
interfaceModel.getCreationalContext());
invocationInterceptors.add(new InterceptorInvocationContext
.InvocationInterceptor(interceptorInstance,
interceptor));
}
}
}
}
/**
* Return type of the method.
*
* @param returnType Method return type
*/
private void returnType(Type returnType) {
if (returnType instanceof ParameterizedType
&& CompletionStage.class.isAssignableFrom((Class<?>) ((ParameterizedType) returnType).getRawType())) {
this.returnType = new GenericType<>(((ParameterizedType) returnType).getActualTypeArguments()[0]);
} else {
this.returnType = new GenericType<>(returnType);
}
}
/**
* HTTP method of the method.
*
* @param httpMethod HTTP method of the method
*/
private void httpMethod(String httpMethod) {
this.httpMethod = httpMethod;
}
/**
* Path value from {@link Path} annotation. If annotation is null, empty String is set as path.
*
* @param path {@link Path} annotation
*/
private void pathValue(Path path) {
this.pathValue = path != null ? path.value() : "";
//if only / is added to path like this "localhost:80/test" it makes invalid path "localhost:80/test/"
this.pathValue = pathValue.equals("/") ? "" : pathValue;
}
/**
* Extracts MediaTypes from {@link Produces} annotation.
* If annotation is null, value from {@link InterfaceModel} is set.
*
* @param produces {@link Produces} annotation
*/
private void produces(Produces produces) {
this.produces = produces == null ? interfaceModel.getProduces() : produces.value();
}
/**
* Extracts MediaTypes from {@link Consumes} annotation.
* If annotation is null, value from {@link InterfaceModel} is set.
*
* @param consumes {@link Consumes} annotation
*/
private void consumes(Consumes consumes) {
this.consumes = consumes == null ? interfaceModel.getConsumes() : consumes.value();
}
/**
* {@link List} of transformed method parameters.
*
* @param parameterModels {@link List} of parameters
*/
private void parameters(List<ParamModel> parameterModels) {
this.parameterModels = parameterModels;
}
/**
* Process data from {@link ClientHeaderParam} annotation to extract methods and values.
*
* @param clientHeaderParams {@link ClientHeaderParam} annotations
*/
private void clientHeaders(ClientHeaderParam[] clientHeaderParams) {
clientHeaders = Arrays.stream(clientHeaderParams)
.map(clientHeaderParam -> new ClientHeaderParamModel(interfaceModel.getRestClientClass(), clientHeaderParam))
.collect(Collectors.toList());
}
/**
* Creates new MethodModel instance.
*
* @return new instance
*/
MethodModel build() {
returnType(method.getGenericReturnType());
httpMethod(parseHttpMethod(interfaceModel, method));
pathValue(method.getAnnotation(Path.class));
produces(method.getAnnotation(Produces.class));
consumes(method.getAnnotation(Consumes.class));
parameters(parameterModels(interfaceModel, method));
clientHeaders(method.getAnnotationsByType(ClientHeaderParam.class));
validateParameters();
validateHeaderDuplicityNames();
if (isJsonValue(returnType.getType())) {
this.produces = new String[] {MediaType.APPLICATION_JSON};
}
parameterModels.stream()
.filter(ParamModel::isEntity)
.map(ParamModel::getType)
.filter(this::isJsonValue)
.findFirst()
.ifPresent(paramModel -> this.consumes = new String[] {MediaType.APPLICATION_JSON});
return new MethodModel(this);
}
private void validateParameters() {
UriBuilder uriBuilder = UriBuilder.fromUri(interfaceModel.getPath()).path(pathValue);
List<String> parameters = InterfaceUtil.parseParameters(uriBuilder.toTemplate());
List<String> methodPathParameters = new ArrayList<>();
List<ParamModel> pathHandlingParams = parameterModels.stream()
.filter(parameterModel -> parameterModel.handles(PathParam.class))
.collect(Collectors.toList());
for (ParamModel paramModel : pathHandlingParams) {
if (paramModel instanceof PathParamModel) {
methodPathParameters.add(((PathParamModel) paramModel).getPathParamName());
} else if (paramModel instanceof BeanParamModel) {
for (ParamModel beanPathParams : ((BeanParamModel) paramModel).getAllParamsWithType(PathParam.class)) {
methodPathParameters.add(((PathParamModel) beanPathParams).getPathParamName());
}
}
}
for (String parameterName : methodPathParameters) {
if (!parameters.contains(parameterName)) {
throw new RestClientDefinitionException("Parameter name " + parameterName + " on "
+ interfaceModel.getRestClientClass().getName()
+ "::" + method.getName()
+ " doesn't match any @Path variable name.");
}
parameters.remove(parameterName);
}
if (!parameters.isEmpty()) {
throw new RestClientDefinitionException("Some variable names does not have matching @PathParam "
+ "defined on method " + interfaceModel.getRestClientClass()
.getName()
+ "::" + method.getName());
}
List<ParamModel> entities = parameterModels.stream()
.filter(ParamModel::isEntity)
.collect(Collectors.toList());
if (entities.size() > 1) {
throw new RestClientDefinitionException("You cant have more than 1 entity method parameter! Check "
+ interfaceModel.getRestClientClass().getName()
+ "::" + method.getName());
}
}
private void validateHeaderDuplicityNames() {
ArrayList<String> names = new ArrayList<>();
for (ClientHeaderParamModel clientHeaderParamModel : clientHeaders) {
String headerName = clientHeaderParamModel.getHeaderName();
if (names.contains(headerName)) {
throw new RestClientDefinitionException("Header name cannot be registered more then once on the same target."
+ "See " + interfaceModel.getRestClientClass().getName());
}
names.add(headerName);
}
}
private boolean isJsonValue(Type type) {
return type instanceof Class && JsonValue.class.isAssignableFrom((Class<?>) type);
}
}
}