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.google.gwtjsonrpc.server.MapDeserializer.java

License:Apache License

public Map<Object, Object> deserialize(final JsonElement json, final Type typeOfT,
        final JsonDeserializationContext context) throws JsonParseException {
    final Type kt = ((ParameterizedType) typeOfT).getActualTypeArguments()[0];
    final Type vt = ((ParameterizedType) typeOfT).getActualTypeArguments()[1];

    if (json.isJsonNull()) {
        return null;
    }// w  w  w  .j  a v a 2s.  c o  m

    if (kt == String.class) {
        if (!json.isJsonObject()) {
            throw new JsonParseException("Expected object for map type");
        }
        final JsonObject p = (JsonObject) json;
        final Map<Object, Object> r = createInstance(typeOfT);
        for (final Map.Entry<String, JsonElement> e : p.entrySet()) {
            final Object v = context.deserialize(e.getValue(), vt);
            r.put(e.getKey(), v);
        }
        return r;
    } else {
        if (!json.isJsonArray()) {
            throw new JsonParseException("Expected array for map type");
        }

        final JsonArray p = (JsonArray) json;
        final Map<Object, Object> r = createInstance(typeOfT);
        for (int n = 0; n < p.size();) {
            final Object k = context.deserialize(p.get(n++), kt);
            final Object v = context.deserialize(p.get(n++), vt);
            r.put(k, v);
        }
        return r;
    }
}

From source file:com.google.identitytoolkit.RpcHelper.java

License:Open Source License

@VisibleForTesting
JsonObject checkGitkitException(String response) throws GitkitClientException, GitkitServerException {
    JsonElement resultElement = new JsonParser().parse(response);
    if (!resultElement.isJsonObject()) {
        throw new GitkitServerException("null error code from Gitkit server");
    }//from  w w w. j a  va 2 s .  co m
    JsonObject result = resultElement.getAsJsonObject();
    if (!result.has("error")) {
        return result;
    }
    // Error handling
    JsonObject error = result.getAsJsonObject("error");
    JsonElement codeElement = error.get("code");
    if (codeElement != null) {
        JsonElement messageElement = error.get("message");
        String message = (messageElement == null) ? "" : messageElement.getAsString();
        if (codeElement.getAsString().startsWith("4")) {
            // 4xx means client input error
            throw new GitkitClientException(message);
        } else {
            throw new GitkitServerException(message);
        }
    }
    throw new GitkitServerException("null error code from Gitkit server");
}

From source file:com.google.iosched.model.DataExtractor.java

License:Open Source License

private void setRelatedVideos(JsonObject origin, JsonObject dest) {
    JsonArray related = getAsArray(origin, VendorAPISource.Topics.related);
    if (related == null) {
        return;//from   w ww . j a va 2  s.c o m
    }
    for (JsonElement el : related) {
        if (!el.isJsonObject()) {
            continue;
        }
        JsonObject obj = el.getAsJsonObject();
        if (!obj.has("name") || !obj.has("values")) {
            continue;
        }

        if (InputJsonKeys.VendorAPISource.Topics.RELATED_NAME_VIDEO
                .equals(obj.getAsJsonPrimitive("name").getAsString())) {

            JsonElement values = obj.get("values");
            if (!values.isJsonArray()) {
                continue;
            }

            // As per the data specification, related content is formatted as
            // "video1 title1\nvideo2 title2\n..."
            StringBuilder relatedContentStr = new StringBuilder();
            for (JsonElement value : values.getAsJsonArray()) {
                String relatedSessionId = value.getAsString();
                JsonObject relatedVideo = videoSessionsById.get(relatedSessionId);
                if (relatedVideo != null) {
                    JsonElement vid = get(relatedVideo, OutputJsonKeys.VideoLibrary.vid);
                    JsonElement title = get(relatedVideo, OutputJsonKeys.VideoLibrary.title);
                    if (vid != null && title != null) {
                        relatedContentStr.append(vid.getAsString()).append(" ").append(title.getAsString())
                                .append("\n");
                    }
                }
            }
            set(new JsonPrimitive(relatedContentStr.toString()), dest, OutputJsonKeys.Sessions.relatedContent);
        }
    }
}

From source file:com.google.iosched.model.DataModelHelper.java

License:Open Source License

