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:edu.vt.middleware.ldap.cli.AbstractCli.java

/**
 * Reads the options from the supplied command line and returns a properties
 * containing those options./*from  w w  w .  j  a  va  2s.  c  o  m*/
 *
 * @param  domain  to place property names in
 * @param  line  command line
 *
 * @return  properties for each option and value
 */
protected Properties getPropertiesFromOptions(final String domain, final CommandLine line) {
    final Properties props = new Properties();
    for (Option o : line.getOptions()) {
        if (o.hasArg()) {
            // if provider property, split the value
            if (o.getOpt().equals(OPT_PROVIDER_PROPERTIES)) {
                final String[] s = o.getValue().split("=");
                props.setProperty(s[0], s[1]);
                // add the domain to vt-ldap properties
            } else {
                props.setProperty(domain + o.getOpt(), o.getValue());
            }
        }
    }
    return props;
}

From source file:createconversioncdsfile.ParseCLI.java

/**
 * Rutger Ozinga. ParseCLI Parses the commandline input and is able to
 * return the wanted option and value./*from   w w  w  .  jav a  2 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("c", true, "Expects a path to a conversion file at.");
    cliOpt.addOption("cds", true, "Expects a path to a cds 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 conversionFileString = cliParser.getOptionValue("c");
                Path conversionPath = Paths.get(conversionFileString);
                if (Files.exists(conversionPath)) {
                    setConversionFilePath(conversionPath);
                } else {
                    System.out.println("The entered Path does" + " not exits");
                    helpForm.printHelp("Please enter -c followed by a valid" + " path ", cliOpt);
                    System.exit(0);
                }
                String cdsFileString = cliParser.getOptionValue("cds");
                Path cdsPath = Paths.get(cdsFileString);
                if (Files.exists(cdsPath)) {
                    setCdsPath(cdsPath);
                } else {
                    System.out.println("The entered Path does" + " not exits");
                    helpForm.printHelp("Please enter -cds 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);
                }
            }
        }
    }
}

From source file:net.alegen.datpass.cli.input.ProfileCommand.java

@Override
public void execute() {
    try {//  www  .j a  va2 s  .  co m
        Configurator configurator = Settings.getConfigurator();
        CommandLineParser parser = new PosixParser();
        String[] arrayArgs = new String[this.args.size()];
        this.args.toArray(arrayArgs);
        CommandLine line = parser.parse(this.options, arrayArgs);
        if (line.getOptions().length == 0) {
            Profile profile = Generator.getInstance().getCurrentProfile();
            if (profile == null)
                System.out.println("No profile is currently in use.");
            else
                System.out.println("Current profile: " + profile.getValue(FieldManager.NAME_FIELD));
        } else if (line.hasOption(OPTION_LIST)) {
            Map<String, Boolean> profiles = configurator.listProfiles();
            if (profiles.size() > 0) {
                System.out.println("Available profiles:");
                for (Map.Entry<String, Boolean> entry : profiles.entrySet()) {
                    if (entry.getValue())
                        System.out.println("* " + entry.getKey() + "\t[encrypted]");
                    else
                        System.out.println("* " + entry.getKey());
                }
            } else
                System.out.println("There are no available profiles.");
        } else if (line.hasOption(OPTION_CREATE)) {
            Profile profile = new Profile();
            for (FieldManager.Field field : FieldManager.getInstance()) {
                boolean valid = false;
                while (!valid) {
                    String question = field.getDescription();
                    if (field.getDefaultValue() != null || field.isMandatory()) {
                        question += " ( ";
                        if (field.getDefaultValue() != null && !field.getDefaultValue().isEmpty()) {
                            if (field.isMandatory()) {
                                question += "default: " + field.getDefaultValue() + ", mandatory";
                            } else {
                                question += "default: " + field.getDefaultValue();
                            }
                        } else {
                            question += "mandatory";
                        }
                        question += " )";
                    }
                    question += ": ";
                    System.out.print(question);
                    String answer = System.console().readLine();
                    if (answer.isEmpty()) {
                        if (field.isMandatory()) {
                            if (field.getDefaultValue() != null && !field.getDefaultValue().isEmpty()) {
                                profile.setValue(field, field.getDefaultValue());
                                System.out.println("Field set to default value.");
                                valid = true;
                            } else
                                System.out.println(
                                        "This field is mandatory and a default value is not available.\nPlease provide a value for it.");
                        } else
                            valid = true;
                    } else {
                        profile.setValue(field, answer);
                        valid = true;
                    }
                }
            }
            if (line.hasOption(OPTION_ENCRYPTED)) {
                String password1 = "password1";
                String password2 = "password2";
                while (!password1.equals(password2)) {
                    System.out.print("Password: ");
                    password1 = String.valueOf(System.console().readPassword());
                    System.out.print("Retype password: ");
                    password2 = String.valueOf(System.console().readPassword());
                    if (!password1.equals(password2))
                        System.out.println("The two passwords do not match. Please try again.");
                }
                configurator.saveProfile(profile, password1);
                configurator.saveConfig();
            } else {
                configurator.saveProfile(profile);
                configurator.saveConfig();
            }
        } else if (line.hasOption(OPTION_UNLOCK)) {
            String name = line.getOptionValue(OPTION_UNLOCK);
            boolean isEncrypted = false;
            Map<String, Boolean> profiles = configurator.listProfiles();
            for (Map.Entry<String, Boolean> entry : profiles.entrySet())
                if (entry.getKey().equals(name)) {
                    isEncrypted = entry.getValue();
                    break;
                }
            Profile profile = null;
            if (isEncrypted) {
                System.out.print("Password: ");
                String password = String.valueOf(System.console().readPassword());
                profile = configurator.loadProfile(name, password);
            } else
                profile = configurator.loadProfile(name, "");
            Generator.getInstance().setCurrentProfile(profile);
        } else if (line.hasOption(OPTION_REMOVE)) {
            String name = line.getOptionValue(OPTION_REMOVE);
            configurator.removeProfile(name);
            configurator.saveConfig();
        }
    } catch (ParseException e) {

    } catch (Configurator.ConfigurationException e) {

    } catch (Profile.InvalidProfileException e) {

    }
}

From source file:net.ripe.rpki.validator.cli.CommandLineOptions.java

public void parse(String... args) throws ParseException {
    CommandLineParser parser = new GnuParser();
    CommandLine commandLine = parser.parse(options, args);

    if (commandLine.hasOption(HELP) || commandLine.getOptions().length == 0) {
        printHelpMode = true;//from  w w w  .j a  va2 s .  c om
    } else if (commandLine.hasOption(VERSION)) {
        printVersionMode = true;
    } else if (commandLine.hasOption(PRINT)) {
        printObjectMode = true;
        requireInputFileOption(commandLine);
        parseInputFile(commandLine);
    } else if (commandLine.hasOption(TAL)) {
        validationMode = true;
        parseTrustAnchorFile(commandLine);

        requireOutputDir(commandLine);
        parseOutputDir(commandLine);

        if (commandLine.hasOption(FILE)) {
            topDownValidationEnabled = false;
            parseInputFile(commandLine);
        } else {
            topDownValidationEnabled = true;
            parseRoaExportFile(commandLine);
            parsePrefetchURIs(commandLine);
        }

        if (commandLine.hasOption(VERBOSE)) {
            verboseEnabled = true;
        }
    }
}

From source file:de.ipbhalle.metfrag.main.CommandLineTool.java

/**
 * setting all parameter given via command line
 * //  ww  w  .  java  2s .  com
 * @param line
 * @return
 */
