Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mutually exclusive options using Apache Commons CLI

I can create 2 mutually exclusive options using the following:

Option a = OptionBuilder.create("a");
Option b = OptionBuilder.create("b");

OptionGroup optgrp = new OptionGroup();
optgrp .setRequired(true);
optgrp .addOption(a);
optgrp .addOption(b);

The above will force the user to provide either option a or option b.

But if I have a third option, c:

Option c = OptionBuilder.create("c");

is it possible to create mutually exclusive options such that:

Either:

  1. Option a must be provided OR
  2. Both options b and c must be provided

I couldn't see a way to do it using OptionGroup?

like image 643
Rory Avatar asked Jan 07 '15 14:01

Rory


People also ask

What is the Apache Commons CLI library?

The Apache Commons CLI library provides an API for parsing command line options passed to programs. It's also able to print help messages detailing the options available for a command line tool. Commons CLI supports different types of options: A typical help message displayed by Commons CLI looks like this:

What is the use of Commons CLI?

Commons CLI The Apache Commons CLI library provides an API for parsing command line options passed to programs. It's also able to print help messages detailing the options available for a command line tool. Commons CLI supports different types of options:

How to print usage guide of command line arguments in Apache Commons CLI?

Apache Commons CLI provides HelpFormatter class to print the usage guide of command line arguments. See the example given below − Run the file and see the result. java CLITester usage: CLITester -g,--gui Show GUI Application -n <arg> No. of copies to print -p,--print Send print request to printer.


1 Answers

As a workaround to this, I implemented the following, not ideal, but..

public static void validate(final CommandLine cmdLine) {
   final boolean aSupplied = cmdLine.hasOption(A);

   final boolean bAndCSupplied = cmdLine.hasOption(B) && cmdLine.hasOption(C);

   final boolean bOrCSupplied = !bAndCSupplied && (cmdLine.hasOption(B) || cmdLine.hasOption(C));

   if ((aSupplied && bAndCSupplied) || (!aSupplied && !bAndCSupplied)
      || (aSupplied && bOrCSupplied )) {
          throw new Exception(...);
   }
}
like image 66
Rory Avatar answered Sep 30 '22 18:09

Rory