Table of contents
1.
Introduction
2.
Setting Up Dropwizard Using Maven
2.1.
Tutorial
2.1.1.
Step 1: Java Installation
2.1.2.
Step 2: Maven Installation
2.1.3.
Step 3: Creating a new Maven project
2.1.4.
Step 4: Install IntelliJ IDEA
2.1.5.
Step 5: Add the dropwizard.version property
2.1.6.
Step 6: Add the dropwizard.core as a dependency
3.
How to Create a Configuration Class
4.
How to Create an Application Class
5.
How to Create a Representation Class
6.
How to Create a Resource Class
7.
How to Create a Health Check
8.
How to Build Fat JARs
9.
Versioning an Application
10.
Running an Application
10.1.
Server Command
11.
Frequently Asked Questions
11.1.
What is Maven?
11.2.
How is Maven used in Dropwizard?
11.3.
What are the three different methods to set up Dropwizard?
11.4.
What are the steps to create a Maven project using the dropwizard.core library?
11.5.
Give a brief outline of setting up Dropwizard using Maven.
12.
Conclusion
Last Updated: Mar 27, 2024
Hard

Dropwizard - Setting Up Using Maven

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

If you’re reading this article, let me guess that you already know what Dropwizard is, but what after that? 

After learning about Dropwizard, we must know how to use it. When talking about setting up Dropwizard, using Maven is definitely what comes up. 

Now, what is Maven? 

Maven is a tool used for project management (introduced by the Apache Software Foundation). It provides a complete framework for build cycles. Primarily used for projects developed in Java, Maven is driven by a project object model (POM). POM is the central repository for all dependencies. Here, the same folder rules across the organizations and can easily be integrated with continuous integration tools such as Jenkins. It is also responsible for project reporting and documentation developed in Java.

Thus, we can see that Maven is used to manage projects in Java. Also, we know that Dropwizard is a Java framework. So, now we need to know the process of setting up Dropwizard using Maven. Let’s see how it’s done in this article.

Dropwizard - Setting Up Using Maven

Setting Up Dropwizard Using Maven

For setting up Dropwizard using Maven, there are three alternatives:

(i) Create a project using Dropwizard - archetype according to the following syntax:

mvn archetype:generate -DarchetypeGroupId=io.dropwizard.archetypes -DarchetypeArtifactId=java-simple -DarchetypeVersion=[REPLACE WITH A VALID DROPWIZARD VERSION]

(ii) Use Dropwizard - example

(iii) Use the Dropwizard.core library to incorporate Dropwizard into an existing project.

The third method is explained in the tutorial below.

A stick figure giving a tutorial

Tutorial

The tutorial below starts with the very basics of setting up Dropwizard using Maven. Each step is explained in detail for thorough understanding.

Step 1: Java Installation

Before we start setting up Dropwizard using Maven, we must install Java. It is usually installed on most systems, but we should still check for our system. To do this, first, we have to open the command prompt. To do this, press Windows+R, in the run prompt type “cmd” and press ok.

In the command prompt, we will run the following command:

java - - version


If the output is similar to the one shown below, Java is already installed in the system.

Command prompt showing the output for the java --version command

If the output shows “'java' is not recognized as an internal or external command, operable program or batch file” then Java is not installed and can be installed here.

Step 2: Maven Installation

Now that Java is installed, we need to install Maven. 

Firstly, download the “Binary zip archive” file from the link given here

Link to download maven from the official website

Then, to install Maven, extract the contents of the downloaded file into the “Program Files” directory. 

We will then open the “Edit the system environment variables” menu on windows and select the “environment variables” under the advanced tab.

System properties window showing the environmental variables option

Create a new system variable with the specifications shown below. The variable value should be the path of the folder in which Maven has been extracted.

Specifications to create a new system variable

Select the “path” system variable and click edit.

How to edit the path from the environmental variables window

There, create a new path variable named “%MAVEN_HOME%\bin”. We can save all the changes by clicking "ok" on each window. 

To verify the installation, run the following command in the command prompt.

mvn --version


Your output should give the details of the version of Maven installed as shown below.

Command prompt showing the output for the mvn --version command

Step 3: Creating a new Maven project

Run the following command to create a Maven project with the name maven-proj.

mvn archetype:generate -DgroupId=com.yammer -DartifactId=maven-proj -DarchetypeArtifactId=maven-archetype-quickstart -DarchetypeVersion=1.4 -DinteractiveMode=false


To check if the project was created, run the following: 

cd maven-proj

Step 4: Install IntelliJ IDEA

For setting up Dropwizard using Maven, we must edit the pom.xml file of our project. To do this, we need an editor. Here, we will be using the IntelliJ IDEA. 

