Example usage for com.google.gson JsonObject getAsJsonArray

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

Introduction

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

Prototype

public JsonArray getAsJsonArray(String memberName) 

Source Link

Document

Convenience method to get the specified member as a JsonArray.

Usage

From source file:com.google.api.ads.adwords.awalerting.sampleimpl.downloader.SqlDbReportDownloader.java

License:Open Source License

/**
 * Get SQL query string according to config, and build column names list.
 *
 * @return the sql query string/* w ww. j a v a 2  s. c  o  m*/
 */
private String getSqlQueryWithReportColumnNames() {
    JsonObject queryConfig = getQueryConfig();

    StringBuilder sqlQueryBuilder = new StringBuilder();
    sqlQueryBuilder.append("SELECT ");

    Preconditions.checkArgument(queryConfig.has(COLUMN_MAPPINGS_TAG), "Missing compulsory property: %s - %s",
            REPORT_QUERY_TAG, COLUMN_MAPPINGS_TAG);
    JsonArray columnMappings = queryConfig.getAsJsonArray(COLUMN_MAPPINGS_TAG);
    // Use LinkedHashMap to preserve order (SQL query and result parsing must have matched order).
    Map<String, String> fieldsMapping = new LinkedHashMap<String, String>(columnMappings.size());

    // Process database column -> report column mapping
    String dbColumnName;
    String reportColumnName;
    for (JsonElement columnMapping : columnMappings) {
        JsonObject mapping = columnMapping.getAsJsonObject();
        Preconditions.checkArgument(mapping.has(DATABASE_COLUMN_NAME_TAG),
                "Missing compulsory property: %s - %s - %s", REPORT_QUERY_TAG, COLUMN_MAPPINGS_TAG,
                DATABASE_COLUMN_NAME_TAG);
        Preconditions.checkArgument(mapping.has(REPORT_COLUMN_NAME_TAG),
                "Missing compulsory property: %s - %s - %s", REPORT_QUERY_TAG, COLUMN_MAPPINGS_TAG,
                REPORT_COLUMN_NAME_TAG);
        dbColumnName = mapping.get(DATABASE_COLUMN_NAME_TAG).getAsString();
        reportColumnName = mapping.get(REPORT_COLUMN_NAME_TAG).getAsString();
        fieldsMapping.put(dbColumnName, reportColumnName);
    }

    sqlQueryBuilder.append(Joiner.on(", ").withKeyValueSeparator(" AS ").join(fieldsMapping));

    Preconditions.checkArgument(queryConfig.has(TABLE_TAG), "Missing compulsory property: %s - %s",
            REPORT_QUERY_TAG, TABLE_TAG);
    sqlQueryBuilder.append(" FROM ").append(queryConfig.get(TABLE_TAG).getAsString());

    boolean hasWhereClause = false;
    if (queryConfig.has(DATE_RANGE_TAG)) {
        DateRange dateRange = DateRange.fromString(queryConfig.get(DATE_RANGE_TAG).getAsString());
        String dateRangeCondition = String.format(DATA_RANGE_CONDITION_FORMAT, DATE_COLUMN_NAME,
                dateRange.getStartDate(), dateRange.getEndDate());
        sqlQueryBuilder.append(" WHERE ").append(dateRangeCondition);
        hasWhereClause = true;
    }

    if (queryConfig.has(CONDITIONS_TAG)) {
        sqlQueryBuilder.append(hasWhereClause ? " AND " : " WHERR ")
                .append(queryConfig.get(CONDITIONS_TAG).getAsString());
    }

    String sqlQuery = sqlQueryBuilder.toString();
    LOGGER.info("SQL query: {}", sqlQuery);
    return sqlQuery;
}

From source file:com.google.cloud.solutions.sampleapps.orchestration.orchestrator.server.GceInstanceRetriever.java

License:Open Source License

/**
 * Parses the response, which contains all information about the running VMs. Extracts only the
 * IPs and names, as they are all that the orchstrator needs. Adjust this implementation to suit
 * your needs if necessary.//from w w w  .ja v a 2 s  .  com
 *
 * @param instanceResponse the string containing the response from queriying "instances" for the
 *        given project.
 * @param instancePrefix returns only instances with name that starts with the prefix as specified
 *        in the configuration properties.
 * @return the extracted IP, or null if it can't be found.
 */
static Map<String, String> extractIpsAndInstanceNames(String instanceResponse, String instancePrefix) {
    JsonParser parser = new JsonParser();
    JsonObject jsonObject = (JsonObject) parser.parse(instanceResponse);
    Map<String, String> gceIpsAndInstanceNames = new HashMap<String, String>();
    JsonArray items = jsonObject.getAsJsonArray("items");
    if (items != null) {
        for (int i = 0; i < items.size(); i++) {
            String natIp = items.get(i).getAsJsonObject().getAsJsonArray("networkInterfaces").get(0)
                    .getAsJsonObject().getAsJsonArray("accessConfigs").get(0).getAsJsonObject().get("natIP")
                    .getAsString();
            String name = items.get(i).getAsJsonObject().get("name").getAsString();
            if (name.startsWith(instancePrefix)) {
                gceIpsAndInstanceNames.put(natIp, name);
            }
        }
    }
    return gceIpsAndInstanceNames;
}

