Example usage for com.google.gson JsonElement isJsonObject

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

Introduction

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

Prototype

public boolean isJsonObject() 

Source Link

Document

provides check for verifying if this element is a Json object or not.

Usage

From source file:com.codereligion.bugsnag.logback.resource.TabVOSerializer.java

License:Apache License

private void filterJsonElement(final JsonElement jsonElement) {
    if (jsonElement.isJsonArray()) {
        filterJsonArray(jsonElement.getAsJsonArray());
    } else if (jsonElement.isJsonObject()) {
        filterJsonObject(jsonElement.getAsJsonObject());
    }// w  w w .j a  v a  2s  .  c om
}

From source file:com.collective.celos.ci.testing.fixtures.compare.json.JsonElementConstructor.java

License:Apache License

private JsonElement deepCopy(String path, JsonElement el, Set<String> ignorePaths) {
    if (el.isJsonArray()) {
        return deepCopyJsonArray(path, el.getAsJsonArray(), ignorePaths);
    }/*from  www  .j  av  a  2s  . c  om*/
    if (el.isJsonObject()) {
        return deepCopyJsonObject(path, el.getAsJsonObject(), ignorePaths);
    }
    if (el.isJsonPrimitive() || el.isJsonNull()) {
        return el;
    }
    throw new IllegalStateException(
            "JSONElement should be either Array, Object, Primitive or Null. So you cannot get here");
}

From source file:com.continusec.client.ObjectHash.java

License:Apache License

/**
 * Calculate the objecthash for a Gson JsonElement object, with a custom redaction prefix string.
 * @param o the Gson JsonElement to calculated the objecthash for.
 * @param r the string to use as a prefix to indicate that a string should be treated as a redacted subobject.
 * @return the objecthash for this object
 * @throws ContinusecException upon error
 *///from  w  ww.  j a  v  a 2s. c  o m
public static final byte[] objectHashWithRedaction(JsonElement o, String r) throws ContinusecException {
    if (o == null || o.isJsonNull()) {
        return hashNull();
    } else if (o.isJsonArray()) {
        return hashArray(o.getAsJsonArray(), r);
    } else if (o.isJsonObject()) {
        return hashObject(o.getAsJsonObject(), r);
    } else if (o.isJsonPrimitive()) {
        JsonPrimitive p = o.getAsJsonPrimitive();
        if (p.isBoolean()) {
            return hashBoolean(p.getAsBoolean());
        } else if (p.isNumber()) {
            return hashDouble(p.getAsDouble());
        } else if (p.isString()) {
            return hashString(p.getAsString(), r);
        } else {
            throw new InvalidObjectException();
        }
    } else {
        throw new InvalidObjectException();
    }
}

From source file:com.continusec.client.ObjectHash.java

License:Apache License

/**
 * Strip away object values that are marked as redacted, and switch nonce-tuples back to normal values.
 * This is useful when an object has been stored with Redactable nonces added, but now it has been retrieved
 * and normal processing needs to be performed on it.
 * @param o the Gson JsonElement that contains the redacted elements and nonce-tuples.
 * @param r the redaction prefix that indicates if a string represents a redacted sub-object.
 * @return a new cleaned up JsonElement//  w w w . j  ava 2s. c  o m
 * @throws ContinusecException upon error
 */
public static final JsonElement shedRedactable(JsonElement o, String r) throws ContinusecException {
    if (o == null) {
        return null;
    } else if (o.isJsonArray()) {
        return shedArray(o.getAsJsonArray(), r);
    } else if (o.isJsonObject()) {
        return shedObject(o.getAsJsonObject(), r);
    } else {
        return o;
    }
}

From source file:com.continuuity.loom.codec.json.upgrade.ProviderUpgradeCodec.java

License:Apache License

private Map<String, String> deserializeProvisionerFields(JsonObject jsonObj,
        JsonDeserializationContext context) {
    if (!jsonObj.has("provisioner")) {
        return Maps.newHashMap();
    }//from ww w .java  2  s  . c o m

    JsonObject fields = jsonObj.get("provisioner").getAsJsonObject();
    // if its the old type
    if (fields.has("auth")) {
        JsonElement authElement = fields.get("auth");
        if (authElement.isJsonObject()) {
            fields = authElement.getAsJsonObject();
        }
    }
    return context.deserialize(fields, new TypeToken<Map<String, String>>() {
    }.getType());
}

From source file:com.continuuity.loom.macro.Expander.java

License:Apache License

