Example usage for com.google.gson JsonObject has

List of usage examples for com.google.gson JsonObject has

Introduction

In this page you can find the example usage for com.google.gson JsonObject has.

Prototype

public boolean has(String memberName) 

Source Link

Document

Convenience method to check if a member with the specified name is present in this object.

Usage

From source file:com.google.wave.api.impl.EventMessageBundleGsonAdaptor.java

License:Apache License

@Override
public EventMessageBundle deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    JsonObject jsonObj = json.getAsJsonObject();
    String robotAddress = jsonObj.get(ROBOT_ADDRESS_TAG).getAsString();
    String rpcServerUrl = "";
    if (jsonObj.has(RPC_SERVER_URL_TAG)) {
        rpcServerUrl = jsonObj.get(RPC_SERVER_URL_TAG).getAsString();
    }//w  w  w .j a  v  a 2  s  .c om
    EventMessageBundle result = new EventMessageBundle(robotAddress, rpcServerUrl);

    OperationQueue operationQueue;
    if (jsonObj.has(PROXYING_FOR_TAG)) {
        result.setProxyingFor(jsonObj.get(PROXYING_FOR_TAG).getAsString());
        operationQueue = new OperationQueue(new ArrayList<OperationRequest>(), result.getProxyingFor());
    } else {
        operationQueue = new OperationQueue();
    }

    // Deserialize wavelet.
    WaveletData waveletData = context.deserialize(jsonObj.get(WAVELET_TAG), WaveletData.class);
    result.setWaveletData(waveletData);
    Map<String, Blip> blips = new HashMap<String, Blip>();
    Map<String, BlipThread> threads = new HashMap<String, BlipThread>();
    Wavelet wavelet = Wavelet.deserialize(operationQueue, blips, threads, waveletData);
    wavelet.setRobotAddress(robotAddress);
    result.setWavelet(wavelet);

    // Deserialize threads.
    Map<String, BlipThread> tempThreads = context.deserialize(jsonObj.get(THREADS_TAG),
            GsonFactory.THREAD_MAP_TYPE);
    for (Entry<String, BlipThread> entry : tempThreads.entrySet()) {
        BlipThread thread = entry.getValue();
        threads.put(entry.getKey(),
                new BlipThread(thread.getId(), thread.getLocation(), thread.getBlipIds(), blips));
    }

    // Deserialize blips.
    Map<String, BlipData> blipDatas = context.deserialize(jsonObj.get(BLIPS_TAG), GsonFactory.BLIP_MAP_TYPE);
    result.setBlipData(blipDatas);
    for (Entry<String, BlipData> entry : blipDatas.entrySet()) {
        blips.put(entry.getKey(), Blip.deserialize(operationQueue, wavelet, entry.getValue()));
    }

    // Deserialize events.
    JsonArray eventsArray = jsonObj.get(EVENTS_TAG).getAsJsonArray();
    List<Event> events = new ArrayList<Event>(eventsArray.size());
    for (JsonElement element : eventsArray) {
        JsonObject eventObject = element.getAsJsonObject();
        try {
            events.add(EventSerializer.deserialize(wavelet, result, eventObject, context));
        } catch (EventSerializationException e) {
            throw new JsonParseException(e.getMessage());
        }
    }
    result.setEvents(events);
    return result;
}

From source file:com.google.wave.api.impl.JsonRpcResponseGsonAdaptor.java

License:Apache License

@Override
public JsonRpcResponse deserialize(JsonElement json, Type type, JsonDeserializationContext context)
        throws JsonParseException {
    JsonObject jsonObject = json.getAsJsonObject();

    String id = jsonObject.get(ResponseProperty.ID.key()).getAsString();
    if (jsonObject.has(ResponseProperty.ERROR.key())) {
        JsonElement errorObject = jsonObject.get(ResponseProperty.ERROR.key());
        String errorMessage = errorObject.getAsJsonObject().get("message").getAsString();
        return JsonRpcResponse.error(id, errorMessage);
    }/*from  www . ja v  a2 s.com*/

    // Deserialize the data.
    Map<ParamsProperty, Object> properties = new HashMap<ParamsProperty, Object>();
    JsonElement data = jsonObject.get(ResponseProperty.DATA.key());
    if (data != null && data.isJsonObject()) {
        for (Entry<String, JsonElement> parameter : data.getAsJsonObject().entrySet()) {
            ParamsProperty parameterType = ParamsProperty.fromKey(parameter.getKey());
            if (parameterType == null) {
                // Skip this unknown parameter.
                continue;
            }
            Object object = null;
            if (parameterType == ParamsProperty.BLIPS) {
                object = context.deserialize(parameter.getValue(), GsonFactory.BLIP_MAP_TYPE);
            } else if (parameterType == ParamsProperty.PARTICIPANTS_ADDED
                    || parameterType == ParamsProperty.PARTICIPANTS_REMOVED) {
                object = context.deserialize(parameter.getValue(), GsonFactory.PARTICIPANT_LIST_TYPE);
            } else if (parameterType == ParamsProperty.THREADS) {
                object = context.deserialize(parameter.getValue(), GsonFactory.THREAD_MAP_TYPE);
            } else if (parameterType == ParamsProperty.WAVELET_IDS) {
                object = context.deserialize(parameter.getValue(), GsonFactory.WAVELET_ID_LIST_TYPE);
            } else if (parameterType == ParamsProperty.RAW_DELTAS) {
                object = context.deserialize(parameter.getValue(), GsonFactory.RAW_DELTAS_TYPE);
            } else {
                object = context.deserialize(parameter.getValue(), parameterType.clazz());
            }
            properties.put(parameterType, object);
        }
    }

    return JsonRpcResponse.result(id, properties);
}

