Example usage for com.google.gson JsonArray get

List of usage examples for com.google.gson JsonArray get

Introduction

In this page you can find the example usage for com.google.gson JsonArray get.

Prototype

public JsonElement get(int i) 

Source Link

Document

Returns the ith element of the array.

Usage

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

License:Open Source License

public JsonArray extractVideoSessions(JsonDataSources sources) {
    videoSessionsById = new HashMap<String, JsonObject>();
    if (categoryToTagMap == null) {
        throw new IllegalStateException("You need to extract tags before attempting to extract video sessions");
    }//w  w  w  . j a  v  a2  s  . c o  m
    if (speakersById == null) {
        throw new IllegalStateException(
                "You need to extract speakers before attempting to extract video sessions");
    }

    JsonArray result = new JsonArray();
    JsonDataSource source = sources.getSource(VendorAPISource.MainTypes.topics.name());
    if (source != null) {
        for (JsonObject origin : source) {

            if (!isVideoSession(origin)) {
                continue;
            }
            if (isHiddenSession(origin)) {
                // Sessions with a "Hidden from schedule" flag should be ignored
                continue;
            }

            JsonObject dest = new JsonObject();

            JsonPrimitive vid = setVideoForVideoSession(origin, dest);

            JsonElement id = get(origin, VendorAPISource.Topics.id);
            // video library id must be the Youtube video id
            set(vid, dest, OutputJsonKeys.VideoLibrary.id);
            set(origin, VendorAPISource.Topics.title, dest, OutputJsonKeys.VideoLibrary.title, null);
            set(origin, VendorAPISource.Topics.description, dest, OutputJsonKeys.VideoLibrary.desc, null);
            set(new JsonPrimitive(Config.CONFERENCE_YEAR), dest, OutputJsonKeys.VideoLibrary.year);

            JsonElement videoTopic = null;
            JsonArray categories = origin.getAsJsonArray(VendorAPISource.Topics.categoryids.name());
            for (JsonElement category : categories) {
                JsonObject tag = categoryToTagMap.get(category.getAsString());
                if (tag != null) {
                    if (isHashtag(tag)) {
                        videoTopic = get(tag, OutputJsonKeys.Tags.name);
                        // by definition, the first tag that can be a hashtag (usually a TOPIC) is considered the video tag
                        break;
                    }
                }
            }
            if (videoTopic != null) {
                set(videoTopic, dest, OutputJsonKeys.VideoLibrary.topic);
            }

            // Concatenate speakers:
            JsonArray speakers = getAsArray(origin, VendorAPISource.Topics.speakerids);
            StringBuilder sb = new StringBuilder();
            if (speakers != null)
                for (int i = 0; i < speakers.size(); i++) {
                    String speakerId = speakers.get(i).getAsString();
                    usedSpeakers.add(speakerId);
                    JsonObject speaker = speakersById.get(speakerId);
                    if (speaker != null) {
                        sb.append(get(speaker, OutputJsonKeys.Speakers.name).getAsString());
                        if (i < speakers.size() - 1)
                            sb.append(", ");
                    }
                }
            set(new JsonPrimitive(sb.toString()), dest, OutputJsonKeys.VideoLibrary.speakers);
            videoSessionsById.put(id.getAsString(), dest);
            result.add(dest);
        }
    }
    return result;
}

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

License:Open Source License

public void addAll(JsonArray arr) {
    String idProperty = null;//  w w w . ja  v a 2s .  c o m
    for (int i = 0; i < arr.size(); i++) {
        JsonObject obj = arr.get(i).getAsJsonObject();
        if (idProperty == null) {
            idProperty = getKeyProperty(obj);
        }
        String id = obj.get(idProperty).getAsString();
        addElement(id, obj);
    }
}

From source file:com.google.javascript.jscomp.NpmCommandLineRunner.java

License:Apache License

private JsonElement unsafeGet(JsonArray o, int key) {
    return nullParseCheck(o.get(key));
}

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

License:Open Source License

