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.britesnow.snow.util.ObjectUtil.java

public static final <T> T getValue(String valueStr, Class<T> cls, T defaultValue) {
    if (valueStr == null) {
        return defaultValue;
    } else {/*from   w w w .j  a  va2  s. co m*/
        try {
            if (cls == String.class) {
                return (T) valueStr;
            } else if (valueStr.length() > 0) {

                if (cls.isArray()) {
                    return getValue(new String[] { valueStr }, cls, defaultValue);
                } else if (cls == Integer.class) {
                    Integer value = numberFormat.parse(valueStr).intValue();
                    return (T) value;
                } else if (cls == Long.class) {
                    Long value = numberFormat.parse(valueStr).longValue();
                    return (T) value;
                } else if (cls == Float.class) {
                    Float value = numberFormat.parse(valueStr).floatValue();
                    return (T) value;
                } else if (cls == Double.class) {
                    Double value = numberFormat.parse(valueStr).doubleValue();
                    return (T) value;
                } else if (cls == Boolean.class) {
                    if ("true".equals(valueStr)) {
                        return (T) new Boolean(true);
                    } else {
                        return (T) new Boolean(false);
                    }
                } else if (cls.isEnum()) {
                    try {
                        return (T) Enum.valueOf((Class<Enum>) cls, valueStr);
                    } catch (IllegalArgumentException e) {
                        return defaultValue;
                    }
                } else if (cls == Date.class) {
                    SimpleDateFormat sdf = new SimpleDateFormat(DEFAULT_DATE_PATTERN);
                    return (T) new java.util.Date(sdf.parse(valueStr).getTime());
                }
            } else {
                return defaultValue;
            }
        } catch (Exception e) {
            return defaultValue;
        }
    }
    return defaultValue;
}

From source file:org.romaframework.core.schema.SchemaClassElement.java

@SuppressWarnings({ "rawtypes", "unchecked" })
protected Object convertValue(Object iFieldValue, SchemaClassDefinition expectedType) {
    if (expectedType == null || expectedType.getSchemaClass().isArray())
        return iFieldValue;

    SchemaClass typeClass = expectedType.getSchemaClass();
    if (typeClass.equals(Roma.schema().getSchemaClass(iFieldValue)))
        return iFieldValue;

    String textValue = null;//from   w  w  w  .j  av  a  2  s.c  o m
    if (iFieldValue instanceof String) {
        textValue = (String) iFieldValue;
    } else if (iFieldValue != null) {
        textValue = iFieldValue.toString();
    }

    Object value = null;

    if (textValue != null) {
        // TRY A SOFT CONVERSION
        if (typeClass.isOfType(Integer.class) || typeClass.isOfType(Integer.TYPE)) {
            try {
                value = textValue.equals("") ? null : Integer.parseInt(textValue);
            } catch (Exception e) {
                value = textValue.equals("") ? null : Double.valueOf(textValue).intValue();
            }
        } else if (typeClass.isOfType(Long.class) || typeClass.isOfType(Long.TYPE)) {
            value = textValue.equals("") ? null : Long.parseLong(textValue);
        } else if (typeClass.isOfType(Short.class) || typeClass.isOfType(Short.TYPE)) {
            value = textValue.equals("") ? null : Short.parseShort(textValue);
        } else if (typeClass.isOfType(Byte.class) || typeClass.isOfType(Byte.TYPE)) {
            value = textValue.equals("") ? null : Byte.parseByte(textValue);
        } else if (typeClass.isOfType(Character.class) || typeClass.isOfType(Character.TYPE)) {
            if (textValue.length() > 0) {
                value = new Character(textValue.charAt(0));
            }
        } else if (typeClass.isOfType(Float.class) || typeClass.isOfType(Float.TYPE)) {
            value = textValue.equals("") ? null : Float.parseFloat(textValue);
        } else if (typeClass.isOfType(Double.class) || typeClass.isOfType(Double.TYPE)) {
            value = textValue.equals("") ? null : Double.parseDouble(textValue);
        } else if (typeClass.isOfType(BigDecimal.class)) {
            value = textValue.equals("") ? null : new BigDecimal(textValue);
        } else if (iFieldValue != null && !typeClass.isArray() && iFieldValue.getClass().isArray()) {
            // DESTINATION VALUE IS NOT AN ARRAY: ASSIGN THE FIRST ONE ELEMENT
            value = ((Object[]) iFieldValue)[0];
        } else if (typeClass.isEnum()) {
            value = Enum.valueOf((Class) typeClass.getLanguageType(), textValue.toUpperCase());
        } else {
            value = iFieldValue;
        }
    }

    if (value != null) {
        // TODO is this the right place to do this...?
        Class<?> valueClass = value.getClass();
        // SUCH A MONSTER!!! MOVE THIS LOGIC IN SchemaClass.isAssignableFrom...
        if (value instanceof VirtualObject
                && !(typeClass.getLanguageType() instanceof Class<?>
                        && ((Class<?>) typeClass.getLanguageType()).isAssignableFrom(VirtualObject.class))
                && ((VirtualObject) value).getSuperClassObject() != null) {
            if (ComposedEntity.class
                    .isAssignableFrom(((VirtualObject) value).getSuperClassObject().getClass())) {
                value = ((VirtualObject) value).getSuperClassObject();
                valueClass = value.getClass();
            }
        }

        if (value instanceof ComposedEntity<?> && !typeClass.isAssignableFrom(valueClass)) {
            value = ((ComposedEntity<?>) value).getEntity();
        }
    }

    if (value == null && typeClass.isPrimitive()) {
        log.warn("Cannot set the field value to null for primitive types! Field: " + getEntity() + "." + name
                + " of class " + expectedType.getName() + ". Setting value to 0.");
        // SET THE VALUE TO 0
        value = SchemaHelper.assignDefaultValueToLiteral(typeClass);
    }
    return value;
}

