forked from actframework/actframework
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRouter.java
More file actions
1599 lines (1446 loc) · 58 KB
/
Router.java
File metadata and controls
1599 lines (1446 loc) · 58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
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
package act.route;
/*-
* #%L
* ACT Framework
* %%
* Copyright (C) 2014 - 2017 ActFramework
* %%
* 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
*
* 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.
* #L%
*/
import act.Act;
import act.Destroyable;
import act.app.*;
import act.cli.tree.TreeNode;
import act.conf.AppConfig;
import act.controller.ParamNames;
import act.controller.builtin.ThrottleFilter;
import act.handler.*;
import act.handler.builtin.*;
import act.handler.builtin.controller.RequestHandlerProxy;
import act.security.CORS;
import act.security.CSRF;
import act.util.ActContext;
import act.util.DestroyableBase;
import act.ws.WsEndpoint;
import org.osgl.$;
import org.osgl.exception.NotAppliedException;
import org.osgl.http.H;
import org.osgl.http.util.Path;
import org.osgl.logging.LogManager;
import org.osgl.logging.Logger;
import org.osgl.mvc.result.Result;
import org.osgl.util.*;
import java.io.File;
import java.io.PrintStream;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import javax.enterprise.context.ApplicationScoped;
import javax.validation.constraints.NotNull;
public class Router extends AppHolderBase<Router> {
/**
* A visitor can be passed to the router to traverse
* the routes
*/
public interface Visitor {
/**
* Visit a route mapping in the router
*
* @param method the HTTP method
* @param path the URL path
* @param handler the handler
*/
void visit(H.Method method, String path, RequestHandler handler);
}
public static final String IGNORE_NOTATION = "...";
private static final H.Method[] targetMethods = new H.Method[]{
H.Method.GET, H.Method.POST, H.Method.DELETE, H.Method.PUT, H.Method.PATCH};
private static final Logger LOGGER = LogManager.get(Router.class);
Node _GET;
Node _PUT;
Node _POST;
Node _DEL;
Node _PATCH;
private Map<String, RequestHandlerResolver> resolvers = new HashMap<>();
private RequestHandlerResolver handlerLookup;
// map action context to url context
// for example `act.` -> `/~`
private Map<String, String> urlContexts = new HashMap<>();
private Set<String> actionNames = new HashSet<>();
private AppConfig appConfig;
private String portId;
private int port;
private OptionsInfoBase optionHandlerFactory;
private Set<RequestHandler> requireBodyParsing = new HashSet<>();
private void initControllerLookup(RequestHandlerResolver lookup) {
if (null == lookup) {
lookup = new RequestHandlerResolverBase() {
@Override
public RequestHandler resolve(String payload, App app) {
if (S.eq(WsEndpoint.PSEUDO_METHOD, payload.toString())) {
return Act.network().createWebSocketConnectionHandler();
}
return new RequestHandlerProxy(payload.toString(), app);
}
};
}
handlerLookup = lookup;
}
public Router(App app) {
this(null, app, null);
}
public Router(App app, String portId) {
this(null, app, portId);
}
public Router(RequestHandlerResolver handlerLookup, App app) {
this(handlerLookup, app, null);
}
public Router(RequestHandlerResolver handlerLookup, App app, String portId) {
super(app);
initControllerLookup(handlerLookup);
this.appConfig = app.config();
this.portId = portId;
if (S.notBlank(portId)) {
this.port = appConfig.namedPort(portId).port();
} else {
this.port = appConfig.httpSecure() ? appConfig.httpExternalSecurePort() : appConfig.httpExternalPort();
}
this.optionHandlerFactory = new OptionsInfoBase(this);
_GET = Node.newRoot("GET", appConfig);
_PUT = Node.newRoot("PUT", appConfig);
_POST = Node.newRoot("POST", appConfig);
_DEL = Node.newRoot("DELETE", appConfig);
_PATCH = Node.newRoot("PATCH", appConfig);
}
@Override
protected void releaseResources() {
_GET.destroy();
_DEL.destroy();
_POST.destroy();
_PUT.destroy();
_PATCH.destroy();
handlerLookup.destroy();
actionNames.clear();
appConfig = null;
}
public String portId() {
return portId;
}
public int port() {
return port;
}
/**
* Accept a {@link Visitor} to traverse route mapping in this
* router
*
* @param visitor the visitor
*/
public void accept(Visitor visitor) {
visit(_GET, H.Method.GET, visitor);
visit(_POST, H.Method.POST, visitor);
visit(_PUT, H.Method.PUT, visitor);
visit(_DEL, H.Method.DELETE, visitor);
visit(_PATCH, H.Method.PATCH, visitor);
}
private void visit(Node node, H.Method method, Visitor visitor) {
RequestHandler handler = node.handler;
if (null != handler) {
if (handler instanceof ContextualHandler) {
handler = ((ContextualHandler) handler).realHandler();
}
visitor.visit(method, node.path(), handler);
}
for (Node child : node.dynamicChilds) {
visit(child, method, visitor);
}
for (Node child : node.staticChildren.values()) {
visit(child, method, visitor);
}
}
// Mark handler as require body parsing
public void markRequireBodyParsing(RequestHandler handler) {
requireBodyParsing.add(handler);
}
// --- routing ---
public RequestHandler getInvoker(H.Method method, String path, ActionContext context) {
context.router(this);
if (method == H.Method.OPTIONS) {
return optionHandlerFactory.optionHandler(path, context);
}
Node node = root(method, false);
if (null == node) {
return UnknownHttpMethodHandler.INSTANCE;
}
node = search(node, Path.tokenizer(Unsafe.bufOf(path)), context);
RequestHandler handler = getInvokerFrom(node);
RequestHandler blockIssueHandler = app().blockIssueHandler();
if (null == blockIssueHandler) {
return handler;
}
if (handler instanceof FileGetter || handler instanceof ResourceGetter) {
return handler;
}
return blockIssueHandler;
}
public RequestHandler findStaticGetHandler(String url) {
Iterator<String> path = Path.tokenizer(Unsafe.bufOf(url));
Node node = root(H.Method.GET);
while (null != node && path.hasNext()) {
String nodeName = path.next();
node = node.staticChildren.get(nodeName);
if (null == node || node.terminateRouteSearch()) {
break;
}
}
return null == node ? null : node.handler;
}
private RequestHandler getInvokerFrom(Node node) {
if (null == node) {
return notFound();
}
RequestHandler handler = node.handler;
if (null == handler) {
for (Node targetNode : node.dynamicChilds) {
if (Node.MATCH_ALL == targetNode.patternTrait || targetNode.pattern.matcher("").matches()) {
return getInvokerFrom(targetNode);
}
}
return notFound();
}
return handler;
}
// --- route building ---
public void addContext(String actionContext, String urlContext) {
urlContexts.put(actionContext, urlContext);
}
enum ConflictResolver {
/**
* Overwrite existing route
*/
OVERWRITE,
/**
* Overwrite and log warn message
*/
OVERWRITE_WARN,
/**
* Skip the new route
*/
SKIP,
/**
* Report error and exit app
*/
EXIT
}
private String withUrlContext(String path, String action) {
String sAction = action.toString();
String urlContext = null;
for (String key : urlContexts.keySet()) {
String sKey = key.toString();
if (sAction.startsWith(sKey)) {
urlContext = urlContexts.get(key);
break;
}
}
return null == urlContext ? path : S.pathConcat(urlContext, '/', path.toString());
}
public void addMapping(H.Method method, String path, String action) {
addMapping(method, withUrlContext(path, action), resolveActionHandler(action), RouteSource.ROUTE_TABLE);
}
public void addMapping(H.Method method, String path, String action, RouteSource source) {
addMapping(method, withUrlContext(path, action), resolveActionHandler(action), source);
}
public void addMapping(H.Method method, String path, RequestHandler handler) {
addMapping(method, path, handler, RouteSource.ROUTE_TABLE);
}
@SuppressWarnings("FallThrough")
public void addMapping(final H.Method method, final String path, RequestHandler handler, final RouteSource source) {
if (isTraceEnabled()) {
trace("R+ %s %s | %s (%s)", method, path, handler, source);
}
if (!app().config().builtInReqHandlerEnabled()) {
String sPath = path.toString();
if (sPath.startsWith("/~/")) {
// disable built-in handlers except those might impact application behaviour
// apibook is allowed here as it only available on dev mode
if (!(sPath.contains("asset") || sPath.contains("i18n") || sPath.contains("job") || sPath.contains("api") || sPath.contains("ticket"))) {
return;
}
}
}
Node node = _locate(method, path, handler.toString());
if (null == node.handler) {
Set<Node> conflicts = node.conflicts();
if (!conflicts.isEmpty()) {
for (Node conflict : conflicts) {
if (null != conflict.handler) {
node = conflict;
break;
}
}
}
}
if (null == node.handler) {
handler = prepareReverseRoutes(handler, node);
node.handler(handler, source);
} else {
RouteSource existing = node.routeSource();
ConflictResolver resolving = source.onConflict(existing);
switch (resolving) {
case OVERWRITE_WARN:
warn("\n\tOverwrite existing route \n\t\t%s\n\twith new route\n\t\t%s",
routeInfo(method, path, node.handler()),
routeInfo(method, path, handler)
);
case OVERWRITE:
handler = prepareReverseRoutes(handler, node);
node.handler(handler, source);
case SKIP:
break;
case EXIT:
throw new DuplicateRouteMappingException(
new RouteInfo(method, path.toString(), node.handler(), existing),
new RouteInfo(method, path.toString(), handler, source)
);
default:
throw E.unsupport();
}
}
}
private RequestHandler prepareReverseRoutes(RequestHandler handler, Node node) {
if (handler instanceof RequestHandlerInfo) {
RequestHandlerInfo info = (RequestHandlerInfo) handler;
String action = info.action;
Node root = node.root;
root.reverseRoutes.put(action.toString(), node);
handler = info.theHandler();
}
return handler;
}
public String reverseRoute(String action, boolean fullUrl) {
return reverseRoute(action, new HashMap<String, Object>(), fullUrl);
}
public String reverseRoute(String action) {
return reverseRoute(action, new HashMap<String, Object>());
}
public String reverseRoute(String action, Map<String, Object> args) {
String fullAction = inferFullActionPath(action);
for (H.Method m : supportedHttpMethods()) {
String url = reverseRoute(fullAction, m, args);
if (null != url) {
return ensureUrlContext(url);
}
}
return null;
}
public static final $.Func0<String> DEF_ACTION_PATH_PROVIDER = new $.Func0<String>() {
@Override
public String apply() throws NotAppliedException, $.Break {
ActContext context = ActContext.Base.currentContext();
E.illegalStateIf(null == context, "cannot use shortcut action path outside of a act context");
return context.methodPath();
}
};
// See https://github.com/actframework/actframework/issues/107
public static String inferFullActionPath(String actionPath) {
return inferFullActionPath(actionPath, DEF_ACTION_PATH_PROVIDER);
}
public static String inferFullActionPath(String actionPath, $.Func0<String> currentActionPathProvider) {
String handler, controller = null;
if (actionPath.contains("/")) {
return actionPath;
}
int pos = actionPath.indexOf(".");
if (pos < 0) {
handler = actionPath;
} else {
controller = actionPath.substring(0, pos);
handler = actionPath.substring(pos + 1, actionPath.length());
if (handler.indexOf(".") > 0) {
// it's a full path, not shortcut
return actionPath;
}
}
String currentPath = currentActionPathProvider.apply();
if (null == currentPath) {
return actionPath;
}
pos = currentPath.lastIndexOf(".");
String currentPathWithoutHandler = currentPath.substring(0, pos);
if (null == controller) {
return S.concat(currentPathWithoutHandler, ".", handler);
}
pos = currentPathWithoutHandler.lastIndexOf(".");
String currentPathWithoutController = currentPathWithoutHandler.substring(0, pos);
return S.concat(currentPathWithoutController, ".", controller, ".", handler);
}
public String reverseRoute(String action, Map<String, Object> args, boolean fullUrl) {
String path = reverseRoute(action, args);
if (null == path) {
return null;
}
return fullUrl ? fullUrl(path) : path;
}
public String reverseRoute(String action, H.Method method, Map<String, Object> args) {
Node root = root(method);
Node node = root.reverseRoutes.get(action);
if (null == node) {
return null;
}
C.List<String> elements = C.newList();
args = new HashMap<>(args);
while (root != node) {
if (node.isDynamic()) {
Node targetNode = node;
for (Map.Entry<String, Node> entry : node.dynamicReverseAliases.entrySet()) {
if (entry.getKey().equals(action)) {
targetNode = entry.getValue();
break;
}
}
S.Buffer buffer = S.buffer();
for ($.Transformer<Map<String, Object>, String> builder : targetNode.nodeValueBuilders) {
String s = builder.transform(args);
buffer.append(s);
}
String s = buffer.toString();
if (S.blank(s)) {
s = S.string(args.remove(S.string(targetNode.varNames.get(0))));
}
if (S.blank(s)) {
s = S.string("-");
}
elements.add(s);
} else {
elements.add(node.name.toString());
}
node = node.parent;
}
S.Buffer sb = S.newBuffer();
Iterator<String> itr = elements.reverseIterator();
while (itr.hasNext()) {
sb.append("/").append(itr.next());
}
if (method == H.Method.GET && !args.isEmpty()) {
boolean first = true;
for (Map.Entry<String, Object> entry : args.entrySet()) {
Object v = entry.getValue();
if (null == v) {
continue;
}
String k = entry.getKey();
if (first) {
sb.append("?");
first = false;
} else {
sb.append("&");
}
sb.append(k).append("=").append(Codec.encodeUrl(v.toString()));
}
}
return sb.toString();
}
public String urlBase() {
ActionContext context = ActionContext.current();
if (null != context) {
return urlBase(context);
}
AppConfig<?> config = Act.appConfig();
/*
* Note we support named port (restricted access) is running in the scope of
* the internal network, thus assume we do not have secure http channel on top
* of that
*/
boolean secure = null != portId && config.httpSecure();
String scheme = secure ? "https" : "http";
String domain = config.host();
if (80 == port || 443 == port) {
return S.concat(scheme, "://", domain);
} else {
return S.concat(scheme, "://", domain, ":", S.string(port));
}
}
public String urlBase(ActionContext context) {
H.Request req = context.req();
String scheme = req.secure() ? "https" : "http";
int port = req.port();
String domain = req.domain();
if (80 == port || 443 == port) {
return S.fmt("%s://%s", scheme, domain);
} else {
return S.fmt("%s://%s:%s", scheme, domain, port);
}
}
private String ensureUrlContext(String path) {
String urlContext = appConfig.urlContext();
if (null == urlContext || path.startsWith(urlContext)) {
if ("/".equals(path)) {
path = "";
}
return path;
}
if (!path.startsWith("/")) {
path = S.concat("/", path);
if (path.startsWith(urlContext)) {
return path;
}
}
if ("/".equals(path)) {
path = "";
}
return S.concat(urlContext, path);
}
public String fullUrl(String path, Object... args) {
path = S.fmt(path, args);
if (path.startsWith("//") || path.startsWith("http")) {
return path;
}
if (path.contains(".") || path.contains("(")) {
path = reverseRoute(path);
}
S.Buffer sb = S.newBuffer(urlBase());
path = ensureUrlContext(path);
return sb.append(S.fmt(path, args)).toString();
}
/**
* Return full URL of reverse rout of specified action
*
* @param action the action path
* @param renderArgs the render arguments
* @return the full URL as described above
*/
public String fullUrl(String action, Map<String, Object> renderArgs) {
return fullUrl(reverseRoute(action, renderArgs));
}
private static final Method M_FULL_URL = $.getMethod(Router.class, "fullUrl", String.class, Object[].class);
public String _fullUrl(String path, Object[] args) {
return $.invokeVirtual(this, M_FULL_URL, path, args);
}
boolean isMapped(H.Method method, String path) {
return null != _search(method, path);
}
private static String routeInfo(H.Method method, String path, Object handler) {
return S.fmt("[%s %s] - > [%s]", method, path, handler);
}
private Node _search(H.Method method, String path) {
Node node = root(method);
assert node != null;
E.unsupportedIf(null == node, "Method %s is not supported", method);
if (path.length() == 1 && path.charAt(0) == '/') {
return node;
}
String sUrl = path.toString();
List<String> paths = Path.tokenize(Unsafe.bufOf(sUrl));
int len = paths.size();
for (int i = 0; i < len - 1; ++i) {
node = node.findChild(paths.get(i));
if (null == node) return null;
}
return node.findChild(paths.get(len - 1));
}
private Node _locate(final H.Method method, final String path, String action) {
Node node = root(method);
E.unsupportedIf(null == node, "Method %s is not supported", method);
assert null != node;
int pathLen = path.length();
if (0 == pathLen || (1 == pathLen && path.charAt(0) == '/')) {
return node;
}
String sUrl = path.toString();
List<String> paths = Path.tokenize(Unsafe.bufOf(sUrl));
int len = paths.size();
for (int i = 0; i < len - 1; ++i) {
String part = paths.get(i);
if (checkIgnoreRestParts(node, part)) {
return node;
}
node = node.addChild(part, path, action);
}
String part = paths.get(len - 1);
if (checkIgnoreRestParts(node, part)) {
return node;
}
return node.addChild(part, path, action);
}
private boolean checkIgnoreRestParts(Node node, String nextPart) {
boolean shouldIgnoreRests = S.eq(IGNORE_NOTATION, S.string(nextPart));
E.invalidConfigurationIf(node.ignoreRestParts() && !shouldIgnoreRests, "Bad route configuration: parts appended to route that ends with \"...\"");
E.invalidConfigurationIf(shouldIgnoreRests && !node.children().isEmpty(), "Bad route configuration: \"...\" appended to node that has children");
node.ignoreRestParts(shouldIgnoreRests);
return shouldIgnoreRests;
}
// --- action handler resolving
/**
* Register 3rd party action handler resolver with specified directive
*
* @param directive
* @param resolver
*/
public void registerRequestHandlerResolver(String directive, RequestHandlerResolver resolver) {
resolvers.put(directive, resolver);
}
// -- action method sensor
public boolean isActionMethod(String className, String methodName) {
return actionNames.contains(S.concat(className, ".", methodName));
}
// TODO: build controllerNames set to accelerate the process
public boolean possibleController(String className) {
return setContains(actionNames, className);
}
private static boolean setContains(Set<String> set, String name) {
for (String s : set) {
if (s.contains(name)) return true;
}
return false;
}
public void debug(PrintStream ps) {
for (H.Method method : supportedHttpMethods()) {
Node node = root(method);
node.debug(method, ps);
}
}
public List<RouteInfo> debug() {
List<RouteInfo> info = new ArrayList<>();
debug(info);
return C.list(info).sorted();
}
public void debug(List<RouteInfo> routes) {
for (H.Method method : supportedHttpMethods()) {
Node node = root(method);
node.debug(method, routes);
}
}
public static H.Method[] supportedHttpMethods() {
return targetMethods;
}
private Node search(Node rootNode, Iterator<String> path, ActionContext context) {
Node node = rootNode;
if (node.terminateRouteSearch() && !context.urlPath().isBuiltIn()) {
S.Buffer sb = S.buffer();
while (path.hasNext()) {
sb.append('/').append(path.next());
}
context.param(ParamNames.PATH, sb.toString());
return node;
}
while (null != node && path.hasNext()) {
String nodeName = path.next();
node = node.child(nodeName, context);
if (null != node) {
if (node.terminateRouteSearch()) {
if (!path.hasNext()) {
context.param(ParamNames.PATH, "");
} else {
S.Buffer sb = S.buffer();
while (path.hasNext()) {
sb.append('/').append(path.next());
}
context.param(ParamNames.PATH, sb.toString());
}
break;
} else if (node.ignoreRestParts()) {
S.Buffer sb = S.buffer();
while (path.hasNext()) {
sb.append('/').append(path.next());
}
context.param(ParamNames.PATH, sb.toString());
break;
}
}
}
return node;
}
private static class RequestHandlerInfo extends DelegateRequestHandler {
private String action;
protected RequestHandlerInfo(RequestHandler handler, String action) {
super(handler);
this.action = action;
}
RequestHandler theHandler() {
return handler_;
}
@Override
public String toString() {
return action.toString();
}
}
private RequestHandlerInfo resolveActionHandler(String action) {
$.T2<String, String> t2 = splitActionStr(action);
String directive = t2._1, payload = t2._2;
if (S.empty(directive)) {
if (payload.contains("/")) {
directive = "resource";
}
}
if (S.notEmpty(directive)) {
RequestHandlerResolver resolver = resolvers.get(directive);
RequestHandler handler = null == resolver ?
BuiltInHandlerResolver.tryResolve(directive, payload, app()) :
resolver.resolve(payload, app());
E.unsupportedIf(null == handler, "cannot find action handler by directive %s on payload %s", directive, payload);
return new RequestHandlerInfo(handler, action);
} else {
RequestHandler handler = handlerLookup.resolve(payload, app());
E.unsupportedIf(null == handler, "cannot find action handler: %s", action);
actionNames.add(payload);
return new RequestHandlerInfo(handler, action);
}
}
private $.T2<String, String> splitActionStr(String action) {
FastStr fs = FastStr.of(action);
FastStr fs1 = fs.beforeFirst(':');
FastStr fs2 = fs1.isEmpty() ? fs : fs.substr(fs1.length() + 1);
return $.T2(fs1.trim().toString(), fs2.trim().toString());
}
private Node root(H.Method method) {
return root(method, true);
}
private Node root(H.Method method, boolean reportError) {
switch (method) {
case GET:
return _GET;
case POST:
return _POST;
case PUT:
return _PUT;
case DELETE:
return _DEL;
case PATCH:
return _PATCH;
default:
if (reportError) {
throw E.unexpected("HTTP Method not supported: %s", method);
}
return null;
}
}
private static AlwaysNotFound notFound() {
return AlwaysNotFound.INSTANCE;
}
private static AlwaysBadRequest badRequest() {
return AlwaysBadRequest.INSTANCE;
}
public final class f {
public $.Predicate<String> IS_CONTROLLER = new $.Predicate<String>() {
@Override
public boolean test(String s) {
for (String action : actionNames) {
if (action.startsWith(s)) {
return true;
}
}
return false;
}
};
}
public final f f = new f();
/**
* The data structure support decision tree for
* fast URL routing
*/
private static class Node extends DestroyableBase implements Serializable, TreeNode, Comparable<Node> {
// used to pass a baq request result when dynamic regex matching failed
private static final Node BADREQUEST = new Node(Integer.MIN_VALUE, Act.appConfig()) {
@Override
boolean terminateRouteSearch() {
return true;
}
};
static {
BADREQUEST.handler = AlwaysBadRequest.INSTANCE;
}
static Node newRoot(String name, AppConfig<?> config) {
Node node = new Node(-1, config);
node.name = name;
return node;
}
static String MATCH_ALL = "(.*?)";
private int id;
private boolean isDynamic;
// --- for static node
private String name;
// ignore all the rest in URL when routing
private boolean ignoreRestParts;
// --- for dynamic node
private Pattern pattern;
private String patternTrait;
private List<String> varNames = new ArrayList<>();
// used to build the node value for reverse routing
private List<$.Transformer<Map<String, Object>, String>> nodeValueBuilders = new ArrayList<>();
// --- references
private Node root;
private Node parent;
private transient Node conflictNode;
private List<Node> dynamicChilds = new ArrayList<>();
private Map<String, Node> staticChildren = new HashMap<>();
private Map<UrlPath, Node> dynamicAliases = new HashMap<>();
private Map<String, Node> dynamicReverseAliases = new HashMap<>();
private RequestHandler handler;
private RouteSource routeSource;
private RouterRegexMacroLookup macroLookup;
private Map<String, Node> reverseRoutes = new HashMap<>();
private Node(int id, AppConfig config) {
this.id = id;
this.macroLookup = config.routerRegexMacroLookup();
name = "";
root = this;
}
Node(String name, Node parent) {
E.NPE(name);
this.name = name;
this.parent = parent;
this.id = name.hashCode();
this.root = parent.root;
this.macroLookup = parent.macroLookup;
parseDynaName(name);
}
@Override
public int hashCode() {
return id;
}
@Override
public boolean equals(Object obj) {
if (obj == this) return true;
if (obj instanceof Node) {
Node that = (Node) obj;
return that.id == id && that.name.equals(name);
}
return false;
}
@Override
public int compareTo(Node o) {
if (!o.isDynamic && !isDynamic) {
return name.compareTo(o.name);
}
int myVars = varNames.size(), hisVars = o.varNames.size();
if (myVars != hisVars) {
return -(myVars - hisVars);
}
boolean fullVar = "(.*)".equals(patternTrait), hisIsFullVar = "(.*)".equals(o.patternTrait);
if (fullVar == hisIsFullVar) {
return name.compareTo(o.name);
}
return fullVar ? 1 : -1;
}
public boolean ignoreRestParts() {
return ignoreRestParts;
}
public void ignoreRestParts(boolean ignore) {
this.ignoreRestParts = ignore;
}
public boolean isDynamic() {
return isDynamic;
}
public Set<Node> conflicts() {
Set<Node> nodes = new HashSet<>();
findOutConflictNodes(nodes);
return nodes;
}
private void findOutConflictNodes(Set<Node> nodes) {
if (null != conflictNode) {
nodes.add(conflictNode);
}
if (this.root == this || this.parent == null) {
return;
}
// track back to parents
// so that we can flag thing like
// /foo/{foo}/xyz and /foo/{bar}/xyz
Set<Node> parentConflictNodes = new HashSet<>();
parent.findOutConflictNodes(parentConflictNodes);
for (Node parentConflictNode : parentConflictNodes) {
Node staticNode = parentConflictNode.staticChildren.get(name);
if (null != staticNode) {
nodes.add(staticNode);
continue;
}
for (Node dynamicNode: parentConflictNode.dynamicChilds) {
if (metaInfoConflict(dynamicNode.name)) {
nodes.add(dynamicNode);
}
}
}
}
boolean metaInfoMatchesExactly(String string) {
return this.isDynamic && $.eq(string, name);
}
boolean metaInfoConflict(String string) {
$.Var<String> patternTraitsVar = $.var();
boolean isDynamic = parseDynaNameStyleA(string, null, null, patternTraitsVar);
isDynamic = isDynamic || parseDynaNameStyleB(
string, null, null,
patternTraitsVar, null);
return isDynamic && patternTrait.equals(patternTraitsVar.get());
}
public boolean matches(String chars) {