Example usage for com.google.gson JsonObject getAsJsonObject

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

Introduction

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

Prototype

public JsonObject getAsJsonObject(String memberName) 

Source Link

Document

Convenience method to get the specified member as a JsonObject.

Usage

From source file:com.ccreanga.bitbucket.rest.client.http.responseparsers.PullRequestParser.java

License:Apache License

@Override
public PullRequest apply(JsonElement jsonElement) {
    if (jsonElement == null || !jsonElement.isJsonObject()) {
        return null;
    }/*from  w  w w  . j  a  v a2 s .c  om*/
    JsonObject json = jsonElement.getAsJsonObject();
    //PullRequest pullRequest = new PullRequest();

    PullRequestParticipant author = pullRequestParticipantParser().apply(json.getAsJsonObject("author"));
    List<PullRequestParticipant> reviewers = listParser(pullRequestParticipantParser())
            .apply(json.get("reviewers"));
    List<PullRequestParticipant> participants = listParser(pullRequestParticipantParser())
            .apply(json.get("participants"));
    PullRequestBranch from = pullRequestBranchParser().apply(json.getAsJsonObject("fromRef"));
    PullRequestBranch to = pullRequestBranchParser().apply(json.getAsJsonObject("toRef"));

    String selfUrl = null;

    if (json.has("links")) {
        selfUrl = linkParser().apply(json.getAsJsonObject("links").get("self").getAsJsonArray().get(0))
                .getHref();
    }

    return new PullRequest(json.get("id").getAsLong(), json.get("version").getAsLong(),
            json.get("title").getAsString(), optionalJsonString(json, "description"),
            PullRequestState.valueOf(json.get("state").getAsString()), json.get("open").getAsBoolean(),
            json.get("closed").getAsBoolean(), new Date(json.get("createdDate").getAsLong()),
            new Date(json.get("updatedDate").getAsLong()), from, to, optionalJsonBoolean(json, "locked"),
            author, reviewers, participants, selfUrl);

}

From source file:com.ccreanga.bitbucket.rest.client.http.responseparsers.PullRequestParticipantParser.java

License:Apache License

@Override
public PullRequestParticipant apply(JsonElement jsonElement) {
    JsonObject jsonObject = jsonElement.getAsJsonObject();
    User user = userParser().apply(jsonObject.getAsJsonObject("user"));
    return new PullRequestParticipant(user, PullRequestRole.valueOf(jsonObject.get("role").getAsString()),
            jsonObject.get("approved").getAsBoolean());
}

From source file:com.ccreanga.bitbucket.rest.client.http.responseparsers.RepositoryParser.java

License:Apache License

@Override
public Repository apply(JsonElement jsonElement) {
    if (jsonElement == null || !jsonElement.isJsonObject()) {
        return null;
    }//from   ww  w .ja va  2  s.c  o m

    JsonObject json = jsonElement.getAsJsonObject();

    String sshCloneUrl = null;
    String httpCloneUrl = null;
    String selfUrl = null;

    if (json.has("links")) {
        JsonObject links = json.getAsJsonObject("links");
        selfUrl = linkParser("url", "text").apply(links.get("self").getAsJsonArray().get(0)).getHref();

        if (links.has("clone")) {
            JsonArray arrayCloneLinks = links.get("clone").getAsJsonArray();
            Link first = linkParser().apply(arrayCloneLinks.get(0));
            Link second = linkParser().apply(arrayCloneLinks.get(1));
            if (first.getName().equals("http")) {
                httpCloneUrl = first.getHref();
                sshCloneUrl = second.getHref();
            } else {
                sshCloneUrl = first.getHref();
                httpCloneUrl = second.getHref();
            }
        }
    }

    return new Repository(optionalJsonString(json, "hierarchyId"), json.get("id").getAsLong(),
            json.get("slug").getAsString(), json.get("name").getAsString(), optionalJsonBoolean(json, "public"),
            optionalJsonBoolean(json, "fork"), optionalJsonBoolean(json, "forkable"), sshCloneUrl, httpCloneUrl,
            selfUrl, projectParser().apply(json.getAsJsonObject("project")),
            json.has("origin") ? repositoryParser().apply(json.getAsJsonObject("origin")) : null,
            json.get("scmId").getAsString(), RepositoryState.valueOf(json.get("state").getAsString()),
            json.get("statusMessage").getAsString());

}

From source file:com.ccreanga.bitbucket.rest.client.http.responseparsers.RepositorySshKeyParser.java

License:Apache License

