1 /*
2 * Licensed to The Apereo Foundation under one or more contributor license
3 * agreements. See the NOTICE file distributed with this work for additional
4 * information regarding copyright ownership.
5 *
6 *
7 * The Apereo Foundation licenses this file to you under the Educational
8 * Community License, Version 2.0 (the "License"); you may not use this file
9 * except in compliance with the License. You may obtain a copy of the License
10 * at:
11 *
12 * http://opensource.org/licenses/ecl2.txt
13 *
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
16 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
17 * License for the specific language governing permissions and limitations under
18 * the License.
19 *
20 */
21
22
23 package org.opencastproject.util;
24
25 import static org.opencastproject.util.data.Option.none;
26 import static org.opencastproject.util.data.Option.some;
27
28 import org.opencastproject.util.data.Function;
29 import org.opencastproject.util.data.Option;
30
31 import java.lang.reflect.InvocationTargetException;
32 import java.lang.reflect.Method;
33
34 /**
35 * Enum utility methods.
36 */
37 public final class EnumSupport {
38
39 private EnumSupport() {
40 }
41
42 /**
43 * Support method to help enums implement an enhanced <code>valueOf(String)</code> method, that does not throw an
44 * IllegalArgumentException in case of incoming values, that do not match any of the enum's values.
45 *
46 * @param enumClass
47 * the enum's class
48 * @param value
49 * the value to look up
50 * @return the matching enum value or null if none matches
51 */
52 @SuppressWarnings("unchecked")
53 public static <E extends Enum<?>> E fromString(Class<E> enumClass, String value) {
54 if (value == null)
55 return null;
56 value = value.trim();
57 if (value.length() == 0)
58 return null;
59 Method m = null;
60 try {
61 m = enumClass.getDeclaredMethod("valueOf", String.class);
62 } catch (NoSuchMethodException ignore) {
63 }
64 try {
65 m.setAccessible(true);
66 } catch (SecurityException ignore) {
67 }
68 try {
69 E enumConstant = (E) m.invoke(null, value);
70 return enumConstant;
71 } catch (IllegalAccessException ignore) {
72 } catch (InvocationTargetException ignore) {
73 }
74 return null;
75 }
76
77 /** Create a function to parse a string into an Enum value. */
78 public static <A extends Enum> Function<String, Option<A>> parseEnum(final A e) {
79 return new Function<String, Option<A>>() {
80 @Override public Option<A> apply(String s) {
81 try {
82 return some((A) Enum.valueOf(e.getClass(), s));
83 } catch (Exception ex) {
84 return none();
85 }
86 }
87 };
88 }
89 }