Example usage for com.google.gson JsonElement isJsonPrimitive

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

Introduction

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

Prototype

public boolean isJsonPrimitive() 

Source Link

Document

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

Usage

From source file:org.metawidget.inspector.json.JsonInspector.java

License:LGPL

public Element inspectAsDom(Object toInspect, String type, String... names) {

    JsonObject root = getRoot();//from  w ww.j  av  a  2  s  .c  o m

    // Traverse names

    for (String name : names) {

        if (!root.has(name)) {
            return null;
        }

        root = root.getAsJsonObject(name);
    }

    // Start the DOM

    Document document = XmlUtils.newDocument();
    Element documentRoot = document.createElementNS(NAMESPACE, ROOT);
    documentRoot.setAttribute(VERSION, "1.0");
    document.appendChild(documentRoot);
    Element entity = document.createElementNS(NAMESPACE, ENTITY);
    entity.setAttribute(TYPE, type);
    documentRoot.appendChild(entity);

    // Write all JSON values into it

    for (Map.Entry<String, JsonElement> entry : root.entrySet()) {

        JsonElement element = entry.getValue();

        // Write the name

        Element child = document.createElementNS(NAMESPACE, PROPERTY);
        child.setAttribute(NAME, entry.getKey());

        // Write the type

        if (element.isJsonPrimitive()) {

            JsonPrimitive primitive = (JsonPrimitive) element;

            if (primitive.isNumber()) {
                child.setAttribute(TYPE, int.class.getName());
            } else if (primitive.isBoolean()) {
                child.setAttribute(TYPE, boolean.class.getName());
            } else {
                child.setAttribute(TYPE, String.class.getName());
            }
        } else if (element.isJsonArray()) {
            child.setAttribute(TYPE, "array");
        } else {
            child.setAttribute(TYPE, Object.class.getName());
        }

        entity.appendChild(child);
    }

    // Return the DOM

    return documentRoot;
}

From source file:org.metawidget.inspector.json.schema.JsonSchemaInspector.java

License:LGPL

private void writeJsonAttributesAsDom(Element element, JsonObject object) {

    for (Map.Entry<String, JsonElement> entry : object.entrySet()) {

        String name = entry.getKey();
        JsonElement jsonElement = entry.getValue();

        if (jsonElement.isJsonArray()) {
            List<String> array = CollectionUtils.newArrayList();
            for (Iterator<JsonElement> i = jsonElement.getAsJsonArray().iterator(); i.hasNext();) {
                array.add(i.next().getAsString());
            }/*ww  w  .j  ava2s.  co m*/
            element.setAttribute(name, CollectionUtils.toString(array));
            continue;
        }

        if (!jsonElement.isJsonPrimitive()) {
            continue;
        }

        element.setAttribute(name, jsonElement.getAsString());
    }
}

From source file:org.mitre.openid.connect.config.JsonMessageSource.java

License:Apache License

/**
 * Get a value from a single map//from w  w  w . j a  va  2s  .  co  m
 * @param code
 * @param lang
 * @return
 */
private String getValue(String code, JsonObject lang) {

    // if there's no language map, nothing to look up
    if (lang == null) {
        return null;
    }

    JsonElement e = lang;

    Iterable<String> parts = Splitter.on('.').split(code);
    Iterator<String> it = parts.iterator();

    String value = null;

    while (it.hasNext()) {
        String p = it.next();
        if (e.isJsonObject()) {
            JsonObject o = e.getAsJsonObject();
            if (o.has(p)) {
                e = o.get(p); // found the next level
                if (!it.hasNext()) {
                    // we've reached a leaf, grab it
                    if (e.isJsonPrimitive()) {
                        value = e.getAsString();
                    }
                }
            } else {
                // didn't find it, stop processing
                break;
            }
        } else {
            // didn't find it, stop processing
            break;
        }
    }

    return value;
}

From source file:org.mitre.provenance.asias.Ingest_AsiasJson.java

License:Apache License

