View Javadoc
1   package com.atlassian.plugin.predicate;
2   
3   import com.atlassian.annotations.ExperimentalApi;
4   import com.atlassian.plugin.Plugin;
5   import com.atlassian.plugin.util.RegularExpressions;
6   
7   import java.util.Collection;
8   import java.util.regex.Matcher;
9   import java.util.regex.Pattern;
10  
11  /**
12   * A plugin predicate which matches regular expressions against plugin keys.
13   */
14  @ExperimentalApi
15  public class PluginKeyPatternsPredicate implements PluginPredicate {
16      public enum MatchType {
17          /**
18           * Specifies a PluginPredicate which matches if any one of a given list of
19           * included regular expressions is matched.
20           */
21          MATCHES_ANY {
22              /**
23               * Obtain a regular expression which matches any of the provided parts.
24               */
25              public String buildRegularExpression(final Collection<String> parts) {
26                  return RegularExpressions.anyOf(parts);
27              }
28  
29              /**
30               * This MatchType matches if the Matcher does match, as we want to match if any of the
31               * inclusions provided to {@link #buildRegularExpression} matches.
32               */
33              public boolean processMatcher(final Matcher matcher) {
34                  return matcher.matches();
35              }
36          },
37  
38          /**
39           * Specifies a PluginPredicate which matches if none of a given list of
40           * excluded regular expressions is matched.
41           */
42          MATCHES_NONE {
43              /**
44               * Obtain a regular expression which matches any of the provided parts.
45               */
46              public String buildRegularExpression(final Collection<String> parts) {
47                  return RegularExpressions.anyOf(parts);
48              }
49  
50              /**
51               * This MatchType matches if the Matcher does not match, as we want to match only when
52               * none of the exclusions provided to {@link #buildRegularExpression} matches.
53               */
54              public boolean processMatcher(final Matcher matcher) {
55                  return !matcher.matches();
56              }
57          };
58  
59          public abstract String buildRegularExpression(final Collection<String> parts);
60  
61          public abstract boolean processMatcher(final Matcher matcher);
62      }
63  
64      private final MatchType matchType;
65      private final Pattern pattern;
66  
67      public PluginKeyPatternsPredicate(final MatchType matchType, final Collection<String> parts) {
68          this.matchType = matchType;
69          this.pattern = Pattern.compile(matchType.buildRegularExpression(parts));
70      }
71  
72      public boolean matches(final Plugin plugin) {
73          return matchType.processMatcher(pattern.matcher(plugin.getKey()));
74      }
75  }