Step 5: Add the dropwizard.version property

After installing IntelliJ IDEA, we need to add the current version of Dropwizard to the project object model (POM). To do this, we will use the dropwizard.version property. The syntax to do this is given below.

<properties>
    <dropwizard.version>ADD VERSION</dropwizard.version>
</properties>

Step 6: Add the dropwizard.core as a dependency

Add the dropwizard.core library as a dependency. The syntax for this is:

<dependencies>
    <dependency>
        <groupId>com.yammer.dropwizard</groupId>
        <artifactId>dropwizard-core</artifactId>
        <version>ADD VERSION </version>
    </dependency>
</dependencies>


Note: The version of dropwizard we have used is 0.6.2.

To sum it up, the ‘pom.xml’ file will look like this.

<?xml version="1.0" encoding="UTF-8"?>

<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>com.yammer</groupId>
 <artifactId>maven-proj</artifactId>
 <version>1.0-SNAPSHOT</version>
 
 <name>maven-proj</name>
 <!-- FIXME change it to the project's website -->
 <url>http://www.example.com</url>
 
 <properties>
   <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
   <maven.compiler.source>1.7</maven.compiler.source>
   <maven.compiler.target>1.7</maven.compiler.target>
   <dropwizard.version>0.6.2</dropwizard.version>
 </properties>
 
 <dependencies>
   <dependency>
     <groupId>junit</groupId>
     <artifactId>junit</artifactId>
     <version>4.11</version>
     <scope>test</scope>
   </dependency>
 </dependencies>
 
 <dependencies>
   <dependency>
     <groupId>com.yammer.dropwizard</groupId>
     <artifactId>dropwizard-core</artifactId>
     <version>0.6.2</version>
   </dependency>
 </dependencies>

 <build>
   <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
     <plugins>
       <!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
       <plugin>
         <artifactId>maven-clean-plugin</artifactId>
         <version>3.1.0</version>
       </plugin>
       <!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
       <plugin>
         <artifactId>maven-resources-plugin</artifactId>
         <version>3.0.2</version>
       </plugin>
       <plugin>
         <artifactId>maven-compiler-plugin</artifactId>
         <version>3.8.0</version>
       </plugin>
       <plugin>
         <artifactId>maven-surefire-plugin</artifactId>
         <version>2.22.1</version>
       </plugin>
       <plugin>
         <artifactId>maven-jar-plugin</artifactId>
         <version>3.0.2</version>
       </plugin>
       <plugin>
         <artifactId>maven-install-plugin</artifactId>
         <version>2.5.2</version>
       </plugin>
       <plugin>
         <artifactId>maven-deploy-plugin</artifactId>
         <version>2.8.2</version>
       </plugin>
       <!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
       <plugin>
         <artifactId>maven-site-plugin</artifactId>
         <version>3.7.1</version>
       </plugin>
       <plugin>
         <artifactId>maven-project-info-reports-plugin</artifactId>
         <version>3.0.0</version>
       </plugin>
     </plugins>
   </pluginManagement>
 </build>
</project>


With this, we have set up a Maven project, but this isn’t much. 

Maven project with a green tick mark

Let’s see how to write the code in the subsequent sections. 

How to Create a Configuration Class

Each Dropwizard application has its own subclass - a configuration class. This class specifies environment-specific parameters. These parameters are added to the YAML configuration file. This is deserialized to an instance of the application’s configuration class for validation. 

For better understanding, let’s consider a configuration class similar to an abstract class, while the YAML configuration file is the derived class. In the example of building a high-performance Hello There service below, you can see how the configuration class creates a template using default variables. Those are configured with values in the YAML file.
Configuration Class:

package com.example.hellothere;
 
import io.dropwizard.Configuration;
import com.fasterxml.jackson.annotation.JsonProperty;
import javax.validation.constraints.NotEmpty;
 
public class HelloThereConfiguration extends Configuration {
    @NotEmpty
    private String template;
 
    @NotEmpty
    private String defaultName = "Person";
 
    @JsonProperty
    public String getTemplate() {
        return template;
    }
 
    @JsonProperty
    public void setTemplate(String template) {
        this.template = template;
    }
 
    @JsonProperty
    public String getDefaultName() {
        return defaultName;
    }

    @JsonProperty
    public void setDefaultName(String name) {
        this.defaultName = name;
    }
}


YAML File:

template: Hello, %s!
defaultName: Person

How to Create an Application Class

Before we create an application class, we must know what it is. 

In simple terms, an application class is analogous to a function in a normal program. It forms the core of the Dropwizard application and combines bundles and commands to provide the basic functionality. For the Hello There service considered above, the application class will be:

package com.example.hellothere;
 
