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.apache.openjpa.persistence.jdbc.XMLPersistenceMappingParser.java

/**
 * Parse inheritance./*from w w w . j a va2 s.  c  om*/
 */
private boolean startInheritance(Attributes attrs) {
    String val = attrs.getValue("strategy");
    if (val == null)
        return true;

    ClassMapping cm = (ClassMapping) currentElement();
    ClassMappingInfo info = cm.getMappingInfo();
    switch (Enum.valueOf(InheritanceType.class, val)) {
    case SINGLE_TABLE:
        info.setHierarchyStrategy(FlatClassStrategy.ALIAS);
        break;
    case JOINED:
        info.setHierarchyStrategy(VerticalClassStrategy.ALIAS);
        break;
    case TABLE_PER_CLASS:
        info.setHierarchyStrategy(FullClassStrategy.ALIAS);
        break;
    }
    return true;
}

From source file:org.anarres.cpp.Main.java

public static Result preprocess(String[] args, String source) throws Exception {

    OptionParser parser = new OptionParser();
    OptionSpec<?> helpOption = parser.accepts("help", "Displays command-line help.").forHelp();
    OptionSpec<?> debugOption = parser.acceptsAll(Arrays.asList("debug"), "Enables debug output.");

    OptionSpec<String> defineOption = parser
            .acceptsAll(Arrays.asList("define", "D"), "Defines the given macro.").withRequiredArg()
            .ofType(String.class).describedAs("name[=definition]");
    OptionSpec<String> undefineOption = parser
            .acceptsAll(Arrays.asList("undefine", "U"),
                    "Undefines the given macro, previously either builtin or defined using -D.")
            .withRequiredArg().describedAs("name");
    OptionSpec<File> includeOption = parser
            .accepts("include",
                    "Process file as if \"#"
                            + "include \"file\"\" appeared as the first line of the primary source file.")
            .withRequiredArg().ofType(File.class).describedAs("file");
    OptionSpec<File> incdirOption = parser
            .acceptsAll(Arrays.asList("incdir", "I"),
                    "Adds the directory dir to the list of directories to be searched for header files.")
            .withRequiredArg().ofType(File.class).describedAs("dir");
    OptionSpec<File> iquoteOption = parser.acceptsAll(Arrays.asList("iquote"),
            "Adds the directory dir to the list of directories to be searched for header files included using \"\".")
            .withRequiredArg().ofType(File.class).describedAs("dir");
    OptionSpec<String> warningOption = parser
            .acceptsAll(Arrays.asList("warning", "W"),
                    "Enables the named warning class (" + getWarnings() + ").")
            .withRequiredArg().ofType(String.class).describedAs("warning");
    OptionSpec<Void> noWarningOption = parser.acceptsAll(Arrays.asList("no-warnings", "w"),
            "Disables ALL warnings.");
    OptionSpec<File> inputsOption = parser.nonOptions().ofType(File.class).describedAs("Files to process.");

    OptionSet options = parser.parse(args);

    if (options.has(helpOption)) {
        parser.printHelpOn(System.out);
        return null;
    }//ww  w. j  a  v  a2 s . co m

    Preprocessor pp = new Preprocessor();
    pp.addFeature(Feature.DIGRAPHS);
    pp.addFeature(Feature.TRIGRAPHS);
    pp.addFeature(Feature.PRAGMA_ONCE);
    //pp.addFeature(Feature.LINEMARKERS);
    pp.addWarning(Warning.IMPORT);
    pp.setListener(new DefaultPreprocessorListener());
    pp.addMacro("__JCPP__");
    pp.getSystemIncludePath().add("/usr/local/include");
    pp.getSystemIncludePath().add("/usr/include");
    pp.getFrameworksPath().add("/System/Library/Frameworks");
    pp.getFrameworksPath().add("/Library/Frameworks");
    pp.getFrameworksPath().add("/Local/Library/Frameworks");

    if (options.has(debugOption))
        pp.addFeature(Feature.DEBUG);

    if (options.has(noWarningOption))
        pp.getWarnings().clear();

    for (String warning : options.valuesOf(warningOption)) {
        warning = warning.toUpperCase();
        warning = warning.replace('-', '_');
        if (warning.equals("ALL"))
            pp.addWarnings(EnumSet.allOf(Warning.class));
        else
            pp.addWarning(Enum.valueOf(Warning.class, warning));
    }

    for (String arg : options.valuesOf(defineOption)) {
        int idx = arg.indexOf('=');
        if (idx == -1)
            pp.addMacro(arg);
        else
            pp.addMacro(arg.substring(0, idx), arg.substring(idx + 1));
    }
    for (String arg : options.valuesOf(undefineOption)) {
        pp.getMacros().remove(arg);
    }

    for (File dir : options.valuesOf(incdirOption))
        pp.getSystemIncludePath().add(dir.getAbsolutePath());
    for (File dir : options.valuesOf(iquoteOption))
        pp.getQuoteIncludePath().add(dir.getAbsolutePath());
    for (File file : options.valuesOf(includeOption))
        // Comply exactly with spec.
        pp.addInput(new StringLexerSource("#" + "include \"" + file + "\"\n"));

    List<File> inputs = options.valuesOf(inputsOption);
    if (inputs.isEmpty()) {
        pp.addInput(new StringLexerSource(source, true));
        //pp.addInput(new InputLexerSource(System.in));
    } else {
        for (File input : inputs)
            pp.addInput(new FileLexerSource(input));
    }

    if (pp.getFeature(Feature.DEBUG)) {
        LOG.info("#" + "include \"...\" search starts here:");
        for (String dir : pp.getQuoteIncludePath())
            LOG.info("  " + dir);
        LOG.info("#" + "include <...> search starts here:");
        for (String dir : pp.getSystemIncludePath())
            LOG.info("  " + dir);
        LOG.info("End of search list.");
    }

    try {
        Result result = new Result();
        result.preprocessor = pp;
        pp.collector = new ActionCollectorImpl(pp, pp.inputs);
        for (;;) {
            TokenS tok = pp.token();
            if (tok == null)
                break;
            if (tok.token.getType() == Token.EOF)
                break;
            result.produced.add(tok);
        }
        result.original = ((ActionCollectorImpl) pp.collector).original;
        result.actions = ((ActionCollectorImpl) pp.collector).actions;
        pp.collector = new ActionCollector();
        return result;
    } catch (Exception e) {
        StringBuilder buf = new StringBuilder("Preprocessor failed:\n");
        Source s = pp.getSource();
        while (s != null) {
            buf.append(" -> ").append(s).append("\n");
            s = s.getParent();
        }
        LOG.error(buf.toString(), e);
    }
    return null;
}

