Example usage for java.lang Enum valueOf

List of usage examples for java.lang Enum valueOf

Introduction

In this page you can find the example usage for java.lang Enum valueOf.

Prototype

public static <T extends Enum<T>> T valueOf(Class<T> enumType, String name) 

Source Link

Document

Returns the enum constant of the specified enum type with the specified name.

Usage

From source file:com.twilio.sdk.AppEngineClientConnection.java

public void sendRequestHeader(HttpRequest request) throws HttpException, IOException {
    try {/*from   w  w  w.j  a  v  a2 s.  c om*/
        HttpHost host = route.getTargetHost();

        URI uri = new URI(host.getSchemeName() + "://" + host.getHostName()
                + ((host.getPort() == -1) ? "" : (":" + host.getPort())) + request.getRequestLine().getUri());

        Class[] requestConstructorTypes = new Class[3];
        requestConstructorTypes[0] = URL.class;
        requestConstructorTypes[1] = HTTPMethod;
        requestConstructorTypes[2] = FetchOptions;

        Constructor requestConstructor = HTTPRequest.getConstructor(requestConstructorTypes);

        Class[] disallowTruncateTypes = new Class[0];
        Method disallowTruncate = FetchOptionsBuilder.getMethod("disallowTruncate", disallowTruncateTypes);

        this.request = requestConstructor.newInstance(uri.toURL(),
                Enum.valueOf(
                        (Class<? extends Enum>) Class.forName("com.google.appengine.api.urlfetch.HTTPMethod"),
                        request.getRequestLine().getMethod()),
                disallowTruncate.invoke(FetchOptionsBuilder, new Object[0]));

        Class[] addHeaderParameterTypes = new Class[1];
        addHeaderParameterTypes[0] = HTTPHeader;
        Method addHeader = HTTPRequest.getMethod("addHeader", addHeaderParameterTypes);

        Class[] httpHeaderConstructorTypes = new Class[2];
        httpHeaderConstructorTypes[0] = String.class;
        httpHeaderConstructorTypes[1] = String.class;

        Constructor httpHeaderConstructor = HTTPHeader.getConstructor(httpHeaderConstructorTypes);

        for (Header h : request.getAllHeaders()) {
            addHeader.invoke(this.request, httpHeaderConstructor.newInstance(h.getName(), h.getValue()));
        }

    } catch (Exception e) {
        throw new IOException("Error during invocation: " + e.getMessage(), e);
    }
}

From source file:io.coala.config.AbstractPropertyGetter.java

/**
 * @param defaultValue//w w  w.  j  a v a 2 s.c  o m
 * @return
 */
public <E extends Enum<E>> E getEnum(final E defaultValue) {
    final String value = defaultValue == null ? get("") : get(defaultValue.name());
    if (value != null && !value.isEmpty())
        try {
            return Enum.valueOf(defaultValue.getDeclaringClass(), value);
        } catch (final Throwable e) {
            LOG.warn("getObject failed", CoalaExceptionFactory.UNMARSHAL_FAILED.create(e, value,
                    defaultValue != null ? defaultValue.getClass() : Enum.class));
        }
    return defaultValue;
}

From source file:com.evolveum.midpoint.prism.util.JavaTypeConverter.java

