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.zenesis.qx.remote.RequestHandler.java

/**
 * Handles setting a server object property from the client; expects a serverId, propertyName, and a value
 * @param jp//ww  w. j a  v  a2s  . co m
 * @throws ServletException
 * @throws IOException
 */
protected void cmdSetProperty(JsonParser jp) throws ServletException, IOException {
    // Get the basics
    int serverId = getFieldValue(jp, "serverId", Integer.class);
    String propertyName = getFieldValue(jp, "propertyName", String.class);
    Object value = null;

    Proxied serverObject = getProxied(serverId);
    ProxyType type = ProxyTypeManager.INSTANCE.getProxyType(serverObject.getClass());
    ProxyProperty prop = getProperty(type, propertyName);

    skipFieldName(jp, "value");
    MetaClass propClass = prop.getPropertyClass();
    if (propClass.isSubclassOf(Proxied.class)) {

        if (propClass.isArray() || propClass.isCollection()) {
            value = readArray(jp, propClass.getJavaType());

        } else if (propClass.isMap()) {
            value = readMap(jp, propClass.getKeyClass(), propClass.getJavaType());

        } else {
            Integer id = jp.readValueAs(Integer.class);
            if (id != null)
                value = getProxied(id);
        }
    } else {
        if (propClass.isArray() || propClass.isCollection()) {
            value = readArray(jp, propClass.getJavaType());

        } else if (propClass.isMap()) {
            value = readMap(jp, propClass.getKeyClass(), propClass.getJavaType());

        } else {
            value = jp.readValueAs(Object.class);
            if (value != null && Enum.class.isAssignableFrom(propClass.getJavaType())) {
                String str = Helpers.camelCaseToEnum(value.toString());
                value = Enum.valueOf(propClass.getJavaType(), str);
            }
        }
    }

    setPropertyValue(type, serverObject, propertyName, value);
    jp.nextToken();
}

From source file:com.hp.ov.sdk.rest.client.PowerDeliveryDeviceClientImpl.java

@Override
public Power getPowerDeliveryDevicePowerState(RestParams params, String resourceId) {
    LOGGER.info("PowerDeliveryDeviceClientImpl : getPowerDeliveryDevicePowerState : Start");

    // validate args
    if (null == params) {
        throw new SDKInvalidArgumentException(SDKErrorEnum.invalidArgument, null, null, null,
                SdkConstants.APPLIANCE, null);
    }//w  w  w .  j av  a2 s  . c  o m
    // set the additional params
    params.setType(HttpMethodType.GET);
    params.setUrl(UrlUtils.createRestUrl(params.getHostname(), ResourceUris.POWER_DEVICE_URI, resourceId,
            SdkConstants.POWER_STATE));

    final String returnObj = httpClient.sendRequest(params);
    LOGGER.debug("PowerDeliveryDeviceClientImpl : getPowerDeliveryDevicePowerState : response from OV :"
            + returnObj);
    if (null == returnObj || returnObj.equals("")) {
        throw new SDKNoResponseException(SDKErrorEnum.noResponseFromAppliance, null, null, null,
                SdkConstants.POWER_DEVICE, null);

    }
    final Power powerState = Enum.valueOf(Power.class, returnObj.replaceAll("^\"|\"$", ""));

    LOGGER.debug("PowerDeliveryDeviceClientImpl : getPowerDeliveryDevicePowerState : Value :"
            + powerState.toString());
    LOGGER.info("PowerDeliveryDeviceClientImpl : getPowerDeliveryDevicePowerState : End");

    return powerState;
}

From source file:com.alliander.osgp.acceptancetests.devicemonitoring.GetActualPowerUsageSteps.java

