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.gradle.play.internal.javascript.GoogleClosureCompiler.java

List<String> compile(RelativeFile javascriptFile, JavaScriptCompileSpec spec,
        JavaScriptCompileDestinationCalculator destinationCalculator) {
    List<String> errors = Lists.newArrayList();

    loadCompilerClasses(getClass().getClassLoader());

    // Create a SourceFile object to represent an "empty" extern
    JavaMethod<?, Object> fromCodeJavaMethod = JavaReflectionUtil.staticMethod(sourceFileClass, Object.class,
            "fromCode", String.class, String.class);
    Object extern = fromCodeJavaMethod.invokeStatic("/dev/null", "");

    // Create a SourceFile object to represent the javascript file to compile
    JavaMethod<?, Object> fromFileJavaMethod = JavaReflectionUtil.staticMethod(sourceFileClass, Object.class,
            "fromFile", File.class);
    Object sourceFile = fromFileJavaMethod.invokeStatic(javascriptFile.getFile());

    // Construct a new CompilerOptions class
    Factory<?> compilerOptionsFactory = JavaReflectionUtil.factory(DirectInstantiator.INSTANCE,
            compilerOptionsClass);//from   www .j a  va2s . c  om
    Object compilerOptions = compilerOptionsFactory.create();

    // Get the CompilationLevel.SIMPLE_OPTIMIZATIONS class and set it on the CompilerOptions class
    @SuppressWarnings({ "rawtypes", "unchecked" })
    Enum simpleLevel = Enum.valueOf(compilationLevelClass, "SIMPLE_OPTIMIZATIONS");
    @SuppressWarnings("rawtypes")
    JavaMethod<Enum, Void> setOptionsForCompilationLevelMethod = JavaReflectionUtil
            .method(compilationLevelClass, Void.class, "setOptionsForCompilationLevel", compilerOptionsClass);
    setOptionsForCompilationLevelMethod.invoke(simpleLevel, compilerOptions);

    // Construct a new Compiler class
    Factory<?> compilerFactory = JavaReflectionUtil.factory(DirectInstantiator.INSTANCE, compilerClass,
            getDummyPrintStream());
    Object compiler = compilerFactory.create();

    // Compile the javascript file with the options we've created
    JavaMethod<Object, Object> compileMethod = JavaReflectionUtil.method(compilerClass, Object.class, "compile",
            sourceFileClass, sourceFileClass, compilerOptionsClass);
    Object result = compileMethod.invoke(compiler, extern, sourceFile, compilerOptions);

    // Get any errors from the compiler result
    PropertyAccessor<Object, Object[]> jsErrorsField = JavaReflectionUtil.readableField(result, Object[].class,
            "errors");
    Object[] jsErrors = jsErrorsField.getValue(result);

    if (jsErrors.length == 0) {
        // If no errors, get the compiled source and write it to the destination file
        JavaMethod<Object, String> toSourceMethod = JavaReflectionUtil.method(compilerClass, String.class,
                "toSource");
        String compiledSource = toSourceMethod.invoke(compiler);
        GFileUtils.writeFile(compiledSource, destinationCalculator.transform(javascriptFile));
    } else {
        for (Object error : jsErrors) {
            errors.add(error.toString());
        }
    }

    return errors;
}

From source file:org.apache.hadoop.mapreduce.counters.FrameworkCounterGroup.java

private T valueOf(String name) {
    return Enum.valueOf(enumClass, name);
}

From source file:com.zhumeng.dream.orm.PropertyFilter.java

/**
 * @param filterName ,???. eg.//ww w .  ja v  a2 s. c o m
 *            LIKES_NAME_OR_LOGIN_NAME
 * @param value .
 */
