01: package org.andromda.core.common;
02:
03: import java.util.regex.PatternSyntaxException;
04:
05: import org.apache.commons.lang.StringUtils;
06:
07: /**
08: * Provides wild card matching on file paths (i.e. Cartridge.java will match <code>*.java</code>, etc).
09: *
10: * @author Chad Brandon
11: */
12: public class PathMatcher {
13:
14: /**
15: * A forward slash.
16: */
17: private static final String FORWARD_SLASH = "/";
18:
19: /**
20: * A double star within a pattern.
21: */
22: private static final String DOUBLE_STAR = "**/";
23:
24: /**
25: * A tripple star within a pattern.
26: */
27: private static final String TRIPPLE_STAR = "***";
28:
29: /**
30: * Provides matching of simple wildcards. (i.e. '*.java' etc.)
31: *
32: * @param path the path to match against.
33: * @param pattern the pattern to check if the path matches.
34: * @return true if the <code>path</code> matches the given <code>pattern</code>, false otherwise.
35: */
36: public static boolean wildcardMatch(String path, String pattern) {
37: ExceptionUtils.checkNull("path", path);
38: ExceptionUtils.checkNull("pattern", pattern);
39: // - remove any starting slashes, as they interfere with the matching
40: if (path.startsWith(FORWARD_SLASH)) {
41: path = path.substring(1, path.length());
42: }
43: path = path.trim();
44: pattern = pattern.trim();
45: boolean matches;
46: pattern = StringUtils.replace(pattern, ".", "\\.");
47: boolean matchAll = pattern.indexOf(DOUBLE_STAR) != -1
48: && pattern.indexOf(TRIPPLE_STAR) == -1;
49: if (matchAll) {
50: String replacement = ".*/";
51: if (path.indexOf(FORWARD_SLASH) == -1) {
52: replacement = ".*";
53: }
54: pattern = StringUtils.replaceOnce(pattern, DOUBLE_STAR,
55: replacement);
56: }
57: pattern = StringUtils.replace(pattern, "*", ".*");
58: try {
59: matches = path.matches(pattern);
60: } catch (final PatternSyntaxException exception) {
61: matches = false;
62: }
63: if (!matchAll) {
64: matches = matches
65: && StringUtils.countMatches(pattern, FORWARD_SLASH) == StringUtils
66: .countMatches(path, FORWARD_SLASH);
67: }
68: return matches;
69: }
70: }
|