@DomainStep("a get actual power usage response message with correlationId (.*), deviceId (.*), qresult (.*), qdescription (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*) is found in the queue (.*)")
public void givenAGetActualPowerUsageResponseMessageIsFoundInQueue(final String correlationId,
        final String deviceId, final String qresult, final String qdescription, final String recordTime,
        final String meterType, final String totalConsumedEnergy, final String actualConsumedPower,
        final String psldDataTotalLightHours, final String actualCurrent1, final String actualCurrent2,
        final String actualCurrent3, final String actualPower1, final String actualPower2,
        final String actualPower3, final String averagePowerFactor1, final String averagePowerFactor2,
        final String averagePowerFactor3, final String relayData1Index, final String relayData1LightingMinutes,
        final String relayData2Index, final String relayData2LightingMinutes, final Boolean isFound) {
    LOGGER.info(/*  ww w .jav  a  2s.  c  o  m*/
            "GIVEN: \"a get actual power usage response message with correlationId {}, deviceId {}, qresult {} and qdescription {} is found {}\".",
            correlationId, deviceId, qresult, qdescription, isFound);

    if (isFound) {
        final ObjectMessage messageMock = mock(ObjectMessage.class);

        try {
            when(messageMock.getJMSCorrelationID()).thenReturn(correlationId);
            when(messageMock.getStringProperty("OrganisationIdentification")).thenReturn(ORGANISATION_ID);
            when(messageMock.getStringProperty("DeviceIdentification")).thenReturn(deviceId);

            final ResponseMessageResultType result = ResponseMessageResultType.valueOf(qresult);
            Serializable dataObject = null;
            OsgpException exception = null;

            if (result.equals(ResponseMessageResultType.NOT_OK)) {
                dataObject = new FunctionalException(FunctionalExceptionType.VALIDATION_ERROR,
                        ComponentType.UNKNOWN, new ValidationException());
                exception = (OsgpException) dataObject;
            } else {

                final MeterType metertype = StringUtils.isBlank(meterType) ? null
                        : Enum.valueOf(MeterType.class, meterType);

                DateTime dateTime = null;
                if (!recordTime.equals("")) {
                    final Date date = new SimpleDateFormat("yyyyMMddHHmmss").parse(recordTime);
                    dateTime = new DateTime(date);
                }

                PowerUsageData powerUsageData = null;
                if (!totalConsumedEnergy.equals("") && !actualConsumedPower.equals("")) {
                    powerUsageData = new PowerUsageData(dateTime, metertype,
                            Long.parseLong(totalConsumedEnergy), Long.parseLong(actualConsumedPower));

                    final PsldData psldData = new PsldData(Integer.valueOf(psldDataTotalLightHours));

                    final List<RelayData> relayDataList = new ArrayList<RelayData>();
                    // Create RelayData instances for relay indexes and
                    // minutes
                    // lighting time.
                    relayDataList.add(new RelayData(Integer.parseInt(relayData1Index),
                            Integer.parseInt(relayData1LightingMinutes)));
                    relayDataList.add(new RelayData(Integer.parseInt(relayData2Index),
                            Integer.parseInt(relayData2LightingMinutes)));

                    // Construct SsldData using the list of RelayData.
                    final SsldData ssldData = new SsldData(Integer.valueOf(actualCurrent1),
                            Integer.valueOf(actualCurrent2), Integer.valueOf(actualCurrent3),
                            Integer.valueOf(actualPower1), Integer.valueOf(actualPower2),
                            Integer.valueOf(actualPower3), Integer.valueOf(averagePowerFactor1),
                            Integer.valueOf(averagePowerFactor2), Integer.valueOf(averagePowerFactor3),
                            relayDataList);

                    powerUsageData.setPsldData(psldData);
                    powerUsageData.setSsldData(ssldData);

                    dataObject = powerUsageData;
                }
            }
            final ResponseMessage message = new ResponseMessage(correlationId, ORGANISATION_ID, deviceId,
                    result, exception, dataObject);

            when(messageMock.getObject()).thenReturn(message);

        } catch (final JMSException e) {
            LOGGER.error("JMSException", e);
        } catch (final ParseException e) {
            LOGGER.error("ParseException", e);
        }

        when(this.publicLightingResponsesJmsTemplate.receiveSelected(any(String.class)))
                .thenReturn(messageMock);
    } else {
        when(this.publicLightingResponsesJmsTemplate.receiveSelected(any(String.class))).thenReturn(null);
    }
}

From source file:com.ng.mats.psa.mt.paga.data.JSONArray.java