public PropertyFilter(final String filterName, final String value) {
    String propertyNameStr = StringUtils.substringAfter(filterName, "_");
    init(filterName, value, propertyNameStr);
    if (propertyClass == Enum.class) {
        for (Class<?> clazz : enumObjects) {
            if (propertyNameStr.equalsIgnoreCase(clazz.getSimpleName())) {
                Class<Enum> enumObjet = (Class<Enum>) clazz;

                // add by wucong
                String[] values = StringUtils.split(value, "_");
                if (!StringUtils.contains(value, "_"))
                    this.matchValue = Enum.valueOf(enumObjet, value);
                else
                    this.matchValue = Enum.valueOf(enumObjet, values[0]);// ?
                if (values != null) {
                    matchValues = new Object[values.length];
                    for (int i = 0; i < values.length; i++) {
                        matchValues[i] = Enum.valueOf(enumObjet, values[i]);
                    }
                    if (values.length == 0) {
                        matchValues = new Object[1];
                        matchValues[0] = this.matchValue;
                    }
                }
                break;
            }
        }
    } else {
        /*
         * if(!StringUtils.contains(value, "_")) this.matchValue =
         * ConvertUtils.convertStringToObject(value, propertyClass);
         */

        // add by wucong
        String[] values = null;
        //???"_"
        if (filterName.lastIndexOf("unionId") > 0 || filterName.lastIndexOf("openId") > 0
                || (!StringUtils.contains(value, "_")))//???"_"
            values = new String[] { value };

        else
            values = StringUtils.split(value, "_");
        if ((!StringUtils.contains(value, "_") || filterName.lastIndexOf("unionId") > 0)
                || (!StringUtils.contains(value, "_") && filterName.lastIndexOf("openId") > 0))//???"_"
            this.matchValue = ConvertUtils.convertStringToObject(value, propertyClass);
        else
            this.matchValue = ConvertUtils.convertStringToObject(values[0], propertyClass);// ?
        if (values != null) {
            matchValues = new Object[values.length];
            for (int i = 0; i < values.length; i++) {
                matchValues[i] = ConvertUtils.convertStringToObject(values[i], propertyClass);
            }
            if (values.length == 0) {
                matchValues = new Object[1];
                matchValues[0] = this.matchValue;
            }
        }
    }

}

From source file:org.mmadsen.sim.transmissionlab.population.StructuredPopulationFactory.java

public IAgentPopulation generatePopulation(IAgentSet population) {
    String populationStructureType = null;
    try {// ww w.  jav  a  2s. co m
        populationStructureType = (String) this.model.getSimpleModelPropertyByName(POP_STRUCTURE_PROPERTY);
    } catch (RepastException ex) {
        this.log.error("Parameter does not exist, defaulting to " + DEFAULT_POP_STRUCTURE.toString());

    }

    if (populationStructureType == null) {
        populationStructureType = DEFAULT_POP_STRUCTURE.toString();
    }

    PopulationStructureOptions option = Enum.valueOf(PopulationStructureOptions.class, populationStructureType);
    IAgentPopulation structuredPop = this.createPopulationObject(option);
    return structuredPop.createStructuredPopulation(population);
}

From source file:org.reficio.cougar.core.FrameBuilder.java

private void validateEnumValue(Class enumClass, String value) throws StompInvalidHeaderException {
    try {/*from   ww  w.j a  va2 s.c  o m*/
        Enum.valueOf(enumClass, value);
    } catch (IllegalArgumentException ex) {
        throw new StompInvalidHeaderException(
                String.format("Value [%s] invalid for enum type [%s]", value, enumClass));
    }
}

From source file:org.hx.rainbow.common.util.JavaBeanUtil.java

@SuppressWarnings({ "rawtypes", "unchecked" })
private static void changeObject(Map<String, Object> map, String key, Object value, Class clazz,
        String dataFormat) throws ParseException {
    if (value instanceof String) {
        String valueStr = (String) value;
        if (clazz.isEnum()) {
            map.put(key, Enum.valueOf(clazz, valueStr));
        } else if (clazz == Date.class) {
            SimpleDateFormat sdf = new SimpleDateFormat(DateUtil.DEFAULT_DATE_PATTERN);
            Date date = sdf.parse(valueStr);
            map.put(key, date);/*from   w w  w. j  av a2 s  .  co  m*/
        } else if (clazz == Integer.class) {
            map.put(key, Integer.valueOf(valueStr));
        } else if (clazz == BigDecimal.class) {
            map.put(key, new BigDecimal(valueStr));
        } else if (clazz == Boolean.class) {
            map.put(key, new Boolean(valueStr));
        } else if (clazz == Number.class) {
            map.put(key, new Integer(valueStr));
        } else if (clazz == int.class) {
            map.put(key, Integer.parseInt(valueStr));
        } else {
            map.put(key, valueStr);
        }
    } else if (value instanceof Integer) {
        Integer valueInt = (Integer) value;
        if (clazz == String.class) {
            map.put(key, valueInt.toString());
        } else if (clazz == Date.class) {
            map.put(key, new Date(valueInt));
        } else {
            map.put(key, valueInt);
        }
    } else if (value instanceof Boolean) {
        Boolean valueBoolean = (Boolean) value;
        if (clazz == String.class) {
            map.put(key, valueBoolean.toString());
        } else {
            map.put(key, valueBoolean);
        }
    } else if (value instanceof Date) {
        Date valueDate = (Date) value;
        if (clazz == String.class) {
            SimpleDateFormat sdf = new SimpleDateFormat(dataFormat);
            map.put(key, sdf.format(valueDate));
        } else {
            map.put(key, valueDate);
        }
    } else if (value instanceof BigDecimal) {
        BigDecimal valueBigDecimal = (BigDecimal) value;
        if (clazz == String.class) {
            map.put(key, valueBigDecimal.toPlainString());
        } else if (clazz == Integer.class) {
            map.put(key, valueBigDecimal.toBigInteger());
        } else {
            map.put(key, valueBigDecimal);
        }
    } else {
        map.put(key, value);
    }
}

