Dropwizard: Command

This entry is part 3 of 5 in the series Dropwizard
(Last Updated On: )

In this tutorial I will give a brief demonstration on how to write a custom dropwizard command.

MyCommand

So below you will see the command class and how we are creating and registering a command line param called “test” which is a Boolean.

package ca.gaudreault.mydropwizardapp;

import io.dropwizard.cli.Command;
import io.dropwizard.setup.Bootstrap;
import net.sourceforge.argparse4j.inf.Namespace;
import net.sourceforge.argparse4j.inf.Subparser;

public class MyCommand extends Command {

	protected MyCommand() {
		super("myCommand", "This is a sample command");
	}

	@Override
	public void configure(Subparser subparser) {
	    subparser.addArgument("-test").required(true).type(Boolean.class).dest("test").help("Does something really awesome");
	}

	@Override
	public void run(Bootstrap<?> bootstrap, Namespace namespace) throws Exception {
		System.out.println("MyCommand " + namespace.getBoolean("test"));
	}
}

MyDropwizardAppApplication

If you remember from part 1 of this series you created the based Dropwizard app. So you should have a class called “MyDropwizardAppApplication”. Open that now and modify the “initialize” like the below. Note that we are only adding the “addCommand”.

@Override
public void initialize(final Bootstrap bootstrap) {
	bootstrap.addCommand(new MyCommand());
}

Executing Command

Basically now we can just call our JAR file and pass the following arguments to it.

myCommand -test false

You will see once it runs that following

MyCommand false
Series Navigation<< Dropwizard: Guice BundleDropwizard: Resource >>