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

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

Introduction

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

Prototype

public Option[] getOptions() 

Source Link

Document

Returns an array of the processed Option s.

Usage

From source file:org.ppojo.ArgumentsParser.java

private static void parseTemplateFileArgs(CommandLine line, ArrayList<ITemplateFileQuery> queries)
        throws ParseException {
    if (line.hasOption(OptionNames.SEARCH)) {
        Option[] options = line.getOptions();
        for (Option option : options) {
            if (option.getOpt() == OptionNames.SEARCH) {
                List<String> values = option.getValuesList();
                if (values == null || values.size() != 2)
                    throw new ParseException(
                            "Invalid values for search option. Expected two arguments for option.");
                boolean isRecursive = parserIsRecursive(values.get(0));

                String fileFilter = FolderTemplateFileQuery.getDefaultFileFilter();
                String folderPath = null;
                File file = (new File(values.get(1))).getAbsoluteFile();
                boolean exists = file.exists();
                boolean isDirectory = file.isDirectory();
                if (exists) {
                    if (isDirectory) //folder path specification with omitted pattern
                        folderPath = file.getAbsolutePath();
                    else if (file.isFile()) { //the pattern resolves to a specific file
                        TemplateFileQuery templateFileQuery = new TemplateFileQuery(file.getAbsolutePath(),
                                true);/* www  .  ja v  a 2 s . c  o  m*/
                        queries.add(templateFileQuery);
                    } else
                        throw new ParseException(
                                "Invalid value for search option. Existing path value is neither a file or directory");

                } else {
                    File parentFile = file.getParentFile();
                    if (!parentFile.exists())
                        throw new FolderNotFoundException("Invalid value for search option. The folder path "
                                + parentFile.getAbsolutePath() + " does not exist");
                    if (!parentFile.isDirectory())
                        throw new InvalidFolderPathException("Invalid value for search option. The folder path "
                                + parentFile.getAbsolutePath() + " is not a folder");
                    String replaceStr = parentFile.toString();
                    if (!replaceStr.endsWith(File.separator))
                        replaceStr += File.separator;
                    fileFilter = file.toString().replace(replaceStr, "");
                    folderPath = parentFile.getAbsolutePath();
                }
                if (!Helpers.IsNullOrEmpty(folderPath)) {
                    folderPath = Paths.get(folderPath).normalize().toString();
                    FolderTemplateFileQuery query = new FolderTemplateFileQuery(folderPath, fileFilter,
                            isRecursive);
                    queries.add(query);
                }
            }
        }

    }

}

From source file:org.psidnell.omnifocus.cli.ActiveOptionProcessor.java

public boolean processOptions(P program, String[] args, int phase) throws Exception {

    CommandLineParser parser = new FixedParser();
    CommandLine cl = parser.parse(options, args);

    // If there are unrecognised options then stop
    @SuppressWarnings("unchecked")
    List<String> unrecognized = cl.getArgList();
    if (!unrecognized.isEmpty()) {
        if (!unrecognized.isEmpty()) {
            System.out.println("Unrecognised command line arguments: " + unrecognized);
        }//ww w  . j ava2 s  .  c o  m
        printHelp();
        return false;
    }

    // Set the option values on the options
    for (Object o : options.getOptions()) {
        @SuppressWarnings("unchecked")
        ActiveOption<P> opt = (ActiveOption<P>) o;
        opt.setValues(cl.getOptionValues(opt.getOpt()));
    }

    // Walk through the options processing in order
    for (Object o : cl.getOptions()) {
        @SuppressWarnings("unchecked")
        ActiveOption<P> opt = (ActiveOption<P>) o;
        if (opt.getPhase() == phase) {
            opt.process(program);
        }
    }

    return true;
}

From source file:org.pz.platypus.commandline.ClProcessor.java

public void processBooleanOptions(final CommandLine cl) {
    if (args.length == 0)
        gdd.log.severe(gdd.getLit("PLEASE_RERUN_WITH_FILENAMES")); // falls through to next test.

    processVerbosityOptions();/*from w  ww  . j a v  a2  s  .  c  o m*/

    if (cl.hasOption("-help") || cl.getOptions().length == 0) {
        MessagesToUser.showUsage(gdd.lits, clp);
        outputFormat = null; // indicates no further output to be done.
    }

    if (cl.hasOption("-fontlist")) {
        outputFormat = "fontlist";
    }
}

From source file:org.rhq.server.control.command.Console.java

