After command line has been parsed, make sure that all required arguments have values, and that
lists with minimum # of elements have sufficient values.

@throws CommandLineException if arguments requirements are not satisfied.
551736
private void validateArgumentValues()  {
        namedArgumentDefinitions = validatePluginArgumentValues(); // trim the list of plugin-derived argument definitions before validation
        for (final NamedArgumentDefinition argumentDefinition : namedArgumentDefinitions) {
            argumentDefinition.validateValues(this);
        }
        if (positionalArgumentDefinition != null) {
            positionalArgumentDefinition.validateValues(this);
        }
    }
1221183
public static void main(String[] args) throws IOException, ParserConfigurationException, SAXException {
    JnaTools.setBugWorkaroundProperty();
    CommandLineParser commandLineParser = new CommandLineParser();
    CommandLineOptions options = null;
    try {
       options = commandLineParser.parseOptions(args);
    } catch (WrongParameterNumberException e) {
      commandLineParser.printUsage();
      System.exit(1);
    } catch (IllegalArgumentException e) {
      System.err.println(e.toString());
      System.exit(1);
    } catch (UnknownParameterException e) {
      if (e.getMessage() != null) {
        System.err.println(e.getMessage());
      } else {
        System.err.println(e.toString());
      }
      commandLineParser.printUsage(System.err);
      System.exit(1);
    }
    if (options.isPrintUsage()) {
      commandLineParser.printUsage();
      System.exit(1);
    }
    if (options.isPrintVersion()) {
      System.out.println("LanguageTool version " + JLanguageTool.VERSION + " (" + JLanguageTool.BUILD_DATE + ", " + JLanguageTool.GIT_SHORT_ID + ")");
      System.exit(0);
    }
    if (options.isPrintLanguages()) {
      printLanguages();
      System.exit(0);
    }

    if (options.getFilename() == null) {
      options.setFilename("-");
    }

    String languageHint = null;
    if (options.getLanguage() == null) {
      if (!options.isXmlFormat() && !options.isAutoDetect()) {
        System.err.println("No language specified, using English (no spell checking active, " +
                "specify a language variant like 'en-GB' if available)");
      }
      options.setLanguage(new English());
    } else if (!options.isXmlFormat() && !options.isApplySuggestions()) {
      languageHint = "Expected text language: " + options.getLanguage().getName();
    }

    options.getLanguage().getSentenceTokenizer().setSingleLineBreaksMarksParagraph(
            options.isSingleLineBreakMarksParagraph());

    Main prg = new Main(options);
    if (options.getFalseFriendFile() != null) {
      List<AbstractPatternRule> ffRules = prg.lt.loadFalseFriendRules(options.getFalseFriendFile());
      for (AbstractPatternRule ffRule : ffRules) {
        prg.lt.addRule(ffRule);
      }
    }
    if (prg.lt.getAllActiveRules().isEmpty()) {
      List<String> catIds = options.getEnabledCategories().stream().map(i -> i.toString()).collect(Collectors.toList());
      throw new RuntimeException("No rules are active. Please make sure your rule ids " +
              "(" + options.getEnabledRules() + ") and " +
              "category ids (" + catIds + ") are correct");
    }
    if (languageHint != null) {
      String spellHint = "";
      if (!prg.isSpellCheckingActive()) {
        if (prg.lt.getLanguage().isVariant()) {
          spellHint = " (no spell checking active)";
        } else {
          spellHint = " (no spell checking active, specify a language variant like 'en-GB' if available)";
        }
      }
      System.err.println(languageHint + spellHint);
    }
    prg.setListUnknownWords(options.isListUnknown());
    if (options.isProfile()) {
      prg.setProfilingMode();
    }
    if (options.isBitext()) {
      if (options.getMotherTongue() == null) {
        throw new IllegalArgumentException("You have to set the source language (as mother tongue) in bitext mode");
      }
      File bitextRuleFile = options.getBitextRuleFile() != null ? new File(options.getBitextRuleFile()) : null;
      prg.setBitextMode(options.getMotherTongue(), options.getDisabledRules(), options.getEnabledRules(), bitextRuleFile);
    }
    if (options.isRecursive()) {
      prg.runRecursive(options.getFilename(), options.getEncoding(), options.isXmlFiltering());
    } else {
      if (options.isLineByLine()) {
        prg.runOnFileLineByLine(options.getFilename(), options.getEncoding());
      } else {
        prg.runOnFile(options.getFilename(), options.getEncoding(), options.isXmlFiltering());
      }
    }
    prg.cleanUp();
  }