public JsonArray extractSessions(JsonDataSources sources) {
    if (videoSessionsById == null) {
        throw new IllegalStateException(
                "You need to extract video sessions before attempting to extract sessions");
    }/*from www  .j a  v a 2  s .c  o  m*/
    if (categoryToTagMap == null) {
        throw new IllegalStateException("You need to extract tags before attempting to extract sessions");
    }

    JsonArray result = new JsonArray();
    JsonDataSource source = sources.getSource(InputJsonKeys.VendorAPISource.MainTypes.topics.name());
    if (source != null) {
        for (JsonObject origin : source) {
            if (isVideoSession(origin)) {
                // Sessions with the Video tag are processed as video library content
                continue;
            }
            if (isHiddenSession(origin)) {
                // Sessions with a "Hidden from schedule" flag should be ignored
                continue;
            }
            JsonElement title = get(origin, InputJsonKeys.VendorAPISource.Topics.title);
            // Since the CMS returns an empty keynote as a session, we need to ignore it
            if (title != null && title.isJsonPrimitive() && "keynote".equalsIgnoreCase(title.getAsString())) {
                continue;
            }
            JsonObject dest = new JsonObject();

            // Some sessions require a special ID, so we replace it here...
            if (title != null && title.isJsonPrimitive()
                    && "after hours".equalsIgnoreCase(title.getAsString())) {
                set(new JsonPrimitive("__afterhours__"), dest, OutputJsonKeys.Sessions.id);
            } else {
                set(origin, InputJsonKeys.VendorAPISource.Topics.id, dest, OutputJsonKeys.Sessions.id);
            }
            set(origin, InputJsonKeys.VendorAPISource.Topics.id, dest, OutputJsonKeys.Sessions.url,
                    Converters.SESSION_URL);
            set(origin, InputJsonKeys.VendorAPISource.Topics.title, dest, OutputJsonKeys.Sessions.title,
                    obfuscate ? Converters.OBFUSCATE : null);
            set(origin, InputJsonKeys.VendorAPISource.Topics.description, dest,
                    OutputJsonKeys.Sessions.description, obfuscate ? Converters.OBFUSCATE : null);
            set(origin, InputJsonKeys.VendorAPISource.Topics.start, dest,
                    OutputJsonKeys.Sessions.startTimestamp, Converters.DATETIME);
            set(origin, InputJsonKeys.VendorAPISource.Topics.finish, dest, OutputJsonKeys.Sessions.endTimestamp,
                    Converters.DATETIME);
            set(new JsonPrimitive(isFeatured(origin)), dest, OutputJsonKeys.Sessions.isFeatured);

            JsonElement documents = get(origin, InputJsonKeys.VendorAPISource.Topics.documents);
            if (documents != null && documents.isJsonArray() && documents.getAsJsonArray().size() > 0) {
                // Note that the input for SessionPhotoURL is the entity ID. We simply ignore the original
                // photo URL, because that will be processed by an offline cron script, resizing the
                // photos and saving them to a known location with the entity ID as its base name.
                set(origin, InputJsonKeys.VendorAPISource.Topics.id, dest, OutputJsonKeys.Sessions.photoUrl,
                        Converters.SESSION_PHOTO_URL);
            }

            setVideoPropertiesInSession(origin, dest);
            setRelatedContent(origin, dest);

            JsonElement mainTag = null;
            JsonElement hashtag = null;
            JsonElement mainTagColor = null;
            JsonArray categories = origin
                    .getAsJsonArray(InputJsonKeys.VendorAPISource.Topics.categoryids.name());
            JsonArray tags = new JsonArray();
            for (JsonElement category : categories) {
                JsonObject tag = categoryToTagMap.get(category.getAsString());
                if (tag != null) {
                    JsonElement tagName = get(tag, OutputJsonKeys.Tags.tag);
                    tags.add(tagName);
                    usedTags.add(tagName.getAsString());

                    if (mainTag == null) {
                        // check if the tag is from a "default" category. For example, if THEME is the default
                        // category, all sessions will have a "mainTag" property set to the first tag of type THEME
                        JsonElement tagCategory = get(tag, OutputJsonKeys.Tags.category); // THEME, TYPE or TOPIC
                        if (tagCategory.equals(mainCategory)) {
                            mainTag = tagName;
                            mainTagColor = get(tag, OutputJsonKeys.Tags.color);
                        }
                        if (hashtag == null && isHashtag(tag)) {
                            hashtag = get(tag, OutputJsonKeys.Tags.hashtag);
                            if (hashtag == null || hashtag.getAsString() == null
                                    || hashtag.getAsString().isEmpty()) {
                                // If no hashtag set in the tagsconf file, we will convert the tagname to find one:
                                hashtag = new JsonPrimitive(
                                        get(tag, OutputJsonKeys.Tags.name, Converters.TAG_NAME).getAsString()
                                                .toLowerCase());
                            }
                        }
                    }
                }
            }
            set(tags, dest, OutputJsonKeys.Sessions.tags);
            if (mainTag != null) {
                set(mainTag, dest, OutputJsonKeys.Sessions.mainTag);
            }
            if (mainTagColor != null) {
                set(mainTagColor, dest, OutputJsonKeys.Sessions.color);
            }
            if (hashtag != null) {
                set(hashtag, dest, OutputJsonKeys.Sessions.hashtag);
            }

            JsonArray speakers = getAsArray(origin, InputJsonKeys.VendorAPISource.Topics.speakerids);
            if (speakers != null)
                for (JsonElement speaker : speakers) {
                    String speakerId = speaker.getAsString();
                    usedSpeakers.add(speakerId);
                }
            set(speakers, dest, OutputJsonKeys.Sessions.speakers);

            JsonArray sessions = origin.getAsJsonArray(InputJsonKeys.VendorAPISource.Topics.sessions.name());
            if (sessions != null && sessions.size() > 0) {
                String roomId = get(sessions.get(0).getAsJsonObject(),
                        InputJsonKeys.VendorAPISource.Sessions.roomid).getAsString();
                roomId = Config.ROOM_MAPPING.getRoomId(roomId);
                set(new JsonPrimitive(roomId), dest, OutputJsonKeys.Sessions.room);

                // captions URL is set based on the session room, so keep it here.
                String captionsURL = Config.ROOM_MAPPING.getCaptions(roomId);
                if (captionsURL != null) {
                    set(new JsonPrimitive(captionsURL), dest, OutputJsonKeys.Sessions.captionsUrl);
                }
            }

            if (Config.DEBUG_FIX_DATA) {
                DebugDataExtractorHelper.changeSession(dest, usedTags);
            }
            result.add(dest);
        }
    }
    return result;
}

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

