Example usage for com.google.gson JsonElement getAsJsonPrimitive

List of usage examples for com.google.gson JsonElement getAsJsonPrimitive

Introduction

In this page you can find the example usage for com.google.gson JsonElement getAsJsonPrimitive.

Prototype

public JsonPrimitive getAsJsonPrimitive() 

Source Link

Document

convenience method to get this element as a JsonPrimitive .

Usage

From source file:org.onebusaway.admin.json.JodaLocalDateAdapter.java

License:Apache License

@Override
public LocalDate deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {

    DateTimeFormatter fmt = DateTimeFormat.forPattern(OneBusAwayDateFormats.DATETIMEPATTERN_DATE);
    LocalDate result = fmt.parseLocalDate(json.getAsJsonPrimitive().getAsString());

    return result;
}

From source file:org.openbase.bco.registry.location.core.dbconvert.LocationConfig_2_To_3_DBConverter.java

License:Open Source License

@Override
public JsonObject upgrade(JsonObject locationConfig, final Map<File, JsonObject> dbSnapshot) {
    String oldId = locationConfig.getAsJsonPrimitive("id").getAsString();
    String newId = UUID.randomUUID().toString();

    locationConfig.remove("id");
    locationConfig.add("id", new JsonPrimitive(newId));

    for (JsonObject location : dbSnapshot.values()) {
        if (location.getAsJsonPrimitive("id").getAsString().equals(oldId)) {
            // set new id here?
            continue;
        }//w  ww. j  ava2s .  c  o  m

        // change parent_id in all location if needed to the new id
        if (location.getAsJsonPrimitive("parent_id") != null
                && location.getAsJsonPrimitive("parent_id").getAsString().equals(oldId)) {
            location.remove("parent_id");
            location.add("parent_id", new JsonPrimitive(newId));
        }

        // adjust the child ids if needed
        if (location.getAsJsonArray("child_id") == null) {
            continue;
        }
        JsonArray childIdArray = new JsonArray();
        for (JsonElement childId : location.getAsJsonArray("child_id")) {
            if (childId.getAsJsonPrimitive().getAsString().equals(oldId)) {
                childIdArray.add(newId);
            } else {
                childIdArray.add(childId.getAsJsonPrimitive().getAsString());
            }
        }
        location.remove("child_id");
        location.add("child_id", childIdArray);
    }

    return locationConfig;
}

From source file:org.openbaton.plugin.utils.PluginCaller.java

License:Apache License

