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:bvt.TestRunner.java

/**
 * Primary entry point for the program.//from w w  w .ja  va  2 s . c  om
 * 
 * @throws Exception
 */
public void run(String[] args) throws Exception {

    // Parse the command line ...
    CommandLine cl = null;
    Options options = getCommandOptions();
    try {
        cl = new BasicParser().parse(options, args);
        if (cl.getOptions().length == 0)
            throw new ParseException("Report format not specified.");
    } catch (ParseException e) {
        System.out.println("");
        System.out.println(e.getMessage());
        System.out.println("");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(80, "TestRunner", "", options, "", true);
        System.out.println("");
        System.out.println("Example: TestRunner -h");
        return;
    }

    // Interpret provided values ...
    boolean isBriefRequested = cl.hasOption("b");
    boolean isFullRequested = cl.hasOption("f");
    boolean isHtmlRequested = cl.hasOption("h");
    boolean isXmlRequested = cl.hasOption("x");
    boolean isVerifyRequested = cl.hasOption("v");

    // Launch the requested tests ...
    if (isBriefRequested)
        org.apache.tools.ant.launch.Launcher.main(new String[] { "-buildfile", "TestRunner.xml", "bvt-brief" });
    if (isFullRequested)
        org.apache.tools.ant.launch.Launcher.main(new String[] { "-buildfile", "TestRunner.xml", "bvt-full" });
    if (isHtmlRequested)
        org.apache.tools.ant.launch.Launcher.main(new String[] { "-buildfile", "TestRunner.xml", "bvt-html" });
    if (isXmlRequested)
        org.apache.tools.ant.launch.Launcher.main(new String[] { "-buildfile", "TestRunner.xml", "bvt-xml" });
    if (isVerifyRequested)
        org.apache.tools.ant.launch.Launcher.main(new String[] { "-buildfile", "TestRunner.xml", "verify" });

}

From source file:gobblin.runtime.cli.ConstructorAndPublicMethodsGobblinCliFactory.java

/**
 * Builds an instance of {@link EmbeddedGobblin} using the selected constructor getting the constructor
 * parameters from the {@link CommandLine}.
 *
 * Note: this method will also automatically call {@link #applyCommandLineOptions(CommandLine, EmbeddedGobblin)} on
 * the constructed {@link EmbeddedGobblin}.
 *//*ww w  .  j  a v a  2s  .  com*/
public EmbeddedGobblin buildInstance(CommandLine cli) {
    String[] constructorArgs = new String[this.constructor.getParameterTypes().length];
    for (Option option : cli.getOptions()) {
        if (this.constructoArgumentsMap.containsKey(option.getOpt())) {
            int idx = this.constructoArgumentsMap.get(option.getOpt());
            constructorArgs[idx] = option.getValue();
        }
    }

    EmbeddedGobblin embeddedGobblin;
    try {
        embeddedGobblin = this.constructor.newInstance((Object[]) constructorArgs);
        return embeddedGobblin;
    } catch (IllegalAccessException | InvocationTargetException | InstantiationException exc) {
        throw new RuntimeException("Could not instantiate " + this.klazz.getName(), exc);
    }
}

From source file:com.github.horrorho.inflatabledonkey.args.PropertyLoader.java

@Override
public boolean test(String[] args) throws IllegalArgumentException {
    try {//  w w w.j  a  va 2  s.c o m
        Map<Option, Property> optionKeyMap = optionKeyMapSupplier.get();

        Options options = new Options();
        optionKeyMap.keySet().forEach(options::addOption);

        CommandLineParser parser = new DefaultParser();
        CommandLine commandLine = parser.parse(options, args);

        Map<Property, String> properties = Stream.of(commandLine.getOptions())
                .collect(Collectors.toMap(optionKeyMap::get, this::parse));

        if (properties.containsKey(Property.ARGS_HELP)) {
            help(OptionsFactory.options().keySet());
            return false;
        }

        List<String> operands = commandLine.getArgList();
        switch (operands.size()) {
        case 0:
            // No setAuthenticationProperties credentials
            throw new IllegalArgumentException("missing appleid/ password or authentication token");
        case 1:
            // Authentication token
            properties.put(Property.AUTHENTICATION_TOKEN, operands.get(0));
            break;
        case 2:
            // AppleId/ password pair
            properties.put(Property.AUTHENTICATION_APPLEID, operands.get(0));
            properties.put(Property.AUTHENTICATION_PASSWORD, operands.get(1));
            break;
        default:
            throw new IllegalArgumentException(
                    "too many non-optional arguments, expected appleid/ password or authentication token only");
        }
        Property.setProperties(properties);
        return true;

    } catch (ParseException ex) {
        throw new IllegalArgumentException(ex.getLocalizedMessage());
    }
}