From source file:com.google.wave.api.RobotSerializer.java

License:Apache License

/**
 * Determines the protocol version of a given operation bundle JSON by
 * inspecting the first operation in the bundle. If it is a
 * {@code robot.notify} operation, and contains {@code protocolVersion}
 * parameter, then this method will return the value of that parameter.
 * Otherwise, this method will return the default version.
 *
 * @param operationBundle the operation bundle to check.
 * @return the wire protocol version of the given operation bundle.
 *//*w ww  . ja  v  a 2s.  c om*/
private ProtocolVersion determineProtocolVersion(JsonArray operationBundle) {
    if (operationBundle.size() == 0 || !operationBundle.get(0).isJsonObject()) {
        return defaultProtocolVersion;
    }

    JsonObject firstOperation = operationBundle.get(0).getAsJsonObject();
    if (!firstOperation.has(RequestProperty.METHOD.key())) {
        return defaultProtocolVersion;
    }

    String method = firstOperation.get(RequestProperty.METHOD.key()).getAsString();
    if (isRobotNotifyOperationMethod(method)) {
        JsonObject params = firstOperation.get(RequestProperty.PARAMS.key()).getAsJsonObject();
        if (params.has(ParamsProperty.PROTOCOL_VERSION.key())) {
            JsonElement protocolVersionElement = params.get(ParamsProperty.PROTOCOL_VERSION.key());
            if (!protocolVersionElement.isJsonNull()) {
                return ProtocolVersion.fromVersionString(protocolVersionElement.getAsString());
            }
        }
    }
    return defaultProtocolVersion;
}

From source file:com.google.wave.api.RobotSerializer.java

License:Apache License

/**
 * Validates that the incoming JSON is a JSON object that represents a
 * JSON-RPC request./*from   w  w  w .  j av  a2s  .c o  m*/
 *
 * @param jsonElement the incoming JSON.
 * @throws InvalidRequestException if the incoming JSON does not have the
 *     required properties.
 */
private static void validate(JsonElement jsonElement) throws InvalidRequestException {
    if (!jsonElement.isJsonObject()) {
        throw new InvalidRequestException("The incoming JSON is not a JSON object: " + jsonElement);
    }

    JsonObject jsonObject = jsonElement.getAsJsonObject();

    StringBuilder missingProperties = new StringBuilder();
    for (RequestProperty requestProperty : RequestProperty.values()) {
        if (!jsonObject.has(requestProperty.key())) {
            missingProperties.append(requestProperty.key());
        }
    }

    if (missingProperties.length() > 0) {
        throw new InvalidRequestException(
                "Missing required properties " + missingProperties + "operation: " + jsonObject);
    }
}

From source file:com.google.wave.api.v2.ElementGsonAdaptorV2.java

License:Apache License

@Override
public Element deserialize(JsonElement jsonElement, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    JsonObject json = jsonElement.getAsJsonObject();
    String type = json.get(TYPE_TAG).getAsString();

    if (ElementType.IMAGE.name().equals(type)) {
        JsonObject properties = json.getAsJsonObject(PROPERTIES_TAG);
        if (!properties.has(Image.URL)) {
            json.addProperty(TYPE_TAG, ElementType.ATTACHMENT.name());
        }//from  w w  w.  j  a va 2s.  co  m
    }
    return super.deserialize(json, typeOfT, context);
}

From source file:com.google.wave.splash.data.serialize.JsonSerializer.java

License:Apache License

/**
 * Parses a string of json from a wave.robot.fetchWave into a result.
 *
 * @param json the json to parse.//from   w ww .j  av  a2s .c  om
 * @return the result object, which may not contain a wavelet.
 */