/**
 * Get the enum value associated with a key.
 * /*  w  w w . ja v  a 2s  . c  o m*/
 * @param clazz
 *            The type of enum to retrieve.
 * @param index
 *            The index must be between 0 and length() - 1.
 * @param defaultValue
 *            The default in case the value is not found
 * @return The enum value at the index location or defaultValue if the value
 *         is not found or cannot be assigned to clazz
 */
public <E extends Enum<E>> E optEnum(Class<E> clazz, int index, E defaultValue) {
    try {
        Object val = this.opt(index);
        if (JSONObject.NULL.equals(val)) {
            return defaultValue;
        }
        if (clazz.isAssignableFrom(val.getClass())) {
            // we just checked it!
            @SuppressWarnings("unchecked")
            E myE = (E) val;
            return myE;
        }
        return Enum.valueOf(clazz, val.toString());
    } catch (IllegalArgumentException | NullPointerException e) {
        return defaultValue;
    }
}

From source file:org.jakz.common.JSONArray.java

/**
 * Get the enum value associated with a key.
 * /*www . j  a v a2s  .  c o  m*/
 * @param clazz
 *            The type of enum to retrieve.
 * @param index
 *            The index must be between 0 and length() - 1.
 * @param defaultValue
 *            The default in case the value is not found
 * @return The enum value at the index location or defaultValue if
 *            the value is not found or cannot be assigned to clazz
 */
public <E extends Enum<E>> E optEnum(Class<E> clazz, int index, E defaultValue) {
    try {
        Object val = this.opt(index);
        if (JSONObject.NULL.equals(val)) {
            return defaultValue;
        }
        if (clazz.isAssignableFrom(val.getClass())) {
            // we just checked it!
            @SuppressWarnings("unchecked")
            E myE = (E) val;
            return myE;
        }
        return Enum.valueOf(clazz, val.toString());
    } catch (IllegalArgumentException e) {
        return defaultValue;
    } catch (NullPointerException e) {
        return defaultValue;
    }
}

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

public OperationResult invokeOperation(String name, Configuration parameters)
        throws InterruptedException, Exception {

    ApplicationServerSupportedOperations operation = Enum.valueOf(ApplicationServerSupportedOperations.class,
            name.toUpperCase());/*  ww  w  . ja  va2s.  c om*/
    return this.operationDelegate.invoke(operation, parameters);
}

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

/**
 * Parse enumerated./*from   w  w  w  .  j  av  a  2 s  . c o m*/
 */
private void endEnumerated() {
    String text = currentText();
    if (StringUtils.isEmpty(text))
        return;
    EnumType type = Enum.valueOf(EnumType.class, text);

    FieldMapping fm = (FieldMapping) currentElement();
    String strat = EnumValueHandler.class.getName() + "(StoreOrdinal="
            + String.valueOf(type == EnumType.ORDINAL) + ")";
    if (fm.isElementCollection())
        fm.getElementMapping().getValueInfo().setStrategy(strat);
    else
        fm.getValueInfo().setStrategy(strat);
}

From source file:com.belle.yitiansystem.merchant.service.impl.MerchantOperationLogServiceImpl.java

@Override
public PageFinder<MerchantOperationLog> queryMerchantOperationLog(SupplierVo supplierVo, Query query) {
    //Amend by LQ on 20150420
    int count = 0;
    count = logMapper.selectMerchantOperationLogCount(supplierVo.getSupplierCode(), supplierVo.getId());
    if (count < 1) {
        return new PageFinder<MerchantOperationLog>(query.getPage(), query.getPageSize(), 0, null);
    } else {/*from   w w  w . j  a va  2 s  .c o m*/

        List<Map> logList = logMapper.selectMerchantOperationLog(supplierVo.getSupplierCode(),
                supplierVo.getId(), query);
        List<MerchantOperationLog> resultList = new ArrayList<MerchantOperationLog>();
        for (Map map : logList) {
            MerchantOperationLog log = new MerchantOperationLog();
            log.setMerchantCode((String) map.get("merchant_code"));
            log.setId((String) map.get("id"));
            log.setOperator((String) map.get("operator"));
            log.setOperated((Date) map.get("operated"));
            log.setOperationNotes((String) map.get("operation_notes"));
            String type = (String) map.get("operation_type");
            log.setOperationType(Enum.valueOf(OperationType.class, type));
            resultList.add(log);

        }
        return new PageFinder<MerchantOperationLog>(query.getPage(), query.getPageSize(), count, resultList);
    }
}