public static JsonPrimitive getMapValue(JsonElement map, String key, Converter converter,
        String defaultValueStr) {
    JsonPrimitive defaultValue = null;//from  www  .j av  a 2s . co  m
    if (defaultValueStr != null) {
        defaultValue = new JsonPrimitive(defaultValueStr);
        if (converter != null)
            defaultValue = converter.convert(defaultValue);
    }
    if (map == null || !map.isJsonArray()) {
        return defaultValue;
    }
    for (JsonElement el : map.getAsJsonArray()) {
        if (!el.isJsonObject()) {
            continue;
        }
        JsonObject obj = el.getAsJsonObject();
        if (!obj.has("name") || !obj.has("value")) {
            continue;
        }
        if (key.equals(obj.getAsJsonPrimitive("name").getAsString())) {
            JsonElement value = obj.get("value");
            if (!value.isJsonPrimitive()) {
                throw new ConverterException(value, converter, "Expected a JsonPrimitive");
            }
            if (converter != null)
                value = converter.convert(value);
            return value.getAsJsonPrimitive();
        }
    }
    return defaultValue;
}

From source file:com.google.mr4c.serialize.json.JsonConfigSerializer.java

License:Open Source License

public LocationsConfig deserializeLocationsConfig(Reader reader) throws IOException {
    Gson gson = buildGson();/*from  ww  w  .  j ava  2  s. co  m*/
    JsonParser parser = new JsonParser();
    JsonElement jsonEle = parser.parse(reader);
    if (jsonEle.isJsonObject()) {
        Map<String, URI> locationMap = gson.fromJson(jsonEle, new TypeToken<Map<String, URI>>() {
        }.getType());
        return new LocationsConfig(locationMap);
    } else if (jsonEle.isJsonArray()) {
        List<URI> locationList = gson.fromJson(jsonEle, new TypeToken<List<URI>>() {
        }.getType());
        return new LocationsConfig(locationList);
    } else {
        throw new IllegalArgumentException("Need JSON Array or Object to deserialize LocationsConfig");
    }
}

From source file:com.google.samples.apps.iosched.server.schedule.model.DataExtractor.java

License:Open Source License

@Deprecated
private void setRelatedVideos(JsonObject origin, JsonObject dest) {
    JsonArray related = getAsArray(origin, InputJsonKeys.VendorAPISource.Topics.related);
    if (related == null) {
        return;/*from w ww  . ja  v  a 2s.c  o m*/
    }
    for (JsonElement el : related) {
        if (!el.isJsonObject()) {
            continue;
        }
        JsonObject obj = el.getAsJsonObject();
        if (!obj.has("name") || !obj.has("values")) {
            continue;
        }

        if (InputJsonKeys.VendorAPISource.Topics.RELATED_NAME_VIDEO
                .equals(obj.getAsJsonPrimitive("name").getAsString())) {

            JsonElement values = obj.get("values");
            if (!values.isJsonArray()) {
                continue;
            }

            // As per the data specification, related content is formatted as
            // "video1 title1\nvideo2 title2\n..."
            StringBuilder relatedContentStr = new StringBuilder();
            for (JsonElement value : values.getAsJsonArray()) {
                String relatedSessionId = value.getAsString();
                JsonObject relatedVideo = videoSessionsById.get(relatedSessionId);
                if (relatedVideo != null) {
                    JsonElement vid = get(relatedVideo, OutputJsonKeys.VideoLibrary.vid);
                    JsonElement title = get(relatedVideo, OutputJsonKeys.VideoLibrary.title);
                    if (vid != null && title != null) {
                        relatedContentStr.append(vid.getAsString()).append(" ").append(title.getAsString())
                                .append("\n");
                    }
                }
            }
            set(new JsonPrimitive(relatedContentStr.toString()), dest, OutputJsonKeys.Sessions.relatedContent);
        }
    }
}

From source file:com.google.samples.apps.iosched.server.schedule.model.DataExtractor.java

License:Open Source License

