1 package org.andromda.core.common;
2
3 import java.util.regex.PatternSyntaxException;
4 import org.apache.commons.lang.StringUtils;
5
6 /**
7 * Provides wild card matching on file paths (i.e. Cartridge.java will match <code>*.java</code>, etc).
8 *
9 * @author Chad Brandon
10 */
11 public class PathMatcher
12 {
13 /**
14 * A forward slash.
15 */
16 private static final String FORWARD_SLASH = "/";
17
18 /**
19 * A double star within a pattern.
20 */
21 private static final String DOUBLE_STAR = "**/*";
22
23 /**
24 * A tripple star within a pattern.
25 */
26 private static final String TRIPPLE_STAR = "***";
27
28 /**
29 * Provides matching of simple wildcards. (i.e. '*.java' etc.)
30 *
31 * @param path the path to match against.
32 * @param pattern the pattern to check if the path matches.
33 * @return true if the <code>path</code> matches the given <code>pattern</code>, false otherwise.
34 */
35 public static boolean wildcardMatch(
36 String path,
37 String pattern)
38 {
39 ExceptionUtils.checkNull(
40 "path",
41 path);
42 ExceptionUtils.checkNull(
43 "pattern",
44 pattern);
45
46 // - remove any starting slashes, as they interfere with the matching
47 if (path.startsWith(FORWARD_SLASH))
48 {
49 path =
50 path.substring(
51 1,
52 path.length());
53 }
54 path = path.trim();
55 pattern = pattern.trim();
56 boolean matches;
57 pattern =
58 StringUtils.replace(
59 pattern,
60 ".",
61 "\\.");
62 boolean matchAll = pattern.contains(DOUBLE_STAR) && !pattern.contains(TRIPPLE_STAR);
63 if (matchAll)
64 {
65 String replacement = ".*";
66 if (!path.contains(FORWARD_SLASH))
67 {
68 replacement = ".*";
69 }
70 pattern =
71 StringUtils.replaceOnce(
72 pattern,
73 DOUBLE_STAR,
74 replacement);
75 }
76 pattern =
77 StringUtils.replace(
78 pattern,
79 "*",
80 ".*");
81 try
82 {
83 matches = path.matches(pattern);
84 }
85 catch (final PatternSyntaxException exception)
86 {
87 matches = false;
88 }
89 if (!matchAll)
90 {
91 matches =
92 matches &&
93 StringUtils.countMatches(
94 pattern,
95 FORWARD_SLASH) == StringUtils.countMatches(
96 path,
97 FORWARD_SLASH);
98 }
99 return matches;
100 }
101 }