License:Open Source License

public JsonArray extractVideoSessions(JsonDataSources sources) {
    videoSessionsById = new HashMap<String, JsonObject>();
    if (categoryToTagMap == null) {
        throw new IllegalStateException("You need to extract tags before attempting to extract video sessions");
    }/*from  www  .  j  a v  a  2  s  .  c o m*/
    if (speakersById == null) {
        throw new IllegalStateException(
                "You need to extract speakers before attempting to extract video sessions");
    }

    JsonArray result = new JsonArray();
    JsonDataSource source = sources.getSource(InputJsonKeys.VendorAPISource.MainTypes.topics.name());
    if (source != null) {
        for (JsonObject origin : source) {

            if (!isVideoSession(origin)) {
                continue;
            }
            if (isHiddenSession(origin)) {
                // Sessions with a "Hidden from schedule" flag should be ignored
                continue;
            }

            JsonObject dest = new JsonObject();

            JsonPrimitive vid = setVideoForVideoSession(origin, dest);

            JsonElement id = get(origin, InputJsonKeys.VendorAPISource.Topics.id);
            // video library id must be the Youtube video id
            set(vid, dest, OutputJsonKeys.VideoLibrary.id);
            set(origin, InputJsonKeys.VendorAPISource.Topics.title, dest, OutputJsonKeys.VideoLibrary.title,
                    obfuscate ? Converters.OBFUSCATE : null);
            set(origin, InputJsonKeys.VendorAPISource.Topics.description, dest,
                    OutputJsonKeys.VideoLibrary.desc, obfuscate ? Converters.OBFUSCATE : null);
            set(new JsonPrimitive(Config.CONFERENCE_YEAR), dest, OutputJsonKeys.VideoLibrary.year);

            JsonElement videoTopic = null;
            JsonArray categories = origin
                    .getAsJsonArray(InputJsonKeys.VendorAPISource.Topics.categoryids.name());
            for (JsonElement category : categories) {
                JsonObject tag = categoryToTagMap.get(category.getAsString());
                if (tag != null) {
                    if (isHashtag(tag)) {
                        videoTopic = get(tag, OutputJsonKeys.Tags.name);
                        // by definition, the first tag that can be a hashtag (usually a TOPIC) is considered the video tag
                        break;
                    }
                }
            }
            if (videoTopic != null) {
                set(videoTopic, dest, OutputJsonKeys.VideoLibrary.topic);
            }

            // Concatenate speakers:
            JsonArray speakers = getAsArray(origin, InputJsonKeys.VendorAPISource.Topics.speakerids);
            StringBuilder sb = new StringBuilder();
            if (speakers != null)
                for (int i = 0; i < speakers.size(); i++) {
                    String speakerId = speakers.get(i).getAsString();
                    usedSpeakers.add(speakerId);
                    JsonObject speaker = speakersById.get(speakerId);
                    if (speaker != null) {
                        sb.append(get(speaker, OutputJsonKeys.Speakers.name).getAsString());
                        if (i < speakers.size() - 1)
                            sb.append(", ");
                    }
                }
            set(new JsonPrimitive(sb.toString()), dest, OutputJsonKeys.VideoLibrary.speakers);
            videoSessionsById.put(id.getAsString(), dest);
            result.add(dest);
        }
    }
    return result;
}

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();/*from  w  w w . j a v a  2s .  com*/
    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.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 .  j  av  a  2  s.  c o m*/
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.splash.data.serialize.JsonSerializer.java