@Timed
public FetchWaveletResult parseFetchWaveletResult(String json) {
    JsonObject dataObject = getDataObject(json);
    if (dataObject == null || !dataObject.has("waveletData")) {
        LOG.warning("Fetch returned empty result.");
        return FetchWaveletResult.emptyResult();
    }

    JsonObject waveletDataJson = dataObject.getAsJsonObject("waveletData");
    OperationQueue operationQueue = new OperationQueue();
    WaveletData waveletData = gson.fromJson(waveletDataJson, WaveletData.class);

    Map<String, Blip> blips = Maps.newHashMap();
    HashMap<String, BlipThread> threads = Maps.newHashMap();
    Wavelet wavelet = Wavelet.deserialize(operationQueue, blips, threads, waveletData);

    JsonObject threadMap = dataObject.getAsJsonObject("threads");
    if (null != threadMap) {
        for (Map.Entry<String, JsonElement> entries : threadMap.entrySet()) {
            JsonObject threadElement = entries.getValue().getAsJsonObject();
            int location = threadElement.get("location").getAsInt();

            List<String> blipIds = Lists.newArrayList();
            for (JsonElement blipId : threadElement.get("blipIds").getAsJsonArray()) {
                blipIds.add(blipId.getAsString());
            }

            BlipThread thread = new BlipThread(entries.getKey(), location, blipIds, blips);
            threads.put(thread.getId(), thread);
        }
    }

    JsonObject blipMap = dataObject.getAsJsonObject("blips");
    for (Map.Entry<String, JsonElement> entries : blipMap.entrySet()) {
        BlipData blipData = gson.fromJson(entries.getValue(), BlipData.class);
        Blip blip = Blip.deserialize(operationQueue, wavelet, blipData);
        blips.put(blipData.getBlipId(), blip);
    }

    return new FetchWaveletResult(wavelet);
}

From source file:com.google.wave.splash.data.serialize.JsonSerializer.java

License:Apache License

@Timed
public FetchProfilesResult parseFetchProfilesResult(String json) {
    JsonObject dataObject = getDataObject(json);
    if (dataObject == null || !dataObject.has("fetchProfilesResult")) {
        LOG.warning("Fetch profiles returned empty result.");
        return new FetchProfilesResult(ImmutableList.<ParticipantProfile>of());
    }// w  ww  . j  a v a  2  s . c o  m

    // TODO: Parse the result when this service works.
    return new FetchProfilesResult(ImmutableList.<ParticipantProfile>of());
}

From source file:com.graphaware.module.es.proc.ESModuleEndToEndProcTestAdvanced.java

License:Open Source License

public void testEsMapping(boolean node) {
    String itemType = node ? "node" : "relationship";

    // match all items
    try (Transaction tx = getDatabase().beginTx()) {
        Result result = getDatabase().execute("CALL ga.es." + itemType + "Mapping() YIELD json return json");

        List<String> columns = result.columns();
        assertEquals(columns.size(), 1);

        Map<String, Object> next = result.next();
        assertTrue(next.get("json") instanceof String);
        JsonObject e = new JsonParser().parse((String) next.get("json")).getAsJsonObject();

        assertTrue(e.has("mappings"));
        assertTrue(e.get("mappings").isJsonObject());

        // item types
        e.get("mappings").getAsJsonObject().entrySet().stream().forEach(typeEntry -> {
            // item type
            assertTrue(typeEntry.getKey() instanceof String);
            assertEquals(typeEntry.getKey(), itemType);

            // item properties
            assertTrue(typeEntry.getValue() instanceof JsonObject);
            JsonObject typeProps = (JsonObject) typeEntry.getValue();
            assertTrue(typeProps.has("properties"));

            JsonObject propertiesMapping = typeProps.get("properties").getAsJsonObject();
            propertiesMapping.entrySet().stream().forEach(propertyMapping -> {
                // property key
                assertTrue(propertyMapping.getKey() instanceof String);

                // property mapping info
                assertTrue(propertyMapping.getValue() instanceof JsonObject);
                JsonObject propertyInfo = (JsonObject) propertyMapping.getValue();
                assertTrue(propertyInfo.has("type"));
            });//  ww  w.ja  va 2 s . c  om

            String categField = node ? AdvancedMapping.LABELS_FIELD : AdvancedMapping.RELATIONSHIP_FIELD;

            assertTrue(propertiesMapping.has(categField));
            assertTrue(propertiesMapping.get(categField).isJsonObject());
            JsonObject categMapping = propertiesMapping.get(categField).getAsJsonObject();
            // categ field has type:string
            categMapping.get("type").isJsonPrimitive();
            assertEquals(categMapping.get("type").getAsString(), "string");
            // categ field has fields:{raw:{type:string, index:not_analyzed}}
            assertTrue(categMapping.get("fields").isJsonObject());
            assertTrue(categMapping.get("fields").getAsJsonObject().has("raw"));
            assertTrue(categMapping.get("fields").getAsJsonObject().get("raw").isJsonObject());
            JsonObject rawField = categMapping.get("fields").getAsJsonObject().get("raw").getAsJsonObject();
            // raw categ field
            assertTrue(rawField.has("type"));
            assertTrue(rawField.get("type").isJsonPrimitive());
            assertEquals(rawField.get("type").getAsString(), "string");
            assertTrue(rawField.has("index"));
            assertTrue(rawField.get("index").isJsonPrimitive());
            assertEquals(rawField.get("index").getAsString(), "not_analyzed");
        });

        tx.success();
    }
}

