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.cloudata.core.common.io.CObjectWritable.java

/** Read a {@link CWritable}, {@link String}, primitive type, or an array of
 * the preceding. *//*from  w w  w  .  j ava2  s.co m*/
@SuppressWarnings("unchecked")
public static Object readObject(DataInput in, CObjectWritable objectWritable, CloudataConf conf,
        boolean arrayComponent, Class componentClass) throws IOException {
    String className;
    if (arrayComponent) {
        className = componentClass.getName();
    } else {
        className = CUTF8.readString(in);
        //SANGCHUL
        //   System.out.println("SANGCHUL] className:" + className);
    }

    Class<?> declaredClass = PRIMITIVE_NAMES.get(className);
    if (declaredClass == null) {
        try {
            declaredClass = conf.getClassByName(className);
        } catch (ClassNotFoundException e) {
            //SANGCHUL
            e.printStackTrace();
            throw new RuntimeException("readObject can't find class[className=" + className + "]", e);
        }
    }

    Object instance;

    if (declaredClass.isPrimitive()) { // primitive types

        if (declaredClass == Boolean.TYPE) { // boolean
            instance = Boolean.valueOf(in.readBoolean());
        } else if (declaredClass == Character.TYPE) { // char
            instance = Character.valueOf(in.readChar());
        } else if (declaredClass == Byte.TYPE) { // byte
            instance = Byte.valueOf(in.readByte());
        } else if (declaredClass == Short.TYPE) { // short
            instance = Short.valueOf(in.readShort());
        } else if (declaredClass == Integer.TYPE) { // int
            instance = Integer.valueOf(in.readInt());
        } else if (declaredClass == Long.TYPE) { // long
            instance = Long.valueOf(in.readLong());
        } else if (declaredClass == Float.TYPE) { // float
            instance = Float.valueOf(in.readFloat());
        } else if (declaredClass == Double.TYPE) { // double
            instance = Double.valueOf(in.readDouble());
        } else if (declaredClass == Void.TYPE) { // void
            instance = null;
        } else {
            throw new IllegalArgumentException("Not a primitive: " + declaredClass);
        }

    } else if (declaredClass.isArray()) { // array
        //System.out.println("SANGCHUL] is array");
        int length = in.readInt();
        //System.out.println("SANGCHUL] array length : " + length);
        //System.out.println("Read:in.readInt():" + length);
        if (declaredClass.getComponentType() == Byte.TYPE) {
            byte[] bytes = new byte[length];
            in.readFully(bytes);
            instance = bytes;
        } else if (declaredClass.getComponentType() == ColumnValue.class) {
            instance = readColumnValue(in, conf, declaredClass, length);
        } else {
            Class componentType = declaredClass.getComponentType();

            // SANGCHUL
            //System.out.println("SANGCHUL] componentType : " + componentType.getName());

            instance = Array.newInstance(componentType, length);
            for (int i = 0; i < length; i++) {
                Object arrayComponentInstance = readObject(in, null, conf, !componentType.isArray(),
                        componentType);
                Array.set(instance, i, arrayComponentInstance);
                //Array.set(instance, i, readObject(in, conf));
            }
        }
    } else if (declaredClass == String.class) { // String
        instance = CUTF8.readString(in);
    } else if (declaredClass.isEnum()) { // enum
        instance = Enum.valueOf((Class<? extends Enum>) declaredClass, CUTF8.readString(in));
    } else if (declaredClass == ColumnValue.class) {
        //ColumnValue?  ?? ?? ?  ? ?.
        //? ?   ? ? ? ? . 
        Class instanceClass = null;
        try {
            short typeDiff = in.readShort();
            if (typeDiff == TYPE_DIFF) {
                instanceClass = conf.getClassByName(CUTF8.readString(in));
            } else {
                instanceClass = declaredClass;
            }
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("readObject can't find class", e);
        }
        ColumnValue columnValue = new ColumnValue();
        columnValue.readFields(in);
        instance = columnValue;
    } else { // Writable

        Class instanceClass = null;
        try {
            short typeDiff = in.readShort();
            // SANGCHUL
            //System.out.println("SANGCHUL] typeDiff : " + typeDiff);
            //System.out.println("Read:in.readShort():" + typeDiff);
            if (typeDiff == TYPE_DIFF) {
                // SANGCHUL
                String classNameTemp = CUTF8.readString(in);
                //System.out.println("SANGCHUL] typeDiff : " + classNameTemp);
                instanceClass = conf.getClassByName(classNameTemp);
                //System.out.println("Read:UTF8.readString(in):" + instanceClass.getClass());
            } else {
                instanceClass = declaredClass;
            }
        } catch (ClassNotFoundException e) {

            // SANGCHUL
            e.printStackTrace();
            throw new RuntimeException("readObject can't find class", e);
        }

        CWritable writable = CWritableFactories.newInstance(instanceClass, conf);
        writable.readFields(in);
        //System.out.println("Read:writable.readFields(in)");
        instance = writable;

        if (instanceClass == NullInstance.class) { // null
            declaredClass = ((NullInstance) instance).declaredClass;
            instance = null;
        }
    }

    if (objectWritable != null) { // store values
        objectWritable.declaredClass = declaredClass;
        objectWritable.instance = instance;
    }

    return instance;
}

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

