Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Dropwizard tutorial

Tags: book import class

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.

1) Create a dynamic web project using maven in eclipse named “DropwizardHelloWordExample”

Maven dependencies

2) We need to add Dropwizard core dependency in the classpath.

io.dropwizard
dropwizard-core
${dropwizard.version}

Here is complete pom.xml

4.0.0org.arpit.java2blog
	DropwizardHelloWordExample
	0.0.1-SNAPSHOTjarDropwizardHelloWordExamplehttp://maven.apache.org1.0.3UTF-8io.dropwizard
			dropwizard-core
			${dropwizard.version}junit
			junit
			3.8.1testDropWizardExample-${version}org.apache.maven.plugins
				maven-compiler-plugin
				3.11.81.8org.apache.maven.plugins
				maven-shade-plugin
				2.1packageshadeorg.arpit.java2blog.Application

Create bean class

3) Create a bean name “Country.java” in org.arpit.java2blog.model.

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.

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 getBooks() {
		List 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

5) Create a class BookService.java in package org.arpit.java2blog.service
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.
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 BookIdMap=getBookIdMap();
 
 
	public BookService() {
		super();
 
		if(BookIdMap==null)
		{
			BookIdMap=new HashMap();
			// 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 getAllBooks()
	{
		List  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() getBookIdMap() {
		return BookIdMap;
	}
 
	// Utility method to get max id
	public static int getMaxId()
	{ int max=0;
	for (int id:BookIdMap.keySet()) { 
		if(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.

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 {
    public static void main(String[] args) throws Exception {
        new DropwizardApplication().run(args);
    }

    @Override
    public void initialize(Bootstrap 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

8) Provide goals as clean install (given below) and click on run

Run the application

9) go to DropwizardApplication.java, right click -> Run as java 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

Download source code – Dropwizard hello world

That’s all about Dropwizard tutorial.

The post Dropwizard tutorial appeared first on Java2Blog.



This post first appeared on How To Learn Java Programming, please read the originial post: here

Share the post

Dropwizard tutorial

×

Subscribe to How To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×