public static <T> T convert(Class<T> expectedType, Object rawValue) {
    if (rawValue == null || expectedType.isInstance(rawValue)) {
        return (T) rawValue;
    }/*  w ww.  j a  v a2s  . c  om*/
    if (rawValue instanceof PrismPropertyValue<?>) {
        rawValue = ((PrismPropertyValue<?>) rawValue).getValue();
    }
    // This really needs to be checked twice
    if (rawValue == null || expectedType.isInstance(rawValue)) {
        return (T) rawValue;
    }

    // Primitive types

    // boolean
    if (expectedType == boolean.class && rawValue instanceof Boolean) {
        return (T) ((Boolean) rawValue);
    }
    if (expectedType == Boolean.class && rawValue instanceof String) {
        return (T) (Boolean) Boolean.parseBoolean(((String) rawValue));
    }
    if (expectedType == Boolean.class && rawValue instanceof PolyString) {
        return (T) (Boolean) Boolean.parseBoolean(((PolyString) rawValue).toString());
    }
    if (expectedType == boolean.class && rawValue instanceof String) {
        return (T) (Boolean) Boolean.parseBoolean(((String) rawValue));
    }
    if (expectedType == boolean.class && rawValue instanceof PolyString) {
        return (T) (Boolean) Boolean.parseBoolean(((PolyString) rawValue).toString());
    }
    if (expectedType == String.class && rawValue instanceof Boolean) {
        return (T) rawValue.toString();
    }

    // int
    if (expectedType == int.class && rawValue instanceof Integer) {
        return (T) ((Integer) rawValue);
    }
    if (expectedType == Integer.class && rawValue instanceof String) {
        return (T) (Integer) Integer.parseInt(((String) rawValue));
    }
    if (expectedType == int.class && rawValue instanceof String) {
        return (T) (Integer) Integer.parseInt(((String) rawValue));
    }
    if (expectedType == String.class && rawValue instanceof Integer) {
        return (T) rawValue.toString();
    }
    if (expectedType == int.class && rawValue instanceof Long) {
        return (T) (Integer) ((Long) rawValue).intValue();
    }

    if (expectedType == long.class && rawValue instanceof Long) {
        return (T) ((Long) rawValue);
    }
    if (expectedType == Long.class && rawValue instanceof String) {
        return (T) (Long) Long.parseLong(((String) rawValue));
    }
    if (expectedType == long.class && rawValue instanceof String) {
        return (T) (Long) Long.parseLong(((String) rawValue));
    }
    if (expectedType == String.class && rawValue instanceof Long) {
        return (T) rawValue.toString();
    }

    if (expectedType == float.class && rawValue instanceof Float) {
        return (T) ((Float) rawValue);
    }
    if (expectedType == Float.class && rawValue instanceof String) {
        return (T) (Float) Float.parseFloat(((String) rawValue));
    }
    if (expectedType == float.class && rawValue instanceof String) {
        return (T) (Float) Float.parseFloat(((String) rawValue));
    }
    if (expectedType == String.class && rawValue instanceof Float) {
        return (T) rawValue.toString();
    }

    if (expectedType == double.class && rawValue instanceof Double) {
        return (T) ((Double) rawValue);
    }
    if (expectedType == Double.class && rawValue instanceof String) {
        return (T) (Double) Double.parseDouble(((String) rawValue));
    }
    if (expectedType == double.class && rawValue instanceof String) {
        return (T) (Double) Double.parseDouble(((String) rawValue));
    }
    if (expectedType == String.class && rawValue instanceof Float) {
        return (T) rawValue.toString();
    }

    if (expectedType == byte.class && rawValue instanceof Byte) {
        return (T) ((Byte) rawValue);
    }
    if (expectedType == Byte.class && rawValue instanceof String) {
        return (T) (Byte) Byte.parseByte(((String) rawValue));
    }
    if (expectedType == byte.class && rawValue instanceof String) {
        return (T) (Byte) Byte.parseByte(((String) rawValue));
    }
    if (expectedType == String.class && rawValue instanceof Byte) {
        return (T) rawValue.toString();
    }

    if (expectedType == BigInteger.class && rawValue instanceof String) {
        return (T) new BigInteger(((String) rawValue));
    }
    if (expectedType == String.class && rawValue instanceof BigInteger) {
        return (T) ((BigInteger) rawValue).toString();
    }

    if (expectedType == BigDecimal.class && rawValue instanceof String) {
        return (T) new BigDecimal(((String) rawValue));
    }
    if (expectedType == String.class && rawValue instanceof BigDecimal) {
        return (T) ((BigDecimal) rawValue).toString();
    }

    if (expectedType == PolyString.class && rawValue instanceof String) {
        return (T) new PolyString((String) rawValue);
    }
    if (expectedType == PolyStringType.class && rawValue instanceof String) {
        PolyStringType polyStringType = new PolyStringType();
        polyStringType.setOrig((String) rawValue);
        return (T) polyStringType;
    }
    if (expectedType == String.class && rawValue instanceof PolyString) {
        return (T) ((PolyString) rawValue).getOrig();
    }
    if (expectedType == String.class && rawValue instanceof PolyStringType) {
        return (T) ((PolyStringType) rawValue).getOrig();
    }
    if (expectedType == PolyString.class && rawValue instanceof PolyStringType) {
        return (T) ((PolyStringType) rawValue).toPolyString();
    }
    if (expectedType == PolyString.class && rawValue instanceof Integer) {
        return (T) new PolyString(((Integer) rawValue).toString());
    }
    if (expectedType == PolyStringType.class && rawValue instanceof PolyString) {
        PolyStringType polyStringType = new PolyStringType((PolyString) rawValue);
        return (T) polyStringType;
    }
    if (expectedType == PolyStringType.class && rawValue instanceof Integer) {
        PolyStringType polyStringType = new PolyStringType(((Integer) rawValue).toString());
        return (T) polyStringType;
    }

    // Date and time
    if (expectedType == XMLGregorianCalendar.class && rawValue instanceof Long) {
        XMLGregorianCalendar xmlCalType = XmlTypeConverter.createXMLGregorianCalendar((Long) rawValue);
        return (T) xmlCalType;
    }
    if (expectedType == XMLGregorianCalendar.class && rawValue instanceof String) {
        XMLGregorianCalendar xmlCalType = magicDateTimeParse((String) rawValue);
        return (T) xmlCalType;
    }
    if (expectedType == String.class && rawValue instanceof XMLGregorianCalendar) {
        return (T) ((XMLGregorianCalendar) rawValue).toXMLFormat();
    }
    if (expectedType == Long.class && rawValue instanceof XMLGregorianCalendar) {
        return (T) (Long) XmlTypeConverter.toMillis((XMLGregorianCalendar) rawValue);
    }

    // XML Enums (JAXB)
    if (expectedType.isEnum() && expectedType.getAnnotation(XmlEnum.class) != null
            && rawValue instanceof String) {
        return XmlTypeConverter.toXmlEnum(expectedType, (String) rawValue);
    }
    if (expectedType == String.class && rawValue.getClass().isEnum()
            && rawValue.getClass().getAnnotation(XmlEnum.class) != null) {
        return (T) XmlTypeConverter.fromXmlEnum(rawValue);
    }

    // Java Enums
    if (expectedType.isEnum() && rawValue instanceof String) {
        return (T) Enum.valueOf((Class<Enum>) expectedType, (String) rawValue);
    }
    if (expectedType == String.class && rawValue.getClass().isEnum()) {
        return (T) rawValue.toString();
    }

    //QName
    if (expectedType == QName.class && rawValue instanceof QName) {
        return (T) rawValue;
    }
    if (expectedType == QName.class && rawValue instanceof String) {
        return (T) QNameUtil.uriToQName((String) rawValue);
    }

    throw new IllegalArgumentException("Expected " + expectedType + " type, but got " + rawValue.getClass());
}

