View Javadoc

1   package com.atlassian.marketplace.client.api;
2   
3   import java.lang.reflect.Method;
4   
5   import com.atlassian.fugue.Option;
6   
7   import static com.atlassian.fugue.Option.none;
8   import static com.atlassian.fugue.Option.some;
9   import static com.google.common.base.Preconditions.checkNotNull;
10  
11  /**
12   * Common interface for {@code enum} types that have a unique string key for each possible value.
13   * @since 2.0.0
14   */
15  public interface EnumWithKey
16  {
17      /**
18       * The string key that represents this value in the Marketplace API.
19       */
20      public String getKey();
21      
22      /**
23       * Helper class that can get allowable values or match a key string for any {@link EnumWithKey} type.
24       */
25      public static class Parser<A extends EnumWithKey>
26      {
27          private final A[] values;
28          
29          private Parser(A[] values)
30          {
31              this.values = checkNotNull(values);
32          }
33          
34          public A[] getValues()
35          {
36              return values;
37          }
38          
39          public Option<A> valueForKey(String key)
40          {
41              for (A v: values)
42              {
43                  if (v.getKey().equalsIgnoreCase(key))
44                  {
45                      return some(v);
46                  }
47              }
48              return none();
49          }
50          
51          public static <A extends EnumWithKey> Parser<A> forType(Class<A> enumClass)
52          {
53              try
54              {
55                  // This is ugly, but unfortunately Java's built-in {@code Enum} doesn't provide
56                  // any *generic* way to get the list of allowed values.
57                  Method method = enumClass.getDeclaredMethod("values");
58                  @SuppressWarnings("unchecked")
59                  A[] values = (A[]) method.invoke(null);
60                  return new Parser<A>(values);
61              }
62              catch (Exception e)
63              {
64                  throw new IllegalStateException(e);
65              }
66          }
67      }
68  }