Parse the command line arguments. @param rawArgs the string arguments to be parsed. @return The parsed command line. opts will be stored under the short argument name. args will be stored under the argument name, unless no arguments are configured, and then they will be stored under "ARGS".
(String... rawArgs)
| 400 | * @throws Exception on any error. |
| 401 | */ |
| 402 | public Map<String, Object> parse(String... rawArgs) throws Exception { |
| 403 | Options options = new Options(); |
| 404 | for (Opt opt : opts) { |
| 405 | if (opt.noValue) { |
| 406 | options.addOption(Option.builder(opt.shortName).longOpt(opt.longName).hasArg(false).build()); |
| 407 | } else { |
| 408 | options.addOption(Option.builder(opt.shortName).longOpt(opt.longName).hasArg().build()); |
| 409 | } |
| 410 | } |
| 411 | DefaultParser parser = new DefaultParser(); |
| 412 | CommandLine cl = parser.parse(options, rawArgs); |
| 413 | HashMap<String, Object> ret = new HashMap<>(); |
| 414 | for (Opt opt : opts) { |
| 415 | if (opt.noValue) { |
| 416 | ret.put(opt.shortName, cl.hasOption(opt.shortName)); |
| 417 | } else { |
| 418 | Object current = null; |
| 419 | String[] strings = cl.getOptionValues(opt.shortName); |
| 420 | if (strings != null) { |
| 421 | for (String val : strings) { |
| 422 | current = opt.process(current, val); |
| 423 | } |
| 424 | } |
| 425 | if (current == null) { |
| 426 | current = opt.defaultValue; |
| 427 | } |
| 428 | ret.put(opt.shortName, current); |
| 429 | } |
| 430 | } |
| 431 | List<Arg> fullArgs = new ArrayList<>(args); |
| 432 | fullArgs.addAll(optionalArgs); |
| 433 | List<String> stringArgs = cl.getArgList(); |
| 434 | if (args.size() > stringArgs.size()) { |
| 435 | throw new RuntimeException("Wrong number of arguments at least " + args.size() |
| 436 | + " expected, but only " + stringArgs.size() + " found"); |
| 437 | } |
| 438 | |
| 439 | int argIndex = 0; |
| 440 | int stringArgIndex = 0; |
| 441 | if (fullArgs.size() > 0) { |
| 442 | while (argIndex < fullArgs.size()) { |
| 443 | Arg arg = fullArgs.get(argIndex); |
| 444 | boolean isLastArg = (argIndex == (fullArgs.size() - 1)); |
| 445 | Object current = null; |
| 446 | int maxStringIndex = isLastArg ? stringArgs.size() : (stringArgIndex + 1); |
| 447 | for (; stringArgIndex < maxStringIndex; stringArgIndex++) { |
| 448 | current = arg.process(current, stringArgs.get(stringArgIndex)); |
| 449 | } |
| 450 | ret.put(arg.name, current); |
| 451 | argIndex++; |
| 452 | } |
| 453 | } else { |
| 454 | ret.put("ARGS", stringArgs); |
| 455 | } |
| 456 | return ret; |
| 457 | } |
| 458 | } |
| 459 | } |