View Javadoc
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 java.lang.reflect.InvocationTargetException;
26  import java.lang.reflect.Method;
27  import java.util.Optional;
28  import java.util.function.Function;
29  
30  /**
31   * Enum utility methods.
32   */
33  public final class EnumSupport {
34  
35    private EnumSupport() {
36    }
37  
38    /**
39     * Support method to help enums implement an enhanced <code>valueOf(String)</code> method, that does not throw an
40     * IllegalArgumentException in case of incoming values, that do not match any of the enum's values.
41     *
42     * @param enumClass
43     *          the enum's class
44     * @param value
45     *          the value to look up
46     * @return the matching enum value or null if none matches
47     */
48    @SuppressWarnings("unchecked")
49    public static <E extends Enum<?>> E fromString(Class<E> enumClass, String value) {
50      if (value == null)
51        return null;
52      value = value.trim();
53      if (value.length() == 0)
54        return null;
55      Method m = null;
56      try {
57        m = enumClass.getDeclaredMethod("valueOf", String.class);
58      } catch (NoSuchMethodException ignore) {
59      }
60      try {
61        m.setAccessible(true);
62      } catch (SecurityException ignore) {
63      }
64      try {
65        E enumConstant = (E) m.invoke(null, value);
66        return enumConstant;
67      } catch (IllegalAccessException ignore) {
68      } catch (InvocationTargetException ignore) {
69      }
70      return null;
71    }
72  
73    /** Create a function to parse a string into an Enum value. */
74    public static <A extends Enum<A>> Function<String, Optional<A>> parseEnum(final A e) {
75      return s -> {
76        try {
77          return Optional.of((A) Enum.valueOf(e.getClass(), s));
78        } catch (Exception ex) {
79          return Optional.empty();
80        }
81      };
82    }
83  }