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.haulmont.cuba.core.sys.MetadataBuildSupport.java

private Object getXmlAnnotationAttributeValue(String value, String className, String datatypeName) {
    if (className == null && datatypeName == null)
        return inferMetaAnnotationType(value);
    if (className != null) {
        Class aClass = ReflectionHelper.getClass(className);
        if (aClass.isEnum()) {
            //noinspection unchecked
            return Enum.valueOf(aClass, value);
        } else {//from   w  ww  . jav  a2  s  .c  o m
            throw new UnsupportedOperationException("Class " + className + "  is not Enum");
        }
    } else {
        try {
            return datatypes.get(datatypeName).parse(value);
        } catch (ParseException e) {
            throw new RuntimeException("Unable to parse XML meta-annotation value", e);
        }
    }
}

From source file:com.l2jfree.config.L2Properties.java

public <T extends Enum<T>> T getEnum(String name, Class<T> enumClass, T deflt) {
    String val = getProperty(name);
    if (val == null)
        return deflt;

    try {//from   w  w w .  j  ava  2s.  c o m
        return Enum.valueOf(enumClass, String.valueOf(val));
    } catch (Exception e) {
        throw new IllegalArgumentException(
                "Enum value of type " + enumClass.getName() + "required, but found: " + val);
    }
}

From source file:hu.javaforum.commons.ReflectionHelper.java

/**
 * Converts the string value to instance of the field class.
 *
 * @param fieldClass The field class//w ww  .java2 s.c om
 * @param stringValue The string value
 * @return The instance of the field class
 * @throws ParseException Throws when the string isn't parseable
 * @throws UnsupportedEncodingException If the Base64 stream contains non UTF-8 chars
 */
private static Object convertToOthers(final Class fieldClass, final String stringValue)
        throws ParseException, UnsupportedEncodingException {
    Object parameter = null;

    if (fieldClass.isEnum()) {
        parameter = Enum.valueOf((Class<Enum>) fieldClass, stringValue);
    } else if (fieldClass.equals(byte[].class)) {
        parameter = Base64.decodeBase64(stringValue.getBytes("UTF-8"));
    } else if (fieldClass.equals(Date.class)) {
        parameter = stringToDate(stringValue);
    } else if (fieldClass.equals(Calendar.class)) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(stringToDate(stringValue));
        parameter = cal;
    }

    return parameter;
}

From source file:com.sqewd.open.dal.core.persistence.db.EntityHelper.java

@SuppressWarnings({ "rawtypes", "unchecked" })
public static Object getColumnValue(final ResultSet rs, final StructAttributeReflect attr,
        final AbstractEntity entity, final AbstractJoinGraph gr, final Stack<KeyValuePair<Class<?>>> path)
        throws Exception {

    Object value = null;//from w w w .  ja  v  a  2 s  .c  o m

    KeyValuePair<String> alias = gr.getAliasFor(path, attr.Column, 0);
    String tabprefix = alias.getKey();

    if (EnumPrimitives.isPrimitiveType(attr.Field.getType())) {
        EnumPrimitives prim = EnumPrimitives.type(attr.Field.getType());
        switch (prim) {
        case ECharacter:
            String sv = rs.getString(tabprefix + "." + attr.Column);
            if (!rs.wasNull()) {
                PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), sv.charAt(0));
            }
            break;
        case EShort:
            short shv = rs.getShort(tabprefix + "." + attr.Column);
            if (!rs.wasNull()) {
                PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), shv);
            }
            break;
        case EInteger:
            int iv = rs.getInt(tabprefix + "." + attr.Column);
            if (!rs.wasNull()) {
                PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), iv);
            }
            break;
        case ELong:
            long lv = rs.getLong(tabprefix + "." + attr.Column);
            if (!rs.wasNull()) {
                PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), lv);
            }
            break;
        case EFloat:
            float fv = rs.getFloat(tabprefix + "." + attr.Column);
            if (!rs.wasNull()) {
                PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), fv);
            }
            break;
        case EDouble:
            double dv = rs.getDouble(tabprefix + "." + attr.Column);
            if (!rs.wasNull()) {
                PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), dv);
            }
            break;
        default:
            throw new Exception("Unsupported Data type [" + prim.name() + "]");
        }
    } else if (attr.Convertor != null) {
        // TODO : Not supported at this time.
        value = rs.getString(tabprefix + "." + attr.Column);

    } else if (attr.Field.getType().equals(String.class)) {
        value = rs.getString(tabprefix + "." + attr.Column);
        if (rs.wasNull()) {
            value = null;
        }
    } else if (attr.Field.getType().equals(Date.class)) {
        long lvalue = rs.getLong(tabprefix + "." + attr.Column);
        if (!rs.wasNull()) {
            Date dt = new Date(lvalue);
            value = dt;
        }
    } else if (attr.Field.getType().isEnum()) {
        String svalue = rs.getString(tabprefix + "." + attr.Column);
        if (!rs.wasNull()) {
            Class ecls = attr.Field.getType();
            value = Enum.valueOf(ecls, svalue);
        }
    } else if (attr.Reference != null) {
        Class<?> rt = Class.forName(attr.Reference.Class);
        Object obj = rt.newInstance();
        if (!(obj instanceof AbstractEntity))
            throw new Exception("Unsupported Entity type [" + rt.getCanonicalName() + "]");
        AbstractEntity rentity = (AbstractEntity) obj;
        if (path.size() > 0) {
            path.peek().setKey(attr.Column);
        }

        KeyValuePair<Class<?>> cls = new KeyValuePair<Class<?>>();
        cls.setValue(rentity.getClass());
        path.push(cls);
        setEntity(rentity, rs, gr, path);
        value = rentity;
        path.pop();
    }
    return value;
}