public static int setParameters(CommandLine line, Options options) {
    Option[] opts = line.getOptions();
    int correct = 0;
    for (int j = 0; j < opts.length; j++) {
        if (correct != 0)
            return correct;
        if (opts[j].getOpt().length() != 1) {
            System.out.println("Warning: Unknown option " + opts[j].getOpt());
        }
        switch (opts[j].getOpt().charAt(0)) {
        case 'r':
            String startToSet = "1";
            String endToSet = String.valueOf(Integer.MAX_VALUE);
            String[] split = opts[j].getValue().trim().split("-");
            if (split.length == 1) {
                if (opts[j].getValue().trim().contains("-"))
                    startToSet = split[0];
                else
                    endToSet = split[0];
            }
            if (split.length == 2) {
                if (split[0].length() == 0 && split[1].length() == 0) {
                    correct = 2;
                    System.out.println("Error: Wrong value for range (-r) given!");
                }
                if (split[0].length() == 0)
                    endToSet = split[1];
                else {
                    startToSet = split[0];
                    endToSet = split[1];
                }
            }
            correct = setIntegerValue(startToSet, true, "startindex", startindex);
            correct = setIntegerValue(endToSet, true, "endindex", endindex);
            rangeIsSet = true;
            break;
        case 'C':
            correct = setIntegerValue(opts[j].getValue().trim(), true, "charge", charge);
            chargeIsSet = true;
            break;
        case 'l': //setting molredundancycheck
            localdb = true;
            localdbIsSet = true;
            settingsfile = opts[j].getValue().trim();
            break;
        case 'd': //setting database
            database = opts[j].getValue().trim();
            databaseIsSet = true;
            break;
        case 'a': //setting mzabs
            correct = setDoubleValue(opts[j].getValue().trim(), true, "mzabs", mzabs);
            mzabsIsSet = true;
            break;
        case 'p': //setting mzppm
            correct = setDoubleValue(opts[j].getValue().trim(), true, "mzppm", mzppm);
            mzppmIsSet = true;
            break;
        case 's': //setting searchppm
            correct = setDoubleValue(opts[j].getValue().trim(), true, "searchppm", searchppm);
            searchppmIsSet = true;
            break;
        case 'n': //setting exactmass
            correct = setDoubleValue(opts[j].getValue().trim(), true, "exactmass", exactMass);
            exactMassIsSet = true;
            break;
        case 'b': //setting onlyBiologicalCompound
            onlyBiologicalCompounds = true;
            onlyBiologicalCompoundsIsSet = true;
            break;
        case 'i': //setting databaseids
            databaseIDs = opts[j].getValue().trim().split(",");
            databaseIDsIsSet = true;
            break;
        case 'S': //setting databaseids
            sampleName = opts[j].getValue().trim();
            sampleNameIsSet = true;
            break;
        case 't': //setting treedepth
            correct = setIntegerValue(opts[j].getValue().trim(), true, "treedepth", treeDepth);
            treedepthIsSet = true;
            break;
        case 'M': //setting mode
            correct = setIntegerValue(opts[j].getValue().trim(), false, "mode", mode);
            modeIsSet = true;
            break;
        case 'f': //setting formula
            formula = opts[j].getValue().trim();
            formulaIsSet = true;
            break;
        case 'P': //setting formula
            saveParameters = true;
            saveParametersIsSet = true;
            break;
        case 'v': //setting molredundancycheck
            verbose = true;
            verboseIsSet = true;
            break;
        case 'B': //setting breakrings
            breakRings = true;
            breakRingsIsSet = true;
            break;
        case 'F': //setting storefragments
            storeFragments = true;
            storeFragmentsIsSet = true;
            break;
        case 'R': //setting resultspath
            resultspath = opts[j].getValue().trim();
            resultPathIsSet = true;
            break;
        case 'L':
            sdfFile = opts[j].getValue().trim();
            usesdf = true;
            sdfFileIsSet = true;
            break;
        case 'T':
            setIntegerValue(opts[j].getValue().trim(), true, "numberThreads", numberThreads);
            numberThreadsIsSet = true;
            break;
        case 'c':
            chemSpiderToken = opts[j].getValue().trim();
            chemSpiderTokenIsSet = true;
            break;
        case 'h':

            return 2;
        case 'e':

            return 2;
        case 'D':

            break;
        default:
            System.out.println("Warning: Unknown option " + opts[j].getOpt());
            break;
        }
    }

    return correct;
}

