-
Notifications
You must be signed in to change notification settings - Fork 37.7k
/
RequestPredicates.java
1099 lines (923 loc) · 33.5 KB
/
RequestPredicates.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 2002-2020 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.web.reactive.function.server;
import java.net.InetSocketAddress;
import java.net.URI;
import java.security.Principal;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.codec.HttpMessageReader;
import org.springframework.http.codec.multipart.Part;
import org.springframework.http.server.PathContainer;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.MultiValueMap;
import org.springframework.web.cors.reactive.CorsUtils;
import org.springframework.web.reactive.function.BodyExtractor;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebSession;
import org.springframework.web.util.UriBuilder;
import org.springframework.web.util.UriUtils;
import org.springframework.web.util.pattern.PathPattern;
import org.springframework.web.util.pattern.PathPatternParser;
/**
* Implementations of {@link RequestPredicate} that implement various useful
* request matching operations, such as matching based on path, HTTP method, etc.
*
* @author Arjen Poutsma
* @since 5.0
*/
public abstract class RequestPredicates {
private static final Log logger = LogFactory.getLog(RequestPredicates.class);
/**
* Return a {@code RequestPredicate} that always matches.
* @return a predicate that always matches
*/
public static RequestPredicate all() {
return request -> true;
}
/**
* Return a {@code RequestPredicate} that matches if the request's
* HTTP method is equal to the given method.
* @param httpMethod the HTTP method to match against
* @return a predicate that tests against the given HTTP method
*/
public static RequestPredicate method(HttpMethod httpMethod) {
return new HttpMethodPredicate(httpMethod);
}
/**
* Return a {@code RequestPredicate} that matches if the request's
* HTTP method is equal to one the of the given methods.
* @param httpMethods the HTTP methods to match against
* @return a predicate that tests against the given HTTP methods
* @since 5.1
*/
public static RequestPredicate methods(HttpMethod... httpMethods) {
return new HttpMethodPredicate(httpMethods);
}
/**
* Return a {@code RequestPredicate} that tests the request path
* against the given path pattern.
* @param pattern the pattern to match to
* @return a predicate that tests against the given path pattern
*/
public static RequestPredicate path(String pattern) {
Assert.notNull(pattern, "'pattern' must not be null");
if (!pattern.isEmpty() && !pattern.startsWith("/")) {
pattern = "/" + pattern;
}
return pathPredicates(PathPatternParser.defaultInstance).apply(pattern);
}
/**
* Return a function that creates new path-matching {@code RequestPredicates}
* from pattern Strings using the given {@link PathPatternParser}.
* <p>This method can be used to specify a non-default, customized
* {@code PathPatternParser} when resolving path patterns.
* @param patternParser the parser used to parse patterns given to the returned function
* @return a function that resolves a pattern String into a path-matching
* {@code RequestPredicates} instance
*/
public static Function<String, RequestPredicate> pathPredicates(PathPatternParser patternParser) {
Assert.notNull(patternParser, "PathPatternParser must not be null");
return pattern -> new PathPatternPredicate(patternParser.parse(pattern));
}
/**
* Return a {@code RequestPredicate} that tests the request's headers
* against the given headers predicate.
* @param headersPredicate a predicate that tests against the request headers
* @return a predicate that tests against the given header predicate
*/
public static RequestPredicate headers(Predicate<ServerRequest.Headers> headersPredicate) {
return new HeadersPredicate(headersPredicate);
}
/**
* Return a {@code RequestPredicate} that tests if the request's
* {@linkplain ServerRequest.Headers#contentType() content type} is
* {@linkplain MediaType#includes(MediaType) included} by any of the given media types.
* @param mediaTypes the media types to match the request's content type against
* @return a predicate that tests the request's content type against the given media types
*/
public static RequestPredicate contentType(MediaType... mediaTypes) {
Assert.notEmpty(mediaTypes, "'mediaTypes' must not be empty");
return new ContentTypePredicate(mediaTypes);
}
/**
* Return a {@code RequestPredicate} that tests if the request's
* {@linkplain ServerRequest.Headers#accept() accept} header is
* {@linkplain MediaType#isCompatibleWith(MediaType) compatible} with any of the given media types.
* @param mediaTypes the media types to match the request's accept header against
* @return a predicate that tests the request's accept header against the given media types
*/
public static RequestPredicate accept(MediaType... mediaTypes) {
Assert.notEmpty(mediaTypes, "'mediaTypes' must not be empty");
return new AcceptPredicate(mediaTypes);
}
/**
* Return a {@code RequestPredicate} that matches if request's HTTP method is {@code GET}
* and the given {@code pattern} matches against the request path.
* @param pattern the path pattern to match against
* @return a predicate that matches if the request method is GET and if the given pattern
* matches against the request path
*/
public static RequestPredicate GET(String pattern) {
return method(HttpMethod.GET).and(path(pattern));
}
/**
* Return a {@code RequestPredicate} that matches if request's HTTP method is {@code HEAD}
* and the given {@code pattern} matches against the request path.
* @param pattern the path pattern to match against
* @return a predicate that matches if the request method is HEAD and if the given pattern
* matches against the request path
*/
public static RequestPredicate HEAD(String pattern) {
return method(HttpMethod.HEAD).and(path(pattern));
}
/**
* Return a {@code RequestPredicate} that matches if request's HTTP method is {@code POST}
* and the given {@code pattern} matches against the request path.
* @param pattern the path pattern to match against
* @return a predicate that matches if the request method is POST and if the given pattern
* matches against the request path
*/
public static RequestPredicate POST(String pattern) {
return method(HttpMethod.POST).and(path(pattern));
}
/**
* Return a {@code RequestPredicate} that matches if request's HTTP method is {@code PUT}
* and the given {@code pattern} matches against the request path.
* @param pattern the path pattern to match against
* @return a predicate that matches if the request method is PUT and if the given pattern
* matches against the request path
*/
public static RequestPredicate PUT(String pattern) {
return method(HttpMethod.PUT).and(path(pattern));
}
/**
* Return a {@code RequestPredicate} that matches if request's HTTP method is {@code PATCH}
* and the given {@code pattern} matches against the request path.
* @param pattern the path pattern to match against
* @return a predicate that matches if the request method is PATCH and if the given pattern
* matches against the request path
*/
public static RequestPredicate PATCH(String pattern) {
return method(HttpMethod.PATCH).and(path(pattern));
}
/**
* Return a {@code RequestPredicate} that matches if request's HTTP method is {@code DELETE}
* and the given {@code pattern} matches against the request path.
* @param pattern the path pattern to match against
* @return a predicate that matches if the request method is DELETE and if the given pattern
* matches against the request path
*/
public static RequestPredicate DELETE(String pattern) {
return method(HttpMethod.DELETE).and(path(pattern));
}
/**
* Return a {@code RequestPredicate} that matches if request's HTTP method is {@code OPTIONS}
* and the given {@code pattern} matches against the request path.
* @param pattern the path pattern to match against
* @return a predicate that matches if the request method is OPTIONS and if the given pattern
* matches against the request path
*/
public static RequestPredicate OPTIONS(String pattern) {
return method(HttpMethod.OPTIONS).and(path(pattern));
}
/**
* Return a {@code RequestPredicate} that matches if the request's path has the given extension.
* @param extension the path extension to match against, ignoring case
* @return a predicate that matches if the request's path has the given file extension
*/
public static RequestPredicate pathExtension(String extension) {
Assert.notNull(extension, "'extension' must not be null");
return new PathExtensionPredicate(extension);
}
/**
* Return a {@code RequestPredicate} that matches if the request's path matches the given
* predicate.
* @param extensionPredicate the predicate to test against the request path extension
* @return a predicate that matches if the given predicate matches against the request's path
* file extension
*/
public static RequestPredicate pathExtension(Predicate<String> extensionPredicate) {
return new PathExtensionPredicate(extensionPredicate);
}
/**
* Return a {@code RequestPredicate} that matches if the request's query parameter of the given name
* has the given value.
* @param name the name of the query parameter to test against
* @param value the value of the query parameter to test against
* @return a predicate that matches if the query parameter has the given value
* @since 5.0.7
* @see ServerRequest#queryParam(String)
*/
public static RequestPredicate queryParam(String name, String value) {
return new QueryParamPredicate(name, value);
}
/**
* Return a {@code RequestPredicate} that tests the request's query parameter of the given name
* against the given predicate.
* @param name the name of the query parameter to test against
* @param predicate the predicate to test against the query parameter value
* @return a predicate that matches the given predicate against the query parameter of the given name
* @see ServerRequest#queryParam(String)
*/
public static RequestPredicate queryParam(String name, Predicate<String> predicate) {
return new QueryParamPredicate(name, predicate);
}
private static void traceMatch(String prefix, Object desired, @Nullable Object actual, boolean match) {
if (logger.isTraceEnabled()) {
logger.trace(String.format("%s \"%s\" %s against value \"%s\"",
prefix, desired, match ? "matches" : "does not match", actual));
}
}
private static void restoreAttributes(ServerRequest request, Map<String, Object> attributes) {
request.attributes().clear();
request.attributes().putAll(attributes);
}
private static Map<String, String> mergePathVariables(Map<String, String> oldVariables,
Map<String, String> newVariables) {
if (!newVariables.isEmpty()) {
Map<String, String> mergedVariables = new LinkedHashMap<>(oldVariables);
mergedVariables.putAll(newVariables);
return mergedVariables;
}
else {
return oldVariables;
}
}
private static PathPattern mergePatterns(@Nullable PathPattern oldPattern, PathPattern newPattern) {
if (oldPattern != null) {
return oldPattern.combine(newPattern);
}
else {
return newPattern;
}
}
/**
* Receives notifications from the logical structure of request predicates.
*/
public interface Visitor {
/**
* Receive notification of an HTTP method predicate.
* @param methods the HTTP methods that make up the predicate
* @see RequestPredicates#method(HttpMethod)
*/
void method(Set<HttpMethod> methods);
/**
* Receive notification of an path predicate.
* @param pattern the path pattern that makes up the predicate
* @see RequestPredicates#path(String)
*/
void path(String pattern);
/**
* Receive notification of an path extension predicate.
* @param extension the path extension that makes up the predicate
* @see RequestPredicates#pathExtension(String)
*/
void pathExtension(String extension);
/**
* Receive notification of an HTTP header predicate.
* @param name the name of the HTTP header to check
* @param value the desired value of the HTTP header
* @see RequestPredicates#headers(Predicate)
* @see RequestPredicates#contentType(MediaType...)
* @see RequestPredicates#accept(MediaType...)
*/
void header(String name, String value);
/**
* Receive notification of a query parameter predicate.
* @param name the name of the query parameter
* @param value the desired value of the parameter
* @see RequestPredicates#queryParam(String, String)
*/
void queryParam(String name, String value);
/**
* Receive first notification of a logical AND predicate.
* The first subsequent notification will contain the left-hand side of the AND-predicate;
* followed by {@link #and()}, followed by the right-hand side, followed by {@link #endAnd()}.
* @see RequestPredicate#and(RequestPredicate)
*/
void startAnd();
/**
* Receive "middle" notification of a logical AND predicate.
* The following notification contains the right-hand side, followed by {@link #endAnd()}.
* @see RequestPredicate#and(RequestPredicate)
*/
void and();
/**
* Receive last notification of a logical AND predicate.
* @see RequestPredicate#and(RequestPredicate)
*/
void endAnd();
/**
* Receive first notification of a logical OR predicate.
* The first subsequent notification will contain the left-hand side of the OR-predicate;
* the second notification contains the right-hand side, followed by {@link #endOr()}.
* @see RequestPredicate#or(RequestPredicate)
*/
void startOr();
/**
* Receive "middle" notification of a logical OR predicate.
* The following notification contains the right-hand side, followed by {@link #endOr()}.
* @see RequestPredicate#or(RequestPredicate)
*/
void or();
/**
* Receive last notification of a logical OR predicate.
* @see RequestPredicate#or(RequestPredicate)
*/
void endOr();
/**
* Receive first notification of a negated predicate.
* The first subsequent notification will contain the negated predicated, followed
* by {@link #endNegate()}.
* @see RequestPredicate#negate()
*/
void startNegate();
/**
* Receive last notification of a negated predicate.
* @see RequestPredicate#negate()
*/
void endNegate();
/**
* Receive first notification of an unknown predicate.
*/
void unknown(RequestPredicate predicate);
}
private static class HttpMethodPredicate implements RequestPredicate {
private final Set<HttpMethod> httpMethods;
public HttpMethodPredicate(HttpMethod httpMethod) {
Assert.notNull(httpMethod, "HttpMethod must not be null");
this.httpMethods = EnumSet.of(httpMethod);
}
public HttpMethodPredicate(HttpMethod... httpMethods) {
Assert.notEmpty(httpMethods, "HttpMethods must not be empty");
this.httpMethods = EnumSet.copyOf(Arrays.asList(httpMethods));
}
@Override
public boolean test(ServerRequest request) {
HttpMethod method = method(request);
boolean match = this.httpMethods.contains(method);
traceMatch("Method", this.httpMethods, method, match);
return match;
}
@Nullable
private static HttpMethod method(ServerRequest request) {
if (CorsUtils.isPreFlightRequest(request.exchange().getRequest())) {
String accessControlRequestMethod =
request.headers().firstHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD);
return HttpMethod.resolve(accessControlRequestMethod);
}
else {
return request.method();
}
}
@Override
public void accept(Visitor visitor) {
visitor.method(Collections.unmodifiableSet(this.httpMethods));
}
@Override
public String toString() {
if (this.httpMethods.size() == 1) {
return this.httpMethods.iterator().next().toString();
}
else {
return this.httpMethods.toString();
}
}
}
private static class PathPatternPredicate implements RequestPredicate, ChangePathPatternParserVisitor.Target {
private PathPattern pattern;
public PathPatternPredicate(PathPattern pattern) {
Assert.notNull(pattern, "'pattern' must not be null");
this.pattern = pattern;
}
@Override
public boolean test(ServerRequest request) {
PathContainer pathContainer = request.requestPath().pathWithinApplication();
PathPattern.PathMatchInfo info = this.pattern.matchAndExtract(pathContainer);
traceMatch("Pattern", this.pattern.getPatternString(), request.path(), info != null);
if (info != null) {
mergeAttributes(request, info.getUriVariables(), this.pattern);
return true;
}
else {
return false;
}
}
private static void mergeAttributes(ServerRequest request, Map<String, String> variables,
PathPattern pattern) {
Map<String, String> pathVariables = mergePathVariables(request.pathVariables(), variables);
request.attributes().put(RouterFunctions.URI_TEMPLATE_VARIABLES_ATTRIBUTE,
Collections.unmodifiableMap(pathVariables));
pattern = mergePatterns(
(PathPattern) request.attributes().get(RouterFunctions.MATCHING_PATTERN_ATTRIBUTE),
pattern);
request.attributes().put(RouterFunctions.MATCHING_PATTERN_ATTRIBUTE, pattern);
}
@Override
public Optional<ServerRequest> nest(ServerRequest request) {
return Optional.ofNullable(this.pattern.matchStartOfPath(request.requestPath().pathWithinApplication()))
.map(info -> new SubPathServerRequestWrapper(request, info, this.pattern));
}
@Override
public void accept(Visitor visitor) {
visitor.path(this.pattern.getPatternString());
}
@Override
public void changeParser(PathPatternParser parser) {
String patternString = this.pattern.getPatternString();
this.pattern = parser.parse(patternString);
}
@Override
public String toString() {
return this.pattern.getPatternString();
}
}
private static class HeadersPredicate implements RequestPredicate {
private final Predicate<ServerRequest.Headers> headersPredicate;
public HeadersPredicate(Predicate<ServerRequest.Headers> headersPredicate) {
Assert.notNull(headersPredicate, "Predicate must not be null");
this.headersPredicate = headersPredicate;
}
@Override
public boolean test(ServerRequest request) {
if (CorsUtils.isPreFlightRequest(request.exchange().getRequest())) {
return true;
}
else {
return this.headersPredicate.test(request.headers());
}
}
@Override
public String toString() {
return this.headersPredicate.toString();
}
}
private static class ContentTypePredicate extends HeadersPredicate {
private final Set<MediaType> mediaTypes;
public ContentTypePredicate(MediaType... mediaTypes) {
this(new HashSet<>(Arrays.asList(mediaTypes)));
}
private ContentTypePredicate(Set<MediaType> mediaTypes) {
super(headers -> {
MediaType contentType =
headers.contentType().orElse(MediaType.APPLICATION_OCTET_STREAM);
boolean match = mediaTypes.stream()
.anyMatch(mediaType -> mediaType.includes(contentType));
traceMatch("Content-Type", mediaTypes, contentType, match);
return match;
});
this.mediaTypes = mediaTypes;
}
@Override
public void accept(Visitor visitor) {
visitor.header(HttpHeaders.CONTENT_TYPE,
(this.mediaTypes.size() == 1) ?
this.mediaTypes.iterator().next().toString() :
this.mediaTypes.toString());
}
@Override
public String toString() {
return String.format("Content-Type: %s",
(this.mediaTypes.size() == 1) ?
this.mediaTypes.iterator().next().toString() :
this.mediaTypes.toString());
}
}
private static class AcceptPredicate extends HeadersPredicate {
private final Set<MediaType> mediaTypes;
public AcceptPredicate(MediaType... mediaTypes) {
this(new HashSet<>(Arrays.asList(mediaTypes)));
}
private AcceptPredicate(Set<MediaType> mediaTypes) {
super(headers -> {
List<MediaType> acceptedMediaTypes = acceptedMediaTypes(headers);
boolean match = acceptedMediaTypes.stream()
.anyMatch(acceptedMediaType -> mediaTypes.stream()
.anyMatch(acceptedMediaType::isCompatibleWith));
traceMatch("Accept", mediaTypes, acceptedMediaTypes, match);
return match;
});
this.mediaTypes = mediaTypes;
}
@NonNull
private static List<MediaType> acceptedMediaTypes(ServerRequest.Headers headers) {
List<MediaType> acceptedMediaTypes = headers.accept();
if (acceptedMediaTypes.isEmpty()) {
acceptedMediaTypes = Collections.singletonList(MediaType.ALL);
}
else {
MediaType.sortBySpecificityAndQuality(acceptedMediaTypes);
}
return acceptedMediaTypes;
}
@Override
public void accept(Visitor visitor) {
visitor.header(HttpHeaders.ACCEPT,
(this.mediaTypes.size() == 1) ?
this.mediaTypes.iterator().next().toString() :
this.mediaTypes.toString());
}
@Override
public String toString() {
return String.format("Accept: %s",
(this.mediaTypes.size() == 1) ?
this.mediaTypes.iterator().next().toString() :
this.mediaTypes.toString());
}
}
private static class PathExtensionPredicate implements RequestPredicate {
private final Predicate<String> extensionPredicate;
@Nullable
private final String extension;
public PathExtensionPredicate(Predicate<String> extensionPredicate) {
Assert.notNull(extensionPredicate, "Predicate must not be null");
this.extensionPredicate = extensionPredicate;
this.extension = null;
}
public PathExtensionPredicate(String extension) {
Assert.notNull(extension, "Extension must not be null");
this.extensionPredicate = s -> {
boolean match = extension.equalsIgnoreCase(s);
traceMatch("Extension", extension, s, match);
return match;
};
this.extension = extension;
}
@Override
public boolean test(ServerRequest request) {
String pathExtension = UriUtils.extractFileExtension(request.path());
return this.extensionPredicate.test(pathExtension);
}
@Override
public void accept(Visitor visitor) {
visitor.pathExtension(
(this.extension != null) ?
this.extension :
this.extensionPredicate.toString());
}
@Override
public String toString() {
return String.format("*.%s",
(this.extension != null) ?
this.extension :
this.extensionPredicate);
}
}
private static class QueryParamPredicate implements RequestPredicate {
private final String name;
private final Predicate<String> valuePredicate;
@Nullable
private final String value;
public QueryParamPredicate(String name, Predicate<String> valuePredicate) {
Assert.notNull(name, "Name must not be null");
Assert.notNull(valuePredicate, "Predicate must not be null");
this.name = name;
this.valuePredicate = valuePredicate;
this.value = null;
}
public QueryParamPredicate(String name, String value) {
Assert.notNull(name, "Name must not be null");
Assert.notNull(value, "Value must not be null");
this.name = name;
this.valuePredicate = value::equals;
this.value = value;
}
@Override
public boolean test(ServerRequest request) {
Optional<String> s = request.queryParam(this.name);
return s.filter(this.valuePredicate).isPresent();
}
@Override
public void accept(Visitor visitor) {
visitor.queryParam(this.name,
(this.value != null) ?
this.value :
this.valuePredicate.toString());
}
@Override
public String toString() {
return String.format("?%s %s", this.name,
(this.value != null) ?
this.value :
this.valuePredicate);
}
}
/**
* {@link RequestPredicate} for where both {@code left} and {@code right} predicates
* must match.
*/
static class AndRequestPredicate implements RequestPredicate, ChangePathPatternParserVisitor.Target {
private final RequestPredicate left;
private final RequestPredicate right;
public AndRequestPredicate(RequestPredicate left, RequestPredicate right) {
Assert.notNull(left, "Left RequestPredicate must not be null");
Assert.notNull(right, "Right RequestPredicate must not be null");
this.left = left;
this.right = right;
}
@Override
public boolean test(ServerRequest request) {
Map<String, Object> oldAttributes = new HashMap<>(request.attributes());
if (this.left.test(request) && this.right.test(request)) {
return true;
}
restoreAttributes(request, oldAttributes);
return false;
}
@Override
public Optional<ServerRequest> nest(ServerRequest request) {
return this.left.nest(request).flatMap(this.right::nest);
}
@Override
public void accept(Visitor visitor) {
visitor.startAnd();
this.left.accept(visitor);
visitor.and();
this.right.accept(visitor);
visitor.endAnd();
}
@Override
public void changeParser(PathPatternParser parser) {
if (this.left instanceof ChangePathPatternParserVisitor.Target) {
((ChangePathPatternParserVisitor.Target) left).changeParser(parser);
}
if (this.right instanceof ChangePathPatternParserVisitor.Target) {
((ChangePathPatternParserVisitor.Target) right).changeParser(parser);
}
}
@Override
public String toString() {
return String.format("(%s && %s)", this.left, this.right);
}
}
/**
* {@link RequestPredicate} that negates a delegate predicate.
*/
static class NegateRequestPredicate implements RequestPredicate, ChangePathPatternParserVisitor.Target {
private final RequestPredicate delegate;
public NegateRequestPredicate(RequestPredicate delegate) {
Assert.notNull(delegate, "Delegate must not be null");
this.delegate = delegate;
}
@Override
public boolean test(ServerRequest request) {
Map<String, Object> oldAttributes = new HashMap<>(request.attributes());
boolean result = !this.delegate.test(request);
if (!result) {
restoreAttributes(request, oldAttributes);
}
return result;
}
@Override
public void accept(Visitor visitor) {
visitor.startNegate();
this.delegate.accept(visitor);
visitor.endNegate();
}
@Override
public void changeParser(PathPatternParser parser) {
if (this.delegate instanceof ChangePathPatternParserVisitor.Target) {
((ChangePathPatternParserVisitor.Target) delegate).changeParser(parser);
}
}
@Override
public String toString() {
return "!" + this.delegate.toString();
}
}
/**
* {@link RequestPredicate} where either {@code left} or {@code right} predicates
* may match.
*/
static class OrRequestPredicate implements RequestPredicate, ChangePathPatternParserVisitor.Target {
private final RequestPredicate left;
private final RequestPredicate right;
public OrRequestPredicate(RequestPredicate left, RequestPredicate right) {
Assert.notNull(left, "Left RequestPredicate must not be null");
Assert.notNull(right, "Right RequestPredicate must not be null");
this.left = left;
this.right = right;
}
@Override
public boolean test(ServerRequest request) {
Map<String, Object> oldAttributes = new HashMap<>(request.attributes());
if (this.left.test(request)) {
return true;
}
else {
restoreAttributes(request, oldAttributes);
if (this.right.test(request)) {
return true;
}
}
restoreAttributes(request, oldAttributes);
return false;
}
@Override
public Optional<ServerRequest> nest(ServerRequest request) {
Optional<ServerRequest> leftResult = this.left.nest(request);
if (leftResult.isPresent()) {
return leftResult;
}
else {
return this.right.nest(request);
}
}
@Override
public void accept(Visitor visitor) {
visitor.startOr();
this.left.accept(visitor);
visitor.or();
this.right.accept(visitor);
visitor.endOr();
}
@Override
public void changeParser(PathPatternParser parser) {
if (this.left instanceof ChangePathPatternParserVisitor.Target) {
((ChangePathPatternParserVisitor.Target) left).changeParser(parser);
}
if (this.right instanceof ChangePathPatternParserVisitor.Target) {
((ChangePathPatternParserVisitor.Target) right).changeParser(parser);
}
}
@Override
public String toString() {
return String.format("(%s || %s)", this.left, this.right);
}
}
private static class SubPathServerRequestWrapper implements ServerRequest {
private final ServerRequest request;
private final RequestPath requestPath;
private final Map<String, Object> attributes;
public SubPathServerRequestWrapper(ServerRequest request,
PathPattern.PathRemainingMatchInfo info, PathPattern pattern) {
this.request = request;
this.requestPath = requestPath(request.requestPath(), info);
this.attributes = mergeAttributes(request, info.getUriVariables(), pattern);
}
private static RequestPath requestPath(RequestPath original, PathPattern.PathRemainingMatchInfo info) {
StringBuilder contextPath = new StringBuilder(original.contextPath().value());
contextPath.append(info.getPathMatched().value());
int length = contextPath.length();
if (length > 0 && contextPath.charAt(length - 1) == '/') {
contextPath.setLength(length - 1);
}
return original.modifyContextPath(contextPath.toString());
}
private static Map<String, Object> mergeAttributes(ServerRequest request,
Map<String, String> pathVariables, PathPattern pattern) {
Map<String, Object> result = new ConcurrentHashMap<>(request.attributes());
result.put(RouterFunctions.URI_TEMPLATE_VARIABLES_ATTRIBUTE,
mergePathVariables(request.pathVariables(), pathVariables));
pattern = mergePatterns(
(PathPattern) request.attributes().get(RouterFunctions.MATCHING_PATTERN_ATTRIBUTE),
pattern);
result.put(RouterFunctions.MATCHING_PATTERN_ATTRIBUTE, pattern);
return result;
}
@Override
public HttpMethod method() {
return this.request.method();
}
@Override
public String methodName() {
return this.request.methodName();
}
@Override
public URI uri() {
return this.request.uri();
}
@Override
public UriBuilder uriBuilder() {
return this.request.uriBuilder();
}
@Override
public RequestPath requestPath() {
return this.requestPath;
}
@Override
public Headers headers() {
return this.request.headers();
}
@Override
public MultiValueMap<String, HttpCookie> cookies() {
return this.request.cookies();
}
@Override
public Optional<InetSocketAddress> remoteAddress() {