/**
 * Given a JSON tree, find the element specified by the path (or the root if path is null). In that subtree,
 * recursively traverse all elements, and expand all String typed right hand side values.  If a macro cannot be
 * expanded due to the cluster object missing certain data, that macro will be left unexpanded.
 *
 * @param json A JSON tree/*from  w  w  w  .j a  v a2  s  .  com*/
 * @param path the path to expand under
 * @param cluster the cluster to use for expanding macros.
 * @param nodes the cluster nodes to use for expanding macros.
 * @param node the cluster node to use for expanding macros.
 * @return a new JSON tree if any expansion took place, and the original JSON tree otherwise.
 * @throws SyntaxException if a macro expression is ill-formed.
 * @throws IncompleteClusterException if the cluster does not have the meta data to expand all macros.
 */
public static JsonElement expand(JsonElement json, @Nullable java.util.List<String> path, Cluster cluster,
        Set<Node> nodes, Node node) throws SyntaxException, IncompleteClusterException {

    // if path is given,
    if (path != null && !path.isEmpty()) {
        String first = path.get(0);
        if (json.isJsonObject()) {
            JsonObject object = json.getAsJsonObject();
            JsonElement json1 = object.get(first);
            if (json1 != null) {
                JsonElement expanded = expand(json1, path.subList(1, path.size()), cluster, nodes, node);
                if (expanded != json1) {
                    // only construct new json object if actual expansion happened
                    JsonObject object1 = new JsonObject();
                    for (Map.Entry<String, JsonElement> entry : object.entrySet()) {
                        object1.add(entry.getKey(), entry.getKey().equals(first) ? expanded : entry.getValue());
                    }
                    return object1;
                }
            }
        }
        // path was given, but either no corresponding subtree was found or no expansion happened...
        return json;
    }

    if (json.isJsonPrimitive()) {
        JsonPrimitive primitive = json.getAsJsonPrimitive();
        if (primitive.isString()) {
            String value = primitive.getAsString();
            String expanded = expand(value, cluster, nodes, node);
            if (!expanded.equals(value)) {
                // only return a new json element if actual expansion happened
                return new JsonPrimitive(expanded);
            }
        }
    }

    if (json.isJsonArray()) {
        JsonArray array = json.getAsJsonArray();
        JsonArray array1 = new JsonArray();
        boolean expansionHappened = false;
        for (JsonElement element : array) {
            JsonElement expanded = expand(element, path, cluster, nodes, node);
            if (expanded != element) {
                expansionHappened = true;
            }
            array1.add(expanded);
        }
        // only return a new json array if actual expansion happened
        if (expansionHappened) {
            return array1;
        }
    }

    if (json.isJsonObject()) {
        JsonObject object = json.getAsJsonObject();
        JsonObject object1 = new JsonObject();
        boolean expansionHappened = false;
        for (Map.Entry<String, JsonElement> entry : object.entrySet()) {
            JsonElement expanded = expand(entry.getValue(), path, cluster, nodes, node);
            if (expanded != entry.getValue()) {
                expansionHappened = true;
            }
            object1.add(entry.getKey(), expand(entry.getValue(), path, cluster, nodes, node));
        }
        if (expansionHappened) {
            return object1;
        }
    }

    return json;
}

From source file:com.continuuity.weave.internal.logging.LogEntryDecoder.java

License:Open Source License

@Override
public LogEntry deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    if (!json.isJsonObject()) {
        return null;
    }/*  w ww  .ja  v a 2 s.c  om*/
    JsonObject jsonObj = json.getAsJsonObject();

    final String name = jsonObj.get("name").getAsString();
    final String host = jsonObj.get("host").getAsString();
    final long timestamp = Long.parseLong(jsonObj.get("timestamp").getAsString());
    final LogEntry.Level level = LogEntry.Level.valueOf(jsonObj.get("level").getAsString());
    final String className = jsonObj.get("className").getAsString();
    final String method = jsonObj.get("method").getAsString();
    final String file = jsonObj.get("file").getAsString();
    final String line = jsonObj.get("line").getAsString();
    final String thread = jsonObj.get("thread").getAsString();
    final String message = jsonObj.get("message").getAsString();

    final StackTraceElement[] stackTraces = context.deserialize(jsonObj.get("stackTraces").getAsJsonArray(),
            StackTraceElement[].class);

    return new LogEntry() {
        @Override
        public String getLoggerName() {
            return name;
        }

        @Override
        public String getHost() {
            return host;
        }

        @Override
        public long getTimestamp() {
            return timestamp;
        }

        @Override
        public Level getLogLevel() {
            return level;
        }

        @Override
        public String getSourceClassName() {
            return className;
        }

        @Override
        public String getSourceMethodName() {
            return method;
        }

        @Override
        public String getFileName() {
            return file;
        }

        @Override
        public int getLineNumber() {
            if (line.equals("?")) {
                return -1;
            } else {
                return Integer.parseInt(line);
            }
        }

        @Override
        public String getThreadName() {
            return thread;
        }

        @Override
        public String getMessage() {
            return message;
        }

        @Override
        public StackTraceElement[] getStackTraces() {
            return stackTraces;
        }
    };
}

