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.locationtech.geogig.spring.service.LegacyFilteredChangesService.java

License:Open Source License

public FilteredChanges filterChanges(RepositoryProvider provider, String repoName, InputStream request) {
    final FilteredChanges filteredChanges = new FilteredChanges();
    try {//from w  ww. j  a va  2  s  .co m
        final Reader body = new InputStreamReader(request);
        final JsonParser parser = new JsonParser();
        final JsonElement messageJson = parser.parse(body);

        final HashSet<ObjectId> tracked = new HashSet<>();

        RepositoryFilter filter = new RepositoryFilter();

        ObjectId commitId = ObjectId.NULL;

        if (messageJson.isJsonObject()) {
            final JsonObject message = messageJson.getAsJsonObject();
            final JsonArray trackedArray;
            if (message.has("tracked") && message.get("tracked").isJsonArray()) {
                trackedArray = message.get("tracked").getAsJsonArray();
            } else {
                trackedArray = new JsonArray();
            }
            if (message.has("commitId") && message.get("commitId").isJsonPrimitive()) {
                commitId = ObjectId.valueOf(message.get("commitId").getAsJsonPrimitive().getAsString());
            } else {
                commitId = ObjectId.NULL;
            }
            for (final JsonElement e : trackedArray) {
                if (e.isJsonPrimitive()) {
                    tracked.add(ObjectId.valueOf(e.getAsJsonPrimitive().getAsString()));
                }
            }

            if (message.has("filter") && message.get("filter").isJsonArray()) {
                JsonArray filterArray = message.get("filter").getAsJsonArray();
                for (final JsonElement e : filterArray) {
                    if (e.isJsonObject()) {
                        JsonObject filterObject = e.getAsJsonObject();
                        String featureType = null;
                        String filterType = null;
                        String filterText = null;
                        if (filterObject.has("featurepath")
                                && filterObject.get("featurepath").isJsonPrimitive()) {
                            featureType = filterObject.get("featurepath").getAsJsonPrimitive().getAsString();
                        }
                        if (filterObject.has("type") && filterObject.get("type").isJsonPrimitive()) {
                            filterType = filterObject.get("type").getAsJsonPrimitive().getAsString();
                        }
                        if (filterObject.has("filter") && filterObject.get("filter").isJsonPrimitive()) {
                            filterText = filterObject.get("filter").getAsJsonPrimitive().getAsString();
                        }
                        if (featureType != null && filterType != null && filterText != null) {
                            filter.addFilter(featureType, filterType, filterText);
                        }
                    }
                }

            }
        }

        final Repository repository = getRepository(provider, repoName);

        RevCommit commit = repository.getCommit(commitId);

        ObjectId parent = ObjectId.NULL;
        if (commit.getParentIds().size() > 0) {
            parent = commit.getParentIds().get(0);
        }

        AutoCloseableIterator<DiffEntry> changes = repository.command(DiffOp.class)
                .setNewVersion(commit.getId()).setOldVersion(parent).setReportTrees(true).call();
        FilteredDiffIterator filteredDiffIterator = new FilteredDiffIterator(changes, repository, filter) {
            @Override
            protected boolean trackingObject(ObjectId objectId) {
                return tracked.contains(objectId);
            }
        };

        filteredChanges.setChanges(filteredDiffIterator).setPacker(new BinaryPackedChanges(repository));

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

From source file:org.matrix.androidsdk.rest.model.bingrules.BingRule.java

License:Apache License

/**
 * Search a JsonPrimitive from its value.
 * @param value the jsonPrimitive value.
 * @return the json primitive. null if not found.
 *//* w  ww. j a va  2s. c  om*/
private JsonPrimitive jsonPrimitive(String value) {
    JsonPrimitive jsonPrimitive = null;

    if (null != actions) {
        for (JsonElement json : actions) {
            if (json.isJsonPrimitive()) {
                JsonPrimitive primitive = json.getAsJsonPrimitive();

                try {
                    if (TextUtils.equals(primitive.getAsString(), value)) {
                        jsonPrimitive = primitive;
                        break;
                    }
                } catch (Exception e) {
                    Log.e(LOG_TAG, "## jsonPrimitive() : " + e.getMessage());
                }
            }
        }
    }
    return jsonPrimitive;
}

From source file:org.micromanager.diagnostics.ProblemReport.java

License:BSD License

private Gson makeGson() {
    final DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");

    class MyDateSerializer implements JsonSerializer<Date> {
        @Override/*from w w w.ja v a  2  s  .c o m*/
        public JsonElement serialize(Date src, Type srcType, JsonSerializationContext context) {
            return new JsonPrimitive(format.format(src));
        }
    }

    class MyDateDeserializer implements JsonDeserializer<Date> {
        @Override
        public Date deserialize(JsonElement json, Type dstType, JsonDeserializationContext context)
                throws JsonParseException {
            try {
                return format.parse(json.getAsJsonPrimitive().getAsString());
            } catch (java.text.ParseException e) {
                return null;
            }
        }
    }

    return new GsonBuilder().registerTypeAdapter(Date.class, new MyDateSerializer())
            .registerTypeAdapter(Date.class, new MyDateDeserializer()).create();
}

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 {/*w  ww. j a v a 2  s. c o 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.modelmapper.gson.JsonElementValueReader.java

License:Apache License

public Object get(JsonElement source, String memberName) {
    if (source.isJsonObject()) {
        JsonObject subjObj = source.getAsJsonObject();
        JsonElement propertyElement = subjObj.get(memberName);
        if (propertyElement == null)
            throw new IllegalArgumentException();

        if (propertyElement.isJsonObject())
            return propertyElement.getAsJsonObject();
        if (propertyElement.isJsonArray())
            return propertyElement.getAsJsonArray();
        if (propertyElement.isJsonPrimitive()) {
            JsonPrimitive jsonPrim = propertyElement.getAsJsonPrimitive();
            if (jsonPrim.isBoolean())
                return jsonPrim.getAsBoolean();
            if (jsonPrim.isNumber())
                return jsonPrim.getAsNumber();
            if (jsonPrim.isString())
                return jsonPrim.getAsString();
        }//from   w  ww.ja  va  2 s  .  co m
    }

    return null;
}

From source file:org.mule.modules.servicesource.ApiResponseDeserealizer.java

License:Open Source License

private Map<String, Object> json2Map(JsonObject element) {
    Map<String, Object> record = new HashMap<String, Object>();

    for (Map.Entry<String, JsonElement> member : element.entrySet()) {
        JsonElement value = member.getValue();

        if (value.isJsonObject()) {
            record.put(member.getKey(), this.json2Map(value.getAsJsonObject()));
        } else if (value.isJsonArray()) {
            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
            for (JsonElement child : value.getAsJsonArray()) {
                if (!child.isJsonObject()) {
                    child = GsonFactory.getGson().toJsonTree(child);
                }/*from   w  w  w .  j a v a 2 s.co  m*/
                list.add(this.json2Map(child.getAsJsonObject()));
            }
            record.put(member.getKey(), list);
        } else if (value.isJsonPrimitive()) {
            record.put(member.getKey(), value.getAsJsonPrimitive().getAsString());
        }
    }

    return record;
}

