Example usage for io.vertx.core.json JsonObject JsonObject

List of usage examples for io.vertx.core.json JsonObject JsonObject

Introduction

In this page you can find the example usage for io.vertx.core.json JsonObject JsonObject.

Prototype

public JsonObject() 

Source Link

Document

Create a new, empty instance

Usage

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);//from  ww w. j  a v  a 2 s.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.iot.i4.server.I4Server.java

private void loadData(MongoClient db) {
    /*/*from w ww. j a v a2 s.c o m*/
    db.dropCollection("users", drop -> {
    if (drop.failed()) {
        throw new RuntimeException(drop.cause());
    }
    List<JsonObject> users = new LinkedList<>();
    users.add(new JsonObject()
            .put("username", "mks")
            .put("firstName", "Siva")
            .put("lastName", "Kalidasan")
            .put("address", "India"));
    users.add(new JsonObject()
            .put("username", "timfox")
            .put("firstName", "Tim")
            .put("lastName", "Fox")
            .put("address", "The Moon"));
    for (JsonObject user : users) {
        db.insert("users", user, res -> {
            System.out.println("inserted " + user.encode());
        });
    }
    });*/

    List<JsonObject> users = new LinkedList<>();
    users.add(new JsonObject().put("username", "mks").put("firstName", "Siva").put("lastName", "Kalidasan")
            .put("address", "India"));
    users.add(new JsonObject().put("username", "timfox").put("firstName", "Tim").put("lastName", "Fox")
            .put("address", "The Moon"));
    for (JsonObject user : users) {
        //                db.insert("users", user, res -> {
        //                    System.out.println("inserted " + user.encode());
        //                });
    }

    //insert some payload
    List<JsonObject> payloads = new LinkedList<>();
    for (int i = 1; i <= 5000; i++) {
        payloads.add(new JsonObject().put("deviceId", "DEV0" + i).put("deviceName", "Arduino" + i)
                .put("hubId", "CBE0" + i).put("status", "On").put("receivedOn", new Date().toString()));
    }

    for (JsonObject payload : payloads) {
        db.insert("payloads", payload, res -> {
            //System.out.println("inserted " + payload.encode());
        });
    }
    System.out.println("inserted");
}

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;//from  ww w . j  a v a 2s  . co 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.childprocess.ProcessOptions.java

License:Apache License

public JsonObject toJson() {
    JsonObject json = new JsonObject();
    ProcessOptionsConverter.toJson(this, json);
    return json;
}

From source file:com.kumuluz.ee.samples.reactive.vertx.DiscoveryVerticle.java

License:MIT License

private void createServer() {
    HttpServer server = vertx.createHttpServer();
    Router router = Router.router(vertx);

    router.get("/").handler(routingContext -> {
        routingContext.response().end((new JsonObject().put("status", "UP")).toString());
    });//from w  ww  .  j  av  a 2  s  .c om

    router.get("/discover").handler(routingContext -> {
        getService(routingContext.response());
    });

    server.requestHandler(router::accept).listen(8082);
}

From source file:com.kumuluz.ee.samples.reactive.vertx.DiscoveryVerticle.java

License:MIT License

private void getService(HttpServerResponse response) {
    vertx.eventBus().send(REQUEST_ADDRESS, SERVICE, ar -> {
        if (ar.succeeded() && ar.result() != null) {
            JsonObject reply = (JsonObject) ar.result().body();
            response.end(reply.toString());
        } else {//from   www .j a  v  a 2s  .com
            response.end((new JsonObject().put("message", "Failed to retrieve service url.")).toString());
        }
    });
}

From source file:com.kumuluz.ee.samples.reactive.vertx.VertxResource.java

License:MIT License

@POST
@Path("publish")
public Response sendMessage(Message message) {
    tacos.send(message.getContent());//www . j a  v  a  2  s  .  c  o m

    JsonObject reponse = new JsonObject().put("message", message.getContent()).put("status", "sent");

    return Response.ok(reponse.encodePrettily()).build();
}

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);/* w  w w.j  a v a2 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);/*from   w w w.ja v a  2s .  co m*/
        }
    }

    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);// www.  ja  v a  2 s. c  om
        }
    }

    return matchesArr;
}