Example usage for com.google.gson JsonArray add

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

Introduction

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

Prototype

public void add(JsonElement element) 

Source Link

Document

Adds the specified element to self.

Usage

From source file:com.google.dart.server.internal.remote.utilities.RequestUtilities.java

License:Open Source License

@VisibleForTesting
public static JsonElement buildJsonElement(Object object) {
    if (object instanceof Boolean) {
        return new JsonPrimitive((Boolean) object);
    } else if (object instanceof Number) {
        return new JsonPrimitive((Number) object);
    } else if (object instanceof String) {
        return new JsonPrimitive((String) object);
    } else if (object instanceof List<?>) {
        List<?> list = (List<?>) object;
        JsonArray jsonArray = new JsonArray();
        for (Object item : list) {
            JsonElement jsonItem = buildJsonElement(item);
            jsonArray.add(jsonItem);
        }/*from www. ja  va 2  s.c  o m*/
        return jsonArray;
    } else if (object instanceof Map<?, ?>) {
        Map<?, ?> map = (Map<?, ?>) object;
        JsonObject jsonObject = new JsonObject();
        for (Entry<?, ?> entry : map.entrySet()) {
            Object key = entry.getKey();
            // prepare string key
            String keyString;
            if (key instanceof String) {
                keyString = (String) key;
            } else {
                throw new IllegalArgumentException("Unable to convert to string: " + getClassName(key));
            }
            // prepare JsonElement value
            Object value = entry.getValue();
            JsonElement valueJson = buildJsonElement(value);
            // put a property into the JSON object
            if (keyString != null && valueJson != null) {
                jsonObject.add(keyString, valueJson);
            }
        }
        return jsonObject;
    } else if (object instanceof AnalysisError) {
        return buildJsonObjectAnalysisError((AnalysisError) object);
    } else if (object instanceof AddContentOverlay) {
        return ((AddContentOverlay) object).toJson();
    } else if (object instanceof ChangeContentOverlay) {
        return ((ChangeContentOverlay) object).toJson();
    } else if (object instanceof RemoveContentOverlay) {
        return ((RemoveContentOverlay) object).toJson();
    } else if (object instanceof AnalysisOptions) {
        return ((AnalysisOptions) object).toJson();
    } else if (object instanceof Location) {
        return buildJsonObjectLocation((Location) object);
    }
    throw new IllegalArgumentException("Unable to convert to JSON: " + object);
}

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

License:Open Source License

protected void populateJsonFromApiInfo(ReadableApiInfo src, JsonObject entry, String baseHref) {
    if (null != src.getName()) {
        entry.addProperty("name", src.getName());
    }//from   w  w  w  .ja  v  a  2  s  .  co m
    if (null != src.getVersion()) {
        entry.addProperty("version", src.getVersion());
    }
    if (null != src.getDisplayName()) {
        entry.addProperty("title", src.getDisplayName());
    }
    if (null != src.getPublisher()) {
        entry.addProperty("publisher", src.getPublisher());
    }
    String[] labels = src.getLabels();
    if (labels.length > 0) {
        JsonArray jsonLabels = new JsonArray();
        for (String label : labels) {
            jsonLabels.add(new JsonPrimitive(label));
        }
        entry.add("labels", jsonLabels);
    }
    entry.addProperty("ranking", src.getRanking());
    if (null != src.getDescription()) {
        entry.addProperty("description", src.getDescription());
    }
    Set<String> iconLinkRefs = src.getIconLinkKeys();
    if (!iconLinkRefs.isEmpty()) {
        JsonObject iconLinks = new JsonObject();
        for (String ref : iconLinkRefs) {
            URL link = src.getIconLink(ref);
            if (link == null) {
                break;
            }
            String linkStr = renderLink(link, baseHref);
            if (linkStr == null) {
                break;
            }
            iconLinks.addProperty(ref, linkStr);
        }
        entry.add("icons", iconLinks);
    }
    if (null != src.getTosLink()) {
        entry.addProperty("tosLink", src.getTosLink().toExternalForm());
    }
    if (null != src.getReleaseDate()) {
        entry.addProperty("releaseDate", src.getReleaseDate().toString());
    }
    if (null != src.getReleaseNotesLink()) {
        entry.addProperty("releaseNotesLink", src.getReleaseNotesLink().toExternalForm());
    }
    if (null != src.getDiscoveryLink()) {
        entry.addProperty("discoveryLink", src.getDiscoveryLink().toExternalForm());
    }
    if (null != src.getDocumentationLink()) {
        entry.addProperty("documentationLink", src.getDocumentationLink().toExternalForm());
    }
    if (null != src.getDownloadLink()) {
        entry.addProperty("downloadLink", src.getDownloadLink().toExternalForm());
    }
}

