Example usage for com.google.gson JsonObject getAsJsonArray

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

Introduction

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

Prototype

public JsonArray getAsJsonArray(String memberName) 

Source Link

Document

Convenience method to get the specified member as a JsonArray.

Usage

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

License:Open Source License

/**
 * Get a list of toolchains using given token and organization name.
 * @param token/*www .j  a v a  2 s  .c  o  m*/
 * @param orgName
 * @return
 */
public static ListBoxModel getToolchainList(String token, String orgName, String environment,
        Boolean debug_mode) {

    LOGGER.setLevel(Level.INFO);

    if (debug_mode) {
        LOGGER.info("#######################");
        LOGGER.info("TOKEN:" + token);
        LOGGER.info("ORG:" + orgName);
        LOGGER.info("ENVIRONMENT:" + environment);
    }

    String orgId = getOrgId(token, orgName, environment, debug_mode);
    ListBoxModel emptybox = new ListBoxModel();
    emptybox.add("", "empty");

    if (orgId == null) {
        return emptybox;
    }

    CloseableHttpClient httpClient = HttpClients.createDefault();
    String toolchains_url = chooseToolchainsUrl(environment);
    if (debug_mode) {
        LOGGER.info("GET TOOLCHAIN LIST URL:" + toolchains_url + orgId);
    }

    HttpGet httpGet = new HttpGet(toolchains_url + orgId);

    httpGet = addProxyInformation(httpGet);

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

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

        if (debug_mode) {
            LOGGER.info("RESPONSE FROM TOOLCHAINS 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 items = obj.getAsJsonArray("items");
            ListBoxModel toolchainList = new ListBoxModel();

            for (int i = 0; i < items.size(); i++) {
                JsonObject toolchainObj = items.get(i).getAsJsonObject();
                String toolchainName = String.valueOf(toolchainObj.get("name")).replaceAll("\"", "");
                String toolchainID = String.valueOf(toolchainObj.get("toolchain_guid")).replaceAll("\"", "");
                toolchainList.add(toolchainName, toolchainID);
            }
            if (debug_mode) {
                LOGGER.info("TOOLCHAIN LIST:" + toolchainList);
                LOGGER.info("#######################");
            }
            if (toolchainList.isEmpty()) {
                if (debug_mode) {
                    LOGGER.info("RETURNED NO TOOLCHAINS.");
                }
                return emptybox;
            }
            return toolchainList;
        } else {
            LOGGER.info(
                    "RETURNED STATUS CODE OTHER THAN 200. RESPONSE: " + response.getStatusLine().toString());
            return emptybox;
        }

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

    return emptybox;
}

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);
    }//ww w  . ja  v a  2 s .co  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);
    }/* www  . ja v  a  2s. c o m*/

    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);
    }/*  ww  w.  j  a  va  2 s .  c  o  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.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  av  a2s  . c  om
 * 
 * @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.mil.readyapps.summit.fragments.DashboardFragment.java

License:Open Source License

private static List<ItemMetaData> getPropertyData(JsonObject object, String propertyName) {
    JsonArray propertyArray = object.getAsJsonArray(propertyName);
    Gson gson = new Gson();
    Type type = new TypeToken<List<ItemMetaData>>() {
    }.getType();/* www  .  j  av a  2s.c  om*/
    return gson.fromJson(propertyArray, type);
}

From source file:com.ibm.streamsx.topology.generator.spl.SPLGenerator.java

License:Open Source License

private List<List<JsonObject>> findCompositeOpsOfAType(JsonObject graph, String startKind, String endKind,
        String opStartParam) {//from w ww  .  j a v a  2  s  . co m

    for (JsonElement jePotentialStart : graph.getAsJsonArray("operators")) {
        JsonObject potentialStart = jePotentialStart.getAsJsonObject();

        // We've found a potential start to a composite. See if the composite doesn't contain another composite.   
        if (kind(potentialStart).equals(startKind)
                || isPhysicalStartOperatorOfAType(potentialStart, opStartParam)) {
            List<List<JsonObject>> startsEndsAndOperators = findCompositeOpsOfATypeGivenPotentialStart(graph,
                    startKind, endKind, opStartParam, potentialStart);
            if (startsEndsAndOperators != null) {
                return startsEndsAndOperators;
            }
        }

    }
    return null;
}

