Example usage for com.google.gson JsonObject getAsJsonPrimitive

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

Introduction

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

Prototype

public JsonPrimitive getAsJsonPrimitive(String memberName) 

Source Link

Document

Convenience method to get the specified member as a JsonPrimitive element.

Usage

From source file:org.broad.igv.ga4gh.Ga4ghAPIHelper.java

License:Open Source License

private static String getErrorMessage(HttpURLConnection connection) throws IOException {
    BufferedReader br = new BufferedReader(
            new InputStreamReader(new GZIPInputStream(connection.getErrorStream())));
    StringBuffer sb = new StringBuffer();
    String str = br.readLine();/*from  w  ww.ja v  a2s  . com*/
    while (str != null) {
        sb.append(str);
        str = br.readLine();
    }
    br.close();

    JsonParser parser = new JsonParser();
    JsonObject obj = parser.parse(sb.toString()).getAsJsonObject();

    JsonObject errorObject = obj.getAsJsonObject("error");
    if (errorObject != null) {
        JsonPrimitive msg = errorObject.getAsJsonPrimitive("message");
        if (msg != null)
            return msg.getAsString();
    }

    return sb.toString();
}

From source file:org.broad.igv.ga4gh.OAuthUtils.java

License:Open Source License

private void fetchTokens(String redirect) throws IOException {

    // properties moved to early init dwm08
    //if (clientId == null) fetchOauthProperties();

    URL url = new URL(tokenURI);

    Map<String, String> params = new HashMap<String, String>();
    params.put("code", authorizationCode);
    params.put("client_id", clientId);
    params.put("client_secret", clientSecret);
    params.put("redirect_uri", redirect);
    params.put("grant_type", "authorization_code");

    // set the resource if it necessary for the auth provider dwm08
    if (appIdURI != null) {
        params.put("resource", appIdURI);
    }/*  w w w .j  a v a2s .c  o m*/

    String response = HttpUtils.getInstance().doPost(url, params);
    JsonParser parser = new JsonParser();
    JsonObject obj = parser.parse(response).getAsJsonObject();

    accessToken = obj.getAsJsonPrimitive("access_token").getAsString();
    refreshToken = obj.getAsJsonPrimitive("refresh_token").getAsString();
    expirationTime = System.currentTimeMillis() + (obj.getAsJsonPrimitive("expires_in").getAsInt() * 1000);

    // Try to store in java.util.prefs
    saveRefreshToken();
}

From source file:org.broad.igv.ga4gh.OAuthUtils.java

License:Open Source License

/**
 * Fetch a new access token from a refresh token.
 *
 * @throws IOException// w  ww  .  java 2  s .c  o m
 */
private void refreshAccessToken() throws IOException {

    // properties moved to early init dwm08
    //if (clientId == null) fetchOauthProperties();

    URL url = new URL(tokenURI);

    Map<String, String> params = new HashMap<String, String>();
    params.put("refresh_token", refreshToken);
    params.put("client_id", clientId);
    params.put("client_secret", clientSecret);
    params.put("grant_type", "refresh_token");

    // set the resource if it necessary for the auth provider dwm08
    if (appIdURI != null) {
        params.put("resource", appIdURI);
    }

    String response = HttpUtils.getInstance().doPost(url, params);
    JsonParser parser = new JsonParser();
    JsonObject obj = parser.parse(response).getAsJsonObject();

    JsonPrimitive atprim = obj.getAsJsonPrimitive("access_token");
    if (atprim != null) {
        accessToken = obj.getAsJsonPrimitive("access_token").getAsString();
        expirationTime = System.currentTimeMillis() + (obj.getAsJsonPrimitive("expires_in").getAsInt() * 1000);
        fetchUserProfile();
    } else {
        // Refresh token has failed, reauthorize from scratch
        reauthorize();
    }

}

From source file:org.broad.igv.google.Ga4ghAlignmentReader.java

License:Open Source License

private void loadMetadata() throws IOException {

    String authKey = provider.apiKey;
    String baseURL = provider.baseURL;

    URL url = HttpUtils//from ww w  .  j a v a  2 s. co  m
            .createURL(baseURL + "/readgroupsets/" + readsetId + (authKey == null ? "" : "?key=" + authKey)); // TODO -- field selection?

    Map<String, String> headers = new HashMap<String, String>();
    String token = OAuthUtils.getInstance().getAccessToken();
    if (token != null) {
        headers.put("Authorization", "Bearer " + token);
    }

    String result = HttpUtils.getInstance().getContentsAsString(url, headers);
    JsonParser parser = new JsonParser();
    JsonObject root = parser.parse(result).getAsJsonObject();

    if (root.has("referenceSetId")) {
        String referenceSetId = root.getAsJsonPrimitive("referenceSetId").getAsString();

        List<JsonObject> refererences = Ga4ghAPIHelper.searchReferences(provider, referenceSetId, 1000);

        sequenceNames = new ArrayList();

        for (JsonObject refObject : refererences) {
            sequenceNames.add(refObject.getAsJsonPrimitive("name").getAsString());
        }
    }
}

