I have mainly been a Java guy throughout my 8 years as a software developer. For most of the applications I have written, I used the Spring framework or Java EE. Lately, I am spending time learning web development in Python, and one thing that has impressed me a lot is the Flask framework. The Flask framework is a micro-framework which makes it very easy to write REST backends. Today for my 30 day challenge, I decided to find a Java alternative to Python's Flask framework. After doing some research, I discovered that the Dropwizard framework can help me achieve the same productivity as the Flask framework. In this blog, we will learn how to build a RESTful Java MongoDB application using Dropwizard.
What is Dropwizard?
Dropwizard is an open source Java framework for developing ops-friendly, high-performance RESTful backends. It was developed by Yammer to power their JVM based backend.
Dropwizard provides best-of-breed Java libraries into one embedded application package. It consists of following components :
Embedded Jetty : Every application is packaged as a jar instead of war file and starts its own embedded jetty container. There is no WAR file and no external servlet container.
JAX-RS : Jersey(the reference implementation for JAX-RS) is used to write RESTful web services. So, your existing JAX-RS knowledge is not wasted.
JSON : The REST services speaks JSON. Jackson library is used to do all the JSON processing.
Logging : It is done using Logback and SLF4J.
Hibernate Validator : Dropwizard uses Hibernate Validator API for declarative validation.
Metrics : Dropwizard has support for monitoring using the metrics library. It provides unparalleled insight into what our code does in production.
Dropwizard also uses some other libraries apart from the one mentioned above. You can find the full list here.
Why Dropwizard?
The reasons I decided to learn Dropwizard are mentioned below:
Quick Project Bootstrap : If you have worked with Spring or Java EE, you will understand the pain a developer has to go through to bootstrap a project. With Dropwizard, you just have to add one dependency in your pom.xml file, and you are done.
Application Metrics : Dropwizard comes with support for application metrics. It provides very useful information like request/response time etc. We just have to put @Timed annotation to get the method execution time.
Productivity : Every Dropwizard application has one main program which starts the jetty container. This means that we can run and debug the application as a main program from within the IDE. There is no need to recompile or redeploy the WAR file.
Github Repository
The code for today's demo application is available on github: day13-dropwizard-mongodb-demo-app.
Prerequisite
Basic Java knowledge is required.
Download and install the MongoDB database.
Install the latest Java Development Kit (JDK) on your operating system. We can either install OpenJDK 7 or Oracle JDK 7. OpenShift supports both OpenJDK 6 and 7. In this blog, we will be using JDK 7.
Download the latest Eclipse package for your operating system from the official Eclipse website. At the time of writing this blog, the latest Eclipse package is Kepler.
It is very easy to install eclipse, just extract the downloaded package, and we are done. On the linux or mac machines, open a new command line terminal and type the following command:
On windows, we can extract the zip file using winzip or 7-zip or any other software.
After we have extracted Eclipse, there will be a folder named eclipse in the directory where we extracted the download. We can optionally create a shortcut of the executable file.
Step 1: Create new Maven project
Open the Eclipse IDE and then navigate to the project workspace. To create a new project, Go to File > New > Maven Project. Choose the maven-archetype-quickstart, then enter Ground Id and Artifact Id, and finally press Finish.
Step 2 : Update the pom.xml
Now update the pom.xml file to include the dropwizard-core maven dependency. We will also update the Maven project to use Java version 1.7. After updating the pom.xml file, update the Maven Project(Right Click > Maven > Update Project)
Step 3 : Create Configuration class
Every Dropwizard application has one configuration class which specifies the environment specific parameters. Later in this blog post, we will add MongoDB configuration parameters like host, port, and db name to it.
This class extends the com.yammer.dropwizard.config.Configuration class.
Step 4 : Create a Service class
The Dropwizard project is bootstrapped by a service class. This class pulls together various bundles and commands which provide basic functionality. It also starts the embedded jetty server and extends com.yammer.dropwizard.Service.
The service class shown above does the following:
The class has a main method which acts as our service entry point. Inside the main method, we create an instance of BlogService and call the run method. We pass the server command as argument. The server command will start the embedded jetty server.
The initialize method is called before running the service run method. We set the name of service to blog.
Next, we have the run method which will be called when service runs. Later in this blog, We will add JAX-RS resources inside this method.
Step 5 : Write IndexResource
Let us write our first resource which will be invoked when a GET request is made to the '/' url. Create a new JAX-RS resource as shown below. This resource will list all the blogs.
The code shown above is a standard JAX-RS resource class. It is annotated with @Path annotation and defines index() method. The index() returns a collection of blogs. These blogs will be converted to JSON document. The @Timed annotation makes sure that Dropwizard infrastructure time this method.
The above mentioned IndexResource used a blog representation. It is shown as below. The Blog representation uses hibernate validator annotations to make sure the content is valid. For example, we use @URL annotation to make sure only valid URLs are stored in the MongoDB database.
Next, we register IndexResource in the service class run method. Update the run method in BlogService with the one shown below.
Now we can run the BlogService class as a main program i.e. Right Click > Run As > Java Application. It will start the embedded jetty container and we can see the application running at http://localhost:8080/.
The administrative interface is available at http://localhost:8081/.
We can check the metrics of the IndexResource by clicking Metrics. The data is available in JSON format.
Step 6 : Configuring MongoDB
Add the mongo-jackson-mapper dependency in pom.xml.
Update the BlogConfiguration class with MongoDB database details i.e. host, port, and database name.
Next we will create a new class named MongoManaged which allows us to manage resources on application start and stop. This implements com.yammer.dropwizard.lifecycle.Managed.
In the code shown above, we close the MongoDB connections in stop method.
Next we will write a MongoHealthCheck which will check if MongoDB is connected or not. A health check is Dropwizard feature to do a runtime test to verify the service’s behaviour in production environment.
Now we will update the BlogService class to include the MongoDB configuration.
In the code shown above :
A new Mongo instance is created using the BlogConfiguration object.
A new instance of MongoManaged is created and added to the environment.
A health check is added.
Run the application as a main program. You can check if MongoDB is running or not by going to the HealtCheck page loacated at http://localhost:8081/healthcheck. If MongoDB is not running, you will see an exception stacktrace.
Now start MongoDB and you should see the following.
Step 7 : Create BlogResource
Now we will write the BlogResource class which will be responsible for creating the blog entries.
Next we will update the BlogService run method to add BlogResource as well.
Run the BlogService class as a Java application. To test the BlogResource, make a curl request as shown below:
Step 8 : Update IndexResource
Now we will update the IndexResource index() method to get all the blog documents from MongoDB.
We will update the BlogService run method to pass the blogs collection to the IndexResource.
Run the BlogService class as a Java application. To test the BlogResource, make a curl request as shown below:
Step 9 : Deploy to the cloud
There is a community blog post which shows how we can deploy Dropwizard applications on OpenShift. You can read the blog here.
That's it for today. Keep giving feedback.
What's Next
Sign up for OpenShift Online
Get your own private Platform As a Service (PaaS) by evaluating OpenShift Enterprise
Need Help? Ask the OpenShift Community your questions in the forums
Showcase your awesome app in the OpenShift Developer Spotlight. Get in the OpenShift Application Gallery today.