Example usage for com.google.gson JsonPrimitive JsonPrimitive

List of usage examples for com.google.gson JsonPrimitive JsonPrimitive

Introduction

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

Prototype

public JsonPrimitive(Character c) 

Source Link

Document

Create a primitive containing a character.

Usage

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

License:Open Source License

/**
 * If this operation can be initiated immediately, rc should be set to 202.
 * //from www .  ja va 2s  . co m
 * If firmware was not previously downloaded successfully, rc should be set to 400.
 * 
 * If firmware update attempt fails, rc should be set to 500 
 * and the message field can optionally be set to contain relevant information.
 * 
 * If firmware update is not supported rc should be set to 501 and the message 
 * field can optionally be set to contain relevant information.
 * 
 * If mgmt.firmware.state is not 2 (Downloaded), an error should be reported 
 * with rc set to 400 and an optional message text. Otherwise, 
 * mgmt.firmware.updateStatus should be set to 1 (In Progress) and firmware 
 * installation should start.
 * 
 *  If firmware installation fails, mgmt.firmware.updateStatus should be set to either:
 *  2 (Out of Memory)
 *  5 (Unsupported Image)
 *  
 *  Once firmware update is complete, mgmt.firmware.updateStatus 
 *  should be set to 0 (Success), mgmt.firmware.state should be set to 0 (Idle), 
 *  downloaded firmware image can be deleted from the device and deviceInfo.fwVersion 
 *  should be set to the value of mgmt.firmware.version.
 */
@Override
public void handleRequest(JsonObject jsonRequest) {
    final String METHOD = "handleRequest";
    ResponseCode rc = ResponseCode.DM_INTERNAL_ERROR;

    JsonObject response = new JsonObject();
    response.add("reqId", jsonRequest.get("reqId"));

    // handle the error conditions
    DeviceFirmware firmware = getDMClient().getDeviceData().getDeviceFirmware();
    if (firmware == null) {
        rc = ResponseCode.DM_FUNCTION_NOT_IMPLEMENTED;
    } else if (firmware.getState() == DeviceFirmware.FirmwareState.IDLE.getState()) {
        rc = ResponseCode.DM_BAD_REQUEST;
    } else {
        // Normal condition

        if (firmware.getUrl() != null) {
            LoggerUtility.fine(CLASS_NAME, METHOD, "Fire event (" + DeviceFirmware.FIRMWARE_UPDATE_START + ")");
            getDMClient().getDeviceData().getDeviceFirmware().fireEvent(DeviceFirmware.FIRMWARE_UPDATE_START);
            rc = ResponseCode.DM_ACCEPTED;
        } else {
            rc = ResponseCode.DM_BAD_REQUEST;
            response.add("message", new JsonPrimitive("The value of the firmware URL is not set or null"));
        }
    }

    response.add("rc", new JsonPrimitive(rc.getCode()));
    respond(response);
}

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

License:Open Source License

/**
 * Handles the observe request from IBM IoT Foundation
 *//* w  w w .  j  av a  2 s  .c  o  m*/
@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.devicemgmt.device.handler.ObserveRequestHandler.java

License:Open Source License

@Override
public void propertyChange(PropertyChangeEvent evt) {

    Resource resource = (Resource) evt.getNewValue();
    // check if there is an observe relation established
    resource = fieldsMap.get(evt.getPropertyName());
    if (resource != null) {
        JsonObject response = new JsonObject();
        JsonObject field = new JsonObject();
        field.add("field", new JsonPrimitive(resource.getCanonicalName()));
        JsonElement value = resource.toJsonObject();
        JsonElement trimedValue = trimResponse(evt.getPropertyName(), value);
        if (null == trimedValue) {
            return;
        }/*from   www.  j av  a  2  s  .c o  m*/
        field.add("value", trimedValue);
        response.add("d", field);
        notify(response);
    }
}

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

License:Open Source License

/**
 * Handle initiate reboot request from IBM IoT Foundation
 */// w ww.  jav a  2s .c  o  m
@Override
protected void handleRequest(JsonObject jsonRequest) {
    final String METHOD = "handleRequest";
    ResponseCode rc = ResponseCode.DM_ACCEPTED;

    JsonObject response = new JsonObject();
    response.add("reqId", jsonRequest.get("reqId"));
    DeviceAction action = getDMClient().getDeviceData().getDeviceAction();
    if (action == null) {
        rc = ResponseCode.DM_FUNCTION_NOT_IMPLEMENTED;
    } else {
        LoggerUtility.fine(CLASS_NAME, METHOD, " fire event(" + DeviceAction.DEVICE_REBOOT_START + ")");

        action.fireEvent(DeviceAction.DEVICE_REBOOT_START);
        rc = ResponseCode.DM_ACCEPTED;
    }
    response.add("rc", new JsonPrimitive(rc.getCode()));
    respond(response);
}

From source file:com.ibm.iotf.devicemgmt.device.listener.DMNotifier.java

