Example usage for org.apache.commons.cli CommandLine getArgList

List of usage examples for org.apache.commons.cli CommandLine getArgList

Introduction

In this page you can find the example usage for org.apache.commons.cli CommandLine getArgList.

Prototype

public List getArgList() 

Source Link

Document

Retrieve any left-over non-recognized options and arguments

Usage

From source file:org.seedstack.seed.shell.internal.AbstractShell.java

@SuppressWarnings("unchecked")
protected Command createCommandAction(String qualifiedName, List<String> args) {
    if (Strings.isNullOrEmpty(qualifiedName)) {
        throw SeedException.createNew(ShellErrorCode.MISSING_COMMAND);
    }//from w ww.  java  2s.  c o  m

    String commandScope;
    String commandName;

    if (qualifiedName.contains(":")) {
        String[] splitName = qualifiedName.split(":");
        commandScope = splitName[0].trim();
        commandName = splitName[1].trim();
    } else {
        commandScope = null;
        commandName = qualifiedName.trim();
    }

    // Build CLI options
    Options options = new Options();
    for (org.seedstack.seed.core.spi.command.Option option : commandRegistry.getOptionsInfo(commandScope,
            commandName)) {
        options.addOption(option.name(), option.longName(), option.hasArgument(), option.description());
    }

    // Parse the command options
    CommandLine cmd;
    try {
        cmd = commandLineParser.parse(options, args.toArray(new String[args.size()]));
    } catch (ParseException e) {
        throw SeedException.wrap(e, ShellErrorCode.OPTIONS_SYNTAX_ERROR);
    }

    Map<String, String> optionValues = new HashMap<String, String>();
    for (Option option : cmd.getOptions()) {
        optionValues.put(option.getOpt(), option.getValue());
    }

    return commandRegistry.createCommand(commandScope, commandName, cmd.getArgList(), optionValues);
}

From source file:org.seedstack.shell.internal.AbstractShell.java

@SuppressWarnings("unchecked")
Command createCommandAction(String qualifiedName, List<String> args) {
    if (Strings.isNullOrEmpty(qualifiedName)) {
        throw SeedException.createNew(ShellErrorCode.MISSING_COMMAND);
    }//www .  ja v  a 2s . co  m

    String commandScope;
    String commandName;

    if (qualifiedName.contains(":")) {
        String[] splitName = qualifiedName.split(":");
        commandScope = splitName[0].trim();
        commandName = splitName[1].trim();
    } else {
        commandScope = null;
        commandName = qualifiedName.trim();
    }

    // Build CLI options
    Options options = new Options();
    for (org.seedstack.seed.command.Option option : commandRegistry.getOptionsInfo(commandScope, commandName)) {
        options.addOption(option.name(), option.longName(), option.hasArgument(), option.description());
    }

    // Parse the command options
    CommandLine cmd;
    try {
        cmd = commandLineParser.parse(options, args.toArray(new String[args.size()]));
    } catch (ParseException e) {
        throw SeedException.wrap(e, ShellErrorCode.OPTIONS_SYNTAX_ERROR);
    }

    Map<String, String> optionValues = new HashMap<>();
    for (Option option : cmd.getOptions()) {
        optionValues.put(option.getOpt(), option.getValue());
    }

    return commandRegistry.createCommand(commandScope, commandName, cmd.getArgList(), optionValues);
}

From source file:org.sonatype.gshell.util.cli2.CliProcessor.java

