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.iosched.model.DataModelHelper.java

License:Open Source License

public static JsonPrimitive getMapValue(JsonElement map, String key, Converter converter,
        String defaultValueStr) {
    JsonPrimitive defaultValue = null;/*  www  .  j  ava 2  s.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.nigori.common.TypeAdapterProtobuf.java

License:Apache License

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

    JsonObject jsonObject = json.getAsJsonObject();
    @SuppressWarnings("unchecked")
    Class<? extends GeneratedMessage> protoClass = (Class<? extends GeneratedMessage>) typeOfT;

    try {/*from  w  w w  .java 2  s . c o  m*/
        // Invoke the ProtoClass.newBuilder() method
        Object protoBuilder = getCachedMethod(protoClass, "newBuilder").invoke(null);
        Class<?> builderClass = protoBuilder.getClass();

        Descriptor protoDescriptor = (Descriptor) getCachedMethod(protoClass, "getDescriptor").invoke(null);
        // Call setters on all of the available fields
        for (FieldDescriptor fieldDescriptor : protoDescriptor.getFields()) {
            String name = fieldDescriptor.getName();
            if (jsonObject.has(name)) {
                JsonElement jsonElement = jsonObject.get(name);
                String fieldName = camelCaseField(name + "_");
                Field field = protoClass.getDeclaredField(fieldName);
                Type fieldType = field.getGenericType();
                if (fieldType.equals(Object.class)) {
                    // TODO(drt24): this is very evil.
                    // In NigoriMessages protobuf strings are stored in a field of type Object so that they
                    // can use either String of ByteString as the implementation, however this causes a type
                    // error when calling the set method. So we make a (potentially false) assumption that
                    // all fields of type Object in NigoriMessages have that type because they actually
                    // should have Strings set.
                    fieldType = String.class;
                }
                Object fieldValue = context.deserialize(jsonElement, fieldType);
                if (fieldDescriptor.getJavaType() == FieldDescriptor.JavaType.ENUM) {
                    Method methodVD = getCachedMethod(fieldValue.getClass(), "getValueDescriptor");
                    fieldValue = methodVD.invoke(fieldValue);
                }
                Method method = getCachedMethod(builderClass, "setField", FieldDescriptor.class, Object.class);
                method.invoke(protoBuilder, fieldDescriptor, fieldValue);
            }
        }
        // Invoke the build method to return the final proto
        return (GeneratedMessage) getCachedMethod(builderClass, "build").invoke(protoBuilder);
    } catch (SecurityException e) {
        throw new JsonParseException(e);
    } catch (NoSuchMethodException e) {
        throw new JsonParseException(e);
    } catch (IllegalArgumentException e) {
        throw new JsonParseException(e);
    } catch (IllegalAccessException e) {
        throw new JsonParseException(e);
    } catch (InvocationTargetException e) {
        throw new JsonParseException(e);
    } catch (NoSuchFieldException e) {
        throw new JsonParseException(e);
    }
}

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  www.  ja  v a2 s  .com*/
    }
    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;//w w w  . j  a  v a  2  s.co 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_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

private void checkPagingConsistency(InputJsonKeys.VendorAPISource.MainTypes entityType, int requestedPage,
        JsonObject obj) {
    if (!obj.has("page") || !obj.has("pagesize") || !obj.has("total")
            || (!obj.has("results") && !obj.has("topics"))) {
        throw new JsonParseException("Invalid response from Vendor API when" + "paging " + entityType
                + " results. At least one of the required properties "
                + "(page, pagesize, total, results|topics) could not be found.");
    }//w  ww  . java 2 s  . com
    int currentPage = obj.get("page").getAsInt();
    if (requestedPage > 0 && requestedPage != currentPage) {
        throw new JsonParseException("Invalid response from Vendor API when" + "paging " + entityType
                + " results. Requested page " + requestedPage + " but got page " + currentPage);
    }
}

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

License:Open Source License

private JsonArray getEntities(JsonObject pagedObject) {
    JsonArray elements;/* ww w.  ja  v a  2  s.  c  o  m*/
    if (pagedObject.has("results")) {
        elements = pagedObject.get("results").getAsJsonArray();
    } else if (pagedObject.has("topics")) {
        elements = pagedObject.get("topics").getAsJsonArray();
    } else {
        throw new JsonParseException(
                "Invalid JSON format for a paged result. Expected either a \"results\" or a topics array property.");
    }
    return elements;
}

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");
    }/*ww  w .  jav  a 2 s . c o m*/

    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.walkaround.proto.gson.RobotSearchDigestGsonImpl.java

License:Apache License

@Override
public void fromGson(JsonElement json, Gson gson, RawStringData raw) throws GsonException {
    reset();//  ww w  . j  av  a 2 s .c om
    JsonObject jsonObject = json.getAsJsonObject();
    // NOTE: always check with has(...) as the json might not have all required
    // fields set.
    if (jsonObject.has("1")) {
        setWaveId(jsonObject.get("1").getAsString());
    }
    if (jsonObject.has("2")) {
        JsonArray array = jsonObject.get("2").getAsJsonArray();
        for (int i = 0; i < array.size(); i++) {
            addParticipant(array.get(i).getAsString());
        }
    }
    if (jsonObject.has("3")) {
        setTitle(jsonObject.get("3").getAsString());
    }
    if (jsonObject.has("4")) {
        setSnippet(jsonObject.get("4").getAsString());
    }
    if (jsonObject.has("5")) {
        setLastModifiedMillis(GsonUtil.fromJson(jsonObject.get("5")));
    }
    if (jsonObject.has("6")) {
        setBlipCount(jsonObject.get("6").getAsInt());
    }
    if (jsonObject.has("7")) {
        setUnreadBlipCount(jsonObject.get("7").getAsInt());
    }
}

