0
# Command-Line Interface
1
2
Dropwizard's extensible command-line interface system provides built-in commands for server management and configuration validation, along with support for custom commands.
3
4
## Capabilities
5
6
### Command Base Class
7
8
Abstract base class for creating custom CLI commands that can be registered with the application.
9
10
```java { .api }
11
/**
12
* A basic CLI command.
13
*/
14
public abstract class Command {
15
/**
16
* Create a new command with the given name and description.
17
* @param name the name of the command, used for command line invocation
18
* @param description a description of the command's purpose
19
*/
20
protected Command(String name, String description);
21
22
/**
23
* Returns the command's name.
24
* @return the command's name
25
*/
26
public final String getName();
27
28
/**
29
* Returns the command's description.
30
* @return the command's description
31
*/
32
public final String getDescription();
33
34
/**
35
* Configure the command's Subparser.
36
* @param subparser the Subparser specific to the command
37
*/
38
public abstract void configure(Subparser subparser);
39
40
/**
41
* Executes when the user runs this specific command.
42
* @param bootstrap the bootstrap
43
* @param namespace the parsed command line namespace
44
* @throws Exception if something goes wrong
45
*/
46
public abstract void run(Bootstrap<?> bootstrap, Namespace namespace) throws Exception;
47
48
/**
49
* Called if there is an issue parsing configuration, setting up the
50
* environment, or running the command itself.
51
* @param cli contains the streams for stdout and stderr
52
* @param namespace the parsed arguments from the commandline
53
* @param e The exception that was thrown when setting up or running the command
54
*/
55
public void onError(Cli cli, Namespace namespace, Throwable e);
56
}
57
```
58
59
**Usage Examples:**
60
61
```java
62
public class RenderCommand extends Command {
63
public RenderCommand() {
64
super("render", "Render the template");
65
}
66
67
@Override
68
public void configure(Subparser subparser) {
69
subparser.addArgument("-t", "--template")
70
.dest("template")
71
.help("template to render")
72
.required(true);
73
74
subparser.addArgument("-o", "--output")
75
.dest("output")
76
.help("output file")
77
.setDefault("output.html");
78
}
79
80
@Override
81
public void run(Bootstrap<?> bootstrap, Namespace namespace) throws Exception {
82
final String template = namespace.getString("template");
83
final String output = namespace.getString("output");
84
85
System.out.println("Rendering template: " + template);
86
System.out.println("Output file: " + output);
87
88
// Implementation here
89
}
90
}
91
92
// Register in Application.initialize()
93
@Override
94
public void initialize(Bootstrap<MyConfiguration> bootstrap) {
95
bootstrap.addCommand(new RenderCommand());
96
}
97
```
98
99
### ConfiguredCommand Class
100
101
Abstract command that loads and parses a configuration file before execution, providing the parsed configuration to the run method.
102
103
```java { .api }
104
/**
105
* A command whose first parameter is the location of a YAML configuration file.
106
* @param <T> the Configuration subclass which is loaded from the configuration file
107
*/
108
public abstract class ConfiguredCommand<T extends Configuration> extends Command {
109
/**
110
* Creates a new configured command.
111
* @param name the command name
112
* @param description the command description
113
*/
114
protected ConfiguredCommand(String name, String description);
115
116
/**
117
* Returns the Class of the configuration type.
118
* @return the Class of the configuration type
119
*/
120
protected Class<T> getConfigurationClass();
121
122
/**
123
* Returns the parsed configuration or null if it hasn't been parsed yet.
124
* @return the parsed configuration or null
125
*/
126
public T getConfiguration();
127
128
/**
129
* Configure the command's Subparser. If you override this method, you must
130
* call super.configure(subparser) to preserve the configuration file parameter.
131
* @param subparser the Subparser specific to the command
132
*/
133
@Override
134
public void configure(Subparser subparser);
135
136
/**
137
* Adds the configuration file argument for the configured command.
138
* @param subparser The subparser to register the argument on
139
* @return the registered argument
140
*/
141
protected Argument addFileArgument(Subparser subparser);
142
143
/**
144
* Runs the command with the given Bootstrap and Configuration.
145
* @param bootstrap the bootstrap
146
* @param namespace the parsed command line namespace
147
* @param configuration the configuration object
148
* @throws Exception if something goes wrong
149
*/
150
protected abstract void run(Bootstrap<T> bootstrap,
151
Namespace namespace,
152
T configuration) throws Exception;
153
154
/**
155
* Mark the command for asynchronous cleanup.
156
*/
157
protected void cleanupAsynchronously();
158
159
/**
160
* Cleanup resources (called automatically unless cleanupAsynchronously() was called).
161
*/
162
protected void cleanup();
163
}
164
```
165
166
**Usage Examples:**
167
168
```java
169
public class DbMigrateCommand<T extends Configuration> extends ConfiguredCommand<T> {
170
private final String migrationsFileName;
171
private final Class<T> configurationClass;
172
173
public DbMigrateCommand(String name, Application<T> application, String migrationsFileName) {
174
super(name, "Run database migrations");
175
this.migrationsFileName = migrationsFileName;
176
this.configurationClass = application.getConfigurationClass();
177
}
178
179
@Override
180
protected Class<T> getConfigurationClass() {
181
return configurationClass;
182
}
183
184
@Override
185
public void configure(Subparser subparser) {
186
super.configure(subparser);
187
subparser.addArgument("--dry-run")
188
.action(storeTrue())
189
.dest("dryRun")
190
.help("Don't actually run migrations, just print what would be done");
191
}
192
193
@Override
194
protected void run(Bootstrap<T> bootstrap, Namespace namespace, T configuration) throws Exception {
195
final boolean dryRun = namespace.getBoolean("dryRun");
196
197
// Access configuration
198
MyConfiguration myConfig = (MyConfiguration) configuration;
199
DataSource dataSource = myConfig.getDataSourceFactory().build(bootstrap.getMetricRegistry(), "migrations");
200
201
if (dryRun) {
202
System.out.println("Would run migrations from: " + migrationsFileName);
203
} else {
204
System.out.println("Running migrations from: " + migrationsFileName);
205
// Run actual migrations
206
}
207
}
208
}
209
```
210
211
### Built-in Commands
212
213
Dropwizard provides several built-in commands that are automatically registered:
214
215
#### ServerCommand
216
217
Starts the application server with the provided configuration.
218
219
```java { .api }
220
/**
221
* Starts an HTTP server running a Dropwizard application.
222
* @param <T> the Configuration subclass
223
*/
224
public class ServerCommand<T extends Configuration> extends EnvironmentCommand<T> {
225
public ServerCommand(Application<T> application);
226
}
227
```
228
229
Usage: `java -jar myapp.jar server config.yml`
230
231
#### CheckCommand
232
233
Validates the configuration file without starting the server.
234
235
```java { .api }
236
/**
237
* Validates a configuration file.
238
* @param <T> the Configuration subclass
239
*/
240
public class CheckCommand<T extends Configuration> extends ConfiguredCommand<T> {
241
public CheckCommand(Application<T> application);
242
}
243
```
244
245
Usage: `java -jar myapp.jar check config.yml`
246
247
### EnvironmentCommand Class
248
249
Abstract configured command that provides full environment setup including the Environment instance, useful for commands that need access to the full application context.
250
251
```java { .api }
252
/**
253
* A command which provides access to the configured Environment.
254
* @param <T> the Configuration subclass
255
*/
256
public abstract class EnvironmentCommand<T extends Configuration> extends ConfiguredCommand<T> {
257
/**
258
* Creates a new environment command.
259
* @param application the application providing this command
260
* @param name the command name
261
* @param description the command description
262
*/
263
protected EnvironmentCommand(Application<T> application, String name, String description);
264
265
/**
266
* Runs the command with the given Environment.
267
* @param environment the configured environment
268
* @param namespace the parsed command line namespace
269
* @param configuration the configuration object
270
* @throws Exception if something goes wrong
271
*/
272
protected abstract void run(Environment environment, Namespace namespace, T configuration) throws Exception;
273
}
274
```
275
276
**Usage Examples:**
277
278
```java
279
public class DataExportCommand<T extends Configuration> extends EnvironmentCommand<T> {
280
public DataExportCommand(Application<T> application) {
281
super(application, "export-data", "Export application data");
282
}
283
284
@Override
285
public void configure(Subparser subparser) {
286
super.configure(subparser);
287
subparser.addArgument("--format")
288
.choices("json", "csv", "xml")
289
.setDefault("json")
290
.help("Export format");
291
}
292
293
@Override
294
protected void run(Environment environment, Namespace namespace, T configuration) throws Exception {
295
final String format = namespace.getString("format");
296
297
// Access environment services
298
HealthCheckRegistry healthChecks = environment.healthChecks();
299
MetricRegistry metrics = environment.metrics();
300
301
// Access configuration
302
MyConfiguration myConfig = (MyConfiguration) configuration;
303
304
System.out.println("Exporting data in " + format + " format");
305
// Implementation here
306
}
307
}
308
```
309
310
### CLI Runner
311
312
The main CLI runner that processes command-line arguments and executes the appropriate command.
313
314
```java { .api }
315
/**
316
* The main CLI runner for Dropwizard applications.
317
*/
318
public class Cli {
319
/**
320
* Creates a new CLI for the given application.
321
* @param location the application's JAR location
322
* @param bootstrap the application bootstrap
323
* @param stdOut the standard output stream
324
* @param stdErr the standard error stream
325
*/
326
public Cli(JarLocation location, Bootstrap<?> bootstrap, PrintStream stdOut, PrintStream stdErr);
327
328
/**
329
* Runs the command line interface with the given arguments.
330
* @param arguments the command line arguments
331
* @return Optional containing throwable if there was an error, empty otherwise
332
*/
333
public Optional<Throwable> run(String... arguments);
334
335
/**
336
* Returns the standard output stream.
337
* @return the stdout stream
338
*/
339
public PrintStream getStdOut();
340
341
/**
342
* Returns the standard error stream.
343
* @return the stderr stream
344
*/
345
public PrintStream getStdErr();
346
}
347
```
348
349
## Command Registration
350
351
Commands are registered during application initialization:
352
353
```java
354
@Override
355
public void initialize(Bootstrap<MyConfiguration> bootstrap) {
356
// Register custom commands
357
bootstrap.addCommand(new RenderCommand());
358
bootstrap.addCommand(new DbMigrateCommand<>(this, "migrations.xml"));
359
bootstrap.addCommand(new DataExportCommand<>(this));
360
}
361
```
362
363
## Command-Line Usage
364
365
```bash
366
# Run the server
367
java -jar myapp.jar server config.yml
368
369
# Check configuration
370
java -jar myapp.jar check config.yml
371
372
# Run custom commands
373
java -jar myapp.jar render -t template.html -o output.html
374
java -jar myapp.jar export-data --format csv config.yml
375
java -jar myapp.jar db migrate --dry-run config.yml
376
377
# Get help
378
java -jar myapp.jar --help
379
java -jar myapp.jar server --help
380
```
381
382
## Types
383
384
```java { .api }
385
// Argument parsing types from argparse4j
386
public interface Subparser {
387
Argument addArgument(String... nameOrFlags);
388
void setDefault(String dest, Object value);
389
void help(String help);
390
}
391
392
public interface Argument {
393
Argument dest(String dest);
394
Argument help(String help);
395
Argument required(boolean required);
396
Argument setDefault(Object defaultValue);
397
Argument choices(Object... choices);
398
Argument action(ArgumentAction action);
399
}
400
401
public interface Namespace {
402
String getString(String dest);
403
Boolean getBoolean(String dest);
404
Integer getInt(String dest);
405
Object get(String dest);
406
}
407
```