1 package org.simantics.graph.store;
3 import gnu.trove.set.hash.THashSet;
5 import java.util.regex.Pattern;
7 import org.simantics.graph.query.Path;
8 import org.simantics.graph.query.PathChild;
9 import org.simantics.graph.query.Paths;
11 public class PathPattern {
13 private static PathPattern EMPTY_PATTERN = new PathPattern(null, null);
18 private PathPattern(Path prefix, Pattern suffix) {
23 public static PathPattern compile(String pattern) {
24 pattern = stripPatternPrefix(pattern);
27 String[] parts = pattern.split("/");
29 Path path = Paths.Root;
30 for(int i=0;i<parts.length;++i) {
31 String part = parts[i];
32 if(containsWildcards(part)) {
33 StringBuilder b = new StringBuilder(pattern.length());
34 for(;i<parts.length;++i) {
38 return new PathPattern(path, compileGlobPattern(b.toString()));
41 path = new PathChild(part, path);
44 return new PathPattern(path, null);
47 private static String patternStart = "http://";
48 private static String stripPatternPrefix(String pattern) {
49 for(int i=0;i<patternStart.length();++i) {
50 if(pattern.length() <= i)
52 char c = pattern.charAt(i);
54 return pattern.substring(i);
55 if(c != patternStart.charAt(i) && c != '?')
58 return pattern.substring(patternStart.length());
61 private static boolean containsWildcards(String pattern) {
62 return pattern.contains("*") || pattern.contains("?");
65 private static Pattern compileGlobPattern(String pattern) {
66 int length = pattern.length();
67 StringBuilder b = new StringBuilder(2*length);
69 for(int i=0;i<length;++i) {
70 char c = pattern.charAt(i);
81 c = pattern.charAt(i);
82 if(c == '\\' && i+1 < length && pattern.charAt(i+1) == 'E') {
84 b.append("\\E\\\\E\\Q");
86 else if(c == '*' || c == '?')
99 return Pattern.compile(b.toString());
103 public String toString() {
104 return "(" + prefix + ", " + suffix + ")";
107 public void search(IdentityStore store, THashSet<Path> result) {
108 int id = store.pathToId(prefix);
111 store.findChildren(id, prefix, "", suffix, result);
114 public static void main(String[] args) {
115 System.out.println(compile("http://www.simantics.org/*/foo"));