From source file:com.continuuity.weave.yarn.YarnWeaveController.java

License:Open Source License

/**
 * Fetches applicationId from the ZK instance node.
 *///w  ww  .jav a 2s.c om
private ApplicationId fetchApplicationId() {
    byte[] data = getLiveNodeData();
    if (data == null) {
        LOG.warn("No live data node.");
        return null;
    }
    JsonElement json = new Gson().fromJson(new String(data, Charsets.UTF_8), JsonElement.class);
    if (!json.isJsonObject()) {
        LOG.warn("Unable to decode live data node.");
        return null;
    }
    JsonObject jsonObj = json.getAsJsonObject();
    json = jsonObj.get("data");
    if (!json.isJsonObject()) {
        LOG.warn("Property data not found in live data node.");
        return null;
    }
    jsonObj = json.getAsJsonObject();
    ApplicationId appId = Records.newRecord(ApplicationId.class);
    appId.setId(jsonObj.get("appId").getAsInt());
    appId.setClusterTimestamp(jsonObj.get("appIdClusterTime").getAsLong());

    return appId;
}

From source file:com.continuuity.weave.yarn.YarnWeaveRunnerService.java

License:Apache License

/**
 * Decodes application ID stored inside the node data.
 * @param nodeData The node data to decode from. If it is {@code null}, this method would return {@code null}.
 * @return The ApplicationId or {@code null} if failed to decode.
 */// w w  w  . j  ava  2 s . co  m
private ApplicationId getApplicationId(NodeData nodeData) {
    byte[] data = nodeData == null ? null : nodeData.getData();
    if (data == null) {
        return null;
    }

    Gson gson = new Gson();
    JsonElement json = gson.fromJson(new String(data, Charsets.UTF_8), JsonElement.class);
    if (!json.isJsonObject()) {
        LOG.warn("Unable to decode live data node.");
        return null;
    }

    JsonObject jsonObj = json.getAsJsonObject();
    json = jsonObj.get("data");
    if (!json.isJsonObject()) {
        LOG.warn("Property data not found in live data node.");
        return null;
    }

    try {
        ApplicationMasterLiveNodeData amLiveNode = gson.fromJson(json, ApplicationMasterLiveNodeData.class);
        return YarnUtils.createApplicationId(amLiveNode.getAppIdClusterTime(), amLiveNode.getAppId());
    } catch (Exception e) {
        LOG.warn("Failed to decode application live node data.", e);
        return null;
    }
}

From source file:com.contrastsecurity.ide.eclipse.core.extended.ExtendedContrastSDK.java

License:Open Source License

public StoryResource getStory(String orgUuid, String traceId) throws IOException, UnauthorizedException {
    InputStream is = null;//from ww  w.  j a  va 2s .  c  o  m
    InputStreamReader reader = null;
    try {
        String traceUrl = getTraceUrl(orgUuid, traceId);
        is = makeRequest(HttpMethod.GET, traceUrl);
        reader = new InputStreamReader(is);

        String inputString = IOUtils.toString(is, "UTF-8");
        StoryResource story = this.gson.fromJson(inputString, StoryResource.class);
        JsonObject object = (JsonObject) new JsonParser().parse(inputString);
        JsonObject storyObject = (JsonObject) object.get("story");
        if (storyObject != null) {
            JsonArray chaptersArray = (JsonArray) storyObject.get("chapters");
            List<Chapter> chapters = story.getStory().getChapters();
            if (chapters == null) {
                chapters = new ArrayList<>();
            } else {
                chapters.clear();
            }
            for (int i = 0; i < chaptersArray.size(); i++) {
                JsonObject member = (JsonObject) chaptersArray.get(i);
                Chapter chapter = gson.fromJson(member, Chapter.class);
                chapters.add(chapter);
                JsonObject properties = (JsonObject) member.get("properties");
                if (properties != null) {
                    Set<Entry<String, JsonElement>> entries = properties.entrySet();
                    Iterator<Entry<String, JsonElement>> iter = entries.iterator();
                    List<PropertyResource> propertyResources = new ArrayList<>();
                    chapter.setPropertyResources(propertyResources);
                    while (iter.hasNext()) {
                        Entry<String, JsonElement> prop = iter.next();
                        // String key = prop.getKey();
                        JsonElement entryValue = prop.getValue();
                        if (entryValue != null && entryValue.isJsonObject()) {
                            JsonObject obj = (JsonObject) entryValue;
                            JsonElement name = obj.get("name");
                            JsonElement value = obj.get("value");
                            if (name != null && value != null) {
                                PropertyResource propertyResource = new PropertyResource();
                                propertyResource.setName(name.getAsString());
                                propertyResource.setValue(value.getAsString());
                                propertyResources.add(propertyResource);
                            }
                        }
                    }
                }

            }
        }
        return story;
    } finally {
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(reader);
    }
}