-
Notifications
You must be signed in to change notification settings - Fork 535
/
Copy pathRouteImpl.java
408 lines (342 loc) · 11.5 KB
/
RouteImpl.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
/*
* Copyright 2014 Red Hat, Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* The Apache License v2.0 is available at
* http://www.opensource.org/licenses/apache2.0.php
*
* You may elect to redistribute this code under either of these licenses.
*/
package io.vertx.ext.web.impl;
import io.vertx.core.Handler;
import io.vertx.core.http.HttpMethod;
import io.vertx.ext.web.Route;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* This class is thread-safe
* <p>
* Some parts (e.g. content negotiation) from Yoke by Paulo Lopes
*
* @author <a href="http://tfox.org">Tim Fox</a>
* @author <a href="http://pmlopes@gmail.com">Paulo Lopes</a>
*/
public class RouteImpl implements Route {
private final RouterImpl router;
private volatile RouteState state;
RouteImpl(RouterImpl router, int order) {
this.router = router;
this.state = new RouteState(this, order);
}
RouteImpl(RouterImpl router, int order, String path) {
this(router, order);
checkPath(path);
setPath(path);
}
RouteImpl(RouterImpl router, int order, HttpMethod method, String path) {
this(router, order);
method(method);
checkPath(path);
setPath(path);
}
RouteImpl(RouterImpl router, int order, String regex, boolean bregex) {
this(router, order);
setRegex(regex);
}
RouteImpl(RouterImpl router, int order, HttpMethod method, String regex, boolean bregex) {
this(router, order);
method(method);
setRegex(regex);
}
RouteState state() {
return state;
}
@Override
public synchronized Route method(HttpMethod method) {
state = state.addMethod(method);
return this;
}
@Override
public Route path(String path) {
checkPath(path);
setPath(path);
return this;
}
@Override
public Route pathRegex(String regex) {
setRegex(regex);
return this;
}
@Override
public synchronized Route produces(String contentType) {
state = state.addProduce(new ParsableMIMEValue(contentType).forceParse());
return this;
}
@Override
public synchronized Route consumes(String contentType) {
state = state.addConsume(new ParsableMIMEValue(contentType).forceParse());
return this;
}
@Override
public synchronized Route virtualHost(String hostnamePattern) {
state = state
.setVirtualHostPattern(
Pattern.compile(
hostnamePattern
.replaceAll("\\.", "\\\\.")
.replaceAll("[*]", "(.*?)"), Pattern.CASE_INSENSITIVE));
return this;
}
@Override
public synchronized Route order(int order) {
if (state.isAdded()) {
throw new IllegalStateException("Can't change order after route is active");
}
state = state.setOrder(order);
return this;
}
@Override
public Route last() {
return order(Integer.MAX_VALUE);
}
@Override
public synchronized Route handler(Handler<RoutingContext> contextHandler) {
if (state.isExclusive()) {
throw new IllegalStateException("This Route is exclusive for already mounted sub router.");
}
state = state.addContextHandler(contextHandler);
checkAdd();
return this;
}
@Override
public Route blockingHandler(Handler<RoutingContext> contextHandler) {
return blockingHandler(contextHandler, true);
}
@Override
public synchronized Route subRouter(Router subRouter) {
// The route path must end with a wild card
if (state.getPath() != null && state.isExactPath()) {
throw new IllegalStateException("Sub router cannot be mounted on an exact path.");
}
// Parameters are allowed but full regex patterns not
if (state.getPath() == null && state.getPattern() != null) {
throw new IllegalStateException("Sub router cannot be mounted on a regular expression path.");
}
// No other handler can be registered before or after this call (but they can on a new route object for the same path)
if (state.getContextHandlersLength() > 0 || state.getFailureHandlersLength() > 0) {
throw new IllegalStateException("Only one sub router per Route object is allowed.");
}
handler(subRouter::handleContext);
failureHandler(subRouter::handleFailure);
subRouter.modifiedHandler(this::validateMount);
// trigger a validation
validateMount(subRouter);
// mark the route as exclusive from now on
this.state = state.setExclusive(true);
return this;
}
@Override
public Route blockingHandler(Handler<RoutingContext> contextHandler, boolean ordered) {
return handler(new BlockingHandlerDecorator(contextHandler, ordered));
}
@Override
public synchronized Route failureHandler(Handler<RoutingContext> exceptionHandler) {
if (state.isExclusive()) {
throw new IllegalStateException("This Route is exclusive for already mounted sub router.");
}
state = state.addFailureHandler(exceptionHandler);
checkAdd();
return this;
}
@Override
public Route remove() {
router.remove(this);
return this;
}
@Override
public synchronized Route disable() {
state = state.setEnabled(false);
return this;
}
@Override
public synchronized Route enable() {
state = state.setEnabled(true);
return this;
}
@Override
public synchronized Route useNormalizedPath(boolean useNormalizedPath) {
state = state.setUseNormalizedPath(useNormalizedPath);
return this;
}
@Override
public String getPath() {
return state.getPath();
}
@Override
public boolean isRegexPath() {
return state.getPattern() != null;
}
@Override
public boolean isExactPath() {
return state.isExactPath();
}
@Override
public Set<HttpMethod> methods() {
return state.getMethods();
}
@Override
public synchronized Route setRegexGroupsNames(List<String> groups) {
state = state.setGroups(groups);
return this;
}
@Override
public synchronized Route setName(String name) {
state = state.setName(name);
return this;
}
@Override
public String getName() {
return state.getName();
}
@Override
public String toString() {
return "RouteImpl@" + System.identityHashCode(this) +
"{" +
"state=" + state +
'}';
}
RouterImpl router() {
return router;
}
private synchronized void setPath(String path) {
// See if the path is a wildcard "*" is present - If so we need to configure this path to be not exact
if (path.charAt(path.length() - 1) != '*') {
state = state.setExactPath(true);
state = state.setPath(path);
} else {
state = state.setExactPath(false);
state = state.setPath(path.substring(0, path.length() - 1));
}
// See if the path contains ":" - if so then it contains parameter capture groups and we have to generate
// a regex for that
int params = 0;
for (int i = 0; i < path.length(); i++) {
if (path.charAt(i) == ':') {
params++;
}
}
if (params > 0) {
int found = createPatternRegex(path);
if (params != found) {
throw new IllegalArgumentException("path param does not follow the variable naming rules, expected (" + params + ") found (" + found + ")");
}
}
state = state.setPathEndsWithSlash(state.getPath().endsWith("/"));
}
private synchronized void setRegex(String regex) {
state = state.setPattern(Pattern.compile(regex));
state = state.setExactPath(true);
findNamedGroups(state.getPattern().pattern());
}
private synchronized void findNamedGroups(String path) {
Matcher m = RE_TOKEN_NAME_SEARCH.matcher(path);
while (m.find()) {
state = state.addNamedGroupInRegex(m.group(1));
}
}
// Allow end users to select either the regular valid characters or the extender pattern
private static final String RE_VAR_NAME = Boolean.getBoolean("io.vertx.web.route.param.extended-pattern") ?
"[A-Za-z_$][A-Za-z0-9_$-]*" :
"[A-Za-z0-9_]+";
// Pattern for :<token name> in path
private static final Pattern RE_TOKEN_SEARCH = Pattern.compile(":(" + RE_VAR_NAME + ")");
// Pattern for (?<token name>) in path
private static final Pattern RE_TOKEN_NAME_SEARCH = Pattern.compile("\\(\\?<(" + RE_VAR_NAME + ")>");
// intersection of regex chars and https://tools.ietf.org/html/rfc3986#section-3.3
private static final Pattern RE_OPERATORS_NO_STAR = Pattern.compile("([\\(\\)\\$\\+\\.])");
private synchronized int createPatternRegex(String path) {
// escape path from any regex special chars
path = RE_OPERATORS_NO_STAR.matcher(path).replaceAll("\\\\$1");
// allow usage of * at the end as per documentation
if (path.charAt(path.length() - 1) == '*') {
path = path.substring(0, path.length() - 1) + "(?<rest>.*)";
state = state.setExactPath(false);
} else {
state = state.setExactPath(true);
}
// We need to search for any :<token name> tokens in the String and replace them with named capture groups
Matcher m = RE_TOKEN_SEARCH.matcher(path);
StringBuffer sb = new StringBuffer();
List<String> groups = new ArrayList<>();
int index = 0;
while (m.find()) {
String param = "p" + index;
String group = m.group().substring(1);
if (groups.contains(group)) {
throw new IllegalArgumentException("Cannot use identifier " + group + " more than once in pattern string");
}
m.appendReplacement(sb, "(?<" + param + ">[^/]+)");
groups.add(group);
index++;
}
m.appendTail(sb);
path = sb.toString();
state = state.setGroups(groups);
state = state.setPattern(Pattern.compile(path));
return index;
}
private void checkPath(String path) {
if ("".equals(path) || path.charAt(0) != '/') {
throw new IllegalArgumentException("Path must start with /");
}
}
int order() {
return state.getOrder();
}
private synchronized void checkAdd() {
if (!state.isAdded()) {
router.add(this);
state = state.setAdded(true);
}
}
public synchronized RouteImpl setEmptyBodyPermittedWithConsumes(boolean emptyBodyPermittedWithConsumes) {
state = state.setEmptyBodyPermittedWithConsumes(emptyBodyPermittedWithConsumes);
return this;
}
private void validateMount(Router router) {
for (Route route : router.getRoutes()) {
final String combinedPath;
if (route.getPath() == null) {
// This is a router with pattern and not path
// we cannot validate
continue;
}
// this method is similar to what the pattern generation does but
// it will not generate a pattern, it will only verify if the paths do not contain
// colliding parameter names with the mount path
// escape path from any regex special chars
combinedPath = RE_OPERATORS_NO_STAR
.matcher(state.getPath() + (state.isPathEndsWithSlash() ? route.getPath().substring(1) : route.getPath()))
.replaceAll("\\\\$1");
// We need to search for any :<token name> tokens in the String
Matcher m = RE_TOKEN_SEARCH.matcher(combinedPath);
Set<String> groups = new HashSet<>();
while (m.find()) {
String group = m.group();
if (groups.contains(group)) {
throw new IllegalStateException("Cannot use identifier " + group + " more than once in pattern string");
}
groups.add(group);
}
}
}
}