From source file:fr.mby.portal.coreimpl.context.PropertiesAppConfigFactory.java

/**
 * @param bundleApp//from  ww w. j  av a2s  . c  om
 * @return
 * @throws AppConfigNotFoundException
 * @throws BadAppConfigException
 */
protected BasicAppConfig buildConfig(final Bundle bundleApp)
        throws AppConfigNotFoundException, BadAppConfigException {
    final BasicAppConfig appConfig = new BasicAppConfig();

    appConfig.setSymbolicName(bundleApp.getSymbolicName());
    appConfig.setVersion(bundleApp.getVersion().toString());

    // ---------- IApp Context ----------
    final BasicAppContext appContext = new BasicAppContext();
    appContext.setBundleId(bundleApp.getBundleId());
    appContext.setWebContextPath(this.buildWebAppBundlePath(bundleApp));
    appConfig.setContext(appContext);

    final String opaSn = bundleApp.getSymbolicName();
    final Properties opaConfig = this.loadOpaConfig(bundleApp);

    // ---------- Diplay configuration ----------
    appConfig.setDefaultTitle(this.getMandatoryValue(opaSn, opaConfig, OpaConfigKeys.DEFAULT_TITLE));
    appConfig.setDefaultWidth(this.getMandatoryValue(opaSn, opaConfig, OpaConfigKeys.DEFAULT_WIDTH));
    appConfig.setDefaultHeight(this.getMandatoryValue(opaSn, opaConfig, OpaConfigKeys.DEFAULT_HEIGHT));

    // ---------- Rendering configuration ----------
    try {
        final String renderingModeVal = this.getMandatoryValue(opaSn, opaConfig, OpaConfigKeys.RENDERING_MODE);
        appConfig.setRenderingMode(Enum.valueOf(RenderingMode.class, renderingModeVal));
    } catch (final IllegalArgumentException e) {
        throw new AppConfigNotFoundException(
                "Bad [" + OpaConfigKeys.RENDERING_MODE.getKey() + "] property value !");
    }

    // ---------- ACL configuration ----------

    // ----- Permissions -----
    final Map<String, IPermission> permissionsMap = this.processAclPermissions(bundleApp, appConfig, opaConfig);

    // ----- Roles -----
    this.processAclRoles(bundleApp, appConfig, opaConfig, permissionsMap);

    // ---------- Preferences configuration ----------
    this.processPreferences(appConfig, opaConfig);

    return appConfig;
}

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

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

From source file:org.lunarray.model.descriptor.converter.def.DelegatingEnumConverterTool.java

/** {@inheritDoc} */
@SuppressWarnings("unchecked")
// We're checking after the fact.
@Override/*  w  ww . j av a 2  s .  com*/
public <T> T convertToInstance(final Class<T> type, final String stringValue, final Locale locale,
        final String format) throws ConverterException {
    Validate.notNull(type, DelegatingEnumConverterTool.TYPE_NULL);
    T result = null;
    if (type.isEnum()) {
        DelegatingEnumConverterTool.LOGGER.debug(
                "Converting to instance type {} with locale {}, format {} and value: {}", type, locale, format,
                stringValue);
        @SuppressWarnings("rawtypes")
        // No other way?
        final Class<? extends Enum> enumType = (Class<? extends Enum>) type;
        if (!StringUtil.isEmptyString(stringValue)) {
            result = (T) Enum.valueOf(enumType, stringValue);
        }
    } else {
        result = this.converterTool.convertToInstance(type, stringValue, locale, format);
    }
    return result;
}

From source file:com.dell.asm.asmcore.asmmanager.snmp.utils.SNMPTrapFrameworkUtils.java

/**
 * Creates and starts the SNMP trap listener
 * //w w  w  .  j a v  a  2 s. co  m
 * @return ISNMPTrapListener
 * 
 * @throws SNMPTrapListenerException
 * 
 */