import io.dropwizard.Application;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import com.example.hellothere.resources.HelloThereResource;
import com.example.hellothere.health.TemplateHealthCheck;
 
public class HelloThereApplication extends Application<HelloThereConfiguration> 
{
	// Main method to start the program
    public static void main(String[] args) throws Exception 
   {
        new HelloThereApplication().run(args);
    }
 
	// The function to perform the action
    @Override
    public String getName() {
        return "hello-there";
    }
 
	// The function to initialize the necessary variables
    @Override
    public void initialize(Bootstrap<HelloThereConfiguration> bootstrap) {
        // nothing
    }

	// The method to perform other functions
    @Override
    public void run(HelloThereConfiguration configuration, Environment environment) {
        // nothing
    }

 
}

How to Create a Representation Class

While creating any application, an important part is an API. For this, one must abide by the RFC 1149 standards. According to the standards, the JSON representation of the Hello There saying is:

{
  "id": NUMBER,  // It is a unique identifier for the saying
  "content": "Hi!"  // It is a textual representation of the saying
}


To model this, a representation class is used. 

For our example, the representation class is as follows:

package com.example.hellothere.api;
 
import com.fasterxml.jackson.annotation.JsonProperty;
 
public class Saying {
    private long id;
    private String content;
 
    public Saying() {
        // Jackson deserialization
    }
 
    public Saying(long id, String content) {
        this.id = id;
        this.content = content;
    }
 
    @JsonProperty
    public long getId() {
        return id;
    }
 
    @JsonProperty
    public String getContent() {
        return content;
    }
}

How to Create a Resource Class

Before knowing what a resource class is, we must learn about URI (universal resource identifier) templates. 

Firstly, a URI is used to identify resources. So, each resource class is associated with a URI template. A URI template contains parameters that we must replace to solve a URI.

In our example of the Hello There service, we need a resource that returns “saying” instance from the URI “/hellothere”. So, our resource will look like this:

package com.example.hellothere.resources;
 
import com.example.hellothere.api.Saying;
import com.codahale.metrics.annotation.Timed;
 
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import java.util.concurrent.atomic.AtomicLong;
import java.util.Optional;
 
@Path("/hello-there")
@Produces(MediaType.APPLICATION_JSON)
public class HelloThereResource {
    private final String template;
    private final AtomicLong counter;
    private final String defaultName;
 
    public HelloThereResource(String template, String defaultName) {
        this.template = template;
        this.counter = new AtomicLong();
        this.defaultName = defaultName;
    }
 
    @GET
    @Timed
    public Saying sayHello(@QueryParam("name") Optional<String> name) {
        final String value = String.format(template, name.orElse(defaultName));
        return new Saying(counter.incrementAndGet(), value);
    }
}


Once we create a resource, we must link it to the application’s Jersey environment. To do that:

@Override
public void run(HelloThereConfiguration configuration,
                Environment environment) {
    final HelloThereResource resource = new HelloThereResource(
        configuration.getTemplate(),
        configuration.getDefaultName()
    );
    environment.jersey().register(resource);
}

How to Create a Health Check

Usually, why does a person get a health check done?

To see if their body’s alright, right?

Similarly, when making an application, we must ensure that it runs properly. To do that, health checks are used.

In our example, let’s add a health check which checks whether we can format the provided template. In other words, the health check ensures that the template is a well-formed format string and that the template produces output with the given name.

package com.example.hellothere.health; 
import com.codahale.metrics.health.HealthCheck;
 
public class TemplateHealthCheck extends HealthCheck {
    private final String template;
 
    public TemplateHealthCheck(String template) {
        this.template = template;
    }
 
    @Override
    protected Result check() throws Exception {
        final String saying = String.format(template, "HealthCheckTEST");
        if (!saying.contains("HealthCheckTEST")) {
            return Result.unhealthy("The provided template doesn't have a name in it");
        }
        return Result.healthy();
    }
}


Now, we only created a health check. We must add it to the Dropwizard project too.

@Override
public void run(HelloThereConfiguration configuration,
                Environment environment) {
    final HelloThereResource resource = new HelloThereResource(
        configuration.getTemplate(),
        configuration.getDefaultName()
    );
    final TemplateHealthCheck healthCheck =
        new TemplateHealthCheck(configuration.getTemplate());
    environment.healthChecks().register("template", healthCheck);
    environment.jersey().register(resource);
}
To do list with the tasks configuration class, application class, representation class, resource class and health check completed

How to Build Fat JARs

The name of a jar makes us think of a jar of candy or cookies.

While setting up Dropwizard using Maven, JARs have a similar meaning. Instead of candy, fat JAR files contain all the class files needed to run an application. This helps make the entire application a single deployable entity that can be sent from the staging environment to the QA (quality assurance) and production environments. 