@Override
protected int exec(CommandLine commandLine) {
    int rValue = RHQControl.EXIT_CODE_OK;

    if (commandLine.getOptions().length != 1) {
        printUsage();/*from   ww w.  ja  v a  2 s  .  c  o m*/
        rValue = RHQControl.EXIT_CODE_INVALID_ARGUMENT;
    } else {
        String option = commandLine.getOptions()[0].getLongOpt();
        try {
            if (option.equals(STORAGE_OPTION)) {
                if (isStorageInstalled()) {
                    rValue = Math.max(rValue, startStorageInForeground());
                } else {
                    log.warn("It appears that the storage node is not installed. The --" + STORAGE_OPTION
                            + " option will be ignored.");
                    rValue = RHQControl.EXIT_CODE_INVALID_ARGUMENT;
                }
            } else if (option.equals(SERVER_OPTION)) {
                if (isServerInstalled()) {
                    rValue = Math.max(rValue, startServerInForeground());
                } else {
                    log.warn("It appears that the server is not installed. The --" + SERVER_OPTION
                            + " option will be ignored.");
                    rValue = RHQControl.EXIT_CODE_INVALID_ARGUMENT;
                }
            } else if (option.equals(AGENT_OPTION)) {
                if (isAgentInstalled()) {
                    rValue = Math.max(rValue, startAgentInForeground());
                } else {
                    log.warn("It appears that the agent is not installed. The --" + AGENT_OPTION
                            + " option will be ignored.");
                    rValue = RHQControl.EXIT_CODE_INVALID_ARGUMENT;
                }
            } else {
                throw new IllegalArgumentException(option + " is not a supported option");
            }
        } catch (Exception e) {
            throw new RHQControlException("Failed to execute console command", e);
        }
    }
    return rValue;
}

From source file:org.rhq.server.control.command.Remove.java

@Override
protected int exec(CommandLine commandLine) {
    int rValue = RHQControl.EXIT_CODE_OK;
    try {/*from   w  w w .j a  va 2 s  .c  o m*/
        // if no options specified, then stop whatever is installed
        if (commandLine.getOptions().length == 0) {
            if (isAgentInstalled()) {
                rValue = Math.max(rValue, removeAgentService());
            }

            // the server service may be installed even if the full server install fails. The files to execute
            // the remove are there after the initial unzip, so just go ahead and try to remove the service. This
            // may help clean up a failed install.
            rValue = Math.max(rValue, removeServerService());

            if (isStorageInstalled()) {
                rValue = Math.max(rValue, removeStorageService());
            }
        } else {
            if (commandLine.hasOption(AGENT_OPTION)) {
                if (isAgentInstalled()) {
                    rValue = Math.max(rValue, removeAgentService());
                } else {
                    log.warn("It appears that the agent is not installed. The --" + AGENT_OPTION
                            + " option will be ignored.");
                    rValue = RHQControl.EXIT_CODE_INVALID_ARGUMENT;
                }
            }
            if (commandLine.hasOption(SERVER_OPTION)) {
                // the server service may be installed even if the full server install fails. The files to execute
                // the remove are there after the initial unzip, so just go ahead and try to remove the service. This
                // may help clean up a failed install.
                rValue = Math.max(rValue, removeServerService());
            }
            if (commandLine.hasOption(STORAGE_OPTION)) {
                if (isStorageInstalled()) {
                    rValue = Math.max(rValue, removeStorageService());
                } else {
                    log.warn("It appears that the storage node is not installed. The --" + STORAGE_OPTION
                            + " option will be ignored.");
                    rValue = RHQControl.EXIT_CODE_INVALID_ARGUMENT;
                }
            }
        }
    } catch (Exception e) {
        throw new RHQControlException("Failed to stop services", e);
    }
    return rValue;
}

From source file:org.rhq.server.control.command.Start.java