License:Open Source License

protected void notify(DeviceTopic topic, JsonObject payload) throws MqttException {
    final String METHOD = "notify(topic + payload)";

    String uuid = UUID.randomUUID().toString();
    payload.add("reqId", new JsonPrimitive(uuid));

    LoggerUtility.log(Level.FINER, CLASS_NAME, METHOD,
            "Topic(" + getNotifyTopic() + ") payload(" + payload.toString() + ")");
    dmClient.publish(topic, payload, 1);
}

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

License:Open Source License

/**
 * <p>Send a device manage request to Watson IoT Platform</p>
 *
 * <p>A Device uses this request to become a managed device.
 * It should be the first device management request sent by the
 * Device after connecting to the IBM Watson IoT Platform.
 * It would be usual for a device management agent to send this
 * whenever is starts or restarts.</p>
 *
 * <p>This method connects the device to Watson IoT Platform connect if its not connected already</p>
 *
 * @param lifetime The length of time in seconds within
 *        which the device must send another Manage device request.
 *        if set to 0, the managed device will not become dormant.
 *        When set, the minimum supported setting is 3600 (1 hour).
 *
 * @param supportFirmwareActions Tells whether the device supports firmware actions or not.
 *        The device must add a firmware handler to handle the firmware requests.
 *
 * @param supportDeviceActions Tells whether the device supports Device actions or not.
 *        The device must add a Device action handler to handle the reboot and factory reset requests.
 *
 * @return boolean response containing the status of the manage request
 * @throws MqttException/*from  w w  w .j ava  2s.c  o  m*/
 */
public boolean sendManageRequest(long lifetime, boolean supportFirmwareActions, boolean supportDeviceActions)
        throws MqttException {

    final String METHOD = "manage";

    LoggerUtility.log(Level.FINE, CLASS_NAME, METHOD, "lifetime(" + lifetime + "), " + "supportFirmwareActions("
            + supportFirmwareActions + "), " + "supportDeviceActions(" + supportDeviceActions + ")");

    boolean success = false;
    String topic = client.getDMAgentTopic().getManageTopic();

    if (!this.isConnected()) {
        this.connect();
    }

    this.supportDeviceActions = supportDeviceActions;
    this.supportFirmwareActions = supportFirmwareActions;
    JsonObject jsonPayload = new JsonObject();
    JsonObject supports = new JsonObject();
    supports.add("deviceActions", new JsonPrimitive(supportDeviceActions));
    supports.add("firmwareActions", new JsonPrimitive(supportFirmwareActions));

    JsonObject data = new JsonObject();
    data.add("supports", supports);
    if (deviceData.getDeviceInfo() != null) {
        data.add("deviceInfo", deviceData.getDeviceInfo().toJsonObject());
    }
    if (deviceData.getMetadata() != null) {
        data.add("metadata", deviceData.getMetadata().getMetadata());
    }
    if (lifetime > 0) {
        data.add("lifetime", new JsonPrimitive(lifetime));
    }
    jsonPayload.add("d", data);

    JsonObject jsonResponse = sendAndWait(topic, jsonPayload, REGISTER_TIMEOUT_VALUE);
    if (jsonResponse != null && jsonResponse.get("rc").getAsInt() == ResponseCode.DM_SUCCESS.getCode()) {
        DMRequestHandler.setRequestHandlers(this.client);
        if (!running) {
            publishQueue = new LinkedBlockingQueue<JsonObject>();
            Thread t = new Thread(this);
            t.start();
            running = true;
        }
        /*
         * set the dormant time to a local variable, in case if the connection is
         * lost due to n/w interruption, we need to send another manage request
         * with the dormant time as the lifetime
         */
        if (lifetime > 0) {
            Date currentTime = new Date();
            dormantTime = new Date(currentTime.getTime() + (lifetime * 1000));
        }
        success = true;
    }
    LoggerUtility.log(Level.FINE, CLASS_NAME, METHOD, "Success (" + success + ")");

    bManaged = success;
    return success;
}

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

License:Open Source License

/**
 * The Log message that needs to be added to the Watson IoT Platform.
 *
 * @param message The Log message that needs to be added to the Watson IoT Platform.
 * @param timestamp The Log timestamp//from  w w  w .j  a v a 2s  .  co m
 * @param severity The Log severity
 * @param data The optional diagnostic string data -
 *             The library will encode the data in base64 format as required by the Platform
 * @return code indicating whether the update is successful or not
 *        (200 means success, otherwise unsuccessful)
 */
