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.jboss.aerogear.android.store.sql.SQLStore.java

License:Apache License

private void saveElement(JsonElement serialized, String path, Serializable id) {
    String sql = String.format(
            "insert into %s_property (PROPERTY_NAME, PROPERTY_VALUE, PARENT_ID) values (?,?,?)", className);

    if (serialized.isJsonObject()) {
        Set<Entry<String, JsonElement>> members = ((JsonObject) serialized).entrySet();
        String pathVar = path.isEmpty() ? "" : ".";

        for (Entry<String, JsonElement> member : members) {
            JsonElement jsonValue = member.getValue();
            String propertyName = member.getKey();

            if (jsonValue.isJsonArray()) {
                JsonArray jsonArray = jsonValue.getAsJsonArray();
                for (int index = 0; index < jsonArray.size(); index++) {
                    saveElement(jsonArray.get(index),
                            path + pathVar + propertyName + String.format("[%d]", index), id);
                }//from  w  w  w. j  ava 2 s. co  m
            } else {
                saveElement(jsonValue, path + pathVar + propertyName, id);
            }
        }
    } else if (serialized.isJsonPrimitive()) {
        JsonPrimitive primitive = serialized.getAsJsonPrimitive();
        if (primitive.isBoolean()) {
            String value = primitive.getAsBoolean() ? "true" : "false";
            database.execSQL(sql, new Object[] { path, value, id });
        } else if (primitive.isNumber()) {
            Number value = primitive.getAsNumber();
            database.execSQL(sql, new Object[] { path, value, id });
        } else if (primitive.isString()) {
            String value = primitive.getAsString();
            database.execSQL(sql, new Object[] { path, value, id });
        } else {
            throw new IllegalArgumentException(serialized + " isn't a number, boolean, or string");
        }
    } else {
        throw new IllegalArgumentException(serialized + " isn't a JsonObject or JsonPrimitive");
    }
}

From source file:org.jboss.aerogear.android.store.sql.SQLStore.java

License:Apache License

private void buildKeyValuePairs(JsonObject where, List<Pair<String, String>> keyValues, String parentPath) {
    Set<Entry<String, JsonElement>> keys = where.entrySet();
    String pathVar = parentPath.isEmpty() ? "" : ".";// Set a dot if parent path is not empty
    for (Entry<String, JsonElement> entry : keys) {
        String key = entry.getKey();
        String path = parentPath + pathVar + key;
        JsonElement jsonValue = entry.getValue();
        if (jsonValue.isJsonObject()) {
            buildKeyValuePairs((JsonObject) jsonValue, keyValues, path);
        } else {/*from  w w  w.j  a  va2 s . c  o  m*/
            if (jsonValue.isJsonPrimitive()) {
                JsonPrimitive primitive = jsonValue.getAsJsonPrimitive();
                if (primitive.isBoolean()) {
                    String value = primitive.getAsBoolean() ? "true" : "false";
                    keyValues.add(new Pair<String, String>(path, value));
                } else if (primitive.isNumber()) {
                    Number value = primitive.getAsNumber();
                    keyValues.add(new Pair<String, String>(path, value.toString()));
                } else if (primitive.isString()) {
                    String value = primitive.getAsString();
                    keyValues.add(new Pair<String, String>(path, value));
                } else {
                    throw new IllegalArgumentException(jsonValue + " isn't a number, boolean, or string");
                }

            } else {
                throw new IllegalArgumentException(jsonValue + " isn't a JsonPrimitive");
            }

        }
    }
}

From source file:org.jclouds.json.internal.ParseObjectFromElement.java

License:Apache License

public Object apply(JsonElement input) {
    Object value = null;/*w w w. j  a va 2 s .  co m*/
    if (input == null || input.isJsonNull()) {
        value = null;
    } else if (input.isJsonPrimitive()) {
        JsonPrimitive primitive = input.getAsJsonPrimitive();
        if (primitive.isNumber()) {
            value = primitive.getAsNumber();
        } else if (primitive.isBoolean()) {
            value = primitive.getAsBoolean();
        } else {
            value = primitive.getAsString();
        }
    } else if (input.isJsonArray()) {
        value = Lists.newArrayList(Iterables.transform(input.getAsJsonArray(), this));
    } else if (input.isJsonObject()) {
        value = Maps.<String, Object>newLinkedHashMap(
                Maps.transformValues(JsonObjectAsMap.INSTANCE.apply(input.getAsJsonObject()), this));
    }
    return value;
}