public Serializable executeRPC(String methodName, Collection<Serializable> args, Type returnType)
        throws IOException, InterruptedException, PluginException {

    Channel channel = connection.createChannel();
    String replyQueueName = channel.queueDeclare().getQueue();
    String exchange = "plugin-exchange";
    channel.queueBind(replyQueueName, exchange, replyQueueName);
    QueueingConsumer consumer = new QueueingConsumer(channel);
    String consumerTag = channel.basicConsume(replyQueueName, true, consumer);

    //Check if plugin is still up
    if (!RabbitManager.getQueues(brokerIp, username, password, managementPort).contains(pluginId))
        throw new PluginException("Plugin with id: " + pluginId + " not existing anymore...");

    String response;/*from www .j  a v  a 2  s.  c  o m*/
    String corrId = UUID.randomUUID().toString();
    PluginMessage pluginMessage = new PluginMessage();
    pluginMessage.setMethodName(methodName);
    pluginMessage.setParameters(args);
    String message = gson.toJson(pluginMessage);

    BasicProperties props = new Builder().correlationId(corrId).replyTo(replyQueueName).build();

    channel.basicPublish(exchange, pluginId, props, message.getBytes());

    if (returnType != null) {

        while (true) {
            Delivery delivery = consumer.nextDelivery();
            if (delivery.getProperties().getCorrelationId().equals(corrId)) {
                response = new String(delivery.getBody());
                log.trace("received: " + response);
                break;
            } else {
                log.error("Received Message with wrong correlation id");
                throw new PluginException(
                        "Received Message with wrong correlation id. This should not happen, if it does please call us.");
            }
        }

        channel.queueDelete(replyQueueName);
        try {
            channel.close();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
        JsonObject jsonObject = gson.fromJson(response, JsonObject.class);

        JsonElement exceptionJson = jsonObject.get("exception");
        if (exceptionJson == null) {
            JsonElement answerJson = jsonObject.get("answer");

            Serializable ret = null;

            if (answerJson.isJsonPrimitive()) {
                ret = gson.fromJson(answerJson.getAsJsonPrimitive(), returnType);
            } else if (answerJson.isJsonArray()) {
                ret = gson.fromJson(answerJson.getAsJsonArray(), returnType);
            } else
                ret = gson.fromJson(answerJson.getAsJsonObject(), returnType);

            log.trace("answer is: " + ret);
            return ret;
        } else {
            PluginException pluginException;
            try {
                pluginException = new PluginException(
                        gson.fromJson(exceptionJson.getAsJsonObject(), VimDriverException.class));
                log.debug("Got Vim Driver Exception with server: "
                        + ((VimDriverException) pluginException.getCause()).getServer());
            } catch (Exception ignored) {
                pluginException = new PluginException(
                        gson.fromJson(exceptionJson.getAsJsonObject(), Throwable.class));
            }
            throw pluginException;
        }
    } else
        return null;
}

From source file:org.opendaylight.controller.sal.rest.impl.JsonToCompositeNodeReader.java

License:Open Source License

private static void addChildToParent(final String childName, final JsonElement childType,
        final CompositeNodeWrapper parent) {
    if (childType.isJsonObject()) {
        CompositeNodeWrapper child = new CompositeNodeWrapper(getNamespaceFor(childName),
                getLocalNameFor(childName));
        parent.addValue(child);/*from  ww  w. j  a va  2 s. com*/
        for (Entry<String, JsonElement> childOfChild : childType.getAsJsonObject().entrySet()) {
            addChildToParent(childOfChild.getKey(), childOfChild.getValue(), child);
        }
    } else if (childType.isJsonArray()) {
        if (childType.getAsJsonArray().size() == 1 && childType.getAsJsonArray().get(0).isJsonNull()) {
            parent.addValue(new EmptyNodeWrapper(getNamespaceFor(childName), getLocalNameFor(childName)));

        } else {
            for (JsonElement childOfChildType : childType.getAsJsonArray()) {
                addChildToParent(childName, childOfChildType, parent);
            }
        }
    } else if (childType.isJsonPrimitive()) {
        JsonPrimitive childPrimitive = childType.getAsJsonPrimitive();
        String value = childPrimitive.getAsString().trim();
        parent.addValue(new SimpleNodeWrapper(getNamespaceFor(childName), getLocalNameFor(childName),
                resolveValueOfElement(value)));
    } else {
        LOG.debug("Ignoring unhandled child type {}", childType);
    }
}

From source file:org.opendolphin.core.comm.JsonCodec.java

License:Apache License

private Object toValidValue(JsonElement jsonElement) {
    if (jsonElement.isJsonNull()) {
        return null;
    } else if (jsonElement.isJsonPrimitive()) {
        JsonPrimitive primitive = jsonElement.getAsJsonPrimitive();
        if (primitive.isBoolean()) {
            return primitive.getAsBoolean();
        } else if (primitive.isString()) {
            return primitive.getAsString();
        } else {/* w ww.j  av a  2  s .  c o  m*/
            return primitive.getAsNumber();
        }
    } else if (jsonElement.isJsonObject()) {
        JsonObject jsonObject = jsonElement.getAsJsonObject();
        if (jsonObject.has(Date.class.toString())) {
            try {
                return new SimpleDateFormat(ISO8601_FORMAT)
                        .parse(jsonObject.getAsJsonPrimitive(Date.class.toString()).getAsString());
            } catch (Exception e) {
                throw new RuntimeException("Can not converte!", e);
            }
        } else if (jsonObject.has(BigDecimal.class.toString())) {
            try {
                return new BigDecimal(jsonObject.getAsJsonPrimitive(BigDecimal.class.toString()).getAsString());
            } catch (Exception e) {
                throw new RuntimeException("Can not converte!", e);
            }
        } else if (jsonObject.has(Float.class.toString())) {
            try {
                return Float.valueOf(jsonObject.getAsJsonPrimitive(Float.class.toString()).getAsString());
            } catch (Exception e) {
                throw new RuntimeException("Can not converte!", e);
            }
        } else if (jsonObject.has(Double.class.toString())) {
            try {
                return Double.valueOf(jsonObject.getAsJsonPrimitive(Double.class.toString()).getAsString());
            } catch (Exception e) {
                throw new RuntimeException("Can not converte!", e);
            }
        }
    }
    throw new RuntimeException("Can not converte!");
}

From source file:org.openecomp.sdc.be.model.tosca.converters.ToscaMapValueConverter.java

License:Open Source License

public Object convertDataTypeToToscaMap(String innerType, Map<String, DataTypeDefinition> dataTypes,
        ToscaValueConverter innerConverter, final boolean isScalarF, JsonElement entryValue) {
    Object convertedValue = null;
    if (isScalarF && entryValue.isJsonPrimitive()) {
        log.debug("try convert scalar value {}", entryValue.getAsString());
        if (entryValue.getAsString() == null) {
            convertedValue = null;//from ww  w .j a  va2s . c  o m
        } else {
            convertedValue = innerConverter.convertToToscaValue(entryValue.getAsString(), innerType, dataTypes);
        }
    } else {
        JsonObject asJsonObjectIn = entryValue.getAsJsonObject();
        Set<Entry<String, JsonElement>> entrySetIn = asJsonObjectIn.entrySet();

        DataTypeDefinition dataTypeDefinition = dataTypes.get(innerType);
        Map<String, PropertyDefinition> allProperties = getAllProperties(dataTypeDefinition);
        Map<String, Object> toscaObjectPresentation = new HashMap<>();

        for (Entry<String, JsonElement> entry : entrySetIn) {
            String propName = entry.getKey();

            JsonElement elementValue = entry.getValue();
            Object convValue;
            if (isScalarF == false) {
                PropertyDefinition propertyDefinition = allProperties.get(propName);
                if (propertyDefinition == null && isScalarF) {
                    log.debug("The property {} was not found under data type {}", propName,
                            dataTypeDefinition.getName());
                    continue;
                }

                String type = propertyDefinition.getType();
                ToscaPropertyType propertyType = ToscaPropertyType.isValidType(type);
                if (propertyType != null) {
                    if (elementValue.isJsonPrimitive()) {
                        ToscaValueConverter valueConverter = propertyType.getValueConverter();
                        convValue = valueConverter.convertToToscaValue(elementValue.getAsString(), type,
                                dataTypes);
                    } else {
                        if (ToscaPropertyType.MAP.equals(type) || ToscaPropertyType.LIST.equals(propertyType)) {
                            ToscaValueConverter valueConverter = propertyType.getValueConverter();
                            String json = gson.toJson(elementValue);
                            String innerTypeRecursive = propertyDefinition.getSchema().getProperty().getType();
                            convValue = valueConverter.convertToToscaValue(json, innerTypeRecursive, dataTypes);
                        } else {
                            convValue = handleComplexJsonValue(elementValue);
                        }
                    }
                } else {
                    convValue = convertToToscaValue(elementValue.getAsString(), type, dataTypes);
                }
            } else {
                if (elementValue.isJsonPrimitive()) {
                    convValue = json2JavaPrimitive(elementValue.getAsJsonPrimitive());
                } else {
                    convValue = handleComplexJsonValue(elementValue);
                }
            }
            toscaObjectPresentation.put(propName, convValue);
        }
        convertedValue = toscaObjectPresentation;
    }
    return convertedValue;
}

From source file:org.openecomp.sdc.be.model.tosca.converters.ToscaValueBaseConverter.java

License:Open Source License

private List<Object> handleJsonArray(JsonElement entry) {
    List<Object> array = new ArrayList<>();
    JsonArray jsonArray = entry.getAsJsonArray();
    Iterator<JsonElement> iterator = jsonArray.iterator();
    while (iterator.hasNext()) {
        Object object;/*ww w  .  j  a  v a  2 s.c o  m*/
        JsonElement element = iterator.next();
        if (element.isJsonPrimitive()) {
            object = json2JavaPrimitive(element.getAsJsonPrimitive());
        } else {
            object = handleComplexJsonValue(element);
        }
        array.add(object);
    }
    return array;
}

From source file:org.openhab.binding.unifi.internal.api.util.UniFiTidyLowerCaseStringDeserializer.java

License:Open Source License

@Override
public String deserialize(JsonElement json, Type type, JsonDeserializationContext context)
        throws JsonParseException {
    String s = json.getAsJsonPrimitive().getAsString();
    return StringUtils.lowerCase(StringUtils.strip(s));
}

From source file:org.openhab.binding.unifi.internal.api.util.UniFiTimestampDeserializer.java

License:Open Source License

@Override
public Calendar deserialize(JsonElement json, Type type, JsonDeserializationContext context) {
    String text = json.getAsJsonPrimitive().getAsString();
    long millis = Long.valueOf(text) * 1000;
    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(millis);//from w  w w .  ja v a  2s  . com
    return cal;
}

From source file:org.openqa.selenium.json.JsonToBeanConverter.java

License:Apache License

@SuppressWarnings("unchecked")
private <T> T convert(Class<T> clazz, Object source, int depth) {
    if (source == null || source instanceof JsonNull) {
        return null;
    }/*from w  w  w.j a va 2 s  .c  o  m*/

    if (source instanceof JsonElement) {
        JsonElement json = (JsonElement) source;

        if (json.isJsonPrimitive()) {
            JsonPrimitive jp = json.getAsJsonPrimitive();

            if (String.class.equals(clazz)) {
                return (T) jp.getAsString();
            }

            if (jp.isNumber()) {
                if (Integer.class.isAssignableFrom(clazz) || int.class.equals(clazz)) {
                    return (T) Integer.valueOf(jp.getAsNumber().intValue());
                } else if (Long.class.isAssignableFrom(clazz) || long.class.equals(clazz)) {
                    return (T) Long.valueOf(jp.getAsNumber().longValue());
                } else if (Float.class.isAssignableFrom(clazz) || float.class.equals(clazz)) {
                    return (T) Float.valueOf(jp.getAsNumber().floatValue());
                } else if (Double.class.isAssignableFrom(clazz) || double.class.equals(clazz)) {
                    return (T) Double.valueOf(jp.getAsNumber().doubleValue());
                } else {
                    return (T) convertJsonPrimitive(jp);
                }
            }
        }
    }

    if (isPrimitive(source.getClass())) {
        return (T) source;
    }

    if (isEnum(clazz, source)) {
        return (T) convertEnum(clazz, source);
    }

    if ("".equals(String.valueOf(source))) {
        return (T) source;
    }

    if (Command.class.equals(clazz)) {
        JsonObject json = new JsonParser().parse((String) source).getAsJsonObject();

        SessionId sessionId = null;
        if (json.has("sessionId") && !json.get("sessionId").isJsonNull()) {
            sessionId = convert(SessionId.class, json.get("sessionId"), depth + 1);
        }

        String name = json.get("name").getAsString();
        if (json.has("parameters")) {
            Map<String, ?> args = (Map<String, ?>) convert(HashMap.class, json.get("parameters"), depth + 1);
            return (T) new Command(sessionId, name, args);
        }

        return (T) new Command(sessionId, name);
    }

    if (Response.class.equals(clazz)) {
        Response response = new Response();
        JsonObject json = source instanceof JsonObject ? (JsonObject) source
                : new JsonParser().parse((String) source).getAsJsonObject();

        if (json.has("error") && !json.get("error").isJsonNull()) {
            String state = json.get("error").getAsString();
            response.setState(state);
            response.setStatus(errorCodes.toStatus(state, Optional.empty()));
            response.setValue(convert(Object.class, json.get("message")));
        }
        if (json.has("state") && !json.get("state").isJsonNull()) {
            String state = json.get("state").getAsString();
            response.setState(state);
            response.setStatus(errorCodes.toStatus(state, Optional.empty()));
        }
        if (json.has("status") && !json.get("status").isJsonNull()) {
            JsonElement status = json.get("status");
            if (status.getAsJsonPrimitive().isString()) {
                String state = status.getAsString();
                response.setState(state);
                response.setStatus(errorCodes.toStatus(state, Optional.empty()));
            } else {
                int intStatus = status.getAsInt();
                response.setState(errorCodes.toState(intStatus));
                response.setStatus(intStatus);
            }
        }
        if (json.has("sessionId") && !json.get("sessionId").isJsonNull()) {
            response.setSessionId(json.get("sessionId").getAsString());
        }

        if (json.has("value")) {
            response.setValue(convert(Object.class, json.get("value")));
        } else {
            response.setValue(convert(Object.class, json));
        }

        return (T) response;
    }

    if (SessionId.class.equals(clazz)) {
        // Stupid heuristic to tell if we are dealing with a selenium 2 or 3 session id.
        JsonElement json = source instanceof String ? new JsonParser().parse((String) source).getAsJsonObject()
                : (JsonElement) source;
        if (json.isJsonPrimitive()) {
            return (T) new SessionId(json.getAsString());
        }
        return (T) new SessionId(json.getAsJsonObject().get("value").getAsString());
    }

    if (Capabilities.class.isAssignableFrom(clazz)) {
        JsonObject json = source instanceof JsonElement ? ((JsonElement) source).getAsJsonObject()
                : new JsonParser().parse(source.toString()).getAsJsonObject();
        Map<String, Object> map = convertMap(json.getAsJsonObject(), depth);
        return (T) new MutableCapabilities(map);
    }

    if (Date.class.equals(clazz)) {
        return (T) new Date(Long.valueOf(String.valueOf(source)));
    }

    if (source instanceof String && !((String) source).startsWith("{") && Object.class.equals(clazz)) {
        return (T) source;
    }

    Method fromJson = getMethod(clazz, "fromJson");
    if (fromJson != null) {
        try {
            return (T) fromJson.invoke(null, source.toString());
        } catch (ReflectiveOperationException e) {
            throw new WebDriverException(e);
        }
    }

    if (depth == 0) {
        if (source instanceof String) {
            source = new JsonParser().parse((String) source);
        }
    }

    if (source instanceof JsonElement) {
        JsonElement element = (JsonElement) source;

        if (element.isJsonNull()) {
            return null;
        }

        if (element.isJsonPrimitive()) {
            return (T) convertJsonPrimitive(element.getAsJsonPrimitive());
        }

        if (element.isJsonArray()) {
            return (T) convertList(element.getAsJsonArray(), depth);
        }

        if (element.isJsonObject()) {
            if (Map.class.isAssignableFrom(clazz)) {
                return (T) convertMap(element.getAsJsonObject(), depth);
            }

            if (Object.class.equals(clazz)) {
                return (T) convertMap(element.getAsJsonObject(), depth);
            }

            return convertBean(clazz, element.getAsJsonObject(), depth);
        }
    }

    return (T) source; // Crap shoot here; probably a string.
}