From source file:net.sf.jvifm.control.FindCommand.java

private IOFileFilter findingFilter(CommandLine cmdLine) {

    AndFileFilter filters = new AndFileFilter();
    Option[] options = cmdLine.getOptions();
    for (int i = 0; i < options.length; i++) {
        IOFileFilter filter = createFilter(options[i].getLongOpt(), options[i].getValue());
        filters.addFileFilter(filter);//w  ww.  j a  va2 s .com
    }
    return filters;
}

From source file:be.svlandeg.diffany.console.RunConsole.java

/**
 * Check whether meta data needs to be displayed, such as the help or version message.
 * /*  w w w .  j  ava 2 s  . com*/
 * If no request for meta data was issued, this method will return false, signaling the calling method that the commandline parameters should containc valid project data.
 * 
 * @param cmd the parsed input arguments provided on the commandline
 * @param diffanyOptions defines the options of the actual Diffany program (this information is needed for printing the help message)
 * 
 * @return whether or not a meta message was printed.
 */
private boolean displayMetaData(CommandLine cmd, Options diffanyOptions) {
    // TODO: keep version number updated
    String version = "1.0.0";

    boolean metaPrinted = false;

    if (cmd != null && cmd.getOptions() != null && cmd.getOptions().length > 0) {
        if (cmd.hasOption(MetaOptions.helpShort)) {
            HelpFormatter formatter = new HelpFormatter();
            String header = "";
            int consoleSize = getSensibleLength();
            formatter.printHelp(consoleSize, "java -jar Diffany_CL_" + version + ".jar", header, diffanyOptions,
                    header, true);
            metaPrinted = true;
        } else if (cmd.hasOption(MetaOptions.versionShort)) {
            System.out.println("Diffany version: " + version);
            metaPrinted = true;
        }
    }
    return metaPrinted;
}

From source file:gobblin.runtime.cli.PublicMethodsCliObjectFactory.java

/**
 * For each method for which the helper created an {@link Option} and for which the input {@link CommandLine} contains
 * that option, this method will automatically call the method on the input object with the correct
 * arguments.//ww w  .j av  a 2 s  . c o  m
 */
public void applyCommandLineOptions(CommandLine cli, T embeddedGobblin) {
    try {
        for (Option option : cli.getOptions()) {
            if (!this.methodsMap.containsKey(option.getOpt())) {
                // Option added by cli driver itself.
                continue;
            }
            if (option.hasArg()) {
                this.methodsMap.get(option.getOpt()).invoke(embeddedGobblin, option.getValue());
            } else {
                this.methodsMap.get(option.getOpt()).invoke(embeddedGobblin);
            }
        }
    } catch (IllegalAccessException | InvocationTargetException exc) {
        throw new RuntimeException("Could not apply options to " + embeddedGobblin.getClass().getName(), exc);
    }
}

From source file:cdscreator.ParseCLI.java

/**
 * Rutger Ozinga. ParseCLI Parses the commandline input and is able to
 * return the wanted option and value.//www  .  java2  s  .co  m
 *
 * @param args are commandline arguments.
 * @throws org.apache.commons.cli.ParseException an exception
 */