1051043
public static void main(String[] args) throws ParseException {
		CliFrontend cli = new CliFrontend();
		int retCode = cli.parseParameters(args);
		System.exit(retCode);
	}
1352519
public static void checkNumOfArgsNoLessThan(Command cmd, CommandLine cl, int n) throws
      InvalidArgumentException {
    if (cl.getArgs().length < n) {
      throw new InvalidArgumentException(ExceptionMessage.INVALID_ARGS_NUM_INSUFFICIENT
          .getMessage(cmd.getCommandName(), n, cl.getArgs().length));
    }
  }
1336759
static void processArgs(String[] args, final PrintStream out, final PrintStream err) {
        GroovyCommand groovyCommand = new GroovyCommand();
        CommandLine parser = new CommandLine(groovyCommand).setUnmatchedArgumentsAllowed(true).setStopAtUnmatched(true);
        try {
            List<CommandLine> result = parser.parse(args);
            if (CommandLine.printHelpIfRequested(result, out, err, Help.Ansi.AUTO)) {
                return;
            }
            // TODO: pass printstream(s) down through process
            if (!groovyCommand.process(parser)) {
                // If we fail, then exit with an error so scripting frameworks can catch it.
                System.exit(1);
            }

        } catch (ParameterException ex) { // command line arguments could not be parsed
            err.println(ex.getMessage());
            ex.getCommandLine().usage(err);
        } catch (IOException ioe) {
            err.println("error: " + ioe.getMessage());
        }
    }
196202
public static void main(String[] args) {
        if (args.length < 2) { // NOSONAR
            LOGGER.error("There must be at least two arguments");
            return;
        }
        int lastIndex = args.length - 1;
        AllureReportGenerator reportGenerator = new AllureReportGenerator(
                getFiles(Arrays.copyOf(args, lastIndex))
        );
        reportGenerator.generate(new File(args[lastIndex]));
    }
86867
public static void main(String[] args)
	{
		CommandLineRemoteRunner runner = new CommandLineRemoteRunner();
		LoggingMonitor monitor = new LoggingMonitor(System.out, System.err);
		runner.setMonitor(monitor);

		try
		{
			runner.run(args);
		}
		catch (ParseException e)
		{
			System.err.println(e.getMessage());
			System.err.println("Try '--help' for more information.");

			if (e.getCause() != null)
			{
				System.err.println("Caused by:");
				e.getCause().printStackTrace(System.err);
			}

			System.exit(1);
		}
		catch (Throwable t)
		{
			monitor.exceptionOccured(t);
			System.exit(1);
		}
	}
