public static void main(String[] args) { GnuParser parser = new GnuParser(); CommandLine commandLine; try { commandLine = parser.parse(CommandLineOption.ALL_COMMAND_LINE_OPTIONS, args); } catch (ParseException e) { printUsage(e); return; } URL url = ClassLoader.getSystemClassLoader().getResource("config.properties"); Configuration.load(url); PropertyConfigurator.configure(url); AbstractCommand command = getCommand(commandLine); if (command != null) { CommandResult result = command.perform(); switch (result.getCode()) { case SUCCESS: logger.info(result.getMessage()); break; default: logger.warn(result.getMessage()); break; } } else { logger.warn("Could not find command"); } }
public void test12210() { // create the main options object which will handle the first parameter Options mainOptions = new Options(); // There can be 2 main exclusive options: -exec|-rep // Therefore, place them in an option group String[] argv = new String[] {"-exec", "-exec_opt1", "-exec_opt2"}; OptionGroup grp = new OptionGroup(); grp.addOption(new Option("exec", false, "description for this option")); grp.addOption(new Option("rep", false, "description for this option")); mainOptions.addOptionGroup(grp); // for the exec option, there are 2 options... Options execOptions = new Options(); execOptions.addOption("exec_opt1", false, " desc"); execOptions.addOption("exec_opt2", false, " desc"); // similarly, for rep there are 2 options... Options repOptions = new Options(); repOptions.addOption("repopto", false, "desc"); repOptions.addOption("repoptt", false, "desc"); // create the parser GnuParser parser = new GnuParser(); // finally, parse the arguments: // first parse the main options to see what the user has specified // We set stopAtNonOption to true so it does not touch the remaining // options try { CommandLine cmd = parser.parse(mainOptions, argv, true); // get the remaining options... argv = cmd.getArgs(); if (cmd.hasOption("exec")) { cmd = parser.parse(execOptions, argv, false); // process the exec_op1 and exec_opt2... assertTrue(cmd.hasOption("exec_opt1")); assertTrue(cmd.hasOption("exec_opt2")); } else if (cmd.hasOption("rep")) { cmd = parser.parse(repOptions, argv, false); // process the rep_op1 and rep_opt2... } else { fail("exec option not found"); } } catch (ParseException exp) { fail("Unexpected exception: " + exp.getMessage()); } }