From source file:org.apache.sqoop.model.ConfigUtils.java

/**
 * Parse given input JSON string and move it's values to given configuration
 * object.//from  w  w  w .j a v  a  2s .  c o m
 *
 * @param json JSON representation of the configuration object
 * @param configuration ConfigurationGroup object to be filled
 */
@SuppressWarnings("unchecked")
public static void fillValues(String json, Object configuration) {
    Class<?> klass = configuration.getClass();

    Set<String> configNames = new HashSet<String>();
    JSONObject jsonConfigs = (JSONObject) JSONValue.parse(json);

    for (Field configField : klass.getDeclaredFields()) {
        configField.setAccessible(true);
        String configName = configField.getName();

        // We're processing only config validations
        Config configAnnotation = configField.getAnnotation(Config.class);
        if (configAnnotation == null) {
            continue;
        }
        configName = getConfigName(configField, configAnnotation, configNames);

        try {
            configField.set(configuration, configField.getType().newInstance());
        } catch (Exception e) {
            throw new SqoopException(ModelError.MODEL_005, "Issue with field " + configName, e);
        }

        JSONObject jsonInputs = (JSONObject) jsonConfigs.get(configField.getName());
        if (jsonInputs == null) {
            continue;
        }

        Object configValue;
        try {
            configValue = configField.get(configuration);
        } catch (IllegalAccessException e) {
            throw new SqoopException(ModelError.MODEL_005, "Issue with field " + configName, e);
        }

        for (Field inputField : configField.getType().getDeclaredFields()) {
            inputField.setAccessible(true);
            String inputName = inputField.getName();

            Input inputAnnotation = inputField.getAnnotation(Input.class);

            if (inputAnnotation == null || jsonInputs.get(inputName) == null) {
                try {
                    inputField.set(configValue, null);
                } catch (IllegalAccessException e) {
                    throw new SqoopException(ModelError.MODEL_005,
                            "Issue with field " + configName + "." + inputName, e);
                }
                continue;
            }

            Class<?> type = inputField.getType();

            try {
                if (type == String.class) {
                    inputField.set(configValue, jsonInputs.get(inputName));
                } else if (type.isAssignableFrom(Map.class)) {
                    Map<String, String> map = new HashMap<String, String>();
                    JSONObject jsonObject = (JSONObject) jsonInputs.get(inputName);
                    for (Object key : jsonObject.keySet()) {
                        map.put((String) key, (String) jsonObject.get(key));
                    }
                    inputField.set(configValue, map);
                } else if (type == Integer.class) {
                    inputField.set(configValue, ((Long) jsonInputs.get(inputName)).intValue());
                } else if (type.isEnum()) {
                    inputField.set(configValue, Enum.valueOf((Class<? extends Enum>) inputField.getType(),
                            (String) jsonInputs.get(inputName)));
                } else if (type == Boolean.class) {
                    inputField.set(configValue, (Boolean) jsonInputs.get(inputName));
                } else {
                    throw new SqoopException(ModelError.MODEL_004, "Unsupported type " + type.getName()
                            + " for input " + configName + "." + inputName);
                }
            } catch (IllegalAccessException e) {
                throw new SqoopException(ModelError.MODEL_005,
                        "Issue with field " + configName + "." + inputName, e);
            }
        }
    }
}

