List of usage examples for com.google.gson JsonPrimitive JsonPrimitive
public JsonPrimitive(Character c)
From source file:com.ibm.iotf.devicemgmt.device.resource.NumberResource.java
License:Open Source License
/** * Returns the value in Json Format */ @Override public JsonElement toJsonObject() { return (JsonElement) new JsonPrimitive(getValue()); }
From source file:com.ibm.iotf.devicemgmt.gateway.ManagedGateway.java
License:Open Source License
/** * <p>Sends a device manage request to IBM Watson IoT Platform</p> * /* w w w . ja v a 2s . c o m*/ * <p>A Gateway uses this request to manage the device connected to it, * It should be the first device management request sent for 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 Gateway/Device to IBM Watson IoT Platform if * its not connected already</p> * * @param typeId The typeId of the device connected to the gateway * * @param deviceId The deviceId of the device connected to the gateway * * @param deviceData The DeviceData containing the information about the device * * @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 True if successful * @throws MqttException */ public boolean sendDeviceManageRequest(String typeId, String deviceId, DeviceData deviceData, long lifetime, boolean supportFirmwareActions, boolean supportDeviceActions) throws MqttException { final String METHOD = "manage"; LoggerUtility.log(Level.FINE, CLASS_NAME, METHOD, "typeId(" + typeId + "), " + "deviceId (" + deviceId + "), lifetime value(" + lifetime + ")"); String key = typeId + ':' + deviceId; ManagedGatewayDevice mc = (ManagedGatewayDevice) this.devicesMap.get(key); if (mc == null) { if (deviceData == null) { deviceData = new DeviceData.Builder().typeId(typeId).deviceId(deviceId).build(); } mc = new ManagedGatewayDevice(this, deviceData, supportFirmwareActions, supportDeviceActions); } else { mc.setSupportsFirmwareActions(supportFirmwareActions); mc.setSupportDeviceActions(supportDeviceActions); } if (reponseSubscription == false) { subscribe(GATEWAY_RESPONSE_TOPIC, 1, this); reponseSubscription = true; } boolean success = false; String topic = mc.getDMAgentTopic().getManageTopic(); if (!this.isConnected()) { this.connect(); } 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 (mc.getDeviceData().getDeviceInfo() != null) { data.add("deviceInfo", mc.getDeviceData().getDeviceInfo().toJsonObject()); } if (mc.getDeviceData().getMetadata() != null) { data.add("metadata", mc.getDeviceData().getMetadata().getMetadata()); } 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(mc); if (!running) { 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(); mc.setDormantTime(new Date(currentTime.getTime() + (lifetime * 1000))); } success = true; this.devicesMap.put(key, mc); } LoggerUtility.log(Level.FINE, CLASS_NAME, METHOD, "Success (" + success + ")"); mc.setbManaged(success); return success; }
From source file:com.ibm.iotf.devicemgmt.gateway.ManagedGateway.java
License:Open Source License
/** * Adds a Device(connected via the Gateway) Log message to the IBM Watson IoT Platform. * //from w ww.j av a 2 s.co m * This method converts the timestamp in the required format. * The caller just need to pass the timestamp in java.util.Date format. * * @param typeId The device type of the device connected to the Gateway. * @param deviceId The deviceId of the device connected to the Gateway. * @param message The Log message that needs to be added to the IBM Watson IoT Platform. * @param timestamp The Log timestamp * @param severity The {@link com.ibm.iotf.devicemgmt.LogSeverity} * @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 addDeviceLog(String typeId, String deviceId, String message, Date timestamp, LogSeverity severity, String data) { final String METHOD = "addDeviceLog"; String key = typeId + ':' + deviceId; ManagedGatewayDevice mc = (ManagedGatewayDevice) this.devicesMap.get(key); if (mc == null) { LoggerUtility.log(Level.SEVERE, CLASS_NAME, METHOD, "The device is not a managed device, so can not send the request"); return -1; } 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(mc.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.gateway.ManagedGateway.java
License:Open Source License
/** * <p>Publish the Device management response to IBm IBM Watson IoT Platform </p> * /* www.ja va 2s . co m*/ * <p>This method is used by the library to respond to each of the Device Management commands from * IBM Watson IoT Platform</p> * * @param topic Topic where the response to be published * @param payload the Payload * @param qos The Quality Of Service * @throws MqttException */ private 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.gateway.ManagedGateway.java
License:Open Source License
/** * <p>Send the message and waits for the response from IBM Watson IoT Platform<p> * //from w w w . jav a2 s . c om * <p>This method is used by the library to send following messages to * IBM Watson IoT Platform</p> * * <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 resonse * @return response in Json format * @throws MqttException */ private 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 + ")"); 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.streamsx.edgevideo.device.clients.wiotp.EdgentControlCmds.java
License:Open Source License
private static JsonArray toJsonArray(String... strings) { JsonArray ja = new JsonArray(); for (String s : strings) ja.add(new JsonPrimitive(s)); return ja;/*w ww. j a va 2s . c o m*/ }
From source file:com.ibm.streamsx.topology.builder.BOperatorInvocation.java
License:Open Source License
public void setParameter(String name, Object value) { if (value == null) throw new IllegalStateException("NULL PARAM:" + name); if (value instanceof SubmissionParameter) { JsonObject svp = SubmissionParameterFactory.asJSON((SubmissionParameter<?>) value); /*/* w w w.j a v a 2 s . com*/ JsonObject param = new JsonObject(); param.add("type", svp.get("type")); param.add("value", svp.get("value")); */ jparams.add(name, svp); return; } Object jsonValue = value; String jsonType = null; if (value instanceof JsonObject) { JsonObject jo = ((JsonObject) value); if (!jo.has("type") || !jo.has("value")) throw new IllegalArgumentException("Illegal JSON object " + jo); String type = jstring(jo, "type"); if ("__spl_value".equals(type)) { /* * The Value object is * <pre><code> * object { * type : "__spl_value" * value : object { * value : any. non-null. type appropriate for metaType * metaType : com.ibm.streams.operator.Type.MetaType.name() string * } * } * </code></pre> */ // unwrap and fall through to handling for the wrapped value JsonObject splValue = object(jo, "value"); value = splValue.get("value"); jsonValue = value; jsonType = jstring(splValue, "metaType"); /* String metaType = jstring(splValue, "metaType"); if ("USTRING".equals(metaType) || "UINT8".equals(metaType) || "UINT16".equals(metaType) || "UINT32".equals(metaType) || "UINT64".equals(metaType)) { jsonType = metaType; } */ // fall through to handle jsonValue as usual } else { jparams.add(name, jo); return; } } else if (value instanceof Supplier<?>) { value = ((Supplier<?>) value).get(); jsonValue = value; } if (value instanceof String) { if (jsonType == null) jsonType = SPLTypes.RSTRING; } else if (value instanceof Byte) { if (jsonType == null) jsonType = SPLTypes.INT8; } else if (value instanceof Short) { if (jsonType == null) jsonType = SPLTypes.INT16; } else if (value instanceof Integer) { if (jsonType == null) jsonType = SPLTypes.INT32; } else if (value instanceof Long) { if (jsonType == null) jsonType = SPLTypes.INT64; } else if (value instanceof Float) { jsonType = SPLTypes.FLOAT32; } else if (value instanceof Double) { jsonType = SPLTypes.FLOAT64; } else if (value instanceof Boolean) { jsonType = SPLTypes.BOOLEAN; } else if (value instanceof BigDecimal) { jsonValue = value.toString(); // Need to maintain exact value jsonType = SPLTypes.DECIMAL128; } else if (value instanceof Enum) { jsonValue = ((Enum<?>) value).name(); jsonType = JParamTypes.TYPE_ENUM; } else if (value instanceof String[]) { String[] sa = (String[]) value; JsonArray a = new JsonArray(); for (String vs : sa) a.add(new JsonPrimitive(vs)); jsonValue = a; } else if (value instanceof JsonElement) { assert jsonType != null; } else { throw new IllegalArgumentException( "Type for parameter " + name + " is not supported:" + value.getClass()); } JsonObject param = JParamTypes.create(jsonType, jsonValue); jparams.add(name, param); }
From source file:com.ibm.streamsx.topology.builder.BPort.java
License:Open Source License
default void connect(BPort other) { JsonPrimitive on = new JsonPrimitive(other.name()); assert !array(_json(), "connections").contains(on); array(_json(), "connections").add(on); }
From source file:com.ibm.streamsx.topology.generator.spl.GraphUtilities.java
License:Open Source License
static void removeOperators(Collection<JsonObject> operators, JsonObject graph) { for (JsonObject iso : operators) { // Get parents and children of operator Set<JsonObject> operatorParents = getUpstream(iso, graph); Set<JsonObject> operatorChildren = getDownstream(iso, graph); JsonArray operatorOutputs = array(iso, "outputs"); // Get the output name of the operator String operatorOutName = ""; if (operatorOutputs != null) { JsonObject operatorFirstOutput = operatorOutputs.get(0).getAsJsonObject(); if (operatorFirstOutput != null) { operatorOutName = jstring(operatorFirstOutput, "name"); }//from w w w .ja v a 2 s.c o m } // Also get input names List<String> operatorInNames = new ArrayList<>(); inputs(iso, input -> operatorInNames.add(jstring(input, "name"))); // Respectively, the names of the child and parent input and // output ports connected to the operator. List<String> childInputPortNames = new ArrayList<>(); List<String> parentOutputPortNames = new ArrayList<>(); // References to the list of connections for the parent and child // output and input ports that are connected to the $isolate$ // operator. List<JsonArray> childConnections = new ArrayList<>(); List<JsonArray> parentConnections = new ArrayList<>(); // Get names of children's input ports that are connected to the // operator; for (JsonObject child : operatorChildren) { JsonArray inputs = child.get("inputs").getAsJsonArray(); for (JsonElement inputObj : inputs) { JsonObject input = inputObj.getAsJsonObject(); JsonArray connections = input.get("connections").getAsJsonArray(); for (JsonElement connectionObj : connections) { String connection = connectionObj.getAsString(); if (connection.equals(operatorOutName)) { childInputPortNames.add(jstring(input, "name")); childConnections.add(connections); connections.remove(connectionObj); break; } } } } // Get names of parent's output ports that are connected to the // $Isolate$ operator; for (JsonObject parent : operatorParents) { JsonArray outputs = parent.get("outputs").getAsJsonArray(); for (JsonElement outputObj : outputs) { JsonObject output = outputObj.getAsJsonObject(); JsonArray connections = output.get("connections").getAsJsonArray(); for (JsonElement connectionObj : connections) { String connection = connectionObj.getAsString(); if (operatorInNames.contains(connection)) { parentOutputPortNames.add(jstring(output, "name")); parentConnections.add(connections); connections.remove(connectionObj); break; } } } } // Connect child to parents for (JsonArray childConnection : childConnections) { for (String name : parentOutputPortNames) childConnection.add(new JsonPrimitive(name)); } // Connect parent to children for (JsonArray parentConnection : parentConnections) { for (String name : childInputPortNames) parentConnection.add(new JsonPrimitive(name)); } JsonArray ops = graph.get("operators").getAsJsonArray(); ops.remove(iso); } }
From source file:com.ibm.streamsx.topology.generator.spl.GraphUtilities.java
License:Open Source License
static void insertOperatorBetweenPorts(JsonObject input, JsonObject output, JsonObject op) { String oportName = jstring(output, "name"); String iportName = jstring(input, "name"); JsonObject opInput = op.get("inputs").getAsJsonArray().get(0).getAsJsonObject(); JsonObject opOutput = op.get("outputs").getAsJsonArray().get(0).getAsJsonObject(); String opIportName = jstring(opInput, "name"); String opOportName = jstring(opOutput, "name"); // Attach op in inputs and outputs JsonArray opInputConns = opInput.get("connections").getAsJsonArray(); JsonArray opOutputConns = opOutput.get("connections").getAsJsonArray(); boolean add = true; for (JsonElement conn : opInputConns) if (conn.getAsString().equals(oportName)) { add = false;//from ww w . j a v a 2 s . co m break; } if (add) opInputConns.add(new JsonPrimitive(oportName)); add = true; for (JsonElement conn : opOutputConns) if (conn.getAsString().equals(iportName)) { add = false; break; } opOutputConns.add(new JsonPrimitive(iportName)); JsonArray outputConns = output.get("connections").getAsJsonArray(); JsonArray inputConns = input.get("connections").getAsJsonArray(); for (int i = 0; i < outputConns.size(); i++) { if (outputConns.get(i).getAsString().equals(iportName)) outputConns.set(i, new JsonPrimitive(opIportName)); } for (int i = 0; i < inputConns.size(); i++) { if (inputConns.get(i).getAsString().equals(oportName)) inputConns.set(i, new JsonPrimitive(opOportName)); } }