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.optimizely.ab.config.parser.GsonHelpers.java

License:Apache License

static FeatureFlag parseFeatureFlag(JsonObject featureFlagJson, JsonDeserializationContext context) {
    String id = featureFlagJson.get("id").getAsString();
    String key = featureFlagJson.get("key").getAsString();
    String layerId = featureFlagJson.get("rolloutId").getAsString();

    JsonArray experimentIdsJson = featureFlagJson.getAsJsonArray("experimentIds");
    List<String> experimentIds = new ArrayList<String>();
    for (JsonElement experimentIdObj : experimentIdsJson) {
        experimentIds.add(experimentIdObj.getAsString());
    }/*  ww w . j av  a 2s  . com*/

    List<FeatureVariable> FeatureVariables = new ArrayList<>();
    try {
        Type FeatureVariableType = new TypeToken<List<FeatureVariable>>() {
        }.getType();
        FeatureVariables = context.deserialize(featureFlagJson.getAsJsonArray("variables"),
                FeatureVariableType);
    } catch (JsonParseException exception) {
        logger.warn("Unable to parse variables for feature \"" + key + "\". JsonParseException: " + exception);
    }

    return new FeatureFlag(id, key, layerId, experimentIds, FeatureVariables);
}

From source file:com.orchestra.portale.profiler.FbProfiler.java

public Map<String, List<String[]>> getFBCategories() {
    if (access_token == null) {
        return null;
    }// w w w  .ja v a  2s  . c o  m

    try {

        HttpURLConnection connection = openConnection("/mom", "GET");

        Map<String, String> params = new HashMap<String, String>();
        params.put("access_token", access_token);
        connection = addParameter(connection, params);

        String json_response = streamToString(connection.getInputStream());
        JsonParser parser = new JsonParser();
        JsonElement element = parser.parse(json_response);
        JsonObject j_object = (JsonObject) element;
        JsonObject cat_list = (JsonObject) j_object.get("msg");

        Map<String, List<String[]>> cat_ret = new HashMap<String, List<String[]>>();
        JsonArray likes = cat_list.getAsJsonArray("likes");
        JsonArray photos = cat_list.getAsJsonArray("photos");
        JsonArray places = cat_list.getAsJsonArray("places");

        List<String[]> likes_array = new ArrayList<String[]>();
        for (JsonElement like : likes) {
            String[] l = { like.getAsJsonObject().get("name").getAsString(),
                    like.getAsJsonObject().get("weight").getAsString() };
            likes_array.add(l);
        }
        cat_ret.put("likes", likes_array);

        List<String[]> photos_array = new ArrayList<String[]>();
        for (JsonElement photo : photos) {
            String[] p = { photo.getAsJsonObject().get("name").getAsString(),
                    photo.getAsJsonObject().get("weight").getAsString() };
            photos_array.add(p);
        }
        cat_ret.put("photos", photos_array);

        List<String[]> places_array = new ArrayList<String[]>();
        for (JsonElement place : places) {
            String[] pl = { place.getAsJsonObject().get("name").getAsString(),
                    place.getAsJsonObject().get("weight").getAsString() };
            places_array.add(pl);
        }
        cat_ret.put("places", places_array);

        return cat_ret;

    } catch (MalformedURLException ex) {
        //ex.printStackTrace();
        return null;
    } catch (IOException ioex) {
        //ioex.printStackTrace();
        return null;
    }

}

From source file:com.perl5.lang.perl.util.PerlDebugUtil.java

License:Apache License

public static void requestAndComputeChildren(@NotNull final XCompositeNode node,
        final PerlStackFrame perlStackFrame, final int[] offset, final int size, String key) {
    PerlDebugThread thread = perlStackFrame.getPerlExecutionStack().getSuspendContext().getDebugThread();

    final int frameSize = XCompositeNode.MAX_CHILDREN_TO_SHOW;
    thread.sendCommandAndGetResponse("getchildren", new PerlValueRequestDescriptor(offset[0], frameSize, key),
            new PerlDebuggingTransactionHandler() {
                @Override//from  ww w.  java  2 s  .  c  om
                public void run(JsonObject jsonObject, JsonDeserializationContext jsonDeserializationContext) {
                    PerlValueDescriptor[] descriptors = jsonDeserializationContext
                            .deserialize(jsonObject.getAsJsonArray("data"), PerlValueDescriptor[].class);

                    XValueChildrenList list = new XValueChildrenList();
                    for (PerlValueDescriptor descriptor : descriptors) {
                        list.add(new PerlXNamedValue(descriptor, perlStackFrame));

                        offset[0]++;
                    }
                    boolean isLast = offset[0] >= size;
                    node.addChildren(list, isLast);
                    if (!isLast) {
                        node.tooManyChildren(size - offset[0]);
                    }
                }
            });
}