/**
 * Process ACL roles map from OPA config.
 * /*from w  w w  .  j a  va  2s.  com*/
 * @param bundleApp
 * @param appConfig
 * @param opaConfig
 * @param permissionsMap
 * 
 * @return the map of all configured roles.
 * @throws AppConfigNotFoundException
 * @throws BadAppConfigException
 */
protected Map<String, IRole> processAclRoles(final Bundle bundleApp, final BasicAppConfig appConfig,
        final Properties opaConfig, final Map<String, IPermission> permissionsMap)
        throws BadAppConfigException {
    final Map<String, IRole> rolesByAclName = new HashMap<String, IRole>(4);

    // Special Roles
    final Set<String> specialRolesNames = new HashSet<String>(SpecialRole.values().length);
    final Map<SpecialRole, IRole> specialRoles = new HashMap<SpecialRole, IRole>(SpecialRole.values().length);
    for (final SpecialRole srEnum : SpecialRole.values()) {
        specialRolesNames.add(srEnum.name());
    }

    // Declared Roles
    final Set<String> aclRolesNames = new HashSet<String>();
    aclRolesNames.addAll(specialRolesNames);
    final String aclRolesVal = this.getOptionalValue(opaConfig, OpaConfigKeys.ACL_ROLES.getKey());
    final String[] aclRolesArray = StringUtils.delimitedListToStringArray(aclRolesVal,
            IAppConfigFactory.OPA_CONFIG_LIST_SPLITER);
    if (aclRolesArray != null) {
        for (final String aclRoleName : aclRolesArray) {
            if (StringUtils.hasText(aclRoleName)) {
                aclRolesNames.add(aclRoleName);
            }
        }
    }

    // Search permissions assignment
    final Map<String, Set<IPermission>> permissionsAssignment = new HashMap<String, Set<IPermission>>(4);
    for (final String aclRoleName : aclRolesNames) {
        // For each role search perm assignment
        final Set<IPermission> rolePermissionSet;
        final String permKey = OpaConfigKeys.ACL_ROLES.getKey().concat(".").concat(aclRoleName)
                .concat(OpaConfigKeys.ACL_PERMISSIONS_ASSIGNMENT_SUFFIX.getKey());
        final String rolePermissionsVal = this.getOptionalValue(opaConfig, permKey);
        final String[] rolePermissionsArray = StringUtils.delimitedListToStringArray(rolePermissionsVal,
                IAppConfigFactory.OPA_CONFIG_LIST_SPLITER);
        if (rolePermissionsArray != null) {
            // We found a perm assignment
            rolePermissionSet = new HashSet<IPermission>();
            for (final String rolePermissionName : rolePermissionsArray) {
                if (StringUtils.hasText(rolePermissionName)) {
                    final IPermission perm = permissionsMap.get(rolePermissionName);
                    if (perm != null) {
                        rolePermissionSet.add(perm);
                    } else {
                        final String message = String.format(
                                "Try to assign undeclared permission: [%1$s] to role: [%2$s] in OPA: [%3$s] !",
                                rolePermissionName, aclRoleName, bundleApp.getSymbolicName());
                        throw new BadAppConfigException(message);
                    }
                }
            }
        } else {
            rolePermissionSet = Collections.emptySet();
        }

        permissionsAssignment.put(aclRoleName, rolePermissionSet);
    }

    // Search sub-roles assignment
    final Map<String, Set<String>> subRolesAssignment = new HashMap<String, Set<String>>(4);
    for (final String aclRoleName : aclRolesNames) {
        final Set<String> subRolesSet;
        final String key = OpaConfigKeys.ACL_ROLES.getKey().concat(".").concat(aclRoleName)
                .concat(OpaConfigKeys.ACL_SUBROLES_ASSIGNMENT_SUFFIX.getKey());
        final String subRolesVal = this.getOptionalValue(opaConfig, key);
        final String[] subRolesArray = StringUtils.delimitedListToStringArray(subRolesVal,
                IAppConfigFactory.OPA_CONFIG_LIST_SPLITER);
        if (subRolesArray != null) {
            subRolesSet = new HashSet<String>();
            for (final String subRoleName : subRolesArray) {
                if (StringUtils.hasText(subRoleName) && aclRolesNames.contains(subRoleName)) {
                    subRolesSet.add(subRoleName);
                } else {
                    final String message = String.format(
                            "Try to assign undeclared sub-role: [%1$s] to role: [%2$s] in OPA: [%3$s] !",
                            subRoleName, aclRoleName, bundleApp.getSymbolicName());
                    throw new BadAppConfigException(message);
                }
            }
        } else {
            subRolesSet = Collections.emptySet();
        }

        subRolesAssignment.put(aclRoleName, subRolesSet);
    }

    // Build roles : begin with the sub-roles
    final Set<String> rolesToBuild = new HashSet<String>(aclRolesNames);
    final Set<String> builtRoles = new HashSet<String>(rolesToBuild.size());
    while (!rolesToBuild.isEmpty()) {
        // Loop while some roles are not built yet
        final Iterator<String> rolesToBuildIt = rolesToBuild.iterator();
        while (rolesToBuildIt.hasNext()) {
            // Loop on all roles not built yet to find one candidate to build
            final String aclRoleName = rolesToBuildIt.next();
            final Set<String> subRolesNames = subRolesAssignment.get(aclRoleName);
            if (builtRoles.containsAll(subRolesNames)) {
                // If all sub-roles are already built we can build the role
                final String finalRoleName = this.buildFinalRoleName(bundleApp, aclRoleName);
                final Set<IPermission> permissions = permissionsAssignment.get(aclRoleName);
                final Set<IRole> subRoles = new HashSet<IRole>(subRolesNames.size());
                for (final String subRoleName : subRolesNames) {
                    subRoles.add(rolesByAclName.get(subRoleName));
                }

                final IRole newRole = this.roleFactory.initializeRole(finalRoleName, permissions, subRoles);
                rolesByAclName.put(aclRoleName, newRole);
                builtRoles.add(aclRoleName);
                rolesToBuildIt.remove();

                if (specialRolesNames.contains(aclRoleName)) {
                    // Current role is special
                    specialRoles.put(Enum.valueOf(SpecialRole.class, aclRoleName), newRole);
                }
            }
        }
    }

    appConfig.setSpecialRoles(Collections.unmodifiableMap(specialRoles));
    final Set<IRole> rolesSet = new HashSet<IRole>(rolesByAclName.values());
    appConfig.setDeclaredRoles(Collections.unmodifiableSet(rolesSet));

    return rolesByAclName;
}

