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.hp.ov.sdk.adaptors.PortTelemetrySerializationAdapter.java

License:Apache License

@Override
public JsonElement serialize(PortTelemetry src, Type typeOfSrc, JsonSerializationContext context) {
    return new JsonPrimitive(src.name());
}

From source file:com.ibm.g11n.pipeline.resfilter.impl.JsonResource.java

License:Open Source License

@Override
public void write(OutputStream outStream, LanguageBundle languageBundle, FilterOptions options)
        throws IOException, ResourceFilterException {
    // extracts key value pairs in original sequence order
    List<ResourceString> resStrings = languageBundle.getSortedResourceStrings();

    JsonObject output = new JsonObject();
    JsonObject top_level;/*from w  w  w  . j  a v  a  2 s  .c om*/

    if (this instanceof GlobalizeJsResource) {
        String resLanguageCode = languageBundle.getEmbeddedLanguageCode();
        if (resLanguageCode == null || resLanguageCode.isEmpty()) {
            throw new ResourceFilterException(
                    "Missing resource language code in the specified language bundle.");
        }
        top_level = new JsonObject();
        top_level.add(resLanguageCode, output);
    } else {
        top_level = output;
    }

    for (ResourceString res : resStrings) {
        String key = res.getKey();
        List<KeyPiece> keyPieces = splitKeyPieces(key);
        JsonElement current = output;
        for (int i = 0; i < keyPieces.size(); i++) {
            if (i + 1 < keyPieces.size()) { // There is structure under this
                                            // key piece
                if (current.isJsonObject()) {
                    JsonObject currentObject = current.getAsJsonObject();
                    if (!currentObject.has(keyPieces.get(i).keyValue)) {
                        if (keyPieces.get(i + 1).keyType == JsonToken.BEGIN_ARRAY) {
                            currentObject.add(keyPieces.get(i).keyValue, new JsonArray());
                        } else {
                            currentObject.add(keyPieces.get(i).keyValue, new JsonObject());
                        }
                    }
                    current = currentObject.get(keyPieces.get(i).keyValue);
                } else {
                    JsonArray currentArray = current.getAsJsonArray();
                    Integer idx = Integer.valueOf(keyPieces.get(i).keyValue);
                    for (int arrayIndex = currentArray.size(); arrayIndex <= idx; arrayIndex++) {
                        currentArray.add(JsonNull.INSTANCE);
                    }
                    if (currentArray.get(idx).isJsonNull()) {
                        if (keyPieces.get(i + 1).keyType == JsonToken.BEGIN_ARRAY) {
                            currentArray.set(idx, new JsonArray());
                        } else {
                            currentArray.set(idx, new JsonObject());
                        }
                    }
                    current = currentArray.get(idx);
                }
            } else { // This is the leaf node
                if (keyPieces.get(i).keyType == JsonToken.BEGIN_ARRAY) {
                    JsonArray currentArray = current.getAsJsonArray();
                    Integer idx = Integer.valueOf(keyPieces.get(i).keyValue);
                    JsonPrimitive e = new JsonPrimitive(res.getValue());
                    for (int arrayIndex = currentArray.size(); arrayIndex <= idx; arrayIndex++) {
                        currentArray.add(JsonNull.INSTANCE);
                    }
                    current.getAsJsonArray().set(idx, e);
                } else {
                    current.getAsJsonObject().addProperty(keyPieces.get(i).keyValue, res.getValue());
                }
            }
        }
    }
    try (OutputStreamWriter writer = new OutputStreamWriter(new BufferedOutputStream(outStream),
            StandardCharsets.UTF_8)) {
        new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create().toJson(top_level, writer);
    }
}

From source file:com.ibm.internal.iotf.devicemgmt.ConcreteCustomAction.java

License:Open Source License

/**
 * Return the <code>JsonObject</code> representation of the <code>Listener Response</code> object.
 * @return JsonObject object//from www.  j  av  a 2  s. c  om
 */
public JsonObject toJsonObject() {
    JsonObject o = new JsonObject();
    if (this.status != null) {
        o.add("rc", new JsonPrimitive(this.status.get()));
    }
    if (this.message != null) {
        o.add("message", new JsonPrimitive(message));
    }
    if (this.reqId != null) {
        o.add("reqId", new JsonPrimitive(reqId));
    }
    return o;
}