private static void createInvocationAndDataNode(String jsonString, ProvenanceCollection col) throws Exception {
    // System.out.println(jsonString);
    JsonElement elem = g.fromJson(jsonString, JsonElement.class);
    if (!elem.isJsonObject())
        throw new Exception("Server response wasn't a JSON object " + elem);
    JsonObject obj = elem.getAsJsonObject();

    // "name" is a required field for ASIAS invocation nodes.
    String analytic_name = obj.get("name").getAsString();
    PLUSInvocation invocation = new PLUSInvocation(analytic_name);
    System.out.println("Adding Node '" + analytic_name + "'. (" + obj.get("meta_id").getAsString() + ")");

    String output_name = analytic_name + "_output";
    if (obj.get("output_name") != null) {
        output_name = obj.get("output_name").getAsString();
    }//from w  w  w  .  ja  va  2 s. com
    PLUSString data = new PLUSString(output_name);

    String content = obj.get("output_schemas_json").getAsString();
    data.setContent(content);
    SHA256ContentHasher myHasher = new SHA256ContentHasher();
    String hashAsString = ContentHasher.formatAsHexString(
            myHasher.hash(new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8))));

    data.getMetadata().put(Metadata.CONTENT_HASH_SHA_256, hashAsString);

    /* Adding properties with as few exceptions as possible, in light of requirements. */
    for (Map.Entry<String, JsonElement> entry : obj.entrySet()) {
        JsonElement jsonElement = entry.getValue();
        String topLevelElement = entry.getKey();
        if (topLevelElement.equals("params_json")) {
            //first, transform out to JSON Object from string
            JsonObject jParams = (JsonObject) toJsonElement(jsonElement);

            // second, establish separate data nodes that feed into the invocation node.
            // Caveat:  This assumes json_params depth is 1.  There has been no discussion on "nesting" in param nodes.
            for (Map.Entry<String, JsonElement> param : jParams.entrySet()) {
                JsonElement paramElement = param.getValue();
                String paramKey = param.getKey();
                String paramValue;
                if (paramElement.isJsonPrimitive()) {
                    paramValue = paramElement.getAsString();
                } else {
                    paramValue = paramElement.toString();
                }
                PLUSString paramNode = new PLUSString(paramKey);
                paramNode.setContent(paramValue);

                // criteria for hashing/uniqueness of param nodes is key plus its value.  (possibly open to revision)
                String paramValueUnique = paramKey + "_" + paramValue;
                String hashString = ContentHasher.formatAsHexString(myHasher
                        .hash(new ByteArrayInputStream(paramValueUnique.getBytes(StandardCharsets.UTF_8))));
                paramNode.getMetadata().put(Metadata.CONTENT_HASH_SHA_256, hashString);

                // Now add hash of value plus process it feeds.  This is so we can make the distinction for NPE types later.
                String paramValueProcessUnique = paramValueUnique + analytic_name;
                String hashStringProcessUnique = ContentHasher.formatAsHexString(myHasher.hash(
                        new ByteArrayInputStream(paramValueProcessUnique.getBytes(StandardCharsets.UTF_8))));
                paramNode.getMetadata().put("sha256hashSpecficProcess", hashStringProcessUnique);

                col.addNode(paramNode);

                // third, establish link from *parameter* node to *invocation* node.
                col.addEdge(new PLUSEdge(paramNode, invocation, PLUSWorkflow.DEFAULT_WORKFLOW,
                        PLUSEdge.EDGE_TYPE_INPUT_TO));

                // Add non-provenance edges for params, but only if they match a previously-loaded parameter.
                if (hashString != null) {
                    //  First look through already loaded nodes to see if other params match.
                    List<PLUSObject> loadList = new ArrayList<PLUSObject>();
                    if (hashedParamNodeLookup.get(hashString) != null) {
                        loadList = hashedParamNodeLookup.get(hashString);

                        Iterator<PLUSObject> listIterator = loadList.iterator();
                        while (listIterator.hasNext()) {
                            PLUSObject otherParam = listIterator.next();
                            String type = "Same Parameter Value, Different Process";
                            if (otherParam.getMetadata().get("sha256hashSpecficProcess")
                                    .equals(paramNode.getMetadata().get("sha256hashSpecficProcess"))) {
                                type = "Same Parameter Value, Same Process";
                            }
                            NonProvenanceEdge npe = new NonProvenanceEdge(paramNode, otherParam, type);
                            System.out.println("adding '" + type + "' NPE from " + paramNode.getId() + " to "
                                    + otherParam.getId());
                            col.addNonProvenanceEdge(npe);
                        }
                    }
                    loadList.add(paramNode);
                    hashedParamNodeLookup.put(hashString, loadList);

                    //  Secondly, do the same thing for previously-loaded nodes in the database.
                    ProvenanceCollection match = new ProvenanceCollection();
                    PLUSObject otherParam = null;
                    Metadata parameters = new Metadata();
                    parameters.put(Metadata.CONTENT_HASH_SHA_256, hashString);
                    match = client.search(parameters, 500);
                    Iterator<PLUSObject> equivalentValues = match.getNodes().iterator();
                    while (equivalentValues.hasNext()) {
                        otherParam = equivalentValues.next();
                        if (!col.contains(otherParam)) {
                            col.addNode(otherParam); // duplicate, only to add NPE.
                        }
                        String type = "Same Parameter Value, Different Process";
                        if (otherParam.getMetadata().get("sha256hashSpecficProcess")
                                .equals(paramNode.getMetadata().get("sha256hashSpecficProcess"))) {
                            type = "Same Parameter Value, Same Process";
                        }
                        NonProvenanceEdge npe = new NonProvenanceEdge(paramNode, otherParam, type);
                        System.out.println("adding '" + type + "' NPE from " + paramNode.getId() + " to "
                                + otherParam.getId());
                        col.addNonProvenanceEdge(npe);
                    }
                    equivalentValues = null;
                }
            }

        } else if (topLevelElement.equals("job_counters")) {
            // only need special handling for "job_counters" because it comes in as a string.
            // if it changes to be JSON in its natural state, this block can be removed.
            addProperty(invocation, topLevelElement, toJsonElement(jsonElement));
        } else if (!topLevelElement.equals("name")
                //&& !topLevelElement.equals("meta_id") 
                && !topLevelElement.equals("output_name") && !topLevelElement.equals("output_schemas_json")
                && !topLevelElement.equals("path")) { // If not one of our special use elements
            addProperty(invocation, topLevelElement, jsonElement);
        } else if (topLevelElement.equals("output_schemas_json") || topLevelElement.equals("path")) {
            // special handling for the output data node's parameters.
            addProperty(data, topLevelElement, jsonElement);
        }
        if (topLevelElement.equals("input_schemas_json")) {
            String hashString = ContentHasher.formatAsHexString(myHasher
                    .hash(new ByteArrayInputStream(jsonElement.toString().getBytes(StandardCharsets.UTF_8))));
            invocation.getMetadata().put(Metadata.CONTENT_HASH_SHA_256, hashString);
        }
    }

    /* Lookups getting set here so that the backwards/forwards lineage edges can be determined afterward. */
    String meta_id = obj.get("meta_id").getAsString();
    nodeLookup.put(meta_id, data); // might be non-intuitive, but we're assigning meta_id as key for data node. 
    nodeLookup.put(analytic_name + "_" + meta_id, invocation); // analytic name is lookup key for invocation node.

    data.getMetadata().put("joins", meta_id); // This is for lookup later, should later runs reference this output.

    invocation.setCreated(); // timestamp "now".
    //invocation.getMetadata().put("ingest", "ASIAS-JSON");  // tag for deleting draft nodes later.   Uncomment if desired.   
    if (obj.get("input_meta_ids") != null) {
        JsonArray input_meta_id = obj.getAsJsonArray("input_meta_ids");
        for (JsonElement in_meta_id : input_meta_id) {
            TreeMap<String, String> addEdge = new TreeMap<String, String>();
            addEdge.put(in_meta_id.getAsString(), analytic_name + "_" + meta_id);
            edgeMap.add(addEdge);
        }
    }
    col.addNode(invocation);
    col.addNode(data);
    col.addEdge(new PLUSEdge(invocation, data, PLUSWorkflow.DEFAULT_WORKFLOW, PLUSEdge.EDGE_TYPE_GENERATED));
}