public int addLog(String message, Date timestamp, LogSeverity severity, String data) {
    final String METHOD = "addLog";
    JsonObject jsonData = new JsonObject();
    JsonObject log = new JsonObject();
    log.add("message", new JsonPrimitive(message));
    log.add("severity", new JsonPrimitive(severity.getSeverity()));
    String utcTime = DateFormatUtils.formatUTC(timestamp,
            DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern());
    log.add("timestamp", new JsonPrimitive(utcTime));

    if (data != null) {
        byte[] encodedBytes = Base64.encodeBase64(data.getBytes());
        log.add("data", new JsonPrimitive(new String(encodedBytes)));
    }
    jsonData.add("d", log);

    try {
        JsonObject response = sendAndWait(client.getDMAgentTopic().getAddDiagLogTopic(), jsonData,
                REGISTER_TIMEOUT_VALUE);
        if (response != null) {
            return response.get("rc").getAsInt();
        }
    } catch (MqttException e) {
        LoggerUtility.log(Level.SEVERE, CLASS_NAME, METHOD, e.toString());
    }
    return 0;
}

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

License:Open Source License

/**
 * <p>Publish the Device management response to IBm Watson IoT Platform </p>
 *
 * <p>This method is used by the library to respond to each of the Device Management commands from
 *  IBM Watson IoT Platform</p>//from   w  w w . ja  v  a2s .c o  m
 *
 * @param topic Topic where the response to be published
 * @param payload the Payload
 * @param qos The Quality Of Service
 * @throws MqttException
 */
public void publish(String topic, JsonObject payload, int qos) throws MqttException {
    final String METHOD = "publish3";
    JsonObject jsonPubMsg = new JsonObject();
    jsonPubMsg.addProperty("topic", topic);
    jsonPubMsg.add("qos", new JsonPrimitive(qos));
    jsonPubMsg.add("payload", payload);
    publishQueue.add(jsonPubMsg);
    LoggerUtility.log(Level.FINE, CLASS_NAME, METHOD,
            ": Queued Topic(" + topic + ") qos=" + qos + " payload (" + payload.toString() + ")");
}

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

License:Open Source License

/**
 * <p>Send the message and waits for the response from IBM Watson IoT Platform<p>
 *
 * <p>This method is used by the library to send following messages to
 *  IBM Watson IoT Platform</p>/*from   w  ww .  j  av  a 2 s  . c o  m*/
 *
 *  <ul class="simple">
 * <li>Manage
 * <li>Unmanage
 * <li>Location update
 * <li>Diagnostic update/clear
 * </ul>
 *
 * @param topic Topic where the message to be sent
 * @param jsonPayload The message
 * @param timeout How long to wait for the response
 * @return response in Json format
 * @throws MqttException
 */
public JsonObject sendAndWait(String topic, JsonObject jsonPayload, long timeout) throws MqttException {

    final String METHOD = "sendAndWait";

    String uuid = UUID.randomUUID().toString();
    jsonPayload.add("reqId", new JsonPrimitive(uuid));

    LoggerUtility.fine(CLASS_NAME, METHOD,
            "Topic (" + topic + ") payload (" + jsonPayload.toString() + ") reqId (" + uuid + ")");

    if (responseSubscription == null) {
        responseSubscription = client.getDMServerTopic().getDMServerTopic();
        subscribe(responseSubscription, 1, this);
    }

    MqttMessage message = new MqttMessage();
    try {
        message.setPayload(jsonPayload.toString().getBytes("UTF-8"));
    } catch (UnsupportedEncodingException e) {
        LoggerUtility.log(Level.SEVERE, CLASS_NAME, METHOD, "Error setting payload for topic: " + topic, e);
        return null;
    }

    message.setQos(1);

    requests.put(uuid, message);

    publish(topic, message);

    JsonObject jsonResponse = null;
    while (jsonResponse == null) {
        try {
            jsonResponse = queue.poll(timeout, TimeUnit.MILLISECONDS);
            if (jsonResponse == null) {
                break;
            }
            if (jsonResponse.get("reqId").getAsString().equals(uuid)) {
                LoggerUtility.fine(CLASS_NAME, METHOD,
                        "" + "This response is for me reqId:" + jsonResponse.toString());
                break;
            } else {
                // This response is not for our request, put it back to the queue.
                LoggerUtility.warn(CLASS_NAME, METHOD,
                        "This response is NOT for me reqId:" + jsonResponse.toString());
                queue.add(jsonResponse);
                jsonResponse = null;
            }
        } catch (InterruptedException e) {
            break;
        }
    }
    if (jsonResponse == null) {
        LoggerUtility.warn(CLASS_NAME, METHOD,
                "NO RESPONSE from Watson IoT Platform for request: " + jsonPayload.toString());
        LoggerUtility.warn(CLASS_NAME, METHOD, "Connected(" + isConnected() + ")");
    }
    return jsonResponse;
}

From source file:com.ibm.iotf.devicemgmt.device.resource.DateResource.java

License:Open Source License

/**
 * Returns the value in Json Format/*from w ww .  j  a v  a 2s  .  c  om*/
 */
@Override
public JsonElement toJsonObject() {
    String utcTime = DateFormatUtils.formatUTC(getValue(),
            DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern());
    return (JsonElement) new JsonPrimitive(utcTime);
}