From source file:com.google.dart.server.internal.remote.processor.NotificationSearchResultsProcessor.java

License:Open Source License

@Override
public void process(JsonObject response) throws Exception {
    JsonObject params = response.getAsJsonObject("params");
    getListener().computedSearchResults(params.get("id").getAsString(),
            SearchResult.fromJsonArray(params.getAsJsonArray("results")), params.get("isLast").getAsBoolean());
}

From source file:com.google.devtools.kythe.platform.shared.KytheMetadataLoader.java

License:Open Source License

@Override
public Metadata parseFile(String fileName, byte[] data) {
    if (!fileName.endsWith(META_SUFFIX)) {
        return null;
    }//from ww  w.  ja v a2 s.co  m
    JsonElement root = null;
    try (ByteArrayInputStream stream = new ByteArrayInputStream(data);
            InputStreamReader reader = new InputStreamReader(stream, StandardCharsets.UTF_8)) {
        root = PARSER.parse(reader);
    } catch (IOException ex) {
        emitWarning(ex.getMessage(), fileName);
        return null;
    }
    if (root == null || !root.isJsonObject()) {
        emitWarning("Missing root.", fileName);
        return null;
    }
    JsonObject rootObject = root.getAsJsonObject();
    JsonPrimitive rootType = rootObject.getAsJsonPrimitive(TYPE);
    if (rootType == null || !rootType.getAsString().equals(KYTHE_FORMAT_0)) {
        emitWarning("Root missing type.", fileName);
        return null;
    }
    JsonArray rules = rootObject.getAsJsonArray(META);
    if (rules == null) {
        emitWarning("Root missing meta array.", fileName);
        return null;
    }
    Metadata metadata = new Metadata();
    for (JsonElement rule : rules) {
        RuleXorError ruleXorError = parseRule(rule.getAsJsonObject());
        if (ruleXorError != null) { // skip nulls
            Metadata.Rule metadataRule = ruleXorError.rule();
            if (metadataRule != null) {
                metadata.addRule(metadataRule);
            } else {
                emitWarning(ruleXorError.error(), fileName);
            }
        }
    }
    return metadata;
}

From source file:com.google.gdt.googleapi.core.ApiDirectoryListingJsonCodec.java

License:Open Source License

protected void populateApiInfoFromJson(URL baseURL, JsonObject object, MutableApiInfo info) {
    if (object.has("name")) {
        info.setName(object.get("name").getAsString());
    }//from  www  . j  a v  a2  s .  c o  m
    if (object.has("version")) {
        info.setVersion(object.get("version").getAsString());
    }
    if (object.has("title")) {
        info.setDisplayName(object.get("title").getAsString());
    }
    if (object.has("publisher")) {
        info.setPublisher(object.get("publisher").getAsString());
    }
    if (object.has("description")) {
        info.setDescription(object.get("description").getAsString());
    }
    if (object.has("icons")) {
        JsonObject iconLinks = object.getAsJsonObject("icons");
        Set<Entry<String, JsonElement>> iconLinksEntrySet = iconLinks.entrySet();
        for (Entry<String, JsonElement> entry : iconLinksEntrySet) {
            try {
                info.putIconLink(entry.getKey(), new URL(baseURL, entry.getValue().getAsString()));
            } catch (MalformedURLException e) {
                // TODO Add logging warn
            }
        }
    }
    if (object.has("labels")) {
        JsonArray labelsJsonArray = object.getAsJsonArray("labels");

        for (JsonElement labelElement : labelsJsonArray) {
            info.addLabel(labelElement.getAsString());
        }
    }
    if (object.has("releaseDate")) {
        try {
            LocalDate date = new LocalDate(object.get("releaseDate").getAsString());
            info.setReleaseDate(date);
        } catch (IllegalArgumentException e) {
            throw new JsonParseException(e);
        }
    }
    if (object.has("releaseNotesLink")) {
        try {
            info.setReleaseNotesLink(new URL(baseURL, object.get("releaseNotesLink").getAsString()));
        } catch (MalformedURLException e) {
            // TODO Add logging warn
        }
    }
    if (object.has("ranking")) {
        info.setRanking(object.get("ranking").getAsInt());
    }
    if (object.has("discoveryLink")) {
        try {
            info.setDiscoveryLink(new URL(baseURL, object.get("discoveryLink").getAsString()));
        } catch (MalformedURLException e) {
            // TODO Add logging warn
        }
    }
    if (object.has("documentationLink")) {
        try {
            info.setDocumentationLink(new URL(baseURL, object.get("documentationLink").getAsString()));
        } catch (MalformedURLException e) {
            // TODO Add logging warn
        }
    }
    if (object.has("downloadLink")) {
        try {
            info.setDownloadLink(new URL(baseURL, object.get("downloadLink").getAsString()));
        } catch (MalformedURLException e) {
            // TODO Add logging warn
        }
    }
    if (object.has("tosLink")) {
        try {
            info.setTosLink(new URL(baseURL, object.get("tosLink").getAsString()));
        } catch (MalformedURLException e) {
            // TODO Add logging warn
        }
    }
}