From source file:nl.knaw.dans.common.ldap.repo.LdapMapper.java

@SuppressWarnings("unchecked")
private Object getSingleValue(Class<?> type, Object o) throws NamingException {
    Object value = null;//  w  w  w .ja  v  a  2 s.  c  om
    if (o != null) {
        if (type.isPrimitive()) {
            value = getPrimitive(type, (String) o);
        } else if (type.isEnum()) {
            value = Enum.valueOf(type.asSubclass(Enum.class), (String) o);
        } else {
            value = o;
        }
    }
    return value;
}

From source file:org.rhq.plugins.jbossas.JBossASServerComponent.java

public OperationResult invokeOperation(String name, Configuration configuration) throws InterruptedException {
    JBossASServerSupportedOperations operation = Enum.valueOf(JBossASServerSupportedOperations.class,
            name.toUpperCase());//  w w  w. j  a v  a2  s . c om
    return operationsDelegate.invoke(operation, configuration);
}

From source file:org.apache.openjpa.persistence.jdbc.XMLPersistenceMappingParser.java

/**
 * Parse temporal.//from ww w.ja  v  a2  s  .co m
 */
private void endTemporal() {
    String temp = currentText();
    if (!StringUtils.isEmpty(temp))
        _temporal = Enum.valueOf(TemporalType.class, temp);
}

From source file:org.jboss.on.plugins.tomcat.TomcatServerComponent.java

public OperationResult invokeOperation(String name, Configuration parameters)
        throws InterruptedException, Exception {
    SupportedOperations operation = Enum.valueOf(SupportedOperations.class, name.toUpperCase());

    addScriptsEnvironment(parameters);/*w  w  w .j a  v a2  s .  c o m*/

    return operationsDelegate.invoke(operation, parameters);
}

