How to accept command line arguments using Dropwizard

I am trying to get my Dropwizard application to accept custom command line arguments. The documentation seems short and only half explains what to do. Given that I'm new to this, I need a very clear example from the code to use the command line.

Does anyone want to share? I examined this issue, but it does not explain clearly, and I cannot get it to work.

Please do not ask for code samples about what I tried. Believe me, I tried a lot, and I don’t know exactly what to do, since most of the code is gone. If you know how to do this, you should not answer for a long time. Thanks.

+5
source share
2 answers

I use the example provided in the manual. If you need to complete the following output, you can do this with the code provided. Let me know if you need something more specific.

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

I'm not sure which version of dropwizard you are using. This one is 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")); } } 

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

+5
source

public class TestCommand extends the {

 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 arguments
Conclusion: command to check -> dwizard

If you wrote a class that extends the Command class or similar, then the following command should work commandName {command} {command arg}

0
source

Source: https://habr.com/ru/post/1237511/


All Articles