public void process(final String... args) throws Exception {
    assert args != null;

    CliParser parser = null;/*from  w w w  .  j  a v a  2s . com*/

    switch (flavor) {
    case POSIX:
        parser = new PosixParser();
        break;
    case GNU:
        parser = new GnuParser();
        break;
    }

    assert parser != null;

    CommandLine cl;

    try {
        cl = parser.parse(createOptions(), args, stopAtNonOption);
    } catch (UnrecognizedOptionException e) {
        throw new ProcessingException(Messages.UNDEFINED_OPTION.format(e.getOption()));
    } catch (MissingArgumentException e) {
        OptionDescriptor desc = ((Opt) e.getOption()).getDescriptor();
        throw new ProcessingException(
                Messages.MISSING_OPERAND.format(desc.getSyntax(), desc.renderToken(messages)));
    } catch (ParseException e) {
        throw new ProcessingException(e);
    }

    Set<CliDescriptor> present = new HashSet<CliDescriptor>();
    boolean override = false;

    for (Object tmp : cl.getOptions()) {
        Opt opt = (Opt) tmp;
        log.trace("Processing option: {}", opt);

        OptionDescriptor desc = opt.getDescriptor();
        present.add(desc);

        // Track the override, this is used to handle when --help present, but a required arg/opt is missing
        if (!override) {
            override = desc.getOverride();
        }

        Handler handler = Handlers.create(desc);
        String[] values = opt.getValues();

        if (values == null || values.length == 0) {
            // Set the value
            handler.handle(opt.getValue());
        } else {
            // Set the values
            for (String value : values) {
                handler.handle(value);
            }
        }
    }

    log.trace("Remaining arguments: {}", cl.getArgList());

    int i = 0;
    for (final String arg : cl.getArgs()) {
        log.trace("Processing argument: {}", arg);

        // Check if we allow an argument or we have overflowed
        if (i >= argumentDescriptors.size()) {
            throw new ProcessingException(
                    argumentDescriptors.size() == 0 ? Messages.NO_ARGUMENT_ALLOWED.format(arg)
                            : Messages.TOO_MANY_ARGUMENTS.format(arg));
        }

        ArgumentDescriptor desc = argumentDescriptors.get(i);
        present.add(desc);

        // For single-valued args, increment the argument index, else let the multivalued handler consume it
        if (!desc.isMultiValued()) {
            i++;
        }

        // Set the value
        Handler handler = Handlers.create(desc);
        handler.handle(arg);
    }

    // Check for any required arguments which were not present
    if (!override) {
        try {
            parser.ensureRequiredOptionsPresent();
        } catch (MissingOptionException e) {
            throw new ProcessingException(Messages.REQUIRED_OPTION_MISSING.format(e.getMissingOptions()));
        }

        for (ArgumentDescriptor arg : argumentDescriptors) {
            if (arg.isRequired() && !present.contains(arg)) {
                throw new ProcessingException(
                        Messages.REQUIRED_ARGUMENT_MISSING.format(arg.renderToken(messages)));
            }
        }
    }

    // TODO: Handle setting defaults
}

From source file:org.sonatype.mercury.mp3.delta.cli.DeltaManagerCli.java

/**
 * @throws Exception // ww w . j  av a2s  .c om
 * 
 */
private void closure(CommandLine cli) throws Exception {
    boolean testBinaries = !cli.hasOption(NO_TEST_BINARIES);

    initMonitor(cli);
    initSettings(cli, _monitor);

    File settingsFile = null;

    settingsFile = new File(_settings);

    setRepositories(cli, settingsFile, _monitor);

    DependencyUtil du = new DependencyUtil(_mercury);

    String dep = cli.getOptionValue(CLOSURE);

    List<String> theRest = cli.getArgList();

    if (Util.isEmpty(theRest) || theRest.size() < 3) {
        _monitor.message(LANG.getMessage("cli.closure.usage"));
        return;
    }

    String re = theRest.get(0);

    String verFrom = theRest.get(1);

    String verTo = theRest.get(2);

    List<ArtifactMetadata> deps = du.floatSnapshot(new ArtifactQueryList(dep), re, verFrom, verTo,
            ArtifactScopeEnum.runtime, _repos, _monitor);

    List<Artifact> binaries = null;

    if (testBinaries)
        _mercury.read(_repos, deps);

    if (!Util.isEmpty(deps)) {
        if (testBinaries && Util.isEmpty(binaries)) {
            _monitor.message(LANG.getMessage("no.binaries.for", deps.toString()));
            return;
        }

        if (testBinaries && binaries.size() != deps.size()) {
            List<ArtifactMetadata> diff = (List<ArtifactMetadata>) CdUtil.binDiff(deps, binaries);
            int diffSize = diff == null ? 0 : diff.size();

            _monitor.message(LANG.getMessage("no.all.binaries.for", "" + binaries.size(), "" + deps.size(),
                    "" + diffSize, diff == null ? "[]" : diff.toString()));
            return;
        }

        System.out.println("<dependencies>");

        for (ArtifactMetadata md : deps)
            System.out.println("<dependency><name>" + md.toString() + "</name></dependency>");

        System.out.println("</dependencies>");
    } else
        System.out.println("No dependencies found");
}

From source file:org.structnetalign.util.NetworkCombiner.java

