Example usage for com.google.gson JsonArray get

List of usage examples for com.google.gson JsonArray get

Introduction

In this page you can find the example usage for com.google.gson JsonArray get.

Prototype

public JsonElement get(int i) 

Source Link

Document

Returns the ith element of the array.

Usage

From source file:com.ibm.iot.auto.bluemix.samples.nodered.SendCarProbe.java

License:Open Source License

public static void main(String[] args) throws Exception {
    Properties deviceProps = new Properties();
    try {//from w  w  w.  java  2s . c  o m
        deviceProps.load(new FileInputStream("config/device.prop"));
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }
    String inputFilename = "data/CarProbeSample.json";
    DeviceClient deviceClient = null;
    try {
        deviceClient = new DeviceClient(deviceProps);
        deviceClient.connect();
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }

    BufferedReader br = null;
    try {
        br = new BufferedReader(new FileReader(inputFilename));
        JsonParser parsor = new JsonParser();
        JsonArray jsonArray = parsor.parse(br).getAsJsonArray();
        for (int i = 0; i < jsonArray.size(); i++) {
            JsonObject jsonObject = (JsonObject) jsonArray.get(i);
            boolean status = deviceClient.publishEvent("load", jsonObject);
            System.out.println(jsonObject);
            Thread.sleep(SLEEP_INTERVAL);
            if (!status) {
                throw new Exception("Failed to publish the event: " + jsonObject);
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
        throw e;
    } finally {
        if (br != null) {
            br.close();
            System.exit(0);
        }
    }
    System.out.println("Completed!!");
}

From source file:com.ibm.iotf.devicemgmt.device.handler.ObserveRequestHandler.java

License:Open Source License

/**
 * Handles the observe request from IBM IoT Foundation
 *//*from w ww . j ava 2  s  .c  om*/
@Override
protected void handleRequest(JsonObject jsonRequest) {
    JsonObject response = new JsonObject();
    JsonArray responseArray = new JsonArray();
    JsonObject d = (JsonObject) jsonRequest.get("d");
    JsonArray fields = (JsonArray) d.get("fields");
    for (int i = 0; i < fields.size(); i++) {
        String name = fields.get(i).getAsString();
        JsonObject fieldResponse = new JsonObject();
        Resource resource = getDMClient().getDeviceData().getResource(name);
        if (resource != null) {
            resource.addPropertyChangeListener(Resource.ChangeListenerType.INTERNAL, this);
            fieldsMap.put(name, resource);
        }
        fieldResponse.add("field", fields.get(i));
        JsonElement value = resource.toJsonObject();
        fieldResponse.add("value", value);
        responseMap.put(name, value);
        responseArray.add(fieldResponse);
    }

    JsonObject responseFileds = new JsonObject();
    responseFileds.add("fields", responseArray);
    response.add("d", responseFileds);
    response.add("reqId", jsonRequest.get("reqId"));
    response.add("rc", new JsonPrimitive(ResponseCode.DM_SUCCESS.getCode()));
    respond(response);
}

From source file:com.ibm.iotf.sample.client.application.api.SampleDeviceDiagnosticsAPIOperations.java

License:Open Source License

/**
 * This sample showcases how to Delete a diagnostic Log.
 * @throws IoTFCReSTException// w ww.  ja v a  2s  .  c  o m
 */
private void deleteDiagnosticLog() {
    System.out.println("Delete a Diag Log for device " + DEVICE_ID + " of type " + DEVICE_TYPE);
    // Lets get all diagnostic Logs and delete the first one
    try {
        JsonArray response = this.apiClient.getAllDiagnosticLogs(DEVICE_TYPE, DEVICE_ID);

        JsonElement logElement = response.get(0);
        JsonObject responseJson = logElement.getAsJsonObject();
        boolean status = apiClient.deleteDiagnosticLog(DEVICE_TYPE, DEVICE_ID,
                responseJson.get("id").getAsString());
        System.out.println("Deletion of Log ID :: " + responseJson.get("id").getAsString() + "  " + status);
    } catch (IoTFCReSTException e) {
        System.out.println("HttpCode :" + e.getHttpCode() + " ErrorMessage :: " + e.getMessage());
        // Print if there is a partial response
        System.out.println(e.getResponse());
    }
}

From source file:com.ibm.iotf.sample.client.application.api.SampleDeviceDiagnosticsAPIOperations.java

License:Open Source License

/**
 * This sample showcases how to get a diagnostic Log with a given ID.
 * @throws IoTFCReSTException//  w w  w. j  a va2  s  . c o m
 */

private void getDiagnosticLog() {
    // Lets get all diagnostic Logs and retrieve the first one based on ID
    try {
        JsonArray response = this.apiClient.getAllDiagnosticLogs(DEVICE_TYPE, DEVICE_ID);
        JsonElement logElement = response.get(0);
        JsonObject responseJson = logElement.getAsJsonObject();
        System.out.println("Get a Diag Log based on Id " + responseJson.get("id").getAsString());
        JsonObject log = apiClient.getDiagnosticLog(DEVICE_TYPE, DEVICE_ID,
                responseJson.get("id").getAsString());
        System.out.println(log);
    } catch (IoTFCReSTException e) {
        System.out.println("HttpCode :" + e.getHttpCode() + " ErrorMessage :: " + e.getMessage());
        // Print if there is a partial response
        System.out.println(e.getResponse());
    }
}

From source file:com.ibm.iotf.sample.client.application.api.SampleDeviceManagementAPIOperations.java

License:Open Source License

/**
 * Clears the status of a device management request. The status for a 
 * request that has been completed is automatically cleared soon after 
 * the request completes. You can use this operation to clear the status 
 * for a completed request, or for an in-progress request which may never 
 * complete due to a problem./*from w w  w .ja  v a 2 s .  com*/
 * 
 * @throws IoTFCReSTException
 */
private void deleteMgmtRequest() throws IoTFCReSTException {
    System.out.println("Delete a DM request from the organization..");
    // Lets clear the first ID from the list
    try {
        JsonElement response = this.apiClient.getAllDeviceManagementRequests();
        JsonArray requests = response.getAsJsonObject().get("results").getAsJsonArray();
        JsonElement request = requests.get(0);
        System.out.println("Delete a DM request .. " + request.getAsJsonObject().get("id").getAsString());
        boolean status = this.apiClient
                .deleteDeviceManagementRequest(request.getAsJsonObject().get("id").getAsString());
        System.out.println("Delete status: " + status);
    } catch (IoTFCReSTException e) {
        System.out.println("HttpCode :" + e.getHttpCode() + " ErrorMessage :: " + e.getMessage());
        // Print if there is a partial response
        System.out.println(e.getResponse());
    }

}

From source file:com.ibm.iotf.sample.client.application.api.SampleDeviceManagementAPIOperations.java

License:Open Source License

/**
 * This sample showcases how to get details of a device management request.
 * @throws IoTFCReSTException//from  w  w w  .  j a v  a  2  s .  com
 */
private void getMgmtRequest() throws IoTFCReSTException {
    System.out.println("Retrieve a DM request from the organization..");
    // Lets clear the first ID from the list
    try {
        JsonElement response = this.apiClient.getAllDeviceManagementRequests();
        JsonArray requests = response.getAsJsonObject().get("results").getAsJsonArray();
        JsonElement request = requests.get(0);
        System.out.println("Get a DM request .. " + request.getAsJsonObject().get("id").getAsString());
        JsonObject details = this.apiClient
                .getDeviceManagementRequest(request.getAsJsonObject().get("id").getAsString());
        System.out.println(details);
    } catch (IoTFCReSTException e) {
        System.out.println("HttpCode :" + e.getHttpCode() + " ErrorMessage :: " + e.getMessage());
        // Print if there is a partial response
        System.out.println(e.getResponse());
    }

}

From source file:com.ibm.iotf.sample.client.application.api.SampleDeviceManagementAPIOperations.java

License:Open Source License

/**
 * This sample showcases how to get list of device management request device statuses
 * @throws IoTFCReSTException/*from www . jav  a  2 s.c o m*/
 */
private void getMgmtRequestDeviceStatus() throws IoTFCReSTException {
    // Lets get the DM request status from the list
    System.out.println("Get DM request device status..");
    try {
        JsonElement response = this.apiClient.getAllDeviceManagementRequests();
        JsonArray requests = response.getAsJsonObject().get("results").getAsJsonArray();
        JsonElement request = requests.get(0);
        String id = request.getAsJsonObject().get("id").getAsString();

        ArrayList<NameValuePair> parameters = new ArrayList<NameValuePair>();
        parameters.add(new BasicNameValuePair("_bookmark", "<bookmark>"));

        JsonObject details = this.apiClient.getDeviceManagementRequestStatus(id);

        // The response will contain more parameters that will be used to issue
        // the next request. The results element will contain the current list of devices
        JsonArray devices = details.get("results").getAsJsonArray();
        for (Iterator<JsonElement> iterator = devices.iterator(); iterator.hasNext();) {
            JsonElement deviceElement = iterator.next();
            JsonObject responseJson = deviceElement.getAsJsonObject();
            System.out.println(responseJson);
        }

    } catch (IoTFCReSTException e) {
        System.out.println("HttpCode :" + e.getHttpCode() + " ErrorMessage :: " + e.getMessage());
        // Print if there is a partial response
        System.out.println(e.getResponse());
    }

}

From source file:com.ibm.iotf.sample.client.application.ApplicationFirmwareRequestSample.java

License:Open Source License

private void clearAllDMRequests() throws IoTFCReSTException {
    JsonElement response = this.apiClient.getAllDeviceManagementRequests();
    if (response.getAsJsonObject().get("results") != null) {
        JsonArray requests = response.getAsJsonObject().get("results").getAsJsonArray();
        for (int i = 0; i < requests.size(); i++) {
            JsonElement request = requests.get(i);
            String requestId = request.getAsJsonObject().get("id").getAsString();
            this.apiClient.deleteDeviceManagementRequest(requestId);
        }/*from   www.  j a va2 s  .c o m*/
    }

}

From source file:com.ibm.iotf.sample.client.application.ApplicationFirmwareRequestSample.java

License:Open Source License

/**
 * The following method sends an acknowledgement from Device to Application,
 * mentioning the status of the execution of Device Action, as triggered
 * by the Application through Watson IoT Platform
 * @throws IoTFCReSTException/*from  w  ww  .  ja  v a 2  s  .co  m*/
 */
private void waitForRequestToFinish() throws IoTFCReSTException {
    JsonElement response = this.apiClient.getAllDeviceManagementRequests();
    JsonArray requests = response.getAsJsonObject().get("results").getAsJsonArray();
    JsonElement request = requests.get(0);
    String requestId = request.getAsJsonObject().get("id").getAsString();

    int count = 0;
    while (count++ <= 3600) { // wait for an hour, before giving it up
        JsonObject details = this.apiClient.getDeviceManagementRequest(requestId);
        System.out.println(details);
        if (details.get("complete").getAsBoolean() == true) {
            break;
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.ibm.streamsx.rest.AbstractStreamingAnalyticsService.java

License:Open Source License

@Override
public Result<Job, JsonObject> buildAndSubmitJob(File archive, JsonObject jco, String buildName)
        throws IOException {

    JsonObject metrics = new JsonObject();
    metrics.addProperty(SubmissionResultsKeys.SUBMIT_ARCHIVE_SIZE, archive.length());

    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {/*  w  w w  . ja va  2  s.  co  m*/
        // Set up the build name
        if (null == buildName) {
            buildName = "build";
        }
        buildName = getSPLCompatibleName(buildName) + "_" + randomHex(16);
        buildName = URLEncoder.encode(buildName, StandardCharsets.UTF_8.name());
        // Perform initial post of the archive
        RemoteContext.REMOTE_LOGGER
                .info("Streaming Analytics service (" + serviceName + "): submitting build " + buildName);
        final long startUploadTime = System.currentTimeMillis();
        JsonObject build = submitBuild(httpclient, getAuthorization(), archive, buildName);
        final long endUploadTime = System.currentTimeMillis();
        metrics.addProperty(SubmissionResultsKeys.SUBMIT_UPLOAD_TIME, (endUploadTime - startUploadTime));

        String buildId = jstring(build, "id");
        String outputId = jstring(build, "output_id");

        // Loop until built
        final long startBuildTime = endUploadTime;
        long lastCheckTime = endUploadTime;
        String status = buildStatusGet(buildId, httpclient, getAuthorization());
        while (!status.equals("built")) {
            String mkey = SubmissionResultsKeys.buildStateMetricKey(status);
            long now = System.currentTimeMillis();
            long duration;
            if (metrics.has(mkey)) {
                duration = metrics.get(mkey).getAsLong();
            } else {
                duration = 0;
            }
            duration += (now - lastCheckTime);
            metrics.addProperty(mkey, duration);
            lastCheckTime = now;

            // 'building', 'notBuilt', and 'waiting' are all states which can eventualy result in 'built'
            // sleep and continue to monitor
            if (status.equals("building") || status.equals("notBuilt") || status.equals("waiting")) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
                status = buildStatusGet(buildId, httpclient, getAuthorization());
                continue;
            }
            // The remaining possible states are 'failed', 'timeout', 'canceled', 'canceling', and 'unknown', none of which can lead to a state of 'built', so we throw an error.
            else {
                RemoteContext.REMOTE_LOGGER
                        .severe("Streaming Analytics service (" + serviceName + "): The submitted archive "
                                + archive.getName() + " failed to build with status " + status + ".");
                JsonObject output = getBuildOutput(buildId, outputId, httpclient, getAuthorization());
                String strOutput = "";
                if (output != null)
                    strOutput = prettyPrintOutput(output);
                throw new IllegalStateException("Error submitting archive for compilation: \n" + strOutput);
            }
        }
        final long endBuildTime = System.currentTimeMillis();
        metrics.addProperty(SubmissionResultsKeys.SUBMIT_TOTAL_BUILD_TIME, (endBuildTime - startBuildTime));

        // Now perform archive put
        build = getBuild(buildId, httpclient, getAuthorization());

        JsonArray artifacts = array(build, "artifacts");
        if (artifacts == null || artifacts.size() == 0) {
            throw new IllegalStateException("No artifacts associated with build " + jstring(build, "id"));
        }
        // TODO: support multiple artifacts associated with a single build.
        JsonObject artifact = artifacts.get(0).getAsJsonObject();
        String submitUrl = getJobSubmitUrl(artifact);

        RemoteContext.REMOTE_LOGGER
                .info("Streaming Analytics service (" + serviceName + "): submitting job request.");
        final long startSubmitTime = System.currentTimeMillis();
        JsonObject response = submitBuildArtifact(httpclient, jco, getAuthorization(), submitUrl);
        final long endSubmitTime = System.currentTimeMillis();
        metrics.addProperty(SubmissionResultsKeys.SUBMIT_JOB_TIME, (endSubmitTime - startSubmitTime));

        Result<Job, JsonObject> result = jobResult(response);
        result.getRawResult().add(SubmissionResultsKeys.SUBMIT_METRICS, metrics);
        return result;
    } finally {
        httpclient.close();
    }
}