@Override
protected int exec(CommandLine commandLine) {
    int rValue = RHQControl.EXIT_CODE_OK;
    try {//from  w  w  w  .j a va  2 s.  c  o  m
        // if no options specified, then start whatever is installed
        if (commandLine.getOptions().length == 0) {
            boolean storageInstalled = isStorageInstalled();
            boolean serverInstalled = isServerInstalled();
            boolean agentInstalled = isAgentInstalled();

            if (!(storageInstalled || serverInstalled || agentInstalled)) {
                log.warn("Nothing to start. No RHQ services are installed.");
                rValue = RHQControl.EXIT_CODE_NOT_INSTALLED;
            } else {
                if (storageInstalled) {
                    rValue = Math.max(rValue, startStorage());
                }
                if (serverInstalled) {
                    rValue = Math.max(rValue, startRHQServer());
                }
                if (agentInstalled) {
                    rValue = Math.max(rValue, startAgent());
                }
            }
        } else {
            if (commandLine.hasOption(STORAGE_OPTION)) {
                if (isStorageInstalled()) {
                    rValue = Math.max(rValue, startStorage());
                } else {
                    log.warn("It appears that the storage node is not installed. The --" + STORAGE_OPTION
                            + " option will be ignored.");
                    rValue = RHQControl.EXIT_CODE_NOT_INSTALLED;
                }
            }
            if (commandLine.hasOption(SERVER_OPTION)) {
                if (isServerInstalled()) {
                    rValue = Math.max(rValue, startRHQServer());
                } else {
                    log.warn("It appears that the server is not installed. The --" + SERVER_OPTION
                            + " option will be ignored.");
                    rValue = RHQControl.EXIT_CODE_NOT_INSTALLED;
                }
            }
            if (commandLine.hasOption(AGENT_OPTION)) {
                if (isAgentInstalled()) {
                    rValue = Math.max(rValue, startAgent());
                } else {
                    log.warn("It appears that the agent is not installed. The --" + AGENT_OPTION
                            + " option will be ignored.");
                    rValue = RHQControl.EXIT_CODE_NOT_INSTALLED;
                }
            }
        }
    } catch (Exception e) {
        throw new RHQControlException("Failed to start services", e);
    }
    return rValue;
}

From source file:org.rhq.server.control.command.Status.java

@Override
protected int exec(CommandLine commandLine) {
    int rValue = RHQControl.EXIT_CODE_OK;
    try {/*from  w w  w  . jav a 2s  . c om*/
        final boolean isColorSupported = Boolean.parseBoolean(System.getProperty("color"));
        // if no options specified, then check the status of whatever is installed
        if (commandLine.getOptions().length == 0) {
            boolean servicesInstalled = false;

            if (isStorageInstalled()) {
                servicesInstalled = true;
                rValue = Math.max(rValue, checkStorageStatus(isColorSupported));
            }
            if (isServerInstalled()) {
                servicesInstalled = true;
                rValue = Math.max(rValue, checkServerStatus());
            }
            if (isAgentInstalled()) {
                servicesInstalled = true;
                rValue = Math.max(rValue, checkAgentStatus());
            }

            if (!servicesInstalled) {
                log.warn(
                        "No services installed. Please install the server, agent, or storage node and then re-run the command.");
            }
        } else {
            if (commandLine.hasOption(STORAGE_OPTION)) {
                if (isStorageInstalled()) {
                    rValue = Math.max(rValue, checkStorageStatus(isColorSupported));
                } else {
                    log.warn("It appears that the storage node is not installed. The --" + STORAGE_OPTION
                            + " option will be ignored.");
                }
            }
            if (commandLine.hasOption(SERVER_OPTION)) {
                if (isServerInstalled()) {
                    rValue = Math.max(rValue, checkServerStatus());
                } else {
                    log.warn("It appears that the server is not installed. The --" + SERVER_OPTION
                            + " option will be ignored.");
                }
            }
            if (commandLine.hasOption(AGENT_OPTION)) {
                if (isAgentInstalled()) {
                    rValue = Math.max(rValue, checkAgentStatus());
                } else {
                    log.warn("It appears that the agent is not installed. The --" + AGENT_OPTION
                            + " option will be ignored.");
                }
            }
        }
    } catch (Exception e) {
        throw new RHQControlException("Failed to check statuses", e);
    }
    return rValue;
}

From source file:org.rhq.server.control.command.Stop.java