public ParseCLI(final String[] args) throws org.apache.commons.cli.ParseException {
    HelpFormatter helpForm = new HelpFormatter();
    Options cliOpt = new Options();
    cliOpt.addOption("h", "help", false, "Displays help");
    cliOpt.addOption("p", true, "Expects a path to a protein fasta file.");
    cliOpt.addOption("t", true, "Expects a path to a transcript fasta file.");
    cliOpt.addOption("nt", true, "Expects a path to place the new tab separated transcript file at.");
    cliOpt.addOption("o", true, "Expects a path to place the new tab separated protein file at");
    if (args.length == 0) {
        helpForm.printHelp("Please enter all the " + "options below. ", cliOpt);
        System.exit(0);
    } else {
        BasicParser parser = new BasicParser();
        CommandLine cliParser = parser.parse(cliOpt, args);
        if (cliParser.getOptions().length < 4) {
            System.out.println(
                    "Error : " + "Please enter all options in" + " order for this program to work" + "!\n");
            helpForm.printHelp("Please enter all of the  " + "option ", cliOpt);
            System.exit(0);
        } else {
            if (cliParser.hasOption("h") && cliParser.hasOption("help")) {
                helpForm.printHelp("Command Line Help:\n", cliOpt);
                System.exit(0);
            } else {
                String snpFileString = cliParser.getOptionValue("p");
                Path snpPath = Paths.get(snpFileString);
                if (Files.exists(snpPath)) {
                    setProtPath(snpPath);
                } else {
                    System.out.println("The entered Path does" + " not exits");
                    helpForm.printHelp("Please enter -p followed by a valid" + " path ", cliOpt);
                    System.exit(0);
                }
                String transcriptFileString = cliParser.getOptionValue("t");
                Path transcriptPath = Paths.get(transcriptFileString);
                if (Files.exists(transcriptPath)) {
                    setTransPath(transcriptPath);
                } else {
                    System.out.println("The entered Path does" + " not exits");
                    helpForm.printHelp("Please enter -t followed by a valid" + " path ", cliOpt);
                    System.exit(0);
                }
                String newFileString = cliParser.getOptionValue("o");
                Matcher match = re.matcher(newFileString);
                String editedFileString = match.replaceAll("");
                Path newPath = Paths.get(editedFileString);
                if (Files.exists(newPath)) {
                    setNewFilePath(newFileString);
                } else {
                    System.out.println("The entered Path does" + " not exits");
                    helpForm.printHelp("Please enter -o followed by a valid" + " path ", cliOpt);
                    System.exit(0);
                }
                String newTranscriptFileString = cliParser.getOptionValue("nt");
                Matcher match2 = re.matcher(newTranscriptFileString);
                String editedTranscriptFileString = match2.replaceAll("");
                Path newTranscriptPath = Paths.get(editedTranscriptFileString);
                if (Files.exists(newTranscriptPath)) {
                    setNewTranscriptFilePath(newTranscriptFileString);
                } else {
                    System.out.println("The entered Path does" + " not exits");
                    helpForm.printHelp("Please enter -nt followed by a valid" + " path ", cliOpt);
                    System.exit(0);
                }
            }
        }
    }
}

From source file:ca.phon.app.modules.EntryPointArgs.java

/**
 * Parse command line arguments./*from www . j  av a  2s  .  co m*/
 * 
 * @param args
 */
public void parseArgs(String[] args) {
    final Options options = new Options();
    options.addOption(PROJECT_NAME_OPT, PROJECT_NAME, true, PROJECT_NAME_DESC);
    options.addOption(PROJECT_LOCATION_OPT, PROJECT_LOCATION, true, PROJECT_LOCATION_DESC);
    options.addOption(CORPUS_NAME_OPT, CORPUS_NAME, true, CORPUS_NAME_DESC);
    options.addOption(SESSION_NAME_OPT, SESSION_NAME, true, SESSION_NAME_DESC);

    final CommandLineParser parser = new EntryPointArgParser();

    try {
        final CommandLine cmdLine = parser.parse(options, args, false);
        for (Option opt : cmdLine.getOptions()) {
            put(opt.getLongOpt(), opt.getValue());
        }
    } catch (ParseException e) {
        LOGGER.log(Level.SEVERE, e.getLocalizedMessage(), e);
    }
}

From source file:main.CommandLineParser.java

private boolean hasInvalidOptionsBesidePasses(CommandLine cmd) {
    boolean hasError = false;

    for (Option option : Arrays.asList(cmd.getOptions())) {
        if (!option.getLongOpt().equals(options.passes.getLongOpt())) {
            error.err(ErrorType.Error, "Invalid option found beside passes: --" + option.getLongOpt(),
                    new MetaListImplementation());
            hasError = true;/* w w w  .  j  ava  2s . com*/
        }
    }

    return hasError;
}

From source file:com.zimbra.cs.localconfig.LocalConfigCLI.java

private void checkCompatibleOptions(String mainOption, String compatibleOptions, CommandLine cl) {
    Option[] opts = cl.getOptions();
    for (int i = 0; i < opts.length; i++) {
        String clOption = opts[i].getOpt() == null ? opts[i].getLongOpt() : opts[i].getOpt();
        if (!mainOption.equals(clOption) && compatibleOptions.indexOf(clOption) == -1) {
            if (mainOption.equals("")) {
                error("invalid option '" + clOption + "'", null);
            } else {
                error("option '" + clOption + "' can not be used with option '" + mainOption + "'", null);
            }/*from  w w  w  .ja  v  a2 s. co m*/
        }
    }
}