This repository has been archived by the owner on May 31, 2019. It is now read-only.
/
RestClientBuilderImpl.java
483 lines (397 loc) · 17.5 KB
/
RestClientBuilderImpl.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
/**
* Copyright 2015-2017 Red Hat, Inc, and individual contributors.
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 io.smallrye.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.Proxy;
import java.net.InetSocketAddress;
import java.net.ProxySelector;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import javax.ws.rs.HttpMethod;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Priorities;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.Configuration;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.ext.ParamConverterProvider;
import io.smallrye.restclient.header.ClientHeadersRequestFilter;
import io.smallrye.restclient.header.ClientHeaderProviders;
import org.eclipse.microprofile.config.Config;
import org.eclipse.microprofile.config.ConfigProvider;
import org.eclipse.microprofile.rest.client.RestClientBuilder;
import org.eclipse.microprofile.rest.client.RestClientDefinitionException;
import org.eclipse.microprofile.rest.client.annotation.RegisterProvider;
import org.eclipse.microprofile.rest.client.ext.AsyncInvocationInterceptorFactory;
import org.eclipse.microprofile.rest.client.ext.ResponseExceptionMapper;
import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.jboss.resteasy.specimpl.ResteasyUriBuilder;
import io.smallrye.restclient.async.AsyncInvocationInterceptorHandler;
class RestClientBuilderImpl implements RestClientBuilder {
private static final String RESTEASY_PROPERTY_PREFIX = "resteasy.";
private static final String DEFAULT_MAPPER_PROP = "microprofile.rest.client.disable.default.mapper";
private static final DefaultMediaTypeFilter DEFAULT_MEDIA_TYPE_FILTER = new DefaultMediaTypeFilter();
public static final MethodInjectionFilter METHOD_INJECTION_FILTER = new MethodInjectionFilter();
public static final ClientHeadersRequestFilter HEADERS_REQUEST_FILTER = new ClientHeadersRequestFilter();
RestClientBuilderImpl() {
ClientBuilder availableBuilder = ClientBuilder.newBuilder();
if (availableBuilder instanceof ResteasyClientBuilder) {
builderDelegate = (ResteasyClientBuilder) availableBuilder;
configurationWrapper = new ConfigurationWrapper(builderDelegate.getConfiguration());
config = ConfigProvider.getConfig();
} else {
throw new IllegalStateException("Incompatible client builder found " + availableBuilder.getClass());
}
}
public Configuration getConfigurationWrapper() {
return configurationWrapper;
}
@Override
public RestClientBuilder baseUrl(URL url) {
try {
baseURI = url.toURI();
return this;
} catch (URISyntaxException e) {
throw new RuntimeException(e.getMessage());
}
}
@Override
public RestClientBuilder baseUri(URI uri) {
baseURI = uri;
return this;
}
@Override
public RestClientBuilder connectTimeout(long l, TimeUnit timeUnit) {
connectTimeout = l;
connectTimeoutUnit = timeUnit;
return this;
}
@Override
public RestClientBuilder readTimeout(long time, TimeUnit timeUnit) {
readTimeout = time;
readTimeoutUnit = timeUnit;
return this;
}
@Override
public RestClientBuilder executorService(ExecutorService executor) {
if (executor == null) {
throw new IllegalArgumentException("ExecutorService must not be null");
}
executorService = executor;
return this;
}
@SuppressWarnings("unchecked")
@Override
public <T> T build(Class<T> aClass) throws IllegalStateException, RestClientDefinitionException {
RestClientListeners.get().forEach(listener -> listener.onNewClient(aClass, this));
// Interface validity
verifyInterface(aClass);
if (baseURI == null) {
throw new IllegalStateException("Neither baseUri nor baseUrl was specified");
}
// Provider annotations
RegisterProvider[] providers = aClass.getAnnotationsByType(RegisterProvider.class);
for (RegisterProvider provider : providers) {
register(provider.value(), provider.priority());
}
// Default exception mapper
if (!isMapperDisabled()) {
register(DefaultResponseExceptionMapper.class);
}
builderDelegate.register(new ExceptionMapping(localProviderInstances), 1);
ClassLoader classLoader = aClass.getClassLoader();
selectHttpProxy()
.ifPresent(proxyAddress -> builderDelegate.defaultProxy(proxyAddress.getHostString(), proxyAddress.getPort()));
// this is rest easy default
ExecutorService executorService = this.executorService != null ? this.executorService : Executors.newFixedThreadPool(10);
ExecutorService executor = AsyncInvocationInterceptorHandler.wrapExecutorService(executorService);
builderDelegate.executorService(executor);
builderDelegate.register(DEFAULT_MEDIA_TYPE_FILTER);
builderDelegate.register(METHOD_INJECTION_FILTER);
builderDelegate.register(HEADERS_REQUEST_FILTER);
if (readTimeout != null) {
builderDelegate.readTimeout(readTimeout, readTimeoutUnit);
}
if (connectTimeout != null) {
builderDelegate.connectTimeout(connectTimeout, connectTimeoutUnit);
}
ResteasyClient client = builderDelegate
.build();
T actualClient = client.target(baseURI)
.proxyBuilder(aClass)
.classloader(classLoader)
.defaultConsumes(MediaType.WILDCARD)
.defaultProduces(MediaType.WILDCARD).build();
Class<?>[] interfaces = new Class<?>[2];
interfaces[0] = aClass;
interfaces[1] = RestClientProxy.class;
T proxy = (T) Proxy.newProxyInstance(classLoader, interfaces, new ProxyInvocationHandler(aClass, actualClient, getLocalProviderInstances(), client, asyncInterceptorFactories));
ClientHeaderProviders.registerForClass(aClass, proxy);
return proxy;
}
private Optional<InetSocketAddress> selectHttpProxy() {
return ProxySelector.getDefault().select(baseURI).stream()
.filter(proxy -> proxy.type() == java.net.Proxy.Type.HTTP)
.map(java.net.Proxy::address)
.map(InetSocketAddress.class::cast)
.findFirst();
}
private boolean isMapperDisabled() {
boolean disabled = false;
Optional<Boolean> defaultMapperProp = config.getOptionalValue(DEFAULT_MAPPER_PROP, Boolean.class);
// disabled through config api
if (defaultMapperProp.isPresent() && defaultMapperProp.get().equals(Boolean.TRUE)) {
disabled = true;
} else if (!defaultMapperProp.isPresent()) {
// disabled through jaxrs property
try {
Object property = builderDelegate.getConfiguration().getProperty(DEFAULT_MAPPER_PROP);
if (property != null) {
disabled = (Boolean) property;
}
} catch (Throwable e) {
// ignore cast exception
}
}
return disabled;
}
private <T> void verifyInterface(Class<T> typeDef) {
Method[] methods = typeDef.getMethods();
// multiple verbs
for (Method method : methods) {
boolean hasHttpMethod = false;
for (Annotation annotation : method.getAnnotations()) {
boolean isHttpMethod = (annotation.annotationType().getAnnotation(HttpMethod.class) != null);
if (!hasHttpMethod && isHttpMethod) {
hasHttpMethod = true;
} else if (hasHttpMethod && isHttpMethod) {
throw new RestClientDefinitionException("Ambiguous @Httpmethod defintion on type " + typeDef);
}
}
}
// invalid parameter
Path classPathAnno = typeDef.getAnnotation(Path.class);
final Set<String> classLevelVariables = new HashSet<>();
ResteasyUriBuilder classTemplate = null;
if (classPathAnno != null) {
classTemplate = (ResteasyUriBuilder) UriBuilder.fromUri(classPathAnno.value());
classLevelVariables.addAll(classTemplate.getPathParamNamesInDeclarationOrder()); // TODO: doesn't seem to be used!
}
ResteasyUriBuilder template;
for (Method method : methods) {
Path methodPathAnno = method.getAnnotation(Path.class);
if (methodPathAnno != null) {
template = classPathAnno == null ? (ResteasyUriBuilder) UriBuilder.fromUri(methodPathAnno.value())
: (ResteasyUriBuilder) UriBuilder.fromUri(classPathAnno.value() + "/" + methodPathAnno.value());
} else {
template = classTemplate;
}
if (template == null) {
continue;
}
// it's not executed, so this can be anything - but a hostname needs to present
template.host("localhost");
Set<String> allVariables = new HashSet<>(template.getPathParamNamesInDeclarationOrder());
Map<String, Object> paramMap = new HashMap<>();
for (Parameter p : method.getParameters()) {
PathParam pathParam = p.getAnnotation(PathParam.class);
if (pathParam != null) {
paramMap.put(pathParam.value(), "foobar");
}
}
if (allVariables.size() != paramMap.size()) {
throw new RestClientDefinitionException("Parameters and variables don't match on " + typeDef + "::" + method.getName());
}
try {
template.resolveTemplates(paramMap, false).build();
} catch (IllegalArgumentException ex) {
throw new RestClientDefinitionException("Parameter names don't match variable names on " + typeDef + "::" + method.getName(), ex);
}
}
}
@Override
public Configuration getConfiguration() {
return getConfigurationWrapper();
}
@Override
public RestClientBuilder property(String name, Object value) {
if (name.startsWith(RESTEASY_PROPERTY_PREFIX)) {
// Makes it possible to configure some of the ResteasyClientBuilder delegate properties
String builderMethodName = name.substring(RESTEASY_PROPERTY_PREFIX.length());
Method builderMethod = Arrays.stream(ResteasyClientBuilder.class.getMethods())
.filter(m -> builderMethodName.equals(m.getName()) && m.getParameterTypes().length >= 1)
.findFirst()
.orElse(null);
if (builderMethod == null) {
throw new IllegalArgumentException("ResteasyClientBuilder setter method not found: " + builderMethodName);
}
Object[] arguments;
if (builderMethod.getParameterTypes().length > 1) {
if (value instanceof List) {
arguments = ((List<?>) value).toArray();
} else {
throw new IllegalArgumentException("Value must be an instance of List<> for ResteasyClientBuilder setter method: " + builderMethodName);
}
} else {
arguments = new Object[] { value };
}
try {
builderMethod.invoke(builderDelegate, arguments);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
throw new IllegalStateException("Unable to invoke ResteasyClientBuilder method: " + builderMethodName, e);
}
}
builderDelegate.property(name, value);
return this;
}
private static Object newInstanceOf(Class<?> clazz) {
try {
return clazz.newInstance();
} catch (Throwable t) {
throw new RuntimeException("Failed to register " + clazz, t);
}
}
@Override
public RestClientBuilder register(Class<?> aClass) {
register(newInstanceOf(aClass));
return this;
}
@Override
public RestClientBuilder register(Class<?> aClass, int i) {
register(newInstanceOf(aClass), i);
return this;
}
@Override
public RestClientBuilder register(Class<?> aClass, Class<?>[] classes) {
register(newInstanceOf(aClass), classes);
return this;
}
@Override
public RestClientBuilder register(Class<?> aClass, Map<Class<?>, Integer> map) {
register(newInstanceOf(aClass), map);
return this;
}
@Override
public RestClientBuilder register(Object o) {
if (o instanceof ResponseExceptionMapper) {
ResponseExceptionMapper mapper = (ResponseExceptionMapper) o;
register(mapper, mapper.getPriority());
} else if (o instanceof ParamConverterProvider) {
register(o, Priorities.USER);
} else if (o instanceof AsyncInvocationInterceptorFactory) {
asyncInterceptorFactories.add((AsyncInvocationInterceptorFactory) o);
} else {
builderDelegate.register(o);
}
return this;
}
@Override
public RestClientBuilder register(Object o, int i) {
if (o instanceof ResponseExceptionMapper) {
// local
ResponseExceptionMapper mapper = (ResponseExceptionMapper) o;
HashMap<Class<?>, Integer> contracts = new HashMap<>();
contracts.put(ResponseExceptionMapper.class, i);
registerLocalProviderInstance(mapper, contracts);
// delegate
builderDelegate.register(mapper, i);
} else if (o instanceof ParamConverterProvider) {
// local
ParamConverterProvider converter = (ParamConverterProvider) o;
HashMap<Class<?>, Integer> contracts = new HashMap<>();
contracts.put(ParamConverterProvider.class, i);
registerLocalProviderInstance(converter, contracts);
// delegate
builderDelegate.register(converter, i);
} else if (o instanceof AsyncInvocationInterceptorFactory) {
asyncInterceptorFactories.add((AsyncInvocationInterceptorFactory) o);
} else {
builderDelegate.register(o, i);
}
return this;
}
@Override
public RestClientBuilder register(Object o, Class<?>[] classes) {
// local
for (Class<?> aClass : classes) {
if (aClass.isAssignableFrom(ResponseExceptionMapper.class)) {
register(o);
}
}
// other
builderDelegate.register(o, classes);
return this;
}
@Override
public RestClientBuilder register(Object o, Map<Class<?>, Integer> map) {
if (o instanceof ResponseExceptionMapper) {
// local
ResponseExceptionMapper mapper = (ResponseExceptionMapper) o;
HashMap<Class<?>, Integer> contracts = new HashMap<>();
contracts.put(ResponseExceptionMapper.class, map.get(ResponseExceptionMapper.class));
registerLocalProviderInstance(mapper, contracts);
// other
builderDelegate.register(o, map);
} else {
builderDelegate.register(o, map);
}
return this;
}
public Set<Object> getLocalProviderInstances() {
return localProviderInstances;
}
public void registerLocalProviderInstance(Object provider, Map<Class<?>, Integer> contracts) {
for (Object registered : getLocalProviderInstances()) {
if (registered == provider) {
System.out.println("Provider already registered " + provider.getClass().getName());
return;
}
}
localProviderInstances.add(provider);
configurationWrapper.registerLocalContract(provider.getClass(), contracts);
}
ResteasyClientBuilder getBuilderDelegate() {
return builderDelegate;
}
private final ResteasyClientBuilder builderDelegate;
private final ConfigurationWrapper configurationWrapper;
private final Config config;
private ExecutorService executorService;
private URI baseURI;
private Long connectTimeout;
private TimeUnit connectTimeoutUnit;
private Long readTimeout;
private TimeUnit readTimeoutUnit;
private Set<Object> localProviderInstances = new HashSet<>();
private final List<AsyncInvocationInterceptorFactory> asyncInterceptorFactories = new ArrayList<>();
}