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
13
14
15 public interface EnumWithKey
16 {
17
18
19
20 public String getKey();
21
22
23
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
56
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 }