From source file:org.rhq.plugins.jbossas5.ApplicationServerOperationsDelegate.java

/**
 * Shuts down the server by dispatching to shutdown via script or JMX. Waits
 * until the server is down.//ww w  .j av a2s.  co  m
 *
 * @return The result of the shutdown operation - is successful
 */
private OperationResult shutDown() {
    AvailabilityType avail = this.serverComponent.getAvailability();
    if (avail == AvailabilityType.DOWN) {
        OperationResult result = new OperationResult();
        result.setErrorMessage("The server is already shut down.");
        return result;
    }

    Configuration pluginConfig = serverComponent.getResourceContext().getPluginConfiguration();
    ApplicationServerShutdownMethod shutdownMethod = Enum.valueOf(ApplicationServerShutdownMethod.class,
            pluginConfig.getSimple(ApplicationServerPluginConfigurationProperties.SHUTDOWN_METHOD_CONFIG_PROP)
                    .getStringValue());
    String resultMessage = ApplicationServerShutdownMethod.JMX.equals(shutdownMethod) ? shutdownViaJmx()
            : shutdownViaScript();

    avail = waitForServerToShutdown();
    OperationResult result;
    if (avail == AvailabilityType.UP) {
        result = new OperationResult();
        result.setErrorMessage("The server failed to shut down.");
    } else {
        return new OperationResult(resultMessage);
    }
    return result;
}

From source file:org.repodriller.scm.GitRepository.java

private Modification diffToModification(Repository repo, DiffEntry diff) throws IOException {
    ModificationType change = Enum.valueOf(ModificationType.class, diff.getChangeType().toString());

    String oldPath = diff.getOldPath();
    String newPath = diff.getNewPath();

    String diffText = "";
    String sc = "";
    if (diff.getChangeType() != ChangeType.DELETE) {
        diffText = getDiffText(repo, diff);
        sc = getSourceCode(repo, diff);/*from  w  w  w  .ja  v  a 2 s.  c  o m*/
    }

    if (diffText.length() > maxSizeOfDiff) {
        log.error("diff for " + newPath + " too big");
        diffText = "-- TOO BIG --";
    }

    return new Modification(oldPath, newPath, change, diffText, sc);
}

From source file:com.zegoggles.smssync.PrefStore.java

static <T extends Enum<T>> T getDefaultType(Context ctx, String pref, Class<T> tClazz, T defaultType) {
    try {//ww  w. j  a  va  2s  .  c  om
        final String s = getPrefs(ctx).getString(pref, null);
        return s == null ? defaultType : Enum.valueOf(tClazz, s.toUpperCase(Locale.ENGLISH));
    } catch (IllegalArgumentException e) {
        Log.e(TAG, "getDefaultType(" + pref + ")", e);
        return defaultType;
    }
}

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