From source file:alma.acs.nc.sm.generic.AcsScxmlDispatchingAction.java

/**
 * Retrieves the user-supplied action dispatcher from the sm root context and
 * caches it in {@link #disp}. //ww  w.j a va2s .  com
 * @param scInstance
 */
private void getActionDispatcher(SCInstance scInstance) {
    if (disp == null) {
        synchronized (this) {
            if (disp == null) {
                disp = (AcsScxmlActionDispatcher<E>) scInstance.getRootContext()
                        .get(AcsScxmlActionDispatcher.class.getName());
                // cache the action enum
                action = Enum.valueOf(disp.getActionType(), this.actionName);
            }
        }
    }
}

From source file:be.fedict.eid.pkira.portal.util.TypeMapper.java

public CertificateTypeWS map(CertificateType certificateType) {
    if (certificateType == null)
        return null;
    return Enum.valueOf(CertificateTypeWS.class, certificateType.name());
}

From source file:org.sd.cluster.config.Admin.java

/**
 * Universal auxiliary for sending a job command message to a running cluster.
 * <p>//from  w  w w. j  a  v  a  2 s . co  m
 * Properties:
 * <ul>
 * <li>jobCommand: (required) JobCommand enumeration name</li>
 * <li>jobId: (required) id.nodeName-jvmNum or jobDescription.groupName identifying localJobId of command recipients.</li>
 * <li>payload: (optional) className[:buildMethod] for job command message payload to send. Must have a 'properties' arg or no-arg constructor. Properties will be passed in.</li>
 * <li>timeout: (optional, default=5000) millis to wait for a resposne from nodes.</li>
 * <li>requireAll: (optional, default=false) flag for throwing an exception if not all responses are received.</li>
 * </ul>
 */
