Example usage for com.google.gson JsonObject has

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

Introduction

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

Prototype

public boolean has(String memberName) 

Source Link

Document

Convenience method to check if a member with the specified name is present in this object.

Usage

From source file:com.google.debugging.sourcemap.SourceMapObjectParser.java

License:Apache License

public static SourceMapObject parse(String contents) throws SourceMapParseException {

    SourceMapObject.Builder builder = SourceMapObject.builder();

    try {/* w ww . j  av a 2 s.c o  m*/
        JsonObject sourceMapRoot = new Gson().fromJson(contents, JsonObject.class);

        builder.setVersion(sourceMapRoot.get("version").getAsInt());
        builder.setFile(getStringOrNull(sourceMapRoot, "file"));
        builder.setLineCount(sourceMapRoot.has("lineCount") ? sourceMapRoot.get("lineCount").getAsInt() : -1);
        builder.setMappings(getStringOrNull(sourceMapRoot, "mappings"));
        builder.setSourceRoot(getStringOrNull(sourceMapRoot, "sourceRoot"));

        if (sourceMapRoot.has("sections")) {
            ImmutableList.Builder<SourceMapSection> listBuilder = ImmutableList.builder();
            for (JsonElement each : sourceMapRoot.get("sections").getAsJsonArray()) {
                listBuilder.add(buildSection(each.getAsJsonObject()));
            }
            builder.setSections(listBuilder.build());
        }

        builder.setSources(getJavaStringArray(sourceMapRoot.get("sources")));
        builder.setNames(getJavaStringArray(sourceMapRoot.get("names")));

        Map<String, Object> extensions = new LinkedHashMap<>();
        for (Map.Entry<String, JsonElement> entry : sourceMapRoot.entrySet()) {
            if (entry.getKey().startsWith("x_")) {
                extensions.put(entry.getKey(), entry.getValue());
            }
        }
        builder.setExtensions(Collections.unmodifiableMap(extensions));

    } catch (JsonParseException ex) {
        throw new SourceMapParseException("JSON parse exception: " + ex);
    }

    return builder.build();
}

From source file:com.google.debugging.sourcemap.SourceMapObjectParser.java

License:Apache License

private static SourceMapSection buildSection(JsonObject section) throws SourceMapParseException {
    JsonObject offset = section.get("offset").getAsJsonObject();
    int line = offset.get("line").getAsInt();
    int column = offset.get("column").getAsInt();

    if (section.has("map") && section.has("url")) {
        throw new SourceMapParseException("Invalid map format: section may not have both 'map' and 'url'");
    } else if (section.has("url")) {
        return SourceMapSection.forURL(section.get("url").getAsString(), line, column);
    } else if (section.has("map")) {
        return SourceMapSection.forMap(section.get("map").toString(), line, column);
    }/*w ww  .  java2 s.c om*/

    throw new SourceMapParseException("Invalid map format: section must have either 'map' or 'url'");
}

From source file:com.google.devtools.build.lib.webstatusserver.WebStatusBuildLog.java

License:Open Source License

private JsonObject mergeTestCases(JsonObject currentNode, String fullName, TestCase testCase, int shardNumber) {
    if (currentNode == null) {
        currentNode = createTestCaseEmptyJsonNode(fullName, testCase);
    }//  ww  w.  jav a2s  .  c o m

    if (testCase.getRun()) {
        JsonObject results = (JsonObject) currentNode.get("results");
        JsonObject times = (JsonObject) currentNode.get("times");

        if (testCase.hasResult()) {
            results.addProperty(Integer.toString(shardNumber), testCase.getResult());
        }

        if (testCase.hasStatus()) {
            results.addProperty(Integer.toString(shardNumber), testCase.getStatus().toString());
        }

        if (testCase.hasRunDurationMillis()) {
            times.addProperty(Integer.toString(shardNumber), testCase.getRunDurationMillis());
        }
    }
    JsonObject children = (JsonObject) currentNode.get("children");

    for (TestCase child : testCase.getChildList()) {
        String fullChildName = child.getClassName() + "." + child.getName();
        JsonObject childNode = mergeTestCases((JsonObject) children.get(fullChildName), fullChildName, child,
                shardNumber);
        if (!children.has(fullChildName)) {
            children.add(fullChildName, childNode);
        }
    }
    return currentNode;
}

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());/*  www  .  ja  v a 2 s. co  m*/
    }
    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.e2e.bcdriver.Main.java

License:Apache License