From source file:com.google.walkaround.util.server.flags.JsonFlags.java

License:Open Source License

@VisibleForTesting
@SuppressWarnings("unchecked")
static Object parseOneFlag(FlagDeclaration decl, JsonObject json) throws FlagFormatException {
    String key = decl.getName();/* www .  j av a 2 s  .  co m*/
    Class<?> type = decl.getType();
    try {
        if (!json.has(key)) {
            throw new FlagFormatException("Missing flag: " + key);
        }
        // Explicit check, otherwise null would be interpreted as "null" (the
        // string) for string and enum values.
        if (json.get(key).isJsonNull()) {
            throw new FlagFormatException("Null value for key " + key);
        }

        if (type == String.class) {
            return json.get(key).getAsString();
        } else if (type == Boolean.class) {
            return Boolean.valueOf(json.get(key).getAsBoolean());
        } else if (type == Integer.class) {
            int val = json.get(key).getAsInt();
            if (val != json.get(key).getAsDouble()) {
                throw new FlagFormatException("Loss of precision for type int, key=" + key + ", value="
                        + json.get(key).getAsDouble());
            }
            return Integer.valueOf(val);
        } else if (type == Double.class) {
            return Double.valueOf(json.get(key).getAsDouble());
        } else if (type.isEnum()) {
            // TODO(ohler): Avoid unchecked warning here, the rest of the method should be clean.
            return parseEnumValue(type.asSubclass(Enum.class), key, json.get(key).getAsString().toUpperCase());
        } else {
            throw new IllegalArgumentException("Unknown flag type " + type.getName());
        }
    } catch (RuntimeException e) {
        throw new FlagFormatException(
                "Invalid flag JSON for key " + key + " (possibly a bad type); map=" + json, e);
    }
}

From source file:com.google.wave.api.event.EventSerializer.java

License:Apache License

/**
 * Deserializes the given {@link JsonObject} into an {@link Event}, and
 * assign the given {@link Wavelet} to the {@link Event}.
 *
 * @param wavelet the wavelet where the event occurred.
 * @param json the JSON representation of {@link Event}.
 * @param context the deserialization context.
 * @return an instance of {@link Event}.
 *
 * @throw {@link EventSerializationException} if there is a problem
 *     deserializing the event JSON./*from w w  w .ja  va2s .c  o  m*/
 */
public static Event deserialize(Wavelet wavelet, EventMessageBundle bundle, JsonObject json,
        JsonDeserializationContext context) throws EventSerializationException {
    // Construct the event object.
    String eventTypeString = json.get(TYPE).getAsString();
    EventType type = EventType.valueOfIgnoreCase(eventTypeString);
    if (type == EventType.UNKNOWN) {
        throw new EventSerializationException(
                "Trying to deserialize event JSON with unknown " + "type: " + json, json);
    }

    // Parse the generic parameters.
    String modifiedBy = json.get(MODIFIED_BY).getAsString();
    Long timestamp = json.get(TIMESTAMP).getAsLong();

    // Construct the event object.
    Class<? extends Event> clazz = type.getClazz();
    Constructor<? extends Event> ctor;
    try {
        ctor = clazz.getDeclaredConstructor();
        ctor.setAccessible(true);
        Event event = ctor.newInstance();

        // Set the default fields from AbstractEvent.
        Class<?> rootClass = AbstractEvent.class;
        setField(event, rootClass.getDeclaredField(WAVELET), wavelet);
        setField(event, rootClass.getDeclaredField(MODIFIED_BY), modifiedBy);
        setField(event, rootClass.getDeclaredField(TIMESTAMP), timestamp);
        setField(event, rootClass.getDeclaredField(TYPE), type);
        setField(event, rootClass.getDeclaredField(BUNDLE), bundle);

        JsonObject properties = json.get(PROPERTIES).getAsJsonObject();

        // Set the blip id field, that can be null for certain events, such as
        // OPERATION_ERROR.
        JsonElement blipId = properties.get(BLIP_ID);
        if (blipId != null && !(blipId instanceof JsonNull)) {
            setField(event, rootClass.getDeclaredField(BLIP_ID), blipId.getAsString());
        }

        // Set the additional fields.
        for (Field field : clazz.getDeclaredFields()) {
            String fieldName = field.getName();
            if (properties.has(fieldName)) {
                setField(event, field, context.deserialize(properties.get(fieldName), field.getGenericType()));
            }
        }
        return event;
    } catch (NoSuchMethodException e) {
        throw new EventSerializationException("Unable to deserialize event JSON: " + json, json);
    } catch (NoSuchFieldException e) {
        throw new EventSerializationException("Unable to deserialize event JSON: " + json, json);
    } catch (InstantiationException e) {
        throw new EventSerializationException("Unable to deserialize event JSON: " + json, json);
    } catch (IllegalAccessException e) {
        throw new EventSerializationException("Unable to deserialize event JSON: " + json, json);
    } catch (InvocationTargetException e) {
        throw new EventSerializationException("Unable to deserialize event JSON: " + json, json);
    } catch (JsonParseException e) {
        throw new EventSerializationException("Unable to deserialize event JSON: " + json, json);
    }
}