Example usage for com.google.gson JsonElement getAsJsonArray

List of usage examples for com.google.gson JsonElement getAsJsonArray

Introduction

In this page you can find the example usage for com.google.gson JsonElement getAsJsonArray.

Prototype

public JsonArray getAsJsonArray() 

Source Link

Document

convenience method to get this element as a JsonArray .

Usage

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

License:Open Source License

public static JsonArray getAsArray(JsonObject source, Enum<?> sourceProperty) {
    if (source == null) {
        return null;
    }/*from   www  . j a va2  s.co  m*/
    JsonElement el = source.get(sourceProperty.name());
    if (el == null || !el.isJsonArray()) {
        return null;
    }
    return el.getAsJsonArray();
}

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   w ww  . j ava2  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.iosched.server.input.DataSourceInput.java

License:Open Source License

public JsonArray fetch(EnumType entityType) throws IOException {
    JsonElement element = getFetcher().fetch(entityType, null);
    if (element == null) {
        return null;
    }/*from   w  ww  .  j  av a2s  .  c om*/
    if (element.isJsonArray()) {
        return element.getAsJsonArray();
    } else {
        throw new JsonParseException(
                "Invalid response from DataSourceInput. Expected " + "a JsonArray, but fetched "
                        + element.getClass().getName() + ". Entity fetcher is " + getFetcher());
    }
}

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 w  w  w.  j  a v a 2  s  . c om*/
    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

@Deprecated
private void setRelatedVideos(JsonObject origin, JsonObject dest) {
    JsonArray related = getAsArray(origin, InputJsonKeys.VendorAPISource.Topics.related);
    if (related == null) {
        return;//from   ww w  .j av  a 2s .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_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 va  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

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  w  w .  j  ava  2s  . com
        }
    }

    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.wave.api.RobotSerializer.java

License:Apache License

/**
 * Deserializes operations. This method supports only the new JSON-RPC style
 * operations./*from ww w  .jav a  2s . c o  m*/
 *
 * @param jsonString the operations JSON string to deserialize.
 * @return a list of {@link OperationRequest},that represents the operations.
 * @throws InvalidRequestException if there is a problem deserializing the
 *     operations.
 */
public List<OperationRequest> deserializeOperations(String jsonString) throws InvalidRequestException {
    if (Util.isEmptyOrWhitespace(jsonString)) {
        return Collections.emptyList();
    }

    // Parse incoming operations.
    JsonArray requestsAsJsonArray = null;

    JsonElement json = null;
    try {
        json = jsonParser.parse(jsonString);
    } catch (JsonParseException e) {
        throw new InvalidRequestException("Couldn't deserialize incoming operations: " + jsonString, null, e);
    }

    if (json.isJsonArray()) {
        requestsAsJsonArray = json.getAsJsonArray();
    } else {
        requestsAsJsonArray = new JsonArray();
        requestsAsJsonArray.add(json);
    }

    // Convert incoming operations into a list of JsonRpcRequest.
    ProtocolVersion protocolVersion = determineProtocolVersion(requestsAsJsonArray);
    PROTOCOL_VERSION_COUNTERS.get(protocolVersion).incrementAndGet();
    List<OperationRequest> requests = new ArrayList<OperationRequest>(requestsAsJsonArray.size());
    for (JsonElement requestAsJsonElement : requestsAsJsonArray) {
        validate(requestAsJsonElement);
        requests.add(getGson(protocolVersion).fromJson(requestAsJsonElement, OperationRequest.class));
    }
    return requests;
}

From source file:com.googlesource.gerrit.plugins.oauth.CasOAuthService.java

License:Apache License

@Override
public OAuthUserInfo getUserInfo(OAuthToken token) throws IOException {
    final String protectedResourceUrl = String.format(PROTECTED_RESOURCE_URL, rootUrl);
    OAuthRequest request = new OAuthRequest(Verb.GET, protectedResourceUrl);
    Token t = new Token(token.getToken(), token.getSecret(), token.getRaw());
    service.signRequest(t, request);/*from  w w w.j a v a 2 s . co  m*/

    Response response = request.send();
    if (response.getCode() != HttpServletResponse.SC_OK) {
        throw new IOException(String.format("Status %s (%s) for request %s", response.getCode(),
                response.getBody(), request.getUrl()));
    }

    if (log.isDebugEnabled()) {
        log.debug("User info response: {}", response.getBody());
    }

    JsonElement userJson = JSON.newGson().fromJson(response.getBody(), JsonElement.class);
    if (!userJson.isJsonObject()) {
        throw new IOException(String.format("Invalid JSON '%s': not a JSON Object", userJson));
    }
    JsonObject jsonObject = userJson.getAsJsonObject();

    JsonElement id = jsonObject.get("id");
    if (id == null || id.isJsonNull()) {
        throw new IOException(String.format("CAS response missing id: %s", response.getBody()));
    }

    JsonElement attrListJson = jsonObject.get("attributes");
    if (attrListJson == null) {
        throw new IOException(String.format("CAS response missing attributes: %s", response.getBody()));
    }

    String email = null, name = null, login = null;

    if (attrListJson.isJsonArray()) {
        // It is possible for CAS to be configured to not return any attributes (email, name, login),
        // in which case,
        // CAS returns an empty JSON object "attributes":{}, rather than "null" or an empty JSON array
        // "attributes": []

        JsonArray attrJson = attrListJson.getAsJsonArray();
        for (JsonElement elem : attrJson) {
            if (elem == null || !elem.isJsonObject()) {
                throw new IOException(String.format("Invalid JSON '%s': not a JSON Object", elem));
            }
            JsonObject obj = elem.getAsJsonObject();

            String property = getStringElement(obj, "email");
            if (property != null)
                email = property;
            property = getStringElement(obj, "name");
            if (property != null)
                name = property;
            property = getStringElement(obj, "login");
            if (property != null)
                login = property;
        }
    }

    return new OAuthUserInfo(CAS_PROVIDER_PREFIX + id.getAsString(), login, email, name,
            fixLegacyUserId ? id.getAsString() : null);
}

From source file:com.gst.batch.service.ResolutionHelper.java

License:Apache License

private JsonElement resolveDependentVariables(final Entry<String, JsonElement> entryElement,
        final JsonModel responseJsonModel) {
    JsonElement value = null;/*from   www  .  j a  v a  2 s  .com*/

    final JsonElement element = entryElement.getValue();

    if (element.isJsonObject()) {
        final JsonObject jsObject = element.getAsJsonObject();
        value = processJsonObject(jsObject, responseJsonModel);
    } else if (element.isJsonArray()) {
        final JsonArray jsElementArray = element.getAsJsonArray();
        value = processJsonArray(jsElementArray, responseJsonModel);
    } else {
        value = resolveDependentVariable(element, responseJsonModel);
    }
    return value;
}