Example usage for com.google.gson JsonPrimitive getAsBoolean

List of usage examples for com.google.gson JsonPrimitive getAsBoolean

Introduction

In this page you can find the example usage for com.google.gson JsonPrimitive getAsBoolean.

Prototype

@Override
public boolean getAsBoolean() 

Source Link

Document

convenience method to get this element as a boolean value.

Usage

From source file:org.eclipse.leshan.standalone.servlet.json.LwM2mNodeDeserializer.java

License:Open Source License

private Value<?> deserializeValue(JsonPrimitive val) {
    Value<?> value = null;/*from  ww  w  .j a va 2  s .  c om*/
    if (val.isNumber()) {

        Number n = val.getAsNumber();
        if (n.doubleValue() == (long) n.doubleValue()) {
            Long lValue = Long.valueOf(n.longValue());
            if (lValue >= Integer.MIN_VALUE && lValue <= Integer.MAX_VALUE) {
                value = Value.newIntegerValue(lValue.intValue());
            } else {
                value = Value.newLongValue(lValue);
            }
        } else {
            Double dValue = Double.valueOf(n.doubleValue());
            if (dValue >= Float.MIN_VALUE && dValue <= Float.MAX_VALUE) {
                value = Value.newFloatValue(dValue.floatValue());
            } else {
                value = Value.newDoubleValue(dValue);
            }
        }

    } else if (val.isBoolean()) {
        value = Value.newBooleanValue(val.getAsBoolean());
    } else if (val.isString()) {
        value = Value.newStringValue(val.getAsString());
    }
    return value;
}

From source file:org.eclipse.milo.opcua.binaryschema.gson.JsonStructureCodec.java

License:Open Source License

@Override
protected Object memberTypeToOpcUaScalar(JsonElement member, String typeName) {
    if (member == null || member.isJsonNull()) {
        return null;
    } else if (member.isJsonArray()) {
        JsonArray array = member.getAsJsonArray();

        switch (typeName) {
        case "ByteString": {
            byte[] bs = new byte[array.size()];

            for (int i = 0; i < array.size(); i++) {
                bs[i] = array.get(i).getAsByte();
            }/*from w w w.  ja v a  2  s. co  m*/

            return ByteString.of(bs);
        }

        default:
            return array;
        }
    } else if (member.isJsonObject()) {
        JsonObject jsonObject = member.getAsJsonObject();

        switch (typeName) {
        case "QualifiedName": {
            return new QualifiedName(jsonObject.get("namespaceIndex").getAsInt(),
                    jsonObject.get("name").getAsString());
        }
        case "LocalizedText": {
            return new LocalizedText(jsonObject.get("locale").getAsString(),
                    jsonObject.get("text").getAsString());
        }

        default:
            return jsonObject;
        }
    } else if (member.isJsonPrimitive()) {
        JsonPrimitive primitive = member.getAsJsonPrimitive();

        if (primitive.isBoolean()) {
            return primitive.getAsBoolean();
        } else if (primitive.isString()) {
            switch (typeName) {
            case "Guid":
                return UUID.fromString(primitive.getAsString());

            case "NodeId":
                return NodeId.parseSafe(primitive.getAsString()).orElse(NodeId.NULL_VALUE);

            case "ExpandedNodeId":
                return ExpandedNodeId.parse(primitive.getAsString());

            case "XmlElement":
                return new XmlElement(primitive.getAsString());

            default:
                return primitive.getAsString();
            }
        } else if (primitive.isNumber()) {
            switch (typeName) {
            case "SByte":
                return primitive.getAsByte();
            case "Int16":
                return primitive.getAsShort();
            case "Int32":
                return primitive.getAsInt();
            case "Int64":
                return primitive.getAsLong();

            case "Byte":
                return ubyte(primitive.getAsShort());
            case "UInt16":
                return ushort(primitive.getAsInt());
            case "UInt32":
                return uint(primitive.getAsLong());
            case "UInt64":
                return ulong(primitive.getAsBigInteger());

            case "Float":
                return primitive.getAsFloat();
            case "Double":
                return primitive.getAsDouble();

            case "DateTime":
                return new DateTime(primitive.getAsLong());

            case "StatusCode":
                return new StatusCode(primitive.getAsLong());

            default:
                return primitive.getAsNumber();
            }
        }
    }

    return null;
}