413441
protected void initializeArguments() {

    Map<String, BasicDoubleLinkedNode<CliArgumentContainer>> argumentMap = new HashMap<>();
    BasicDoubleLinkedNode<CliArgumentContainer> startHead = null;
    BasicDoubleLinkedNode<CliArgumentContainer> startTail = null;
    BasicDoubleLinkedNode<CliArgumentContainer> endHead = null;
    BasicDoubleLinkedNode<CliArgumentContainer> endTail = null;
    for (CliArgumentContainer argumentContainer : this.arguments) {
      String id = argumentContainer.getId();
      if ((CliArgument.ID_FIRST.equals(id)) || (CliArgument.ID_LAST.equals(id))) {
        throw new NlsIllegalArgumentException(id, argumentContainer.toString());
      }
      if (argumentMap.containsKey(id)) {
        throw new DuplicateObjectException(argumentContainer, id);
      }
      BasicDoubleLinkedNode<CliArgumentContainer> node = new BasicDoubleLinkedNode<>();
      node.setValue(argumentContainer);
      argumentMap.put(id, node);
      CliArgument cliArgument = argumentContainer.getArgument();
      boolean addAfter = cliArgument.addAfter();
      String nextTo = cliArgument.addCloseTo();
      if (CliArgument.ID_FIRST.equals(nextTo)) {
        if ((startHead == null) || (startTail == null)) {
          startHead = node;
          startTail = node;
        } else {
          if (addAfter) {
            startTail.insertAsNext(node);
            startTail = node;
          } else {
            startHead.insertAsPrevious(node);
            startHead = node;
          }
        }
        argumentContainer.init();
      } else if (CliArgument.ID_LAST.equals(nextTo)) {
        if ((endTail == null) || (endHead == null)) {
          endTail = node;
          endHead = node;
        } else {
          if (addAfter) {
            endTail.insertAsNext(node);
            endTail = node;
          } else {
            endHead.insertAsPrevious(node);
            endHead = node;
          }
        }
        argumentContainer.init();
      }
    }
    if ((startTail != null) && (endHead != null)) {
      // connect start and end of list...
      startTail.insertAsNext(endHead);
    }
    for (BasicDoubleLinkedNode<CliArgumentContainer> node : argumentMap.values()) {
      List<String> cycle = initializeArgumentRecursive(node, argumentMap);
      if (cycle != null) {
        StringBuilder sb = new StringBuilder();
        for (int i = cycle.size() - 1; i >= 0; i--) {
          sb.append(cycle.get(i));
          if (i > 0) {
            sb.append("-->");
          }
        }
        throw new IllegalStateException("Cyclic dependency of CLI modes: " + sb.toString());
      }
    }
    // order arguments
    if (startHead != null) {
      this.arguments.clear();
      startHead.addToList(this.arguments);
    } else if (endHead != null) {
      this.arguments.clear();
      BasicDoubleLinkedNode<CliArgumentContainer> node = endHead;
      BasicDoubleLinkedNode<CliArgumentContainer> previous = node.getPrevious();
      while (previous != null) {
        node = previous;
        previous = node.getPrevious();
      }
      node.addToList(this.arguments);
    }
  }
152866
public void run(String[] args) {
    // Add and parse options.
    OptionParser parser = new OptionParser();
    initializeCommonOptions(parser);
    initializeOptions(parser);

    String errorMessage = null;
    try {
      parsedOptions = parser.parse(args);
    } catch (OptionException e) {
      errorMessage = e.getMessage();
    }

    boolean printHelp = false;
    if (errorMessage != null) {
      // If an error occurs, the options don't parse.
      // Therefore, we must manually check if the help option was
      // given.
      for (int i = 0; i < args.length; i++) {
        if (args[i].equals("--help")) {
          printHelp = true;
        }
      }
    }

    if (errorMessage != null && !printHelp) {
      System.err.println(errorMessage);
      System.err.println("Try --help for more information about options.");
      System.exit(1);
    }

    if (printHelp || parsedOptions.has(helpOpt)) {
      // If a help option is given, print help then quit.
      try {
        parser.printHelpOn(System.err);
      } catch (IOException ioException) {
        throw new RuntimeException(ioException);
      }
      System.exit(0);
    }

    // Log any passed-in options.
    if (!parsedOptions.has(noPrintOptions)) {
      System.out.println("Command-line options:");
      for (OptionSpec<?> optionSpec : parsedOptions.specs()) {
        if (parsedOptions.hasArgument(optionSpec)) {
          System.out.println("--" + Iterables.getFirst(optionSpec.options(), "") + " "
              + Joiner.on(" ").join(parsedOptions.valuesOf(optionSpec)));
        } else {
          System.out.println("--" + Iterables.getFirst(optionSpec.options(), ""));
        }
      }
      System.out.println("");
    }

    // Run the program.
    long startTime = System.currentTimeMillis();
    processOptions(parsedOptions);
    run(parsedOptions);
    long endTime = System.currentTimeMillis();

    if (!parsedOptions.has(noPrintOptions)) {
      System.out.println("Total time elapsed: " + TimeUtils.durationToString(endTime - startTime));
    }

    System.exit(0);
  }