public static final void sendJobCommand(Properties properties) {
    // jobCommand
    // jobId (id.nodeName-jvmNum or jobDescription.groupName)
    // payload (optional)
    // timeout
    // requireAll

    final String jobCommandName = properties.getProperty("jobCommand");
    if (jobCommandName == null) {
        throw new IllegalArgumentException("Must define a 'jobCommand' (enum name) to send!");
    }
    final JobCommand jobCommand = Enum.valueOf(JobCommand.class, jobCommandName.toUpperCase());

    final String jobIdString = properties.getProperty("jobId");
    if (jobIdString == null) {
        throw new IllegalArgumentException(
                "Must define a 'jobId' (id.nodeName-jvmNum or jobDescription.groupName) to send to!");
    }
    final LocalJobId jobId = new LocalJobId(jobIdString);

    final String payloadString = properties.getProperty("payload");
    final Publishable payload = (payloadString == null) ? null
            : (Publishable) ReflectUtil.buildInstance(payloadString, properties);

    final JobCommandMessage message = new JobCommandMessage(jobCommand, jobId, payload);

    doSendMessage(message, jobId.getNodeName(), properties);
}

From source file:jef.tools.Assert.java

/**
 * /*w w w .  j a  va2s  .c  om*/
 * @param string
 * @param name
 * @param msg
 */
public static <T extends Enum<T>> void isEnumOf(Object string, Class<T> name, String msg) {
    try {
        Enum.valueOf(name, string.toString());
    } catch (IllegalArgumentException e) {
        throw new IllegalArgumentException(msg);
    }
}

From source file:com.hortonworks.streamline.streams.security.catalog.AclEntry.java

@Override
public Storable fromMap(Map<String, Object> map) {
    ObjectMapper mapper = new ObjectMapper();
    setId((Long) map.get(ID));// w ww.  j  a va  2s .com
    setObjectId((Long) map.get(OBJECT_ID));
    setObjectNamespace((String) map.get(OBJECT_NAMESPACE));
    setSidId((Long) map.get(SID_ID));
    setSidType(Enum.valueOf(SidType.class, (String) map.get(SID_TYPE)));
    String permissionsStr = (String) map.get(PERMISSIONS);
    if (!StringUtils.isEmpty(permissionsStr)) {
        EnumSet<Permission> permissions;
        try {
            permissions = mapper.readValue(permissionsStr, new TypeReference<EnumSet<Permission>>() {
            });
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
        setPermissions(permissions);
    }
    setOwner((Boolean) map.get(OWNER));
    setGrant((Boolean) map.get(GRANT));
    setTimestamp((Long) map.get(TIMESTAMP));
    return this;
}

From source file:be.fedict.eid.pkira.portal.util.TypeMapper.java

public <T extends Enum<T>> T getEnum(Class<T> enumClass, String name) {
    if (StringUtils.isBlank(name))
        return null;
    return Enum.valueOf(enumClass, name);
}

From source file:com.adobe.acs.commons.mcp.util.AnnotatedFieldDeserializer.java

private static Object convertValue(String value, Class<?> type) throws ParseException {
    Class clazz = type.isArray() ? type.getComponentType() : type;
    if (clazz.isPrimitive() || Number.class.isAssignableFrom(clazz) || clazz == Boolean.class) {
        return convertPrimitiveValue(value, clazz);
    } else if (clazz == String.class) {
        return value;
    } else if (clazz.isEnum()) {
        return Enum.valueOf((Class<Enum>) clazz, value);
    }//from www  . j  ava 2s. c o  m

    return null;
}

From source file:org.jolokia.converter.object.StringToObjectConverter.java

private Object prepareValue(Class expectedClass, Object pValue) {
    if (pValue == null) {
        return null;
    }//from ww w  .  j  a  v a 2 s .  co  m
    if (Enum.class.isAssignableFrom(expectedClass)) {
        return Enum.valueOf(expectedClass, pValue.toString());
    } else {
        return prepareForDirectUsage(expectedClass, pValue);
    }
}