-
Notifications
You must be signed in to change notification settings - Fork 888
/
ResteasyClientBuilderImpl.java
686 lines (601 loc) · 23.4 KB
/
ResteasyClientBuilderImpl.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
682
683
684
685
686
package org.jboss.resteasy.client.jaxrs.internal;
import java.security.AccessController;
import java.security.KeyStore;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import jakarta.ws.rs.Priorities;
import jakarta.ws.rs.RuntimeType;
import jakarta.ws.rs.core.Configuration;
import org.apache.http.HttpHost;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.jboss.resteasy.client.jaxrs.ClientHttpEngine;
import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.jboss.resteasy.client.jaxrs.engines.ApacheHttpAsyncClient4Engine;
import org.jboss.resteasy.client.jaxrs.engines.ClientHttpEngineBuilder43;
import org.jboss.resteasy.client.jaxrs.i18n.LogMessages;
import org.jboss.resteasy.client.jaxrs.i18n.Messages;
import org.jboss.resteasy.client.jaxrs.spi.ClientConfigProvider;
import org.jboss.resteasy.concurrent.ContextualExecutorService;
import org.jboss.resteasy.concurrent.ContextualExecutors;
import org.jboss.resteasy.core.providerfactory.ResteasyProviderFactoryDelegate;
import org.jboss.resteasy.plugins.interceptors.AcceptEncodingGZIPFilter;
import org.jboss.resteasy.plugins.providers.RegisterBuiltin;
import org.jboss.resteasy.spi.ResteasyProviderFactory;
/**
* Abstraction for creating Clients. Allows SSL configuration. Uses Apache Http Client under
* the covers. If used with other ClientHttpEngines though, all configuration options are ignored.
*
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class ResteasyClientBuilderImpl extends ResteasyClientBuilder {
protected KeyStore truststore;
protected KeyStore clientKeyStore;
protected String clientPrivateKeyPassword;
protected boolean disableTrustManager;
protected HostnameVerificationPolicy policy = HostnameVerificationPolicy.WILDCARD;
protected ResteasyProviderFactory providerFactory;
protected ExecutorService asyncExecutor;
protected ScheduledExecutorService scheduledExecutorService;
protected boolean cleanupExecutor;
protected SSLContext sslContext;
protected Map<String, Object> properties = new HashMap<String, Object>();
protected ClientHttpEngine httpEngine;
protected int connectionPoolSize = 50;
protected int maxPooledPerRoute = 0;
protected long connectionTTL = -1;
protected TimeUnit connectionTTLUnit = TimeUnit.MILLISECONDS;
protected long socketTimeout = -1;
protected TimeUnit socketTimeoutUnits = TimeUnit.MILLISECONDS;
protected long establishConnectionTimeout = -1;
protected TimeUnit establishConnectionTimeoutUnits = TimeUnit.MILLISECONDS;
protected int connectionCheckoutTimeoutMs = -1;
protected HostnameVerifier verifier = null;
protected HttpHost defaultProxy;
protected int responseBufferSize;
protected List<String> sniHostNames = new ArrayList<>();
protected boolean trustSelfSignedCertificates = true;
protected boolean cookieManagementEnabled;
protected boolean disableAutomaticRetries = false;
protected boolean followRedirects;
static ResteasyProviderFactory PROVIDER_FACTORY;
public static void setProviderFactory(ResteasyProviderFactory providerFactory) {
PROVIDER_FACTORY = providerFactory;
}
public ResteasyClientBuilderImpl() {
if (PROVIDER_FACTORY != null) {
ResteasyProviderFactory localProviderFactory = new LocalResteasyProviderFactory(PROVIDER_FACTORY);
if (ResteasyProviderFactory.peekInstance() != null) {
localProviderFactory.initializeClientProviders(ResteasyProviderFactory.getInstance());
}
providerFactory = localProviderFactory;
}
}
/**
* Changing the providerFactory will wipe clean any registered components or properties.
*
* @param providerFactory provider factory
* @return the updated client builder instance
*/
@Override
public ResteasyClientBuilderImpl providerFactory(ResteasyProviderFactory providerFactory) {
if (providerFactory instanceof LocalResteasyProviderFactory) {
this.providerFactory = providerFactory;
} else {
this.providerFactory = new ResteasyProviderFactoryDelegate(providerFactory) {
@Override
public jakarta.ws.rs.RuntimeType getRuntimeType() {
return RuntimeType.CLIENT;
}
};
}
return this;
}
/**
* Executor to use to run AsyncInvoker invocations.
*
* @param asyncExecutor executor service
* @return the updated client builder instance
* @deprecated use {@link ResteasyClientBuilderImpl#executorService(ExecutorService)} instead
*/
@Deprecated
public ResteasyClientBuilderImpl asyncExecutor(ExecutorService asyncExecutor) {
return asyncExecutor(asyncExecutor, false);
}
/**
* Executor to use to run AsyncInvoker invocations.
*
* @param asyncExecutor executor service
* @param cleanupExecutor true if the Client should close the executor when it is closed
* @return the updated client builder instance
*/
@Deprecated
public ResteasyClientBuilderImpl asyncExecutor(ExecutorService asyncExecutor, boolean cleanupExecutor) {
this.asyncExecutor = asyncExecutor;
this.cleanupExecutor = cleanupExecutor;
return this;
}
/**
* If there is a connection pool, set the time to live in the pool.
*
* @param ttl time to live
* @param unit the time unit of the ttl argument
* @return the updated client builder instance
*/
public ResteasyClientBuilderImpl connectionTTL(long ttl, TimeUnit unit) {
this.connectionTTL = ttl;
this.connectionTTLUnit = unit;
return this;
}
@Override
public ResteasyClientBuilderImpl readTimeout(long timeout, TimeUnit unit) {
this.socketTimeout = timeout;
this.socketTimeoutUnits = unit;
return this;
}
@Override
public ResteasyClientBuilderImpl connectTimeout(long timeout, TimeUnit unit) {
this.establishConnectionTimeout = timeout;
this.establishConnectionTimeoutUnits = unit;
return this;
}
/**
* If connection pooling enabled, how many connections to pool per url?
*
* @param maxPooledPerRoute max pool size per url
* @return the updated client builder instance
*/
public ResteasyClientBuilderImpl maxPooledPerRoute(int maxPooledPerRoute) {
this.maxPooledPerRoute = maxPooledPerRoute;
return this;
}
/**
* If connection pooling is enabled, how long will we wait to get a connection?
*
* @param timeout the timeout
* @param unit the units the timeout is in
* @return the updated client builder instance
*/
public ResteasyClientBuilderImpl connectionCheckoutTimeout(long timeout, TimeUnit unit) {
this.connectionCheckoutTimeoutMs = (int) TimeUnit.MILLISECONDS.convert(timeout, unit);
return this;
}
/**
* Number of connections allowed to pool.
*
* @param connectionPoolSize connection pool size
* @return the updated client builder instance
*/
public ResteasyClientBuilderImpl connectionPoolSize(int connectionPoolSize) {
this.connectionPoolSize = connectionPoolSize;
return this;
}
/**
* Response stream is wrapped in a BufferedInputStream. Default is 8192. Value of 0 will not wrap it.
* Value of -1 will use a SelfExpandingBufferedInputStream.
*
* @param size response buffer size
* @return the updated client builder instance
*/
public ResteasyClientBuilderImpl responseBufferSize(int size) {
this.responseBufferSize = size;
return this;
}
/**
* Disable trust management and hostname verification. <i>NOTE</i> this is a security
* hole, so only set this option if you cannot or do not want to verify the identity of the
* host you are communicating with.
*
* @return the updated client builder instance
*/
public ResteasyClientBuilderImpl disableTrustManager() {
this.disableTrustManager = true;
return this;
}
/**
* SSL policy used to verify hostnames
*
* @param policy SSL policy
* @return the updated client builder instance
*/
public ResteasyClientBuilderImpl hostnameVerification(HostnameVerificationPolicy policy) {
this.policy = policy;
return this;
}
/**
* Negates all ssl and connection specific configuration
*
* @param httpEngine http engine
* @return the updated client builder instance
*/
public ResteasyClientBuilderImpl httpEngine(ClientHttpEngine httpEngine) {
this.httpEngine = httpEngine;
return this;
}
public ResteasyClientBuilderImpl useAsyncHttpEngine() {
this.httpEngine = new ApacheHttpAsyncClient4Engine(HttpAsyncClients.createSystem(), true);
return this;
}
@Override
public ResteasyClientBuilderImpl sslContext(SSLContext sslContext) {
this.sslContext = sslContext;
return this;
}
@Override
public ResteasyClientBuilderImpl trustStore(KeyStore truststore) {
this.truststore = truststore;
return this;
}
@Override
public ResteasyClientBuilderImpl keyStore(KeyStore keyStore, String password) {
this.clientKeyStore = keyStore;
this.clientPrivateKeyPassword = password;
return this;
}
@Override
public ResteasyClientBuilderImpl keyStore(KeyStore keyStore, char[] password) {
this.clientKeyStore = keyStore;
this.clientPrivateKeyPassword = new String(password);
return this;
}
@Override
public ResteasyClientBuilderImpl property(String name, Object value) {
getProviderFactory().property(name, value);
return this;
}
/**
* Adds a TLS/SSL SNI Host Name for authentication.
*
* @param sniHostNames host names
* @return the updated client builder instance
*/
public ResteasyClientBuilderImpl sniHostNames(String... sniHostNames) {
this.sniHostNames.addAll(Arrays.asList(sniHostNames));
return this;
}
/**
* Specify a default proxy. Default port and schema will be used.
*
* @param hostname host name
* @return the updated client builder instance
*/
public ResteasyClientBuilderImpl defaultProxy(String hostname) {
return defaultProxy(hostname, -1, null);
}
/**
* Specify a default proxy host and port. Default schema will be used.
*
* @param hostname host name
* @param port port
* @return the updated client builder instance
*/
public ResteasyClientBuilderImpl defaultProxy(String hostname, int port) {
return defaultProxy(hostname, port, null);
}
/**
* Specify default proxy.
*
* @param hostname host name
* @param port port
* @param scheme scheme
* @return the updated client builder instance
*/
public ResteasyClientBuilderImpl defaultProxy(String hostname, int port, final String scheme) {
this.defaultProxy = hostname != null ? new HttpHost(hostname, port, scheme) : null;
return this;
}
public ResteasyProviderFactory getProviderFactory() {
if (providerFactory == null) {
ClassLoader loader = null;
if (System.getSecurityManager() == null) {
loader = Thread.currentThread().getContextClassLoader();
} else {
try {
loader = AccessController.doPrivileged(new PrivilegedExceptionAction<ClassLoader>() {
@Override
public ClassLoader run() throws Exception {
return Thread.currentThread().getContextClassLoader();
}
});
} catch (PrivilegedActionException pae) {
throw new RuntimeException(pae);
}
}
// create a new one
providerFactory = new LocalResteasyProviderFactory(
RegisterBuiltin.getClientInitializedResteasyProviderFactory(loader));
if (ResteasyProviderFactory.peekInstance() != null) {
providerFactory.initializeClientProviders(ResteasyProviderFactory.getInstance());
}
// Execution of 'if' above overwrites providerFactory clientRequestFilterRegistry
// Reregister provider as appropriate.
if (RegisterBuiltin.isGZipEnabled()) {
providerFactory.registerProvider(AcceptEncodingGZIPFilter.class, true);
}
}
return providerFactory;
}
@Override
public ResteasyClient build() {
ClientConfiguration config = new ClientConfiguration(getProviderFactory());
for (Map.Entry<String, Object> entry : properties.entrySet()) {
config.property(entry.getKey(), entry.getValue());
}
boolean resetProxy = false;
if (this.defaultProxy == null) {
resetProxy = true;
// check for proxy config parameters
setProxyIfNeeded(config);
}
for (Object p : getProviderFactory().getProviderInstances()) {
if (p instanceof ClientHttpEngine) {
httpEngine((ClientHttpEngine) p);
break;
}
}
final Object localFollowRedirects = config.getProperty(PROPERTY_FOLLOW_REDIRECTS);
if (localFollowRedirects != null) {
this.followRedirects = Boolean.parseBoolean(String.valueOf(localFollowRedirects));
}
ClientHttpEngine engine = httpEngine != null ? httpEngine
: new ClientHttpEngineBuilder43().resteasyClientBuilder(this).build();
if (resetProxy) {
this.defaultProxy = null;
}
Iterator<ClientConfigProvider> serviceLoaderIterator = ServiceLoader.load(ClientConfigProvider.class).iterator();
if (serviceLoaderIterator.hasNext()) {
config.register(new ClientConfigProviderFilter(serviceLoaderIterator.next()), Priorities.AUTHENTICATION);
}
final ContextualExecutorService executor = getExecutorService();
return createResteasyClient(engine, executor, !executor.isManaged(),
ContextualExecutors.wrapOrLookup(scheduledExecutorService), config);
}
/**
* This method sets http proxy if {@link ResteasyClientBuilder#PROPERTY_PROXY_HOST} is set in the properties.
*
* @param clientConfig client config
*/
private void setProxyIfNeeded(ClientConfiguration clientConfig) {
try {
if (clientConfig.hasProperty(ResteasyClientBuilder.PROPERTY_PROXY_HOST)) {
Object proxyHostProp = clientConfig.getProperty(ResteasyClientBuilder.PROPERTY_PROXY_HOST);
Integer proxyPort = -1;
if (clientConfig.hasProperty(ResteasyClientBuilder.PROPERTY_PROXY_PORT)) {
// default if the port is not set or if it is not string or number
Object proxyPortProp = clientConfig.getProperty(ResteasyClientBuilder.PROPERTY_PROXY_PORT);
if (proxyPortProp instanceof Number) {
proxyPort = ((Number) proxyPortProp).intValue();
} else if (proxyPortProp instanceof String) {
proxyPort = Integer.parseInt((String) proxyPortProp);
}
}
Object proxySchemeProp = clientConfig.getProperty(ResteasyClientBuilder.PROPERTY_PROXY_SCHEME);
defaultProxy((String) proxyHostProp, proxyPort, (String) proxySchemeProp);
}
} catch (Exception e) {
// catch possible exceptions (in this case we do not set proxy at all)
LogMessages.LOGGER.warn(Messages.MESSAGES.unableToSetHttpProxy(), e);
}
}
protected ResteasyClient createResteasyClient(ClientHttpEngine engine, ExecutorService executor, boolean cleanupExecutor,
ScheduledExecutorService scheduledExecutorService, ClientConfiguration config) {
return new ResteasyClientImpl(engine, executor, cleanupExecutor,
ContextualExecutors.wrapOrLookup(scheduledExecutorService), config);
}
@Override
public ResteasyClientBuilderImpl hostnameVerifier(HostnameVerifier verifier) {
this.verifier = verifier;
return this;
}
@Override
public Configuration getConfiguration() {
return getProviderFactory().getConfiguration();
}
@Override
public ResteasyClientBuilderImpl register(Class<?> componentClass) {
getProviderFactory().register(componentClass);
return this;
}
@Override
public ResteasyClientBuilderImpl register(Class<?> componentClass, int priority) {
getProviderFactory().register(componentClass, priority);
return this;
}
@Override
public ResteasyClientBuilderImpl register(Class<?> componentClass, Class<?>... contracts) {
getProviderFactory().register(componentClass, contracts);
return this;
}
@Override
public ResteasyClientBuilderImpl register(Class<?> componentClass, Map<Class<?>, Integer> contracts) {
getProviderFactory().register(componentClass, contracts);
return this;
}
@Override
public ResteasyClientBuilderImpl register(Object component) {
getProviderFactory().register(component);
return this;
}
@Override
public ResteasyClientBuilderImpl register(Object component, int priority) {
getProviderFactory().register(component, priority);
return this;
}
@Override
public ResteasyClientBuilderImpl register(Object component, Class<?>... contracts) {
getProviderFactory().register(component, contracts);
return this;
}
@Override
public ResteasyClientBuilderImpl register(Object component, Map<Class<?>, Integer> contracts) {
getProviderFactory().register(component, contracts);
return this;
}
@Override
public ResteasyClientBuilderImpl withConfig(Configuration config) {
providerFactory = new LocalResteasyProviderFactory();
providerFactory.setProperties(config.getProperties());
for (Class clazz : config.getClasses()) {
Map<Class<?>, Integer> contracts = config.getContracts(clazz);
try {
register(clazz, contracts);
} catch (RuntimeException e) {
throw new RuntimeException(Messages.MESSAGES.failedOnRegisteringClass(clazz.getName()), e);
}
}
for (Object obj : config.getInstances()) {
Map<Class<?>, Integer> contracts = config.getContracts(obj.getClass());
register(obj, contracts);
}
return this;
}
@Override
public ResteasyClientBuilder executorService(ExecutorService executorService) {
return asyncExecutor(executorService, false);
}
@Override
public ResteasyClientBuilder executorService(ExecutorService executorService, boolean cleanupExecutor) {
return asyncExecutor(executorService, cleanupExecutor);
}
@Override
public ResteasyClientBuilder scheduledExecutorService(ScheduledExecutorService scheduledExecutorService) {
this.scheduledExecutorService = scheduledExecutorService;
return this;
}
@Override
public long getConnectionTTL(TimeUnit unit) {
return connectionTTLUnit.equals(unit) ? connectionTTL : unit.convert(connectionTTL, connectionTTLUnit);
}
@Override
public int getMaxPooledPerRoute() {
return maxPooledPerRoute;
}
@Override
public long getConnectionCheckoutTimeout(TimeUnit unit) {
return TimeUnit.MILLISECONDS.equals(unit) ? connectionCheckoutTimeoutMs
: unit.convert(connectionCheckoutTimeoutMs, TimeUnit.MILLISECONDS);
}
@Override
public int getConnectionPoolSize() {
return connectionPoolSize;
}
@Override
public int getResponseBufferSize() {
return responseBufferSize;
}
@Override
public boolean isTrustManagerDisabled() {
return disableTrustManager;
}
@Override
public boolean isTrustSelfSignedCertificates() {
return trustSelfSignedCertificates;
}
@Override
public void setIsTrustSelfSignedCertificates(boolean b) {
trustSelfSignedCertificates = b;
}
@Override
public HostnameVerificationPolicy getHostnameVerification() {
return policy;
}
@Override
public ClientHttpEngine getHttpEngine() {
return httpEngine;
}
@Override
public boolean isUseAsyncHttpEngine() {
return httpEngine != null && (httpEngine instanceof ApacheHttpAsyncClient4Engine);
}
@Override
public List<String> getSniHostNames() {
return sniHostNames;
}
@Override
public String getDefaultProxyHostname() {
return defaultProxy != null ? defaultProxy.getHostName() : null;
}
@Override
public int getDefaultProxyPort() {
return defaultProxy != null ? defaultProxy.getPort() : -1;
}
@Override
public String getDefaultProxyScheme() {
return defaultProxy != null ? defaultProxy.getSchemeName() : null;
}
@Override
public long getReadTimeout(TimeUnit unit) {
return socketTimeoutUnits.equals(unit) ? socketTimeout : unit.convert(socketTimeout, socketTimeoutUnits);
}
@Override
public long getConnectionTimeout(TimeUnit unit) {
return establishConnectionTimeoutUnits.equals(unit) ? establishConnectionTimeout
: unit.convert(establishConnectionTimeout, establishConnectionTimeoutUnits);
}
@Override
public SSLContext getSSLContext() {
return sslContext;
}
@Override
public KeyStore getKeyStore() {
return clientKeyStore;
}
@Override
public String getKeyStorePassword() {
return clientPrivateKeyPassword;
}
@Override
public KeyStore getTrustStore() {
return truststore;
}
@Override
public HostnameVerifier getHostnameVerifier() {
return verifier;
}
@Override
public ResteasyClientBuilder enableCookieManagement() {
this.cookieManagementEnabled = true;
return this;
}
@Override
public boolean isCookieManagementEnabled() {
return cookieManagementEnabled;
}
@Override
public ResteasyClientBuilder disableAutomaticRetries() {
this.disableAutomaticRetries = true;
return this;
}
@Override
public boolean isDisableAutomaticRetries() {
return disableAutomaticRetries;
}
@Override
public ResteasyClientBuilder setFollowRedirects(boolean followRedirects) {
this.followRedirects = followRedirects;
return this;
}
@Override
public boolean isFollowRedirects() {
return followRedirects;
}
private ContextualExecutorService getExecutorService() {
if (asyncExecutor != null) {
return ContextualExecutors.wrap(asyncExecutor, !cleanupExecutor);
}
return ContextualExecutors.threadPool();
}
}