From source file:com.graphhopper.json.FeatureJsonDeserializer.java

License:Apache License

@Override
public JsonFeature deserialize(JsonElement json, Type type, JsonDeserializationContext context)
        throws JsonParseException {
    try {//from w  ww . jav a  2 s. co  m
        JsonObject obj = json.getAsJsonObject();
        String id, strType = null;
        Map<String, Object> properties = null;
        BBox bbox = null;
        Geometry geometry = null;

        // TODO ensure uniqueness
        if (obj.has("id"))
            id = obj.get("id").getAsString();
        else
            id = UUID.randomUUID().toString();

        if (obj.has("properties")) {
            properties = context.deserialize(obj.get("properties"), Map.class);
        }

        if (obj.has("bbox"))
            bbox = parseBBox(obj.get("bbox").getAsJsonArray());

        if (obj.has("geometry")) {
            JsonObject geometryJson = obj.get("geometry").getAsJsonObject();

            if (geometryJson.has("coordinates")) {
                if (!geometryJson.has("type"))
                    throw new IllegalArgumentException("No type for non-empty coordinates specified");

                strType = context.deserialize(geometryJson.get("type"), String.class);
                if ("Point".equals(strType)) {
                    JsonArray arr = geometryJson.get("coordinates").getAsJsonArray();
                    double lon = arr.get(0).getAsDouble();
                    double lat = arr.get(1).getAsDouble();
                    if (arr.size() == 3)
                        geometry = new Point(lat, lon, arr.get(2).getAsDouble());
                    else
                        geometry = new Point(lat, lon);

                } else if ("MultiPoint".equals(strType)) {
                    geometry = parseLineString(geometryJson);

                } else if ("LineString".equals(strType)) {
                    geometry = parseLineString(geometryJson);

                } else {
                    throw new IllegalArgumentException("Coordinates type " + strType + " not yet supported");
                }
            }
        }

        return new JsonFeature(id, strType, bbox, geometry, properties);

    } catch (Exception ex) {
        throw new JsonParseException("Problem parsing JSON feature " + json);
    }
}

From source file:com.graphhopper.json.geo.FeatureJsonDeserializer.java

License:Apache License

@Override
public JsonFeature deserialize(JsonElement json, Type type, JsonDeserializationContext context)
        throws JsonParseException {
    try {//from   ww w .j a  v a2s . c  o  m
        JsonFeature feature = new JsonFeature();
        JsonObject obj = json.getAsJsonObject();

        // TODO ensure uniqueness
        if (obj.has("id"))
            feature.id = obj.get("id").getAsString();
        else
            feature.id = UUID.randomUUID().toString();

        if (obj.has("properties")) {
            Map<String, Object> map = context.deserialize(obj.get("properties"), Map.class);
            feature.properties = map;
        }

        if (obj.has("bbox"))
            feature.bbox = parseBBox(obj.get("bbox").getAsJsonArray());

        if (obj.has("geometry")) {
            JsonObject geometry = obj.get("geometry").getAsJsonObject();

            if (geometry.has("coordinates")) {
                if (!geometry.has("type"))
                    throw new IllegalArgumentException("No type for non-empty coordinates specified");

                String strType = context.deserialize(geometry.get("type"), String.class);
                feature.type = strType;
                if ("Point".equals(strType)) {
                    JsonArray arr = geometry.get("coordinates").getAsJsonArray();
                    double lon = arr.get(0).getAsDouble();
                    double lat = arr.get(1).getAsDouble();
                    if (arr.size() == 3)
                        feature.geometry = new Point(lat, lon, arr.get(2).getAsDouble());
                    else
                        feature.geometry = new Point(lat, lon);

                } else if ("MultiPoint".equals(strType)) {
                    feature.geometry = parseLineString(geometry);

                } else if ("LineString".equals(strType)) {
                    feature.geometry = parseLineString(geometry);

                } else {
                    throw new IllegalArgumentException("Coordinates type " + strType + " not yet supported");
                }
            }
        }

        return feature;

    } catch (Exception ex) {
        throw new JsonParseException("Problem parsing JSON feature " + json);
    }
}