From source file:org.eclipse.php.composer.api.json.JsonParser.java

License:Open Source License

private Object buildTree(JsonElement entity) {

    if (entity.isJsonPrimitive()) {
        JsonPrimitive p = entity.getAsJsonPrimitive();
        if (p.isBoolean()) {
            return p.getAsBoolean();
        }/*from   w  w  w.  jav a  2s .co  m*/
        if (p.isNumber()) {
            return p.getAsLong();
        }
        return p.getAsString();
    } else if (entity.isJsonNull()) {
        return null;
    } else if (entity.isJsonArray()) {
        LinkedList<Object> arr = new LinkedList<Object>();
        for (JsonElement el : entity.getAsJsonArray()) {
            arr.add(buildTree(el));
        }
        return arr;
    } else if (entity.isJsonObject()) {
        LinkedHashMap<String, Object> map = new LinkedHashMap<String, Object>();
        for (Entry<String, JsonElement> el : entity.getAsJsonObject().entrySet()) {
            map.put(el.getKey(), buildTree(el.getValue()));
        }
        return map;
    }

    return null;
}

From source file:org.eclipse.scada.base.json.VariantJsonDeserializer.java

License:Open Source License

private Variant decodeFromPrimitive(final JsonElement json) {
    final JsonPrimitive jsonPrim = (JsonPrimitive) json;
    if (jsonPrim.isBoolean()) {
        return Variant.valueOf(jsonPrim.getAsBoolean());
    } else if (jsonPrim.isNumber()) {
        return Variant.valueOf(jsonPrim.getAsNumber());
    } else {//from ww w . j a  v  a  2s. c o  m
        return VariantEditor.toVariant(jsonPrim.getAsString());
    }
}

From source file:org.eclipse.smarthome.automation.parser.gson.internal.ConfigurationDeserializer.java

License:Open Source License

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

    Configuration configuration = new Configuration();
    JsonObject jo = (JsonObject) json;//w w w  .  j  av  a  2 s. c  om
    for (Entry<String, JsonElement> e : jo.entrySet()) {
        JsonPrimitive value = e.getValue().getAsJsonPrimitive();
        if (value.isString()) {
            configuration.put(e.getKey(), value.getAsString());
        } else if (value.isNumber()) {
            configuration.put(e.getKey(), value.getAsBigDecimal());
        } else if (value.isBoolean()) {
            configuration.put(e.getKey(), value.getAsBoolean());
        }
    }
    return configuration;
}

From source file:org.eclipse.smarthome.config.core.ConfigurationDeserializer.java

License:Open Source License

private Object deserialize(JsonPrimitive primitive) {
    if (primitive.isString()) {
        return primitive.getAsString();
    } else if (primitive.isNumber()) {
        return primitive.getAsBigDecimal();
    } else if (primitive.isBoolean()) {
        return primitive.getAsBoolean();
    } else {//from  ww w  . j a va2 s.c om
        throw new IllegalArgumentException("Unsupported primitive: " + primitive);
    }
}

From source file:org.eel.kitchen.jsonschema.GsonProvider.java

License:Open Source License

private static JsonNode gsonToValueNode(final JsonPrimitive primitive) {
    if (primitive.isBoolean())
        return factory.booleanNode(primitive.getAsBoolean());
    if (primitive.isNumber())
        return toNumberNode(primitive.getAsBigDecimal());

    // Can only be a string,now
    return factory.textNode(primitive.getAsString());
}

From source file:org.faul.jql.utils.RemoteObjectHandler.java

License:Open Source License

Object getPrimitive(JsonPrimitive p) {
    if (p.isNumber()) {
        String str = p.getAsString();
        try {//w w w  .j  a va  2s.  c  o  m
            return Long.parseLong(str);
        } catch (Exception error) {
        }
        return Double.parseDouble(str);
    }

    if (p.isBoolean()) {
        return p.getAsBoolean();
    }

    if (p.isJsonArray()) {
        return p.getAsJsonArray();
    }

    if (p.isString()) {
        return p.getAsString();
    }

    return null;
}

From source file:org.geogit.rest.repository.MergeFeatureResource.java

License:Open Source License