From source file:com.philips.hsdp.feed.ObservationFeed.java

License:Open Source License

@Override
public boolean handleResponse(JsonObject inJsonComplete) {
    //Log.i("HS", "--- Received Observation Json Data");
    mObservations.clear();//from  ww w. java 2  s. c o m

    JsonParser fhirJsonParser = new JsonParser();
    if (inJsonComplete.has("entry")) {
        JsonArray jsonList = inJsonComplete.getAsJsonArray(("entry"));

        for (int i = 0; i < jsonList.size(); i++) {
            // Data comes with double quotes "SomeTitle", so removing double quotes
            String title = jsonList.get(i).getAsJsonObject().get("title").toString().replaceAll("^\"|\"$", "");
            String id = jsonList.get(i).getAsJsonObject().get("id").toString().replaceAll("^\"|\"$", "");
            ;
            String dateUpdated = jsonList.get(i).getAsJsonObject().get("updated").toString()
                    .replaceAll("^\"|\"$", "");

            JsonObject observationJson = jsonList.get(i).getAsJsonObject().getAsJsonObject("content");

            HSDPObservation phpsObservation = (HSDPObservation) getPHPSObjectFromJson(PHPS_OBJECT.Observation,
                    fhirJsonParser, observationJson);
            if (phpsObservation == null)
                return false;

            phpsObservation.setExtraInfo(id, title, dateUpdated);
            mObservations.add(phpsObservation);
        }
    } else {
        HSDPObservation phpsObservation = (HSDPObservation) getPHPSObjectFromJson(PHPS_OBJECT.Observation,
                fhirJsonParser, inJsonComplete);
        if (phpsObservation == null)
            return false;
        mObservations.add(phpsObservation);
    }

    return true;
}

From source file:com.philips.hsdp.feed.OrganizationFeed.java

License:Open Source License

@Override
public boolean handleResponse(JsonObject inJsonComplete) {
    //Log.i("HS", "--- Received Organization Json Data");
    mOrganizations.clear();//  w  w w  . j a  v  a2  s  .c  o  m

    JsonParser fhirJsonParser = new JsonParser();
    if (inJsonComplete.has("entry")) {
        JsonArray jsonListPatients = inJsonComplete.getAsJsonArray(("entry"));

        for (int i = 0; i < jsonListPatients.size(); i++) {
            String title = jsonListPatients.get(i).getAsJsonObject().get("title").toString()
                    .replaceAll("^\"|\"$", "");
            String id = jsonListPatients.get(i).getAsJsonObject().get("id").toString().replaceAll("^\"|\"$",
                    "");
            String dateUpdated = jsonListPatients.get(i).getAsJsonObject().get("updated").toString()
                    .replaceAll("^\"|\"$", "");
            JsonObject organizationJson = jsonListPatients.get(i).getAsJsonObject().getAsJsonObject("content");

            HSDPOrganization phpsOrganization = (HSDPOrganization) getPHPSObjectFromJson(
                    PHPS_OBJECT.Organization, fhirJsonParser, organizationJson);
            if (phpsOrganization == null)
                return false;

            phpsOrganization.setExtraInfo(id, title, dateUpdated);
            mOrganizations.add(phpsOrganization);
        }
    } else {
        HSDPOrganization phpsOrganization = (HSDPOrganization) getPHPSObjectFromJson(PHPS_OBJECT.Organization,
                fhirJsonParser, inJsonComplete);
        if (phpsOrganization == null)
            return false;
        mOrganizations.add(phpsOrganization);
    }

    return true;
}

From source file:com.philips.hsdp.feed.PatientFeed.java

License:Open Source License

