I'm trying to use OptionGroup to mutually exclude arguments, and it seems
to be broken. I've setup --ip-address & --hostname as options in a single
group, then provide both on the "command line" and would expect the parser
to throw an AlreadySelectedException, but it doesn't... it happily parses
both. Should I raise a JIRA issue for this, or am I totally missing
something?

Bill-

    public static void main(String[] args) {
        fakeMain(new String[] { "--ip-address", "192.168.1.1",
"--hostname", "www.example.com"});
    }

    public static void fakeMain(String[] args) {
        final PosixParser parser = new PosixParser();
        final Options options = configureOptions();

        // parse with the basic parser
        CommandLine cmdLine = null;
        try {
            cmdLine = parser.parse(options, args);
        } catch(ParseException e) {
            e.printStackTrace();
            return;
        }

        // get the IP address or hostname
        if(cmdLine.hasOption("ip-address")) {
            System.out.println("IP: " +
cmdLine.getOptionValue("ip-address"));
        }
        if(cmdLine.hasOption("hostname")){
            System.out.println("Hostname: " +
cmdLine.getOptionValue("hostname"));
        }
    }

    @SuppressWarnings("static-access")
    public static Options configureOptions() {
        Options options = new Options();

        // create the group to specify either an IP or hostname
        OptionGroup group = new OptionGroup();

        group.addOption(OptionBuilder.withLongOpt("ip-address")
                                     .withArgName("ip")
                                     .hasArg()
                                     .withDescription("IP address to use")
                                     .create());

        group.addOption(OptionBuilder.withLongOpt("hostname")
                                     .withArgName("host")
                                     .hasArg()
                                     .withDescription("Hostname address to
use")
                                     .create());
        options.addOptionGroup(group);

        return options;
    }

*** OUTPUT ***
IP: 192.168.1.1
Hostname: www.example.com

Reply via email to