View Javadoc
1   package com.atlassian.sal.api.features;
2   
3   import com.google.common.base.Predicate;
4   
5   import javax.annotation.Nullable;
6   import javax.annotation.concurrent.Immutable;
7   import java.util.regex.Pattern;
8   
9   /**
10   * A given string represents a valid feature key if the following conditions are satisfied:
11   * <ul>
12   * <li>Contains alphanumeric characters including the dot (.), dash (,) and underscore (_) only</li>
13   * <li>The minimal size is at least one character, while the upper limit is not restricted</li>
14   * </ul>
15   *
16   * @since 2.10
17   */
18  @Immutable
19  public enum ValidFeatureKeyPredicate implements Predicate<String> {
20      INSTANCE;
21  
22      private static final Pattern VALID_FEATURE_KEY_PATTERN = Pattern.compile("[\\w\\.\\-]+");
23  
24      /**
25       * Verify that the given string represents a valid feature key.
26       *
27       * @param input a feature key candidate
28       * @return <code>true</code> if the given input is an acceptable feature key, <code>false</code> otherwise
29       * @see ValidFeatureKeyPredicate
30       */
31      public static boolean isValidFeatureKey(@Nullable final String input) {
32          return INSTANCE.apply(input);
33      }
34  
35      /**
36       * Ensure that the given input string is a valid feature key. Otherwise an exception is thrown.
37       *
38       * @param input the expected feature key
39       * @return the input if it is a valid feature key
40       * @throws InvalidFeatureKeyException if the input is not a valid feature key
41       */
42      public static String checkFeatureKey(@Nullable final String input) {
43          if (isValidFeatureKey(input)) {
44              return input;
45          } else {
46              throw new InvalidFeatureKeyException("Invalid feature key: '" + input + "'");
47          }
48      }
49  
50      /**
51       * Verify that the given string represents a valid feature key.
52       *
53       * @param input a feature key candidate
54       * @return <code>true</code> if the given input is an acceptable feature key, <code>false</code> otherwise
55       */
56      @Override
57      public boolean apply(@Nullable final String input) {
58          return input != null && VALID_FEATURE_KEY_PATTERN.matcher(input).matches();
59      }
60  }