From source file:com.google.gerrit.httpd.restapi.ParameterParser.java

License:Apache License

@VisibleForTesting
static JsonObject formToJson(Map<String, String[]> map, Set<String> query) throws BadRequestException {
    JsonObject inputObject = new JsonObject();
    for (Map.Entry<String, String[]> ent : map.entrySet()) {
        String key = ent.getKey();
        String[] values = ent.getValue();

        if (query.contains(key) || values.length == 0) {
            // Disallow processing query parameters as input body fields.
            // Implementations of views should avoid duplicate naming.
            continue;
        }//from  w w w  .  j a va2 s .c om

        JsonObject obj = inputObject;
        int dot = key.indexOf('.');
        if (0 <= dot) {
            String property = key.substring(0, dot);
            JsonElement e = inputObject.get(property);
            if (e == null) {
                obj = new JsonObject();
                inputObject.add(property, obj);
            } else if (e.isJsonObject()) {
                obj = e.getAsJsonObject();
            } else {
                throw new BadRequestException(String.format("key %s conflicts with %s", key, property));
            }
            key = key.substring(dot + 1);
        }

        if (obj.get(key) != null) {
            // This error should never happen. If all form values are handled
            // together in a single pass properties are set only once. Setting
            // again indicates something has gone very wrong.
            throw new BadRequestException("invalid form input, use JSON instead");
        } else if (values.length == 1) {
            obj.addProperty(key, values[0]);
        } else {
            JsonArray list = new JsonArray();
            for (String v : values) {
                list.add(new JsonPrimitive(v));
            }
            obj.add(key, list);
        }
    }
    return inputObject;
}

From source file:com.google.gerrit.sshd.commands.QueryShell.java

License:Apache License

/**
 * Outputs a result set to stdout in Json format.
 *
 * @param rs ResultSet to show.//www .  j  a va2  s.co  m
 * @param alreadyOnRow true if rs is already on the first row. false
 *     otherwise.
 * @param start Timestamp in milliseconds when executing the statement
 *     started. This timestamp is used to compute statistics about the
 *     statement. If no statistics should be shown, set it to 0.
 * @param show Functions to map columns
 * @throws SQLException
 */
private void showResultSetJson(final ResultSet rs, boolean alreadyOnRow, long start, Function... show)
        throws SQLException {
    JsonArray collector = new JsonArray();
    final ResultSetMetaData meta = rs.getMetaData();
    final Function[] columnMap;
    if (show != null && 0 < show.length) {
        columnMap = show;

    } else {
        final int colCnt = meta.getColumnCount();
        columnMap = new Function[colCnt];
        for (int colId = 0; colId < colCnt; colId++) {
            final int p = colId + 1;
            final String name = meta.getColumnLabel(p);
            columnMap[colId] = new Identity(p, name);
        }
    }

    int rowCnt = 0;
    while (alreadyOnRow || rs.next()) {
        final JsonObject row = new JsonObject();
        final JsonObject cols = new JsonObject();
        for (Function function : columnMap) {
            String v = function.apply(rs);
            if (v == null) {
                continue;
            }
            cols.addProperty(function.name.toLowerCase(), v);
        }
        row.addProperty("type", "row");
        row.add("columns", cols);
        switch (outputFormat) {
        case JSON:
            println(row.toString());
            break;
        case JSON_SINGLE:
            collector.add(row);
            break;
        default:
            final JsonObject obj = new JsonObject();
            obj.addProperty("type", "error");
            obj.addProperty("message", "Unsupported Json variant");
            println(obj.toString());
            return;
        }
        alreadyOnRow = false;
        rowCnt++;
    }

    JsonObject tail = null;
    if (start != 0) {
        tail = new JsonObject();
        tail.addProperty("type", "query-stats");
        tail.addProperty("rowCount", rowCnt);
        final long ms = TimeUtil.nowMs() - start;
        tail.addProperty("runTimeMilliseconds", ms);
    }

    switch (outputFormat) {
    case JSON:
        if (tail != null) {
            println(tail.toString());
        }
        break;
    case JSON_SINGLE:
        if (tail != null) {
            collector.add(tail);
        }
        println(collector.toString());
        break;
    default:
        final JsonObject obj = new JsonObject();
        obj.addProperty("type", "error");
        obj.addProperty("message", "Unsupported Json variant");
        println(obj.toString());
    }
}

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