From source file:org.nuxeo.ecm.platform.ui.web.tag.fn.Functions.java

public static String printFormatedFileSize(String sizeS, String format, Boolean isShort) {
    long size = (sizeS == null || "".equals(sizeS)) ? 0 : Long.parseLong(sizeS);
    BytePrefix prefix = Enum.valueOf(BytePrefix.class, format);
    int base = prefix.getBase();
    String[] suffix = isShort ? prefix.getShortSuffixes() : prefix.getLongSuffixes();
    int ex = 0;/*from  www .  ja  v  a 2  s  .co  m*/
    while (size > base - 1 || ex > suffix.length) {
        ex++;
        size /= base;
    }

    FacesContext context = FacesContext.getCurrentInstance();
    String msg;
    if (context != null) {
        String bundleName = context.getApplication().getMessageBundle();
        Locale locale = context.getViewRoot().getLocale();
        msg = I18NUtils.getMessageString(bundleName, "label.bytes.suffix", null, locale);
        if ("label.bytes.suffix".equals(msg)) {
            // Set default value if no message entry found
            msg = "B";
        }
    } else {
        // No faces context, set default value
        msg = "B";
    }

    return "" + size + " " + suffix[ex] + msg;
}

From source file:be.fedict.eid.pkira.blm.model.contracthandler.ContractHandlerBean.java

