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:org.noroomattheinn.utils.Utils.java

public static <T extends Enum<T>> T stringToEnum(Class<T> eClass, String val) {
    try {//from   w  ww. jav a  2  s  .c  o  m
        if (val == null || val.isEmpty() || val.equals("null")) {
            val = "Unknown";
        }
        return Enum.valueOf(eClass, val);
    } catch (Exception e) {
        logger.info("Problem converting String (" + val + ") to Enum: " + e);
        return Enum.valueOf(eClass, "Unknown");
    }
}

From source file:com.github.carlomicieli.rest.representations.RollingStockRepresentation.java

/**
 * Sets the model era.
 * @param era the model era.
 */
public void setEra(String era) {
    getInner().setEra(Enum.valueOf(Era.class, era));
}

From source file:com.meidusa.venus.frontend.http.VenusPoolFactory.java

@SuppressWarnings("unchecked")
public void afterPropertiesSet() throws Exception {
    logger.trace("current Venus Client id=" + PacketConstant.VENUS_CLIENT_ID);

    beanContext = new BeanContext() {
        public Object getBean(String beanName) {
            if (beanFactory != null) {
                return beanFactory.getBean(beanName);
            } else {
                return null;
            }//from  w ww .  j  a va 2  s. c  o m
        }

        public Object createBean(Class clazz) throws Exception {
            if (beanFactory instanceof AutowireCapableBeanFactory) {
                AutowireCapableBeanFactory factory = (AutowireCapableBeanFactory) beanFactory;
                return factory.autowire(clazz, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false);
            }
            return null;
        }
    };

    BeanContextBean.getInstance().setBeanContext(beanContext);
    VenusBeanUtilsBean.setInstance(new BeanUtilsBean(new ConvertUtilsBean(), new PropertyUtilsBean()) {

        public void setProperty(Object bean, String name, Object value)
                throws IllegalAccessException, InvocationTargetException {
            if (value instanceof String) {
                PropertyDescriptor descriptor = null;
                try {
                    descriptor = getPropertyUtils().getPropertyDescriptor(bean, name);
                    if (descriptor == null) {
                        return; // Skip this property setter
                    } else {
                        if (descriptor.getPropertyType().isEnum()) {
                            Class<Enum> clazz = (Class<Enum>) descriptor.getPropertyType();
                            value = Enum.valueOf(clazz, (String) value);
                        } else {
                            Object temp = null;
                            try {
                                temp = ConfigUtil.filter((String) value, beanContext);
                            } catch (Exception e) {
                            }
                            if (temp == null) {
                                temp = ConfigUtil.filter((String) value);
                            }
                            value = temp;
                        }
                    }
                } catch (NoSuchMethodException e) {
                    return; // Skip this property setter
                }
            }
            super.setProperty(bean, name, value);
        }

    });

    reloadConfiguration();

    __RELOAD: {
        if (enableReload) {
            File[] files = new File[this.configFiles.length];
            for (int i = 0; i < this.configFiles.length; i++) {
                try {
                    files[i] = ResourceUtils.getFile(configFiles[i].trim());
                } catch (FileNotFoundException e) {
                    logger.warn(e.getMessage());
                    enableReload = false;
                    logger.warn("venus serviceFactory configuration reload disabled!");
                    break __RELOAD;
                }
            }
            VenusFileWatchdog dog = new VenusFileWatchdog(files);
            dog.setDelay(1000 * 10);
            dog.start();
        }
    }
}

From source file:be.fedict.eid.dss.model.bean.ConfigurationBean.java

/**
 * {@inheritDoc}/*from  www . jav  a2s.co  m*/
 */
