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.

  1. package ca.gaudreault.mydropwizardapp;
  2.  
  3. import io.dropwizard.cli.Command;
  4. import io.dropwizard.setup.Bootstrap;
  5. import net.sourceforge.argparse4j.inf.Namespace;
  6. import net.sourceforge.argparse4j.inf.Subparser;
  7.  
  8. public class MyCommand extends Command {
  9.  
  10. protected MyCommand() {
  11. super("myCommand", "This is a sample command");
  12. }
  13.  
  14. @Override
  15. public void configure(Subparser subparser) {
  16. subparser.addArgument("-test").required(true).type(Boolean.class).dest("test").help("Does something really awesome");
  17. }
  18.  
  19. @Override
  20. public void run(Bootstrap<?> bootstrap, Namespace namespace) throws Exception {
  21. System.out.println("MyCommand " + namespace.getBoolean("test"));
  22. }
  23. }

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”.

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

Executing Command

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

  1. myCommand -test false

You will see once it runs that following

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