From source file:org.mitre.provenance.asias.Ingest_AsiasJson.java

License:Apache License

public static void addProperty(PLUSObject node, String propertyName, JsonElement propertyValue) {
    if (propertyValue.isJsonPrimitive()) {
        //System.out.println("  Adding property " + propertyName+".");
        node.getMetadata().put(propertyName, propertyValue.getAsString());
    }/*  www  .  j  av a  2  s .c om*/
    // ***************************************
    // For arrays and Objects, break out into 1st-level properties, with property label reflecting object hierarchy. 
    // ***************************************
    else if (propertyValue.isJsonArray()) {
        JsonArray arrayObj = propertyValue.getAsJsonArray();
        if (arrayObj.size() == 1) {
            addProperty(node, propertyName, arrayObj.get(0));
        } else if (arrayObj.size() > 1) {
            int count = 1;
            for (JsonElement arrayElement : arrayObj) {
                addProperty(node, propertyName + "_" + count, arrayElement);
                count++;
            }
        }
    } else {
        JsonObject obj = propertyValue.getAsJsonObject();
        for (Map.Entry<String, JsonElement> entry : obj.entrySet()) {
            JsonElement subElement = entry.getValue();
            String elementName = entry.getKey();
            addProperty(node, propertyName + "__" + elementName, subElement);
        }
    }
}

