Repository navigation
Expand file tree
/
Copy pathConfig.java
More file actions
712 lines (637 loc) · 21 KB
/
Copy pathConfig.java
File metadata and controls
712 lines (637 loc) · 21 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
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
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
/**
* The MIT License
*
* Copyright for portions of unirest-java are held by Kong Inc (c) 2013.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package kong.unirest;
import kong.unirest.apache.ApacheAsyncClient;
import kong.unirest.apache.ApacheClient;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.client.HttpClient;
import org.apache.http.nio.client.HttpAsyncClient;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.KeyStore;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Config {
public static final int DEFAULT_CONNECTION_TIMEOUT = 10000;
public static final int DEFAULT_MAX_CONNECTIONS = 200;
public static final int DEFAULT_MAX_PER_ROUTE = 20;
public static final int DEFAULT_CONNECT_TIMEOUT = 10000;
public static final int DEFAULT_SOCKET_TIMEOUT = 60000;
private Optional<Client> client = Optional.empty();
private Optional<AsyncClient> asyncClient = Optional.empty();
private Optional<ObjectMapper> objectMapper = Optional.empty();
private List<HttpRequestInterceptor> interceptors = new ArrayList<>();
private Headers headers;
private Proxy proxy;
private int connectionTimeout;
private int socketTimeout;
private int maxTotal;
private int maxPerRoute;
private boolean followRedirects;
private boolean cookieManagement;
private boolean useSystemProperties;
private String defaultResponseEncoding = StandardCharsets.UTF_8.name();
private Function<Config, AsyncClient> asyncBuilder;
private Function<Config, Client> clientBuilder;
private boolean requestCompressionOn = true;
private boolean automaticRetries;
private boolean verifySsl = true;
private boolean addShutdownHook = false;
private KeyStore keystore;
private Supplier<String> keystorePassword = () -> null;
private String cookieSpec;
private UniMetric metrics = new NoopMetric();
public Config() {
setDefaults();
try {
asyncBuilder = ApacheAsyncClient::new;
clientBuilder = ApacheClient::new;
}catch (BootstrapMethodError e){
throw new UnirestException("It looks like you are using an older version of Apache Http Client. \n" +
"For security and performance reasons Unirest requires the most recent version. Please upgrade.", e);
}
}
private void setDefaults() {
interceptors.clear();
proxy = null;
headers = new Headers();
connectionTimeout = DEFAULT_CONNECTION_TIMEOUT;
socketTimeout = DEFAULT_SOCKET_TIMEOUT;
maxTotal = DEFAULT_MAX_CONNECTIONS;
maxPerRoute = DEFAULT_MAX_PER_ROUTE;
followRedirects = true;
cookieManagement = true;
requestCompressionOn = true;
automaticRetries = true;
verifySsl = true;
keystore = null;
keystorePassword = null;
}
/**
* Set the HttpClient implementation to use for every synchronous request
*
* @param httpClient Custom httpClient implementation
* @return this config object
*/
public Config httpClient(HttpClient httpClient) {
client = Optional.of(new ApacheClient(httpClient, this, null, null));
return this;
}
/**
* Set the HttpClient implementation to use for every synchronous request
*
* @param httpClient Custom httpClient implementation
* @return this config object
*/
public Config httpClient(Client httpClient) {
client = Optional.of(httpClient);
return this;
}
/**
* Provide a builder for a client
*
* @param httpClient Custom httpClient implementation
* @return this config object
*/
public Config httpClient(Function<Config, Client> httpClient) {
clientBuilder = httpClient;
return this;
}
/**
* Set the asynchronous AbstractHttpAsyncClient implementation to use for every asynchronous request
*
* @param value Custom CloseableHttpAsyncClient implementation
* @return this config object
*/
public Config asyncClient(HttpAsyncClient value) {
this.asyncClient = Optional.of(new ApacheAsyncClient(value, this, null, null));
return this;
}
/**
* Set the full async configuration including monitors. These will be shutDown on a Unirest.shudown()
*
* @param value Custom AsyncConfig class. The actual AsyncHttpClient is required.
* @return this config object
*/
public Config asyncClient(AsyncClient value) {
asyncClient = Optional.of(value);
return this;
}
/**
* Set the full async configuration including monitors. These will be shutDown on a Unirest.shudown()
*
* @param asyncClientBuilder A builder function for creating a AsyncClient
* @return this config object
*/
public Config asyncClient(Function<Config, AsyncClient> asyncClientBuilder) {
this.asyncBuilder = asyncClientBuilder;
return this;
}
/**
* Set a proxy
*
* @param value Proxy settings object.
* @return this config object
*/
public Config proxy(Proxy value) {
validateClientsNotRunning();
this.proxy = value;
return this;
}
/**
* Set a proxy
*
* @param host the hostname of the proxy server.
* @param port the port of the proxy server
* @return this config object
*/
public Config proxy(String host, int port) {
return proxy(new Proxy(host, port));
}
/**
* Set an authenticated proxy
*
* @param host the hostname of the proxy server.
* @param port the port of the proxy server
* @param username username for authenticated proxy
* @param password password for authenticated proxy
* @return this config object
*/
public Config proxy(String host, int port, String username, String password) {
return proxy(new Proxy(host, port, username, password));
}
/**
* Set the ObjectMapper implementation to use for Response to Object binding
*
* @param om Custom implementation of ObjectMapper interface
* @return this config object
*/
public Config setObjectMapper(ObjectMapper om) {
this.objectMapper = Optional.ofNullable(om);
return this;
}
/**
* Set a custom keystore
*
* @param store the keystore to use for a custom ssl context
* @param password the password for the store
* @return this config object
*/
public Config clientCertificateStore(KeyStore store, String password) {
this.keystore = store;
this.keystorePassword = () -> password;
return this;
}
/**
* Set a custom keystore via a file path. Must be a valid PKCS12 file
*
* @param fileLocation the path keystore to use for a custom ssl context
* @param password the password for the store
* @return this config object
*/
public Config clientCertificateStore(String fileLocation, String password) {
try (InputStream keyStoreStream = Util.getFileInputStream(fileLocation)) {
this.keystorePassword = () -> password;
this.keystore = KeyStore.getInstance("PKCS12");
this.keystore.load(keyStoreStream, keystorePassword.get().toCharArray());
} catch (Exception e) {
throw new UnirestConfigException(e);
}
return this;
}
/**
* Set the connection timeout
*
* @param inMillies The timeout until a connection with the server is established (in milliseconds). Default is 10000. Set to zero to disable the timeout.
* @return this config object
*/
public Config connectTimeout(int inMillies) {
validateClientsNotRunning();
this.connectionTimeout = inMillies;
return this;
}
/**
* Set the socket timeout
*
* @param inMillies The timeout to receive data (in milliseconds). Default is 60000. Set to zero to disable the timeout.
* @return this config object
*/
public Config socketTimeout(int inMillies) {
validateClientsNotRunning();
this.socketTimeout = inMillies;
return this;
}
/**
* Set the concurrency levels
*
* @param total Defines the overall connection limit for a connection pool. Default is 200.
* @param perRoute Defines a connection limit per one HTTP route (this can be considered a per target host limit). Default is 20.
* @return this config object
*/
public Config concurrency(int total, int perRoute) {
validateClientsNotRunning();
this.maxTotal = total;
this.maxPerRoute = perRoute;
return this;
}
/**
* Clear default headers
* @return this config object
*/
public Config clearDefaultHeaders() {
headers.clear();
return this;
}
/**
* Default basic auth credentials
* @param username the username
* @param password the password
* @return this config object
*/
public Config setDefaultBasicAuth(String username, String password) {
headers.replace("Authorization", Util.toBasicAuthValue(username, password));
return this;
}
/**
* Set default header to appear on all requests
*
* @param name The name of the header.
* @param value The value of the header.
* @return this config object
*/
public Config setDefaultHeader(String name, String value) {
headers.replace(name, value);
return this;
}
/**
* Set default header to appear on all requests, value is through a Supplier
* This is useful for adding tracing elements to requests.
*
* @param name The name of the header.
* @param value a supplier that will get called as part of the request.
* @return this config object
*/
public Config setDefaultHeader(String name, Supplier<String> value) {
headers.add(name, value);
return this;
}
/**
* Add default header to appear on all requests
*
* @param name The name of the header.
* @param value The value of the header.
* @return this config object
*/
public Config addDefaultHeader(String name, String value) {
headers.add(name, value);
return this;
}
/**
* Add a metric object for instrumentation
* @param metric a UniMetric object
* @return this config object
*/
public Config instrumentWith(UniMetric metric) {
this.metrics = metric;
return this;
}
/**
* Add a HttpRequestInterceptor to the clients. This can be called multiple times to add as many as you like.
* https://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/HttpRequestInterceptor.html
*
* @param interceptor The addInterceptor
* @return this config object
*/
public Config addInterceptor(HttpRequestInterceptor interceptor) {
validateClientsNotRunning();
interceptors.add(interceptor);
return this;
}
/**
* Allow the client to follow redirects. Defaults to TRUE
*
* @param enable The name of the header.
* @return this config object
*/
public Config followRedirects(boolean enable) {
validateClientsNotRunning();
this.followRedirects = enable;
return this;
}
/**
* Allow the client to manage cookies. Defaults to TRUE
*
* @param enable The name of the header.
* @return this config object
*/
public Config enableCookieManagement(boolean enable) {
validateClientsNotRunning();
this.cookieManagement = enable;
return this;
}
/**
* Toggle verifying SSL/TLS certificates. Defaults to TRUE
*
* @param value a bool is its true or not.
* @return this config object
*/
public Config verifySsl(boolean value) {
this.verifySsl = value;
return this;
}
/**
* Tell the HttpClients to use the system properties for things like proxies
*
* @param value a bool is its true or not.
* @return this config object
*/
public Config useSystemProperties(boolean value) {
this.useSystemProperties = value;
return this;
}
/**
* Turn on or off requesting all content as compressed. (GZIP encoded)
* Default is true
*
* @param value a bool is its true or not.
* @return this config object
*/
public Config requestCompression(boolean value) {
this.requestCompressionOn = value;
return this;
}
/**
* Automaticly retry certain recoverable errors like socket timeouts. Up to 4 times
* Note that currently this only works on synchronous calls.
* Default is true
*
* @param value a bool is its true or not.
* @return this config object
*/
public Config automaticRetries(boolean value) {
automaticRetries = value;
return this;
}
/**
* Sets a cookie policy
* Acceptable values:
* 'default' (same as Netscape),
* 'netscape',
* 'ignoreCookies',
* 'standard' (RFC 6265 interoprability profile) ,
* 'standard-strict' (RFC 6265 strict profile)
*
* @param policy: the policy for cookies to follow
* @return this config object
*/
public Config cookieSpec(String policy) {
this.cookieSpec = policy;
return this;
}
/**
* Set the default encoding that will be used for serialization into Strings.
* The default-default is UTF-8
*
* @param value a bool is its true or not.
* @return this config object
*/
public Config setDefaultResponseEncoding(String value) {
Objects.requireNonNull(value, "Encoding cannot be null");
this.defaultResponseEncoding = value;
return this;
}
/**
* Register the client with a system shutdown hook. Note that this creates up to two threads
* (depending on if you use both sync and async clients). default is false
*
* @param value a bool is its true or not.
* @return this config object
*/
public Config addShutdownHook(boolean value) {
this.addShutdownHook = value;
if (value) {
client.ifPresent(Client::registerShutdownHook);
asyncClient.ifPresent(AsyncClient::registerShutdownHook);
}
return this;
}
/**
* Return default headers that are added to every request
*
* @return Headers
*/
public Headers getDefaultHeaders() {
return headers;
}
/**
* Does the config have currently running clients? Find out here.
*
* @return boolean
*/
public boolean isRunning() {
return client.isPresent() || asyncClient.isPresent();
}
/**
* Shutdown the current config and re-init.
*
* @return this config
*/
public Config reset() {
shutDown(false);
return this;
}
/**
* Shut down the configuration and its clients.
* The config can be re-initialized with its settings
*
* @param clearOptions should the current non-client settings be retained.
*/
public void shutDown(boolean clearOptions) {
List<Exception> ex = Stream.concat(
client.map(Client::close).orElseGet(Stream::empty),
asyncClient.map(AsyncClient::close).orElseGet(Stream::empty)
).collect(Collectors.toList());
client = Optional.empty();
asyncClient = Optional.empty();
if (clearOptions) {
setDefaults();
}
if (!ex.isEmpty()) {
throw new UnirestException(ex);
}
}
/**
* Return the current Client. One will be build if it does
* not yet exist.
*
* @return A synchronous Client
*/
public Client getClient() {
if (!client.isPresent()) {
buildClient();
}
return client.get();
}
private synchronized void buildClient() {
if (!client.isPresent()) {
client = Optional.of(clientBuilder.apply(this));
}
}
/**
* Return the current HttpAsyncClient. One will be build if it does
* not yet exist.
*
* @return Apache HttpAsyncClient
*/
public AsyncClient getAsyncClient() {
if (!asyncClientIsReady()) {
buildAsyncClient();
}
return asyncClient.get();
}
private boolean asyncClientIsReady() {
return asyncClient
.map(AsyncClient::isRunning)
.orElse(false);
}
private synchronized void buildAsyncClient() {
if (!asyncClientIsReady()) {
AsyncClient value = asyncBuilder.apply(this);
verifyIsOn(value);
asyncClient = Optional.of(value);
}
}
private void verifyIsOn(AsyncClient value) {
if (!value.isRunning()) {
throw new UnirestConfigException("Attempted to get a new async client but it was not started. Please ensure it is");
}
}
// Accessors for unirest.
/**
* @return if cookie management should be enabled.
* default: true
*/
public boolean getEnabledCookieManagement() {
return cookieManagement;
}
/**
* @return if the clients should follow redirects
* default: true
*/
public boolean getFollowRedirects() {
return followRedirects;
}
/**
* @return the maximum number of connections the clients for this config will manage at once
* default: 200
*/
public int getMaxConnections() {
return maxTotal;
}
/**
* @return the maximum number of connections per route the clients for this config will manage at once
* default: 20
*/
public int getMaxPerRoutes() {
return maxPerRoute;
}
/**
* @return the connection timeout in milliseconds
* default: 10000
*/
public int getConnectionTimeout() {
return connectionTimeout;
}
/**
* @return socket timeout in milliseconds
* default: 60000
*/
public int getSocketTimeout() {
return socketTimeout;
}
/**
* @return a security keystore if one has been provided
*/
public KeyStore getKeystore() {
return this.keystore;
}
/**
* @return The password for the keystore if provided
*/
public String getKeyStorePassword() {
return this.keystorePassword.get();
}
/**
* @return a configured object mapper
* @throws UnirestException if none has been configured.
*/
public ObjectMapper getObjectMapper() {
return objectMapper.orElseThrow(() -> new UnirestException("No Object Mapper Configured. Please config one with Unirest.config().setObjectMapper"));
}
private void validateClientsNotRunning() {
if (client.isPresent() || asyncClient.isPresent()) {
throw new UnirestConfigException(
"Http Clients are already built in order to build a new config execute Unirest.config().reset() before changing settings. \n" +
"This should be done rarely."
);
}
}
public List<HttpRequestInterceptor> getInterceptors() {
return interceptors;
}
public Proxy getProxy() {
return proxy;
}
public boolean useSystemProperties() {
return this.useSystemProperties;
}
public String getDefaultResponseEncoding() {
return defaultResponseEncoding;
}
public boolean isRequestCompressionOn() {
return requestCompressionOn;
}
public boolean isAutomaticRetries() {
return automaticRetries;
}
public boolean isVerifySsl() {
return verifySsl;
}
public boolean shouldAddShutdownHook() {
return addShutdownHook;
}
public String getCookieSpec() {
return cookieSpec;
}
public UniMetric getMetric() {
return metrics;
}
}