From source file:com.ibm.internal.iotf.devicemgmt.ConcreteDeviceAction.java

License:Open Source License

/**
 * Return the <code>JsonObject</code> representation of the <code>Listener Response</code> object.
 * @return JsonObject object//from   www .j a  v a  2s. c o m
 */
public JsonObject toJsonObject() {
    JsonObject o = new JsonObject();
    o.add("rc", new JsonPrimitive(this.status.get()));
    if (this.message != null) {
        o.add("message", new JsonPrimitive(message));
    }
    return o;
}

From source file:com.ibm.internal.iotf.devicemgmt.handler.CancelRequestHandler.java

License:Open Source License

/**
 * This method handles the cancel request messages from IBM Watson IoT Platform
 *//* w w  w. j ava  2 s.c  o m*/
@Override
protected void handleRequest(JsonObject jsonRequest) {
    JsonArray fields = null;
    JsonObject d = (JsonObject) jsonRequest.get("d");
    if (d != null) {
        fields = (JsonArray) d.get("data");
        if (fields != null) {
            ObserveRequestHandler observe = getObserveRequestHandler(getDMClient());
            if (observe != null) {
                observe.cancel(fields);
            }
        }
    }

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

From source file:com.ibm.internal.iotf.devicemgmt.handler.CustomRequestHandler.java

License:Open Source License

/**
 * Handle initiate custom action request from IBM Watson IoT Platform
 *///  ww w.  j  av  a  2 s . c om
@Override
protected void handleRequest(JsonObject jsonRequest, String topic) {
    final String METHOD = "handleRequest";

    ConcreteCustomAction action = (ConcreteCustomAction) getDMClient().getDeviceData().getCustomAction();
    if (action == null || getDMClient().getCustomActionHandler() == null) {
        // this should never happen
        JsonObject response = new JsonObject();
        response.add(REQ_ID, jsonRequest.get(REQ_ID));
        response.add("rc", new JsonPrimitive(ResponseCode.DM_FUNCTION_NOT_IMPLEMENTED.getCode()));
        respond(response);
    } else {
        LoggerUtility.fine(CLASS_NAME, METHOD, " start custom action ");
        // remove any other listener that are listening for the status update

        // iotdm-1/mgmt/custom/bundleId/actionId
        // iotdm-1/type/typeId/id/deviceId/mgmt/custom/bundleId/actionId
        String customActionSubstring = topic.substring(topic.indexOf("mgmt/custom/"));
        String[] customActionParts = customActionSubstring.split("/");
        String bundleId = customActionParts[2];
        String actionId = customActionParts[3];
        action.setBundleId(bundleId);
        action.setActionId(actionId);
        action.setReqId(jsonRequest.get(REQ_ID).getAsString());
        action.setPayload(jsonRequest);

        ((ConcreteCustomAction) action).clearListener();
        ((ConcreteCustomAction) action).addPropertyChangeListener(this);
        CustomActionHandler handler = getDMClient().getCustomActionHandler();
        handler.handleCustomAction(action);
    }
}

From source file:com.ibm.internal.iotf.devicemgmt.handler.DeviceUpdateRequestHandler.java

License:Open Source License

/**
 * This method handles all the update requests from IBM Watson IoT Platform
 *///from w  w w. j  av  a2 s  .c  om
@Override
public void handleRequest(JsonObject jsonRequest) {
    final String METHOD = "handleRequest";
    List<Resource> fireRequiredResources = new ArrayList<Resource>();
    JsonArray fields = null;
    ResponseCode rc = ResponseCode.DM_UPDATE_SUCCESS;
    JsonObject response = new JsonObject();
    JsonObject d = (JsonObject) jsonRequest.get("d");

    if (d != null) {
        fields = (JsonArray) d.get("fields");
        if (fields != null) {

            /**
             * update the fields in actual device object
             */
            JsonArray resFields = new JsonArray();
            for (int i = 0; i < fields.size(); i++) {
                JsonObject obj = (JsonObject) fields.get(i);
                if (obj.get("field") != null) {
                    String key = obj.get("field").getAsString();
                    JsonObject value = (JsonObject) obj.get("value");
                    boolean success = false;
                    try {
                        Resource resource = getDMClient().getDeviceData().getResource(key);
                        if (resource != null) {
                            success = updateField(resource, value);
                            fireRequiredResources.add(resource);
                        }
                    } catch (Exception e) {
                        LoggerUtility.log(Level.SEVERE, CLASS_NAME, METHOD,
                                "Exception in updating field " + key + " value " + value, e);

                        if (e.getMessage() != null)
                            response.add("message", new JsonPrimitive(e.getMessage()));
                    }
                    if (success == false) {
                        resFields.add(new JsonPrimitive(key));
                        rc = ResponseCode.DM_NOT_FOUND;
                    }
                }
            }

            if (resFields.size() != 0) {
                JsonObject json = new JsonObject();
                json.add("fields", resFields);
                response.add("d", json);
            }
        }
    }

    response.add("rc", new JsonPrimitive(rc.getCode()));
    response.add("reqId", jsonRequest.get("reqId"));
    respond(response);

    // Lets fire the property change event now - this will notify the
    // device code if they are listening to
    Task task = this.new Task(fireRequiredResources);
    executor.execute(task);
}

From source file:com.ibm.internal.iotf.devicemgmt.handler.FactoryResetRequestHandler.java

License:Open Source License

/**
 * Handle the initiate factory reset messages from IBM Watson IoT Platform 
 *//* w  ww. j a  v  a2  s.c  o m*/
@Override
protected void handleRequest(JsonObject jsonRequest) {
    final String METHOD = "handleRequest";

    DeviceAction action = getDMClient().getDeviceData().getDeviceAction();
    if (action == null || getDMClient().getActionHandler() == null) {
        JsonObject response = new JsonObject();
        response.add("reqId", jsonRequest.get("reqId"));
        response.add("rc", new JsonPrimitive(ResponseCode.DM_FUNCTION_NOT_IMPLEMENTED.getCode()));
        respond(response);
    } else {
        LoggerUtility.fine(CLASS_NAME, METHOD, " start Factory Reset action ");
        // remove any other listener that are listening for the status update
        ((ConcreteDeviceAction) action).clearListener();
        ((ConcreteDeviceAction) action).addPropertyChangeListener(this);
        this.reqId = jsonRequest.get("reqId");
        DeviceActionHandler handler = getDMClient().getActionHandler();
        handler.handleFactoryReset(action);
    }
}

From source file:com.ibm.internal.iotf.devicemgmt.handler.FirmwareDownloadRequestHandler.java

License:Open Source License

/**
 * Following are actions that needs to be taken after receiving the command
 * //www .  j  a v a  2  s  .co  m
 * If mgmt.firmware.state is not 0 ("Idle") an error should be reported with 
 * response code 400, and an optional message text.
 * 
 * If the action can be initiated immediately, set rc to 202.
 * 
 * If mgmt.firmware.url is not set or is not a valid URL, set rc to 400.
 * 
 * If firmware download attempt fails, set rc to 500 and optionally set message accordingly.
 * 
 * If firmware download is not supported, set rc to 501 and optionally set message accordingly.
 */
@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"));
    DeviceFirmware deviceFirmware = getDMClient().getDeviceData().getDeviceFirmware();
    if (deviceFirmware == null || getDMClient().getFirmwareHandler() == null) {
        rc = ResponseCode.DM_FUNCTION_NOT_IMPLEMENTED;
    } else if (deviceFirmware.getState() != DeviceFirmware.FirmwareState.IDLE.getState()) {
        rc = ResponseCode.DM_BAD_REQUEST;
    } else {
        if (deviceFirmware.getUrl() != null) {
            LoggerUtility.fine(CLASS_NAME, METHOD, "fire firmware download");
            getDMClient().getFirmwareHandler().downloadFirmware(deviceFirmware);
            rc = ResponseCode.DM_ACCEPTED;
        } else {
            rc = ResponseCode.DM_BAD_REQUEST;
            LoggerUtility.severe(CLASS_NAME, METHOD, "No URL mentioned in the request");
        }
    }
    response.add("rc", new JsonPrimitive(rc.getCode()));
    respond(response);
}

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

License:Open Source License

/**
 * If this operation can be initiated immediately, rc should be set to 202.
 * //from w w w.ja  va  2  s  .  com
 * 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 || getDMClient().getFirmwareHandler() == 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 Firmware update ");
            getDMClient().getFirmwareHandler().updateFirmware(firmware);
            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);
}