From source file:org.mitre.provenance.asias.Ingest_AsiasJson.java

License:Apache License

public static JsonElement toJsonElement(JsonElement jsonElement) {
    JsonElement returnObj;/*from   w w  w .  j  a v a 2  s.c om*/
    if (jsonElement.isJsonPrimitive()) {
        String p_j = jsonElement.getAsString();
        p_j = p_j.replaceAll("\\\"", "\""); //clean up escaping so we can parse as JsonObj.
        return g.fromJson(p_j, JsonElement.class);
    } else {
        return jsonElement;
    }
}

From source file:org.mitre.provenance.client.RESTProvenanceClient.java

License:Apache License

public boolean dominates(PrivilegeClass a, PrivilegeClass b) throws ProvenanceClientException {
    Builder r = getRequestBuilderForPath(PRIVILEGE_PATH + a.getId() + "/" + b.getId());
    Response response = r.get();/*from w w  w  .  j  ava  2s.  co m*/
    Gson g = new GsonBuilder().create();
    String txt = response.readEntity(String.class);
    JsonElement elem = g.fromJson(txt, JsonElement.class);
    if (elem.isJsonPrimitive())
        return elem.getAsBoolean();
    throw new ProvenanceClientException(txt);
}

From source file:org.mitre.provenance.plusobject.json.JsonObjectPropertyWrapper.java

License:Apache License

public Object getProperty(String key) {
    if (!obj.has(key))
        return null;
    //JsonPrimitive p = obj.get(key).getAsJsonPrimitive();
    JsonElement elem = obj.get(key);

    if (elem.isJsonPrimitive() && ((JsonPrimitive) elem).isString())
        return elem.getAsString();
    if (elem.isJsonPrimitive() && ((JsonPrimitive) elem).isNumber())
        return elem.getAsLong();

    if (elem.isJsonArray()) {
        JsonArray arr = (JsonArray) elem;

        String[] r = new String[arr.size()];

        for (int x = 0; x < arr.size(); x++) {
            r[x] = arr.get(x).getAsString();
        }/*w  w  w  . ja  v a2  s. c o m*/

        return r;
    }

    // Default case.
    return elem.getAsString();
}

From source file:org.mitre.provenance.plusobject.json.ProvenanceCollectionDeserializer.java

License:Apache License

