-
-
Notifications
You must be signed in to change notification settings - Fork 4.1k
/
Http.java
2275 lines (2004 loc) · 69.2 KB
/
Http.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 (C) Lightbend Inc. <https://www.lightbend.com>
*/
package play.mvc;
import static play.core.formatters.Multipart.escapeParamWithHTML5Strategy;
import akka.stream.Materializer;
import akka.stream.javadsl.Sink;
import akka.stream.javadsl.Source;
import akka.util.ByteString;
import com.fasterxml.jackson.databind.JsonNode;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import play.api.http.HttpConfiguration;
import play.api.libs.json.JsValue;
import play.api.mvc.Headers$;
import play.api.mvc.request.*;
import play.core.j.JavaHelpers$;
import play.core.j.JavaParsers;
import play.i18n.Lang;
import play.i18n.Messages;
import play.i18n.MessagesApi;
import play.libs.Files;
import play.libs.Json;
import play.libs.Scala;
import play.libs.XML;
import play.libs.typedmap.TypedKey;
import play.libs.typedmap.TypedMap;
import play.mvc.Http.Cookie.SameSite;
import scala.collection.immutable.Map$;
import scala.compat.java8.OptionConverters;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.cert.X509Certificate;
import java.time.Duration;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
/** Defines HTTP standard objects. */
public class Http {
public static class Headers {
private final Map<String, List<String>> headers;
public Headers(Map<String, List<String>> headers) {
this.headers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
this.headers.putAll(headers);
}
/**
* @return all the headers as a map.
* @deprecated Deprecated as of 2.8.0. Use {@link #asMap()} instead.
*/
@Deprecated
public Map<String, List<String>> toMap() {
return headers;
}
/** @return all the headers as an unmodifiable map. */
public Map<String, List<String>> asMap() {
return Collections.unmodifiableMap(headers);
}
/**
* Checks if the given header is present.
*
* @param headerName The name of the header (case-insensitive)
* @return <code>true</code> if the request did contain the header.
*/
public boolean contains(String headerName) {
return headers.containsKey(headerName);
}
/**
* Gets the header value. If more than one value is associated with this header, then returns
* the first one.
*
* @param name the header name
* @return the first header value or empty if no value available.
*/
public Optional<String> get(String name) {
return Optional.ofNullable(headers.get(name))
.flatMap(headerValues -> headerValues.stream().findFirst());
}
/**
* Get all the values associated with the header name.
*
* @param name the header name.
* @return the list of values associates with the header of empty.
*/
public List<String> getAll(String name) {
return headers.getOrDefault(name, Collections.emptyList());
}
/** @return the scala version of this headers. */
public play.api.mvc.Headers asScala() {
return new play.api.mvc.Headers(
JavaHelpers$.MODULE$.javaMapOfListToScalaSeqOfPairs(this.headers));
}
/**
* Add a new header with the given value.
*
* @param name the header name
* @param value the header value
* @return this with the new header added
* @deprecated Deprecated as of 2.8.0. Use {@link #adding(String, String)} instead.
*/
@Deprecated
public Headers addHeader(String name, String value) {
this.headers.put(name, Collections.singletonList(value));
return this;
}
/**
* Add a new header with the given value.
*
* @param name the header name
* @param value the header value
* @return a new Header instance with the new header added
*/
public Headers adding(String name, String value) {
return adding(name, Collections.singletonList(value));
}
/**
* Add a new header with the given values.
*
* @param name the header name
* @param values the header values
* @return this with the new header added
* @deprecated Deprecated as of 2.8.0. Use {@link #adding(String, List)} instead.
*/
@Deprecated
public Headers addHeader(String name, List<String> values) {
this.headers.put(name, values);
return this;
}
/**
* Add a new header with the given values.
*
* @param name the header name
* @param values the header values
* @return a new Header instance with the new header added
*/
public Headers adding(String name, List<String> values) {
Map<String, List<String>> newHeaders = new HashMap<>(this.headers.size() + 1);
newHeaders.putAll(this.headers);
newHeaders.put(name, values);
return new Headers(newHeaders);
}
/**
* Remove a header.
*
* @param name the header name.
* @return this without the removed header.
* @deprecated Deprecated as of 2.8.0. Use {@link #removing(String)} instead.
*/
@Deprecated
public Headers remove(String name) {
this.headers.remove(name);
return this;
}
/**
* Remove a header.
*
* @param name the header name.
* @return a new Header instance without the removed header.
*/
public Headers removing(String name) {
Map<String, List<String>> newHeaders = new HashMap<>(this.headers.size());
newHeaders.putAll(this.headers);
newHeaders.remove(name);
return new Headers(newHeaders);
}
}
public interface RequestHeader {
/**
* The request id. The request id is stored as an attribute indexed by {@link
* RequestAttrKey#Id()}.
*/
default Long id() {
return (Long) attrs().get(RequestAttrKey.Id().asJava());
}
/** @return The complete request URI, containing both path and query string */
String uri();
/** @return the HTTP Method */
String method();
/** @return the HTTP version */
String version();
/**
* The client IP address.
*
* <p>Retrieves the last untrusted proxy from the Forwarded-Headers or the
* X-Forwarded-*-Headers.
*
* @return the remote address
*/
String remoteAddress();
/** @return true if the client is using SSL */
boolean secure();
/** @return a map of typed attributes associated with the request. */
TypedMap attrs();
/**
* Create a new version of this object with the given attributes attached to it.
*
* @param newAttrs The new attributes to add.
* @return The new version of this object with the attributes attached.
*/
RequestHeader withAttrs(TypedMap newAttrs);
/**
* Create a new versions of this object with the given attribute attached to it.
*
* @param key The new attribute key.
* @param value The attribute value.
* @param <A> the attribute type
* @return The new version of this object with the new attribute.
*/
<A> RequestHeader addAttr(TypedKey<A> key, A value);
/**
* Create a new versions of this object with the given attribute removed.
*
* @param key The key of the attribute to remove.
* @return The new version of this object with the attribute removed.
*/
RequestHeader removeAttr(TypedKey<?> key);
/**
* Attach a body to this header.
*
* @param body The body to attach.
* @return A new request with the body attached to the header.
*/
Request withBody(RequestBody body);
/** @return the request host */
String host();
/** @return the URI path */
String path();
/**
* The Request Langs extracted from the Accept-Language header and sorted by preference
* (preferred first).
*
* @return the preference-ordered list of languages accepted by the client
*/
List<Lang> acceptLanguages();
/**
* @return The media types set in the request Accept header, sorted by preference (preferred
* first)
*/
List<play.api.http.MediaRange> acceptedTypes();
/**
* Check if this request accepts a given media type.
*
* @param mimeType the mimeType to check for support.
* @return true if <code>mimeType</code> is in the Accept header, otherwise false
*/
boolean accepts(String mimeType);
/**
* The query string content.
*
* @return the query string map
*/
Map<String, String[]> queryString();
/**
* Helper method to access a queryString parameter.
*
* @param key the query string parameter to look up
* @return the value for the provided <code>key</code>.
* @deprecated Deprecated as of 2.8.0. Use {@link #queryString(String)} instead.
*/
@Deprecated
String getQueryString(String key);
/**
* Helper method to access a queryString parameter.
*
* @param key the query string parameter to look up
* @return the value for the provided <code>key</code>, if it exists.
*/
Optional<String> queryString(String key);
/** @return the request cookies */
Cookies cookies();
/**
* @param name Name of the cookie to retrieve
* @return the cookie, if found, otherwise null
* @deprecated Deprecated as of 2.8.0. Use {@link #getCookie(String)} instead.
*/
@Deprecated
Cookie cookie(String name);
/**
* @param name Name of the cookie to retrieve
* @return the cookie, if found
*/
Optional<Cookie> getCookie(String name);
/**
* Parses the Session cookie and returns the Session data. The request's session cookie is
* stored in an attribute indexed by {@link RequestAttrKey#Session()}. The attribute uses a
* {@link Cell} to store the session cookie, to allow it to be evaluated on-demand.
*/
default Session session() {
return attrs().get(RequestAttrKey.Session().asJava()).value().asJava();
}
/**
* Parses the Flash cookie and returns the Flash data. The request's flash cookie is stored in
* an attribute indexed by {@link RequestAttrKey#Flash()}}. The attribute uses a {@link Cell} to
* store the flash, to allow it to be evaluated on-demand.
*/
default Flash flash() {
return attrs().get(RequestAttrKey.Flash().asJava()).value().asJava();
}
/**
* Retrieve all headers.
*
* @return the request headers for this request.
*/
Headers getHeaders();
/**
* Retrieves a single header.
*
* @param headerName The name of the header (case-insensitive)
* @return the value corresponding to <code>headerName</code>, or empty if it was not present
*/
default Optional<String> header(String headerName) {
return getHeaders().get(headerName);
}
/**
* Checks if the request has the header.
*
* @param headerName The name of the header (case-insensitive)
* @return <code>true</code> if the request did contain the header.
*/
default boolean hasHeader(String headerName) {
return getHeaders().contains(headerName);
}
/** @return true if request has a body, false otherwise. */
boolean hasBody();
/** @return The request content type excluding the charset, if it exists. */
Optional<String> contentType();
/** @return The request charset, which comes from the content type header, if it exists. */
Optional<String> charset();
/**
* The X509 certificate chain presented by a client during SSL requests.
*
* @return The chain of X509Certificates used for the request if the request is secure and the
* server supports it.
*/
Optional<List<X509Certificate>> clientCertificateChain();
/**
* Create a new version of this object with the given transient language set. The transient
* language will be taken into account when using {@link MessagesApi#preferred(RequestHeader)}}
* (It will take precedence over any other language).
*
* @param lang The language to use.
* @return The new version of this object with the given transient language set.
*/
default RequestHeader withTransientLang(Lang lang) {
return addAttr(Messages.Attrs.CurrentLang, lang);
}
/**
* Create a new version of this object with the given transient language set. The transient
* language will be taken into account when using {@link MessagesApi#preferred(RequestHeader)}}
* (It will take precedence over any other language).
*
* @param code The language to use.
* @return The new version of this object with the given transient language set.
* @deprecated Deprecated as of 2.8.0 Use {@link #withTransientLang(Lang)} instead.
*/
@Deprecated
default RequestHeader withTransientLang(String code) {
return addAttr(Messages.Attrs.CurrentLang, Lang.forCode(code));
}
/**
* Create a new version of this object with the given transient language set. The transient
* language will be taken into account when using {@link MessagesApi#preferred(RequestHeader)}}
* (It will take precedence over any other language).
*
* @param locale The language to use.
* @return The new version of this object with the given transient language set.
*/
default RequestHeader withTransientLang(Locale locale) {
return addAttr(Messages.Attrs.CurrentLang, new Lang(locale));
}
/**
* Create a new version of this object with the given transient language removed.
*
* @return The new version of this object with the transient language removed.
*/
default RequestHeader withoutTransientLang() {
return removeAttr(Messages.Attrs.CurrentLang);
}
/**
* The transient language will be taken into account when using {@link
* MessagesApi#preferred(RequestHeader)}} (It will take precedence over any other language).
*
* @return The current transient language of this request.
*/
default Optional<Lang> transientLang() {
return attrs().getOptional(Messages.Attrs.CurrentLang).map(play.api.i18n.Lang::asJava);
}
/**
* @return the Scala version for this request header.
* @see play.api.mvc.RequestHeader
*/
play.api.mvc.RequestHeader asScala();
}
/** An HTTP request. */
public interface Request extends RequestHeader {
/** @return the request body */
RequestBody body();
Request withBody(RequestBody body);
// Override return type
Request withAttrs(TypedMap newAttrs);
// Override return type
<A> Request addAttr(TypedKey<A> key, A value);
// Override return type
Request removeAttr(TypedKey<?> key);
// Override return type and provide default implementation
default Request withTransientLang(Lang lang) {
return addAttr(Messages.Attrs.CurrentLang, lang);
}
// Override return type and provide default implementation
@Deprecated
default Request withTransientLang(String code) {
return addAttr(Messages.Attrs.CurrentLang, Lang.forCode(code));
}
// Override return type and provide default implementation
default Request withTransientLang(Locale locale) {
return addAttr(Messages.Attrs.CurrentLang, new Lang(locale));
}
// Override return type and provide default implementation
default Request withoutTransientLang() {
return removeAttr(Messages.Attrs.CurrentLang);
}
/** @return the underlying (Scala API) request. */
play.api.mvc.Request<RequestBody> asScala();
}
/** An HTTP request. */
public static class RequestImpl extends play.core.j.RequestImpl {
/**
* Constructor only based on a header.
*
* @param header the header from a request
* @deprecated Since 2.7.0. Use {@link #RequestImpl(play.api.mvc.Request)} instead.
*/
@Deprecated
public RequestImpl(play.api.mvc.RequestHeader header) {
super(header.withBody(null));
}
/**
* Constructor with a {@link RequestBody}.
*
* @param request the body of the request
*/
public RequestImpl(play.api.mvc.Request<RequestBody> request) {
super(request);
}
}
/** The builder for building a request. */
public static class RequestBuilder {
protected play.api.mvc.Request<RequestBody> req;
/**
* Returns a simple request builder. The initial request is "GET / HTTP/1.1" from 127.0.0.1 over
* an insecure connection. The request is created using the default factory.
*/
public RequestBuilder() {
this(new DefaultRequestFactory(HttpConfiguration.createWithDefaults()));
// Add a host of "localhost" to validate against the AllowedHostsFilter.
this.host("localhost");
}
/** Returns a request builder as copy of the passed request builder. */
public RequestBuilder(RequestBuilder copy) {
req = copy.req;
}
/**
* Returns a simple request builder. The initial request is "GET / HTTP/1.1" from 127.0.0.1 over
* an insecure connection. The request is created using the given factory.
*
* @param requestFactory the incoming request factory
*/
public RequestBuilder(RequestFactory requestFactory) {
req =
requestFactory.createRequest(
RemoteConnection$.MODULE$.apply(
"127.0.0.1", false, OptionConverters.toScala(Optional.empty())),
"GET",
RequestTarget$.MODULE$.apply("/", "/", Map$.MODULE$.empty()),
"HTTP/1.1",
Headers$.MODULE$.create(),
TypedMap.empty().asScala(),
new RequestBody(null));
}
/** @return the request body, if a previously the body has been set */
public RequestBody body() {
return req.body();
}
/**
* Set the body of the request.
*
* @param body the body
* @param contentType Content-Type header value
* @return the modified builder
*/
protected RequestBuilder body(RequestBody body, String contentType) {
header(HeaderNames.CONTENT_TYPE, contentType);
body(body);
return this;
}
/**
* Set the body of the request.
*
* @param body The body.
* @return the modified builder
*/
protected RequestBuilder body(RequestBody body) {
if (body == null || body.as(Object.class) == null) {
// assume null signifies no body; RequestBody is a wrapper for the actual body content
headers(
getHeaders()
.removing(HeaderNames.CONTENT_LENGTH)
.removing(HeaderNames.TRANSFER_ENCODING));
} else {
if (!getHeaders().get(HeaderNames.TRANSFER_ENCODING).isPresent()) {
final MultipartFormData<?> multipartFormData = body.asMultipartFormData();
if (multipartFormData != null) {
header(
HeaderNames.CONTENT_LENGTH,
Long.toString(calcMultipartFormDataBodyLength(multipartFormData)));
} else {
int length = body.asBytes().length();
header(HeaderNames.CONTENT_LENGTH, Integer.toString(length));
}
}
}
req = req.withBody(body);
return this;
}
private long calcMultipartFormDataBodyLength(final MultipartFormData<?> multipartFormData) {
final String boundaryToContentTypeStart = MultipartFormatter.boundaryToContentType("");
final String boundary =
getHeaders()
.get(HeaderNames.CONTENT_TYPE)
.filter(ct -> ct.startsWith(boundaryToContentTypeStart))
.map(ct -> "\r\n--" + ct.substring(boundaryToContentTypeStart.length()))
.orElseThrow(
() ->
new RuntimeException(
("Content-Type header starting with \""
+ boundaryToContentTypeStart
+ "\" needs to be present")));
long dataSizeSum =
multipartFormData.asFormUrlEncoded().entrySet().stream()
.mapToLong(
dataPart ->
Arrays.stream(dataPart.getValue())
.mapToLong(
value ->
partLength(
boundary,
"form-data",
dataPart.getKey()
+ (dataPart.getValue().length > 1 ? "[]" : ""),
null,
null,
value))
.sum())
.sum();
long fileHeadersSizeSum =
multipartFormData.getFiles().stream()
.mapToLong(
filePart ->
// Pass empty body because we add the file size sum later instead anyway (see
// next assignment below)
partLength(
boundary,
filePart.getDispositionType(),
filePart.getKey(),
filePart.getFilename(),
filePart.getContentType(),
""))
.sum();
long fileSizeSum =
multipartFormData.getFiles().stream()
.mapToLong(MultipartFormData.FilePart::getFileSize)
.sum();
long length = dataSizeSum + fileHeadersSizeSum + fileSizeSum;
if (length > 0) {
// Remove trailing "\r\n" from first boundary
length -= 2;
// Add last boundary with double dash (--) at the end
length += (boundary + "--").getBytes(StandardCharsets.UTF_8).length;
}
return length;
}
private int partLength(
final String boundary,
final String dispositionType,
final String name,
final String filename,
final String contentType,
final String body) {
final String part =
boundary
+ "\r\n"
+ "Content-Disposition: "
+ dispositionType
+ "; name=\""
+ escapeParamWithHTML5Strategy(name)
+ "\""
+ (filename != null
? "; filename=\"" + escapeParamWithHTML5Strategy(filename) + "\""
: "")
+ "\r\n"
+ (contentType != null ? "Content-Type: " + contentType + "\r\n" : "")
+ "\r\n"
+ body;
return part.getBytes(StandardCharsets.UTF_8).length;
}
/**
* Set a Binary Data to this request using a singleton temp file creator The {@code
* Content-Type} header of the request is set to {@code application/octet-stream}.
*
* @param data the Binary Data
* @return the modified builder
*/
public RequestBuilder bodyRaw(ByteString data) {
final Files.TemporaryFileCreator tempFileCreator = Files.singletonTemporaryFileCreator();
play.api.mvc.RawBuffer buffer =
new play.api.mvc.RawBuffer(data.size(), tempFileCreator.asScala(), data);
return body(new RequestBody(JavaParsers.toJavaRaw(buffer)), "application/octet-stream");
}
/**
* Set a Binary Data to this request. The {@code Content-Type} header of the request is set to
* {@code application/octet-stream}.
*
* @param data the Binary Data
* @param tempFileCreator the temporary file creator for binary data.
* @return the modified builder
*/
public RequestBuilder bodyRaw(ByteString data, Files.TemporaryFileCreator tempFileCreator) {
play.api.mvc.RawBuffer buffer =
new play.api.mvc.RawBuffer(data.size(), tempFileCreator.asScala(), data);
return body(new RequestBody(JavaParsers.toJavaRaw(buffer)), "application/octet-stream");
}
/**
* Set a Binary Data to this request using a singleton temporary file creator. The {@code
* Content-Type} header of the request is set to {@code application/octet-stream}.
*
* @param data the Binary Data
* @return the modified builder
*/
public RequestBuilder bodyRaw(byte[] data) {
Files.TemporaryFileCreator tempFileCreator = Files.singletonTemporaryFileCreator();
return bodyRaw(ByteString.fromArray(data), tempFileCreator);
}
/**
* Set a Binary Data to this request. The {@code Content-Type} header of the request is set to
* {@code application/octet-stream}.
*
* @param data the Binary Data
* @param tempFileCreator the temporary file creator for binary data.
* @return the modified builder
*/
public RequestBuilder bodyRaw(byte[] data, Files.TemporaryFileCreator tempFileCreator) {
return bodyRaw(ByteString.fromArray(data), tempFileCreator);
}
/**
* Set a Form url encoded body to this request.
*
* @param data the x-www-form-urlencoded parameters
* @return the modified builder
*/
public RequestBuilder bodyFormArrayValues(Map<String, String[]> data) {
return body(new RequestBody(data), "application/x-www-form-urlencoded");
}
/**
* Set a Form url encoded body to this request.
*
* @param data the x-www-form-urlencoded parameters
* @return the modified builder
*/
public RequestBuilder bodyForm(Map<String, String> data) {
Map<String, String[]> arrayValues = new HashMap<>();
for (Entry<String, String> entry : data.entrySet()) {
arrayValues.put(entry.getKey(), new String[] {entry.getValue()});
}
return bodyFormArrayValues(arrayValues);
}
/**
* Set a Multipart Form url encoded body to this request saving it as a raw body.
*
* @param data the multipart-form parameters
* @param temporaryFileCreator the temporary file creator.
* @param mat a Akka Streams Materializer
* @return the modified builder
* @deprecated Deprecated as of 2.7.0. Renamed to {@link #bodyRaw(List,
* Files.TemporaryFileCreator, Materializer)}.
*/
@Deprecated
public RequestBuilder bodyMultipart(
List<MultipartFormData.Part<Source<ByteString, ?>>> data,
Files.TemporaryFileCreator temporaryFileCreator,
Materializer mat) {
return bodyRaw(data, temporaryFileCreator, mat);
}
/**
* Set a Multipart Form url encoded body to this request saving it as a raw body.
*
* @param data the multipart-form parameters
* @param temporaryFileCreator the temporary file creator.
* @param mat a Akka Streams Materializer
* @return the modified builder
*/
public RequestBuilder bodyRaw(
List<MultipartFormData.Part<Source<ByteString, ?>>> data,
Files.TemporaryFileCreator temporaryFileCreator,
Materializer mat) {
String boundary = MultipartFormatter.randomBoundary();
try {
ByteString materializedData =
MultipartFormatter.transform(Source.from(data), boundary)
.runWith(Sink.reduce(ByteString::concat), mat)
.toCompletableFuture()
.get();
play.api.mvc.RawBuffer buffer =
new play.api.mvc.RawBuffer(
materializedData.size(), temporaryFileCreator.asScala(), materializedData);
return body(
new RequestBody(JavaParsers.toJavaRaw(buffer)),
MultipartFormatter.boundaryToContentType(boundary));
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException("Failure while materializing Multipart/Form Data", e);
}
}
/**
* Set a Multipart Form url encoded body to this request.
*
* @param formData the URL form-encoded data part
* @param files the files part
* @return the modified builder
*/
public RequestBuilder bodyMultipart(
Map<String, String[]> formData, List<MultipartFormData.FilePart> files) {
MultipartFormData multipartFormData =
new MultipartFormData() {
@Override
public Map<String, String[]> asFormUrlEncoded() {
return Collections.unmodifiableMap(formData);
}
@Override
public List<FilePart> getFiles() {
return Collections.unmodifiableList(files);
}
};
return body(
new RequestBody(multipartFormData),
MultipartFormatter.boundaryToContentType(MultipartFormatter.randomBoundary()));
}
/**
* Set a Json Body to this request. The {@code Content-Type} header of the request is set to
* {@code application/json}.
*
* @param node the Json Node
* @return this builder, updated
*/
public RequestBuilder bodyJson(JsonNode node) {
return body(new RequestBody(node), "application/json");
}
/**
* Set a Json Body to this request. The {@code Content-Type} header of the request is set to
* {@code application/json}.
*
* @param json the JsValue
* @return the modified builder
*/
public RequestBuilder bodyJson(JsValue json) {
return bodyJson(Json.parse(play.api.libs.json.Json.stringify(json)));
}
/**
* Set a XML to this request. The {@code Content-Type} header of the request is set to {@code
* application/xml}.
*
* @param xml the XML
* @return the modified builder
*/
public RequestBuilder bodyXml(InputSource xml) {
return bodyXml(XML.fromInputSource(xml));
}
/**
* Set a XML to this request.
*
* <p>The {@code Content-Type} header of the request is set to {@code application/xml}.
*
* @param xml the XML
* @return the modified builder
*/
public RequestBuilder bodyXml(Document xml) {
return body(new RequestBody(xml), "application/xml");
}
/**
* Set a Text to this request. The {@code Content-Type} header of the request is set to {@code
* text/plain}.
*
* @param text the text, assumed to be encoded in US_ASCII format, per
* https://tools.ietf.org/html/rfc6657#section-4
* @return this builder, updated
*/
public RequestBuilder bodyText(String text) {
return body(new RequestBody(text), "text/plain");
}
/**
* Set a Text to this request. The {@code Content-Type} header of the request is set to {@code
* text/plain; charset=$charset}.
*
* @param text the text, which is assumed to be already encoded in the format defined by
* charset.
* @param charset the character set that the request is encoded in.
* @return this builder, updated
*/
public RequestBuilder bodyText(String text, Charset charset) {
return body(new RequestBody(text), "text/plain; charset=" + charset.name());
}
/**
* Builds the request.
*
* @return a build of the given parameters
*/
public RequestImpl build() {
return new RequestImpl(req);
}
// -------------------
// REQUEST HEADER CODE
/** @return the id of the request */
public Long id() {
return req.id();
}
/**
* @param id the id to be used
* @return the builder instance
*/
public RequestBuilder id(Long id) {
attr(new TypedKey<>(RequestAttrKey.Id()), id);
return this;
}
/**
* Add an attribute to the request.
*
* @param key The key of the attribute to add.
* @param value The value of the attribute to add.
* @param <T> The type of the attribute to add.
* @return the request builder with extra attribute
*/
public <T> RequestBuilder attr(TypedKey<T> key, T value) {
req = req.addAttr(key.asScala(), value);
return this;
}
/**
* Update the request attributes. This replaces all existing attributes.
*
* @param newAttrs The attribute entries to add.
* @return the request builder with extra attributes set.
*/
public RequestBuilder attrs(TypedMap newAttrs) {
req = req.withAttrs(newAttrs.asScala());
return this;
}
/** @return the request builder's request attributes. */
public TypedMap attrs() {
return new TypedMap(req.attrs());
}
/** @return the builder instance. */
public String method() {
return req.method();
}
/**
* @param method sets the method
* @return the builder instance
*/
public RequestBuilder method(String method) {
req = req.withMethod(method);
return this;
}
/** @return gives the uri of the request */
public String uri() {
return req.uri();
}
public RequestBuilder uri(URI uri) {
req = JavaHelpers$.MODULE$.updateRequestWithUri(req, uri);
return this;
}
/**
* Sets the uri.
*