@Override
public RepositorySshKey apply(JsonElement json) {
    JsonObject jsonObject = json.getAsJsonObject();
    JsonObject repositoryObject = jsonObject.getAsJsonObject("repository");
    Repository repository = Parsers.repositoryParser().apply(repositoryObject);

    JsonObject key = jsonObject.getAsJsonObject("key");

    return new RepositorySshKey(key.get("id").getAsLong(), key.get("text").getAsString(),
            key.get("label").getAsString(), repository, jsonObject.get("permission").getAsString());
}

From source file:com.ccreanga.bitbucket.rest.client.http.responseparsers.TaskParser.java

License:Apache License

@Override
public Task apply(JsonElement jsonElement) {
    if (jsonElement == null || !jsonElement.isJsonObject()) {
        return null;
    }//from w  w  w . java 2 s .  co  m
    JsonObject json = jsonElement.getAsJsonObject();
    return new Task(json.get("id").getAsLong(), TaskState.valueOf(json.get("state").getAsString()),
            json.get("text").getAsString(), new Date(json.get("createdDate").getAsLong()),
            commentParser().apply(json.getAsJsonObject("anchor")),
            userParser().apply(json.getAsJsonObject("author")),
            taskOperationsParser().apply(json.getAsJsonObject("permittedOperations")));
}

From source file:com.cloudant.client.api.Search.java

License:Open Source License

/**
 * Performs a Cloudant Search and returns the result as an {@link SearchResult}
 *
 * @param <T>      Object type T, an instance into which the rows[].doc/group[].rows[].doc
 *                 attribute of the Search result response should be deserialized into. Same
 *                 goes for the rows[].fields/group[].rows[].fields attribute
 * @param query    the Lucene query to be passed to the Search index
 * @param classOfT The class of type T./* www .  jav a  2  s  .c om*/
 * @return The Search result entries
 */
public <T> SearchResult<T> querySearchResult(String query, Class<T> classOfT) {
    InputStream instream = null;
    try {
        Reader reader = new InputStreamReader(instream = queryForStream(query), "UTF-8");
        JsonObject json = new JsonParser().parse(reader).getAsJsonObject();
        SearchResult<T> sr = new SearchResult<T>();
        sr.setTotalRows(getAsLong(json, "total_rows"));
        sr.setBookmark(getAsString(json, "bookmark"));
        if (json.has("rows")) {
            sr.setRows(getRows(json.getAsJsonArray("rows"), sr, classOfT));
        } else if (json.has("groups")) {
            setGroups(json.getAsJsonArray("groups"), sr, classOfT);
        }

        if (json.has("counts")) {
            sr.setCounts(getFieldsCounts(json.getAsJsonObject("counts").entrySet()));
        }

        if (json.has("ranges")) {
            sr.setRanges(getFieldsCounts(json.getAsJsonObject("ranges").entrySet()));
        }
        return sr;
    } catch (UnsupportedEncodingException e) {
        // This should never happen as every implementation of the java platform is required
        // to support UTF-8.
        throw new RuntimeException(e);
    } finally {
        close(instream);
    }
}

From source file:com.continusec.client.VerifiableMap.java

License:Apache License

/**
 * Get the tree hash for given tree size.
 *
 * @param treeSize the tree size to retrieve the hash for. Pass {@link ContinusecClient#HEAD} to get the
 * latest tree size./* w  ww  .j a  v  a2  s. c  o m*/
 * @return the tree hash for the given size (includes the tree size actually used, if unknown before running the query).
 * @throws ContinusecException upon error
 */
public MapTreeHead getTreeHead(int treeSize) throws ContinusecException {
    try {
        JsonObject e = new JsonParser().parse(new String(
                this.client.makeRequest("GET", this.path + "/tree/" + treeSize, null, null).data, "UTF-8"))
                .getAsJsonObject();
        return new MapTreeHead(Base64.decodeBase64(e.get("map_hash").getAsString()),
                LogTreeHead.fromJsonObject(e.getAsJsonObject("mutation_log")));
    } catch (UnsupportedEncodingException e) {
        throw new ContinusecException(e);
    }
}

From source file:com.continuuity.loom.codec.json.current.ResourceCollectionCodec.java

License:Apache License