From source file:com.ibm.streamsx.topology.internal.gson.GsonUtilities.java

License:Open Source License

/**
 * Like objectCreate but the last element is created as an array if
 * it doesn't already exist.//from w  w  w .  j av a2  s.  c  o  m
 */
public static JsonArray arrayCreate(JsonObject object, String... property) {

    assert property.length > 0;

    if (property.length > 1) {
        String[] objprops = new String[property.length - 1];
        System.arraycopy(property, 0, objprops, 0, objprops.length);
        object = objectCreate(object, objprops);
    }

    String arrayProperty = property[property.length - 1];

    if (object.has(arrayProperty))
        return object.getAsJsonArray(arrayProperty);

    JsonArray array = new JsonArray();
    object.add(arrayProperty, array);
    return array;
}

From source file:com.ibm.watson.developer_cloud.util.BluemixUtils.java

License:Open Source License

/**
 * Returns the apiKey from the VCAP_SERVICES or null if doesn't exists. If plan is specified, then
 * only credentials for the given plan will be returned.
 * //from w w w.j a v  a  2 s . c o m
 * @param serviceName the service name
 * @param plan the service plan: standard, free or experimental
 * @return the API key
 */
public static String getAPIKey(String serviceName, String plan) {
    if (serviceName == null || serviceName.isEmpty())
        return null;

    final JsonObject services = getVCAPServices();
    if (services == null)
        return null;

    for (final Entry<String, JsonElement> entry : services.entrySet()) {
        final String key = entry.getKey();
        if (key.startsWith(serviceName)) {
            final JsonArray servInstances = services.getAsJsonArray(key);
            for (final JsonElement instance : servInstances) {
                final JsonObject service = instance.getAsJsonObject();
                final String instancePlan = service.get(PLAN).getAsString();
                if (plan == null || plan.equalsIgnoreCase(instancePlan)) {
                    final JsonObject credentials = instance.getAsJsonObject().getAsJsonObject(CREDENTIALS);
                    if (serviceName.equalsIgnoreCase(ALCHEMY_API)) {
                        return credentials.get(APIKEY).getAsString();
                    } else {
                        final String username = credentials.get(USERNAME).getAsString();
                        final String password = credentials.get(PASSWORD).getAsString();
                        return Credentials.basic(username, password);
                    }
                }
            }
        }
    }
    return null;
}

From source file:com.ibm.watson.developer_cloud.util.CredentialUtils.java

License:Open Source License

/**
 * A helper method to retrieve the appropriate 'credentials' JSON property value from the VCAP_SERVICES.
 *
 * @param vcapServices JSON object representing the VCAP_SERVICES
 * @param serviceName the name of the service whose credentials are sought
 * @param plan the name of the plan for which the credentials are sought, e.g. 'standard', 'beta' etc, may be null
 * @return the first set of credentials that match the search criteria, service name and plan. May return null
 *///  ww w. j a  va2s .com
private static JsonObject getCredentialsObject(JsonObject vcapServices, String serviceName, String plan) {
    for (final Entry<String, JsonElement> entry : vcapServices.entrySet()) {
        final String key = entry.getKey();
        if (key.startsWith(serviceName)) {
            final JsonArray servInstances = vcapServices.getAsJsonArray(key);
            for (final JsonElement instance : servInstances) {
                final JsonObject service = instance.getAsJsonObject();
                final String instancePlan = service.get(PLAN).getAsString();
                if ((plan == null) || plan.equalsIgnoreCase(instancePlan)) {
                    return instance.getAsJsonObject().getAsJsonObject(CREDENTIALS);
                }
            }
        }
    }
    return null;
}