@SuppressWarnings({ "unchecked" })
public <T> T getValue(ConfigProperty configProperty, String index, Class<T> type) {

    if (!type.equals(configProperty.getType())) {
        throw new IllegalArgumentException("incorrect type: " + type.getName());
    }

    String propertyName = getPropertyName(configProperty, index);

    ConfigPropertyEntity configPropertyEntity = this.entityManager.find(ConfigPropertyEntity.class,
            propertyName);
    if (null == configPropertyEntity) {
        if (Boolean.class == configProperty.getType()) {
            return (T) Boolean.FALSE;
        } else {
            return null;
        }
    }
    String value = configPropertyEntity.getValue();
    if (null == value || value.trim().length() == 0) {
        if (Boolean.class == configProperty.getType()) {
            return (T) Boolean.FALSE;
        } else {
            return null;
        }
    }

    if (String.class == configProperty.getType()) {
        return (T) value;
    }
    if (Boolean.class == configProperty.getType()) {
        Boolean booleanValue = Boolean.parseBoolean(value);
        return (T) booleanValue;
    }
    if (Integer.class == configProperty.getType()) {
        Integer integerValue = Integer.parseInt(value);
        return (T) integerValue;
    }
    if (Long.class == configProperty.getType()) {
        Long longValue = Long.parseLong(value);
        return (T) longValue;
    }
    if (configProperty.getType().isEnum()) {
        Enum<?> e = (Enum<?>) configProperty.getType().getEnumConstants()[0];
        return (T) Enum.valueOf(e.getClass(), value);
    }
    throw new RuntimeException("unsupported type: " + configProperty.getType().getName());
}

From source file:com.thinkbiganalytics.metadata.modeshape.common.mixin.NodeEntityMixin.java

default <T> T getPropertyFromNode(Node node, String name, Class<T> type, boolean allowNotFound) {
    Object o = JcrPropertyUtil.getProperty(node, name, allowNotFound);
    if (allowNotFound && o == null) {
        return null;
    }/*from  w  w  w  .  j  a v a 2 s.c  o  m*/
    if (type.isEnum()) {
        String savedType = o.toString();
        if (StringUtils.isNotBlank(savedType)) {
            Class<? extends Enum> x = (Class<? extends Enum>) type;
            return (T) Enum.valueOf(x, savedType);
        }
    }
    if (!o.getClass().isAssignableFrom(type)) {
        //if it cant be matched and it is a Node > JcrObject, do the conversion
        if (o instanceof Node && JcrObject.class.isAssignableFrom(type)) {
            return JcrUtil.constructNodeObject((Node) o, type, null);
        } else {
            throw new MetadataRepositoryException("Unable to convert Property " + name + " to type " + type);
        }
    } else {
        return (T) o;
    }
}

From source file:nl.knaw.dans.common.lang.search.bean.AbstractSearchBeanFactory.java

