Example usage for com.google.gson JsonArray size

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

Introduction

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

Prototype

public int size() 

Source Link

Document

Returns the number of elements in the array.

Usage

From source file:com.google.e2e.bcdriver.Main.java

License:Apache License

private static final void runImportTest(JsonObject config, File base)
        throws IOException, PGPException, SignatureException {
    File root = base.getParentFile();
    String baseName = getBaseName(base);
    KeyChecker.PKR info = KeyChecker.validate(Util.readPublicKeyRing(new File(root, baseName + ".asc")));
    assertEquals(info.getErrors(), KeyChecker.PKR.Status.OK, info.getStatus());
    assertEquals("mismatched fingerprint", config.get("expected_fingerprint").getAsString(),
            hexEncode(info.getOriginal().getPublicKey().getFingerprint()));
    JsonArray uids = config.get("expected_uids").getAsJsonArray();
    assertEquals("Uids not correctly found", uids.size(), info.getUserIDs().size());
    Set<String> actualUids = new HashSet<String>();
    for (KeyChecker.UserID uid : info.getUserIDs()) {
        actualUids.add(uid.getName());/*ww  w.  j a  v a 2 s  . com*/
    }
    for (JsonElement uid : uids) {
        assertEquals("missing uid", actualUids.contains(uid.getAsString()), true);
    }
    if (config.has("expected_subkeys")) {
        JsonArray subkeys = config.get("expected_subkeys").getAsJsonArray();
        assertEquals("Subkeys not found", subkeys.size(), info.getSubkeys().size());
        Set<String> fingerprints = new HashSet<String>();
        for (KeyChecker.Subkey subkey : info.getSubkeys()) {
            fingerprints.add(hexEncode(subkey.getPublicKey().getFingerprint()));
        }
        for (JsonElement subkey : subkeys) {
            JsonObject data = subkey.getAsJsonObject();
            if (data.has("expected_fingerprint")) {
                assertEquals("missing fingerprint",
                        fingerprints.contains(data.get("expected_fingerprint").getAsString()), true);
            }
        }
    }
    println("OK");
}

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 .j  av  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.gwtjsonrpc.server.CallDeserializer.java

License:Apache License

public CallType deserialize(final JsonElement json, final Type typeOfT,
        final JsonDeserializationContext context) throws JsonParseException, NoSuchRemoteMethodException {
    if (!json.isJsonObject()) {
        throw new JsonParseException("Expected object");
    }//from  ww w. j a  va2 s  .  co  m

    final JsonObject in = json.getAsJsonObject();
    req.id = in.get("id");

    final JsonElement jsonrpc = in.get("jsonrpc");
    final JsonElement version = in.get("version");
    if (isString(jsonrpc) && version == null) {
        final String v = jsonrpc.getAsString();
        if ("2.0".equals(v)) {
            req.versionName = "jsonrpc";
            req.versionValue = jsonrpc;
        } else {
            throw new JsonParseException("Expected jsonrpc=2.0");
        }

    } else if (isString(version) && jsonrpc == null) {
        final String v = version.getAsString();
        if ("1.1".equals(v)) {
            req.versionName = "version";
            req.versionValue = version;
        } else {
            throw new JsonParseException("Expected version=1.1");
        }
    } else {
        throw new JsonParseException("Expected version=1.1 or jsonrpc=2.0");
    }

    final JsonElement method = in.get("method");
    if (!isString(method)) {
        throw new JsonParseException("Expected method name as string");
    }

    req.method = server.lookupMethod(method.getAsString());
    if (req.method == null) {
        throw new NoSuchRemoteMethodException();
    }

    final JsonElement callback = in.get("callback");
    if (callback != null) {
        if (!isString(callback)) {
            throw new JsonParseException("Expected callback as string");
        }
        req.callback = callback.getAsString();
    }

    final JsonElement xsrfKey = in.get("xsrfKey");
    if (xsrfKey != null) {
        if (!isString(xsrfKey)) {
            throw new JsonParseException("Expected xsrfKey as string");
        }
        req.xsrfKeyIn = xsrfKey.getAsString();
    }

    final Type[] paramTypes = req.method.getParamTypes();
    final JsonElement params = in.get("params");
    if (params != null) {
        if (!params.isJsonArray()) {
            throw new JsonParseException("Expected params array");
        }

        final JsonArray paramsArray = params.getAsJsonArray();
        if (paramsArray.size() != paramTypes.length) {
            throw new JsonParseException("Expected " + paramTypes.length + " parameter values in params array");
        }

        final Object[] r = new Object[paramTypes.length];
        for (int i = 0; i < r.length; i++) {
            final JsonElement v = paramsArray.get(i);
            if (v != null) {
                r[i] = context.deserialize(v, paramTypes[i]);
            }
        }
        req.params = r;
    } else {
        if (paramTypes.length != 0) {
            throw new JsonParseException("Expected params array");
        }
        req.params = JsonServlet.NO_PARAMS;
    }

    return req;
}

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