public static void main(String[] args) {

    Options options = getOptions();/*from   w ww.j  a  v  a 2s.c om*/
    CommandLineParser parser = new GnuParser();
    CommandLine cmd;
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        printUsage(e.getMessage(), options);
        return;
    }

    File output = new File(cmd.getOptionValue("output"));

    double probability;
    try {
        probability = Double.parseDouble(cmd.getOptionValue("probability"));
    } catch (NumberFormatException e) {
        printUsage("probability must be a floating-point number", options);
        return;
    }

    String pdbDir = cmd.getOptionValue("pdb_dir");
    if (pdbDir != null) {
        System.setProperty(AbstractUserArgumentProcessor.PDB_DIR, pdbDir);
        AtomCacheFactory.setCache(pdbDir);
    }

    boolean removeLonely = cmd.hasOption("remove_lonely");
    boolean requirePdb = cmd.hasOption("require_pdb");
    boolean requireScop = cmd.hasOption("require_scop");
    boolean requireFasta = cmd.hasOption("require_fasta");

    List<?> argList = cmd.getArgList();
    File[] inputs = new File[argList.size()];
    for (int i = 0; i < argList.size(); i++) {
        inputs[i] = new File(argList.get(i).toString());
    }

    runCombiner(output, probability, requirePdb, requireScop, requireFasta, removeLonely, inputs);

}

From source file:org.sysmgr.listmaker.Main.java

public static void main(String[] argv) throws IOException, ParseException {
    Options o = new Options();
    o.addOption("p", "props", true, "Name of configuration properties file");

    CommandLineParser clp = new GnuParser();
    CommandLine cl = clp.parse(o, argv);

    // Load properties file
    Properties config = new Properties();
    try {// w ww .  j av  a 2  s. c  o m
        config.load(new FileInputStream(cl.getOptionValue("props")));
    } catch (Throwable t) {
        printUsage();
        System.err.println("ERROR: Could not load" + " properties file: " + t.getMessage());
        System.exit(2);
        return;
    }

    // Parse method
    Nexus n = new Nexus(config);
    Action a = null;
    if (cl.getArgList() == null || cl.getArgList().size() < 1) {
        System.err.println("ERROR: Must specify a list name!");
    } else {
        a = new SyncAction(n, (String) cl.getArgList().get(0));
    }

    if (a == null) {
        printUsage();
        System.exit(1);
        return;
    }
    a.doAction();
    a.close();
}

From source file:org.sysmgr.listmaker.Main.java

private static boolean isCommand(CommandLine cl, String match) {
    return ((String) cl.getArgList().get(0)).trim().equalsIgnoreCase(match);
}

From source file:org.terracotta.voter.TCVoterMain.java

public void processArgs(String[] args) throws ConfigurationSetupException, ParseException {
    DefaultParser parser = new DefaultParser();
    Options voterOptions = voterOptions();
    CommandLine commandLine = parser.parse(voterOptions, args);

    if (commandLine.getArgList().size() > 0) {
        throw new ConfigurationSetupException("Invalid arguments provided: " + commandLine.getArgList());
    }//from w w  w  .j  a v a  2  s  . c o  m

    if (commandLine.hasOption(HELP)) {
        new HelpFormatter().printHelp("start-voter.sh[bat]", voterOptions);
        return;
    }

    if (commandLine.getOptions().length == 0) {
        throw new ConfigurationSetupException(
                "Neither the override option -o nor the regular options -s or -f provided");
    }

    if (commandLine.hasOption(SERVER) && commandLine.hasOption(CONFIG_FILE)) {
        throw new ConfigurationSetupException(
                "Both -s and -f options provided. Use either one and not both together.");
    }

    Optional<Properties> connectionProps = getConnectionProperties(commandLine);
    if (commandLine.hasOption(SERVER)) {
        processServerArg(connectionProps, commandLine.getOptionValues(SERVER));
    } else if (commandLine.hasOption(CONFIG_FILE)) {
        processConfigFileArg(connectionProps, commandLine.getOptionValues(CONFIG_FILE));
    } else if (commandLine.hasOption(OVERRIDE)) {
        String hostPort = commandLine.getOptionValue(OVERRIDE);
        validateHostPort(hostPort);
        getVoter(connectionProps).overrideVote(hostPort);
    } else {
        throw new AssertionError("This should not happen");
    }
}

From source file:org.topdesk.maven.tracker.MavenCli.java