From source file:org.broad.igv.google.OAuthUtils.java

License:Open Source License

private void fetchTokens(String redirect) throws IOException {

    // properties moved to early init dwm08
    //if (clientId == null) fetchOauthProperties();

    URL url = HttpUtils.createURL(tokenURI);

    Map<String, String> params = new HashMap<String, String>();
    params.put("code", authorizationCode);
    params.put("client_id", clientId);
    params.put("client_secret", clientSecret);
    params.put("redirect_uri", redirect);
    params.put("grant_type", "authorization_code");

    // set the resource if it necessary for the auth provider dwm08
    if (appIdURI != null) {
        params.put("resource", appIdURI);
    }/*from w ww .j av  a2s  .co m*/

    String response = HttpUtils.getInstance().doPost(url, params);
    JsonParser parser = new JsonParser();
    JsonObject obj = parser.parse(response).getAsJsonObject();

    accessToken = obj.getAsJsonPrimitive("access_token").getAsString();
    refreshToken = obj.getAsJsonPrimitive("refresh_token").getAsString();
    expirationTime = System.currentTimeMillis() + (obj.getAsJsonPrimitive("expires_in").getAsInt() * 1000);

    // Try to store in java.util.prefs
    saveRefreshToken();
}

From source file:org.broad.igv.google.OAuthUtils.java

License:Open Source License

/**
 * Fetch a new access token from a refresh token.
 *
 * @throws IOException//from   w ww.java  2s.c o m
 */
private void refreshAccessToken() throws IOException {

    // properties moved to early init dwm08
    //if (clientId == null) fetchOauthProperties();

    URL url = HttpUtils.createURL(tokenURI);

    Map<String, String> params = new HashMap<String, String>();
    params.put("refresh_token", refreshToken);
    params.put("client_id", clientId);
    params.put("client_secret", clientSecret);
    params.put("grant_type", "refresh_token");

    // set the resource if it necessary for the auth provider dwm08
    if (appIdURI != null) {
        params.put("resource", appIdURI);
    }

    String response = HttpUtils.getInstance().doPost(url, params);
    JsonParser parser = new JsonParser();
    JsonObject obj = parser.parse(response).getAsJsonObject();

    JsonPrimitive atprim = obj.getAsJsonPrimitive("access_token");
    if (atprim != null) {
        accessToken = obj.getAsJsonPrimitive("access_token").getAsString();
        expirationTime = System.currentTimeMillis() + (obj.getAsJsonPrimitive("expires_in").getAsInt() * 1000);
        fetchUserProfile();
    } else {
        // Refresh token has failed, reauthorize from scratch
        reauthorize();
    }

}

From source file:org.crsh.web.GistsServlet.java

License:Open Source License

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    ///*from   w w w .j a v  a 2  s  . com*/
    String pathInfo = req.getPathInfo();
    if (pathInfo != null && pathInfo.length() > 0) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "No gist id must be provided");
    } else {
        // Build body
        JsonObject body = new JsonObject();
        body.addProperty("description", "A set of shell JVM commands for CRaSH http://try.crashub.org");
        body.addProperty("public", true);
        JsonObject files = new JsonObject();
        for (Map.Entry<String, String[]> parameter : req.getParameterMap().entrySet()) {
            String script = parameter.getValue()[0];
            JsonObject file = new JsonObject();
            file.addProperty("content", script);
            files.add(parameter.getKey() + ".groovy", file);
        }
        body.add("files", files);

        // Perform request
        Client c = Client.create();
        WebResource r = c.resource("https://api.github.com/gists");
        ClientResponse response = r.accept(MediaType.APPLICATION_JSON_TYPE)
                .type(MediaType.APPLICATION_JSON_TYPE).post(ClientResponse.class, body.toString());
        String entity = response.getEntity(String.class);

        //
        int status = response.getStatus();
        if (status >= 200 && status <= 299) {
            JsonObject object = (JsonObject) new JsonParser().parse(entity);
            String id = object.getAsJsonPrimitive("id").getAsString();
            log.log(Level.INFO, req.getRemoteHost() + " created gist " + id);
            resp.sendRedirect(req.getContextPath() + "/gists/" + id);
        } else {
            log.log(Level.SEVERE,
                    req.getRemoteHost() + " could not create gist status =" + status + " entity = " + entity);
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Could not create gist status =" + status + " entity = " + entity);
        }
    }
}

