PathParser { public PathParserResult parse(String path) { Matcher matcher = caseSelector.matcher(); matcher.feed(path).end(); if (matcher.getDomain() < 0) { return new PathParserResult(-1, new int[0], new int[0]); } PathParserCase parserCase = cases[matcher.getDomain()]; PathParserElement[] elements = parserCase.elements; int[] startIndexes = new int[elements.length]; int[] endIndexes = new int[startIndexes.length]; if (elements.length > 0) { Matcher[] matchers = new Matcher[elements.length]; for (int j = 0; j < matchers.length; ++j) { matchers[j] = elements[j].pattern.matcher(); } startIndexes[0] = parserCase.prefixLength; endIndexes[0] = parserCase.prefixLength; int i = 0; while (i < elements.length) { int next = matchers[i].eat(path, endIndexes[i]); if (next == -1) { matchers[i--].restart(); } else { endIndexes[i] = next; if (i + 1 < elements.length) { startIndexes[++i] = next; endIndexes[i] = next; } else if (next == path.length()) { break; } } } for (i = 0; i < endIndexes.length; ++i) { endIndexes[i] -= elements[i].suffixLength; } } return new PathParserResult(matcher.getDomain(), startIndexes, endIndexes); } PathParser(PathParserCase[] cases, Pattern caseSelector);   PathParser(List<PathBuilder> pathBuilders); PathParser prepare(); PathParserResult parse(String path);  }
@Test public void parsesPath() { PathParserBuilder builder = new PathParserBuilder(); builder.path().text("/users"); builder.path().text("/users/").escapedRegex("[0-9]+"); builder.path().text("/users/").escapedRegex("[0-9]+").text("/edit"); PathParser parser = builder.build(); assertThat(parser.parse("/users").getCaseIndex(), is(0)); PathParserResult result = parser.parse("/users/23"); assertThat(result.getCaseIndex(), is(1)); assertThat(result.start(0), is(7)); assertThat(result.end(0), is(9)); result = parser.parse("/users/23/edit"); assertThat(result.getCaseIndex(), is(2)); assertThat(result.start(0), is(7)); assertThat(result.end(0), is(9)); }
@Test public void transformsRegex() { PathParserBuilder builder = new PathParserBuilder(); builder.path().escapedRegex("foo|bar-[0-9/]*|baz- PathParser parser = builder.build(); assertThat(parser.parse("foo").getCaseIndex(), is(0)); assertThat(parser.parse("bar-23").getCaseIndex(), is(0)); assertThat(parser.parse("bar-2/3").getCaseIndex(), is(-1)); assertThat(parser.parse("bar-2%2F3").getCaseIndex(), is(0)); assertThat(parser.parse("bar-2%2f3").getCaseIndex(), is(0)); assertThat(parser.parse("baz- assertThat(parser.parse("baz-%2F%2F").getCaseIndex(), is(-1)); }