001/* 002 * JGrapes Event Driven Framework 003 * Copyright (C) 2016-2018 Michael N. Lipp 004 * 005 * This program is free software; you can redistribute it and/or modify it 006 * under the terms of the GNU Affero General Public License as published by 007 * the Free Software Foundation; either version 3 of the License, or 008 * (at your option) any later version. 009 * 010 * This program is distributed in the hope that it will be useful, but 011 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 012 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License 013 * for more details. 014 * 015 * You should have received a copy of the GNU Affero General Public License along 016 * with this program; if not, see <http://www.gnu.org/licenses/>. 017 */ 018 019package org.jgrapes.http; 020 021import java.net.URI; 022import java.text.ParseException; 023import java.util.ArrayList; 024import java.util.Arrays; 025import java.util.List; 026import java.util.Optional; 027import java.util.Spliterators.AbstractSpliterator; 028import java.util.StringTokenizer; 029import java.util.function.Consumer; 030import java.util.regex.Matcher; 031import java.util.regex.Pattern; 032import java.util.stream.Collectors; 033import java.util.stream.Stream; 034import java.util.stream.StreamSupport; 035 036/** 037 * A resource pattern can be used to filter URIs. A pattern looks 038 * similar to a URI (<code>scheme://host:port/path</code>) with the 039 * following differences: 040 * 041 * * The <em>scheme</em> may be a single protocol name or a list 042 * of protocol names separated by commas, or an asterisk, which is matched 043 * by URIs with any scheme. The scheme part ({@code scheme://}) is optional 044 * in a pattern. Omitting it is equivalent to specifying an asterisk. 045 * 046 * * The <em>host</em> may be a host name or an IP address or an asterisk. 047 * Unless the value is an asterisk, filtered URIs must match the value 048 * literally. 049 * 050 * * The <em>port</em> may be a number or an asterisk. 051 * Unless the value is an asterisk, filtered URIs must match it. 052 * 053 * * Specifying a port ({@code :port}) is optional. If omitted, 054 * it is equivalent to specifying an asterisk. 055 * 056 * * If the scheme part is omitted, the {@code host:port} part may 057 * completely be left out as well, which is 058 * equivalent to specifying an asterisk for both host and port. 059 * 060 * * The optional path part consist of one or more path separated by commas. 061 * 062 * Each path consists of a sequence of names and asterisks separated 063 * by slashes or a vertical bar ("|"). A name must be matched by the 064 * corresponding path element of filtered URIs, an asterisk is matched by 065 * any corresponding path element (which, however, must exist in the 066 * filtered URI). The final element in 067 * the path of a pattern may be two asterisks ({@code **}), which matches 068 * any remaining path elements in the filtered URI. 069 * 070 * Using a vertical bar instead of a slash separates the path in a 071 * prefix part and the rest. The number of prefix segments is the 072 * value returned by the match methods. 073 * 074 * If a path ends with a vertical bar and the URI matched with the 075 * path does not end with a slash, a slash is appended to the URI 076 * before matching. This causes both `/foo` and `/foo/` to match 077 * a path `/foo|`. This is usually intended. If you do want to 078 * treat `/foo` as a leaf, specify `/foo,/foo|` in your pattern. 079 * 080 */ 081@SuppressWarnings("PMD.GodClass") 082public class ResourcePattern { 083 084 @SuppressWarnings("PMD.AvoidFieldNameMatchingTypeName") 085 private static Pattern resourcePattern = Pattern.compile( 086 "^((?<proto>[^:]+|\\*)://)?" // Optional protocol (2) 087 + "(" // Start of optional host/port part 088 + "(?<host>([^\\[/\\|][^:/\\|]*)|(\\[[^\\]]*\\]))" // Host (4) 089 + "(:(?<port>([0-9]+)|(\\*)))?" // Optional port (8) 090 + ")?" // End of optional host/port 091 + "(?<path>[/\\|].*)?"); // Finally path (11) 092 093 private final String pattern; 094 private final String protocol; 095 private final String host; 096 private final String port; 097 private final String path; 098 private final String[][] pathPatternElements; 099 private int[] prefixSegs; 100 101 /** 102 * Creates a new resource pattern. 103 * 104 * @param pattern the pattern to be used for matching 105 * @throws ParseException if an invalid pattern is specified 106 */ 107 @SuppressWarnings({ "PMD.AvoidInstantiatingObjectsInLoops", 108 "PMD.CognitiveComplexity" }) 109 public ResourcePattern(String pattern) throws ParseException { 110 this.pattern = pattern; 111 Matcher rpm = resourcePattern.matcher(pattern); 112 if (!rpm.matches()) { 113 throw new ParseException("Invalid pattern: " + pattern, 0); 114 } 115 protocol = rpm.group("proto"); 116 host = rpm.group("host"); 117 port = rpm.group("port"); 118 path = rpm.group("path"); 119 if (path == null) { 120 pathPatternElements = new String[0][]; 121 } else { 122 String[] paths = path.split(","); 123 pathPatternElements = new String[paths.length][]; 124 prefixSegs = new int[paths.length]; 125 for (int i = 0; i < paths.length; i++) { 126 @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") 127 List<String> segs = new ArrayList<>(); 128 prefixSegs[i] = 0; 129 StringTokenizer tokenizer = new StringTokenizer( 130 paths[i], "/|", true); 131 while (tokenizer.hasMoreTokens()) { 132 String token = tokenizer.nextToken(); 133 switch (token) { 134 case "/": 135 continue; 136 case "|": 137 prefixSegs[i] = segs.size(); 138 continue; 139 default: 140 segs.add(token); 141 continue; 142 } 143 } 144 if (paths[i].endsWith("/") || paths[i].endsWith("|")) { 145 segs.add(""); 146 } 147 pathPatternElements[i] = segs.toArray(new String[0]); 148 } 149 } 150 } 151 152 /** 153 * @return the pattern (string) that was used to create this 154 * resource pattern. 155 */ 156 public String pattern() { 157 return pattern; 158 } 159 160 /** 161 * @return the protocol value specified in the pattern or {@code null} 162 */ 163 public String protocol() { 164 return protocol; 165 } 166 167 /** 168 * @return the host value specified in the pattern or {@code null} 169 */ 170 public String host() { 171 return host; 172 } 173 174 /** 175 * @return the port value specified in the pattern or {@code null} 176 */ 177 public String port() { 178 return port; 179 } 180 181 /** 182 * @return the path value specified in the pattern or {@code null} 183 */ 184 public String path() { 185 return path; 186 } 187 188 /** 189 * Matches the given resource URI against the pattern. 190 * 191 * @param resource the URI specifying the resource to match 192 * @return -1 if the resource does not match, else the number 193 * of prefix segments (which may be 0) 194 */ 195 public int matches(URI resource) { 196 return matches(resource, Integer.MAX_VALUE); 197 } 198 199 /** 200 * Matches the given resource URI against the pattern, comparing 201 * at most the given number of path segments. 202 * 203 * @param resource the URI specifying the resource to match 204 * @param pathSegs the maximum number of path segments to compare 205 * @return -1 if the resource does not match, else the number 206 * of prefix segments (which may be 0) 207 */ 208 @SuppressWarnings({ "PMD.CyclomaticComplexity", "PMD.NPathComplexity", 209 "PMD.CollapsibleIfStatements", "PMD.CognitiveComplexity", 210 "PMD.AvoidDeeplyNestedIfStmts" }) 211 public int matches(URI resource, int pathSegs) { 212 if (protocol != null && !"*".equals(protocol)) { 213 if (resource.getScheme() == null) { 214 return -1; 215 } 216 if (Arrays.stream(protocol.split(",")) 217 .noneMatch(proto -> proto.equals(resource.getScheme()))) { 218 return -1; 219 } 220 } 221 if (host != null && !"*".equals(host)) { 222 if (resource.getHost() == null 223 || !resource.getHost().equals(host)) { 224 return -1; 225 } 226 } 227 if (port != null && !"*".equals(port)) { 228 if (Integer.parseInt(port) != resource.getPort()) { 229 return -1; 230 } 231 } 232 233 String[] reqElements = PathSpliterator.stream(resource.getPath()) 234 .skip(1).toArray(size -> new String[size]); 235 String[] reqElementsPlus = null; // Created lazily 236 for (int pathIdx = 0; pathIdx < pathPatternElements.length; pathIdx++) { 237 String[] pathPattern = pathPatternElements[pathIdx]; 238 if (prefixSegs[pathIdx] == pathPattern.length - 1 239 && lastIsEmpty(pathPattern)) { 240 // Special case, pattern ends with vertical bar 241 if (reqElementsPlus == null) { 242 reqElementsPlus = reqElements; 243 if (!lastIsEmpty(reqElementsPlus)) { 244 reqElementsPlus = Arrays.copyOf( 245 reqElementsPlus, reqElementsPlus.length + 1); 246 reqElementsPlus[reqElementsPlus.length - 1] = ""; 247 } 248 } 249 if (matchPath(pathPattern, reqElementsPlus, pathSegs)) { 250 return prefixSegs[pathIdx]; 251 } 252 } else { 253 if (matchPath(pathPattern, reqElements, pathSegs)) { 254 return prefixSegs[pathIdx]; 255 } 256 } 257 } 258 return -1; 259 } 260 261 /** 262 * Matches the given pattern against the given resource URI. 263 * 264 * @param pattern the pattern to match 265 * @param resource the URI specifying the resource to match 266 * @return {@code true} if the resource URI matches 267 * @throws ParseException if an invalid pattern is specified 268 */ 269 public static boolean matches(String pattern, URI resource) 270 throws ParseException { 271 return new ResourcePattern(pattern).matches(resource) >= 0; 272 } 273 274 /** 275 * Matches the given pattern against the given resource URI, comparing 276 * at most the given number of path segments. 277 * 278 * @param pattern the pattern to match 279 * @param resource the URI specifying the resource to match 280 * @param pathSegments the maximum number of path segments to compare 281 * @return {@code true} if the resource URI matches 282 * @throws ParseException if an invalid pattern is specified 283 */ 284 public static boolean matches(String pattern, URI resource, 285 int pathSegments) 286 throws ParseException { 287 return new ResourcePattern(pattern).matches(resource, 288 pathSegments) >= 0; 289 } 290 291 @SuppressWarnings("PMD.UseVarargs") 292 private static boolean lastIsEmpty(String[] elements) { 293 return elements.length > 0 294 && elements[elements.length - 1].length() == 0; 295 } 296 297 @SuppressWarnings({ "PMD.AvoidLiteralsInIfCondition" }) 298 private boolean matchPath(String[] patternElements, String[] reqElements, 299 int maxSegs) { 300 int pathIdx = 0; 301 int reqIdx = 0; 302 int patternEls = Math.min(patternElements.length, maxSegs); 303 int reqEls = Math.min(reqElements.length, maxSegs); 304 while (true) { 305 if (pathIdx == patternEls) { 306 // Reached pattern end, is match if we also reached end 307 // of requested elements. 308 return reqIdx == reqEls; 309 } 310 if (reqIdx == reqEls) { 311 // Not pattern end, but more segments from request 312 // means no match. 313 return false; 314 } 315 @SuppressWarnings({ "PMD.AssignmentInOperand", 316 "PMD.AvoidDuplicateLiterals" }) 317 String matchElement = patternElements[pathIdx++]; 318 if ("**".equals(matchElement)) { 319 // Accept anything left means match. 320 return true; 321 } 322 @SuppressWarnings("PMD.AssignmentInOperand") 323 String reqElement = reqElements[reqIdx++]; 324 if (!"*".equals(matchElement) && !matchElement.equals(reqElement)) { 325 // If not equal (or wildcard) we have no match. 326 return false; 327 } 328 } 329 330 } 331 332 /** 333 * Removes the given number of segments (and their trailing slashes) 334 * from the beginning of the path. Segments may be empty. This implies 335 * that invoking this method with a path that starts with a 336 * slash, the first removed segment is the empty segment 337 * preceding the slash and the starting slash. Put differently, 338 * invoking this method with an absolute path and 1 makes the path 339 * relative. 340 * 341 * @param path the path 342 * @param segments the number of segments to remove 343 * @return the result 344 */ 345 public static String removeSegments(String path, int segments) { 346 return PathSpliterator.stream(path) 347 .skip(segments).collect(Collectors.joining("/")); 348 } 349 350 /** 351 * Splits the given path in a prefix with the given number of 352 * segments and the rest. Like {{@link #removeSegments(String, int)} 353 * but additionally returning the removed segments. 354 * 355 * @param path the path 356 * @param segments the number of segments in the prefi 357 * @return the prefix and the rest 358 */ 359 @SuppressWarnings({ "PMD.AssignmentInOperand", 360 "PMD.AvoidLiteralsInIfCondition" }) 361 public static String[] split(String path, int segments) { 362 StringBuilder prefix = new StringBuilder(); 363 StringBuilder suffix = new StringBuilder(); 364 int[] count = { 0 }; 365 PathSpliterator.stream(path).forEach(seg -> { 366 if (count[0]++ < segments) { 367 if (count[0] > 1) { 368 prefix.append('/'); 369 } 370 prefix.append(seg); 371 } else { 372 if (count[0] > segments + 1) { 373 suffix.append('/'); 374 } 375 suffix.append(seg); 376 } 377 }); 378 return new String[] { prefix.toString(), suffix.toString() }; 379 } 380 381 /** 382 * If the URI matches, returns the path split according to 383 * the matched pattern (see {@link #split(String, int)}). 384 * 385 * @param resource the resource 386 * @return the result. 387 */ 388 public Optional<String[]> splitPath(URI resource) { 389 int matchRes = matches(resource); 390 if (matchRes < 0) { 391 return Optional.empty(); 392 } 393 return Optional.of(split(resource.getPath(), matchRes + 1)); 394 } 395 396 /** 397 * If the URI matches, returns the path without prefix as specified 398 * by the matched pattern (see {@link #split(String, int)}). 399 * 400 * @param resource the resource 401 * @return the result. 402 */ 403 @SuppressWarnings("PMD.AssignmentInOperand") 404 public Optional<String> pathRemainder(URI resource) { 405 int matchRes = matches(resource); 406 if (matchRes < 0) { 407 return Optional.empty(); 408 } 409 int segments = matchRes + 1; 410 StringBuilder suffix = new StringBuilder(); 411 int[] count = { 0 }; 412 PathSpliterator.stream(resource.getPath()).forEach(seg -> { 413 if (count[0]++ >= segments) { 414 if (count[0] > segments + 1) { 415 suffix.append('/'); 416 } 417 suffix.append(seg); 418 } 419 }); 420 return Optional.of(suffix.toString()); 421 } 422 423 /* 424 * (non-Javadoc) 425 * 426 * @see java.lang.Object#toString() 427 */ 428 @Override 429 public String toString() { 430 StringBuilder builder = new StringBuilder(30); 431 builder.append("ResourcePattern [") 432 .append(pattern) 433 .append(']'); 434 return builder.toString(); 435 } 436 437 /* 438 * (non-Javadoc) 439 * 440 * @see java.lang.Object#hashCode() 441 */ 442 @Override 443 public int hashCode() { 444 final int prime = 31; 445 int result = 1; 446 result = prime * result + ((pattern == null) ? 0 : pattern.hashCode()); 447 return result; 448 } 449 450 /* 451 * (non-Javadoc) 452 * 453 * @see java.lang.Object#equals(java.lang.Object) 454 */ 455 @Override 456 public boolean equals(Object obj) { 457 if (this == obj) { 458 return true; 459 } 460 if (obj == null) { 461 return false; 462 } 463 if (getClass() != obj.getClass()) { 464 return false; 465 } 466 ResourcePattern other = (ResourcePattern) obj; 467 if (pattern == null) { 468 if (other.pattern != null) { 469 return false; 470 } 471 } else if (!pattern.equals(other.pattern)) { 472 return false; 473 } 474 return true; 475 } 476 477 /** 478 * Returns the segments of the path. If the path starts with a slash, 479 * an empty string is returned as first segment. If the path ends 480 * with a slash, an empty string is returned as final segment. 481 */ 482 public static class PathSpliterator extends AbstractSpliterator<String> { 483 private StringTokenizer tokenizer; 484 private boolean pendingLeadingEmpty; 485 private boolean pendingTrailingEmpty; 486 487 /** 488 * Creates a new stream for the given path, using "/" 489 * as path separator. 490 * 491 * @param path the path 492 */ 493 public static Stream<String> stream(String path) { 494 return StreamSupport.stream(new PathSpliterator(path), false); 495 } 496 497 /** 498 * Creates a new stream for the given path, using 499 * the characters from delimiters as seperators. 500 * 501 * @param path the path 502 * @param delimiters the delimiters 503 */ 504 public static Stream<String> stream(String path, String delimiters) { 505 return StreamSupport.stream( 506 new PathSpliterator(path, delimiters), false); 507 } 508 509 /** 510 * Creates a new spliterator for the given path, using "/" 511 * as path separator. 512 * 513 * @param path the path 514 */ 515 public PathSpliterator(String path) { 516 this(path, "/"); 517 } 518 519 /** 520 * Creates a new spliterator for the given path, using 521 * the characters from delimiters as seperators. 522 * 523 * @param path the path 524 * @param delimiters the delimiters 525 */ 526 public PathSpliterator(String path, String delimiters) { 527 super(Long.MAX_VALUE, ORDERED | IMMUTABLE); 528 tokenizer = new StringTokenizer(path, delimiters); 529 pendingLeadingEmpty = path.startsWith("/"); 530 pendingTrailingEmpty = path.endsWith("/"); 531 } 532 533 /* 534 * (non-Javadoc) 535 * 536 * @see java.util.Spliterator#tryAdvance(java.util.function.Consumer) 537 */ 538 @Override 539 public boolean tryAdvance(Consumer<? super String> consumer) { 540 if (tokenizer == null) { 541 return false; 542 } 543 if (pendingLeadingEmpty) { 544 pendingLeadingEmpty = false; 545 consumer.accept(""); 546 return true; 547 } 548 if (tokenizer.hasMoreTokens()) { 549 consumer.accept(tokenizer.nextToken()); 550 return true; 551 } 552 tokenizer = null; 553 if (pendingTrailingEmpty) { 554 consumer.accept(""); 555 return true; 556 } 557 return false; 558 } 559 560 } 561}