From source file:com.google.gerrit.elasticsearch.AbstractElasticIndex.java

License:Apache License

protected static <T> List<T> decodeProtos(JsonObject doc, String fieldName, ProtobufCodec<T> codec) {
    JsonArray field = doc.getAsJsonArray(fieldName);
    if (field == null) {
        return null;
    }//from w  w w  . jav  a 2s  .  co  m
    return FluentIterable.from(field).transform(i -> codec.decode(decodeBase64(i.toString()))).toList();
}

From source file:com.google.gms.googleservices.GoogleServicesTask.java

License:Apache License

/**
 * find an item in the "client" array that match the package name of the app
 * @param jsonObject the root json object.
 * @return a JsonObject representing the client entry or null if no match is found.
 *//*from   ww w . ja  v a 2  s .c  o m*/
private JsonObject getClientForPackageName(JsonObject jsonObject) {
    JsonArray array = jsonObject.getAsJsonArray("client");
    if (array != null) {
        final int count = array.size();
        for (int i = 0; i < count; i++) {
            JsonElement clientElement = array.get(i);
            if (clientElement == null || !clientElement.isJsonObject()) {
                continue;
            }

            JsonObject clientObject = clientElement.getAsJsonObject();

            JsonObject clientInfo = clientObject.getAsJsonObject("client_info");
            if (clientInfo == null)
                continue;

            JsonObject androidClientInfo = clientInfo.getAsJsonObject("android_client_info");
            if (androidClientInfo == null)
                continue;

            JsonPrimitive clientPackageName = androidClientInfo.getAsJsonPrimitive("package_name");
            if (clientPackageName == null)
                continue;

            if (packageName.equals(clientPackageName.getAsString())) {
                return clientObject;
            }
        }
    }

    return null;
}

From source file:com.google.iosched.input.fetcher.RemoteJsonHelper.java

License:Open Source License

public static JsonObject mergeJsonFiles(JsonObject target, String... filenames) throws IOException {
    if (target == null) {
        target = new JsonObject();
    }/*from ww  w .j a va  2  s  . c  om*/
    for (String filename : filenames) {
        String url = Config.CLOUD_STORAGE_BASE_URL + filename;
        JsonObject obj = fetchJsonFromPublicURL(url);
        if (obj == null) {
            throw new FileNotFoundException(url);
        } else {
            for (Entry<String, JsonElement> entry : obj.entrySet()) {
                if (entry.getValue().isJsonArray()) {
                    // tries to merge an array with the existing one, if it's the case:
                    JsonArray existing = target.getAsJsonArray(entry.getKey());
                    if (existing == null) {
                        existing = new JsonArray();
                        target.add(entry.getKey(), existing);
                    }
                    existing.addAll(entry.getValue().getAsJsonArray());
                } else {
                    target.add(entry.getKey(), entry.getValue());
                }
            }
        }
    }
    return target;
}

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

License:Open Source License

public void checkUsingPredicator(CheckResult result, JsonObject oldData, JsonObject newData,
        ArrayValidator predicate) {/*from   ww w . j a v a2 s . c om*/
    for (Map.Entry<String, JsonElement> entry : oldData.entrySet()) {
        String oldKey = entry.getKey();
        JsonArray oldValues = entry.getValue().getAsJsonArray();
        predicate.evaluate(result, oldKey, oldValues, newData.getAsJsonArray(oldKey));
    }
}

From source file:com.google.iosched.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");
    }//  w w w  .j  a v a 2s  . 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(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, 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();
            set(origin, VendorAPISource.Topics.id, dest, OutputJsonKeys.Sessions.id);
            set(origin, VendorAPISource.Topics.id, dest, OutputJsonKeys.Sessions.url, Converters.SESSION_URL);
            set(origin, VendorAPISource.Topics.title, dest, OutputJsonKeys.Sessions.title, null);
            set(origin, VendorAPISource.Topics.description, dest, OutputJsonKeys.Sessions.description, null);
            set(origin, VendorAPISource.Topics.start, dest, OutputJsonKeys.Sessions.startTimestamp,
                    Converters.DATETIME);
            set(origin, VendorAPISource.Topics.finish, dest, OutputJsonKeys.Sessions.endTimestamp,
                    Converters.DATETIME);

            JsonElement documents = get(origin, 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, VendorAPISource.Topics.id, dest, OutputJsonKeys.Sessions.photoUrl,
                        Converters.SESSION_PHOTO_URL);
            }

            setVideoPropertiesInSession(origin, dest);
            setRelatedVideos(origin, dest);

            JsonElement mainTag = null;
            JsonElement hashtag = null;
            JsonElement mainTagColor = null;
            JsonArray categories = origin.getAsJsonArray(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, 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(VendorAPISource.Topics.sessions.name());
            if (sessions != null && sessions.size() > 0) {
                String roomId = get(sessions.get(0).getAsJsonObject(), 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);
                }
            }

            result.add(dest);
        }
    }
    return result;
}