public void post(Representation entity) {
    InputStream input = null;/*w ww  .j  av a 2 s .c  om*/

    try {
        input = getRequest().getEntity().getStream();
        final GeoGIT ggit = getGeogit(getRequest()).get();
        final Reader body = new InputStreamReader(input);
        final JsonParser parser = new JsonParser();
        final JsonElement conflictJson = parser.parse(body);

        if (conflictJson.isJsonObject()) {
            final JsonObject conflict = conflictJson.getAsJsonObject();
            String featureId = null;
            RevFeature ourFeature = null;
            RevFeatureType ourFeatureType = null;
            RevFeature theirFeature = null;
            RevFeatureType theirFeatureType = null;
            JsonObject merges = null;
            if (conflict.has("path") && conflict.get("path").isJsonPrimitive()) {
                featureId = conflict.get("path").getAsJsonPrimitive().getAsString();
            }
            Preconditions.checkState(featureId != null);

            if (conflict.has("ours") && conflict.get("ours").isJsonPrimitive()) {
                String ourCommit = conflict.get("ours").getAsJsonPrimitive().getAsString();
                Optional<NodeRef> ourNode = parseID(ObjectId.valueOf(ourCommit), featureId, ggit);
                if (ourNode.isPresent()) {
                    Optional<RevObject> object = ggit.command(RevObjectParse.class)
                            .setObjectId(ourNode.get().objectId()).call();
                    Preconditions.checkState(object.isPresent() && object.get() instanceof RevFeature);

                    ourFeature = (RevFeature) object.get();

                    object = ggit.command(RevObjectParse.class).setObjectId(ourNode.get().getMetadataId())
                            .call();
                    Preconditions.checkState(object.isPresent() && object.get() instanceof RevFeatureType);

                    ourFeatureType = (RevFeatureType) object.get();
                }
            }

            if (conflict.has("theirs") && conflict.get("theirs").isJsonPrimitive()) {
                String theirCommit = conflict.get("theirs").getAsJsonPrimitive().getAsString();
                Optional<NodeRef> theirNode = parseID(ObjectId.valueOf(theirCommit), featureId, ggit);
                if (theirNode.isPresent()) {
                    Optional<RevObject> object = ggit.command(RevObjectParse.class)
                            .setObjectId(theirNode.get().objectId()).call();
                    Preconditions.checkState(object.isPresent() && object.get() instanceof RevFeature);

                    theirFeature = (RevFeature) object.get();

                    object = ggit.command(RevObjectParse.class).setObjectId(theirNode.get().getMetadataId())
                            .call();
                    Preconditions.checkState(object.isPresent() && object.get() instanceof RevFeatureType);

                    theirFeatureType = (RevFeatureType) object.get();
                }
            }

            if (conflict.has("merges") && conflict.get("merges").isJsonObject()) {
                merges = conflict.get("merges").getAsJsonObject();
            }
            Preconditions.checkState(merges != null);

            Preconditions.checkState(ourFeatureType != null || theirFeatureType != null);

            SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(
                    (SimpleFeatureType) (ourFeatureType != null ? ourFeatureType.type()
                            : theirFeatureType.type()));

            ImmutableList<PropertyDescriptor> descriptors = (ourFeatureType == null ? theirFeatureType
                    : ourFeatureType).sortedDescriptors();

            for (Entry<String, JsonElement> entry : merges.entrySet()) {
                int descriptorIndex = getDescriptorIndex(entry.getKey(), descriptors);
                if (descriptorIndex != -1 && entry.getValue().isJsonObject()) {
                    PropertyDescriptor descriptor = descriptors.get(descriptorIndex);
                    JsonObject attributeObject = entry.getValue().getAsJsonObject();
                    if (attributeObject.has("ours") && attributeObject.get("ours").isJsonPrimitive()
                            && attributeObject.get("ours").getAsBoolean()) {
                        featureBuilder.set(descriptor.getName(), ourFeature == null ? null
                                : ourFeature.getValues().get(descriptorIndex).orNull());
                    } else if (attributeObject.has("theirs") && attributeObject.get("theirs").isJsonPrimitive()
                            && attributeObject.get("theirs").getAsBoolean()) {
                        featureBuilder.set(descriptor.getName(), theirFeature == null ? null
                                : theirFeature.getValues().get(descriptorIndex).orNull());
                    } else if (attributeObject.has("value") && attributeObject.get("value").isJsonPrimitive()) {
                        JsonPrimitive primitive = attributeObject.get("value").getAsJsonPrimitive();
                        if (primitive.isString()) {
                            try {
                                Object object = valueFromString(
                                        FieldType.forBinding(descriptor.getType().getBinding()),
                                        primitive.getAsString());
                                featureBuilder.set(descriptor.getName(), object);
                            } catch (Exception e) {
                                throw new Exception("Unable to convert attribute (" + entry.getKey()
                                        + ") to required type: "
                                        + descriptor.getType().getBinding().toString());
                            }
                        } else if (primitive.isNumber()) {
                            try {
                                Object value = valueFromNumber(
                                        FieldType.forBinding(descriptor.getType().getBinding()),
                                        primitive.getAsNumber());
                                featureBuilder.set(descriptor.getName(), value);
                            } catch (Exception e) {
                                throw new Exception("Unable to convert attribute (" + entry.getKey()
                                        + ") to required type: "
                                        + descriptor.getType().getBinding().toString());
                            }
                        } else if (primitive.isBoolean()) {
                            try {
                                Object value = valueFromBoolean(
                                        FieldType.forBinding(descriptor.getType().getBinding()),
                                        primitive.getAsBoolean());
                                featureBuilder.set(descriptor.getName(), value);
                            } catch (Exception e) {
                                throw new Exception("Unable to convert attribute (" + entry.getKey()
                                        + ") to required type: "
                                        + descriptor.getType().getBinding().toString());
                            }
                        } else if (primitive.isJsonNull()) {
                            featureBuilder.set(descriptor.getName(), null);
                        } else {
                            throw new Exception(
                                    "Unsupported JSON type for attribute value (" + entry.getKey() + ")");
                        }
                    }
                }
            }
            SimpleFeature feature = featureBuilder.buildFeature(NodeRef.nodeFromPath(featureId));
            RevFeature revFeature = RevFeatureBuilder.build(feature);
            ggit.getRepository().stagingDatabase().put(revFeature);

            getResponse()
                    .setEntity(new StringRepresentation(revFeature.getId().toString(), MediaType.TEXT_PLAIN));
        }

    } catch (Exception e) {
        throw new RestletException(e.getMessage(), Status.SERVER_ERROR_INTERNAL, e);
    } finally {
        if (input != null)
            Closeables.closeQuietly(input);
    }
}