From source file:org.jenkinsci.plugins.fod.FoDAPI.java

public Map<String, String> getApplicationList() throws IOException {
    final String METHOD_NAME = CLASS_NAME + ".getApplicationList";

    String endpoint = baseUrl + "/api/v1/Application/?fields=applicationId,applicationName,isMobile&limit=9999"; //TODO make this consistent elsewhere by a global config
    HttpGet connection = (HttpGet) getHttpUriRequest("GET", endpoint);
    InputStream is = null;/*from  w w w.j a  v  a 2s  .c o m*/

    try {
        // Get Response
        HttpResponse response = getHttpClient().execute(connection);
        is = response.getEntity().getContent();
        StringBuffer buffer = collectInputStream(is);
        JsonArray arr = getDataJsonArray(buffer);
        Map<String, String> map = new TreeMap<String, String>();
        for (int ix = 0; ix < arr.size(); ix++) {
            JsonElement entity = arr.get(ix);
            JsonObject obj = entity.getAsJsonObject();
            JsonPrimitive name = obj.getAsJsonPrimitive("applicationName");
            JsonPrimitive id = obj.getAsJsonPrimitive("applicationID");
            JsonPrimitive isMobile = obj.getAsJsonPrimitive("isMobile");

            if (map.containsKey(name.getAsString())) {
                continue;
            }
            if (!isMobile.getAsBoolean()) {
                map.put(name.getAsString(), id.getAsString());
            }
        }
        return map;
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

From source file:org.kurento.commons.BasicJsonUtils.java

License:Apache License

private static Object convertValue(JsonElement value) {
    if (value.isJsonNull()) {
        return null;
    } else if (value.isJsonPrimitive()) {
        JsonPrimitive prim = value.getAsJsonPrimitive();
        if (prim.isBoolean()) {
            return prim.getAsBoolean();
        } else if (prim.isNumber()) {
            Number n = prim.getAsNumber();
            if (n.doubleValue() == n.intValue()) {
                return n.intValue();
            } else {
                return n.doubleValue();
            }// w  w w  .  ja  va2 s .  c o  m
        } else if (prim.isString()) {
            return prim.getAsString();
        } else {
            throw new RuntimeException("Unrecognized value: " + value);
        }
    } else {
        return value.toString();
    }
}

From source file:org.kurento.jsonrpc.JsonUtils.java

License:Apache License

public Object toPrimitiveObject(JsonElement element) {

    JsonPrimitive primitive = (JsonPrimitive) element;
    if (primitive.isBoolean()) {
        return Boolean.valueOf(primitive.getAsBoolean());
    } else if (primitive.isNumber()) {
        Number number = primitive.getAsNumber();
        double value = number.doubleValue();
        if ((int) value == value) {
            return Integer.valueOf((int) value);
        }//w w  w. ja va  2  s .c  o m

        return Float.valueOf((float) value);

    } else if (primitive.isString()) {
        return primitive.getAsString();
    } else {
        throw new JsonRpcException("Unrecognized JsonPrimitive: " + primitive);
    }
}

From source file:org.kurento.modulecreator.codegen.JsonObjectAsMap.java

License:Apache License

public Object createObjectFromJsonElement(JsonElement value) {

    if (value == null) {
        return null;
    }/*  www.  ja v a 2  s  .  c  o m*/

    if (value instanceof JsonPrimitive) {
        JsonPrimitive primitive = (JsonPrimitive) value;

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

        if (primitive.isNumber()) {
            return primitive.getAsNumber();
        }

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

    if (value instanceof JsonArray) {

        JsonArray array = (JsonArray) value;

        List<Object> values = new ArrayList<Object>();
        for (JsonElement element : array) {
            values.add(createObjectFromJsonElement(element));
        }

        return values;
    }

    if (value instanceof JsonObject) {
        return createObjectFromJsonElement(value);
    }

    throw new RuntimeException("Unrecognized json element: " + value);
}

From source file:org.locationtech.geogig.rest.repository.MergeFeatureResource.java

License:Open Source License

public void post(Representation entity) {
    InputStream input = null;//from   w  w  w  . j  a  va2  s  .  c  o  m

    try {
        input = getRequest().getEntity().getStream();
        final Repository ggig = getGeogig(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, ggig);
                if (ourNode.isPresent()) {
                    Optional<RevObject> object = ggig.command(RevObjectParse.class)
                            .setObjectId(ourNode.get().getObjectId()).call();
                    Preconditions.checkState(object.isPresent() && object.get() instanceof RevFeature);

                    ourFeature = (RevFeature) object.get();

                    object = ggig.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, ggig);
                if (theirNode.isPresent()) {
                    Optional<RevObject> object = ggig.command(RevObjectParse.class)
                            .setObjectId(theirNode.get().getObjectId()).call();
                    Preconditions.checkState(object.isPresent() && object.get() instanceof RevFeature);

                    theirFeature = (RevFeature) object.get();

                    object = ggig.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).descriptors();

            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.get(descriptorIndex).orNull());
                    } else if (attributeObject.has("theirs") && attributeObject.get("theirs").isJsonPrimitive()
                            && attributeObject.get("theirs").getAsBoolean()) {
                        featureBuilder.set(descriptor.getName(),
                                theirFeature == null ? null : theirFeature.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);
            ggig.objectDatabase().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.locationtech.geogig.spring.service.LegacyMergeFeatureService.java

License:Open Source License

public RevFeature mergeFeatures(RepositoryProvider provider, String repoName, String request) {
    // get the repo
    Repository repository = getRepository(provider, repoName);
    if (repository != null) {
        final JsonParser parser = new JsonParser();
        final JsonElement conflictJson;
        try {/*www. ja  v  a2s.com*/
            conflictJson = parser.parse(request);
        } catch (Exception e) {
            invalidPostData();
            return null;
        }

        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();
            }
            if (featureId == null) {
                invalidPostData();
            }

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

                    ourFeature = (RevFeature) object.get();

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

                    ourFeatureType = (RevFeatureType) object.get();
                }
            } else {
                invalidPostData();
            }

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

                    theirFeature = (RevFeature) object.get();

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

                    theirFeatureType = (RevFeatureType) object.get();
                }
            } else {
                invalidPostData();
            }

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

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

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

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

            for (Map.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.get(descriptorIndex).orNull());
                    } else if (attributeObject.has("theirs") && attributeObject.get("theirs").isJsonPrimitive()
                            && attributeObject.get("theirs").getAsBoolean()) {
                        featureBuilder.set(descriptor.getName(),
                                theirFeature == null ? null : theirFeature.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 CommandSpecException("Unable to convert attribute (" + entry.getKey()
                                        + ") to required type: " + descriptor.getType().getBinding().toString(),
                                        HttpStatus.INTERNAL_SERVER_ERROR);
                            }
                        } 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 CommandSpecException("Unable to convert attribute (" + entry.getKey()
                                        + ") to required type: " + descriptor.getType().getBinding().toString(),
                                        HttpStatus.INTERNAL_SERVER_ERROR);
                            }
                        } 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 CommandSpecException("Unable to convert attribute (" + entry.getKey()
                                        + ") to required type: " + descriptor.getType().getBinding().toString(),
                                        HttpStatus.INTERNAL_SERVER_ERROR);
                            }
                        } else if (primitive.isJsonNull()) {
                            featureBuilder.set(descriptor.getName(), null);
                        } else {
                            throw new CommandSpecException(
                                    "Unsupported JSON type for attribute value (" + entry.getKey() + ")",
                                    HttpStatus.INTERNAL_SERVER_ERROR);
                        }
                    }
                }
            }
            SimpleFeature feature = featureBuilder.buildFeature(NodeRef.nodeFromPath(featureId));
            RevFeature revFeature = RevFeatureBuilder.build(feature);
            repository.objectDatabase().put(revFeature);

            return revFeature;
        } else {
            invalidPostData();
        }
    }
    return null;
}

From source file:org.mitre.jwt.model.ClaimSet.java

License:Apache License

/**
 * Set a primitive claim/*  ww  w . j a  v a  2 s .  c o  m*/
 */
public void setClaim(String key, JsonPrimitive prim) {
    invalidateString();
    if (prim == null) {
        // in case we get here with a primitive null
        claims.put(key, prim);
    } else if (prim.isBoolean()) {
        claims.put(key, prim.getAsBoolean());
    } else if (prim.isNumber()) {
        claims.put(key, prim.getAsNumber());
    } else if (prim.isString()) {
        claims.put(key, prim.getAsString());
    }

}