From source file:org.cvasilak.jboss.mobile.admin.fragments.DataSourceMetricsViewFragment.java

License:Open Source License

public void refresh() {
    progress = ProgressDialog.show(getSherlockActivity(), "", getString(R.string.queryingServer));

    application.getOperationsManager().fetchDataSourceMetrics(this.dsName, this.dsType, new Callback() {
        @Override/*from w w w . java2  s  .  com*/
        public void onSuccess(JsonElement reply) {
            progress.dismiss();

            JsonObject jsonObj = reply.getAsJsonObject();

            Map<String, String> info = new HashMap<String, String>();

            JsonObject jsonPool = jsonObj.getAsJsonObject("step-1").getAsJsonObject("result");
            int availCount = jsonPool.getAsJsonPrimitive("AvailableCount").getAsInt();
            int activeCount = jsonPool.getAsJsonPrimitive("ActiveCount").getAsInt();
            int maxUsedCount = jsonPool.getAsJsonPrimitive("MaxUsedCount").getAsInt();

            float usedPerc = (availCount != 0 ? ((float) activeCount / availCount) * 100 : 0);

            info.put("AvailableCount", String.format("%d", availCount));
            info.put("ActiveCount", String.format("%d (%.0f%%)", activeCount, usedPerc));
            info.put("MaxUsedCount", String.format("%d", maxUsedCount));

            for (Metric metric : poolMetrics) {
                metric.setValue(info.get(metric.getKey()));
            }

            JsonObject jsonJDBC = jsonObj.getAsJsonObject("step-2").getAsJsonObject("result");
            int curSize = jsonJDBC.getAsJsonPrimitive("PreparedStatementCacheCurrentSize").getAsInt();
            int hitCount = jsonJDBC.getAsJsonPrimitive("PreparedStatementCacheHitCount").getAsInt();
            float hitPerc = (curSize != 0 ? ((float) hitCount / curSize) * 100 : 0);

            int misUsed = jsonJDBC.getAsJsonPrimitive("PreparedStatementCacheMissCount").getAsInt();
            float misPerc = (curSize != 0 ? ((float) misUsed / curSize) * 100 : 0);

            info.put("PreparedStatementCacheCurrentSize", String.format("%d", curSize));
            info.put("PreparedStatementCacheHitCount", String.format("%d (%.0f%%)", hitCount, hitPerc));
            info.put("PreparedStatementCacheMissCount", String.format("%d (%.0f%%)", misUsed, misPerc));

            for (Metric metric : prepStatementMetrics) {
                metric.setValue(info.get(metric.getKey()));
            }

            // refresh table
            ((MergeAdapter) getListAdapter()).notifyDataSetChanged();
        }

        @Override
        public void onFailure(Exception e) {
            progress.dismiss();

            AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());

            alertDialog.setTitle(R.string.dialog_error_title).setMessage(e.getMessage())
                    .setPositiveButton(R.string.dialog_button_Bummer, null).setCancelable(false)
                    .setIcon(android.R.drawable.ic_dialog_alert).show();

        }
    });
}

From source file:org.cvasilak.jboss.mobile.admin.fragments.JMSQueueMetricsViewFragment.java

License:Open Source License

