vert.x and MongoDB – The quick intro

Finally I got some small amount of time to give it a try to MongoDB module for vert.x.

The sample code can be found in github and describes how to:

– Deploy MongoDB module
– Add, remove and query data from the database
– Use event bus for asynchronous app notification

package org.riaconnection.vertx.server;

import org.vertx.java.core.Handler;
import org.vertx.java.core.eventbus.EventBus;
import org.vertx.java.core.eventbus.Message;
import org.vertx.java.core.http.HttpServer;
import org.vertx.java.core.http.HttpServerRequest;
import org.vertx.java.core.json.JsonArray;
import org.vertx.java.core.json.JsonObject;
import org.vertx.java.core.logging.Logger;
import org.vertx.java.deploy.Verticle;

public class MongoTest extends Verticle {

	private Logger logger;

	private static String pa = "vertx.mongopersistor";
	private static String appNotify = "app.notify";
	private static String DB_LOADED = "db.loaded";
	private EventBus eb;

	@Override
	public void start() throws Exception {

		logger = container.getLogger();

		eb = vertx.eventBus();

		// Deploy MongoDB module and load some sample data into it
		container.deployModule("vertx.mongo-persistor-v1.0", null, 1,
				new Handler<String>() {

					@Override
					public void handle(String info) {

						// Remove all data from collection
						JsonObject delete = new JsonObject();
						delete.putString("action", "delete");
						delete.putString("collection", "teams");
						delete.putObject("matcher", new JsonObject("{}"));

						eb.send(pa, delete);

						// Add new entries to collection
						String[] teams = { "Benfica", "Sporting", "Porto" };

						JsonObject team = new JsonObject();
						JsonObject entry = new JsonObject();
						entry.putString("action", "save");
						entry.putString("collection", "teams");

						for (String name : teams) {
							team.putString("name", name);
							entry.putObject("document", team);
							eb.send(pa, entry);
						}

						// Notify app that data has been loaded
						eb.send(appNotify, DB_LOADED);
					}
				});

		// Register for app notifications
		eb.registerHandler(appNotify, new Handler<Message<String>>() {

			@Override
			public void handle(Message<String> message) {

				logger.info("Notification message received: "
						+ message.body.toString());

				// If db loaded then query for all items in collection
				if (message.body.equals(DB_LOADED)) {
					JsonObject find = new JsonObject();
					find.putString("action", "find");
					find.putString("collection", "teams");
					find.putObject("matcher", new JsonObject());

					eb.send(pa, find, new Handler<Message<JsonObject>>() {

						@Override
						public void handle(Message<JsonObject> req) {

							JsonArray entries = req.body.getArray("results");
							for (Object obj : entries) {
								JsonObject entry = (JsonObject) obj;
								logger.info("name: " + entry.getString("name")
										+ ", id: " + entry.getString("_id"));
							}
						}
					});
				}
			}

		});

		// Create HTTP server
		HttpServer server = vertx.createHttpServer();

		// Register HTTP container
		server.requestHandler(new Handler<HttpServerRequest>() {

			@Override
			public void handle(HttpServerRequest req) {
				String file = req.path.equals("/") ? "index.html" : req.path;
				req.response.sendFile("webroot/" + file);
			}

		});

		server.listen(8080, "localhost");

	}
}
Advertisements

About CrazyPenguin

Software Engineer
This entry was posted in Java, JavaScript, Vert.X IO. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s