Search in sources :

Example 66 with JsonArray

use of io.vertx.core.json.JsonArray in project vertx-examples by vert-x3.

the class SimpleREST method handleListProducts.

private void handleListProducts(RoutingContext routingContext) {
    JsonArray arr = new JsonArray();
    products.forEach((k, v) -> arr.add(v));
    routingContext.response().putHeader("content-type", "application/json").end(arr.encodePrettily());
}
Also used : JsonArray(io.vertx.core.json.JsonArray)

Example 67 with JsonArray

use of io.vertx.core.json.JsonArray in project vertx-examples by vert-x3.

the class Server method start.

@Override
public void start() throws Exception {
    // Create a mongo client using all defaults (connect to localhost and default port) using the database name "demo".
    mongo = MongoClient.createShared(vertx, new JsonObject().put("db_name", "demo"));
    // the load function just populates some data on the storage
    loadData(mongo);
    Router router = Router.router(vertx);
    router.route().handler(BodyHandler.create());
    // define some REST API
    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());
        });
    });
    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.createHttpServer().requestHandler(router::accept).listen(8080);
}
Also used : JsonArray(io.vertx.core.json.JsonArray) JsonObject(io.vertx.core.json.JsonObject) Router(io.vertx.ext.web.Router)

Example 68 with JsonArray

use of io.vertx.core.json.JsonArray in project vertx-examples by vert-x3.

the class Server method start.

@Override
public void start() throws Exception {
    // To simplify the development of the web components we use a Router to route all HTTP requests
    // to organize our code in a reusable way.
    final Router router = Router.router(vertx);
    // In order to use a template we first need to create an engine
    final HandlebarsTemplateEngine engine = HandlebarsTemplateEngine.create();
    // Entry point to the application, this will render a custom template.
    router.get().handler(ctx -> {
        // we define a hardcoded title for our application
        ctx.put("title", "Seasons of the year");
        // we define a hardcoded array of json objects
        JsonArray seasons = new JsonArray();
        seasons.add(new JsonObject().put("name", "Spring"));
        seasons.add(new JsonObject().put("name", "Summer"));
        seasons.add(new JsonObject().put("name", "Autumn"));
        seasons.add(new JsonObject().put("name", "Winter"));
        ctx.put("seasons", seasons);
        // and now delegate to the engine to render it.
        engine.render(ctx, "templates/index.hbs", res -> {
            if (res.succeeded()) {
                ctx.response().end(res.result());
            } else {
                ctx.fail(res.cause());
            }
        });
    });
    // start a HTTP web server on port 8080
    vertx.createHttpServer().requestHandler(router::accept).listen(8080);
}
Also used : JsonArray(io.vertx.core.json.JsonArray) Router(io.vertx.ext.web.Router) JsonObject(io.vertx.core.json.JsonObject) HandlebarsTemplateEngine(io.vertx.ext.web.templ.HandlebarsTemplateEngine)

Example 69 with JsonArray

use of io.vertx.core.json.JsonArray in project vertx-examples by vert-x3.

the class Server method listAlbums.

private void listAlbums(Message<JsonObject> msg) {
    // issue a find command to mongo to fetch all documents from the "albums" collection.
    mongo.find("albums", new JsonObject(), lookup -> {
        // error handling
        if (lookup.failed()) {
            msg.fail(500, lookup.cause().getMessage());
            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);
        }
        msg.reply(json);
    });
}
Also used : JsonArray(io.vertx.core.json.JsonArray) JsonObject(io.vertx.core.json.JsonObject)

Example 70 with JsonArray

use of io.vertx.core.json.JsonArray in project rulesservice by genny-project.

the class QRules method publishData.

public void publishData(final QEventLinkChangeMessage cmdMsg, final String[] recipientsCode) {
    JsonArray recipients = new JsonArray();
    if (recipientsCode != null) {
        for (String recipientCode : recipientsCode) {
            if (recipientCode != null) {
                recipients.add(recipientCode);
            }
        }
    }
    JsonObject json = new JsonObject(JsonUtils.toJson(cmdMsg));
    json.put("recipientCodeArray", recipients);
    publish("data", json);
}
Also used : JsonArray(io.vertx.core.json.JsonArray) JsonObject(io.vertx.core.json.JsonObject)

Aggregations

JsonArray (io.vertx.core.json.JsonArray)535 JsonObject (io.vertx.core.json.JsonObject)379 Test (org.junit.Test)185 List (java.util.List)69 ArrayList (java.util.ArrayList)66 Map (java.util.Map)52 Handler (io.vertx.core.Handler)49 HashMap (java.util.HashMap)42 Collectors (java.util.stream.Collectors)42 Test (org.junit.jupiter.api.Test)41 Future (io.vertx.core.Future)37 IOException (java.io.IOException)35 AsyncResult (io.vertx.core.AsyncResult)34 Buffer (io.vertx.core.buffer.Buffer)33 HttpURLConnection (java.net.HttpURLConnection)30 StandardCharsets (java.nio.charset.StandardCharsets)29 RoutingContext (io.vertx.ext.web.RoutingContext)26 Objects (java.util.Objects)25 Instant (java.time.Instant)24 Rule (org.junit.Rule)22