private CertificateType mapCertificateType(CertificateSigningRequestType request) {
    return Enum.valueOf(CertificateType.class, request.getCertificateType().name());
}

From source file:com.opengamma.web.analytics.blotter.BlotterUtils.java

@Override
public T convertFromString(Class<? extends T> type, String str) {
    // IntelliJ says this cast is redundant but javac disagrees
    //noinspection RedundantCast
    return (T) Enum.valueOf(type, str.toUpperCase().replace(' ', '_'));
}

From source file:it.unimi.di.big.mg4j.document.DispatchingDocumentFactory.java

@SuppressWarnings({ "rawtypes", "unchecked" })
@Override//from  w  w  w . j av  a2  s. c  om
protected boolean parseProperty(final String key, final String[] values,
        final Reference2ObjectMap<Enum<?>, Object> metadata) throws ConfigurationException {
    if (sameKey(MetadataKeys.FIELDNAME, key)) {
        fieldName = values;
        numberOfFields = fieldName.length;
        return true;
    } else if (sameKey(MetadataKeys.KEY, key)) {
        final String dispatchingKeyName = ensureJustOne(key, values);
        final int lastDot = dispatchingKeyName.lastIndexOf('.');
        try {
            dispatchingKey = Enum.valueOf((Class<Enum>) Class.forName(dispatchingKeyName.substring(0, lastDot)),
                    dispatchingKeyName.substring(lastDot + 1));
        } catch (ClassNotFoundException e) {
            throw new IllegalArgumentException(
                    "The class specified in the key " + dispatchingKeyName + " cannot be found");
        }
        return true;
    } else if (sameKey(MetadataKeys.RULE, key)) {
        String[] rules = values;
        value2factoryClass = new Object2ObjectLinkedOpenHashMap<String, Class<? extends DocumentFactory>>();
        int i, m = rules.length;
        for (i = 0; i < m; i++) {
            int pos = rules[i].indexOf(':');
            if (pos <= 0 || pos == rules[i].length() - 1)
                throw new ConfigurationException(
                        "Rule " + rules[i] + " does not contain a colon or it is malformed");
            if (rules[i].indexOf(':', pos + 1) >= 0)
                throw new ConfigurationException("Rule " + rules[i] + " contains too many colons");
            String factoryName = rules[i].substring(pos + 1);
            Class<? extends DocumentFactory> factoryClass = null;
            try {
                factoryClass = (Class<? extends DocumentFactory>) Class.forName(factoryName);
                if (!(DocumentFactory.class.isAssignableFrom(factoryClass)))
                    throw new ClassNotFoundException();
            } catch (ClassNotFoundException e) {
                throw new ConfigurationException(
                        "ParsingFactory " + factoryName + " is invalid; maybe the package name is missing");
            }
            value2factoryClass.put(rules[i].substring(0, pos), factoryClass);
        }
        m = value2factoryClass.values().size();
        return true;

    } else if (sameKey(MetadataKeys.MAP, key)) {
        String[] pieces = values;
        int i, m = pieces.length;
        rename = new int[m][];
        for (i = 0; i < m; i++) {
            String[] subpieces = pieces[i].split(":");
            if (i > 0 && subpieces.length != rename[0].length)
                throw new ConfigurationException("Length mismatch in the map " + values);
            rename[i] = new int[subpieces.length];
            for (int k = 0; k < subpieces.length; k++) {
                try {
                    rename[i][k] = Integer.parseInt(subpieces[k]);
                } catch (NumberFormatException e) {
                    throw new ConfigurationException("Number format exception in the map " + values);
                }
            }
        }
    }
    return super.parseProperty(key, values, metadata);
}

From source file:com.evolveum.midpoint.repo.sql.query.restriction.ItemRestriction.java