@Override
public JsonElement serialize(ResourceCollection src, Type typeOfSrc, JsonSerializationContext context) {
    JsonObject out = new JsonObject();
    out.add("automatortypes", new JsonObject());
    out.add("providertypes", new JsonObject());

    /*//  w w w  . j  a  va  2 s  .  co  m
     * Transform it into something like:
     *
     * "resources": {
     *   "automatortypes": {
     *     "chef-solo": {
     *       "cookbooks": {
     *         "format": "archive|file",
     *         "active": [
     *           {
     *             "name":"reactor",
     *             "version":9
     *           }
     *         ]
     *       }
     *     },
     *     ...
     *   },
     * }
     */
    for (ImmutablePair<ResourceType, ResourceTypeFormat> key : src.getResources().keySet()) {
        ResourceType resourceType = key.getFirst();
        ResourceTypeFormat format = key.getSecond();
        String pluginTypeStr = pluginTypeToStr(resourceType.getPluginType());
        String pluginName = resourceType.getPluginName();
        String resourceTypeStr = resourceType.getTypeName();
        // ex: json object for automatortypes
        JsonObject pluginTypeObj = out.getAsJsonObject(pluginTypeStr);
        if (!pluginTypeObj.has(pluginName)) {
            pluginTypeObj.add(pluginName, new JsonObject());
        }
        // ex: json object for chef-solo
        JsonObject pluginObj = pluginTypeObj.getAsJsonObject(pluginName);
        if (!pluginObj.has(resourceTypeStr)) {
            pluginObj.add(resourceTypeStr, new JsonObject());
        }
        // ex: json object for cookbooks
        JsonObject resourceListObj = pluginObj.getAsJsonObject(resourceTypeStr);
        // write the format
        resourceListObj.add("format", context.serialize(format));
        // write the list of active resources
        JsonArray activeList = new JsonArray();
        for (ResourceMeta meta : src.getResources().get(key)) {
            JsonObject metaObj = new JsonObject();
            metaObj.addProperty("name", meta.getName());
            metaObj.addProperty("version", meta.getVersion());
            activeList.add(metaObj);
        }
        resourceListObj.add("active", activeList);
    }

    return out;
}

From source file:com.continuuity.loom.codec.json.upgrade.NodeUpgradeCodec.java

License:Apache License

@Override
public Node deserialize(JsonElement json, Type type, JsonDeserializationContext context)
        throws JsonParseException {
    JsonObject jsonObj = json.getAsJsonObject();

    String id = context.deserialize(jsonObj.get("id"), String.class);
    String clusterId = context.deserialize(jsonObj.get("clusterId"), String.class);
    Set<Service> services = context.deserialize(jsonObj.get("services"), new TypeToken<Set<Service>>() {
    }.getType());//w  w  w . ja  va  2 s.  c  o m

    JsonObject properties = jsonObj.getAsJsonObject("properties");
    String ipaddress = context.deserialize(properties.get("ipaddress"), String.class);
    String hostname = context.deserialize(properties.get("hostname"), String.class);
    Integer nodenum = context.deserialize(properties.get("nodenum"), Integer.class);
    if (nodenum == null) {
        nodenum = 0;
    }
    Set<String> automators = context.deserialize(properties.get("automators"), new TypeToken<Set<String>>() {
    }.getType());
    Set<String> nodeServices = context.deserialize(properties.get("services"), new TypeToken<Set<String>>() {
    }.getType());
    String hardwaretype = context.deserialize(properties.get("hardwaretype"), String.class);
    String imagetype = context.deserialize(properties.get("imagetype"), String.class);
    String flavor = context.deserialize(properties.get("flavor"), String.class);
    String image = context.deserialize(properties.get("image"), String.class);
    NodeProperties nodeProperties = NodeProperties.builder().setHostname(hostname).setIpaddress(ipaddress)
            .setNodenum(nodenum).setHardwaretype(hardwaretype).setImagetype(imagetype).setFlavor(flavor)
            .setImage(image).setAutomators(automators).setServiceNames(nodeServices).setSSHUser("root").build();
    return new Node(id, clusterId, services, nodeProperties);
}

From source file:com.createtank.payments.coinbase.CoinbaseApi.java

License:Apache License

/**
 * Purchase bitcoin by debiting the user's U.S. bank account.
 * @param qty the number of bitcoins to buy
 * @return A Transfer object containing information about the purchase
 * @throws IOException/*from   ww  w  . j a  v  a 2s.  c  o  m*/
 */
public Transfer buyBitcoins(float qty) throws IOException {
    Map<String, String> params = new HashMap<String, String>();
    if (apiKey != null)
        params.put("api_key", apiKey);

    params.put("qty", Float.toString(qty));
    params.put("agree_btc_amount_varies", Boolean.toString(true));

    JsonObject response = RequestClient.post(this, "buys", params, accessToken);
    boolean success = response.get("success").getAsBoolean();

    return success ? Transfer.fromJson(response.getAsJsonObject("transfer")) : null;
}