private MavenExecutionRequest populateRequest(CliRequest cliRequest) {
    MavenExecutionRequest request = cliRequest.request;
    CommandLine commandLine = cliRequest.commandLine;
    String workingDirectory = cliRequest.workingDirectory;
    boolean debug = cliRequest.debug;
    boolean quiet = cliRequest.quiet;
    boolean showErrors = cliRequest.showErrors;

    String[] deprecatedOptions = { "up", "npu", "cpu", "npr" };
    for (String deprecatedOption : deprecatedOptions) {
        if (commandLine.hasOption(deprecatedOption)) {
            cliRequest.stdout.println("[WARNING] Command line option -" + deprecatedOption
                    + " is deprecated and will be removed in future Maven versions.");
        }/*from  w ww . j av a  2  s . c o m*/
    }

    // ----------------------------------------------------------------------
    // Now that we have everything that we need we will fire up plexus and
    // bring the maven component to life for use.
    // ----------------------------------------------------------------------

    if (commandLine.hasOption(CLIManager.BATCH_MODE)) {
        request.setInteractiveMode(false);
    }

    boolean noSnapshotUpdates = false;
    if (commandLine.hasOption(CLIManager.SUPRESS_SNAPSHOT_UPDATES)) {
        noSnapshotUpdates = true;
    }

    // ----------------------------------------------------------------------
    //
    // ----------------------------------------------------------------------

    @SuppressWarnings("unchecked")
    List<String> goals = commandLine.getArgList();

    boolean recursive = true;

    // this is the default behavior.
    String reactorFailureBehaviour = MavenExecutionRequest.REACTOR_FAIL_FAST;

    if (commandLine.hasOption(CLIManager.NON_RECURSIVE)) {
        recursive = false;
    }

    if (commandLine.hasOption(CLIManager.FAIL_FAST)) {
        reactorFailureBehaviour = MavenExecutionRequest.REACTOR_FAIL_FAST;
    } else if (commandLine.hasOption(CLIManager.FAIL_AT_END)) {
        reactorFailureBehaviour = MavenExecutionRequest.REACTOR_FAIL_AT_END;
    } else if (commandLine.hasOption(CLIManager.FAIL_NEVER)) {
        reactorFailureBehaviour = MavenExecutionRequest.REACTOR_FAIL_NEVER;
    }

    if (commandLine.hasOption(CLIManager.OFFLINE)) {
        request.setOffline(true);
    }

    boolean updateSnapshots = false;

    if (commandLine.hasOption(CLIManager.UPDATE_SNAPSHOTS)) {
        updateSnapshots = true;
    }

    String globalChecksumPolicy = null;

    if (commandLine.hasOption(CLIManager.CHECKSUM_FAILURE_POLICY)) {
        globalChecksumPolicy = MavenExecutionRequest.CHECKSUM_POLICY_FAIL;
    } else if (commandLine.hasOption(CLIManager.CHECKSUM_WARNING_POLICY)) {
        globalChecksumPolicy = MavenExecutionRequest.CHECKSUM_POLICY_WARN;
    }

    File baseDirectory = new File(workingDirectory, "").getAbsoluteFile();

    // ----------------------------------------------------------------------
    // Profile Activation
    // ----------------------------------------------------------------------

    List<String> activeProfiles = new ArrayList<String>();

    List<String> inactiveProfiles = new ArrayList<String>();

    if (commandLine.hasOption(CLIManager.ACTIVATE_PROFILES)) {
        String[] profileOptionValues = commandLine.getOptionValues(CLIManager.ACTIVATE_PROFILES);
        if (profileOptionValues != null) {
            for (int i = 0; i < profileOptionValues.length; ++i) {
                StringTokenizer profileTokens = new StringTokenizer(profileOptionValues[i], ",");

                while (profileTokens.hasMoreTokens()) {
                    String profileAction = profileTokens.nextToken().trim();

                    if (profileAction.startsWith("-") || profileAction.startsWith("!")) {
                        inactiveProfiles.add(profileAction.substring(1));
                    } else if (profileAction.startsWith("+")) {
                        activeProfiles.add(profileAction.substring(1));
                    } else {
                        activeProfiles.add(profileAction);
                    }
                }
            }
        }
    }

    TransferListener transferListener;

    if (quiet) {
        transferListener = new QuietMavenTransferListener();
    } else if (request.isInteractiveMode()) {
        transferListener = new ConsoleMavenTransferListener(cliRequest.stdout);
    } else {
        transferListener = new BatchModeMavenTransferListener(cliRequest.stdout);
    }

    String alternatePomFile = null;
    if (commandLine.hasOption(CLIManager.ALTERNATE_POM_FILE)) {
        alternatePomFile = commandLine.getOptionValue(CLIManager.ALTERNATE_POM_FILE);
    }

    int loggingLevel;

    if (debug) {
        loggingLevel = MavenExecutionRequest.LOGGING_LEVEL_DEBUG;
    } else if (quiet) {
        // TODO: we need to do some more work here. Some plugins use sys out or log errors at info level.
        // Ideally, we could use Warn across the board
        loggingLevel = MavenExecutionRequest.LOGGING_LEVEL_ERROR;
        // TODO:Additionally, we can't change the mojo level because the component key includes the version and
        // it isn't known ahead of time. This seems worth changing.
    } else {
        loggingLevel = MavenExecutionRequest.LOGGING_LEVEL_INFO;
    }

    File userToolchainsFile;
    if (commandLine.hasOption(CLIManager.ALTERNATE_USER_TOOLCHAINS)) {
        userToolchainsFile = new File(commandLine.getOptionValue(CLIManager.ALTERNATE_USER_TOOLCHAINS));
        userToolchainsFile = resolveFile(userToolchainsFile, workingDirectory);
    } else {
        userToolchainsFile = MavenCli.DEFAULT_USER_TOOLCHAINS_FILE;
    }

    request.setBaseDirectory(baseDirectory).setGoals(goals).setSystemProperties(cliRequest.systemProperties)
            .setUserProperties(cliRequest.userProperties).setReactorFailureBehavior(reactorFailureBehaviour) // default: fail fast
            .setRecursive(recursive) // default: true
            .setShowErrors(showErrors) // default: false
            .addActiveProfiles(activeProfiles) // optional
            .addInactiveProfiles(inactiveProfiles) // optional
            .setLoggingLevel(loggingLevel) // default: info
            .setTransferListener(transferListener) // default: batch mode which goes along with interactive
            .setUpdateSnapshots(updateSnapshots) // default: false
            .setNoSnapshotUpdates(noSnapshotUpdates) // default: false
            .setGlobalChecksumPolicy(globalChecksumPolicy) // default: warn
            .setUserToolchainsFile(userToolchainsFile);

    if (alternatePomFile != null) {
        File pom = resolveFile(new File(alternatePomFile), workingDirectory);

        request.setPom(pom);
    } else {
        File pom = modelProcessor.locatePom(baseDirectory);

        if (pom.isFile()) {
            request.setPom(pom);
        }
    }

    if ((request.getPom() != null) && (request.getPom().getParentFile() != null)) {
        request.setBaseDirectory(request.getPom().getParentFile());
    }

    if (commandLine.hasOption(CLIManager.RESUME_FROM)) {
        request.setResumeFrom(commandLine.getOptionValue(CLIManager.RESUME_FROM));
    }

    if (commandLine.hasOption(CLIManager.PROJECT_LIST)) {
        String projectList = commandLine.getOptionValue(CLIManager.PROJECT_LIST);
        String[] projects = StringUtils.split(projectList, ",");
        request.setSelectedProjects(Arrays.asList(projects));
    }

    if (commandLine.hasOption(CLIManager.ALSO_MAKE)
            && !commandLine.hasOption(CLIManager.ALSO_MAKE_DEPENDENTS)) {
        request.setMakeBehavior(MavenExecutionRequest.REACTOR_MAKE_UPSTREAM);
    } else if (!commandLine.hasOption(CLIManager.ALSO_MAKE)
            && commandLine.hasOption(CLIManager.ALSO_MAKE_DEPENDENTS)) {
        request.setMakeBehavior(MavenExecutionRequest.REACTOR_MAKE_DOWNSTREAM);
    } else if (commandLine.hasOption(CLIManager.ALSO_MAKE)
            && commandLine.hasOption(CLIManager.ALSO_MAKE_DEPENDENTS)) {
        request.setMakeBehavior(MavenExecutionRequest.REACTOR_MAKE_BOTH);
    }

    String localRepoProperty = request.getUserProperties().getProperty(MavenCli.LOCAL_REPO_PROPERTY);

    if (localRepoProperty == null) {
        localRepoProperty = request.getSystemProperties().getProperty(MavenCli.LOCAL_REPO_PROPERTY);
    }

    if (localRepoProperty != null) {
        request.setLocalRepositoryPath(localRepoProperty);
    }

    final String threadConfiguration = commandLine.hasOption(CLIManager.THREADS)
            ? commandLine.getOptionValue(CLIManager.THREADS)
            : request.getSystemProperties().getProperty(MavenCli.THREADS_DEPRECATED); // TODO: Remove this setting. Note that the int-tests use it

    if (threadConfiguration != null) {
        request.setPerCoreThreadCount(threadConfiguration.contains("C"));
        if (threadConfiguration.contains("W")) {
            LifecycleWeaveBuilder.setWeaveMode(request.getUserProperties());
        }
        request.setThreadCount(threadConfiguration.replace("C", "").replace("W", "").replace("auto", ""));
    }

    request.setCacheNotFound(true);
    request.setCacheTransferError(false);

    return request;
}