Apache Common CLI Example

The Apache Commons CLI project has been around for almost 10 years. It’s a library that that simplifies the handling of command line arguments. I had the opportunity to use it on a small project at work the other day. Here’s an example of how it was used:

public class CliExample {
    private static final String DB_TIMEOUT = "dbTimeout";
    private int dbTimeoutInMinutes = 6;

    public static void main(String... args) {

        final Options options = createOptions();
        final CommandLine line = getCommandLine(options, args);

        if (line.hasOption("help")) {
            help(options);
            return;
        } else if (line.hasOption("DB_TIMEOUT") {
            setDbTimeoutMinutes(Integer.valueOf(line.getOptionValue(DB_TIMEOUT));
        }  
    }

    public int getDbTimeoutInMinutes() {
        return dbTimeoutInMinutes;
    }

    public void setDbTimeoutInMinutes(final int dbTimeoutInMinutes) {
        this.dbTimeoutInMinutes = dbTimeoutInMinutes;
    }

    private static CommandLine getCommandLine(final Options options, final String[] args)
        throws Exception {
        final CommandLineParser parser = new GnuParser();
        final CommandLine line;

        try {
            line = parser.parse(options, args);
        } catch (ParseException e) {
            help(options);
            throw new Exception("Unable to process command line options");
        }

        return line;
    }

    @SuppressWarnings("static-access")
    private static Options createOptions() {
        final Options options = new Options();
        options.addOption("help", false, "USAGE: FeeLifecycleTask [-" + DB_TIMEOUT + " int]");
        options.addOption(OptionBuilder
                .withType(Integer.class)
                .withArgName("int")
                .hasArg()
                .withDescription(DB_TIMEOUT + " - sets the db timeout window in minutes")
                .create(DB_TIMEOUT));

        return options;
    }

    private static void help(final Options options) {
        final HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("FeeLifecycleTask", options);
    }
}

It looks like a lot of code to parse 2 arguments (help and -dbTimeout) but it makes adding additional arguments super simple. Add a new option within createOptions() and the CommandLine object and help method are automatically updated. All that would need to be done is to map the new argument to a local variable.

Leave a Reply

Your email address will not be published. Required fields are marked *