/**
 * This method provides transformation from {@link String} value defined in
 * {@link com.evolveum.midpoint.repo.sql.query.definition.VirtualQueryParam#value()} to real object. Currently only
 * to simple types and enum values.//from w  w w  .j ava 2  s .c om
 *
 * @param param
 * @param propPath
 * @return real value
 * @throws QueryException
 */
private Object createQueryParamValue(VirtualQueryParam param, ItemPath propPath) throws QueryException {
    Class type = param.type();
    String value = param.value();

    try {
        if (type.isPrimitive()) {
            return type.getMethod("valueOf", new Class[] { String.class }).invoke(null, new Object[] { value });
        }

        if (type.isEnum()) {
            return Enum.valueOf(type, value);
        }
    } catch (Exception ex) {
        throw new QueryException("Couldn't transform virtual query parameter '" + param.name()
                + "' from String to '" + type + "', reason: " + ex.getMessage(), ex);
    }

    throw new QueryException("Couldn't transform virtual query parameter '" + param.name()
            + "' from String to '" + type + "', it's not yet implemented.");
}

From source file:com.cedarsoft.serialization.jackson.AbstractJacksonSerializer.java

/**
 * Deserializes the enumeration/*from w w w .j ava  2s  . co  m*/
 *
 * @param enumClass    the enum class
 * @param propertyName the property name
 * @param parser       the parser
 * @param <T>          the type
 * @return the deserialized enum
 *
 * @throws IOException
 */
@Nonnull
public <T extends Enum<T>> T deserializeEnum(@Nonnull Class<T> enumClass, @Nonnull String propertyName,
        @Nonnull JsonParser parser) throws IOException {
    JacksonParserWrapper wrapper = new JacksonParserWrapper(parser);
    wrapper.nextFieldValue(propertyName);
    return Enum.valueOf(enumClass, parser.getText());
}

From source file:alluxio.Configuration.java

/**
 * Gets the value for the given key as an enum value.
 *
 * @param key the key to get the value for
 * @param enumType the type of the enum/*  w ww  . j  a  v  a 2  s  . c o  m*/
 * @param <T> the type of the enum
 * @return the value for the given key as an enum value
 */
public <T extends Enum<T>> T getEnum(String key, Class<T> enumType) {
    if (!mProperties.containsKey(key)) {
        throw new RuntimeException(ExceptionMessage.INVALID_CONFIGURATION_KEY.getMessage(key));
    }
    final String val = get(key);
    return Enum.valueOf(enumType, val);
}

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

@Override
public void loadRep(Repository rep, IMetaStore metaStore, ObjectId id_jobentry, List<DatabaseMeta> databases,
        List<SlaveServer> slaveServers) throws KettleException {
    super.loadRep(rep, metaStore, id_jobentry, databases, slaveServers);
    try {//from w  ww  . j  a va 2  s .com
        setAddFilesToResult(rep.getJobEntryAttributeBoolean(id_jobentry, "addFilesToResult"));
        setCreateTargetFolder(rep.getJobEntryAttributeBoolean(id_jobentry, "createTargetFolder"));
        setTargetFolder(rep.getJobEntryAttributeString(id_jobentry, "targetFolder"));
        long fileCount = rep.getJobEntryAttributeInteger(id_jobentry, "fileSelectionCount");
        fileSelections = new GoogleDriveExportFileSelection[(int) fileCount];
        for (int i = 0; i < fileCount; i++) {
            GoogleDriveFileType fileType = Enum.valueOf(GoogleDriveFileType.class,
                    rep.getJobEntryAttributeString(id_jobentry, i, "queryFileType"));
            GoogleDriveExportFormat exportFormat = Enum.valueOf(GoogleDriveExportFormat.class,
                    rep.getJobEntryAttributeString(id_jobentry, i, "exportFileType"));
            String queryOptions = rep.getJobEntryAttributeString(id_jobentry, i, "customQuery");
            boolean deleteSource = rep.getJobEntryAttributeBoolean(id_jobentry, i, "removeSourceFiles");
            fileSelections[i] = new GoogleDriveExportFileSelection(fileType, exportFormat, queryOptions,
                    deleteSource);
        }
    } catch (KettleDatabaseException dbe) {
        throw new KettleException(
                BaseMessages.getString(PKG, "Demo.Error.UnableToLoadFromRepository") + id_jobentry, dbe);
    }
}