From source file:io.wcm.sling.commons.request.RequestParam.java

/**
 * Returns a request parameter as enum value.
 * @param <T> Enum type//from   w w w.j a  va  2s  . c  o m
 * @param request Request.
 * @param param Parameter name.
 * @param enumClass Enum class
 * @param defaultValue Default value.
 * @return Parameter value or the default value if it is not set or an invalid enum value.
 */
@SuppressWarnings("unchecked")
public static <T extends Enum> T getEnum(ServletRequest request, String param, Class<T> enumClass,
        T defaultValue) {
    String value = RequestParam.get(request, param);
    if (StringUtils.isNotEmpty(value)) {
        try {
            return (T) Enum.valueOf(enumClass, value);
        } catch (IllegalArgumentException ex) {
            // ignore, return default
        }
    }
    return defaultValue;
}

From source file:org.debux.webmotion.server.handler.ExecutorParametersConvertorHandler.java

protected Object convert(ParameterTree parameterTree, Class<?> type, Type genericType) throws Exception {
    Object result = null;/*from w  w w  .  j av  a 2  s.c  o  m*/

    if (parameterTree == null) {
        return null;
    }

    if (genericType == null) {
        genericType = type.getGenericSuperclass();
    }

    Map<String, List<ParameterTree>> parameterArray = parameterTree.getArray();
    Map<String, ParameterTree> parameterObject = parameterTree.getObject();
    Object value = parameterTree.getValue();

    Converter lookup = converter.lookup(type);
    if (lookup != null) {

        // converter found, use it
        result = lookup.convert(type, value);
        return result;
    }

    // Manage enums
    if (type.isEnum()) {
        Object name = value == null ? null : ((Object[]) value)[0];
        if (name != null) {
            result = Enum.valueOf((Class<? extends Enum>) type, name.toString());
        }

        // Manage collection
    } else if (Collection.class.isAssignableFrom(type)) {

        Collection instance;
        if (type.isInterface()) {
            if (List.class.isAssignableFrom(type)) {
                instance = new ArrayList();

            } else if (Set.class.isAssignableFrom(type)) {
                instance = new HashSet();

            } else if (SortedSet.class.isAssignableFrom(type)) {
                instance = new TreeSet();

            } else {
                instance = new ArrayList();
            }
        } else {
            instance = (Collection) type.newInstance();
        }

        Class convertType = String.class;
        if (genericType != null && genericType instanceof ParameterizedType) {
            ParameterizedType parameterizedType = (ParameterizedType) genericType;
            convertType = (Class) parameterizedType.getActualTypeArguments()[0];
        }

        if (parameterObject != null) {
            for (Map.Entry<String, ParameterTree> entry : parameterObject.entrySet()) {
                ParameterTree object = entry.getValue();
                Object converted = convert(object, convertType, null);
                instance.add(converted);
            }
        } else {
            Object[] tab = (Object[]) value;
            for (Object object : tab) {
                Object converted = converter.convert(object, convertType);
                instance.add(converted);
            }
        }

        result = instance;

        // Manage map
    } else if (Map.class.isAssignableFrom(type)) {
        Map instance;
        if (type.isInterface()) {
            if (SortedMap.class.isAssignableFrom(type)) {
                instance = new TreeMap();

            } else {
                instance = new HashMap();
            }
        } else {
            instance = (Map) type.newInstance();
        }

        Class convertKeyType = String.class;
        Class convertValueType = String.class;
        if (genericType != null && genericType instanceof ParameterizedType) {
            ParameterizedType parameterizedType = (ParameterizedType) genericType;
            convertKeyType = (Class) parameterizedType.getActualTypeArguments()[0];
            convertValueType = (Class) parameterizedType.getActualTypeArguments()[1];
        }

        for (Map.Entry<String, ParameterTree> entry : parameterObject.entrySet()) {
            String mapKey = entry.getKey();
            ParameterTree mapValue = entry.getValue();

            Object convertedKey = converter.convert(mapKey, convertKeyType);
            Object convertedValue = convert(mapValue, convertValueType, null);

            instance.put(convertedKey, convertedValue);
        }

        result = instance;

        // Manage simple object
    } else if (type.isArray()) {
        Class<?> componentType = type.getComponentType();

        if (parameterObject != null) {
            Object[] tabConverted = (Object[]) Array.newInstance(componentType, parameterObject.size());
            result = tabConverted;

            int index = 0;
            for (Map.Entry<String, ParameterTree> entry : parameterObject.entrySet()) {
                ParameterTree object = entry.getValue();
                Object objectConverted = convert(object, componentType, null);
                tabConverted[index] = objectConverted;
                index++;
            }

        } else {
            Object[] tab = (Object[]) value;
            Object[] tabConverted = (Object[]) Array.newInstance(componentType, tab.length);
            result = tabConverted;

            for (int index = 0; index < tab.length; index++) {
                Object object = tab[index];
                Object objectConverted = converter.convert(object, componentType);
                tabConverted[index] = objectConverted;
            }
        }

    } else if (value instanceof UploadFile) {
        if (File.class.isAssignableFrom(type)) {
            UploadFile uploadFile = (UploadFile) value;
            result = uploadFile.getFile();
        } else {
            result = value;
        }

        // Manage simple object
    } else {
        Object instance = type.newInstance();
        boolean one = false;

        if (parameterObject != null) {
            for (Map.Entry<String, ParameterTree> attribut : parameterObject.entrySet()) {
                String attributeName = attribut.getKey();
                ParameterTree attributeValue = attribut.getValue();

                boolean writeable = propertyUtils.isWriteable(instance, attributeName);
                if (writeable) {
                    one = true;

                    Field field = FieldUtils.getField(type, attributeName, true);
                    Class<?> attributeType = field.getType();

                    genericType = field.getGenericType();
                    Object attributeConverted = convert(attributeValue, attributeType, genericType);
                    beanUtil.setProperty(instance, attributeName, attributeConverted);
                }
            }
        }

        if (parameterArray != null) {
            for (Map.Entry<String, List<ParameterTree>> entry : parameterArray.entrySet()) {
                String attributeName = entry.getKey();
                List<ParameterTree> attributeValues = entry.getValue();

                boolean writeable = propertyUtils.isWriteable(instance, attributeName);
                if (writeable) {
                    one = true;

                    Field field = FieldUtils.getField(type, attributeName, true);
                    Class<?> attributeType = field.getType();

                    genericType = field.getGenericType();
                    Object attributeConverted = convert(attributeValues, attributeType, genericType);
                    beanUtil.setProperty(instance, attributeName, attributeConverted);
                }
            }
        }

        if (one) {
            result = instance;

        } else {
            result = null;
        }
    }

    return result;
}

