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.alliander.osgp.acceptancetests.adhocmanagement.GetStatusSteps.java

@DomainStep("an ovl get status result message with result (.*), description (.*), (.*), (.*), (.*), (.*), (.*), (.*), and (.*) should be sent to the ovl out queue")
public boolean thenAnOvlGetStatusResultMessageWithResultShouldBeSentToTheOvlOutQueue(final String result,
        final String description, final String preferredLinktype, final String actualLinktype,
        final String lighttype, final String eventnotifications, final String index, final String on,
        final String dimValue) {
    LOGGER.info("THEN: an ovl get status result message with result {} should be sent to the ovl out queue",
            result);//from   w w w.  java 2s .  c o  m

    String expected;
    String actual;
    DeviceStatus deviceStatus;

    try {
        final ArgumentCaptor<ResponseMessage> argument = ArgumentCaptor.forClass(ResponseMessage.class);
        verify(this.webServiceResponseMessageSenderMock, timeout(10000).times(1)).send(argument.capture());

        // Check the result.
        expected = result.equals(NULL) ? null : result;
        actual = argument.getValue().getResult().getValue();

        Assert.assertTrue("Invalid result, found: " + actual + " , expected: " + expected,
                actual.equals(expected));

        // Check the description.
        expected = description.equals(NULL) ? null : description;
        actual = argument.getValue().getOsgpException() == null ? ""
                : argument.getValue().getOsgpException().getMessage();

        Assert.assertTrue("Invalid description, found: " + actual + " , expected: " + expected,
                actual.equals(expected));

        if (argument.getValue().getResult().getValue().equals("OK")) {
            deviceStatus = (DeviceStatus) argument.getValue().getDataObject();

            // Check if the DeviceStatus is not null.
            Assert.assertNotNull("DeviceStatus is null", deviceStatus);

            // Check the preferredLinktype.
            expected = preferredLinktype.equals(NULL) || preferredLinktype.equals(LINK_NOT_SET) ? EMPTY
                    : preferredLinktype;
            actual = deviceStatus.getPreferredLinkType() == null ? EMPTY
                    : deviceStatus.getPreferredLinkType().toString();

            Assert.assertTrue("Invalid preferredLinktype, found: " + actual + " , expected: " + expected,
                    actual.equals(expected));

            // Check the actualLinktype.
            expected = actualLinktype.equals(NULL) || actualLinktype.equals(LINK_NOT_SET) ? EMPTY
                    : actualLinktype;
            actual = deviceStatus.getActualLinkType() == null ? EMPTY
                    : deviceStatus.getActualLinkType().toString();

            Assert.assertTrue("Invalid actualLinktype, found: " + actual + " , expected: " + expected,
                    actual.equals(expected));

            // Check the lighttype.
            expected = lighttype.equals(NULL) || lighttype.equals(LT_NOT_SET) ? EMPTY : lighttype;
            actual = deviceStatus.getLightType() == null ? EMPTY : deviceStatus.getLightType().toString();

            Assert.assertTrue("Invalid lighttype, found: " + actual + " , expected: " + expected,
                    actual.equals(expected));

            // Check the eventnotifications.
            final HashSet<EventNotificationType> expectedEventNotificationTypes = new HashSet<>();
            if (StringUtils.isNotBlank(eventnotifications)) {
                for (final String event : eventnotifications.split(",")) {
                    expectedEventNotificationTypes.add(Enum.valueOf(EventNotificationType.class, event));
                }
            }
            final HashSet<EventNotificationType> actualEventNotificationTypes = new HashSet<>(
                    deviceStatus.getEventNotifications());

            Assert.assertEquals("Event notifications should equal expected value",
                    expectedEventNotificationTypes, actualEventNotificationTypes);

            // Get the list of LightValues.
            final List<com.alliander.osgp.domain.core.valueobjects.LightValue> lightValues = deviceStatus
                    .getLightValues();

            // Check if the lightValues list is not null.
            Assert.assertNotNull("lightValues list is null", lightValues);

            for (final com.alliander.osgp.domain.core.valueobjects.LightValue lightValue : lightValues) {
                // Check if the lightValue is not null.
                Assert.assertNotNull("lightValue is null", lightValue);

                // Check the on boolean.
                expected = on.equals(NULL) ? null : on;
                actual = lightValue.isOn() + "";

                Assert.assertTrue("Invalid lightValue.isOn, found: " + actual + " , expected: " + expected,
                        actual.equals(expected));

                // Check the dimValue.
                expected = dimValue.equals(NULL) ? EMPTY : dimValue;
                actual = lightValue.getDimValue() == null ? EMPTY : lightValue.getDimValue().toString();

                Assert.assertTrue("Invalid lightValue.dimValue, found: " + actual + " , expected: " + expected,
                        actual.equals(expected));

                // Check the index.
                expected = index.equals(NULL) ? null : index;
                actual = lightValue.getIndex() == null ? EMPTY : lightValue.getIndex().toString();

                Assert.assertTrue("Invalid lightValue.index, found: " + actual + " , expected: " + expected,
                        actual.equals(expected));
            }

            final List<com.alliander.osgp.domain.core.valueobjects.TariffValue> tariffValues = ((DeviceStatusMapped) deviceStatus)
                    .getTariffValues();

            Assert.assertNotNull("tariffValues is null", tariffValues);

            for (final com.alliander.osgp.domain.core.valueobjects.TariffValue tariffValue : tariffValues) {
                Assert.assertNotNull("tariffValue is null", tariffValue);

                switch (this.deviceRelayType) {
                case LIGHT:
                    // Do nothing.
                    break;
                case TARIFF:
                    Assert.assertEquals("RelayType.TARIFF", on, (!tariffValue.isHigh()) + "");
                    break;
                case TARIFF_REVERSED:
                    Assert.assertEquals("RelayType.TARIFF_REVERSED", on, (tariffValue.isHigh()) + "");
                    break;
                default:
                    // Do nothing.
                    break;
                }
            }
        }
    } catch (final Throwable t) {
        LOGGER.error("Exception [{}]: {}", t.getClass().getSimpleName(), t.getMessage());
        return false;
    }

    return true;
}

