Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to accept custom command line arguments with Dropwizard

I am trying to get my Dropwizard application to accept custom command line arguments. The documentation seems to fall short and only half explains what to do. Considering I am new to this I need a very clear example from code to command line usage.

Would anybody care to share? I have viewed this question but it doesn't explain clearly and I can't get it to work.

Please don't ask for code samples about what I have tried. Trust me I have tried a lot and i'm not sure exactly what to post as most of the code is gone. If you know how to do this it shouldn't take long to answer. Thanks.

like image 959
jim Avatar asked Dec 06 '15 16:12

jim


People also ask

Does Dropwizard use Log4j?

Dropwizard uses Logback for its logging backend. It provides an slf4j implementation, and even routes all java. util. logging , Log4j, and Apache Commons Logging usage through Logback.

Does Dropwizard use Jetty?

Overview. Dropwizard is an open-source Java framework used for the fast development of high-performance RESTful web services. It gathers some popular libraries to create the light-weight package. The main libraries that it uses are Jetty, Jersey, Jackson, JUnit, and Guava.


1 Answers

I'm using the example stated in the manual. If you need to achieve the following output, you can do so with the code provided. Let me know if you need anything more specific.

Input: java -jar <your-jar> hello -u conor
Output: Hello conor

I'm not sure which version of dropwizard you're using. This one's for 0.9.1

Main Class

public class MyApplication extends Application<MyConfiguration> {
  public static void main(String[] args) throws Exception {
    {
      new MyApplication().run(args);
    }
  }

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

  @Override
  public void run(ExampleConfiguration config,
                  Environment environment) {
  }
}

MyCommand.java

public class MyCommand extends Command {
  public MyCommand() {        
    super("hello", "Prints a greeting");
  }

  @Override
  public void configure(Subparser subparser) {
    // Add a command line option
    subparser.addArgument("-u", "--user")
      .dest("user")
      .type(String.class)
      .required(true)
      .help("The user of the program");
  }

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

Reference: http://www.dropwizard.io/0.9.1/docs/manual/core.html#man-core-commands

like image 51
dkulkarni Avatar answered Oct 11 '22 06:10

dkulkarni