To build the Hello There application as a fat JAR, we must first configure a Maven plugin called maven-shade. Then in the <build> and then to <plugins> section of the pom.xml file, we must add the following code:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-shade-plugin</artifactId>
    <version>2.3</version>
    <configuration>
        <createDependencyReducedPom>true</createDependencyReducedPom>
        <filters>
            <filter>
                <artifact>*:*</artifact>
                <excludes>
                    <exclude>META-INF/*.SF</exclude>
                    <exclude>META-INF/*.DSA</exclude>
                    <exclude>META-INF/*.RSA</exclude>
                </excludes>
            </filter>
        </filters>
    </configuration>
    <executions>
        <execution>
            <phase>package</phase>
            <goals>
                <goal>shade</goal>
            </goals>
            <configuration>
                <transformers>
                    <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
                    <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                        <mainClass>com.example.helloThere.HelloThereApplication</mainClass>
                    </transformer>
                </transformers>
            </configuration>
        </execution>
    </executions>
</plugin>


This code does the following:

(i) Produce a pom.xml file excluding the dependencies for the libraries whose contents are included in the fat JAR file. 

(ii) Exclude all the digital signatures from signed JARs so that Java considers the signature valid and loads and runs the JAR file. 

(iii) Collects the different service entries in the JAR files.

(iv) Sets JAR’s MainClass as “com.example.hellothere.HelloThereApplication” to run the JAR using java-jar. 

A jar with files in it

Versioning an Application

A web application may have many versions. So, the version of an application is embedded in its JAR file as the “Implementation-Version”.

To embed the version information using Maven, we have to add the code given below to the <build> and then to <plugins> section of the pom.xml file.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
    <version>2.4</version>
    <configuration>
        <archive>
            <manifest>
                <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
            </manifest>
        </archive>
    </configuration>
</plugin>


After this step is complete, we must go to the project directory and run “mvn package” or “package” from the IDE to get an output like this:

Command prompt showing the output obtained on running the command mvn package

If we get such an output, that means we have been successful in setting up Dropwizard using Maven!

A happy boy jumping with his arms in the air

Now, we just don’t want to build an application. We want to run it too. Let’s see how that’s done next. 

Must Read Apache Server

Running an Application

To run the application, in the project directory, run this:

java -jar target/hello-there-0.6.2.jar


The output should be something like this:

Command prompt showing the output for running the application

This means that the Dropwizard will take the first command line argument and dispatch it to a matching command. 

Here, the available command is “server” which will run our application as an HTTP server. 

Server Command

We can also try running the "server" command, but we need a configuration file. We’ll use the YAML file we created earlier for this purpose. 

java -jar target/hello-there-0.6.2.jar server hello-there.yml


The output will be:

Command prompt showing the output for running the server command

From this, we can see that the Dropwizard application listens on ports 8080 and 8081 for requests. 

Note: To close the application, press ^C. 

This completes the process of setting up Dropwizard using Maven. 

Some parts may seem confusing to you as a beginner, so don't hesitate to repeat the entire process. 

Let's see some frequently asked questions for those who have thoroughly understood.

FAQs written with 3 question marks in the background

Frequently Asked Questions

What is Maven?

Maven is a tool used for project management (introduced by the Apache Software Foundation) that provides a complete framework for build cycles. It is primarily used for projects developed in Java.

How is Maven used in Dropwizard?

Maven is used to create and manage Dropwizard projects.

What are the three different methods to set up Dropwizard?

Dropwizard can be set up by creating a project using Dropwizard - archetype, Dropwizard - example, or the Dropwizard.core library.

What are the steps to create a Maven project using the dropwizard.core library?

To create a Maven project using the dropwizard.core library, we first need to add the current version of Dropwizard to the POM. Next, we need to add the dropwizard.core library as a dependency.

Give a brief outline of setting up Dropwizard using Maven.

To set up Dropwizard using Maven, we first need to create a Maven project. Then we must create a configuration class, application class, representation class, resource class, and health check. Finally, all the files in the project are added to a fat JAR file. 

Conclusion

As this article comes to a close, we know about setting up Dropwizard using Maven. We learned how to create a Maven project, configuration class, application class, representation class, resource class, and health check. We also learned how to wrap up all the files in the project in a fat JAR file. Yet, this is just the beginning of learning about Dropwizard. 

After this, we must know about Dropwizard dependency injectionDropwizard clientDropwizard JDBI3, and many more things you can find on Coding Ninjas Studio.

Apart from resources on Dropwizard, you may also refer to our Guided Path for coding interview preparations. Further, for thorough preparation, don’t forget to check out Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and many more!

Happy learning!

Live masterclass