private static final void runDecryptTest(JsonObject config, File base)
        throws PGPException, SignatureException, IOException {
    File root = base.getParentFile();
    String baseName = getBaseName(base);

    KeyChecker.PKR verify;//  w ww .j a v  a  2  s  .  c o  m
    if (config.has("verifyKey")) {
        verify = KeyChecker
                .validate(Util.readPublicKeyRing(new File(root, config.get("verifyKey").getAsString())));
        assertEquals(verify.getErrors(), KeyChecker.PKR.Status.OK, verify.getStatus());
    } else {
        verify = null;
    }

    PGPSecretKeyRing skr = Util.readSecretKeyRing(new File(root, config.get("decryptKey").getAsString()));
    assertNotNull("Could not read key", skr);

    PGPPrivateKey decryptKey = Decryptor.extractDecryptionKey(skr, config.get("passphrase").getAsString());
    assertNotNull("Could not decrypt secret key", decryptKey);

    BufferedInputStream bin = null;
    try {
        bin = new BufferedInputStream(new FileInputStream(new File(root, baseName + ".asc")));
        Decryptor.Result result = Decryptor.decrypt(bin, decryptKey, verify);
        if (config.has("filename")) {
            assertEquals("Mismatched filename", config.get("filename").getAsString(), result.getName());
        }
        if (config.has("textcontent")) {
            assertEquals("Incorrect content", config.get("textcontent").getAsString(),
                    new String(result.getPlainText(), "utf-8"));
        }
        println("OK");
    } finally {
        if (bin != null) {
            try {
                bin.close();
            } catch (IOException ignore) {
                ; // ignore
            }
        }
    }
}

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  ww w .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.identitytoolkit.GitkitClient.java

License:Open Source License

/**
 * Verifies a Gitkit token.// w w w  .jav a 2  s.co m
 *
 * @param token token string to be verified.
 * @return Gitkit user if token is valid.
 * @throws GitkitClientException if token has invalid signature
 */
public GitkitUser validateToken(String token) throws GitkitClientException {
    JsonObject jsonToken = validateTokenToJson(token);
    if (jsonToken == null) {
        return null;
    }
    return new GitkitUser().setLocalId(jsonToken.get(JsonTokenHelper.ID_TOKEN_USER_ID).getAsString())
            .setEmail(jsonToken.get(JsonTokenHelper.ID_TOKEN_EMAIL).getAsString())
            .setCurrentProvider(jsonToken.has(JsonTokenHelper.ID_TOKEN_PROVIDER)
                    ? jsonToken.get(JsonTokenHelper.ID_TOKEN_PROVIDER).getAsString()
                    : null)
            .setName(jsonToken.has(JsonTokenHelper.ID_TOKEN_DISPLAY_NAME)
                    ? jsonToken.get(JsonTokenHelper.ID_TOKEN_DISPLAY_NAME).getAsString()
                    : null)
            .setPhotoUrl(jsonToken.has(JsonTokenHelper.ID_TOKEN_PHOTO_URL)
                    ? jsonToken.get(JsonTokenHelper.ID_TOKEN_PHOTO_URL).getAsString()
                    : null);
}

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

License:Open Source License

@VisibleForTesting
JsonObject checkGitkitException(String response) throws GitkitClientException, GitkitServerException {
    JsonElement resultElement = new JsonParser().parse(response);
    if (!resultElement.isJsonObject()) {
        throw new GitkitServerException("null error code from Gitkit server");
    }/*from   w w w. j  av a 2s .  co  m*/
    JsonObject result = resultElement.getAsJsonObject();
    if (!result.has("error")) {
        return result;
    }
    // Error handling
    JsonObject error = result.getAsJsonObject("error");
    JsonElement codeElement = error.get("code");
    if (codeElement != null) {
        JsonElement messageElement = error.get("message");
        String message = (messageElement == null) ? "" : messageElement.getAsString();
        if (codeElement.getAsString().startsWith("4")) {
            // 4xx means client input error
            throw new GitkitClientException(message);
        } else {
            throw new GitkitServerException(message);
        }
    }
    throw new GitkitServerException("null error code from Gitkit server");
}

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

License:Open Source License

private void merge(JsonObject source, JsonObject dest) {
    for (Map.Entry<String, JsonElement> entry : source.entrySet()) {
        JsonArray values = entry.getValue().getAsJsonArray();
        if (dest.has(entry.getKey())) {
            dest.get(entry.getKey()).getAsJsonArray().addAll(values);
        } else {//from  w ww.j  a  va 2 s  .  com
            dest.add(entry.getKey(), values);
        }
    }
}

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

License:Open Source License

private void setRelatedVideos(JsonObject origin, JsonObject dest) {
    JsonArray related = getAsArray(origin, VendorAPISource.Topics.related);
    if (related == null) {
        return;/*from   www. jav  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);
        }
    }
}