@Override
public boolean handleResponse(JsonObject inJsonComplete) {
    //Log.i("HS", "--- Received Patient Json Data");
    mPatients.clear();// ww  w. j  av a2 s.com

    JsonParser fhirJsonParser = new JsonParser();
    if (inJsonComplete.has("entry")) {
        JsonArray jsonListPatients = inJsonComplete.getAsJsonArray(("entry"));

        for (int i = 0; i < jsonListPatients.size(); i++) {
            String title = jsonListPatients.get(i).getAsJsonObject().get("title").toString()
                    .replaceAll("^\"|\"$", "");
            String id = jsonListPatients.get(i).getAsJsonObject().get("id").toString().replaceAll("^\"|\"$",
                    "");
            String dateUpdated = jsonListPatients.get(i).getAsJsonObject().get("updated").toString()
                    .replaceAll("^\"|\"$", "");
            JsonObject patientJson = jsonListPatients.get(i).getAsJsonObject().getAsJsonObject("content");

            HSDPPatient phpsPatient = (HSDPPatient) getPHPSObjectFromJson(PHPS_OBJECT.Patient, fhirJsonParser,
                    patientJson);
            if (phpsPatient == null)
                return false;

            phpsPatient.setExtraInfo(id, title, dateUpdated);
            mPatients.add(phpsPatient);
        }
    } else {
        HSDPPatient phpsPatient = (HSDPPatient) getPHPSObjectFromJson(PHPS_OBJECT.Patient, fhirJsonParser,
                inJsonComplete);
        if (phpsPatient == null)
            return false;
        mPatients.add(phpsPatient);
    }

    return true;
}

From source file:com.photon.phresco.framework.impl.CIManagerImpl.java

License:Apache License

private void setBuildStatus(CIBuild ciBuild, CIJob job) throws PhrescoException {
    S_LOGGER.debug("Entering Method CIManagerImpl.setBuildStatus(CIBuild ciBuild)");
    S_LOGGER.debug("setBuildStatus()  url = " + ciBuild.getUrl());
    String buildUrl = ciBuild.getUrl();
    String jenkinsUrl = job.getJenkinsUrl() + ":" + job.getJenkinsPort();
    buildUrl = buildUrl.replaceAll("localhost:" + job.getJenkinsPort(), jenkinsUrl); // display the jenkins running url in ci list
    String response = getJsonResponse(buildUrl + "api/json");
    JsonParser parser = new JsonParser();
    JsonElement jsonElement = parser.parse(response);
    JsonObject jsonObject = jsonElement.getAsJsonObject();

    JsonElement resultJson = jsonObject.get(FrameworkConstants.CI_JOB_BUILD_RESULT);
    JsonElement idJson = jsonObject.get(FrameworkConstants.CI_JOB_BUILD_ID);
    JsonElement timeJson = jsonObject.get(FrameworkConstants.CI_JOB_BUILD_TIME_STAMP);
    JsonArray asJsonArray = jsonObject.getAsJsonArray(FrameworkConstants.CI_JOB_BUILD_ARTIFACTS);

    if (jsonObject.get(FrameworkConstants.CI_JOB_BUILD_RESULT).toString().equals("null")) { // when build is result is not known
        ciBuild.setStatus("INPROGRESS");
    } else if (resultJson.getAsString().equals("SUCCESS") && asJsonArray.size() < 1) { // when build is success and zip relative path is not added in json
        ciBuild.setStatus("INPROGRESS");
    } else {//from w w w. j  a  va  2s  .co m
        ciBuild.setStatus(resultJson.getAsString());
        //download path
        for (JsonElement jsonArtElement : asJsonArray) {
            ciBuild.setDownload(jsonArtElement.getAsJsonObject()
                    .get(FrameworkConstants.CI_JOB_BUILD_DOWNLOAD_PATH).toString());
        }
    }

    ciBuild.setId(idJson.getAsString());
    String dispFormat = "dd/MM/yyyy hh:mm:ss";
    ciBuild.setTimeStamp(getDate(timeJson.getAsString(), dispFormat));
}

From source file:com.photon.phresco.framework.impl.CIManagerImpl.java

License:Apache License

@Override
public int getTotalBuilds(CIJob job) throws PhrescoException {
    S_LOGGER.debug("Entering Method CIManagerImpl.getTotalBuilds(CIJob job)");
    S_LOGGER.debug("getCIBuilds()  JobName = " + job.getName());
    JsonArray jsonArray = getBuildsArray(job);
    Gson gson = new Gson();
    CIBuild ciBuild = null;/*from  w w w .j a v  a 2s  .c om*/
    if (jsonArray.size() > 0) {
        ciBuild = gson.fromJson(jsonArray.get(0), CIBuild.class);
        String buildUrl = ciBuild.getUrl();
        String jenkinsUrl = job.getJenkinsUrl() + ":" + job.getJenkinsPort();
        buildUrl = buildUrl.replaceAll("localhost:" + job.getJenkinsPort(), jenkinsUrl); // display the jenkins running url in ci list
        String response = getJsonResponse(buildUrl + "api/json");
        JsonParser parser = new JsonParser();
        JsonElement jsonElement = parser.parse(response);
        JsonObject jsonObject = jsonElement.getAsJsonObject();
        JsonElement resultJson = jsonObject.get(FrameworkConstants.CI_JOB_BUILD_RESULT);
        JsonArray asJsonArray = jsonObject.getAsJsonArray(FrameworkConstants.CI_JOB_BUILD_ARTIFACTS);
        if (jsonObject.get(FrameworkConstants.CI_JOB_BUILD_RESULT).toString().equals("null")) { // when build result is not known
            return -1; // it indicates the job is in progress and not yet completed
        } else if (resultJson.getAsString().equals("SUCCESS") && asJsonArray.size() < 1) { // when build is success and build zip relative path is unknown
            return -1;
        } else {
            return jsonArray.size();
        }
    } else {
        return -1; // When the project is build first time,
    }
}