License:Open Source License

/**
 * Using 2-Leg Oauth (i.e. Service Account).
 *//*  w w w  .  j  a v  a 2  s . c om*/
public JsonObject getAccountInfoById(String localId) throws GitkitClientException, GitkitServerException {
    JsonObject params = new JsonObject();
    JsonArray localIdArray = new JsonArray();
    localIdArray.add(new JsonPrimitive(localId));
    params.add("localId", localIdArray);
    return invokeGoogle2LegOauthApi("getAccountInfo", params);
}

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

License:Open Source License

/**
 * Using 2-Leg Oauth (i.e. Service Account).
 *///from w  w w  .  j av a2  s . co  m
public JsonObject getAccountInfoByEmail(String email) throws GitkitClientException, GitkitServerException {
    JsonObject params = new JsonObject();
    JsonArray emailArray = new JsonArray();
    emailArray.add(new JsonPrimitive(email));
    params.add("email", emailArray);
    return invokeGoogle2LegOauthApi("getAccountInfo", params);
}

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

License:Open Source License

private static JsonArray toJsonArray(List<GitkitUser> accounts) {
    JsonArray infos = new JsonArray();
    for (GitkitUser account : accounts) {
        JsonObject user = new JsonObject();
        user.addProperty("email", account.getEmail());
        user.addProperty("localId", account.getLocalId());
        if (account.getHash() != null) {
            user.addProperty("passwordHash", BaseEncoding.base64Url().encode(account.getHash()));
        }//  ww w.j  a v  a  2s  . co m
        if (account.getSalt() != null) {
            user.addProperty("salt", BaseEncoding.base64Url().encode(account.getSalt()));
        }
        if (account.getProviders() != null) {
            JsonArray providers = new JsonArray();
            for (GitkitUser.ProviderInfo idpInfo : account.getProviders()) {
                JsonObject provider = new JsonObject();
                provider.addProperty("federatedId", idpInfo.getFederatedId());
                provider.addProperty("providerId", idpInfo.getProviderId());
                providers.add(provider);
            }
            user.add("providerUserInfo", providers);
        }
        infos.add(user);
    }
    return infos;
}

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

License:Open Source License

public JsonArray extractRooms(JsonDataSources sources) {
    HashSet<String> ids = new HashSet<String>();
    JsonArray result = new JsonArray();
    JsonDataSource source = sources.getSource(VendorAPISource.MainTypes.rooms.name());
    if (source != null) {
        for (JsonObject origin : source) {
            JsonObject dest = new JsonObject();
            JsonElement originalId = get(origin, VendorAPISource.Rooms.id);
            String id = Config.ROOM_MAPPING.getRoomId(originalId.getAsString());
            if (!ids.contains(id)) {
                String title = Config.ROOM_MAPPING.getTitle(id,
                        get(origin, VendorAPISource.Rooms.name).getAsString());
                set(new JsonPrimitive(id), dest, OutputJsonKeys.Rooms.id);
                set(originalId, dest, OutputJsonKeys.Rooms.original_id);
                set(new JsonPrimitive(title), dest, OutputJsonKeys.Rooms.name);
                result.add(dest);
                ids.add(id);/*from   www  .  java  2  s  . com*/
            }
        }
    }
    return result;
}

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

License:Open Source License