From source file:alluxio.cli.fsadmin.report.CapacityCommand.java

/**
 * Gets the worker info options./*from   www.  jav a 2 s  .com*/
 *
 * @param cl CommandLine that contains the client options
 * @return GetWorkerReportOptions to get worker information
 */
private GetWorkerReportOptions getOptions(CommandLine cl) throws IOException {
    if (cl.getOptions().length > 1) {
        System.out.println(getUsage());
        throw new InvalidArgumentException("Too many arguments passed in.");
    }
    GetWorkerReportOptions workerOptions = GetWorkerReportOptions.defaults();

    Set<WorkerInfoField> fieldRange = new HashSet<>(Arrays.asList(WorkerInfoField.ADDRESS,
            WorkerInfoField.CAPACITY_BYTES, WorkerInfoField.CAPACITY_BYTES_ON_TIERS,
            WorkerInfoField.LAST_CONTACT_SEC, WorkerInfoField.USED_BYTES, WorkerInfoField.USED_BYTES_ON_TIERS));
    workerOptions.setFieldRange(fieldRange);

    if (cl.hasOption(ReportCommand.LIVE_OPTION_NAME)) {
        workerOptions.setWorkerRange(WorkerRange.LIVE);
    } else if (cl.hasOption(ReportCommand.LOST_OPTION_NAME)) {
        workerOptions.setWorkerRange(WorkerRange.LOST);
    } else if (cl.hasOption(ReportCommand.SPECIFIED_OPTION_NAME)) {
        workerOptions.setWorkerRange(WorkerRange.SPECIFIED);
        String addressString = cl.getOptionValue(ReportCommand.SPECIFIED_OPTION_NAME);
        String[] addressArray = addressString.split(",");
        // Addresses in GetWorkerReportOptions is only used when WorkerRange is SPECIFIED
        workerOptions.setAddresses(new HashSet<>(Arrays.asList(addressArray)));
    }
    return workerOptions;
}

From source file:edu.vt.middleware.ldap.AbstractCli.java

/**
 * Initialize the supplied config with command line options.
 *
 * @param  config  property config to configure
 * @param  line  Parsed command line arguments container.
 *
 * @throws  Exception  On errors thrown by handler.
 *///w w w .ja  v a 2  s . co  m
