CommandParser { public static HashMap<String, Object> parse(String[] _args, Options options) throws CommandLineParserException { final CommandLineParser parser = new DefaultParser(); CommandLine cmd = null; try { cmd = parser.parse(options, _args, true); } catch (ParseException e) { throw new CommandLineParserException(e.getMessage()); } HashMap<String, Object> mapOptionValues = new HashMap<>(); Collection<Option> optionCollection = options.getOptions(); for (Option option : optionCollection) { if (option.hasArg()) { mapOptionValues.put(option.getOpt(), cmd.getOptionValue(option.getOpt())); } else { if (cmd.hasOption(option.getOpt()) || cmd.hasOption(option.getLongOpt())) { mapOptionValues.put(option.getOpt(), true); } else { mapOptionValues.put(option.getOpt(), false); } } } return mapOptionValues; }  static HashMap<String, Object> parse(String[] _args, Options options);  }
@Test public void testParse() throws CommandLineParserException { Options options = new Options(); options.addRequiredOption( DIRECTORY_OPTION, DIRECTORY_LONG_OPTION, true, "directory containing mutiple commit folders with meta files"); options.addOption( OVERWRITE_OPTION, OVERWRITE_LONG_OPTION, false, "overwrite the bug if it already exists in the backend"); options.addOption(VERBOSE_OPTION, VERBOSE_LONG_OPTION, false, "Verbose mode"); options.addOption( UPLOAD_CONSTRUCT_OPTION, UPLOAD_LONG_OPTION, false, "Upload construct changes"); String _args = "-d test -u -v"; HashMap<String, Object> parsedCommands = CommandParser.parse(_args.split(" "), options); assertEquals("test", parsedCommands.get(DIRECTORY_OPTION)); assertTrue((boolean) parsedCommands.get(VERBOSE_OPTION)); assertTrue((boolean) parsedCommands.get(UPLOAD_CONSTRUCT_OPTION)); assertFalse((boolean) parsedCommands.get(OVERWRITE_OPTION)); }
@Test(expected = CommandLineParserException.class) public void testRequiredOptions() throws CommandLineParserException { Options options = new Options(); options.addRequiredOption( DIRECTORY_OPTION, DIRECTORY_LONG_OPTION, true, "directory containing mutiple commit folders with meta files"); options.addOption( OVERWRITE_OPTION, OVERWRITE_LONG_OPTION, false, "overwrite the bug if it already exists in the backend"); options.addOption(VERBOSE_OPTION, VERBOSE_LONG_OPTION, false, "Verbose mode"); options.addOption( UPLOAD_CONSTRUCT_OPTION, UPLOAD_LONG_OPTION, false, "Upload construct changes"); String _args = "-u -v"; CommandParser.parse(_args.split(" "), options); }