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.ibasco.agql.protocols.valve.steam.webapi.SteamWebApiInterface.java

License:Open Source License

protected JsonObject getSteamResult(JsonObject root) {
    if (root.has("result")) {
        return root.getAsJsonObject("result");
    }//w  w w.  j  a  va2 s  .c o  m
    return null;
}

From source file:com.ibm.devops.dra.AbstractDevOpsAction.java

License:Open Source License

public static String getOrgId(String token, String orgName, String environment, Boolean debug_mode) {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    String organizations_url = chooseOrganizationsUrl(environment);
    if (debug_mode) {
        LOGGER.info("GET ORG_GUID URL:" + organizations_url + orgName);
    }//from www  .  j  a va 2  s .  c o m

    try {
        HttpGet httpGet = new HttpGet(
                organizations_url + URLEncoder.encode(orgName, "UTF-8").replaceAll("\\+", "%20"));

        httpGet = addProxyInformation(httpGet);

        httpGet.setHeader("Authorization", token);
        CloseableHttpResponse response = null;

        response = httpClient.execute(httpGet);
        String resStr = EntityUtils.toString(response.getEntity());

        if (debug_mode) {
            LOGGER.info("RESPONSE FROM ORGANIZATIONS API:" + response.getStatusLine().toString());
        }
        if (response.getStatusLine().toString().contains("200")) {
            // get 200 response
            JsonParser parser = new JsonParser();
            JsonElement element = parser.parse(resStr);
            JsonObject obj = element.getAsJsonObject();
            JsonArray resources = obj.getAsJsonArray("resources");

            if (resources.size() > 0) {
                JsonObject resource = resources.get(0).getAsJsonObject();
                JsonObject metadata = resource.getAsJsonObject("metadata");
                if (debug_mode) {
                    LOGGER.info("ORG_ID:" + String.valueOf(metadata.get("guid")).replaceAll("\"", ""));
                }
                return String.valueOf(metadata.get("guid")).replaceAll("\"", "");
            } else {
                if (debug_mode) {
                    LOGGER.info("RETURNED NO ORGANIZATIONS.");
                }
                return null;
            }

        } else {
            if (debug_mode) {
                LOGGER.info("RETURNED STATUS CODE OTHER THAN 200. RESPONSE: "
                        + response.getStatusLine().toString());
            }
            return null;
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}

From source file:com.ibm.devops.dra.AbstractDevOpsAction.java

License:Open Source License

public static String getSpaceId(String token, String spaceName, String environment, Boolean debug_mode) {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    String spaces_url = chooseSpacesUrl(environment);
    if (debug_mode) {
        LOGGER.info("GET SPACE_GUID URL:" + spaces_url + spaceName);
    }/*from w w w  .j av  a  2s .  com*/

    try {
        HttpGet httpGet = new HttpGet(
                spaces_url + URLEncoder.encode(spaceName, "UTF-8").replaceAll("\\+", "%20"));

        httpGet = addProxyInformation(httpGet);

        httpGet.setHeader("Authorization", token);
        CloseableHttpResponse response = null;

        response = httpClient.execute(httpGet);
        String resStr = EntityUtils.toString(response.getEntity());

        if (debug_mode) {
            LOGGER.info("RESPONSE FROM SPACES API:" + response.getStatusLine().toString());
        }
        if (response.getStatusLine().toString().contains("200")) {
            // get 200 response
            JsonParser parser = new JsonParser();
            JsonElement element = parser.parse(resStr);
            JsonObject obj = element.getAsJsonObject();
            JsonArray resources = obj.getAsJsonArray("resources");

            if (resources.size() > 0) {
                JsonObject resource = resources.get(0).getAsJsonObject();
                JsonObject metadata = resource.getAsJsonObject("metadata");
                if (debug_mode) {
                    LOGGER.info("SPACE_ID:" + String.valueOf(metadata.get("guid")).replaceAll("\"", ""));
                }
                return String.valueOf(metadata.get("guid")).replaceAll("\"", "");
            } else {
                if (debug_mode) {
                    LOGGER.info("RETURNED NO SPACES.");
                }
                return null;
            }

        } else {
            if (debug_mode) {
                LOGGER.info("RETURNED STATUS CODE OTHER THAN 200. RESPONSE: "
                        + response.getStatusLine().toString());
            }
            return null;
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}

From source file:com.ibm.devops.dra.AbstractDevOpsAction.java

License:Open Source License

public static String getAppId(String token, String appName, String orgName, String spaceName,
        String environment, Boolean debug_mode) {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    String apps_url = chooseAppsUrl(environment);
    if (debug_mode) {
        LOGGER.info("GET APPS_GUID URL:" + apps_url + appName + ORG + orgName + SPACE + spaceName);
    }//from   w  ww . ja va 2 s. co  m

    try {
        HttpGet httpGet = new HttpGet(apps_url + URLEncoder.encode(appName, "UTF-8").replaceAll("\\+", "%20")
                + ORG + URLEncoder.encode(orgName, "UTF-8").replaceAll("\\+", "%20") + SPACE
                + URLEncoder.encode(spaceName, "UTF-8").replaceAll("\\+", "%20"));

        httpGet = addProxyInformation(httpGet);

        httpGet.setHeader("Authorization", token);
        CloseableHttpResponse response = null;

        response = httpClient.execute(httpGet);
        String resStr = EntityUtils.toString(response.getEntity());

        if (debug_mode) {
            LOGGER.info("RESPONSE FROM APPS API:" + response.getStatusLine().toString());
        }
        if (response.getStatusLine().toString().contains("200")) {
            // get 200 response
            JsonParser parser = new JsonParser();
            JsonElement element = parser.parse(resStr);
            JsonObject obj = element.getAsJsonObject();
            JsonArray resources = obj.getAsJsonArray("resources");

            if (resources.size() > 0) {
                JsonObject resource = resources.get(0).getAsJsonObject();
                JsonObject metadata = resource.getAsJsonObject("metadata");
                if (debug_mode) {
                    LOGGER.info("APP_ID:" + String.valueOf(metadata.get("guid")).replaceAll("\"", ""));
                }
                return String.valueOf(metadata.get("guid")).replaceAll("\"", "");
            } else {
                if (debug_mode) {
                    LOGGER.info("RETURNED NO APPS.");
                }
                return null;
            }

        } else {
            if (debug_mode) {
                LOGGER.info("RETURNED STATUS CODE OTHER THAN 200. RESPONSE: "
                        + response.getStatusLine().toString());
            }
            return null;
        }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:com.ibm.g11n.pipeline.client.ServiceAccount.java

License:Open Source License

/**
 * Returns an instance of ServiceAccount for a JsonArray in the VCAP_SERVICES environment.
 * <p>//w  w w .  j a v  a2 s.  com
 * This method is called from {@link #getInstanceByVcapServices(String, String)}.
 * 
 * @param jsonArray
 *          The candidate JSON array which may include valid credentials.
 * @param serviceInstanceName
 *          The name of IBM Globalization Pipeline service instance, or null
 *          designating the first available service instance.
 * @return  An instance of ServiceAccount. This method returns null if no matching service
 *          instance name was found (when serviceInstanceName is null), or no valid
 *          credential data was found. 
 */
private static ServiceAccount parseToServiceAccount(JsonArray jsonArray, String serviceInstanceName) {
    ServiceAccount account = null;
    for (int i = 0; i < jsonArray.size(); i++) {
        JsonObject gpObj = jsonArray.get(i).getAsJsonObject();
        if (serviceInstanceName != null) {
            // When service instance name is specified,
            // this method returns only a matching entry
            JsonPrimitive name = gpObj.getAsJsonPrimitive("name");
            if (name == null || !serviceInstanceName.equals(name.getAsString())) {
                continue;
            }
        }
        JsonObject credentials = gpObj.getAsJsonObject("credentials");
        if (credentials == null) {
            continue;
        }
        JsonPrimitive jsonUrl = credentials.getAsJsonPrimitive("url");
        JsonPrimitive jsonInstanceId = credentials.getAsJsonPrimitive("instanceId");
        JsonPrimitive jsonUserId = credentials.getAsJsonPrimitive("userId");
        JsonPrimitive jsonPassword = credentials.getAsJsonPrimitive("password");

        if (jsonUrl != null && jsonInstanceId != null && jsonUserId != null & jsonPassword != null) {
            account = getInstance(jsonUrl.getAsString(), jsonInstanceId.getAsString(), jsonUserId.getAsString(),
                    jsonPassword.getAsString());
            logger.config("A ServiceAccount is created from VCAP_SERVICES: url=" + jsonUrl + ", instanceId="
                    + jsonInstanceId + ", userId=" + jsonUserId + ", password=***");
            break;
        }
    }

    return account;
}

From source file:com.ibm.gaas.ServiceAccount.java

License:Open Source License

/**
 * Returns an instance of ServiceAccount from the VCAP_SERVICES environment
 * variable. When <code>serviceInstanceName</code> is null, this method returns
 * a ServiceAccount for the first valid IBM Globlization service instance.
 * If <code>serviceInstanceName</code> is not null, this method look up a
 * matching service entry, and returns a ServiceAccount for the matching entry.
 * If <code>serviceInstanceName</code> is not null and there is no match,
 * this method returns null.// w  w  w .j  a  va2 s  .  c o m
 * 
 * @param serviceInstanceName
 *          The name of the IBM Globalization service instance, or null
 *          designating the first available service instance.
 * @return  An instance of ServiceAccount for the specified service instance
 *          name, or null.
 */
private static ServiceAccount getInstanceByVcapServices(String serviceInstanceName) {
    Map<String, String> env = System.getenv();
    String vcapServices = env.get("VCAP_SERVICES");
    if (vcapServices == null) {
        return null;
    }

    ServiceAccount account = null;
    try {
        JsonObject obj = new JsonParser().parse(vcapServices).getAsJsonObject();
        JsonArray gaasArray = obj.getAsJsonArray(GAAS_SERVICE_NAME);
        if (gaasArray != null) {
            for (int i = 0; i < gaasArray.size(); i++) {
                JsonObject gaasEntry = gaasArray.get(i).getAsJsonObject();
                if (serviceInstanceName != null) {
                    // When service instance name is specified,
                    // this method returns only a matching entry
                    JsonPrimitive name = gaasEntry.getAsJsonPrimitive("name");
                    if (name == null || !serviceInstanceName.equals(name.getAsString())) {
                        continue;
                    }
                }
                JsonObject credentials = gaasEntry.getAsJsonObject("credentials");
                if (credentials == null) {
                    continue;
                }
                JsonPrimitive jsonUri = credentials.getAsJsonPrimitive("uri");
                JsonPrimitive jsonApiKey = credentials.getAsJsonPrimitive("api_key");
                if (jsonUri != null && jsonApiKey != null) {
                    logger.info(
                            "A ServiceAccount is created from VCAP_SERVICES: uri=" + jsonUri + ", api_key=***");
                    account = getInstance(jsonUri.getAsString(), jsonApiKey.getAsString());
                    break;
                }
            }
        }
    } catch (JsonParseException e) {
        // Fall through - will return null
    }

    return account;
}

From source file:com.ibm.iotf.devicemgmt.device.ManagedDevice.java

License:Open Source License

private void publish(JsonObject jsonPubMsg) throws MqttException, UnsupportedEncodingException {
    final String METHOD = "publish1";
    String topic = jsonPubMsg.get("topic").getAsString();
    int qos = jsonPubMsg.get("qos").getAsInt();
    JsonObject payload = jsonPubMsg.getAsJsonObject("payload");
    LoggerUtility.log(Level.FINE, CLASS_NAME, METHOD,
            ": Topic(" + topic + ") qos=" + qos + " payload (" + payload.toString() + ")");
    MqttMessage message = new MqttMessage();
    message.setPayload(payload.toString().getBytes("UTF-8"));
    message.setQos(qos);//w ww  .  j a  v a2s. c om
    publish(topic, message);
}

From source file:com.ibm.mil.cafejava.CafeJava.java

License:Open Source License

private static JsonElement parseNestedJson(WLResponse wlResponse, String... memberNames) {
    String json = wlResponse.getResponseJSON().toString();
    JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject();

    // For each member name, fetch the object it maps to until you reach the final member name.
    // Once the final member name is reached, return its corresponding value.
    for (int i = 0, size = memberNames.length; i < size; i++) {
        String member = memberNames[i];

        if (i == size - 1) {
            // last member name reached; return its value
            return jsonObject.get(member);
        } else {//from w  ww  . j a  va 2s .  co m
            // more member names remain, therefore current member must map to an object
            jsonObject = jsonObject.getAsJsonObject(member);
        }
    }

    // no nesting required; return top-level object
    return jsonObject;
}

From source file:com.ibm.streamsx.edgevideo.device.edgent.JsonFaceEvent.java

License:Open Source License

/** Get the face from a FaceEvent */
public static Mat getFace(JsonObject faceEvent) {
    return JsonMat.fromJsonObject(faceEvent.getAsJsonObject("face"));
}

From source file:com.ibm.streamsx.topology.internal.context.AnalyticsServiceStreamsContext.java

License:Open Source License

private BigInteger submitJobToService(File bundle, JsonObject submission) throws IOException {
    JsonObject deploy = deploy(submission);

    final JsonObject service = getVCAPService(deploy);
    final String serviceName = jstring(service, "name");

    final JsonObject credentials = service.getAsJsonObject("credentials");

    final CloseableHttpClient httpClient = HttpClients.createDefault();
    try {/*from  ww w. j ava 2s . co  m*/
        Topology.STREAMS_LOGGER
                .info("Streaming Analytics service (" + serviceName + "): Checking status :" + serviceName);

        RestUtils.checkInstanceStatus(httpClient, service);

        Topology.STREAMS_LOGGER.info("Streaming Analytics service (" + serviceName + "): Submitting bundle : "
                + bundle.getName() + " to " + serviceName);

        JsonObject jcojson = DeployKeys.copyJobConfigOverlays(deploy);

        Topology.STREAMS_LOGGER.info(
                "Streaming Analytics service (" + serviceName + "): submit job request:" + jcojson.toString());

        JsonObject response = RestUtils.postJob(httpClient, service, bundle, jcojson);

        final JsonObject submissionResult = GsonUtilities.objectCreate(submission,
                RemoteContext.SUBMISSION_RESULTS);
        GsonUtilities.addAll(submissionResult, response);

        String jobId = jstring(response, "jobId");

        if (jobId == null)
            return BigInteger.valueOf(-1);

        return new BigInteger(jobId);
    } finally {
        httpClient.close();
    }
}