From source file:com.pinterest.arcee.lease.QuboleLeaseManager.java

License:Apache License

public QuboleClusterBean fromJson(String clusterId, String configuration, String clusterState) {
    if (StringUtils.isEmpty(configuration) || StringUtils.isEmpty(clusterState)) {
        return null;
    }/*from  www  .j  a  v a2s. c o  m*/

    QuboleClusterBean quboleClusterBean = new QuboleClusterBean();
    quboleClusterBean.setClusterId(clusterId);
    JsonParser parser = new JsonParser();
    JsonObject jsonObj = (JsonObject) parser.parse(configuration);
    // http://docs.qubole.com/en/latest/rest-api/cluster_api/get-cluster-information.html
    JsonObject nodeConfiguration = jsonObj.getAsJsonObject("node_configuration");
    quboleClusterBean.setMinSize(nodeConfiguration.getAsJsonPrimitive(MIN_SIZE_TAG).getAsInt());
    quboleClusterBean.setMaxSize(nodeConfiguration.getAsJsonPrimitive(MAX_SIZE_TAG).getAsInt());

    JsonObject stateObj = (JsonObject) parser.parse(clusterState);
    JsonArray array = stateObj.getAsJsonArray("nodes");
    int reservedInsanceCount = 0;
    int spotInstanceCount = 0;
    for (int i = 0; i < array.size(); ++i) {
        JsonObject nodeObject = array.get(i).getAsJsonObject();
        Boolean isSpotInstance = nodeObject.getAsJsonPrimitive("is_spot_instance").getAsBoolean();
        if (isSpotInstance) {
            spotInstanceCount++;
        } else {
            reservedInsanceCount++;
        }
    }
    quboleClusterBean.setRunningReservedInstanceCount(reservedInsanceCount);
    quboleClusterBean.setRunningSpotInstanceCount(spotInstanceCount);
    return quboleClusterBean;
}

From source file:com.pinterest.arcee.metrics.StatsboardMetricSource.java

License:Apache License

@Override
public Collection<MetricDatumBean> getMetrics(String metricName, String start) throws Exception {
    HTTPClient httpClient = new HTTPClient();
    Map<String, String> params = new HashMap<>();
    params.put("target", metricName);
    params.put("start", start);
    HashMap<String, String> headers = new HashMap<>();

    String url = String.format("%s/api/v1/query", readPath);
    String jsonPayload = httpClient.get(url, params, headers, 1);
    LOG.debug(String.format("Get metric data from source: %s", jsonPayload));
    List<MetricDatumBean> dataPoints = new ArrayList<>();
    JsonParser parser = new JsonParser();
    JsonArray array = (JsonArray) parser.parse(jsonPayload);
    if (array.isJsonNull() || array.size() == 0) {
        LOG.info(String.format("Cannot obtain metrics %s from %s", metricName, url));
        return dataPoints;
    }/*from   ww w. ja  v a2 s .  c o m*/

    JsonObject object = (JsonObject) array.get(0);
    JsonArray data = object.getAsJsonArray("datapoints");
    for (Iterator<JsonElement> elementIterator = data.iterator(); elementIterator.hasNext();) {
        JsonArray metric = (JsonArray) elementIterator.next();
        MetricDatumBean dataPoint = new MetricDatumBean();
        dataPoint.setTimestamp(metric.get(0).getAsLong() * 1000);
        double metricValue = metric.get(1).getAsDouble();
        metricValue = metricValue == Double.MIN_VALUE ? 0 : metricValue;
        dataPoint.setValue(metricValue);
        dataPoints.add(dataPoint);
    }
    return dataPoints;
}