@Override
protected int exec(CommandLine commandLine) {

    int rValue = RHQControl.EXIT_CODE_OK;

    try {/*  ww w  .jav a2  s  . co  m*/
        // if no options specified, then stop whatever is installed
        if (commandLine.getOptions().length == 0) {
            if (isAgentInstalled()) {
                rValue = Math.max(rValue, stopAgent());
            }

            // the server service may be installed even if the full server install fails. The files to execute
            // the remove are there after the initial unzip, so just go ahead and try to stop the service. This
            // may help clean up a failed install.
            rValue = Math.max(rValue, stopRHQServer());

            if (isStorageInstalled()) {
                rValue = Math.max(rValue, stopStorage());
            }
        } else {
            if (commandLine.hasOption(AGENT_OPTION)) {
                if (isAgentInstalled()) {
                    rValue = Math.max(rValue, stopAgent());
                } else {
                    log.warn("It appears that the agent is not installed. The --" + AGENT_OPTION
                            + " option will be ignored.");
                    rValue = RHQControl.EXIT_CODE_INVALID_ARGUMENT;
                }
            }

            if (commandLine.hasOption(SERVER_OPTION)) {
                // the server service may be installed even if the full server install fails. The files to execute
                // the remove are there after the initial unzip, so just go ahead and try to stop the service. This
                // may help clean up a failed install.
                rValue = Math.max(rValue, stopRHQServer());
            }

            if (commandLine.hasOption(STORAGE_OPTION)) {
                if (isStorageInstalled()) {
                    rValue = Math.max(rValue, stopStorage());
                } else {
                    log.warn("It appears that the storage node is not installed. The --" + STORAGE_OPTION
                            + " option will be ignored.");
                    rValue = RHQControl.EXIT_CODE_INVALID_ARGUMENT;
                }
            }
        }
    } catch (Exception e) {
        throw new RHQControlException("Failed to stop services", e);
    }
    return rValue;
}

From source file:org.scidb.iquery.Config.java

/**
 * Parse command-line parameters into the Config object.
 *
 * @note (For developers:) Please do not use a number as either a short option name or a long option name.
 *       This will ensure that DefaultParser::isArgument() returns true if and only if the token is not an option.
 *//* www  .j a  v a2  s . co  m*/
public void parse(String[] args) throws ParseException {
    Options options = new Options();
    options.addOption(Option.builder("w").required(false).hasArg(true).longOpt("precision").build());
    options.addOption(Option.builder("c").required(false).hasArg(true).longOpt("host").build());
    options.addOption(Option.builder("p").required(false).hasArg(true).longOpt("port").build());
    options.addOption(Option.builder("q").required(false).hasArg(true).longOpt("query").build());
    options.addOption(Option.builder("f").required(false).hasArg(true).longOpt("query_file").build());
    options.addOption(Option.builder("r").required(false).hasArg(true).longOpt("result").build());
    options.addOption(Option.builder("o").required(false).hasArg(true).longOpt("format").build());
    options.addOption(Option.builder("A").required(false).hasArg(true).longOpt("auth-file").build());
    //options.addOption(Option.builder("U").required(false).hasArg(true).longOpt("user-name").build());
    //options.addOption(Option.builder("P").required(false).hasArg(true).longOpt("user-password").build());
    options.addOption(Option.builder("v").required(false).hasArg(false).longOpt("verbose").build());
    options.addOption(Option.builder("t").required(false).hasArg(false).longOpt("timer").build());
    options.addOption(Option.builder("n").required(false).hasArg(false).longOpt("no_fetch").build());
    options.addOption(Option.builder("a").required(false).hasArg(false).longOpt("afl").build());
    options.addOption(Option.builder("h").required(false).hasArg(false).longOpt("help").build());
    options.addOption(Option.builder("V").required(false).hasArg(false).longOpt("version").build());
    options.addOption(Option.builder("i").required(false).hasArg(false).longOpt("ignore_errors").build());
    options.addOption(
            Option.builder("b").required(false).hasArg(false).longOpt("bypass_usr_cfg_perms_chk").build());

    CommandLineParser parser = new DefaultParser();
    CommandLine line = parser.parse(options, args);
    Option[] processedOptions = line.getOptions();

    for (Option o : processedOptions) {
        switch (o.getId()) {
        case 'w':
            setPrecision(Integer.parseInt(o.getValue()));
            break;
        case 'c':
            setHost(o.getValue());
            break;
        case 'p':
            setPort(Integer.parseInt(o.getValue()));
            break;
        case 'q':
            setQuery(o.getValue());
            break;
        case 'f':
            setQueryFile(o.getValue());
            break;
        case 'r':
            setResult(o.getValue());
            break;
        case 'o':
            setFormat(o.getValue());
            break;
        case 'A':
            setAuthFile(o.getValue());
            break;
        case 'v':
            setVerbose(true);
            break;
        case 't':
            setTimer(true);
            break;
        case 'n':
            setNoFetch(true);
            break;
        case 'a':
            setAfl(true);
            break;
        case 'i':
            setIgnoreErrors(true);
            break;
        case 'b':
            setBypassUsrCfgPermsChk(true);
            break;
        case 'h':
            printHelp();
            System.exit(0);
        case 'V':
            printVersion();
            System.exit(0);
        case '?':
            System.exit(1);
        }
    }
}

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.  jav  a  2s . com*/

    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);
}