@SuppressWarnings("unchecked")
public Object createSearchBean(String type, Document document)
        throws SearchBeanFactoryException, SearchBeanException {
    Class<?> sbClass = null;
    Object searchBean = null;/*from   w w w  .j  a v a2s  . co  m*/
    sbClass = getTypeMap().get(type);
    if (sbClass == null)
        throw new UnknownSearchBeanTypeException(type);

    Map<String, java.lang.reflect.Field> fieldsMap = null;
    try {
        fieldsMap = getFieldsMap(sbClass);
        searchBean = sbClass.newInstance();
    } catch (Exception e) {
        throw new SearchBeanException(e);
    }

    // check if the primary key is in the document
    Index index = SearchBeanUtil.getDefaultIndex(sbClass);
    if (index != null) {
        if (document.getFieldByName(index.getPrimaryKey()) == null)
            throw new PrimaryKeyMissingException("Primary key not found in document. " + document.toString());
    }

    // convert fields
    for (Map.Entry<String, java.lang.reflect.Field> searchField : fieldsMap.entrySet()) {
        Field docField = document.getFieldByName(searchField.getKey());
        java.lang.reflect.Field classField = searchField.getValue();
        if (docField != null) {
            String propName = classField.getName();
            String setMethodName = "set" + StringUtils.capitalize(propName);
            try {
                Method setMethod = sbClass.getMethod(setMethodName, new Class[] { classField.getType() });
                Class fieldType = classField.getType();
                Object value = docField.getValue();

                SearchField sbField = classField.getAnnotation(SearchField.class);
                Class<? extends SearchFieldConverter<?>> converterClass = sbField.converter();

                // convert to basic types
                boolean basicConversionFailed = false;
                if (!ClassUtil.instanceOf(value, fieldType)) {
                    // Don't change the type of value if we have a non-default converter
                    // instead, let the converter do it's work
                    //if (ClassUtil.classImplements(fieldType, Collection.class) )
                    if (ClassUtil.classImplements(fieldType, Collection.class)
                            && converterClass.equals(DefaultSearchFieldConverter.class)) {
                        ArrayList listValue = new ArrayList(1);
                        listValue.add(value);
                        value = listValue;
                    } else if (fieldType.equals(String.class)) {
                        value = value.toString();
                    } else if (fieldType.equals(DateTime.class) && value.getClass().equals(Date.class)) {
                        value = new DateTime((Date) value);
                    } else if (fieldType.equals(DateTime.class) && value.getClass().equals(String.class)) {
                        value = new DateTime(value.toString());
                    } else if (ClassUtil.instanceOf(fieldType, Enum.class)) {
                        value = Enum.valueOf(fieldType, value.toString());
                    } else if (fieldType.equals(int.class) && value.getClass().equals(Integer.class)) {
                        value = ((Integer) value).intValue();
                    } else
                        // if basic conversion fails, the converter might still
                        // save the day
                        basicConversionFailed = true;
                }

                if (!converterClass.equals(DefaultSearchFieldConverter.class)) {
                    SearchFieldConverter<?> converter = converterClass.newInstance();
                    value = converter.fromFieldValue(value);
                } else {
                    if (basicConversionFailed)
                        // converter did not save the day
                        throw new DocumentReturnedInvalidTypeException(
                                "expected " + fieldType.toString() + " but got " + value.getClass().toString());
                }

                setMethod.invoke(searchBean, value);
            } catch (Exception e) {
                throw new SearchBeanException(e);
            }
        } else {
            SearchField sbField = classField.getAnnotation(SearchField.class);
            if (sbField.required())
                throw new MissingRequiredFieldException(sbField.name());
        }
    }

    return searchBean;
}

From source file:com.happyblueduck.lembas.datastore.LembasEntity.java

public void readField(Field f, Object value) throws IllegalAccessException {
    if (f.getType().isEnum()) {

        Class z = f.getType();/*from  w w  w.java  2 s .c  o  m*/
        Object[] cons = z.getEnumConstants();
        int intValue = -1;
        if (value instanceof Long)
            intValue = ((Long) value).intValue();

        for (int i = 0; i < cons.length; i++) {
            if (i == intValue) {
                f.set(this, Enum.valueOf((Class<Enum>) f.getType(), cons[i].toString()));
            }
        }
    } else {
        f.set(this, value);
    }
}

From source file:edu.umn.msi.tropix.common.concurrent.impl.RepeaterSupplierImpl.java

@ManagedAttribute
public void setSleepTimeUnit(final String sleepTimeUnitString) {
    final TimeUnit sleepTimeUnit = Enum.valueOf(TimeUnit.class, sleepTimeUnitString);
    if (sleepTimeUnit != null) {
        this.setSleepTimeUnit(sleepTimeUnit);
    }//w  w  w .jav  a 2 s  .c om
}

From source file:com.github.carlomicieli.rest.representations.RollingStockRepresentation.java

/**
 * Sets the model power method.//www  .j a  v a  2s .com
 * @param powerMethod the model power method.
 */
public void setPowerMethod(String powerMethod) {
    getInner().setPowerMethod(Enum.valueOf(PowerMethod.class, powerMethod));
}

From source file:com.groupon.jenkins.dynamic.build.DbBackedBuild.java

public Object getState(final String state) {
    try {/*ww  w  . j a va  2 s  .c  o m*/
        return Enum.valueOf((Class<Enum>) Class.forName("hudson.model.Run$State"), state);
    } catch (final ClassNotFoundException e) {
        throw new RuntimeException(e);
    }
}