From source file:com.ebay.pulsar.analytics.service.GroupService.java

public boolean isValidRight(String rightName, int rightType) {
    if (rightType == PermissionConst.RIGHT_TYPE_SYS) {
        try {//from w  w  w  .j  av a2 s. co m
            SysPermission permission = Enum.valueOf(SysPermission.class, rightName);
            return permission != null;
        } catch (Exception e) {
        }
    } else {
        String dname = null;
        if (rightName.endsWith("_MANAGE")) {
            dname = rightName.substring(0, rightName.lastIndexOf("_MANAGE"));
        } else if (rightName.endsWith("_VIEW")) {
            dname = rightName.substring(0, rightName.lastIndexOf("_VIEW"));
        } else {
            return false;
        }
        if (rightType == PermissionConst.RIGHT_TYPE_DATA) {
            if (this.isStaticDataSource(dname))
                return true;
            DBDataSource condition = new DBDataSource();
            condition.setName(dname);
            List<DBDataSource> list = dataSourceService.get(condition);
            return list != null && list.size() > 0;
        } else if (rightType == PermissionConst.RIGHT_TYPE_DASHBOARD) {
            DBDashboard condition = new DBDashboard();
            condition.setName(dname);
            List<DBDashboard> list = dashboardService.get(condition);
            return list != null && list.size() > 0;
        } else if (rightType == PermissionConst.RIGHT_TYPE_GROUP) {
            DBGroup condition = new DBGroup();
            condition.setName(dname);
            List<DBGroup> list = groupService.get(condition);
            return list != null && list.size() > 0;
        }
    }
    return false;
}

From source file:org.apache.openjpa.persistence.jdbc.XMLPersistenceMappingParser.java

/**
 * Parse temporal.//from w w w  .j  a  va  2 s  .  c om
 */
private void endMapKeyTemporal() {
    String temp = currentText();
    TemporalType _mapKeyTemporal = null;
    if (!StringUtils.isEmpty(temp))
        _mapKeyTemporal = Enum.valueOf(TemporalType.class, temp);
    FieldMapping fm = (FieldMapping) currentElement();
    List<Column> cols = fm.getKeyMapping().getValueInfo().getColumns();
    if (cols.isEmpty()) {
        cols = Arrays.asList(new Column[] { new Column() });
        fm.getKeyMapping().getValueInfo().setColumns(cols);
    }

    Column col = (Column) cols.get(0);
    switch (_mapKeyTemporal) {
    case DATE:
        col.setType(Types.DATE);
        break;
    case TIME:
        col.setType(Types.TIME);
        break;
    case TIMESTAMP:
        col.setType(Types.TIMESTAMP);
        break;
    }
}

From source file:io.stallion.reflection.PropertyUtils.java

/**
 * Try to transform the passed in value into the destinationClass, via a applying a boatload of
 * heuristics./*from   ww w.  j  a v a 2s. c  o m*/
 *
 * @param value
 * @param destinationClass
 * @return
 */