public static ISNMPTrapListener createAndStartListener() throws SNMPTrapListenerException {

    SNMPTrapListenerProtocolEnum protocol = null;
    ISNMPTrapListener listener = null;
    URL propFileURL = null;
    String host = null;
    String value = null;
    int port = 0;

    Set<ISNMPTrapHandler> handlers = new HashSet<ISNMPTrapHandler>();
    SNMPTrapListenerSpec spec = new SNMPTrapListenerSpec();

    try {

        // Load the properties file
        propFileURL = SNMPTrapFrameworkUtils.class.getClassLoader()
                .getResource(SNMPTrapListnerConstants.SNMP_PROPERTIES_FILE);

        // Read the properties file
        Properties props = getPropertiesFromFile(propFileURL);

        // Read Host
        MonitoringSettingModel monitoringSetting = MonitoringSettingMgr.getInstance().getMonitoringSettings();
        if (null == monitoringSetting) {
            String msg = "Host is null.";
            throw new SNMPTrapListenerException(msg);
        }
        List<TrapSettingModel> trapSettings = monitoringSetting.getTrapSettings().getTrapSetting();
        for (TrapSettingModel trapSetting : trapSettings) {
            if (trapSetting.isDefaultIp()) {
                host = trapSetting.getDestinationIPAddress();
                break;
            }
        }

        if (StringUtils.isBlank(host)) {
            String msg = "Host is null.";
            throw new SNMPTrapListenerException(msg);
        }
        // Read Port
        value = props.getProperty(SNMPTrapListnerConstants.PROP_PORT);
        if (StringUtils.isBlank(value)) {
            String msg = "Port is null.";
            throw new SNMPTrapListenerException(msg);
        }
        try {
            port = Integer.parseInt(value);
        } catch (NumberFormatException e) {
            throw new SNMPTrapListenerException("Port (" + value + ") is not valid.");
        }

        // Read Protocol
        value = props.getProperty(SNMPTrapListnerConstants.PROP_PROTOCOL);
        if (StringUtils.isBlank(value)) {
            throw new SNMPTrapListenerException("Protocol is null.");
        }
        try {
            protocol = Enum.valueOf(SNMPTrapListenerProtocolEnum.class, value);
        } catch (IllegalArgumentException e) {
            throw new SNMPTrapListenerException("Protocol (" + value + ") is not valid.");
        }

        // Add the listener specifications
        spec.setListenerHost(host);
        spec.setListenerPort(port);
        spec.setProtocol(protocol);

        // Read snmp supported versions
        if (StringUtils.isBlank(props.getProperty(SNMPTrapListnerConstants.PROP_SNMP_V1))
                & StringUtils.isBlank(props.getProperty(SNMPTrapListnerConstants.PROP_SNMP_V1))
                & StringUtils.isBlank(props.getProperty(SNMPTrapListnerConstants.PROP_SNMP_V1))) {
            throw new SNMPTrapListenerException("SNMP version is null.");
        }

        // Add the supported versions to the listener specifications
        if (Boolean.valueOf(props.getProperty(SNMPTrapListnerConstants.PROP_SNMP_V1))) {
            spec.getSupportedSNMPVersions().add(SNMPVersionEnum.VERSION1);
        }
        if (Boolean.valueOf(props.getProperty(SNMPTrapListnerConstants.PROP_SNMP_V2))) {
            spec.getSupportedSNMPVersions().add(SNMPVersionEnum.VERSION2);
        }
        if (Boolean.valueOf(props.getProperty(SNMPTrapListnerConstants.PROP_SNMP_V3))) {
            spec.getSupportedSNMPVersions().add(SNMPVersionEnum.VERSION3);
        }

        listener = SNMPTrapListenerFactory.createTrapListener(spec, handlers);

        logger.info("SNMP trap listener started successfully at Host " + host + " , on Port " + port
                + " ,using " + protocol + " Protocol.");

    } catch (SecurityException e) {
        throw new SNMPTrapListenerException("Unable to start the SNMP trap listener. " + e.getMessage());
    } catch (SNMPTrapListenerException e) {
        throw new SNMPTrapListenerException("Unable to start the SNMP trap listener. " + e.getMessage());
    } catch (AsmCheckedException e) {
        throw new SNMPTrapListenerException("Unable to start the SNMP trap listener. " + e.getMessage());
    } catch (IOException e) {
        throw new SNMPTrapListenerException("Unable to start the SNMP trap listener. " + e.getMessage());
    }
    return listener;
}