From source file:org.mule.modules.zendesk.jersey.DateDeserializer.java

License:CPAL v1.0

public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    return ISODateTimeFormat.dateTimeNoMillis().parseDateTime(json.getAsJsonPrimitive().getAsString()).toDate();
}

From source file:org.mythtv.android.data.entity.mapper.serializers.DateTimeDeserializer.java

License:Open Source License

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

    if ("".equals(json.getAsJsonPrimitive().getAsString())) {

        return null;
    }//from w w  w  .  j ava 2s. c o m

    return DateTime.parse(json.getAsJsonPrimitive().getAsString(),
            DateTimeFormat.forPattern(pattern).withZoneUTC());
}

From source file:org.nordapp.web.util.GsonHashMapDeserializer.java

License:Apache License

public Object deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {

    if (json.isJsonNull())
        return null;
    else if (json.isJsonPrimitive())
        return handlePrimitive(json.getAsJsonPrimitive());
    else if (json.isJsonArray())
        return handleArray(json.getAsJsonArray(), context);
    else// w w  w . j a va 2 s.  c  o  m
        return handleObject(json.getAsJsonObject(), context);
}

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

License:Apache License

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

    DateTimeFormatter fmt = OneBusAwayDateFormats.DATETIMEPATTERN_JSON_DATE_TIME;
    DateTime result = fmt.parseDateTime(json.getAsJsonPrimitive().getAsString());

    return result;
}