jim
jim

Reputation: 9138

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.

Upvotes: 7

Views: 7244

Answers (2)

user6679850
user6679850

Reputation: 29

public class TestCommand extends Command {

public TestCommand() {
    super("commandName", "CommandDesc");
}

@Override
public void configure(Subparser subparser) {
    subparser.addArgument("-ct", "--commandTest").dest("Dest").type(String.class).required(true)
            .help("command test");
}

@Override
public void run(Bootstrap<?> bootstrap, Namespace namespace) throws Exception {
    System.out.println("command to test -> " + namespace.getString("Dest"));
}

}

Run the code: commandName -ct dwizard as args
Output: command to test -> dwizard

If you have written a class which extends "Command" class or similar, then the following command should work commandName {command} {command arg}

Upvotes: 0

dkulkarni
dkulkarni

Reputation: 2830

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

Upvotes: 7

Related Questions