public JsonArray extractTags(JsonDataSources sources) {
    JsonArray result = new JsonArray();
    JsonDataSource source = sources.getSource(VendorAPISource.MainTypes.categories.name());
    JsonDataSource tagCategoryMappingSource = sources
            .getSource(ExtraSource.MainTypes.tag_category_mapping.name());
    JsonDataSource tagsConfSource = sources.getSource(ExtraSource.MainTypes.tag_conf.name());

    categoryToTagMap = new HashMap<String, JsonObject>();

    // Only for checking duplicates.
    HashSet<String> originalTagNames = new HashSet<String>();

    if (source != null) {
        for (JsonObject origin : source) {
            JsonObject dest = new JsonObject();

            // set tag category, looking for parentid in the tag_category_mapping data source
            JsonElement parentId = get(origin, VendorAPISource.Categories.parentid);

            // Ignore categories with null parents, because they are roots (tag categories).
            if (parentId != null && !parentId.getAsString().equals("")) {
                JsonElement category = null;
                if (tagCategoryMappingSource != null) {
                    JsonObject categoryMapping = tagCategoryMappingSource
                            .getElementById(parentId.getAsString());
                    if (categoryMapping != null) {
                        category = get(categoryMapping, ExtraSource.CategoryTagMapping.tag_name);
                        JsonPrimitive isDefault = (JsonPrimitive) get(categoryMapping,
                                ExtraSource.CategoryTagMapping.is_default);
                        if (isDefault != null && isDefault.getAsBoolean()) {
                            mainCategory = category;
                        }/*from   w w  w  .  j a va2  s. co m*/
                    }
                    set(category, dest, OutputJsonKeys.Tags.category);
                }

                // Ignore categories unrecognized parents (no category)
                if (category == null) {
                    continue;
                }

                // Tag name is by convention: "TAGCATEGORY_TAGNAME"
                JsonElement name = get(origin, VendorAPISource.Categories.name);
                JsonElement tagName = new JsonPrimitive(
                        category.getAsString() + "_" + Converters.TAG_NAME.convert(name).getAsString());
                JsonElement originalTagName = tagName;

                set(tagName, dest, OutputJsonKeys.Tags.tag);
                set(name, dest, OutputJsonKeys.Tags.name);
                set(origin, VendorAPISource.Categories.id, dest, OutputJsonKeys.Tags.original_id);
                set(origin, VendorAPISource.Categories.description, dest, OutputJsonKeys.Tags._abstract, null);

                if (tagsConfSource != null) {
                    JsonObject tagConf = tagsConfSource.getElementById(originalTagName.getAsString());
                    if (tagConf != null) {
                        set(tagConf, ExtraSource.TagConf.order_in_category, dest,
                                OutputJsonKeys.Tags.order_in_category);
                        set(tagConf, ExtraSource.TagConf.color, dest, OutputJsonKeys.Tags.color);
                        set(tagConf, ExtraSource.TagConf.hashtag, dest, OutputJsonKeys.Tags.hashtag);
                    }
                }

                categoryToTagMap.put(get(origin, VendorAPISource.Categories.id).getAsString(), dest);
                if (originalTagNames.add(originalTagName.getAsString())) {
                    result.add(dest);
                }
            }
        }
    }
    return result;
}

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

License:Open Source License

public JsonArray extractSpeakers(JsonDataSources sources) {
    speakersById = new HashMap<String, JsonObject>();
    JsonArray result = new JsonArray();
    JsonDataSource source = sources.getSource(VendorAPISource.MainTypes.speakers.name());
    if (source != null) {
        for (JsonObject origin : source) {
            JsonObject dest = new JsonObject();
            JsonElement id = get(origin, VendorAPISource.Speakers.id);
            set(id, dest, OutputJsonKeys.Speakers.id);
            set(origin, VendorAPISource.Speakers.name, dest, OutputJsonKeys.Speakers.name, null);
            set(origin, VendorAPISource.Speakers.bio, dest, OutputJsonKeys.Speakers.bio, null);
            set(origin, VendorAPISource.Speakers.companyname, dest, OutputJsonKeys.Speakers.company, null);
            JsonElement originalPhoto = get(origin, VendorAPISource.Speakers.photo);
            if (originalPhoto != null && !"".equals(originalPhoto.getAsString())) {
                // Note that the input for SPEAKER_PHOTO_ID converter 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.Speakers.id, dest, OutputJsonKeys.Speakers.thumbnailUrl,
                        Converters.SPEAKER_PHOTO_URL);
            }//  ww w .j  a  v a  2s  .  c o m
            JsonElement info = origin.get(VendorAPISource.Speakers.info.name());
            JsonPrimitive plusUrl = getMapValue(info,
                    InputJsonKeys.VendorAPISource.Speakers.INFO_PUBLIC_PLUS_ID, Converters.GPLUS_URL, null);
            if (plusUrl != null) {
                set(plusUrl, dest, OutputJsonKeys.Speakers.plusoneUrl);
            }
            result.add(dest);
            speakersById.put(id.getAsString(), dest);
        }
    }
    return result;
}