private void init(final String filterName, final Object value, String propertyNameStr) {
    String firstPart = StringUtils.substringBefore(filterName, "_");

    String matchTypeCode = StringUtils.substring(firstPart, 0, firstPart.length() - 1);

    String propertyTypeCode = StringUtils.substring(firstPart, firstPart.length() - 1, firstPart.length());

    try {/*w ww . j a va2  s  . c o  m*/
        matchType = Enum.valueOf(MatchType.class, matchTypeCode);
    } catch (RuntimeException e) {
        throw new IllegalArgumentException(
                "filter??" + filterName + ",.", e);
    }

    try {
        propertyClass = Enum.valueOf(PropertyType.class, propertyTypeCode).getValue();
    } catch (RuntimeException e) {
        throw new IllegalArgumentException(
                "filter??" + filterName + ",.", e);
    }

    // String propertyNameStr = StringUtils.substringAfter(filterName, "_");
    Assert.isTrue(StringUtils.isNotBlank(propertyNameStr),
            "filter??" + filterName + ",??.");

    propertyNames = StringUtils.splitByWholeSeparator(propertyNameStr, PropertyFilter.OR_SEPARATOR);

}

From source file:org.forgerock.restlet.ext.oauth2.flow.AbstractFlow.java

protected Representation getPage(String templateName, Object dataModel) {
    String display = OAuth2Utils.getRequestParameter(getRequest(), OAuth2Constants.Custom.DISPLAY,
            String.class);
    OAuth2Constants.DisplayType displayType = OAuth2Constants.DisplayType.PAGE;
    if (OAuth2Utils.isNotBlank(display)) {
        try {//from  w  w  w . j a va2  s .  c  o m
            displayType = Enum.valueOf(OAuth2Constants.DisplayType.class, display.toUpperCase());
        } catch (IllegalArgumentException e) {
        }
    }
    Representation r = null;
    if (display != null && display.equalsIgnoreCase(OAuth2Constants.DisplayType.POPUP.name())) {
        Representation popup = getPage(displayType.getFolder(), "authorize.ftl", dataModel);

        try {
            ((Map) dataModel).put("htmlCode", popup.getText());
        } catch (IOException e) {
            OAuth2Utils.DEBUG.error("AbstractFlow::Server can not serve the content of authorization page");
            throw OAuthProblemException.OAuthError.SERVER_ERROR.handle(getRequest(),
                    "Server can not serve the content of authorization page");
        }
        r = getPage(displayType.getFolder(), "popup.ftl", dataModel);
    } else {
        r = getPage(displayType.getFolder(), templateName, dataModel);
    }
    if (null != r) {
        return r;
    }
    OAuth2Utils.DEBUG.error("AbstractFlow::Server can not serve the content of authorization page");
    throw OAuthProblemException.OAuthError.SERVER_ERROR.handle(getRequest(),
            "Server can not serve the content of authorization page");
}

From source file:org.pentaho.di.job.entries.googledrive.JobEntryGoogleDriveExport.java

@Override
public void loadXML(Node entrynode, List<DatabaseMeta> databases, List<SlaveServer> slaveServers,
        Repository rep, IMetaStore metaStore) throws KettleXMLException {
    try {/* www  .ja va  2  s .  c om*/
        super.loadXML(entrynode, databases, slaveServers, rep, metaStore);
        setAddFilesToResult("Y".equalsIgnoreCase(XMLHandler.getTagValue(entrynode, "addFilesToResult")));
        setCreateTargetFolder("Y".equalsIgnoreCase(XMLHandler.getTagValue(entrynode, "createTargetFolder")));
        setTargetFolder(XMLHandler.getTagValue(entrynode, "targetFolder"));
        Node filesNode = XMLHandler.getSubNode(entrynode, "files");
        if (filesNode != null) {
            int fileCount = XMLHandler.countNodes(filesNode, "file");
            fileSelections = new GoogleDriveExportFileSelection[fileCount];

            for (int i = 0; i < fileCount; i++) {
                Node fileNode = XMLHandler.getSubNodeByNr(filesNode, "file", i);
                GoogleDriveFileType fileType = Enum.valueOf(GoogleDriveFileType.class,
                        XMLHandler.getTagValue(fileNode, "queryFileType"));
                GoogleDriveExportFormat exportFormat = Enum.valueOf(GoogleDriveExportFormat.class,
                        XMLHandler.getTagValue(fileNode, "exportFileType"));
                String queryOptions = XMLHandler.getTagValue(fileNode, "customQuery");
                boolean deleteSource = "Y"
                        .equalsIgnoreCase(XMLHandler.getTagValue(fileNode, "removeSourceFiles"));

                fileSelections[i] = new GoogleDriveExportFileSelection(fileType, exportFormat, queryOptions,
                        deleteSource);
            }
        }
    } catch (Exception e) {
        throw new KettleXMLException(BaseMessages.getString(PKG, "Demo.Error.UnableToLoadFromXML"), e);
    }
}