902909
public static void mainInternal(String[] args) throws Exception {

        Options options = new Options();
        CmdLineParser parser = new CmdLineParser(options);
        try {
            parser.parseArgument(args);
        } catch (CmdLineException e) {
            helpScreen(parser);
            return;
        }

        try {
            List<String> configs = new ArrayList<>();
            if (options.configs != null) {
                configs.addAll(Arrays.asList(options.configs.split(",")));
            }
            ConfigSupport.applyConfigChange(ConfigSupport.getJBossHome(), configs, options.enable);
        } catch (ConfigException ex) {
            ConfigLogger.error(ex);
            throw ex;
        } catch (Throwable th) {
            ConfigLogger.error(th);
            throw th;
        }
    }
789112
@SuppressWarnings({"rawtypes", "unchecked"})
    private void setCollectionValues(
            final CommandLineArgumentParser commandLineArgumentParser,
            final List<String> preprocessedValues) // Note that some of these might be tag surrogates
    {
        final Collection c = (Collection) getArgumentValue();
        if (!commandLineArgumentParser.getAppendToCollectionsParserOption()) {
            // if this is a collection then we only want to clear it once at the beginning, before we
            // process any of the values, unless we're in APPEND_TO_COLLECTIONS mode
            c.clear();
        }

        for (int i = 0; i < preprocessedValues.size(); i++) {
            final String stringValue = preprocessedValues.get(i);
            if (stringValue.equals(NULL_ARGUMENT_STRING)) {
                if (i != 0) {
                    // if a "null" is included that isn't the first value for this option, honor it but warn, since it
                    // will clobber any previously set values, and may indicate an unintentional error on the user's part
                    logger.warn(String.format(
                            "A \"null\" value was detected for an option after values for that option were already set. " +
                                    "Clobbering previously set values for this option: %s.", getArgumentAliasDisplayString()));
                }
                if (!isOptional()) {
                    throw new CommandLineException(
                            String.format("Non \"null\" value must be provided for '%s'", getArgumentAliasDisplayString()));
                }
                c.clear();
            } else {
                // if a collection argument was presented as a tagged argument on the command line, and an expansion
                // file was provided as the value, propagate the tags to each value from the expansion file
                final Pair<String, String> normalizedSurrogatePair = getNormalizedTagValuePair(commandLineArgumentParser, stringValue);
                final List<String> expandedValues = argumentAnnotation.suppressFileExpansion() ?
                        Collections.singletonList(normalizedSurrogatePair.getRight()) :
                        commandLineArgumentParser.expandFromExpansionFile(
                                this,
                                normalizedSurrogatePair.getRight(),
                                preprocessedValues);

                for (final String expandedValue : expandedValues) {
                    final Object actualValue = getValuePopulatedWithTags(
                            normalizedSurrogatePair.getLeft(),
                            expandedValue);
                    checkArgumentRange(actualValue);
                    c.add(actualValue);
                }
            }
        }
    }
712568
@Override
	public List<ParsingError> doValidate() {

		// Component checks
		List<ParsingError> result = new ArrayList<> ();
		if( Utils.isEmptyOrWhitespaces( this.componentName ))
			result.add( error( ErrorCode.CMD_MISSING_COMPONENT_NAME ));

		else if( this.component == null )
			result.add( error( ErrorCode.CMD_INEXISTING_COMPONENT, component( this.componentName )));

		else if( ! this.component.getAncestors().isEmpty()) {

			Instance resolvedParentInstance;
			if( this.parentInstancePath == null )
				result.add( error( ErrorCode.CMD_MISSING_PARENT_INSTANCE ));
			else if(( resolvedParentInstance = this.context.resolveInstance( this.parentInstancePath )) == null )
				result.add( error( ErrorCode.CMD_NO_MATCHING_INSTANCE, instance( this.parentInstancePath )));
			else if( ! this.component.getAncestors().contains( resolvedParentInstance.getComponent()))
				result.add( error( ErrorCode.CMD_NOT_AN_ACCEPTABLE_PARENT, component( this.componentName )));

		} else if( this.parentInstancePath != null ) {
			result.add( error( ErrorCode.CMD_CANNOT_HAVE_ANY_PARENT, component( this.componentName )));
		}

		// Instance stuff
		if( Utils.isEmptyOrWhitespaces( this.instanceName ))
			result.add( error( ErrorCode.CMD_MISSING_INSTANCE_NAME ));
		else if( ! this.instanceName.matches( ParsingConstants.PATTERN_FLEX_ID ))
			result.add( error( ErrorCode.CMD_INVALID_INSTANCE_NAME, instance( this.instanceName )));

		String newInstancePath = (this.parentInstancePath == null ? "" : this.parentInstancePath) + "/" + this.instanceName;
		if( this.context.instancePathToComponentName.containsKey( newInstancePath ))
			result.add( error( ErrorCode.CMD_CONFLICTING_INSTANCE_NAME ));

		return result;
	}
