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 {
21 INSTANCE;
22
23 private static final Pattern VALID_FEATURE_KEY_PATTERN = Pattern.compile("[\\w\\.\\-]+");
24
25 /**
26 * Verify that the given string represents a valid feature key.
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 {
33 return INSTANCE.apply(input);
34 }
35
36 /**
37 * Ensure that the given input string is a valid feature key. Otherwise an exception is thrown.
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 {
44 if (isValidFeatureKey(input))
45 {
46 return input;
47 }
48 else
49 {
50 throw new InvalidFeatureKeyException("Invalid feature key: '" + input + "'");
51 }
52 }
53
54 /**
55 * Verify that the given string represents a valid feature key.
56 * @param input a feature key candidate
57 * @return <code>true</code> if the given input is an acceptable feature key, <code>false</code> otherwise
58 */
59 @Override
60 public boolean apply(@Nullable final String input)
61 {
62 return input != null && VALID_FEATURE_KEY_PATTERN.matcher(input).matches();
63 }
64 }