From source file:org.rhq.enterprise.gui.common.servlet.ParameterizedServlet.java

/**
 * Parse the passed parameter to find out its value. If the parameter is not found, the passed default value will be
 * used/*ww w. j  a  va  2s .  c o m*/
 *
 * @param  request       A HttpServletRequest
 * @param  parameterName The paramter we are looking for
 * @param  clazz         The class of the desired Enum
 * @param  defaultValue  A value of the Enum class clazz, which is taken as default
 *
 * @return either The matched value from the request or the default if it is not found or not valid
 *
 *         <p/>Usage example: <code>UnitsConstants x = parseEnumParameter(request, "unitsConstants",
 *         UnitsConstants.class, UnitsConstants.UNIT_BITS);</code>
 */
protected <E extends Enum<E>> E parseEnumParameter(HttpServletRequest request, final String parameterName,
        Class<E> clazz, E defaultValue) {
    String param = request.getParameter(parameterName);
    if (null == param) {
        return defaultValue;
    }

    E value;
    try {
        value = Enum.valueOf(clazz, param);
    } catch (IllegalArgumentException iae) {
        value = defaultValue;
    }

    return value;
}

From source file:org.apache.hadoop.hive.ql.metadata.GlobalSchema.java

public TableType getTableType() {
    return Enum.valueOf(TableType.class, tschema.getSchemaType());
}