741600
private void setArgumentValue(final Object value) {
        try {
            getUnderlyingField().set(getContainingObject(), value);
        } catch (final IllegalAccessException e) {
            throw new CommandLineException.ShouldNeverReachHereException(
                    String.format(
                            "Couldn't set field value for %s in %s with value %s.",
                            getUnderlyingField().getName(),
                            getContainingObject().toString(),
                            value.toString()),
                    e);
        }
    }
615458
public void fillArguments(@Nonnull @MustNotContainNull final List<ExpressionTree> arguments) {
    assertNotEmptySlot();

    if (arguments == null) {
      throw new PreprocessorException("[Expression]Argument list is null", this.sourceString, this.includeStack, null);
    }

    if (childElements.length != arguments.size()) {
      throw new PreprocessorException("Wrong argument list size", this.sourceString, this.includeStack, null);
    }

    int i = 0;
    for (ExpressionTree arg : arguments) {
      if (arg == null) {
        throw new PreprocessorException("[Expression]Argument [" + (i + 1) + "] is null", this.sourceString, this.includeStack, null);
      }

      if (!childElements[i].isEmptySlot()) {
        throw new PreprocessorException("[Expression]Non-empty slot detected, it is possible that there is a program error, contact a developer please", this.sourceString, this.includeStack, null);
      }

      final ExpressionTreeElement root = arg.getRoot();
      if (root.isEmptySlot()) {
        throw new PreprocessorException("[Expression]Empty argument [" + (i + 1) + "] detected", this.sourceString, this.includeStack, null);
      }
      childElements[i] = root;
      root.parentTreeElement = this;

      i++;
    }
  }
316853
public static void main(String... args) {
        CommandLineRunner runner = new CommandLineRunner();

        try {
            runner.run(args);
        } catch (Exception t) {
            System.err.println(t.getMessage());
            System.err.println("Try '--help' for more information.");

            t.printStackTrace(System.err);

            System.exit(1);
        }

        System.exit(0);
    }
704307
@SuppressWarnings("unchecked")
        public static void executeCommand(String[] args) throws IOException {

            OptionParser parser = getParser();

            // declare parameters
            List<String> metaKeys = null;
            String url = null;

            // parse command-line input
            args = AdminToolUtils.copyArrayAddFirst(args, "--" + OPT_HEAD_META_CHECK);
            OptionSet options = parser.parse(args);
            if(options.has(AdminParserUtils.OPT_HELP)) {
                printHelp(System.out);
                return;
            }

            // check required options and/or conflicting options
            AdminParserUtils.checkRequired(options, OPT_HEAD_META_CHECK);
            AdminParserUtils.checkRequired(options, AdminParserUtils.OPT_URL);

            // load parameters
            metaKeys = (List<String>) options.valuesOf(OPT_HEAD_META_CHECK);
            url = (String) options.valueOf(AdminParserUtils.OPT_URL);


            // execute command
            if(metaKeys.size() == 0
               || (metaKeys.size() == 1 && metaKeys.get(0).equals(METAKEY_ALL))) {
                metaKeys = Lists.newArrayList();
                metaKeys.add(MetadataStore.CLUSTER_KEY);
                metaKeys.add(MetadataStore.STORES_KEY);
                metaKeys.add(MetadataStore.SERVER_STATE_KEY);
            }

            AdminClient adminClient = AdminToolUtils.getAdminClient(url);

            doMetaCheck(adminClient, metaKeys);
        }
38544
@Override
    public String getValue(ParsedCommandLine args, boolean required) throws CommandFormatException {
        if(!required) {
            return null;
        }
        if(isPresent(args)) {
            return null;
        }
        throw new CommandFormatException("Required argument '" + fullName + "' is missing value.");
    }