Table of Contents
In this post, we will see about Dropwizard tutorial.
Dropwizard is java framework to develop high-performance restful web services faster. It will use some of the stable libraries to create simple,light-weight package so that you can actually focus on business logic rather than worrying about configuration.
Dropwizard provides out of the box support for configuration, application metrics, logging and many other operational tools.
It will help you to create production-ready web services in the shortest time possible.
Libraries used by Dropwizard
Jetty for HTTP
Dropwizard uses jetty as embed HTTP server for your projects.Dropwizard project will have main method which will start HTTP server and you can start your application seamlessly.
Jersey for rest
Dropwizard uses jersey library to create restful web application. This allows creating clean and testable classes which map HTTP requests to simple java objects.
Jackson for JSON
Jackson is well know library for mapping JSON data to java objects.Dropwizard uses Jackson for all JSON related conversions.
Other libraries
Metrics – library for providing JVM- and application-level metrics for monitoring
Guava – utility library
Logback and sl4j – logging library
Hibernate validator – Hibernate validator provides easy way to validate user input and generating helpful error messages.
Apache HttpClient and Jersey clients
JDBI Library to use relational databases.
Liquidbase – It is an open source database-independent library for tracking, managing and applying database schema changes.
Freemarker and mustache – simple templating system for UI
Joda time – Library for handling dates and time.
Let’s start with Dropwizard hello world example. In this tutorial, we will create simple Rest CRUD example.
Maven dependencies
2)Â We need to add Dropwizard core dependency in the classpath.
1 2 3 4 5 6 7 |
<dependency> <groupId>io.dropwizard</groupId> <artifactId>dropwizard-core</artifactId> <version>${dropwizard.version}</version> </dependency> |
Here is complete pom.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.arpit.java2blog</groupId> <artifactId>DropwizardHelloWordExample</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>DropwizardHelloWordExample</name> <url>http://maven.apache.org</url> <properties> <dropwizard.version>1.0.3</dropwizard.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>io.dropwizard</groupId> <artifactId>dropwizard-core</artifactId> <version>${dropwizard.version}</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies> <build> <finalName>DropWizardExample-{version}</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> <version>2.1</version> <executions> <execution> <phase>package</phase> <goals> <goal>shade</goal> </goals> <configuration> <transformers> <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer"> <mainClass>org.arpit.java2blog.Application</mainClass> </transformer> <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"> </transformer> </transformers> </configuration> </execution> </executions> </plugin> </plugins> </build> </project> |
Create bean class
3)Â Create a bean name "Country.java" in org.arpit.java2blog.model.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
package org.arpit.java2blog.model; public class Book{ int id; String title; long pages; public Book() { } public Book(int id, String title, long pages) { super(); this.id = id; this.title = title; this.pages = pages; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public long getPages() { return pages; } public void setPages(long pages) { this.pages = pages; } } |
Create Controller
4) Create a controller named "BookController.java" in package org.arpit.java2blog.controller.Please note that we will use JAXRS annotations over here.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
package org.arpit.java2blog.controller; import java.util.List; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.arpit.java2blog.model.Book; import org.arpit.java2blog.service.BookService; @Path("bookService") @Produces(MediaType.APPLICATION_JSON) public class BookController { BookService bookService = new BookService(); @Path("/books") @GET public List<Book> getBooks() { List<Book> listOfBooks = bookService.getAllBooks(); return listOfBooks; } @Path("/book/{id}") @GET public Book getBookById(@PathParam(value = "id") int id) { return bookService.getBook(id); } @Consumes(MediaType.APPLICATION_JSON) @Path("/books") @POST public Book addBook(Book Book) { return bookService.addBook(Book); } @Path("/books") @PUT @Consumes(MediaType.APPLICATION_JSON) public Book updateBook(Book Book) { return bookService.updateBook(Book); } @Produces(MediaType.APPLICATION_JSON) @Path("/book/{id}") @DELETE public void deleteBook(@PathParam(value = "id")int id) { bookService.deleteBook(id); } } |
Create Service class
It is just a helper class which should be replaced by database implementation. It is not very well written class, it is just used for demonstration.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 |
package org.arpit.java2blog.service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.arpit.java2blog.model.Book; /* * It is just a helper class which should be replaced by database implementation. * It is not very well written class, it is just used for demonstration. */ public class BookService { static HashMap<Integer,Book> BookIdMap=getBookIdMap(); public BookService() { super(); if(BookIdMap==null) { BookIdMap=new HashMap<Integer,Book>(); // Creating some objects of Book while initializing Book javaBook=new Book(1, "Head first java",400); Book springBook=new Book(4, "Spring in action",500); Book pythonBook=new Book(3, "Learning Python",250); Book hiberanteBook=new Book(2, "Hibernate in action",300); BookIdMap.put(1,javaBook); BookIdMap.put(4,springBook); BookIdMap.put(3,pythonBook); BookIdMap.put(2,hiberanteBook); } } public List<Book> getAllBooks() { List<Book> books = new ArrayList<>(BookIdMap.values()); return books; } public Book getBook(int id) { Book Book= BookIdMap.get(id); return Book; } public Book addBook(Book Book) { Book.setId(getMaxId()+1); BookIdMap.put(Book.getId(), Book); return Book; } public Book updateBook(Book Book) { if(Book.getId()<=0) return null; BookIdMap.put(Book.getId(), Book); return Book; } public void deleteBook(int id) { BookIdMap.remove(id); } public static HashMap<Integer, Book> getBookIdMap() { return BookIdMap; } // Utility method to get max id public static int getMaxId() { int max=0; for (int id:BookIdMap.keySet()) { if(max<=id) max=id; } return max; } } |
Create Dropwizard main class
6) Let’s create DropwizardApplication.java. This is the class which we will run to start our application.When you run the application, it will automatically start embedded Jetty server.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
package org.arpit.java2blog; import org.arpit.java2blog.controller.BookController; import io.dropwizard.Application; import io.dropwizard.Configuration; import io.dropwizard.setup.Bootstrap; import io.dropwizard.setup.Environment; public class DropwizardApplication extends Application<Configuration> { public static void main(String[] args) throws Exception { new DropwizardApplication().run(args); } @Override public void initialize(Bootstrap<Configuration> bootstrap) { // nothing to do yet } @Override public void run(Configuration c, Environment e) throws Exception { e.jersey().register(new BookController()); } } |
The Application class takes care of various bundles and commands which provide basic functionality. You can use initialize method to configure or register health check metrics or object mappers etc.I will cover more about this in subsequent tutorials. Main method is entry point for our application as usual.
Environment class acts as a registry of all things our application can do.We have create new BookController and registered it with enviroment using "e.jersey().register(new BookController())".
Dropwizard allows you to create as many resources (with different URI) as you want and register it with the environment.
7)Â It ‘s time to do maven build.
Right click on project -> Run as -> Maven build
Run the application
10) We will test this application in  postman , UI based client for testing restful web applications. It is chrome plugin. Launch postman.If you want java based client, then you can also use how to send get or post request in java.
Get method
11)Â Test your get method
URL :“localhost:8080/bookService/books”.
You will get following output:
get books by id
URL :“localhost:8080/bookService/book/2”.
You will get the following output:
Post method
12)Â Post method is used to create new resource. Here we are adding new Book “Effective Javascript” to book list, so you can see we have used new book json in post body.
URL:Â “localhost:8080/bookService/books”.
Use get method to check if above book has been added to book list.
Put Method
13)Â Put method is used to update the resource. Here will update pages of book “Hibernate in action” using put method.
We will update book json in body of request.
URL :Â “localhost:8080/bookService/books”
Use get method to check pages of book “hibernate in action”.
Delete method
14)Â Delete method is used to delete resource.We will pass id of book which needs to be deleted as PathParam. We are going delete id:4 i.e. book “Learning Python” to demonstrate delete method.
URL :Â “localhost:8080/bookService/book/3”
Use get method to check book list.
As you can see, we have deleted country with id 3 i.e. Learning python.
Source code
That’s all about Dropwizard tutorial.