public void refresh() {
    progress = ProgressDialog.show(getSherlockActivity(), "", getString(R.string.queryingServer));

    application.getOperationsManager().fetchJMSQueueMetrics(queueName, JMSType.QUEUE, new Callback() {
        @Override//from   w  w w  . j av a2  s .  c  o m
        public void onSuccess(JsonElement reply) {
            progress.dismiss();

            JsonObject jsonObj = reply.getAsJsonObject();

            Map<String, String> info = new HashMap<String, String>();

            int msgCount = jsonObj.getAsJsonPrimitive("message-count").getAsInt();
            int delivCount = jsonObj.getAsJsonPrimitive("delivering-count").getAsInt();
            float delivPerc = (msgCount != 0 ? ((float) delivCount / msgCount) * 100 : 0);
            int msgAdded = jsonObj.getAsJsonPrimitive("messages-added").getAsInt();

            info.put("message-count", String.format("%d", msgCount));
            info.put("delivering-count", String.format("%d (%.0f%%)", delivCount, delivPerc));
            for (Metric metric : inFlightMetrics) {
                metric.setValue(info.get(metric.getKey()));
            }

            int schCount = jsonObj.getAsJsonPrimitive("scheduled-count").getAsInt();
            info.put("messages-added", String.format("%d", msgAdded));
            info.put("scheduled-count", String.format("%d", schCount));

            for (Metric metric : msgProcessedMetrics) {
                metric.setValue(info.get(metric.getKey()));
            }

            int consCount = jsonObj.getAsJsonPrimitive("consumer-count").getAsInt();
            info.put("consumer-count", String.format("%d", consCount));

            for (Metric metric : consumerMetrics) {
                metric.setValue(info.get(metric.getKey()));
            }

            // refresh table
            ((MergeAdapter) getListAdapter()).notifyDataSetChanged();
        }

        @Override
        public void onFailure(Exception e) {
            progress.dismiss();

            AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());

            alertDialog.setTitle(R.string.dialog_error_title).setMessage(e.getMessage())
                    .setPositiveButton(R.string.dialog_button_Bummer, null).setCancelable(false)
                    .setIcon(android.R.drawable.ic_dialog_alert).show();

        }
    });
}

From source file:org.cvasilak.jboss.mobile.admin.fragments.JMSTopicMetricsViewFragment.java

License:Open Source License

public void refresh() {
    progress = ProgressDialog.show(getSherlockActivity(), "", getString(R.string.queryingServer));

    application.getOperationsManager().fetchJMSQueueMetrics(topicName, JMSType.TOPIC, new Callback() {
        @Override/*from   ww w. ja va2  s  . c o m*/
        public void onSuccess(JsonElement reply) {
            progress.dismiss();

            JsonObject jsonObj = reply.getAsJsonObject();

            Map<String, String> info = new HashMap<String, String>();

            // common metrics
            int msgCount = jsonObj.getAsJsonPrimitive("message-count").getAsInt();
            int delivCount = jsonObj.getAsJsonPrimitive("delivering-count").getAsInt();
            float delivPerc = (msgCount != 0 ? ((float) delivCount / msgCount) * 100 : 0);
            int msgAdded = jsonObj.getAsJsonPrimitive("messages-added").getAsInt();

            info.put("message-count", String.format("%d", msgCount));
            info.put("delivering-count", String.format("%d (%.0f%%)", delivCount, delivPerc));
            info.put("messages-added", String.format("%d", msgAdded));

            for (Metric metric : inFlightMetrics) {
                metric.setValue(info.get(metric.getKey()));
            }

            int durCount = jsonObj.getAsJsonPrimitive("durable-message-count").getAsInt();
            float durPerc = (msgAdded != 0 ? ((float) durCount / msgAdded) * 100 : 0);

            int nonDurCount = jsonObj.getAsJsonPrimitive("non-durable-message-count").getAsInt();
            float nonDurPerc = (msgAdded != 0 ? ((float) nonDurCount / msgAdded) * 100 : 0);

            int subCount = jsonObj.getAsJsonPrimitive("subscription-count").getAsInt();
            int durSubCount = jsonObj.getAsJsonPrimitive("durable-subscription-count").getAsInt();
            int nonDurSubCount = jsonObj.getAsJsonPrimitive("non-durable-subscription-count").getAsInt();

            info.put("durable-message-count", String.format("%d (%.0f%%)", durCount, durPerc));
            info.put("non-durable-message-count", String.format("%d (%.0f%%)", nonDurCount, nonDurPerc));
            info.put("subscription-count", String.format("%d", subCount));
            info.put("durable-subscription-count", String.format("%d", durSubCount));
            info.put("non-durable-subscription-count", String.format("%d", nonDurSubCount));

            for (Metric metric : msgProcessedMetrics) {
                metric.setValue(info.get(metric.getKey()));
            }

            for (Metric metric : subscriptionMetrics) {
                metric.setValue(info.get(metric.getKey()));
            }

            // refresh table
            ((MergeAdapter) getListAdapter()).notifyDataSetChanged();
        }

        @Override
        public void onFailure(Exception e) {
            progress.dismiss();

            AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());

            alertDialog.setTitle(R.string.dialog_error_title).setMessage(e.getMessage())
                    .setPositiveButton(R.string.dialog_button_Bummer, null).setCancelable(false)
                    .setIcon(android.R.drawable.ic_dialog_alert).show();

        }
    });
}