List of usage examples for io.vertx.core.json JsonObject put
public JsonObject put(String key, Object value)
From source file:com.iot.i4.server.I4Server.java
@Override public void start() throws Exception { // Create a mongo client using all defaults (connect to localhost and default port) using the database name "demo". JsonObject config = new JsonObject().put("connection_string", "mongodb://localhost:27017").put("db_name", "i4"); mongo = MongoClient.createShared(Vertx.vertx(), config); // the load function just populates some data on the storage loadData(mongo);/*ww w . j a va 2s .c om*/ Router router = Router.router(Vertx.vertx()); router.route().handler(BodyHandler.create()); //1.findAll payloads router.get("/api/payloads").handler(ctx -> { mongo.find("payloads", new JsonObject(), lookup -> { // error handling if (lookup.failed()) { ctx.fail(500); return; } // now convert the list to a JsonArray because it will be easier to encode the final object as the response. final JsonArray json = new JsonArray(); for (JsonObject o : lookup.result()) { json.add(o); } ctx.response().putHeader(HttpHeaders.CONTENT_TYPE, "application/json"); ctx.response().end(json.encode()); }); }); //1. findAll router.get("/api/users").handler(ctx -> { mongo.find("users", new JsonObject(), lookup -> { // error handling if (lookup.failed()) { ctx.fail(500); return; } // now convert the list to a JsonArray because it will be easier to encode the final object as the response. final JsonArray json = new JsonArray(); for (JsonObject o : lookup.result()) { json.add(o); } ctx.response().putHeader(HttpHeaders.CONTENT_TYPE, "application/json"); ctx.response().end(json.encode()); }); }); //2.findOne router.get("/api/users/:id").handler(ctx -> { mongo.findOne("users", new JsonObject().put("_id", ctx.request().getParam("id")), null, lookup -> { // error handling if (lookup.failed()) { ctx.fail(500); return; } JsonObject user = lookup.result(); if (user == null) { ctx.fail(404); } else { ctx.response().putHeader(HttpHeaders.CONTENT_TYPE, "application/json"); ctx.response().end(user.encode()); } }); }); router.post("/api/users").handler(ctx -> { JsonObject newUser = ctx.getBodyAsJson(); mongo.findOne("users", new JsonObject().put("username", newUser.getString("username")), null, lookup -> { // error handling if (lookup.failed()) { ctx.fail(500); return; } JsonObject user = lookup.result(); if (user != null) { // already exists ctx.fail(500); } else { mongo.insert("users", newUser, insert -> { // error handling if (insert.failed()) { ctx.fail(500); return; } // add the generated id to the user object newUser.put("_id", insert.result()); ctx.response().putHeader(HttpHeaders.CONTENT_TYPE, "application/json"); ctx.response().end(newUser.encode()); }); } }); }); router.put("/api/users/:id").handler(ctx -> { mongo.findOne("users", new JsonObject().put("_id", ctx.request().getParam("id")), null, lookup -> { // error handling if (lookup.failed()) { ctx.fail(500); return; } JsonObject user = lookup.result(); if (user == null) { // does not exist ctx.fail(404); } else { // update the user properties JsonObject update = ctx.getBodyAsJson(); user.put("username", update.getString("username")); user.put("firstName", update.getString("firstName")); user.put("lastName", update.getString("lastName")); user.put("address", update.getString("address")); mongo.replace("users", new JsonObject().put("_id", ctx.request().getParam("id")), user, replace -> { // error handling if (replace.failed()) { ctx.fail(500); return; } ctx.response().putHeader(HttpHeaders.CONTENT_TYPE, "application/json"); ctx.response().end(user.encode()); }); } }); }); router.delete("/api/users/:id").handler(ctx -> { mongo.findOne("users", new JsonObject().put("_id", ctx.request().getParam("id")), null, lookup -> { // error handling if (lookup.failed()) { ctx.fail(500); return; } JsonObject user = lookup.result(); if (user == null) { // does not exist ctx.fail(404); } else { mongo.remove("users", new JsonObject().put("_id", ctx.request().getParam("id")), remove -> { // error handling if (remove.failed()) { ctx.fail(500); return; } ctx.response().setStatusCode(204); ctx.response().end(); }); } }); }); // Create a router endpoint for the static content. router.route().handler(StaticHandler.create()); Vertx.vertx().createHttpServer().requestHandler(router::accept).listen(8080); //Vertx.vertx().createHttpServer().requestHandler(req -> req.response().end("Hello World From I4Server!")).listen(8080); System.out.println("Server started & listening to [8080]"); }
From source file:com.jedlab.vertee.DatabaseServiceVertxEBProxy.java
License:Apache License
public void persist(JsonObject document, Handler<AsyncResult<JsonObject>> resultHandle) { if (closed) { resultHandle.handle(Future.failedFuture(new IllegalStateException("Proxy is closed"))); return;/* www. ja v a 2 s . c o m*/ } JsonObject _json = new JsonObject(); _json.put("document", document); DeliveryOptions _deliveryOptions = (_options != null) ? new DeliveryOptions(_options) : new DeliveryOptions(); _deliveryOptions.addHeader("action", "persist"); _vertx.eventBus().<JsonObject>send(_address, _json, _deliveryOptions, res -> { if (res.failed()) { resultHandle.handle(Future.failedFuture(res.cause())); } else { resultHandle.handle(Future.succeededFuture(res.result().body())); } }); }
From source file:com.julienviet.aeron.client.AeronClientOptionsConverter.java
License:Apache License
public static void toJson(AeronClientOptions obj, JsonObject json) { if (obj.getDirectory() != null) { json.put("directory", obj.getDirectory()); }//from w w w . j a va2s.com }
From source file:com.nasa.ElasticSearchAdapter.java
public JsonObject getSymptoms(String word) throws IOException { JsonObject result = new JsonObject(); JsonArray matchesArr = new JsonArray(); String data = "{\n" + " \"size\": 0,\n" + " \"aggs\" : {\n" + " \"langs\" : {\n" + " \"terms\" : { \"field\" : \"symptoms.name\" }\n" + " }\n" + " }\n" + "}"; JsonObject response = doPost(ES_URL + "/healthy-travel/feedback/_search", data); JsonArray items = response.getJsonObject("aggregations").getJsonObject("langs").getJsonArray("buckets"); for (Object item : items) { JsonObject obj = (JsonObject) item; String key = obj.getString("key"); if (key != null && obj.getString("key").startsWith(word)) { matchesArr.add(key);/*from w ww .j a v a 2 s .com*/ } } result.put("symptoms", matchesArr); return result; }
From source file:com.nasa.ElasticSearchAdapter.java
public JsonObject getConditions(String word) throws IOException { JsonObject result = new JsonObject(); JsonArray matchesArr = new JsonArray(); String data = "{\n" + " \"size\": 0,\n" + " \"aggs\" : {\n" + " \"langs\" : {\n" + " \"terms\" : { \"field\" : \"condition\" }\n" + " }\n" + " }\n" + "}"; JsonObject response = doPost(ES_URL + "/healthy-travel/feedback/_search", data); JsonArray items = response.getJsonObject("aggregations").getJsonObject("langs").getJsonArray("buckets"); for (Object item : items) { JsonObject obj = (JsonObject) item; String key = obj.getString("key"); if (key != null && obj.getString("key").startsWith(word)) { matchesArr.add(key);/*w ww. j ava2s . c om*/ } } result.put("conditions", matchesArr); return result; }
From source file:com.nasa.ElasticSearchAdapter.java
public JsonArray getCheck(Float lat, Float lon) throws IOException { JsonArray matchesArr = new JsonArray(); String data = "{\n" + " \"size\": 0,\n" + " \"query\": {\n" + " \"filtered\": {\n" + " \"query\": {\n" + " \"match_all\": {}\n" + " },\n" + " \"filter\": {\n" + " \"geo_distance\": {\n" + " \"distance\": \"100km\",\n" + " \"location\": {\n" + " \"lat\": " + lat + ",\n" + " \"lon\": " + lon + "\n" + " }\n" + " }\n" + " }\n" + " }\n" + " },\n" + " \"aggs\": {\n" + " \"langs\": {\n" + " \"terms\": {\n" + " \"field\": \"condition\"\n" + " }\n" + " }\n" + " }\n" + "}"; JsonObject response = doPost(ES_URL + "/healthy-travel/feedback/_search", data); JsonArray items = response.getJsonObject("aggregations").getJsonObject("langs").getJsonArray("buckets"); for (Object item : items) { JsonObject obj = (JsonObject) item; String key = obj.getString("key"); int value = obj.getInteger("doc_count"); if (key != null && value > 0) { JsonObject cond = new JsonObject(); cond.put("name", key); cond.put("reported_cases", value); matchesArr.add(cond);/*from w w w . j a v a2 s. c o m*/ } } return matchesArr; }
From source file:com.nasa.ElasticSearchAdapter.java
public JsonObject postFeedback(JsonObject feedback) throws IOException { JsonObject result = new JsonObject(); String data = feedback.toString(); // normalize or remove non ascii characters data = Normalizer.normalize(data, Normalizer.Form.NFD); data = data.replaceAll("[^\\x00-\\x7F]", ""); JsonObject response = doPost(ES_URL + "/healthy-travel/feedback", data); result.put("success", response.getJsonObject("_shards").getInteger("successful") > 0); return result; }
From source file:com.nasa.ESWorkerVerticle.java
@Override public void start() throws Exception { EventBus eb = vertx.eventBus();// ww w . j a v a 2 s . c o m eb.consumer("bus.symptoms").handler(message -> { String text = ((JsonObject) message.body()).getString("text"); JsonObject result = null; try { if (text != null) { result = es.getSymptoms(text); } } catch (Exception ex) { result = new JsonObject(); result.put("symptoms", new JsonArray()); } message.reply(result); }); eb.consumer("bus.conditions").handler(message -> { String text = ((JsonObject) message.body()).getString("text"); JsonObject result = null; try { if (text != null) { result = es.getConditions(text); } } catch (Exception ex) { result = new JsonObject(); result.put("conditions", new JsonArray()); } message.reply(result); }); eb.consumer("bus.map.weather").handler(message -> { String lat = ((JsonObject) message.body()).getString("lat"); String lon = ((JsonObject) message.body()).getString("lon"); String zoom = ((JsonObject) message.body()).getString("zoom"); String count = ((JsonObject) message.body()).getString("count"); JsonObject result = null; try { if (lat != null && lon != null && zoom != null) { result = Transformer.weatherToMap(es.getMap(lat, lon, zoom, count)); } else { throw new IllegalArgumentException("incorrect weather params: " + message.body().toString()); } } catch (Exception ex) { ex.printStackTrace(); result = new JsonObject(); result.put("type", "FeatureCollection"); result.put("features", new JsonArray()); } message.reply(result); }); eb.consumer("bus.map.pollution").handler(message -> { String lat = ((JsonObject) message.body()).getString("lat"); String lon = ((JsonObject) message.body()).getString("lon"); String zoom = ((JsonObject) message.body()).getString("zoom"); String count = ((JsonObject) message.body()).getString("count"); System.out.println("Worker: " + message.body()); JsonObject result = null; try { if (lat != null && lon != null && zoom != null) { result = Transformer.pollutionToMap(es.getMap(lat, lon, zoom, count)); } else { throw new IllegalArgumentException("incorrect pollution params: " + message.body().toString()); } } catch (Exception ex) { ex.printStackTrace(); result = new JsonObject(); result.put("type", "FeatureCollection"); result.put("features", new JsonArray()); } message.reply(result); }); eb.consumer("bus.map.condition").handler(message -> { String lat = ((JsonObject) message.body()).getString("lat"); String lon = ((JsonObject) message.body()).getString("lon"); String zoom = ((JsonObject) message.body()).getString("zoom"); String count = ((JsonObject) message.body()).getString("count"); JsonObject result = null; try { if (lat != null && lon != null && zoom != null) { result = Transformer.conditionToMap(es.getMap(lat, lon, zoom, count)); } else { throw new IllegalArgumentException("incorrect condition params: " + message.body().toString()); } } catch (Exception ex) { ex.printStackTrace(); result = new JsonObject(); result.put("type", "FeatureCollection"); result.put("features", new JsonArray()); } message.reply(result); }); eb.consumer("bus.check").handler(message -> { Float lat = Float.parseFloat(((JsonObject) message.body()).getString("lat")); Float lon = Float.parseFloat(((JsonObject) message.body()).getString("lon")); JsonObject result = new JsonObject(); Gson gson = new Gson(); try { JsonArray matchesArr = new JsonArray(); if (lat != null && lon != null) { matchesArr = es.getCheck(lat, lon); result.put("conditions", matchesArr); } OtherOmwClient owm = new OtherOmwClient(); BreezoMeterClient bm = new BreezoMeterClient(); JsonObject weatherJ = owm.currentWeather(lat, lon); JsonObject pollutionJ = bm.currentAirQualityAtPoint(lat, lon); Weather weather = owm.toWeather(weatherJ); if (weather != null) { result.put("weather", new JsonObject(gson.toJson(weather))); } Pollution pollution = bm.toPollution(pollutionJ); if (pollution != null) { result.put("pollution", new JsonObject(gson.toJson(pollution))); } } catch (Exception ex) { result = new JsonObject(); result.put("conditions", new JsonArray()); result.put("weather", new JsonObject()); result.put("pollution", new JsonObject()); } message.reply(result); }); eb.consumer("bus.feedback").handler(message -> { JsonObject userFeedback = (JsonObject) message.body(); JsonObject result = new JsonObject(); try { Gson gson = new Gson(); Feedback feedback = gson.fromJson(userFeedback.toString(), Feedback.class); float lat = feedback.getLocation().getLat(); float lon = feedback.getLocation().getLon(); OtherOmwClient owm = new OtherOmwClient(); JsonObject owmData = owm.currentWeather(lat, lon); feedback.setWeather(owm.toWeather(owmData)); BreezoMeterClient bm = new BreezoMeterClient(); JsonObject bmData = bm.currentAirQualityAtPoint(lat, lon); feedback.setPollution(bm.toPollution(bmData)); result = es.postFeedback(new JsonObject(gson.toJson(feedback))); } catch (Exception ex) { ex.printStackTrace(); result.put("success", false); } message.reply(result); }); }
From source file:com.nasa.Transformer.java
public static JsonObject weatherToMap(JsonObject jsonObject) { JsonObject result = new JsonObject(); JsonArray featuresArr = new JsonArray(); JsonArray items = jsonObject.getJsonObject("hits").getJsonArray("hits"); int idx = 0;//from ww w .ja va2 s . c om for (Object hit : items) { JsonObject source = ((JsonObject) hit).getJsonObject("_source"); JsonObject feature = new JsonObject(); feature.put("type", "Feature"); feature.put("id", idx); JsonObject properties = new JsonObject(); float mag = source.getJsonObject("weather").getFloat("temp"); properties.put("mag", mag); feature.put("properties", properties); JsonObject geometry = new JsonObject(); geometry.put("type", "Point"); JsonArray coordinates = new JsonArray(); Float lon = source.getJsonObject("location").getFloat("lon"); Float lat = source.getJsonObject("location").getFloat("lat"); coordinates.add(lon); coordinates.add(lat); geometry.put("coordinates", coordinates); feature.put("geometry", geometry); featuresArr.add(feature); idx++; } result.put("type", "FeatureCollection"); result.put("features", featuresArr); return result; }
From source file:com.nasa.Transformer.java
public static JsonObject pollutionToMap(JsonObject jsonObject) { JsonObject result = new JsonObject(); JsonArray featuresArr = new JsonArray(); JsonArray items = jsonObject.getJsonObject("hits").getJsonArray("hits"); int idx = 0;/* w w w .ja v a 2 s .c o m*/ for (Object hit : items) { JsonObject source = ((JsonObject) hit).getJsonObject("_source"); JsonObject feature = new JsonObject(); feature.put("type", "Feature"); feature.put("id", idx); JsonObject properties = new JsonObject(); float mag = source.getJsonObject("pollution").getFloat("aqi"); properties.put("mag", mag); feature.put("properties", properties); JsonObject geometry = new JsonObject(); geometry.put("type", "Point"); JsonArray coordinates = new JsonArray(); Float lon = source.getJsonObject("location").getFloat("lon"); Float lat = source.getJsonObject("location").getFloat("lat"); coordinates.add(lon); coordinates.add(lat); geometry.put("coordinates", coordinates); feature.put("geometry", geometry); featuresArr.add(feature); idx++; } result.put("type", "FeatureCollection"); result.put("features", featuresArr); return result; }