protected void initLdapProperties(final PropertyConfig config, final CommandLine line) throws Exception {
    final LdapProperties ldapProperties = new LdapProperties(config);
    for (Option o : line.getOptions()) {
        if (o.getOpt().equals(OPT_USE_PROPERTIES)) {
            ldapProperties.useDefaultPropertiesFile();
        } else if (!this.opts.contains(o.getOpt())) {
            ldapProperties.setProperty(o.getOpt(), o.getValue());
        }
    }
    ldapProperties.configure();
}

From source file:com.jonasjberg.voltdivx.arguments.ArgumentParser.java

public void parse() {
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = null;

    SiUnitParser siParser = new SiUnitParser();

    try {/*from  w  w w .j  a v a 2s .co  m*/
        cmd = parser.parse(ArgumentOptions.getOptions(), args);

        if (cmd.hasOption("h") || cmd.getOptions().length == 0) {
            Main.printLogo();
            Help.displayHelp();
            Main.exit(0);
        }

        else {
            if (cmd.hasOption("i")) {
                double opt = siParser.parse(cmd.getOptionValue("i"));
                contents.setInputVoltage(opt);
            }

            if (cmd.hasOption("o")) {
                double opt = siParser.parse(cmd.getOptionValue("o"));
                contents.setOutputVoltage(opt);
            }

            if (cmd.hasOption("g")) {
                double opt = siParser.parse(cmd.getOptionValue("g"));
                contents.setGroundVoltage(opt);
            }

            if (cmd.hasOption("r")) {
                double opt = siParser.parse(cmd.getOptionValue("r"));
                contents.setR1Resistance(opt);
            }

            if (cmd.hasOption("t")) {
                double opt = siParser.parse(cmd.getOptionValue("t"));
                contents.setR2Resistance(opt);
            }

            if (cmd.hasOption("s")) {
                String opt = cmd.getOptionValue("s");
                contents.setValueSeries(parseValueSeries(opt));

                /* Set tolerancePercent to the tolerance of the selected value
                 * series as default if the error option is not used. */
                //  if (!cmd.hasOption("e")) {
                //      double tolerancePercent = 100 * contents.getValueSeries().getTolerance();
                //      System.out.println("tolerancePercent = " + tolerancePercent);
                //      contents.setMaxErrorPercent(tolerancePercent);
                //  }

            } else {
                contents.setValueSeries(null);
            }

            if (cmd.hasOption("l")) {
                String opt = cmd.getOptionValue("l");
                int i = Integer.parseInt(opt);

                contents.setNumberOfLines(i);
            }

            if (cmd.hasOption("c")) {
                double opt = siParser.parse(cmd.getOptionValue("c"));
                contents.setMaxCurrent(opt);
            }

            if (cmd.hasOption("e")) {
                String opt = cmd.getOptionValue("e");

                if (opt.contains("%")) {
                    opt = opt.replaceAll("%", "").trim();
                    contents.setMaxErrorPercent(Double.parseDouble(opt));
                } else {
                    contents.setMaxErrorVoltage(siParser.parse(opt));
                }
            }

            if (cmd.hasOption("q")) {
                contents.setFlagQuiet(true);
            }
        }

    } catch (ParseException e) {
        // e.printStackTrace();
        System.err.println("Caught exception:" + e.getMessage());
    }
}

From source file:com.cloudera.csd.tools.codahale.AbstractCodahaleFixtureGenerator.java

public AbstractCodahaleFixtureGenerator(String[] args, Options options) throws Exception {
    Preconditions.checkNotNull(args);/* w w  w  . java  2 s  . c  om*/
    Preconditions.checkNotNull(options);

    CommandLineParser parser = new DefaultParser();
    try {
        CommandLine cmdLine = parser.parse(options, args);
        if (!cmdLine.getArgList().isEmpty()) {
            throw new ParseException("Unexpected extra arguments: " + cmdLine.getArgList());
        }
        config = new MapConfiguration(Maps.<String, Object>newHashMap());
        for (Option option : cmdLine.getOptions()) {
            config.addProperty(option.getLongOpt(), option.getValue());
        }
    } catch (ParseException ex) {
        IOUtils.write("Error: " + ex.getMessage() + "\n", System.err);
        printUsageMessage(System.err, options);
        throw ex;
    }
}

From source file:com.inetpsa.seed.plugin.CmdMojoDelegate.java

protected Command createCommand(CommandRegistry commandRegistry, String qualifiedName, String[] args) {
    if (Strings.isNullOrEmpty(qualifiedName)) {
        throw new IllegalArgumentException("No command named " + qualifiedName);
    }/*from   www.java2  s.  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);
    } catch (ParseException e) {
        throw new IllegalArgumentException("Syntax error in arguments", e);
    }

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