From source file:com.facebook.LegacyTokenHelper.java

private void deserializeKey(String key, Bundle bundle) throws JSONException {
    String jsonString = cache.getString(key, "{}");
    JSONObject json = new JSONObject(jsonString);

    String valueType = json.getString(JSON_VALUE_TYPE);

    if (valueType.equals(TYPE_BOOLEAN)) {
        bundle.putBoolean(key, json.getBoolean(JSON_VALUE));
    } else if (valueType.equals(TYPE_BOOLEAN_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        boolean[] array = new boolean[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = jsonArray.getBoolean(i);
        }//from ww  w  . j ava2 s . c  o  m
        bundle.putBooleanArray(key, array);
    } else if (valueType.equals(TYPE_BYTE)) {
        bundle.putByte(key, (byte) json.getInt(JSON_VALUE));
    } else if (valueType.equals(TYPE_BYTE_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        byte[] array = new byte[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = (byte) jsonArray.getInt(i);
        }
        bundle.putByteArray(key, array);
    } else if (valueType.equals(TYPE_SHORT)) {
        bundle.putShort(key, (short) json.getInt(JSON_VALUE));
    } else if (valueType.equals(TYPE_SHORT_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        short[] array = new short[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = (short) jsonArray.getInt(i);
        }
        bundle.putShortArray(key, array);
    } else if (valueType.equals(TYPE_INTEGER)) {
        bundle.putInt(key, json.getInt(JSON_VALUE));
    } else if (valueType.equals(TYPE_INTEGER_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        int[] array = new int[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = jsonArray.getInt(i);
        }
        bundle.putIntArray(key, array);
    } else if (valueType.equals(TYPE_LONG)) {
        bundle.putLong(key, json.getLong(JSON_VALUE));
    } else if (valueType.equals(TYPE_LONG_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        long[] array = new long[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = jsonArray.getLong(i);
        }
        bundle.putLongArray(key, array);
    } else if (valueType.equals(TYPE_FLOAT)) {
        bundle.putFloat(key, (float) json.getDouble(JSON_VALUE));
    } else if (valueType.equals(TYPE_FLOAT_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        float[] array = new float[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = (float) jsonArray.getDouble(i);
        }
        bundle.putFloatArray(key, array);
    } else if (valueType.equals(TYPE_DOUBLE)) {
        bundle.putDouble(key, json.getDouble(JSON_VALUE));
    } else if (valueType.equals(TYPE_DOUBLE_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        double[] array = new double[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = jsonArray.getDouble(i);
        }
        bundle.putDoubleArray(key, array);
    } else if (valueType.equals(TYPE_CHAR)) {
        String charString = json.getString(JSON_VALUE);
        if (charString != null && charString.length() == 1) {
            bundle.putChar(key, charString.charAt(0));
        }
    } else if (valueType.equals(TYPE_CHAR_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        char[] array = new char[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            String charString = jsonArray.getString(i);
            if (charString != null && charString.length() == 1) {
                array[i] = charString.charAt(0);
            }
        }
        bundle.putCharArray(key, array);
    } else if (valueType.equals(TYPE_STRING)) {
        bundle.putString(key, json.getString(JSON_VALUE));
    } else if (valueType.equals(TYPE_STRING_LIST)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        int numStrings = jsonArray.length();
        ArrayList<String> stringList = new ArrayList<String>(numStrings);
        for (int i = 0; i < numStrings; i++) {
            Object jsonStringValue = jsonArray.get(i);
            stringList.add(i, jsonStringValue == JSONObject.NULL ? null : (String) jsonStringValue);
        }
        bundle.putStringArrayList(key, stringList);
    } else if (valueType.equals(TYPE_ENUM)) {
        try {
            String enumType = json.getString(JSON_VALUE_ENUM_TYPE);
            @SuppressWarnings({ "unchecked", "rawtypes" })
            Class<? extends Enum> enumClass = (Class<? extends Enum>) Class.forName(enumType);
            @SuppressWarnings("unchecked")
            Enum<?> enumValue = Enum.valueOf(enumClass, json.getString(JSON_VALUE));
            bundle.putSerializable(key, enumValue);
        } catch (ClassNotFoundException e) {
        } catch (IllegalArgumentException e) {
        }
    }
}

From source file:org.apache.sqoop.SqoopOptions.java

@SuppressWarnings("unchecked")
/**//ww w .  j ava 2s  .com
 * Given a set of properties, load this into the current SqoopOptions
 * instance.
 */
public void loadProperties(Properties props) {

    try {
        Field[] fields = SqoopOptions.class.getDeclaredFields();
        for (Field f : fields) {
            if (f.isAnnotationPresent(StoredAsProperty.class)) {
                Class typ = f.getType();
                StoredAsProperty storedAs = f.getAnnotation(StoredAsProperty.class);
                String propName = storedAs.value();

                if (typ.equals(int.class)) {
                    f.setInt(this, getIntProperty(props, propName, f.getInt(this)));
                } else if (typ.equals(boolean.class)) {
                    f.setBoolean(this, getBooleanProperty(props, propName, f.getBoolean(this)));
                } else if (typ.equals(long.class)) {
                    f.setLong(this, getLongProperty(props, propName, f.getLong(this)));
                } else if (typ.equals(String.class)) {
                    f.set(this, props.getProperty(propName, (String) f.get(this)));
                } else if (typ.equals(Integer.class)) {
                    String value = props.getProperty(propName,
                            f.get(this) == null ? "null" : f.get(this).toString());
                    f.set(this, value.equals("null") ? null : new Integer(value));
                } else if (typ.isEnum()) {
                    f.set(this, Enum.valueOf(typ, props.getProperty(propName, f.get(this).toString())));
                } else {
                    throw new RuntimeException("Could not retrieve property " + propName + " for type: " + typ);
                }
            }
        }
    } catch (IllegalAccessException iae) {
        throw new RuntimeException("Illegal access to field in property setter", iae);
    }

    // Now load properties that were stored with special types, or require
    // additional logic to set.

    if (getBooleanProperty(props, "db.require.password", false)) {
        // The user's password was stripped out from the metastore.
        // Require that the user enter it now.
        setPasswordFromConsole();
    } else {
        this.password = props.getProperty("db.password", this.password);
    }

    if (this.jarDirIsAuto) {
        // We memoized a user-specific nonce dir for compilation to the data
        // store.  Disregard that setting and create a new nonce dir.
        String localUsername = System.getProperty("user.name", "unknown");
        this.jarOutputDir = getNonceJarDir(tmpDir + "sqoop-" + localUsername + "/compile");
    }

    String colListStr = props.getProperty("db.column.list", null);
    if (null != colListStr) {
        this.columns = listToArray(colListStr);
    }

    this.inputDelimiters = getDelimiterProperties(props, "codegen.input.delimiters", this.inputDelimiters);
    this.outputDelimiters = getDelimiterProperties(props, "codegen.output.delimiters", this.outputDelimiters);

    this.extraArgs = getArgArrayProperty(props, "tool.arguments", this.extraArgs);

    this.connectionParams = getPropertiesAsNetstedProperties(props, "db.connect.params");

    // Loading user mapping
    this.mapColumnHive = getPropertiesAsNetstedProperties(props, "map.column.hive");
    this.mapColumnJava = getPropertiesAsNetstedProperties(props, "map.column.java");

    // Delimiters were previously memoized; don't let the tool override
    // them with defaults.
    this.areDelimsManuallySet = true;

    // If we loaded true verbose flag, we need to apply it
    if (this.verbose) {
        LoggingUtils.setDebugLevel();
    }

    // Custom configuration options
    this.invalidIdentifierPrefix = props.getProperty("invalid.identifier.prefix", "_");
}