From source file:com.amazon.kinesis.streaming.agent.config.Configuration.java

/**
 *
 * @param enumType/*from w w w.  jav  a2 s  . co m*/
 * @param key
 * @param fallback
 * @return the enum constant at given key, or <code>fallback</code> if the
 *         key does not exist in the configuration.
 * @throws ConfigurationException
 *             if the enum type is <code>null</code> or the specified enum type 
 *             has no constant with the specified value read from key
 */
public <E extends Enum<E>> E readEnum(Class<E> enumType, String key, E fallback) {
    String stringVal = readString(key, null);
    if (stringVal != null) {
        try {
            return Enum.valueOf(enumType, stringVal);
        } catch (Exception e) {
            throw new ConfigurationException(
                    String.format("Value(%s) is not legally accepted by key: %s. " + "Legal values are %s",
                            stringVal, key, Joiner.on(",").join(enumType.getEnumConstants())),
                    e);
        }
    } else
        return fallback;
}

From source file:com.evolveum.midpoint.repo.sql.query2.resolution.ItemPathResolver.java

/**
 * This method provides transformation from {@link String} value defined in
 * {@link com.evolveum.midpoint.repo.sql.query.definition.VirtualQueryParam#value()} to real object. Currently only
 * to simple types and enum values.//w w  w . jav  a  2  s  .  c o m
 */