License:Open Source License

public GitkitUser setProviders(JsonArray providers) {
    List<ProviderInfo> providerInfo = new ArrayList<ProviderInfo>();
    if (providers != null) {
        for (int i = 0; i < providers.size(); i++) {
            JsonObject provider = providers.get(i).getAsJsonObject();
            JsonElement displayNameElement = provider.get("displayName");
            JsonElement photoUrlElement = provider.get("photoUrl");
            providerInfo.add(new ProviderInfo(provider.get("providerId").getAsString(),
                    provider.get("federatedId").getAsString(),
                    (displayNameElement == null) ? "" : displayNameElement.getAsString(),
                    (photoUrlElement == null) ? "" : photoUrlElement.getAsString()));
        }/*ww w. j a v a 2  s.c  om*/
    }
    this.providers = providerInfo;
    return this;
}

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 ww.  j av  a 2  s  . com*/
    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;
}

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");
    }//from   w  w  w  .j  a  va  2s  .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;//www . ja  v  a2s.com
    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.iosched.server.input.DataSourceInput.java

License:Open Source License

public JsonDataSources fetchAllDataSources() throws IOException {
    JsonDataSources sources = new JsonDataSources();
    for (EnumType type : getType().getEnumConstants()) {
        JsonArray data = fetch(type);
        if (LOG.isLoggable(Level.INFO)) {
            LOG.info("result for " + type + ": entities=" + data.size());
        }/*from ww w.j av  a 2 s.  c o m*/
        sources.addSource(new JsonDataSource(type, data));
    }
    return sources;
}

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

License:Apache License

@Override
protected List<SourceFile> createExterns() throws FlagUsageException, IOException {
    List<SourceFile> externs = Lists.newArrayList(externsMap.get("es3.js"), externsMap.get("es5.js"),
            externsMap.get("es6.js"), externsMap.get("v8.js"));

    // Attempt to load user-defined externs from the "externs" key in "package.json".
    // Expects the contents of "externs" to be an array.
    Path moduleRoot = getModuleRoot();
    File packageFile = new File(moduleRoot.toString(), "package.json");
    if (packageFile.isFile()) {
        try {//from   w  w w  .  j av  a2 s . c  o m
            JsonObject packageJson = getPackageJson(packageFile);
            JsonArray jsonExterns = unsafeGet(packageJson, "externs").getAsJsonArray();
            int len = jsonExterns.size();
            for (int i = 0; i < len; i++) {
                String path = moduleRoot.resolve(unsafeGet(jsonExterns, i).getAsString()).normalize()
                        .toString();
                externs.add(SourceFile.fromFile(path));
            }
        } catch (JsonParseException e) {
        } // no one cares
        catch (IOException e) {
        } // no one cares
    }

    return externs;
}

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");
    }/*  w w w.j a  va  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(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;
}