Search in sources :

Example 11 with MongoClient

use of io.vertx.ext.mongo.MongoClient in project vertx-examples by vert-x3.

the class MongoClientVerticle method start.

@Override
public void start() throws Exception {
    JsonObject config = Vertx.currentContext().config();
    String uri = config.getString("mongo_uri");
    if (uri == null) {
        uri = "mongodb://localhost:27017";
    }
    String db = config.getString("mongo_db");
    if (db == null) {
        db = "test";
    }
    JsonObject mongoconfig = new JsonObject().put("connection_string", uri).put("db_name", db);
    MongoClient mongoClient = MongoClient.createShared(vertx, mongoconfig);
    JsonObject product1 = new JsonObject().put("itemId", "12345").put("name", "Cooler").put("price", "100.0");
    mongoClient.save("products", product1, id -> {
        System.out.println("Inserted id: " + id.result());
        mongoClient.find("products", new JsonObject().put("itemId", "12345"), res -> {
            System.out.println("Name is " + res.result().get(0).getString("name"));
            mongoClient.remove("products", new JsonObject().put("itemId", "12345"), rs -> {
                if (rs.succeeded()) {
                    System.out.println("Product removed ");
                }
            });
        });
    });
}
Also used : MongoClient(io.vertx.ext.mongo.MongoClient) JsonObject(io.vertx.core.json.JsonObject)

Example 12 with MongoClient

use of io.vertx.ext.mongo.MongoClient 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".
    final MongoClient mongo = MongoClient.createShared(vertx, new JsonObject().put("db_name", "demo"));
    // In order to use a JADE template we first need to create an engine
    final JadeTemplateEngine jade = JadeTemplateEngine.create(vertx);
    // 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);
    // Enable the body parser to we can get the form data and json documents in out context.
    router.route().handler(BodyHandler.create());
    // Entry point to the application, this will render a custom JADE template.
    router.get("/").handler(ctx -> {
        // we define a hardcoded title for our application
        JsonObject data = new JsonObject().put("title", "Vert.x Web");
        // and now delegate to the engine to render it.
        jade.render(data, "templates/index.jade", res -> {
            if (res.succeeded()) {
                ctx.response().putHeader(HttpHeaders.CONTENT_TYPE, "text/html").end(res.result());
            } else {
                ctx.fail(res.cause());
            }
        });
    });
    // and now we mount the handlers in their appropriate routes
    // Read all users from the mongo collection.
    router.get("/users").handler(ctx -> {
        // issue a find command to mongo to fetch all documents from the "users" collection.
        mongo.find("users", new JsonObject(), lookup -> {
            // error handling
            if (lookup.failed()) {
                ctx.fail(lookup.cause());
                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);
            }
            // since we are producing json we should inform the browser of the correct content type.
            ctx.response().putHeader(HttpHeaders.CONTENT_TYPE, "application/json");
            // encode to json string
            ctx.response().end(json.encode());
        });
    });
    // Create a new document on mongo.
    router.post("/users").handler(ctx -> {
        // since jquery is sending data in multipart-form format to avoid preflight calls, we need to convert it to JSON.
        JsonObject user = new JsonObject().put("username", ctx.request().getFormAttribute("username")).put("email", ctx.request().getFormAttribute("email")).put("fullname", ctx.request().getFormAttribute("fullname")).put("location", ctx.request().getFormAttribute("location")).put("age", ctx.request().getFormAttribute("age")).put("gender", ctx.request().getFormAttribute("gender"));
        // insert into mongo
        mongo.insert("users", user, lookup -> {
            // error handling
            if (lookup.failed()) {
                ctx.fail(lookup.cause());
                return;
            }
            // inform that the document was created
            ctx.response().setStatusCode(201);
            ctx.response().end();
        });
    });
    // Remove a document from mongo.
    router.delete("/users/:id").handler(ctx -> {
        // catch the id to remove from the url /users/:id and transform it to a mongo query.
        mongo.removeOne("users", new JsonObject().put("_id", ctx.request().getParam("id")), lookup -> {
            // error handling
            if (lookup.failed()) {
                ctx.fail(lookup.cause());
                return;
            }
            // inform the browser that there is nothing to return.
            ctx.response().setStatusCode(204);
            ctx.response().end();
        });
    });
    // Serve the non private static pages
    router.route().handler(StaticHandler.create());
    // start a HTTP web server on port 8080
    vertx.createHttpServer().requestHandler(router).listen(8080);
}
Also used : JsonArray(io.vertx.core.json.JsonArray) MongoClient(io.vertx.ext.mongo.MongoClient) JadeTemplateEngine(io.vertx.ext.web.templ.jade.JadeTemplateEngine) JsonObject(io.vertx.core.json.JsonObject) Router(io.vertx.ext.web.Router)

Example 13 with MongoClient

use of io.vertx.ext.mongo.MongoClient in project vertx-examples by vert-x3.

the class Client method start.

@Override
@Suspendable
public void start() throws Exception {
    JsonObject config = new JsonObject().put("connection_string", "mongodb://localhost:27018").put("db_name", "my_DB");
    // Deploy an embedded mongo database so we can test against that, this can be disabled using embedded-mongo.skip
    if (!Boolean.getBoolean("embedded-mongo.skip")) {
        String deploymentID = awaitResult(h -> vertx.deployVerticle("service:io.vertx.vertx-mongo-embedded-db", h));
        System.out.println("dep id of embedded mongo verticle is " + deploymentID);
    }
    // Create the client
    MongoClient mongo = MongoClient.createShared(vertx, config);
    // Create a collection
    Void v = awaitResult(h -> mongo.createCollection("users", h));
    // Insert some docs:
    List<JsonObject> users = Arrays.asList(new JsonObject().put("username", "temporalfox").put("firstname", "Julien").put("password", "bilto"), new JsonObject().put("username", "purplefox").put("firstname", "Tim").put("password", "wibble"));
    for (JsonObject user : users) {
        String id = awaitResult(h -> mongo.insert("users", user, h));
        System.out.println("Inserted id is " + id);
    }
    // Now query them
    List<JsonObject> results = awaitResult(h -> mongo.find("users", new JsonObject(), h));
    System.out.println("Retrieved " + results.size() + " results");
    // Print them
    results.forEach(System.out::println);
}
Also used : MongoClient(io.vertx.ext.mongo.MongoClient) JsonObject(io.vertx.core.json.JsonObject) Suspendable(co.paralleluniverse.fibers.Suspendable)

Aggregations

JsonObject (io.vertx.core.json.JsonObject)13 MongoClient (io.vertx.ext.mongo.MongoClient)13 Truth.assertThat (com.google.common.truth.Truth.assertThat)7 NoopSpan (io.opentracing.noop.NoopSpan)7 Future (io.vertx.core.Future)7 Timeout (io.vertx.junit5.Timeout)7 VertxExtension (io.vertx.junit5.VertxExtension)7 VertxTestContext (io.vertx.junit5.VertxTestContext)7 Optional (java.util.Optional)7 TimeUnit (java.util.concurrent.TimeUnit)7 BeforeEach (org.junit.jupiter.api.BeforeEach)7 Test (org.junit.jupiter.api.Test)7 ExtendWith (org.junit.jupiter.api.extension.ExtendWith)7 ArgumentMatchers.any (org.mockito.ArgumentMatchers.any)7 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)7 Mockito.mock (org.mockito.Mockito.mock)7 Mockito.when (org.mockito.Mockito.when)7 FindOptions (io.vertx.ext.mongo.FindOptions)6 UpdateOptions (io.vertx.ext.mongo.UpdateOptions)6 Instant (java.time.Instant)6