...
Initialize the HTTP Client and HTTP POST method as follows.
Code Block language java HttpClient httpClient = new SystemDefaultHttpClient(); HttpPost method = new HttpPost(url);
Then we need to build event as a JSON object. Here We have used JsonObject class provided by gson library. Main JSON event could consist of 3 JSON objects for meta, correlation and payload data. We can include required properties and their values for each object. JSON event format should be as follows whereas event object is consist of metaData, correlationData and payloadData objects. Each object has set of properties and values.
Code Block language java { "event":{ "metaData":{ "timestamp":1442921557056, "isPowerSaverEnabled":false, "sensorId":100, "sensorName":"temperature" }, "correlationData":{ "longitude":2332.424, "latitude":2323.23232 }, "payloadData":{ "humidity":2.3, "sensorValue":23423.234 } } }
You can use above event as a string or else you can even build JSON object by using a parser like gson and convert it as a string.
Code Block language java JsonObject event = new JsonObject(); JsonObject metaData = new JsonObject(); JsonObject correlationData = new JsonObject(); JsonObject payLoadData = new JsonObject(); metaData.addProperty("timestamp", System.currentTimeMillis()); metaData.addProperty("isPowerSaverEnabled", false); metaData.addProperty("sensorId", count); metaData.addProperty("sensorName", "temperature"); correlationData.addProperty("longitude", 2332.424); correlationData.addProperty("latitude", 2323.23232); payLoadData.addProperty("humidity", 2.3f); payLoadData.addProperty("sensorValue", 23423.234); event.add("metaData", metaData); event.add("correlationData", correlationData); event.add("payloadData", payLoadData); String eventString = "{\"event\": " + event + "}";
Once JSON Object String is created, it will be converted as a StringEntity by enclosing as event object. StringEntity is a class provided by apache HTTP library. This entity will be set to HTTP method.
Code Block language java StringEntity entity = new StringEntity("{\"event\": " + event + "}");eventString); method.setEntity(entity);
If URL endpoint is https, we need to add Authorization Basic header by encoding username and password. Finally we will use HTTP client to execute defined HTTP Method.
Code Block language java if (url.startsWith("https")) { method.setHeader("Authorization", "Basic " + Base64.encode((username + ":" + password).getBytes())); } httpClient.execute(method).getEntity().getContent().close();
Info For more information on the usage of data publishers, see the sample producer in the
<CEP_HOME>/samples/producers/http/
directory.