Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
 package com.yammer.dropwizard.cli;
 
The command-line runner for Dropwizard services.
public class Cli {
    private static final String COMMAND_NAME_ATTR = "command";
    private static final String[] HELP = { "-h" };
    private final SortedMap<StringCommandcommands;
    private final Bootstrap<?> bootstrap;
    private final ArgumentParser parser;

    
Create a new CLI interface for a service and its bootstrapped environment.

Parameters:
serviceClass the service class
bootstrap the bootstrap for the service
    public Cli(Class<?> serviceClassBootstrap<?> bootstrap) {
        this. = Maps.newTreeMap();
        this. = buildParser(serviceClass);
        this. = bootstrap;
        for (Command command : bootstrap.getCommands()) {
            addCommand(command);
        }
    }

    
Runs the command line interface given some arguments.

Parameters:
arguments the command line arguments
Throws:
java.lang.Exception if something goes wrong
    public void run(String[] argumentsthrows Exception {
        try {
            // assume -h if no arguments are given
            final String[] args = (arguments.length == 0) ?  : arguments;
            final Namespace namespace = .parseArgs(args);
            final Command command = .get(namespace.getString());
            command.run(namespace);
        } catch (ArgumentParserException e) {
            .handleError(e);
            System.exit(1);
        }
    }
    private ArgumentParser buildParser(Class<?> serviceClass) {
        final String usage = "java -jar " + new JarLocation(serviceClass);
        final ArgumentParser p = ArgumentParsers.newArgumentParser(usage)
                                                .defaultHelp(true);
        String version = serviceClass.getPackage().getImplementationVersion();
        if (version == null) {
            version = "No service version detected. Add a Implementation-Version " +
                    "entry to your JAR's manifest to enable this.";
        }
        p.version(version);
        p.addArgument("-v""--version")
         .action(new VersionArgumentAction())
         .help("show the service version and exit");
        return p;
    }
    private void addCommand(Command command) {
        .put(command.getName(), command);
        .addSubparsers().help("available commands");
        final Subparser subparser = .addSubparsers().addParser(command.getName());
        command.configure(subparser);
        subparser.description(command.getDescription())
                 .setDefault(command.getName())
                 .defaultHelp(true);
    }
New to GrepCode? Check out our FAQ X