-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathRequestBuilderBase.java
657 lines (577 loc) · 19.4 KB
/
RequestBuilderBase.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
/*
* Copyright 2010-2013 Ning, Inc.
*
* This program is licensed to you 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:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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 org.asynchttpclient;
import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.cookie.Cookie;
import io.netty.resolver.DefaultNameResolver;
import io.netty.resolver.NameResolver;
import io.netty.util.concurrent.ImmediateEventExecutor;
import org.asynchttpclient.channel.ChannelPoolPartitioning;
import org.asynchttpclient.cookie.CookieStore;
import org.asynchttpclient.proxy.ProxyServer;
import org.asynchttpclient.request.body.generator.BodyGenerator;
import org.asynchttpclient.request.body.generator.ReactiveStreamsBodyGenerator;
import org.asynchttpclient.request.body.multipart.Part;
import org.asynchttpclient.uri.Uri;
import org.asynchttpclient.util.UriEncoder;
import org.reactivestreams.Publisher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.InputStream;
import java.net.InetAddress;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.*;
import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_TYPE;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.asynchttpclient.util.HttpUtils.extractContentTypeCharsetAttribute;
import static org.asynchttpclient.util.MiscUtils.isNonEmpty;
import static org.asynchttpclient.util.MiscUtils.withDefault;
/**
* Builder for {@link Request}
*
* @param <T> the builder type
*/
public abstract class RequestBuilderBase<T extends RequestBuilderBase<T>> {
private final static Logger LOGGER = LoggerFactory.getLogger(RequestBuilderBase.class);
private static final Uri DEFAULT_REQUEST_URL = Uri.create("http://localhost");
public static NameResolver<InetAddress> DEFAULT_NAME_RESOLVER = new DefaultNameResolver(ImmediateEventExecutor.INSTANCE);
// builder only fields
protected UriEncoder uriEncoder;
protected List<Param> queryParams;
protected SignatureCalculator signatureCalculator;
// request fields
protected String method;
protected Uri uri;
protected InetAddress address;
protected InetAddress localAddress;
protected HttpHeaders headers;
protected ArrayList<Cookie> cookies;
protected CookieStore cookieStore;
protected byte[] byteData;
protected List<byte[]> compositeByteData;
protected String stringData;
protected ByteBuffer byteBufferData;
protected InputStream streamData;
protected BodyGenerator bodyGenerator;
protected List<Param> formParams;
protected List<Part> bodyParts;
protected String virtualHost;
protected ProxyServer proxyServer;
protected Realm realm;
protected File file;
protected Boolean followRedirect;
protected int requestTimeout;
protected int readTimeout;
protected long rangeOffset;
protected Charset charset;
protected ChannelPoolPartitioning channelPoolPartitioning = ChannelPoolPartitioning.PerHostChannelPoolPartitioning.INSTANCE;
protected NameResolver<InetAddress> nameResolver = DEFAULT_NAME_RESOLVER;
protected RequestBuilderBase(String method, boolean disableUrlEncoding) {
this(method, disableUrlEncoding, true);
}
protected RequestBuilderBase(String method, boolean disableUrlEncoding, boolean validateHeaders) {
this.method = method;
this.uriEncoder = UriEncoder.uriEncoder(disableUrlEncoding);
this.headers = new DefaultHttpHeaders(validateHeaders);
}
protected RequestBuilderBase(Request prototype) {
this(prototype, false, false);
}
protected RequestBuilderBase(Request prototype, boolean disableUrlEncoding, boolean validateHeaders) {
this.method = prototype.getMethod();
this.uriEncoder = UriEncoder.uriEncoder(disableUrlEncoding);
this.uri = prototype.getUri();
this.address = prototype.getAddress();
this.localAddress = prototype.getLocalAddress();
this.headers = new DefaultHttpHeaders(validateHeaders);
this.headers.add(prototype.getHeaders());
if (isNonEmpty(prototype.getCookies())) {
this.cookies = new ArrayList<>(prototype.getCookies());
}
this.cookieStore = prototype.getCookieStore();
this.byteData = prototype.getByteData();
this.compositeByteData = prototype.getCompositeByteData();
this.stringData = prototype.getStringData();
this.byteBufferData = prototype.getByteBufferData();
this.streamData = prototype.getStreamData();
this.bodyGenerator = prototype.getBodyGenerator();
if (isNonEmpty(prototype.getFormParams())) {
this.formParams = new ArrayList<>(prototype.getFormParams());
}
if (isNonEmpty(prototype.getBodyParts())) {
this.bodyParts = new ArrayList<>(prototype.getBodyParts());
}
this.virtualHost = prototype.getVirtualHost();
this.proxyServer = prototype.getProxyServer();
this.realm = prototype.getRealm();
this.file = prototype.getFile();
this.followRedirect = prototype.getFollowRedirect();
this.requestTimeout = prototype.getRequestTimeout();
this.readTimeout = prototype.getReadTimeout();
this.rangeOffset = prototype.getRangeOffset();
this.charset = prototype.getCharset();
this.channelPoolPartitioning = prototype.getChannelPoolPartitioning();
this.nameResolver = prototype.getNameResolver();
}
@SuppressWarnings("unchecked")
private T asDerivedType() {
return (T) this;
}
public T setUrl(String url) {
return setUri(Uri.create(url));
}
public T setUri(Uri uri) {
this.uri = uri;
return asDerivedType();
}
public T setAddress(InetAddress address) {
this.address = address;
return asDerivedType();
}
public T setLocalAddress(InetAddress address) {
this.localAddress = address;
return asDerivedType();
}
public T setVirtualHost(String virtualHost) {
this.virtualHost = virtualHost;
return asDerivedType();
}
/**
* Remove all added headers
*
* @return {@code this}
*/
public T clearHeaders() {
this.headers.clear();
return asDerivedType();
}
/**
* @param name header name
* @param value header value to set
* @return {@code this}
* @see #setHeader(CharSequence, Object)
*/
public T setHeader(CharSequence name, String value) {
return setHeader(name, (Object) value);
}
/**
* Set uni-value header for the request
*
* @param name header name
* @param value header value to set
* @return {@code this}
*/
public T setHeader(CharSequence name, Object value) {
this.headers.set(name, value);
return asDerivedType();
}
/**
* Set multi-values header for the request
*
* @param name header name
* @param values {@code Iterable} with multiple header values to set
* @return {@code this}
*/
public T setHeader(CharSequence name, Iterable<?> values) {
this.headers.set(name, values);
return asDerivedType();
}
/**
* @param name header name
* @param value header value to add
* @return {@code this}
* @see #addHeader(CharSequence, Object)
*/
public T addHeader(CharSequence name, String value) {
return addHeader(name, (Object) value);
}
/**
* Add a header value for the request. If a header with {@code name} was setup for this request already -
* call will add one more header value and convert it to multi-value header
*
* @param name header name
* @param value header value to add
* @return {@code this}
*/
public T addHeader(CharSequence name, Object value) {
if (value == null) {
LOGGER.warn("Value was null, set to \"\"");
value = "";
}
this.headers.add(name, value);
return asDerivedType();
}
/**
* Add header values for the request. If a header with {@code name} was setup for this request already -
* call will add more header values and convert it to multi-value header
*
* @param name header name
* @param values {@code Iterable} with multiple header values to add
* @return {@code}
*/
public T addHeader(CharSequence name, Iterable<?> values) {
this.headers.add(name, values);
return asDerivedType();
}
public T setHeaders(HttpHeaders headers) {
if (headers == null)
this.headers.clear();
else
this.headers = headers;
return asDerivedType();
}
/**
* Set request headers using a map {@code headers} of pair (Header name, Header values)
* This method could be used to setup multi-valued headers
*
* @param headers map of header names as the map keys and header values {@link Iterable} as the map values
* @return {@code this}
*/
public T setHeaders(Map<? extends CharSequence, ? extends Iterable<?>> headers) {
clearHeaders();
if (headers != null) {
headers.forEach((name, values) -> this.headers.add(name, values));
}
return asDerivedType();
}
/**
* Set single-value request headers using a map {@code headers} of pairs (Header name, Header value).
* To set headers with multiple values use {@link #setHeaders(Map)}
*
* @param headers map of header names as the map keys and header values as the map values
* @return {@code this}
*/
public T setSingleHeaders(Map<? extends CharSequence, ?> headers) {
clearHeaders();
if (headers != null) {
headers.forEach((name, value) -> this.headers.add(name, value));
}
return asDerivedType();
}
private void lazyInitCookies() {
if (this.cookies == null)
this.cookies = new ArrayList<>(3);
}
public T setCookies(Collection<Cookie> cookies) {
this.cookies = new ArrayList<>(cookies);
return asDerivedType();
}
public T addCookie(Cookie cookie) {
lazyInitCookies();
this.cookies.add(cookie);
return asDerivedType();
}
/**
* Add/replace a cookie based on its name
* @param cookie the new cookie
* @return this
*/
public T addOrReplaceCookie(Cookie cookie) {
String cookieKey = cookie.name();
boolean replace = false;
int index = 0;
lazyInitCookies();
for (Cookie c : this.cookies) {
if (c.name().equals(cookieKey)) {
replace = true;
break;
}
index++;
}
if (replace)
this.cookies.set(index, cookie);
else
this.cookies.add(cookie);
return asDerivedType();
}
public void resetCookies() {
if (this.cookies != null)
this.cookies.clear();
}
public T setCookieStore(CookieStore cookieStore) {
this.cookieStore = cookieStore;
return asDerivedType();
}
public void resetQuery() {
queryParams = null;
if (this.uri != null)
this.uri = this.uri.withNewQuery(null);
}
public void resetFormParams() {
this.formParams = null;
}
public void resetNonMultipartData() {
this.byteData = null;
this.compositeByteData = null;
this.byteBufferData = null;
this.stringData = null;
this.streamData = null;
this.bodyGenerator = null;
}
public void resetMultipartData() {
this.bodyParts = null;
}
public T setBody(File file) {
this.file = file;
return asDerivedType();
}
private void resetBody() {
resetFormParams();
resetNonMultipartData();
resetMultipartData();
}
public T setBody(byte[] data) {
resetBody();
this.byteData = data;
return asDerivedType();
}
public T setBody(List<byte[]> data) {
resetBody();
this.compositeByteData = data;
return asDerivedType();
}
public T setBody(String data) {
resetBody();
this.stringData = data;
return asDerivedType();
}
public T setBody(ByteBuffer data) {
resetBody();
this.byteBufferData = data;
return asDerivedType();
}
public T setBody(InputStream stream) {
resetBody();
this.streamData = stream;
return asDerivedType();
}
public T setBody(Publisher<ByteBuf> publisher) {
return setBody(publisher, -1L);
}
public T setBody(Publisher<ByteBuf> publisher, long contentLength) {
return setBody(new ReactiveStreamsBodyGenerator(publisher, contentLength));
}
public T setBody(BodyGenerator bodyGenerator) {
this.bodyGenerator = bodyGenerator;
return asDerivedType();
}
public T addQueryParam(String name, String value) {
if (queryParams == null)
queryParams = new ArrayList<>(1);
queryParams.add(new Param(name, value));
return asDerivedType();
}
public T addQueryParams(List<Param> params) {
if (queryParams == null)
queryParams = params;
else
queryParams.addAll(params);
return asDerivedType();
}
public T setQueryParams(Map<String, List<String>> map) {
return setQueryParams(Param.map2ParamList(map));
}
public T setQueryParams(List<Param> params) {
// reset existing query
if (this.uri != null && isNonEmpty(this.uri.getQuery()))
this.uri = this.uri.withNewQuery(null);
queryParams = params;
return asDerivedType();
}
public T addFormParam(String name, String value) {
resetNonMultipartData();
resetMultipartData();
if (this.formParams == null)
this.formParams = new ArrayList<>(1);
this.formParams.add(new Param(name, value));
return asDerivedType();
}
public T setFormParams(Map<String, List<String>> map) {
return setFormParams(Param.map2ParamList(map));
}
public T setFormParams(List<Param> params) {
resetNonMultipartData();
resetMultipartData();
this.formParams = params;
return asDerivedType();
}
public T addBodyPart(Part bodyPart) {
resetFormParams();
resetNonMultipartData();
if (this.bodyParts == null)
this.bodyParts = new ArrayList<>();
this.bodyParts.add(bodyPart);
return asDerivedType();
}
public T setBodyParts(List<Part> bodyParts) {
this.bodyParts = new ArrayList<>(bodyParts);
return asDerivedType();
}
public T setProxyServer(ProxyServer proxyServer) {
this.proxyServer = proxyServer;
return asDerivedType();
}
public T setProxyServer(ProxyServer.Builder proxyServerBuilder) {
this.proxyServer = proxyServerBuilder.build();
return asDerivedType();
}
public T setRealm(Realm.Builder realm) {
this.realm = realm.build();
return asDerivedType();
}
public T setRealm(Realm realm) {
this.realm = realm;
return asDerivedType();
}
public T setFollowRedirect(boolean followRedirect) {
this.followRedirect = followRedirect;
return asDerivedType();
}
public T setRequestTimeout(int requestTimeout) {
this.requestTimeout = requestTimeout;
return asDerivedType();
}
public T setReadTimeout(int readTimeout) {
this.readTimeout = readTimeout;
return asDerivedType();
}
public T setRangeOffset(long rangeOffset) {
this.rangeOffset = rangeOffset;
return asDerivedType();
}
public T setMethod(String method) {
this.method = method;
return asDerivedType();
}
public T setCharset(Charset charset) {
this.charset = charset;
return asDerivedType();
}
public T setChannelPoolPartitioning(ChannelPoolPartitioning channelPoolPartitioning) {
this.channelPoolPartitioning = channelPoolPartitioning;
return asDerivedType();
}
public T setNameResolver(NameResolver<InetAddress> nameResolver) {
this.nameResolver = nameResolver;
return asDerivedType();
}
public T setSignatureCalculator(SignatureCalculator signatureCalculator) {
this.signatureCalculator = signatureCalculator;
return asDerivedType();
}
private RequestBuilderBase<?> executeSignatureCalculator() {
if (signatureCalculator == null)
return this;
// build a first version of the request, without signatureCalculator in play
RequestBuilder rb = new RequestBuilder(this.method);
// make copy of mutable collections so we don't risk affecting
// original RequestBuilder
// call setFormParams first as it resets other fields
if (this.formParams != null)
rb.setFormParams(this.formParams);
if (this.headers != null)
rb.headers.add(this.headers);
if (this.cookies != null)
rb.setCookies(this.cookies);
if (this.bodyParts != null)
rb.setBodyParts(this.bodyParts);
// copy all other fields
// but rb.signatureCalculator, that's the whole point here
rb.uriEncoder = this.uriEncoder;
rb.queryParams = this.queryParams;
rb.uri = this.uri;
rb.address = this.address;
rb.localAddress = this.localAddress;
rb.byteData = this.byteData;
rb.compositeByteData = this.compositeByteData;
rb.stringData = this.stringData;
rb.byteBufferData = this.byteBufferData;
rb.streamData = this.streamData;
rb.bodyGenerator = this.bodyGenerator;
rb.virtualHost = this.virtualHost;
rb.proxyServer = this.proxyServer;
rb.realm = this.realm;
rb.file = this.file;
rb.followRedirect = this.followRedirect;
rb.requestTimeout = this.requestTimeout;
rb.rangeOffset = this.rangeOffset;
rb.charset = this.charset;
rb.channelPoolPartitioning = this.channelPoolPartitioning;
rb.nameResolver = this.nameResolver;
rb.cookieStore = this.cookieStore;
Request unsignedRequest = rb.build();
signatureCalculator.calculateAndAddSignature(unsignedRequest, rb);
return rb;
}
private void updateCharset() {
String contentTypeHeader = headers.get(CONTENT_TYPE);
Charset contentTypeCharset = extractContentTypeCharsetAttribute(contentTypeHeader);
charset = withDefault(contentTypeCharset, withDefault(charset, UTF_8));
if (contentTypeHeader != null && contentTypeHeader.regionMatches(true, 0, "text/", 0, 5) && contentTypeCharset == null) {
// add explicit charset to content-type header
headers.set(CONTENT_TYPE, contentTypeHeader + "; charset=" + charset.name());
}
}
private Uri computeUri() {
Uri tempUri = this.uri;
if (tempUri == null) {
LOGGER.debug("setUrl hasn't been invoked. Using {}", DEFAULT_REQUEST_URL);
tempUri = DEFAULT_REQUEST_URL;
} else {
Uri.validateSupportedScheme(tempUri);
}
return uriEncoder.encode(tempUri, queryParams);
}
public Request build() {
updateCharset();
RequestBuilderBase<?> rb = executeSignatureCalculator();
Uri finalUri = rb.computeUri();
// make copies of mutable internal collections
List<Cookie> cookiesCopy = rb.cookies == null ? Collections.emptyList() : new ArrayList<>(rb.cookies);
List<Param> formParamsCopy = rb.formParams == null ? Collections.emptyList() : new ArrayList<>(rb.formParams);
List<Part> bodyPartsCopy = rb.bodyParts == null ? Collections.emptyList() : new ArrayList<>(rb.bodyParts);
return new DefaultRequest(rb.method,
finalUri,
rb.address,
rb.localAddress,
rb.headers,
cookiesCopy,
rb.cookieStore,
rb.byteData,
rb.compositeByteData,
rb.stringData,
rb.byteBufferData,
rb.streamData,
rb.bodyGenerator,
formParamsCopy,
bodyPartsCopy,
rb.virtualHost,
rb.proxyServer,
rb.realm,
rb.file,
rb.followRedirect,
rb.requestTimeout,
rb.readTimeout,
rb.rangeOffset,
rb.charset,
rb.channelPoolPartitioning,
rb.nameResolver);
}
}