private Object createQueryParamValue(VirtualQueryParam param) throws QueryException {
    Class type = param.type();
    String value = param.value();

    try {
        if (type.isPrimitive()) {
            return type.getMethod("valueOf", new Class[] { String.class }).invoke(null, new Object[] { value });
        }

        if (type.isEnum()) {
            return Enum.valueOf(type, value);
        }
    } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | RuntimeException ex) {
        throw new QueryException("Couldn't transform virtual query parameter '" + param.name()
                + "' from String to '" + type + "', reason: " + ex.getMessage(), ex);
    }

    throw new QueryException("Couldn't transform virtual query parameter '" + param.name()
            + "' from String to '" + type + "', it's not yet implemented.");
}

From source file:org.cloudifysource.dsl.internal.BaseDslScript.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private void applyPropertyToObject(final Object object, final String name, final Object value) {

    if (!isProperyExistsInBean(object, name)) {
        throw new IllegalArgumentException("Could not find property: " + name + " on Object: " + object);
    }//from w ww.ja  v a  2  s .  c om

    // Check for duplicate properties.
    if (this.usedProperties == null) {
        throw new IllegalArgumentException("used properties can not be null. Property: " + name + ", Value: "
                + value.toString() + ", Active object: " + this.activeObject);
    }
    if (this.usedProperties.contains(name)) {
        if (!isDuplicatePropertyAllowed(value)) {
            throw new IllegalArgumentException(
                    "Property duplication was found: Property " + name + " is define" + "d more than once.");
        }
    }

    this.usedProperties.add(name);
    Object convertedValue = null;
    try {
        convertedValue = convertValueToExecutableDSLEntryIfNeeded(getDSLFile().getParentFile(), object, name,
                value);
        if (logger.isLoggable(Level.FINEST)) {
            logger.finest("BeanUtils.setProperty(object=" + object + ",name=" + name + ",value="
                    + convertedValue + ",value.getClass()=" + convertedValue.getClass());
        }

        // Check if writable
        if (!PropertyUtils.isWriteable(object, name)) {
            throw new IllegalArgumentException("Field " + name + " in object of type: "
                    + object.getClass().getName() + " is not writable");
        }

        // If value is a map, merge with existing map
        final Object currentValue = PropertyUtils.getProperty(object, name);
        if (currentValue != null && currentValue instanceof Map<?, ?> && convertedValue != null
                && convertedValue instanceof Map<?, ?>) {

            final Map<Object, Object> currentMap = (Map<Object, Object>) currentValue;
            currentMap.putAll((Map<Object, Object>) convertedValue);

        } else if (PropertyUtils.getPropertyType(object, name).isEnum() && value instanceof String) {
            final Class enumClass = PropertyUtils.getPropertyType(object, name);
            final Enum enumValue = Enum.valueOf(enumClass, (String) value);
            BeanUtils.setProperty(object, name, enumValue);
        } else {
            // Then set it
            BeanUtils.setProperty(object, name, convertedValue);
        }
    } catch (final DSLValidationException e) {
        throw new DSLValidationRuntimeException(e);
    } catch (final Exception e) {
        throw new IllegalArgumentException("Failed to set property " + name + " of Object " + object
                + " to value: " + value + ". Error was: " + e.getMessage(), e);
    }

    checkForApplicationServiceBlockNameParameter(name, value);

}