public static Object transform(Object value, Class destinationClass) {
    if (value == null) {
        return null;
    }
    if (value.getClass() == destinationClass)
        return value;
    if (destinationClass.isInstance(value)) {
        return value;
    }

    // If target type is Date and json was a long, convert the long to a date
    if (destinationClass == Date.class && (value.getClass() == long.class || value.getClass() == Long.class)) {
        return new Date((long) value);
    }
    // Convert integers to longs, if target type is long
    if ((destinationClass == Long.class || destinationClass == long.class)
            && (value.getClass() == int.class || value.getClass() == Integer.class)) {
        return new Long((int) value);
    }
    // Convert ints and longs to ZonedDateTime, if ZonedDateTime was a long
    if (destinationClass == ZonedDateTime.class
            && (value.getClass() == long.class || value.getClass() == Long.class
                    || value.getClass() == int.class || value.getClass() == Integer.class)) {
        if (value.getClass() == Integer.class || value.getClass() == int.class) {
            return ZonedDateTime.ofInstant(Instant.ofEpochMilli(((int) value) * 1000), GeneralUtils.UTC);
        } else {
            return ZonedDateTime.ofInstant(Instant.ofEpochMilli((long) value), GeneralUtils.UTC);
        }
    }

    if (destinationClass == ZonedDateTime.class && value instanceof Timestamp) {
        return ZonedDateTime.ofInstant(((Timestamp) value).toInstant(), UTC);
    }
    if (destinationClass == Long.class && value instanceof BigInteger) {
        return ((BigInteger) value).longValue();
    }

    if (destinationClass == ZonedDateTime.class
            && (value.getClass() == double.class || value.getClass() == Double.class)) {
        return ZonedDateTime.ofInstant(Instant.ofEpochMilli(Math.round((Double) value)), GeneralUtils.UTC);
    }

    // Convert Strings to Enums, if target type was an enum
    if (destinationClass.isEnum()) {
        return Enum.valueOf(destinationClass, value.toString());
    }

    if ((destinationClass == boolean.class || destinationClass == Boolean.class)) {
        if (value instanceof String) {
            return Boolean.valueOf((String) value);
        } else if (value instanceof Integer) {
            return (Integer) value > 0;
        } else if (value instanceof Long) {
            return (Long) value > 0;
        }
    }

    if ((destinationClass == byte.class || destinationClass == Byte.class)
            && value.getClass() == String.class) {
        return new Byte((String) value);
    }
    if ((destinationClass == short.class || destinationClass == Short.class)
            && value.getClass() == String.class) {
        return new Short((String) value);
    }
    if ((destinationClass == int.class || destinationClass == Integer.class)
            && value.getClass() == String.class) {
        return new Integer((String) value);
    }
    if ((destinationClass == long.class || destinationClass == Long.class)
            && value.getClass() == String.class) {
        return new Long((String) value);
    }
    if ((destinationClass == long.class || destinationClass == Long.class) && value instanceof Integer) {
        return new Long((Integer) value);
    }
    if ((destinationClass == float.class || destinationClass == Float.class)
            && value.getClass() == String.class) {
        return new Float((String) value);
    }
    if ((destinationClass == float.class || destinationClass == Float.class)
            && value.getClass() == Integer.class) {
        return ((Integer) value).floatValue();
    }
    if ((destinationClass == float.class || destinationClass == Float.class)
            && value.getClass() == Long.class) {
        return ((Long) value).floatValue();
    }
    if ((destinationClass == float.class || destinationClass == Float.class)
            && value.getClass() == Double.class) {
        return ((Double) value).floatValue();
    }

    if ((destinationClass == double.class || destinationClass == Double.class)
            && value.getClass() == Long.class) {
        return ((Long) value).floatValue();
    }

    if ((destinationClass == float.class || destinationClass == Float.class)
            && value.getClass() == String.class) {
        return new Float((String) value);
    }

    if ((destinationClass == double.class || destinationClass == Double.class)
            && value.getClass() == String.class) {
        return new Double((String) value);
    }

    // If the type mis-match is due to boxing, just return the value
    if (value.getClass() == boolean.class || value.getClass() == Boolean.class || value.getClass() == byte.class
            || value.getClass() == Byte.class || value.getClass() == short.class
            || value.getClass() == Short.class || value.getClass() == int.class
            || value.getClass() == Integer.class || value.getClass() == long.class
            || value.getClass() == Long.class || value.getClass() == float.class
            || value.getClass() == Float.class || value.getClass() == double.class
            || value.getClass() == Double.class)
        return value;

    throw new PropertyException("cannot convert values of type '" + value.getClass().getName() + "' into type '"
            + destinationClass + "'");
}