protected static PLUSObject convertObject(JsonObject obj, ProvenanceCollection contextCollection)
        throws JsonParseException {
    String t = obj.get(JSONConverter.KEY_TYPE).getAsString();
    String st = obj.get(JSONConverter.KEY_SUBTYPE).getAsString();
    String name = obj.get(JSONConverter.KEY_NAME).getAsString();

    if (name == null || "null".equals(name))
        throw new JsonParseException("Missing name on object " + obj);
    if (t == null || "null".equals(t))
        throw new JsonParseException("Missing type on object " + obj);
    if (st == null || "null".equals(st))
        throw new JsonParseException("Missing subtype on object " + obj);

    JsonObjectPropertyWrapper n = new JsonObjectPropertyWrapper(obj);

    try {//from   ww  w  .  j  a  v  a 2  s  .  co m
        PLUSObject o = null;

        if (PLUSInvocation.PLUS_SUBTYPE_INVOCATION.equals(st)) {
            o = new PLUSInvocation().setProperties(n, contextCollection);
        } else if (PLUSWorkflow.PLUS_TYPE_WORKFLOW.equals(t)) {
            o = new PLUSWorkflow().setProperties(n, contextCollection);
        } else if (st.equals(PLUSString.PLUS_SUBTYPE_STRING)) {
            o = new PLUSString().setProperties(n, contextCollection);
        } else if (PLUSFile.PLUS_SUBTYPE_FILE.equals(st)) {
            o = new PLUSFile().setProperties(n, contextCollection);
        } else if (PLUSFileImage.PLUS_SUBTYPE_FILE_IMAGE.equals(st)) {
            o = new PLUSFileImage().setProperties(n, contextCollection);
        } else if (PLUSURL.PLUS_SUBTYPE_URL.equals(st)) {
            o = new PLUSURL().setProperties(n, contextCollection);
        } else if (PLUSActivity.PLUS_TYPE_ACTIVITY.equals(t)) {
            o = new PLUSActivity().setProperties(n, contextCollection);
        } else if (PLUSRelational.PLUS_SUBTYPE_RELATIONAL.equals(st)) {
            o = new PLUSRelational().setProperties(n, contextCollection);
        } else if (Taint.PLUS_SUBTYPE_TAINT.equals(st)) {
            o = new Taint().setProperties(n, contextCollection);
        } else {
            log.info("Couldn't find more specific type for " + t + "/" + st + " so loading as generic.");
            o = new PLUSGeneric().setProperties(n, contextCollection);
        }

        // Check metadata
        if (obj.has(JSONConverter.KEY_METADATA) && obj.get(JSONConverter.KEY_METADATA).isJsonObject()) {
            JsonObject md = obj.get(JSONConverter.KEY_METADATA).getAsJsonObject();

            Metadata m = new Metadata();

            for (Map.Entry<String, JsonElement> entry : md.entrySet()) {
                String key = entry.getKey();
                String val = null;

                JsonElement v = entry.getValue();
                if (!v.isJsonPrimitive()) {
                    log.warning("Skipping metadata key/value " + key + " => " + v
                            + " because value isn't primitive.");
                    continue;
                } else {
                    val = v.getAsJsonPrimitive().getAsString();
                }

                m.put(key, val);
            } // End for

            o.getMetadata().putAll(m);
        }

        // Check owner status.
        // Property is not guaranteed to be present; if it's present, get it as a string, otherwise use null.
        String aid = (obj.get("ownerid") != null ? obj.get("ownerid").getAsString() : null);

        // log.info("Deserializing " + o + " actorID = " + aid + " and owner=" + obj.get(JSONConverter.KEY_OWNER));
        if (isBlank(aid) && obj.has(JSONConverter.KEY_OWNER)) {
            JsonElement ownerJson = obj.get(JSONConverter.KEY_OWNER);
            if (!ownerJson.isJsonObject())
                throw new JsonParseException("Property 'owner' must be an object on " + obj);

            PLUSActor owner = convertActor((JsonObject) ownerJson);
            if (owner != null) {
                log.info("Set using converted owner property " + owner);
                o.setOwner(owner);
            }
        } else if (!isBlankOrNull(aid)) {
            if (contextCollection.containsActorID(aid)) {
                // log.info("Set using provided context collection " + contextCollection.getActor(aid));
                o.setOwner(contextCollection.getActor(aid));
            } else {
                log.severe("Deserializer cannot find actor by dangling reference " + aid
                        + " - provenance context collection is needed to identify this actor without database access.");
                o.setOwner(null);
            }
        }

        return o;
    } catch (PLUSException exc) {
        exc.printStackTrace();
        throw new JsonParseException(exc.getMessage());
    }
}

From source file:org.mitre.util.JsonUtils.java

License:Apache License

/**
 * Gets the value of the given member (expressed as integer seconds since epoch) as a Date
 *//*w w  w. j  av a2s. c o  m*/
public static Date getAsDate(JsonObject o, String member) {
    if (o.has(member)) {
        JsonElement e = o.get(member);
        if (e != null && e.isJsonPrimitive()) {
            return new Date(e.getAsInt() * 1000L);
        } else {
            return null;
        }
    } else {
        return null;
    }
}