From source file:org.dasein.persist.PersistentCache.java

@SuppressWarnings({ "rawtypes", "unchecked" })
protected Object mapValue(String fieldName, Object dataStoreValue, Class<?> toType, ParameterizedType ptype)
        throws PersistenceException {
    LookupDelegate delegate = getLookupDelegate(fieldName);

    if (dataStoreValue != null && delegate != null && !delegate.validate(dataStoreValue.toString())) {
        throw new PersistenceException("Value " + dataStoreValue + " for " + fieldName + " is not valid.");
    }//from   w  w  w .jav a  2s .  co  m
    try {
        if (toType.equals(String.class)) {
            if (dataStoreValue != null && !(dataStoreValue instanceof String)) {
                dataStoreValue = dataStoreValue.toString();
            }
        } else if (Enum.class.isAssignableFrom(toType)) {
            if (dataStoreValue != null) {
                Enum e = Enum.valueOf((Class<? extends Enum>) toType, dataStoreValue.toString());

                dataStoreValue = e;
            }
        } else if (toType.equals(Boolean.class) || toType.equals(boolean.class)) {
            if (dataStoreValue == null) {
                dataStoreValue = false;
            } else if (!(dataStoreValue instanceof Boolean)) {
                if (Number.class.isAssignableFrom(dataStoreValue.getClass())) {
                    dataStoreValue = (((Number) dataStoreValue).intValue() != 0);
                } else {
                    dataStoreValue = (dataStoreValue.toString().trim().equalsIgnoreCase("true")
                            || dataStoreValue.toString().trim().equalsIgnoreCase("y"));
                }
            }
        } else if (Number.class.isAssignableFrom(toType) || toType.equals(byte.class)
                || toType.equals(short.class) || toType.equals(long.class) || toType.equals(int.class)
                || toType.equals(float.class) || toType.equals(double.class)) {
            if (dataStoreValue == null) {
                if (toType.equals(int.class) || toType.equals(short.class) || toType.equals(long.class)) {
                    dataStoreValue = 0;
                } else if (toType.equals(float.class) || toType.equals(double.class)) {
                    dataStoreValue = 0.0f;
                }
            } else if (toType.equals(Number.class)) {
                if (!(dataStoreValue instanceof Number)) {
                    if (dataStoreValue instanceof String) {
                        try {
                            dataStoreValue = Double.parseDouble((String) dataStoreValue);
                        } catch (NumberFormatException e) {
                            throw new PersistenceException("Unable to map " + fieldName + " as " + toType
                                    + " using " + dataStoreValue);
                        }
                    } else if (dataStoreValue instanceof Boolean) {
                        dataStoreValue = (((Boolean) dataStoreValue) ? 1 : 0);
                    } else {
                        throw new PersistenceException(
                                "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                    }
                }
            } else if (toType.equals(Integer.class) || toType.equals(int.class)) {
                if (dataStoreValue instanceof Number) {
                    if (!(dataStoreValue instanceof Integer)) {
                        dataStoreValue = ((Number) dataStoreValue).intValue();
                    }
                } else if (dataStoreValue instanceof String) {
                    try {
                        dataStoreValue = Integer.parseInt((String) dataStoreValue);
                    } catch (NumberFormatException e) {
                        throw new PersistenceException(
                                "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                    }
                } else if (dataStoreValue instanceof Boolean) {
                    dataStoreValue = (((Boolean) dataStoreValue) ? 1 : 0);
                } else {
                    throw new PersistenceException(
                            "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                }
            } else if (toType.equals(Long.class) || toType.equals(long.class)) {
                if (dataStoreValue instanceof Number) {
                    if (!(dataStoreValue instanceof Long)) {
                        dataStoreValue = ((Number) dataStoreValue).longValue();
                    }
                } else if (dataStoreValue instanceof String) {
                    try {
                        dataStoreValue = Long.parseLong((String) dataStoreValue);
                    } catch (NumberFormatException e) {
                        throw new PersistenceException(
                                "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                    }
                } else if (dataStoreValue instanceof Boolean) {
                    dataStoreValue = (((Boolean) dataStoreValue) ? 1L : 0L);
                } else {
                    throw new PersistenceException(
                            "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                }
            } else if (toType.equals(Byte.class) || toType.equals(byte.class)) {
                if (dataStoreValue instanceof Number) {
                    if (!(dataStoreValue instanceof Byte)) {
                        dataStoreValue = ((Number) dataStoreValue).byteValue();
                    }
                } else if (dataStoreValue instanceof String) {
                    try {
                        dataStoreValue = Byte.parseByte((String) dataStoreValue);
                    } catch (NumberFormatException e) {
                        throw new PersistenceException(
                                "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                    }
                } else if (dataStoreValue instanceof Boolean) {
                    dataStoreValue = (((Boolean) dataStoreValue) ? 1 : 0);
                } else {
                    throw new PersistenceException(
                            "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                }
            } else if (toType.equals(Short.class) || toType.equals(short.class)) {
                if (dataStoreValue instanceof Number) {
                    if (!(dataStoreValue instanceof Short)) {
                        dataStoreValue = ((Number) dataStoreValue).shortValue();
                    }
                } else if (dataStoreValue instanceof String) {
                    try {
                        dataStoreValue = Short.parseShort((String) dataStoreValue);
                    } catch (NumberFormatException e) {
                        throw new PersistenceException(
                                "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                    }
                } else if (dataStoreValue instanceof Boolean) {
                    dataStoreValue = (((Boolean) dataStoreValue) ? 1 : 0);
                } else {
                    throw new PersistenceException(
                            "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                }
            } else if (toType.equals(Double.class) || toType.equals(double.class)) {
                if (dataStoreValue instanceof Number) {
                    if (!(dataStoreValue instanceof Double)) {
                        dataStoreValue = ((Number) dataStoreValue).doubleValue();
                    }
                } else if (dataStoreValue instanceof String) {
                    try {
                        dataStoreValue = Double.parseDouble((String) dataStoreValue);
                    } catch (NumberFormatException e) {
                        throw new PersistenceException(
                                "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                    }
                } else if (dataStoreValue instanceof Boolean) {
                    dataStoreValue = (((Boolean) dataStoreValue) ? 1.0 : 0.0);
                } else {
                    throw new PersistenceException(
                            "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                }
            } else if (toType.equals(Float.class) || toType.equals(float.class)) {
                if (dataStoreValue instanceof Number) {
                    if (!(dataStoreValue instanceof Float)) {
                        dataStoreValue = ((Number) dataStoreValue).floatValue();
                    }
                } else if (dataStoreValue instanceof String) {
                    try {
                        dataStoreValue = Float.parseFloat((String) dataStoreValue);
                    } catch (NumberFormatException e) {
                        throw new PersistenceException(
                                "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                    }
                } else if (dataStoreValue instanceof Boolean) {
                    dataStoreValue = (((Boolean) dataStoreValue) ? 1.0f : 0.0f);
                } else {
                    throw new PersistenceException(
                            "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                }
            } else if (toType.equals(BigDecimal.class)) {
                if (dataStoreValue instanceof Number) {
                    if (!(dataStoreValue instanceof BigDecimal)) {
                        if (dataStoreValue instanceof BigInteger) {
                            dataStoreValue = new BigDecimal((BigInteger) dataStoreValue);
                        } else {
                            dataStoreValue = BigDecimal.valueOf(((Number) dataStoreValue).doubleValue());
                        }
                    }
                } else if (dataStoreValue instanceof String) {
                    try {
                        dataStoreValue = new BigDecimal((String) dataStoreValue);
                    } catch (NumberFormatException e) {
                        throw new PersistenceException(
                                "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                    }
                } else if (dataStoreValue instanceof Boolean) {
                    dataStoreValue = new BigDecimal((((Boolean) dataStoreValue) ? 1.0 : 0.0));
                } else {
                    throw new PersistenceException(
                            "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                }
            } else if (toType.equals(BigInteger.class)) {
                if (dataStoreValue instanceof Number) {
                    if (!(dataStoreValue instanceof BigInteger)) {
                        if (dataStoreValue instanceof BigDecimal) {
                            dataStoreValue = ((BigDecimal) dataStoreValue).toBigInteger();
                        } else {
                            dataStoreValue = BigInteger.valueOf(((Number) dataStoreValue).longValue());
                        }
                    }
                } else if (dataStoreValue instanceof String) {
                    try {
                        dataStoreValue = new BigDecimal((String) dataStoreValue);
                    } catch (NumberFormatException e) {
                        throw new PersistenceException(
                                "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                    }
                } else if (dataStoreValue instanceof Boolean) {
                    dataStoreValue = new BigDecimal((((Boolean) dataStoreValue) ? 1.0 : 0.0));
                } else {
                    throw new PersistenceException(
                            "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                }
            } else if (dataStoreValue != null) {
                logger.error("Type of dataStoreValue=" + dataStoreValue.getClass());
                throw new PersistenceException(
                        "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
            }
        } else if (toType.equals(Locale.class)) {
            if (dataStoreValue != null && !(dataStoreValue instanceof Locale)) {
                String[] parts = dataStoreValue.toString().split("_");

                if (parts != null && parts.length > 1) {
                    dataStoreValue = new Locale(parts[0], parts[1]);
                } else {
                    dataStoreValue = new Locale(parts[0]);
                }
            }
        } else if (Measured.class.isAssignableFrom(toType)) {
            if (dataStoreValue != null && ptype != null) {
                if (Number.class.isAssignableFrom(dataStoreValue.getClass())) {
                    Constructor<? extends Measured> constructor = null;
                    double value = ((Number) dataStoreValue).doubleValue();

                    for (Constructor<?> c : toType.getDeclaredConstructors()) {
                        Class[] args = c.getParameterTypes();

                        if (args != null && args.length == 2 && Number.class.isAssignableFrom(args[0])
                                && UnitOfMeasure.class.isAssignableFrom(args[1])) {
                            constructor = (Constructor<? extends Measured>) c;
                            break;
                        }
                    }
                    if (constructor == null) {
                        throw new PersistenceException("Unable to map with no proper constructor");
                    }
                    dataStoreValue = constructor.newInstance(value,
                            ((Class<?>) ptype.getActualTypeArguments()[0]).newInstance());
                } else if (!(dataStoreValue instanceof Measured)) {
                    try {
                        dataStoreValue = Double.parseDouble(dataStoreValue.toString());
                    } catch (NumberFormatException e) {
                        Method method = null;

                        for (Method m : toType.getDeclaredMethods()) {
                            if (Modifier.isStatic(m.getModifiers()) && m.getName().equals("valueOf")) {
                                if (m.getParameterTypes().length == 1
                                        && m.getParameterTypes()[0].equals(String.class)) {
                                    method = m;
                                    break;
                                }
                            }
                        }
                        if (method == null) {
                            throw new PersistenceException("Don't know how to map " + dataStoreValue + " to "
                                    + toType + "<" + ptype + ">");
                        }
                        dataStoreValue = method.invoke(null, dataStoreValue.toString());
                    }
                }
                // just because we converted it to a measured object above doesn't mean
                // we have the unit of measure right
                if (dataStoreValue instanceof Measured) {
                    UnitOfMeasure targetUom = (UnitOfMeasure) ((Class<?>) ptype.getActualTypeArguments()[0])
                            .newInstance();

                    if (!(((Measured) dataStoreValue).getUnitOfMeasure()).equals(targetUom)) {
                        dataStoreValue = ((Measured) dataStoreValue).convertTo(
                                (UnitOfMeasure) ((Class<?>) ptype.getActualTypeArguments()[0]).newInstance());
                    }
                }
            }
        } else if (toType.equals(UUID.class)) {
            if (dataStoreValue != null && !(dataStoreValue instanceof UUID)) {
                dataStoreValue = UUID.fromString(dataStoreValue.toString());
            }
        } else if (toType.equals(TimeZone.class)) {
            if (dataStoreValue != null && !(dataStoreValue instanceof TimeZone)) {
                dataStoreValue = TimeZone.getTimeZone(dataStoreValue.toString());
            }
        } else if (toType.equals(Currency.class)) {
            if (dataStoreValue != null && !(dataStoreValue instanceof Currency)) {
                dataStoreValue = Currency.getInstance(dataStoreValue.toString());
            }
        } else if (toType.isArray()) {
            Class<?> t = toType.getComponentType();

            if (dataStoreValue == null) {
                dataStoreValue = Array.newInstance(t, 0);
            } else if (dataStoreValue instanceof JSONArray) {
                JSONArray arr = (JSONArray) dataStoreValue;

                if (long.class.isAssignableFrom(t)) {
                    long[] replacement = (long[]) Array.newInstance(long.class, arr.length());

                    for (int i = 0; i < arr.length(); i++) {
                        replacement[i] = (Long) mapValue(fieldName, arr.get(i), t, null);
                    }
                    dataStoreValue = replacement;
                } else if (int.class.isAssignableFrom(t)) {
                    int[] replacement = (int[]) Array.newInstance(int.class, arr.length());

                    for (int i = 0; i < arr.length(); i++) {
                        replacement[i] = (Integer) mapValue(fieldName, arr.get(i), t, null);
                    }
                    dataStoreValue = replacement;
                } else if (float.class.isAssignableFrom(t)) {
                    float[] replacement = (float[]) Array.newInstance(float.class, arr.length());

                    for (int i = 0; i < arr.length(); i++) {
                        replacement[i] = (Float) mapValue(fieldName, arr.get(i), t, null);
                    }
                    dataStoreValue = replacement;
                } else if (double.class.isAssignableFrom(t)) {
                    double[] replacement = (double[]) Array.newInstance(double.class, arr.length());

                    for (int i = 0; i < arr.length(); i++) {
                        replacement[i] = (Double) mapValue(fieldName, arr.get(i), t, null);
                    }
                    dataStoreValue = replacement;
                } else if (boolean.class.isAssignableFrom(t)) {
                    boolean[] replacement = (boolean[]) Array.newInstance(boolean.class, arr.length());

                    for (int i = 0; i < arr.length(); i++) {
                        replacement[i] = (Boolean) mapValue(fieldName, arr.get(i), t, null);
                    }
                    dataStoreValue = replacement;
                } else {
                    Object[] replacement = (Object[]) Array.newInstance(t, arr.length());

                    for (int i = 0; i < arr.length(); i++) {
                        replacement[i] = mapValue(fieldName, arr.get(i), t, null);
                    }
                    dataStoreValue = replacement;
                }
            } else if (!dataStoreValue.getClass().isArray()) {
                logger.error("Unable to map data store type " + dataStoreValue.getClass().getName() + " to "
                        + toType.getName());
                logger.error("Value of " + fieldName + "=" + dataStoreValue);
                throw new PersistenceException("Data store type=" + dataStoreValue.getClass().getName());
            }
        } else if (dataStoreValue != null && !toType.isAssignableFrom(dataStoreValue.getClass())) {
            Annotation[] alist = toType.getDeclaredAnnotations();
            boolean autoJSON = false;

            for (Annotation a : alist) {
                if (a instanceof AutoJSON) {
                    autoJSON = true;
                }
            }
            if (autoJSON) {
                dataStoreValue = autoDeJSON(toType, (JSONObject) dataStoreValue);
            } else {
                try {
                    Method m = toType.getDeclaredMethod("valueOf", JSONObject.class);

                    dataStoreValue = m.invoke(null, dataStoreValue);
                } catch (NoSuchMethodException ignore) {
                    try {
                        Method m = toType.getDeclaredMethod("valueOf", String.class);

                        if (m != null) {
                            dataStoreValue = m.invoke(null, dataStoreValue.toString());
                        } else {
                            throw new PersistenceException(
                                    "No valueOf() field in " + toType + " for mapping " + fieldName);
                        }
                    } catch (NoSuchMethodException e) {
                        throw new PersistenceException("No valueOf() field in " + toType + " for mapping "
                                + fieldName + " with " + dataStoreValue + ": ("
                                + dataStoreValue.getClass().getName() + " vs " + toType.getName() + ")");
                    }
                }
            }
        }
    } catch (Exception e) {
        String err = "Error mapping field in " + toType + " for " + fieldName + ": " + e.getMessage();
        logger.error(err, e);
        throw new PersistenceException();
    }
    return dataStoreValue;
}

From source file:com.microsoft.azure.management.compute.ComputeManagementClientImpl.java

/**
* The Get Operation Status operation returns the status of the specified
* operation. After calling an asynchronous operation, you can call
* GetLongRunningOperationStatus to determine whether the operation has
* succeeded, failed, or is still in progress.
*
* @param operationStatusLink Required. Location value returned by the Begin
* operation.//from www. j av  a2s . c  o  m
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return The Compute service response for long-running operations.
*/
@Override
public ComputeLongRunningOperationResponse getLongRunningOperationStatus(String operationStatusLink)
        throws IOException, ServiceException {
    // Validate
    if (operationStatusLink == null) {
        throw new NullPointerException("operationStatusLink");
    }

    // Tracing
    boolean shouldTrace = CloudTracing.getIsEnabled();
    String invocationId = null;
    if (shouldTrace) {
        invocationId = Long.toString(CloudTracing.getNextInvocationId());
        HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
        tracingParameters.put("operationStatusLink", operationStatusLink);
        CloudTracing.enter(invocationId, this, "getLongRunningOperationStatusAsync", tracingParameters);
    }

    // Construct URL
    String url = "";
    url = url + operationStatusLink;
    url = url.replace(" ", "%20");

    // Create HTTP transport objects
    HttpGet httpRequest = new HttpGet(url);

    // Set Headers

    // Send Request
    HttpResponse httpResponse = null;
    try {
        if (shouldTrace) {
            CloudTracing.sendRequest(invocationId, httpRequest);
        }
        httpResponse = this.getHttpClient().execute(httpRequest);
        if (shouldTrace) {
            CloudTracing.receiveResponse(invocationId, httpResponse);
        }
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_ACCEPTED) {
            ServiceException ex = ServiceException.createFromJson(httpRequest, null, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

        // Create Result
        ComputeLongRunningOperationResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_ACCEPTED) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new ComputeLongRunningOperationResponse();
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode responseDoc = null;
            String responseDocContent = IOUtils.toString(responseContent);
            if (responseDocContent == null == false && responseDocContent.length() > 0) {
                responseDoc = objectMapper.readTree(responseDocContent);
            }

            if (responseDoc != null && responseDoc instanceof NullNode == false) {
                JsonNode operationIdValue = responseDoc.get("operationId");
                if (operationIdValue != null && operationIdValue instanceof NullNode == false) {
                    String operationIdInstance;
                    operationIdInstance = operationIdValue.getTextValue();
                    result.setTrackingOperationId(operationIdInstance);
                }

                JsonNode statusValue = responseDoc.get("status");
                if (statusValue != null && statusValue instanceof NullNode == false) {
                    ComputeOperationStatus statusInstance;
                    statusInstance = Enum.valueOf(ComputeOperationStatus.class, statusValue.getTextValue());
                    result.setStatus(statusInstance);
                }

                JsonNode startTimeValue = responseDoc.get("startTime");
                if (startTimeValue != null && startTimeValue instanceof NullNode == false) {
                    Calendar startTimeInstance;
                    startTimeInstance = DatatypeConverter.parseDateTime(startTimeValue.getTextValue());
                    result.setStartTime(startTimeInstance);
                }

                JsonNode endTimeValue = responseDoc.get("endTime");
                if (endTimeValue != null && endTimeValue instanceof NullNode == false) {
                    Calendar endTimeInstance;
                    endTimeInstance = DatatypeConverter.parseDateTime(endTimeValue.getTextValue());
                    result.setEndTime(endTimeInstance);
                }

                JsonNode propertiesValue = responseDoc.get("properties");
                if (propertiesValue != null && propertiesValue instanceof NullNode == false) {
                    JsonNode outputValue = propertiesValue.get("output");
                    if (outputValue != null && outputValue instanceof NullNode == false) {
                        String outputInstance;
                        outputInstance = outputValue.getTextValue();
                        result.setOutput(outputInstance);
                    }
                }

                JsonNode errorValue = responseDoc.get("error");
                if (errorValue != null && errorValue instanceof NullNode == false) {
                    ApiError errorInstance = new ApiError();
                    result.setError(errorInstance);

                    JsonNode detailsArray = errorValue.get("details");
                    if (detailsArray != null && detailsArray instanceof NullNode == false) {
                        for (JsonNode detailsValue : ((ArrayNode) detailsArray)) {
                            ApiErrorBase apiErrorBaseInstance = new ApiErrorBase();
                            errorInstance.getDetails().add(apiErrorBaseInstance);

                            JsonNode codeValue = detailsValue.get("code");
                            if (codeValue != null && codeValue instanceof NullNode == false) {
                                String codeInstance;
                                codeInstance = codeValue.getTextValue();
                                apiErrorBaseInstance.setCode(codeInstance);
                            }

                            JsonNode targetValue = detailsValue.get("target");
                            if (targetValue != null && targetValue instanceof NullNode == false) {
                                String targetInstance;
                                targetInstance = targetValue.getTextValue();
                                apiErrorBaseInstance.setTarget(targetInstance);
                            }

                            JsonNode messageValue = detailsValue.get("message");
                            if (messageValue != null && messageValue instanceof NullNode == false) {
                                String messageInstance;
                                messageInstance = messageValue.getTextValue();
                                apiErrorBaseInstance.setMessage(messageInstance);
                            }
                        }
                    }

                    JsonNode innererrorValue = errorValue.get("innererror");
                    if (innererrorValue != null && innererrorValue instanceof NullNode == false) {
                        InnerError innererrorInstance = new InnerError();
                        errorInstance.setInnerError(innererrorInstance);

                        JsonNode exceptiontypeValue = innererrorValue.get("exceptiontype");
                        if (exceptiontypeValue != null && exceptiontypeValue instanceof NullNode == false) {
                            String exceptiontypeInstance;
                            exceptiontypeInstance = exceptiontypeValue.getTextValue();
                            innererrorInstance.setExceptionType(exceptiontypeInstance);
                        }

                        JsonNode errordetailValue = innererrorValue.get("errordetail");
                        if (errordetailValue != null && errordetailValue instanceof NullNode == false) {
                            String errordetailInstance;
                            errordetailInstance = errordetailValue.getTextValue();
                            innererrorInstance.setErrorDetail(errordetailInstance);
                        }
                    }

                    JsonNode codeValue2 = errorValue.get("code");
                    if (codeValue2 != null && codeValue2 instanceof NullNode == false) {
                        String codeInstance2;
                        codeInstance2 = codeValue2.getTextValue();
                        errorInstance.setCode(codeInstance2);
                    }

                    JsonNode targetValue2 = errorValue.get("target");
                    if (targetValue2 != null && targetValue2 instanceof NullNode == false) {
                        String targetInstance2;
                        targetInstance2 = targetValue2.getTextValue();
                        errorInstance.setTarget(targetInstance2);
                    }

                    JsonNode messageValue2 = errorValue.get("message");
                    if (messageValue2 != null && messageValue2 instanceof NullNode == false) {
                        String messageInstance2;
                        messageInstance2 = messageValue2.getTextValue();
                        errorInstance.setMessage(messageInstance2);
                    }
                }
            }

        }
        result.setStatusCode(statusCode);
        if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
            result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
        }

        if (shouldTrace) {
            CloudTracing.exit(invocationId, result);
        }
        return result;
    } finally {
        if (httpResponse != null && httpResponse.getEntity() != null) {
            httpResponse.getEntity().getContent().close();
        }
    }
}

From source file:org.roda.core.index.utils.SolrUtils.java

private static <E extends Enum<E>> E objectToEnum(Object object, Class<E> enumeration, E defaultValue) {
    E ret = defaultValue;// w  w  w  .j  a v  a  2 s  . c  o  m
    if (object != null) {
        if (object instanceof String) {
            String name = (String) object;
            try {
                ret = Enum.valueOf(enumeration, name);
            } catch (IllegalArgumentException e) {
                LOGGER.warn("Invalid name for enumeration: {}, name: {}", enumeration.getName(), name);
            } catch (NullPointerException e) {
                LOGGER.warn("Error parsing enumeration: {}, name: {}", enumeration.getName(), name);
            }
        } else {
            LOGGER.warn("Could not convert Solr object to enumeration: {}, unsupported class: {}",
                    enumeration.getName(), object.getClass().getName());
        }
    }
    return ret;
}

From source file:org.diffkit.db.DKDBType.java

/**
 * will simply return null if argument is not recognized, instead of throwing
 *//*from   w w  w  .j a v a2 s  .  c o  m*/
public static DKDBType forName(String name_) {
    if (IS_DEBUG_ENABLED)
        LOG.debug("name_->{}", name_);
    if (name_ == null)
        return null;

    try {
        DKDBType forName = Enum.valueOf(DKDBType.class, name_);
        if (IS_DEBUG_ENABLED)
            LOG.debug("forName->{}", forName);
        return forName;
    } catch (Exception e_) {
        return null;
    }
}

From source file:com.alliander.osgp.acceptancetests.configurationmanagement.GetConfigurationDataSteps.java

@DomainStep("a get configuration response message with correlationId (.*), deviceId (.*), qresult (.*), qdescription (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*) is found in the queue (.*)")
public void givenAGetConfigurationResponseMessageIsFoundInQueue(final String correlationId,
        final String deviceId, final String qresult, final String qdescription, final String lightType,
        final String dcLights, final String dcMap, final String rcType, final String rcMap,
        final String shortInterval, final String preferredLinkType, final String meterType,
        final String longInterval, final String longIntervalType, final Boolean isFound) {
    LOGGER.info(/*  w w w .ja  v  a 2 s  .c  om*/
            "GIVEN: \"a get configuration 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 com.alliander.osgp.domain.core.valueobjects.LightType lighttype = StringUtils
                        .isBlank(lightType) ? null
                                : Enum.valueOf(com.alliander.osgp.domain.core.valueobjects.LightType.class,
                                        lightType);
                final Map<Integer, Integer> indexAddressMap = new HashMap<Integer, Integer>();

                final com.alliander.osgp.domain.core.valueobjects.DaliConfiguration daliconfiguration = new com.alliander.osgp.domain.core.valueobjects.DaliConfiguration(
                        22, indexAddressMap);

                final List<com.alliander.osgp.domain.core.valueobjects.RelayMap> relayMap = new ArrayList<>();
                final com.alliander.osgp.domain.core.valueobjects.RelayConfiguration relayConf = new com.alliander.osgp.domain.core.valueobjects.RelayConfiguration(
                        relayMap);

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

                final Integer shortinterval = StringUtils.isBlank(shortInterval) ? 0
                        : Integer.valueOf(shortInterval);
                final Integer longinterval = StringUtils.isBlank(longInterval) ? 0
                        : Integer.valueOf(longInterval);

                // construct new Configuration
                dataObject = new com.alliander.osgp.domain.core.valueobjects.Configuration(lighttype,
                        daliconfiguration, relayConf, shortinterval, LinkType.ETHERNET, metertype, longinterval,
                        longtermintervalType);
            }

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

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

        } catch (final JMSException e) {
            e.printStackTrace();
        }

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

From source file:com.zenesis.qx.remote.RequestHandler.java

/**
 * Handles creating a server object to match one created on the client; expects className,
 * clientId, properties//from www  .ja va  2 s  . co  m
 * @param jp
 * @throws ServletException
 * @throws IOException
 */
protected void cmdNewObject(JsonParser jp) throws ServletException, IOException {
    // Get the basics
    String className = getFieldValue(jp, "className", String.class);
    int clientId = getFieldValue(jp, "clientId", Integer.class);

    // Get the class
    Class<? extends Proxied> clazz;
    try {
        clazz = (Class<? extends Proxied>) Class.forName(className);
    } catch (ClassNotFoundException e) {
        throw new ServletException("Unknown class " + className);
    }
    ProxyType type = ProxyTypeManager.INSTANCE.getProxyType(clazz);

    // Create the instance
    Proxied proxied;
    try {
        proxied = type.newInstance(clazz);
    } catch (InstantiationException e) {
        throw new ServletException("Cannot create class " + className + ": " + e.getMessage(), e);
    } catch (InvocationTargetException e) {
        throw new ServletException("Cannot create class " + className + ": " + e.getMessage(), e);
    } catch (IllegalAccessException e) {
        throw new ServletException("Cannot create class " + className + ": " + e.getMessage(), e);
    }

    // Get the server ID
    int serverId = tracker.addClientObject(proxied);

    // Remember the client ID, in case there are subsequent commands which refer to it
    if (clientObjects == null)
        clientObjects = new HashMap<Integer, Proxied>();
    clientObjects.put(clientId, proxied);

    // Tell the client about the new ID - do this before changing properties
    tracker.invalidateCache(proxied);
    tracker.getQueue().queueCommand(CommandId.CommandType.MAP_CLIENT_ID, proxied, null,
            new MapClientId(serverId, clientId));

    // Set property values
    if (jp.nextToken() == JsonToken.FIELD_NAME) {
        if (jp.nextToken() != JsonToken.START_OBJECT)
            throw new ServletException("Unexpected properties definiton for 'new' command");
        while (jp.nextToken() != JsonToken.END_OBJECT) {
            String propertyName = jp.getCurrentName();
            jp.nextToken();

            // Read a Proxied object?  
            ProxyProperty prop = getProperty(type, propertyName);
            MetaClass propClass = prop.getPropertyClass();
            Object value = null;
            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 {
                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, proxied, propertyName, value);
        }
    }

    // Done
    jp.nextToken();
}

From source file:org.geosamples.samples.Samples.java

private static <T extends Enum<T>> boolean checkThatValueIsLegal(Class<T> enumType, String name,
        boolean required) {
    boolean isLegal = (name != null);
    if (isLegal) {
        try {//from  w ww.j  a v  a2 s  .  c  om
            Enum.valueOf(enumType, name.toUpperCase());
        } catch (IllegalArgumentException e) {
            isLegal = false;
        }
    } else {
        isLegal = !required;
    }

    return isLegal;
}

From source file:edu.duke.cabig.c3pr.domain.StudyVersion.java

public void setAmendmentReasonsInternal(String amendmentReason) {
    amendmentReasons = new ArrayList<StudyPart>();
    if (!StringUtils.isBlank(amendmentReason)) {
        StringTokenizer tokenizer = new StringTokenizer(amendmentReason, " : ");
        while (tokenizer.hasMoreTokens()) {
            StudyPart reason = (StudyPart) Enum.valueOf(StudyPart.class, tokenizer.nextToken());
            amendmentReasons.add(reason);
        }/* w  w w .j  a  va2 s .c  o m*/
        ;
    }
}

From source file:org.apache.hadoop.hive.metastore.utils.MetaStoreUtils.java

public static WMPoolSchedulingPolicy parseSchedulingPolicy(String schedulingPolicy) {
    if (schedulingPolicy == null) {
        return WMPoolSchedulingPolicy.FAIR;
    }/*  www.jav  a  2s  .c o  m*/
    schedulingPolicy = schedulingPolicy.trim().toUpperCase();
    if ("DEFAULT".equals(schedulingPolicy)) {
        return WMPoolSchedulingPolicy.FAIR;
    }
    return Enum.valueOf(WMPoolSchedulingPolicy.class, schedulingPolicy);
}