From source file:org.geogit.web.api.repo.MergeFeatureResource.java

License:Open Source License

@Override
protected Representation post(Representation entity) throws ResourceException {
    try {/*  w ww  .  j a  va 2s .  c om*/
        final GeoGIT ggit = (GeoGIT) getApplication().getContext().getAttributes().get("geogit");
        final Reader body = entity.getReader();
        final JsonParser parser = new JsonParser();
        final JsonElement conflictJson = parser.parse(body);

        Preconditions.checkArgument(conflictJson.isJsonObject(), "Post data should be a JSON Object.");

        final JsonObject conflict = conflictJson.getAsJsonObject();
        String featureId = null;
        RevFeature ourFeature = null;
        RevFeatureType ourFeatureType = null;
        RevFeature theirFeature = null;
        RevFeatureType theirFeatureType = null;
        JsonObject merges = null;
        if (conflict.has("path") && conflict.get("path").isJsonPrimitive()) {
            featureId = conflict.get("path").getAsJsonPrimitive().getAsString();
        }
        Preconditions.checkState(featureId != null);

        if (conflict.has("ours") && conflict.get("ours").isJsonPrimitive()) {
            String ourCommit = conflict.get("ours").getAsJsonPrimitive().getAsString();
            Optional<NodeRef> ourNode = parseID(ObjectId.valueOf(ourCommit), featureId, ggit);
            if (ourNode.isPresent()) {
                Optional<RevObject> object = ggit.command(RevObjectParse.class)
                        .setObjectId(ourNode.get().objectId()).call();
                Preconditions.checkState(object.isPresent() && object.get() instanceof RevFeature);

                ourFeature = (RevFeature) object.get();

                object = ggit.command(RevObjectParse.class).setObjectId(ourNode.get().getMetadataId()).call();
                Preconditions.checkState(object.isPresent() && object.get() instanceof RevFeatureType);

                ourFeatureType = (RevFeatureType) object.get();
            }
        }

        if (conflict.has("theirs") && conflict.get("theirs").isJsonPrimitive()) {
            String theirCommit = conflict.get("theirs").getAsJsonPrimitive().getAsString();
            Optional<NodeRef> theirNode = parseID(ObjectId.valueOf(theirCommit), featureId, ggit);
            if (theirNode.isPresent()) {
                Optional<RevObject> object = ggit.command(RevObjectParse.class)
                        .setObjectId(theirNode.get().objectId()).call();
                Preconditions.checkState(object.isPresent() && object.get() instanceof RevFeature);

                theirFeature = (RevFeature) object.get();

                object = ggit.command(RevObjectParse.class).setObjectId(theirNode.get().getMetadataId()).call();
                Preconditions.checkState(object.isPresent() && object.get() instanceof RevFeatureType);

                theirFeatureType = (RevFeatureType) object.get();
            }
        }

        if (conflict.has("merges") && conflict.get("merges").isJsonObject()) {
            merges = conflict.get("merges").getAsJsonObject();
        }
        Preconditions.checkState(merges != null);

        Preconditions.checkState(ourFeatureType != null || theirFeatureType != null);

        SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(
                (SimpleFeatureType) (ourFeatureType != null ? ourFeatureType.type() : theirFeatureType.type()));

        ImmutableList<PropertyDescriptor> descriptors = (ourFeatureType == null ? theirFeatureType
                : ourFeatureType).sortedDescriptors();

        for (Entry<String, JsonElement> entry : merges.entrySet()) {
            int descriptorIndex = getDescriptorIndex(entry.getKey(), descriptors);
            if (descriptorIndex != -1 && entry.getValue().isJsonObject()) {
                PropertyDescriptor descriptor = descriptors.get(descriptorIndex);
                JsonObject attributeObject = entry.getValue().getAsJsonObject();
                if (attributeObject.has("ours") && attributeObject.get("ours").isJsonPrimitive()
                        && attributeObject.get("ours").getAsBoolean()) {
                    featureBuilder.set(descriptor.getName(),
                            ourFeature == null ? null : ourFeature.getValues().get(descriptorIndex).orNull());
                } else if (attributeObject.has("theirs") && attributeObject.get("theirs").isJsonPrimitive()
                        && attributeObject.get("theirs").getAsBoolean()) {
                    featureBuilder.set(descriptor.getName(), theirFeature == null ? null
                            : theirFeature.getValues().get(descriptorIndex).orNull());
                } else if (attributeObject.has("value") && attributeObject.get("value").isJsonPrimitive()) {
                    JsonPrimitive primitive = attributeObject.get("value").getAsJsonPrimitive();
                    if (primitive.isString()) {
                        try {
                            Object object = valueFromString(
                                    FieldType.forBinding(descriptor.getType().getBinding()),
                                    primitive.getAsString());
                            featureBuilder.set(descriptor.getName(), object);
                        } catch (Exception e) {
                            throw new Exception("Unable to convert attribute (" + entry.getKey()
                                    + ") to required type: " + descriptor.getType().getBinding().toString());
                        }
                    } else if (primitive.isNumber()) {
                        try {
                            Object value = valueFromNumber(
                                    FieldType.forBinding(descriptor.getType().getBinding()),
                                    primitive.getAsNumber());
                            featureBuilder.set(descriptor.getName(), value);
                        } catch (Exception e) {
                            throw new Exception("Unable to convert attribute (" + entry.getKey()
                                    + ") to required type: " + descriptor.getType().getBinding().toString());
                        }
                    } else if (primitive.isBoolean()) {
                        try {
                            Object value = valueFromBoolean(
                                    FieldType.forBinding(descriptor.getType().getBinding()),
                                    primitive.getAsBoolean());
                            featureBuilder.set(descriptor.getName(), value);
                        } catch (Exception e) {
                            throw new Exception("Unable to convert attribute (" + entry.getKey()
                                    + ") to required type: " + descriptor.getType().getBinding().toString());
                        }
                    } else if (primitive.isJsonNull()) {
                        featureBuilder.set(descriptor.getName(), null);
                    } else {
                        throw new Exception(
                                "Unsupported JSON type for attribute value (" + entry.getKey() + ")");
                    }
                }
            }
        }
        SimpleFeature feature = featureBuilder.buildFeature(NodeRef.nodeFromPath(featureId));
        RevFeature revFeature = RevFeatureBuilder.build(feature);
        ggit.getRepository().getIndex().getDatabase().put(revFeature);

        return new StringRepresentation(revFeature.getId().toString(), MediaType.TEXT_PLAIN);

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}