private void setRelatedContent(JsonObject origin, JsonObject dest) {
    JsonArray related = getAsArray(origin, InputJsonKeys.VendorAPISource.Topics.related);
    JsonArray outputArray = new JsonArray();

    if (related == null) {
        return;/*from  w  w w  .  j  a  v  a  2s.c om*/
    }
    for (JsonElement el : related) {
        if (!el.isJsonObject()) {
            continue;
        }
        JsonObject obj = el.getAsJsonObject();
        if (!obj.has("name") || !obj.has("values")) {
            continue;
        }

        if (InputJsonKeys.VendorAPISource.Topics.RELATED_NAME_SESSIONS
                .equals(obj.getAsJsonPrimitive("name").getAsString())) {

            JsonElement values = obj.get("topics");
            if (!values.isJsonArray()) {
                continue;
            }

            // As per the data specification, related content is formatted as
            // "video1 title1\nvideo2 title2\n..."
            for (JsonElement topic : values.getAsJsonArray()) {
                if (!topic.isJsonObject()) {
                    continue;
                }

                JsonObject topicObj = topic.getAsJsonObject();

                String id = get(topicObj, InputJsonKeys.VendorAPISource.RelatedTopics.id).getAsString();
                String title = get(topicObj, InputJsonKeys.VendorAPISource.RelatedTopics.title).getAsString();

                if (id != null && title != null) {
                    JsonObject outputObj = new JsonObject();
                    set(new JsonPrimitive(id), outputObj, OutputJsonKeys.RelatedContent.id);
                    set(new JsonPrimitive(title), outputObj, OutputJsonKeys.RelatedContent.title);
                    outputArray.add(outputObj);
                }
            }
            set(outputArray, dest, OutputJsonKeys.Sessions.relatedContent);
        }
    }
}

From source file:com.google.samples.apps.iosched.server.schedule.server.input.VendorDynamicInput.java

License:Open Source License

public JsonArray fetchArray(InputJsonKeys.VendorAPISource.MainTypes entityType, int page) throws IOException {

    HashMap<String, String> params = null;

    if (entityType.equals(InputJsonKeys.VendorAPISource.MainTypes.topics)
            || entityType.equals(InputJsonKeys.VendorAPISource.MainTypes.speakers)) {
        params = new HashMap<String, String>();

        // Topics and speakers require param "includeinfo=true" to bring extra data
        params.put("includeinfo", "true");

        if (entityType.equals(InputJsonKeys.VendorAPISource.MainTypes.topics)) {
            if (extractUnpublished) {
                params.put("minpublishstatus", "0");
            }/*from   w ww  .ja v  a2s  .  c o m*/
        }
    }

    if (page == 0) {
        page = 1;
    } else if (page > 1) {
        if (params == null) {
            params = new HashMap<String, String>();
        }
        params.put("page", Integer.toString(page));
    }

    JsonElement element = getFetcher().fetch(entityType, params);

    if (element.isJsonArray()) {
        return element.getAsJsonArray();
    } else if (element.isJsonObject()) {
        // check if there are extra pages requiring further fetching
        JsonObject obj = element.getAsJsonObject();
        checkPagingConsistency(entityType, page, obj);

        int pageSize = obj.get("pagesize").getAsInt();
        int totalEntities = obj.get("total").getAsInt();
        JsonArray elements = getEntities(obj);
        if (page * pageSize < totalEntities) {
            // fetch the next page
            elements.addAll(fetchArray(entityType, page + 1));
        }
        return elements;
    } else {
        throw new JsonParseException("Invalid response from Vendor API. Request should return "
                + "either a JsonArray or a JsonObject, but returned " + element.getClass().getName()
                + ". Entity fetcher is " + getFetcher());
    }
}

From source file:com.google.u2f.server.impl.U2FServerReferenceImpl.java

License:Open Source License

private void verifyBrowserData(JsonElement browserDataAsElement, String messageType,
        EnrollSessionData sessionData) throws U2FException {

    if (!browserDataAsElement.isJsonObject()) {
        throw new U2FException("browserdata has wrong format");
    }//from w  ww  . j  a v  a 2 s  .  com

    JsonObject browserData = browserDataAsElement.getAsJsonObject();

    // check that the right "typ" parameter is present in the browserdata JSON
    if (!browserData.has(TYPE_PARAM)) {
        throw new U2FException("bad browserdata: missing 'typ' param");
    }

    String type = browserData.get(TYPE_PARAM).getAsString();
    if (!messageType.equals(type)) {
        throw new U2FException("bad browserdata: bad type " + type);
    }

    // check that the right challenge is in the browserdata
    if (!browserData.has(CHALLENGE_PARAM)) {
        throw new U2FException("bad browserdata: missing 'challenge' param");
    }

    if (browserData.has(ORIGIN_PARAM)) {
        verifyOrigin(browserData.get(ORIGIN_PARAM).getAsString());
    }

    byte[] challengeFromBrowserData = Base64.decodeBase64(browserData.get(CHALLENGE_PARAM).getAsString());

    if (!Arrays.equals(challengeFromBrowserData, sessionData.getChallenge())) {
        throw new U2FException("wrong challenge signed in browserdata");
    }

    // TODO: Deal with ChannelID
}

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);
    }// ww w.j av a  2s  .c  om

    // 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);
}