/
ClientConfiguration.java
2504 lines (2290 loc) · 103 KB
/
ClientConfiguration.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
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
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2010-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 com.amazonaws;
import com.amazonaws.annotation.NotThreadSafe;
import com.amazonaws.http.IdleConnectionReaper;
import com.amazonaws.http.SystemPropertyTlsKeyManagersProvider;
import com.amazonaws.http.TlsKeyManagersProvider;
import com.amazonaws.retry.PredefinedRetryPolicies;
import com.amazonaws.retry.RetryMode;
import com.amazonaws.retry.RetryPolicy;
import com.amazonaws.util.StringUtils;
import com.amazonaws.util.ValidationUtils;
import com.amazonaws.util.VersionInfoUtils;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Client configuration options such as proxy settings, user agent string, max retry attempts, etc.
*
* @see PredefinedClientConfigurations
*/
@NotThreadSafe
public class ClientConfiguration {
private static final Log log = LogFactory.getLog(ClientConfiguration.class);
/** The default timeout for creating new connections. */
public static final int DEFAULT_CONNECTION_TIMEOUT = 10 * 1000;
/** The default timeout for reading from a connected socket. */
public static final int DEFAULT_SOCKET_TIMEOUT = 50 * 1000;
/**
* The default timeout for a request. This is disabled by default.
*/
public static final int DEFAULT_REQUEST_TIMEOUT = 0;
/**
* The default timeout for a request. This is disabled by default.
*/
public static final int DEFAULT_CLIENT_EXECUTION_TIMEOUT = 0;
/**
* The default on whether to disable {@code Socket} proxies.
*/
public static final boolean DEFAULT_DISABLE_SOCKET_PROXY = false;
/** The default max connection pool size. */
public static final int DEFAULT_MAX_CONNECTIONS = 50;
/**
* The default on whether to utilize the USE_EXPECT_CONTINUE handshake for operations. Currently
* only honored for PUT operations.
*/
public static final boolean DEFAULT_USE_EXPECT_CONTINUE = true;
/** The default HTTP user agent header for AWS Java SDK clients. */
public static final String DEFAULT_USER_AGENT = VersionInfoUtils.getUserAgent();
/**
* Default request retry policy, including the maximum retry count of 3, the default retry
* condition and the default back-off strategy.
*
* @see PredefinedRetryPolicies#DEFAULT
* @see PredefinedRetryPolicies#DYNAMODB_DEFAULT
*/
public static final RetryPolicy DEFAULT_RETRY_POLICY = PredefinedRetryPolicies.DEFAULT;
/**
* The default on whether to use the {@link IdleConnectionReaper} to manage stale connections
*
* @see IdleConnectionReaper
*/
public static final boolean DEFAULT_USE_REAPER = true;
/**
* The default on whether to use gzip decompression.
*/
public static final boolean DEFAULT_USE_GZIP = false;
/**
* The default expiration time (in milliseconds) for a connection in the connection pool.
*/
public static final long DEFAULT_CONNECTION_TTL = -1;
/**
* The default maximum idle time (in milliseconds) for a connection in the connection pool.
*/
public static final long DEFAULT_CONNECTION_MAX_IDLE_MILLIS = 60 * 1000;
/**
* The default time a connection can be idle in the connection pool before it must be validated that it's still open.
*/
public static final int DEFAULT_VALIDATE_AFTER_INACTIVITY_MILLIS = 5 * 1000;
/**
* The default on whether to use TCP KeepAlive.
*/
public static final boolean DEFAULT_TCP_KEEP_ALIVE = false;
/**
* The default on whether to throttle retries.
*/
public static final boolean DEFAULT_THROTTLE_RETRIES = true;
/**
* The default on whether to cache response metadata.
*/
public static final boolean DEFAULT_CACHE_RESPONSE_METADATA = true;
/**
* The default response metadata cache size.
*/
public static final int DEFAULT_RESPONSE_METADATA_CACHE_SIZE = 50;
public static final int DEFAULT_MAX_CONSECUTIVE_RETRIES_BEFORE_THROTTLING = 100;
/** A prefix to the HTTP user agent header passed with all HTTP requests. */
private String userAgentPrefix = DEFAULT_USER_AGENT;
/** A suffix to the HTTP user agent header. */
private String userAgentSuffix;
/**
* The maximum number of times that a retryable failed request (ex: a 5xx response from a
* service) will be retried. Or -1 if the user has not explicitly set this value, in which case
* the configured RetryPolicy will be used to control the retry count.
*/
private int maxErrorRetry = -1;
/** The retry policy upon failed requests. **/
private RetryPolicy retryPolicy = DEFAULT_RETRY_POLICY;
/** Optionally specifies the local address to bind to */
private InetAddress localAddress;
/**
* The protocol to use when connecting to Amazon Web Services.
* <p>
* The default configuration is to use HTTPS for all requests for increased security.
*/
private Protocol protocol = Protocol.HTTPS;
/**
* The protocol to use when connecting to an HTTP proxy.
* <p>
* The default configuration is to use {@link Protocol#HTTP}.
*/
private Protocol proxyProtocol = Protocol.HTTP;
/** Optionally specifies the proxy host to connect through. */
private String proxyHost = null;
/** Optionally specifies the port on the proxy host to connect through. */
private int proxyPort = -1;
/** Optionally specifies the user name to use when connecting through a proxy. */
private String proxyUsername = null;
/** Optionally specifies the password to use when connecting through a proxy. */
private String proxyPassword = null;
/** Optional Windows domain name for configuring NTLM proxy support. */
private String proxyDomain = null;
/** Optional Windows workstation name for configuring NTLM proxy support. */
private String proxyWorkstation = null;
/** Optional specifies the hosts that should be accessed without going through the proxy. */
private String nonProxyHosts = null;
/** Specifies the proxy authentication methods that should be used, in priority order. */
private List<ProxyAuthenticationMethod> proxyAuthenticationMethods = null;
/**
* Controls whether {@link java.net.Socket}s created by the client should
* use the default {@link java.net.ProxySelector} when connecting to the
* remote host to find an appropriate proxy or connect directly to the
* host.
* <p />
* Note this property is only guaranteed to be honored when using the
* default connection factories.
*/
private boolean disableSocketProxy = DEFAULT_DISABLE_SOCKET_PROXY;
/**
* Whether to pre-emptively authenticate against a proxy server using basic authentication
*/
private boolean preemptiveBasicProxyAuth;
/** The maximum number of open HTTP connections. */
private int maxConnections = DEFAULT_MAX_CONNECTIONS;
/**
* The amount of time to wait (in milliseconds) for data to be transferred over an established,
* open connection before the connection is timed out. A value of 0 means infinity, and is not
* recommended.
*/
private int socketTimeout = DEFAULT_SOCKET_TIMEOUT;
/**
* The amount of time to wait (in milliseconds) when initially establishing a connection before
* giving up and timing out. A value of 0 means infinity, and is not recommended.
*/
private int connectionTimeout = DEFAULT_CONNECTION_TIMEOUT;
/**
* The amount of time to wait (in milliseconds) for a request to complete before giving up and
* timing out. A value of 0 means infinity. Consider setting this if a harder guarantee is
* required on the maximum amount of time a request will take for non-streaming operations, and
* are willing to spin up a background thread to enforce it.
*/
private int requestTimeout = DEFAULT_REQUEST_TIMEOUT;
private int clientExecutionTimeout = DEFAULT_CLIENT_EXECUTION_TIMEOUT;
private boolean throttleRetries = DEFAULT_THROTTLE_RETRIES;
/**
* Optional size hint (in bytes) for the low level TCP send buffer. This is an advanced option
* for advanced users who want to tune low level TCP parameters to try and squeeze out more
* performance.
*/
private int socketSendBufferSizeHint = 0;
/**
* Optional size hint (in bytes) for the low level TCP receive buffer. This is an advanced
* option for advanced users who want to tune low level TCP parameters to try and squeeze out
* more performance.
*/
private int socketReceiveBufferSizeHint = 0;
/**
* Optional whether to use the {@link IdleConnectionReaper} to manage stale connections. A
* reason for not running the {@link IdleConnectionReaper} can be if running in an environment
* where the modifyThread and modifyThreadGroup permissions are not allowed.
*/
private boolean useReaper = DEFAULT_USE_REAPER;
/**
* Optional whether to use gzip decompression when receiving HTTP responses.
*/
private boolean useGzip = DEFAULT_USE_GZIP;
/**
* Optional override to control which signature algorithm should be used to sign requests to the
* service. If not explicitly set, the client will determine the algorithm to use by inspecting
* a configuration file baked in to the SDK.
*/
private String signerOverride;
/**
* Optional expiration time for a connection in the connection pool. When a connection is
* retrieved from the connection pool, this parameter is checked to see if the connection can be
* reused.
*/
private long connectionTTL = DEFAULT_CONNECTION_TTL;
/**
* The maximum idle time for a connection in the connection pool.
*/
private long connectionMaxIdleMillis = DEFAULT_CONNECTION_MAX_IDLE_MILLIS;
private int validateAfterInactivityMillis = DEFAULT_VALIDATE_AFTER_INACTIVITY_MILLIS;
/**
* Optional override to enable support for TCP KeepAlive (not to be confused with HTTP
* KeepAlive). TCP KeepAlive can be used to detect misbehaving routers or down servers through
* the use of special, empty-data keep alive packets.
* <p>
* Actual TCP KeepAlive values (timeout, number of packets, etc) are configured via the
* operating system (sysctl on Linux, and Registry values on Windows).
*/
private boolean tcpKeepAlive = DEFAULT_TCP_KEEP_ALIVE;
/**
* Whether or not to cache response metadata.
* <p>
* Response metadata is typically used for troubleshooting issues with AWS support staff when
* services aren't acting as expected.
* </p>
* <p>
* While this feature is useful for debugging it adds overhead and disabling it may
* be desired in high throughput applications.
* </p>
*/
private boolean cacheResponseMetadata = DEFAULT_CACHE_RESPONSE_METADATA;
/**
* Size of the response metadata cache, if it is enabled.
* <p>
* Response metadata is typically used for troubleshooting issues with AWS support staff when
* services aren't acting as expected.
*/
private int responseMetadataCacheSize = DEFAULT_RESPONSE_METADATA_CACHE_SIZE;
/**
* The DNS Resolver to resolve IP addresses of Amazon Web Services.
*/
private DnsResolver dnsResolver = new SystemDefaultDnsResolver();
/**
* An instance of {@link SecureRandom} configured by the user; or the JDK default will be used
* if it is set to null or not explicitly configured.
*/
private SecureRandom secureRandom;
/**
* Headers to be added to all requests
*/
private Map<String, String> headers = new HashMap<String, String>();
/**
* Optional override to enable/disable support for HTTP/1.1 handshake utilizing EXPECT:
* 100-Continue. The default value is true.
* <p>
* The detail of HTTP Expect Continue is defined at
* <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec8.html#sec8.2.3"> Use of the 100
* (Continue) Status</a>. Setting this as false will reduce latency when you want to send small
* size of payload. It is highly recommended to use the default value if you want to transfer a
* large amount of data to the server, such as uploading a big file to S3 bucket.
*/
private boolean useExpectContinue = DEFAULT_USE_EXPECT_CONTINUE;
/**
* The maximum number of throttled retries if the initial request
* fails.
*/
private int maxConsecutiveRetriesBeforeThrottling = DEFAULT_MAX_CONSECUTIVE_RETRIES_BEFORE_THROTTLING;
/**
* Can be used to specify custom specific Apache HTTP client configurations.
*/
private final ApacheHttpClientConfig apacheHttpClientConfig;
/**
* Configuration option to disable the host prefix injection.
*
* The hostPrefix template is specified in the service model and is used by the SDK to modify the endpoint
* the request is sent to. Host prefix injection is enabled by default. This option can be set to disable the behavior.
*/
private boolean disableHostPrefixInjection;
private final AtomicReference<URLHolder> httpProxyHolder = new AtomicReference<URLHolder>();
private final AtomicReference<URLHolder> httpsProxyHolder = new AtomicReference<URLHolder>();
private TlsKeyManagersProvider tlsKeyManagersProvider;
private RetryMode retryMode;
public ClientConfiguration() {
apacheHttpClientConfig = new ApacheHttpClientConfig();
}
public ClientConfiguration(ClientConfiguration other) {
this.connectionTimeout = other.getConnectionTimeout();
this.maxConnections = other.getMaxConnections();
this.maxErrorRetry = other.getMaxErrorRetry();
this.retryPolicy = other.getRetryPolicy();
this.throttleRetries = other.useThrottledRetries();
this.localAddress = other.getLocalAddress();
this.protocol = other.getProtocol();
this.proxyProtocol = other.getProxyProtocol();
this.proxyDomain = other.getProxyDomain();
this.proxyHost = other.getProxyHost();
this.proxyPassword = other.getProxyPassword();
this.proxyPort = other.getProxyPort();
this.proxyUsername = other.getProxyUsername();
this.proxyWorkstation = other.getProxyWorkstation();
this.nonProxyHosts = other.getNonProxyHosts();
this.disableSocketProxy = other.disableSocketProxy();
this.proxyAuthenticationMethods = other.getProxyAuthenticationMethods();
this.preemptiveBasicProxyAuth = other.isPreemptiveBasicProxyAuth();
this.socketTimeout = other.getSocketTimeout();
this.requestTimeout = other.getRequestTimeout();
this.clientExecutionTimeout = other.getClientExecutionTimeout();
this.userAgentPrefix = other.getUserAgentPrefix();
this.userAgentSuffix = other.getUserAgentSuffix();
this.useReaper = other.useReaper();
this.useGzip = other.useGzip();
this.socketSendBufferSizeHint = other.getSocketBufferSizeHints()[0];
this.socketReceiveBufferSizeHint = other.getSocketBufferSizeHints()[1];
this.signerOverride = other.getSignerOverride();
this.responseMetadataCacheSize = other.getResponseMetadataCacheSize();
this.dnsResolver = other.getDnsResolver();
this.useExpectContinue = other.isUseExpectContinue();
this.apacheHttpClientConfig = new ApacheHttpClientConfig(other.getApacheHttpClientConfig());
this.cacheResponseMetadata = other.getCacheResponseMetadata();
this.connectionTTL = other.getConnectionTTL();
this.connectionMaxIdleMillis = other.getConnectionMaxIdleMillis();
this.validateAfterInactivityMillis = other.getValidateAfterInactivityMillis();
this.tcpKeepAlive = other.useTcpKeepAlive();
this.secureRandom = other.getSecureRandom();
this.headers.clear();
this.headers.putAll(other.getHeaders());
this.maxConsecutiveRetriesBeforeThrottling = other.getMaxConsecutiveRetriesBeforeThrottling();
this.disableHostPrefixInjection = other.disableHostPrefixInjection;
this.httpProxyHolder.set(other.httpProxyHolder.get());
this.httpsProxyHolder.set(other.httpsProxyHolder.get());
this.tlsKeyManagersProvider = other.tlsKeyManagersProvider;
this.retryMode = other.retryMode;
}
/**
* Returns the protocol (HTTP or HTTPS) to use when connecting to Amazon Web Services.
* <p>
* The default configuration is to use HTTPS for all requests for increased security.
* <p>
* Individual clients can also override this setting by explicitly including the protocol as
* part of the endpoint URL when calling {@link AmazonWebServiceClient#setEndpoint(String)}.
*
* @return The protocol to use when connecting to Amazon Web Services.
*/
public Protocol getProtocol() {
return protocol;
}
/**
* Sets the protocol (i.e. HTTP or HTTPS) to use when connecting to Amazon Web Services.
* <p>
* The default configuration is to use HTTPS for all requests for increased security.
* <p>
* Individual clients can also override this setting by explicitly including the protocol as
* part of the endpoint URL when calling {@link AmazonWebServiceClient#setEndpoint(String)}.
*
* @param protocol
* The protocol to use when connecting to Amazon Web Services.
*/
public void setProtocol(Protocol protocol) {
this.protocol = protocol;
}
/**
* Sets the protocol (i.e. HTTP or HTTPS) to use when connecting to Amazon Web Services, and
* returns the updated ClientConfiguration object so that additional calls may be chained
* together.
* <p>
* The default configuration is to use HTTPS for all requests for increased security.
* <p>
* Individual clients can also override this setting by explicitly including the protocol as
* part of the endpoint URL when calling {@link AmazonWebServiceClient#setEndpoint(String)}.
*
* @param protocol
* The protocol to use when connecting to Amazon Web Services.
* @return The updated ClientConfiguration object with the new max HTTP connections setting.
*/
public ClientConfiguration withProtocol(Protocol protocol) {
setProtocol(protocol);
return this;
}
/**
* Returns the maximum number of allowed open HTTP connections.
*
* @return The maximum number of allowed open HTTP connections.
*/
public int getMaxConnections() {
return maxConnections;
}
/**
* Sets the maximum number of allowed open HTTP connections.
*
* @param maxConnections
* The maximum number of allowed open HTTP connections.
*/
public void setMaxConnections(int maxConnections) {
this.maxConnections = maxConnections;
}
/**
* Sets the maximum number of allowed open HTTP connections and returns the updated
* ClientConfiguration object.
*
* @param maxConnections
* The maximum number of allowed open HTTP connections.
* @return The updated ClientConfiguration object with the new max HTTP connections setting.
*/
public ClientConfiguration withMaxConnections(int maxConnections) {
setMaxConnections(maxConnections);
return this;
}
/**
* @deprecated Replaced by {@link #getUserAgentPrefix()} and {@link #getUserAgentSuffix()}
* @return The user agent string to use when sending requests.
*/
@Deprecated
public String getUserAgent() {
return getUserAgentPrefix();
}
/**
* @deprecated Replaced by {@link #setUserAgentPrefix(String)} and {@link #setUserAgentSuffix(String)}
* @param userAgent
* The user agent string to use when sending requests.
*/
@Deprecated
public void setUserAgent(String userAgent) {
setUserAgentPrefix(userAgent);
}
/**
* @deprecated Replaced by {@link #withUserAgentPrefix(String)} and {@link #withUserAgentSuffix(String)}
* @param userAgent
* The user agent string to use when sending requests.
* @return The updated ClientConfiguration object.
*/
@Deprecated
public ClientConfiguration withUserAgent(String userAgent) {
return withUserAgentPrefix(userAgent);
}
/**
* Returns the HTTP user agent header prefix to send with all requests.
*
* @return The user agent string prefix to use when sending requests.
*/
public String getUserAgentPrefix() {
return userAgentPrefix;
}
/**
* Sets the HTTP user agent prefix to send with all requests.
*
* @param prefix
* The string to prefix to user agent to use when sending requests.
*/
public void setUserAgentPrefix(String prefix) {
this.userAgentPrefix = prefix;
}
/**
* Sets the HTTP user agent prefix header used in requests and returns the updated ClientConfiguration
* object.
*
* @param prefix
* The string to prefix to user agent to use when sending requests.
* @return The updated ClientConfiguration object.
*/
public ClientConfiguration withUserAgentPrefix(String prefix) {
setUserAgentPrefix(prefix);
return this;
}
/**
* Returns the HTTP user agent header suffix to add to the end of the user agent header on all requests.
*
* @return The user agent string suffix to use when sending requests.
*/
public String getUserAgentSuffix() {
return userAgentSuffix;
}
/**
* Sets the HTTP user agent suffix to send with all requests.
*
* @param suffix
* The string to suffix to user agent to use when sending requests.
*/
public void setUserAgentSuffix(String suffix) {
this.userAgentSuffix = suffix;
}
/**
* Sets the HTTP user agent suffix header used in requests and returns the updated ClientConfiguration
* object.
*
* @param suffix
* The string to suffix to user agent to use when sending requests.
* @return The updated ClientConfiguration object.
*/
public ClientConfiguration withUserAgentSuffix(String suffix) {
setUserAgentSuffix(suffix);
return this;
}
/**
* Returns the optional local address the client will bind to.
*
* @return The local address the client will bind to.
*/
public InetAddress getLocalAddress() {
return localAddress;
}
/**
* Sets the optional local address the client will bind to.
*
* @param localAddress
* The local address the client will bind to.
*/
public void setLocalAddress(InetAddress localAddress) {
this.localAddress = localAddress;
}
/**
* Sets the optional local address the client will bind to and returns the updated
* ClientConfiguration object.
*
* @param localAddress
* The local address the client will bind to.
* @return The updated ClientConfiguration object.
*/
public ClientConfiguration withLocalAddress(InetAddress localAddress) {
setLocalAddress(localAddress);
return this;
}
/**
* Returns the value for the given system property.
*/
private String getSystemProperty(String property) {
return System.getProperty(property);
}
/**
* Returns the value for the given environment variable.
*/
private String getEnvironmentVariable(String environmentVariable) {
String value = StringUtils.trim(System.getenv(environmentVariable));
return StringUtils.hasValue(value) ? value : null;
}
/**
* Returns the value for the given environment variable if its set, otherwise returns
* the lowercase version of variable.
*/
private String getEnvironmentVariableCaseInsensitive(String environmentVariable) {
String result = getEnvironmentVariable(environmentVariable);
return result != null ? result : getEnvironmentVariable(environmentVariable.toLowerCase());
}
/**
* @return The {@link Protocol} to use for connecting to the proxy.
*/
public Protocol getProxyProtocol() {
return proxyProtocol;
}
/**
* Set the {@link Protocol} to use for connecting to the proxy.
*
* @param proxyProtocol The protocol.
* @return The updated ClientConfiguration object.
*/
public ClientConfiguration withProxyProtocol(Protocol proxyProtocol) {
this.proxyProtocol = proxyProtocol == null ? Protocol.HTTP : proxyProtocol;
return this;
}
/**
* Set the {@link Protocol} to use for connecting to the proxy.
*
* @param proxyProtocol The protocol.
*/
public void setProxyProtocol(Protocol proxyProtocol) {
withProxyProtocol(proxyProtocol);
}
/**
* Returns the Java system property for proxy host depending on
* {@link #getProtocol()}: i.e. if protocol is https, returns
* the value of the system property https.proxyHost, otherwise
* returns value of http.proxyHost.
*/
private String getProxyHostProperty() {
return getProtocol() == Protocol.HTTPS
? getSystemProperty("https.proxyHost")
: getSystemProperty("http.proxyHost");
}
/**
* Returns the environment variable for proxy host depending on
* {@link #getProtocol()}: i.e. if protocol is https, returns
* the host in the value of the environment variable HTTPS_PROXY/https_proxy,
* otherwise, returns the host in the value of the environment
* variable HTTP_PROXY/http_proxy.
*/
private String getProxyHostEnvironment() {
URL httpProxy = getHttpProxyEnvironmentVariable();
if (httpProxy != null) {
return httpProxy.getHost();
}
return null;
}
/**
* Returns the optional proxy host the client will connect
* through. Returns either the proxyHost set on this object, or
* if not provided, checks the value of the Java system property
* for proxy host according to {@link #getProtocol()}: i.e. if
* protocol is https, returns the value of the system property
* https.proxyHost, otherwise returns value of http.proxyHost.
* If neither are set, checks the value of the environment variable
* according to {@link #getProtocol()}: i.e. if protocol is https,
* returns the host in the value of the HTTPS_PROXY/https_proxy
* environment variable, otherwise returns the host in the value
* of the HTTP_PROXY/http_proxy environment variable.
*
* @return The proxy host the client will connect through.
*/
public String getProxyHost() {
if (proxyHost != null) {
return proxyHost;
} else if (getProxyHostProperty() != null) {
return getProxyHostProperty();
} else {
return getProxyHostEnvironment();
}
}
/**
* Sets the optional proxy host the client will connect through.
*
* @param proxyHost
* The proxy host the client will connect through.
*/
public void setProxyHost(String proxyHost) {
this.proxyHost = proxyHost;
}
/**
* Sets the optional proxy host the client will connect through and returns the updated
* ClientConfiguration object.
*
* @param proxyHost
* The proxy host the client will connect through.
* @return The updated ClientConfiguration object.
*/
public ClientConfiguration withProxyHost(String proxyHost) {
setProxyHost(proxyHost);
return this;
}
/**
* Returns the Java system property for proxy port depending on
* {@link #getProtocol()}: i.e. if protocol is https, returns
* the value of the system property https.proxyPort, otherwise
* returns value of http.proxyPort. Defaults to {@link this.proxyPort}
* if the system property is not set with a valid port number.
*/
private int getProxyPortProperty() {
try {
return getProtocol() == Protocol.HTTPS
? Integer.parseInt(getSystemProperty("https.proxyPort"))
: Integer.parseInt(getSystemProperty("http.proxyPort"));
} catch (NumberFormatException e) {
return proxyPort;
}
}
/**
* Returns the environment variable for proxy port depending on
* {@link #getProtocol()}: i.e. if protocol is https, returns
* the port in the value of the environment variable HTTPS_PROXY/https_proxy,
* otherwise, returns the port in the value of the environment
* variable HTTP_PROXY/http_proxy.
*/
private int getProxyPortEnvironment() {
URL httpProxy = getHttpProxyEnvironmentVariable();
if (httpProxy != null) {
return httpProxy.getPort();
}
return proxyPort;
}
/**
* Returns the optional proxy port the client will connect
* through. Returns either the proxyPort set on this object, or
* if not provided, checks the value of the Java system property
* for proxy port according to {@link #getProtocol()}: i.e. if
* protocol is https, returns the value of the system property
* https.proxyPort, otherwise returns value of http.proxyPort.
* If neither are set, checks the value of the environment variable
* according to {@link #getProtocol()}: i.e. if protocol is https,
* returns the port in the value of the HTTPS_PROXY/https_proxy
* environment variable, otherwise returns the port in the value
* of the HTTP_PROXY/http_proxy environment variable.
*
* @return The proxy port the client will connect through.
*/
public int getProxyPort() {
if (proxyPort >= 0) {
return proxyPort;
} else if (getProxyPortProperty() >= 0) {
return getProxyPortProperty();
} else {
return getProxyPortEnvironment();
}
}
/**
* Sets the optional proxy port the client will connect through.
*
* @param proxyPort
* The proxy port the client will connect through.
*/
public void setProxyPort(int proxyPort) {
this.proxyPort = proxyPort;
}
/**
* Sets the optional proxy port the client will connect through and returns the updated
* ClientConfiguration object.
*
* @param proxyPort
* The proxy port the client will connect through.
* @return The updated ClientConfiguration object.
*/
public ClientConfiguration withProxyPort(int proxyPort) {
setProxyPort(proxyPort);
return this;
}
/**
* Set whether to disable proxies at the socket level.
*
* @param disableSocketProxy Whether to disable proxies at the socket level.
*
* @return The updated ClientConfiguration object.
*/
public ClientConfiguration withDisableSocketProxy(boolean disableSocketProxy) {
this.disableSocketProxy = disableSocketProxy;
return this;
}
/**
* Set whether to disable proxies at the socket level.
*
* @param disableSocketProxy Whether to disable proxies at the socket level.
*/
public void setDisableSocketProxy(boolean disableSocketProxy) {
withDisableSocketProxy(disableSocketProxy);
}
/**
* @return Whether to disable proxies at the socket level.
*/
public boolean disableSocketProxy() {
return disableSocketProxy;
}
/**
* Returns the Java system property for proxy user name depending on
* {@link #getProtocol()}: i.e. if protocol is https, returns
* the value of the system property https.proxyUser, otherwise
* returns value of http.proxyUser.
*/
private String getProxyUsernameProperty() {
return (getProtocol() == Protocol.HTTPS)
? getSystemProperty("https.proxyUser")
: getSystemProperty("http.proxyUser");
}
/**
* Returns the environment variable for proxy host depending on
* {@link #getProtocol()}: i.e. if protocol is https, returns
* the user name in the value of the environment variable
* HTTPS_PROXY/https_proxy, otherwise, returns the user name in
* the value of the environment variable HTTP_PROXY/http_proxy.
*/
private String getProxyUsernameEnvironment() {
URL httpProxy = getHttpProxyEnvironmentVariable();
if (httpProxy != null) {
try {
return httpProxy.getUserInfo().split(":", 2)[0];
} catch (Exception ignored) {
}
}
return null;
}
/**
* Returns the optional proxy user name to use if connecting
* through a proxy. Returns either the proxyUsername set on this
* object, or if not provided, checks the value of the Java system
* property for proxy user name according to {@link #getProtocol()}:
* i.e. if protocol is https, returns the value of the system
* property https.proxyUser, otherwise returns value of
* http.proxyUser. If neither are set, checks the value of the
* environment variable according to {@link #getProtocol()}: i.e.
* if protocol is https, returns the user name in the value of the
* HTTPS_PROXY/https_proxy environment variable, otherwise returns
* the user name in the value of the HTTP_PROXY/http_proxy environment
* variable.
*
* @return The optional proxy user name the configured client will use if connecting through a
* proxy.
*/
public String getProxyUsername() {
if (proxyUsername != null) {
return proxyUsername;
} else if (getProxyUsernameProperty() != null) {
return getProxyUsernameProperty();
} else {
return getProxyUsernameEnvironment();
}
}
/**
* Sets the optional proxy user name to use if connecting through a proxy.
*
* @param proxyUsername
* The proxy user name to use if connecting through a proxy.
*/
public void setProxyUsername(String proxyUsername) {
this.proxyUsername = proxyUsername;
}
/**
* Sets the optional proxy user name and returns the updated ClientConfiguration object.
*
* @param proxyUsername
* The proxy user name to use if connecting through a proxy.
* @return The updated ClientConfiguration object.
*/
public ClientConfiguration withProxyUsername(String proxyUsername) {
setProxyUsername(proxyUsername);
return this;
}
/**
* Returns the Java system property for proxy password depending on
* {@link #getProtocol()}: i.e. if protocol is https, returns
* the value of the system property https.proxyPassword, otherwise
* returns value of http.proxyPassword.
*/
private String getProxyPasswordProperty() {
return (getProtocol() == Protocol.HTTPS)
? getSystemProperty("https.proxyPassword")
: getSystemProperty("http.proxyPassword");
}
/**
* Returns the environment variable for proxy host depending on
* {@link #getProtocol()}: i.e. if protocol is https, returns
* the password in the value of the environment variable HTTPS_PROXY/https_proxy,
* otherwise, returns the password in the value of the environment
* variable HTTP_PROXY/http_proxy.
*/
private String getProxyPasswordEnvironment() {
URL httpProxy = getHttpProxyEnvironmentVariable();
if (httpProxy != null) {
try {
return httpProxy.getUserInfo().split(":", 2)[1];
} catch (Exception ignored) {
}
}
return null;
}
/**
* Returns the optional proxy password to use if connecting
* through a proxy. Returns either the proxyPassword set on this
* object, or if not provided, checks the value of the Java system
* property for proxy password according to {@link #getProtocol()}:
* i.e. if protocol is https, returns the value of the system
* property https.proxyPassword, otherwise returns value of
* http.proxyPassword. If neither are set, checks the value of the
* environment variable according to {@link #getProtocol()}: i.e. if
* protocol is https, returns the password in the value of the
* HTTPS_PROXY/https_proxy environment variable, otherwise returns
* the password in the value of the HTTP_PROXY/http_proxy environment
* variable.
*
* @return The password to use when connecting through a proxy.
*/
public String getProxyPassword() {
if (proxyPassword != null) {
return proxyPassword;
} else if (getProxyPasswordProperty() != null) {
return getProxyPasswordProperty();
} else {
return getProxyPasswordEnvironment();
}
}