License:Apache License

private JsonObject getDataObject(String json) {
    if (json == null) {
        return null;
    }/*from   ww w  .ja va2  s. co  m*/
    JsonArray array = parser.parse(json).getAsJsonArray();
    if (array.size() == 0) {
        return null;
    }
    return array.get(0).getAsJsonObject().getAsJsonObject("data");
}

From source file:com.googleapis.maps.services.impl.DistanceMatrixQueryImpl.java

License:Apache License

protected List<DistanceMatrixResult> unmarshallList(JsonObject response) {
    String status = response.get("status").getAsString();
    if (!"OK".equals(status) && !"ZERO_RESULTS".equals(status)) {
        throw createGoogleMapsException(status);
    }//from   w ww .j  ava  2 s  .com
    List<String> originAddresses = unmarshall(new TypeToken<List<String>>() {
    }, response.get("origin_addresses"));
    List<String> destinationAddresses = unmarshall(new TypeToken<List<String>>() {
    }, response.get("destination_addresses"));

    ArrayList<DistanceMatrixResult> list = new ArrayList<DistanceMatrixResult>();
    JsonArray results = response.get("rows").getAsJsonArray();
    for (int i = 0; i < results.size(); i++) {
        JsonElement object = results.get(i);
        List<DistanceMatrixResult> elements = unmarshall(new TypeToken<List<DistanceMatrixResult>>() {
        }, object.getAsJsonObject().get("elements"));
        for (int j = 0; j < elements.size(); j++) {
            DistanceMatrixResult element = elements.get(j);
            element.setOriginAddress(originAddresses.get(i));
            element.setDestinationAddress(destinationAddresses.get(j));
            list.add(element);
        }
    }
    return list;
}

From source file:com.googlecode.goclipse.tooling.oracle.GuruPackageDescribeParser.java

License:Open Source License

protected ArrayList2<StructureElement> parseElements(JsonArray members, boolean parsingMethods)
        throws CommonException {
    ArrayList2<StructureElement> elements = new ArrayList2<>();

    if (members != null) {
        for (int i = 0; i < members.size(); i++) {
            JsonElement arrayElement = members.get(i);
            if (arrayElement.isJsonObject()) {
                JsonObject jsonObject = arrayElement.getAsJsonObject();
                StructureElement structureElement = parseStructureElement(jsonObject, parsingMethods);
                if (structureElement == null) {
                    continue; // Can happen for external elements
                }/*from  ww w.j  a v a2  s .  c  om*/
                elements.add(structureElement);
            } else {
                throw new CommonException("'members' array element is not a JSONObject: " + arrayElement);
            }
        }
    }

    Collections.sort(elements, new Comparator<StructureElement>() {
        @Override
        public int compare(StructureElement o1, StructureElement o2) {
            SourceRange sr1 = o1.getSourceRange();
            SourceRange sr2 = o2.getSourceRange();

            int cmp = sr1.getOffset() - sr2.getOffset();
            if (cmp == 0) {
                int offset1 = o1.getNameSourceRange2() == null ? 0 : o1.getNameSourceRange2().getOffset();
                int offset2 = o2.getNameSourceRange2() == null ? 0 : o2.getNameSourceRange2().getOffset();
                return offset1 - offset2;
            }
            return cmp;
        }
    });

    return elements;
}