Example usage for org.apache.commons.cli BasicParser parse

List of usage examples for org.apache.commons.cli BasicParser parse

Introduction

In this page you can find the example usage for org.apache.commons.cli BasicParser parse.

Prototype

public CommandLine parse(Options options, String[] arguments) throws ParseException 

Source Link

Document

Parses the specified arguments based on the specifed Options .

Usage

From source file:kieker.tools.AbstractCommandLineTool.java

private CommandLine parseCommandLineArguments(final Options options, final String[] arguments) {
    final BasicParser parser = new BasicParser();

    try {/*from ww  w. ja  v  a  2 s  . co  m*/
        return parser.parse(options, arguments);
    } catch (final ParseException ex) {
        // Note that we append ex.getMessage() to the log message on purpose to improve the
        // logging output on the console.
        LOG.error("An error occurred while parsing the command line arguments: " + ex.getMessage(), ex);
        LOG.info("Use the option `--" + CMD_OPT_NAME_HELP_LONG + "` for usage information");

        return null;
    }
}

From source file:fastacreator.ParseCLI.java

/**
 * Rutger Ozinga. ParseCLI Parses the commandline input and is able to
 * return the wanted option and value.//from www.  ja v  a2  s  .c  o 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("n", true, "Expects a path to place the new tab separated transcript file at.");
    cliOpt.addOption("i", true, "The index of the sequence");
    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 < 2) {
            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)) {
                    setCDSPath(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 newFileString = cliParser.getOptionValue("n");
                Matcher match2 = re.matcher(newFileString);
                String editedTranscriptFileString = match2.replaceAll("");
                Path newFilePath = Paths.get(editedTranscriptFileString);
                if (Files.exists(newFilePath)) {
                    setNewFilePath(newFileString);
                } else {
                    System.out.println("The entered Path does" + " not exits");
                    helpForm.printHelp("Please enter -nt followed by a valid" + " path ", cliOpt);
                    System.exit(0);
                }
                String indexString = cliParser.getOptionValue("i");
                int index = Integer.parseInt(indexString);
                setIndex(index);
            }
        }
    }
}

From source file:com.shmsoft.dmass.main.SHMcloudMain.java

/**
 * Process the command line arguments//from w w  w.j  a v  a 2 s . c  om
 *
 * @param args command line arguments
 */
private void processOptions(String[] args) {
    String customParameterFile;
    Project project = null;
    try {
        BasicParser parser = new BasicParser();
        commandLine = parser.parse(options, args);

        // one-time actions
        if (commandLine.hasOption(CommandLineOption.HELP.getName()) || commandLine.getOptions().length == 0) {
            HelpFormatter f = new HelpFormatter();
            f.printHelp("java -jar FreeEed.jar [options]\n\n" + "where options include:", options);
        } else if (commandLine.hasOption(CommandLineOption.VERSION.getName())) {
            System.out.println(Version.getVersionAndBuild());
        } else if (commandLine.hasOption(CommandLineOption.GUI.getName())) {
            openGUI();
        } else if (commandLine.hasOption(CommandLineOption.ENRON.getName())) {
            processEnronDataSet();
        } else {
            if (commandLine.hasOption(CommandLineOption.PARAM_FILE.getName())) {
                // independent actions
                customParameterFile = commandLine.getOptionValue(CommandLineOption.PARAM_FILE.getName());
                project = new Project().loadFromFile(new File(customParameterFile));
                Project.setProject(project);
                SHMcloudLogging.init(false);
            }
            if (commandLine.hasOption(CommandLineOption.DRY.getName())) {
                System.out.println("Dry run - exiting now.");
            } else {
                if (project.isStage()) {
                    stagePackageInput();
                }
                String runWhere = project.getProcessWhere();
                if (runWhere != null) {
                    process(runWhere);
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace(System.out);
    }
}

From source file:net.sf.clirr.cli.Clirr.java

private CommandLine parseCommandLine(String[] args, Options options) {
    BasicParser parser = new BasicParser();
    CommandLine cmdline = null;/*from  ww  w  . ja  va 2 s .co m*/
    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException ex) {
        System.err.println("Invalid command line arguments.");
        printUsage(options, System.err);
        System.exit(-1);
    }
    return cmdline;
}

From source file:cdscreator.ParseCLI.java

/**
 * Rutger Ozinga. ParseCLI Parses the commandline input and is able to
 * return the wanted option and value./* w w  w.ja v  a2  s .  c o  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:com.alcatel_lucent.nz.wnmsextract.WNMSTransform.java

/**
 * Called if the Transformer class is called as a main. Useful for one off XML parse jobs
 * @param args// w  w  w . j av a  2s .  c o m
 */
public void processcli(String[] args) {
    String xf = null, sf = null, of = null;
    try {
        Options opt = new Options();

        opt.addOption("h", "help", false, "Print help for this application");
        opt.addOption("x", "xml", true, "The XCM file to load");
        opt.addOption("s", "xsl", true, "The stylesheet to apply");
        opt.addOption("o", true, "The output CSV to generate");

        BasicParser bp = new BasicParser();
        CommandLine cl = bp.parse(opt, args);

        ALUParser p = new ALUParserFactory("WIPS").getInstance();

        if (cl.hasOption('h')) {
            HelpFormatter f = new HelpFormatter();
            f.printHelp("OptionsTip", opt);
        } else {
            //XCM snapshot
            if (cl.hasOption('x')) {
                xf = cl.getOptionValue("x");
            } else {
                System.err.println("XML File not Specified");
                System.exit(1);
            }

            //stylesheet
            if (cl.hasOption('s')) {
                sf = cl.getOptionValue("s");
            } else {
                System.err.println("XSL File not Specified");
                System.exit(1);
            }

            //output
            if (cl.hasOption('o')) {
                of = cl.getOptionValue("o");
            } else {
                String sfn = sf.substring(sf.lastIndexOf("\\") + 1, sf.length() - 4);
                of = xf.substring(0, xf.length() - 4) + "." + sfn + ".csv";
            }

            System.out.println(xf + " + " + sf + " -> " + of);

            p.setParseFile(xf);
            p.setTransformFile(sf);
            p.setResultFile(of);
            //how is this ever supposed to work if you never call transform?!?

        }
    } catch (ParseException e) {
        e.printStackTrace();
    }
}

From source file:com.amazonaws.mturk.cmd.AbstractCmd.java

public void run(String[] args) {
    try {//ww  w  .  ja  va  2s.  c o  m
        BasicParser parser = new BasicParser();
        CommandLine cmdLine = parser.parse(opt, args);

        if (cmdLine.hasOption(ARG_HELP) || cmdLine.hasOption(ARG_HELP_SHORT)) {
            printHelp();
            System.exit(-1);
        }

        if (cmdLine.hasOption(ARG_SANDBOX)
                && !ClientConfig.SANDBOX_SERVICE_URL.equalsIgnoreCase(config.getServiceURL())) {
            log.info("Sandbox override");

            setSandBoxMode();
        } else {
            initService();
        }

        log.debug(String.format("Running command against %s", config.getServiceURL()));

        runCommand(cmdLine);
    } catch (Exception e) {
        log.error("An error occurred: " + e.getLocalizedMessage(), e);
        System.exit(-1);
    }
}

From source file:createconversioncdsfile.ParseCLI.java

/**
 * Rutger Ozinga. ParseCLI Parses the commandline input and is able to
 * return the wanted option and value.// w  w w . ja v  a2s.  c  o  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:com.twitter.distributedlog.benchmark.Benchmarker.java

void run() throws Exception {
    logger.info("Running benchmark.");

    BasicParser parser = new BasicParser();
    CommandLine cmdline = parser.parse(options, args);
    if (cmdline.hasOption("h")) {
        printUsage();//from  www. ja  va  2  s .c  o m
        System.exit(0);
    }
    if (cmdline.hasOption("s")) {
        String serversetPathStr = cmdline.getOptionValue("s");
        serversetPaths = Arrays.asList(StringUtils.split(serversetPathStr, ','));
    }
    if (cmdline.hasOption("fn")) {
        String finagleNameStr = cmdline.getOptionValue("fn");
        finagleNames = Arrays.asList(StringUtils.split(finagleNameStr, ','));
    }
    if (cmdline.hasOption("i")) {
        shardId = Integer.parseInt(cmdline.getOptionValue("i"));
    }
    if (cmdline.hasOption("d")) {
        durationMins = Integer.parseInt(cmdline.getOptionValue("d"));
    }
    if (cmdline.hasOption("sp")) {
        streamPrefix = cmdline.getOptionValue("sp");
    }
    if (cmdline.hasOption("sc")) {
        numStreams = Integer.parseInt(cmdline.getOptionValue("sc"));
    }
    if (cmdline.hasOption("ms")) {
        msgSize = Integer.parseInt(cmdline.getOptionValue("ms"));
    }
    if (cmdline.hasOption("r")) {
        rate = Integer.parseInt(cmdline.getOptionValue("r"));
    }
    if (cmdline.hasOption("mr")) {
        maxRate = Integer.parseInt(cmdline.getOptionValue("mr"));
    }
    if (cmdline.hasOption("cr")) {
        changeRate = Integer.parseInt(cmdline.getOptionValue("cr"));
    }
    if (cmdline.hasOption("ci")) {
        changeRateSeconds = Integer.parseInt(cmdline.getOptionValue("ci"));
    }
    if (cmdline.hasOption("t")) {
        concurrency = Integer.parseInt(cmdline.getOptionValue("t"));
    }
    if (cmdline.hasOption("m")) {
        mode = cmdline.getOptionValue("m");
    }
    if (cmdline.hasOption("u")) {
        dlUri = URI.create(cmdline.getOptionValue("u"));
    }
    if (cmdline.hasOption("bs")) {
        batchSize = Integer.parseInt(cmdline.getOptionValue("bs"));
        Preconditions.checkArgument("write" != mode, "batchSize supported only for mode=write");
    }
    if (cmdline.hasOption("c")) {
        String configFile = cmdline.getOptionValue("c");
        conf.loadConf(new File(configFile).toURI().toURL());
    }
    if (cmdline.hasOption("rps")) {
        readersPerStream = Integer.parseInt(cmdline.getOptionValue("rps"));
    }
    if (cmdline.hasOption("msid")) {
        maxStreamId = Integer.parseInt(cmdline.getOptionValue("msid"));
    }
    if (cmdline.hasOption("ti")) {
        truncationInterval = Integer.parseInt(cmdline.getOptionValue("ti"));
    }
    if (cmdline.hasOption("ssid")) {
        startStreamId = Integer.parseInt(cmdline.getOptionValue("ssid"));
    }
    if (cmdline.hasOption("esid")) {
        endStreamId = Integer.parseInt(cmdline.getOptionValue("esid"));
    }
    if (cmdline.hasOption("hccs")) {
        hostConnectionCoreSize = Integer.parseInt(cmdline.getOptionValue("hccs"));
    }
    if (cmdline.hasOption("hcl")) {
        hostConnectionLimit = Integer.parseInt(cmdline.getOptionValue("hcl"));
    }
    if (cmdline.hasOption("sb")) {
        sendBufferSize = Integer.parseInt(cmdline.getOptionValue("sb"));
    }
    if (cmdline.hasOption("rb")) {
        recvBufferSize = Integer.parseInt(cmdline.getOptionValue("rb"));
    }
    thriftmux = cmdline.hasOption("mx");
    handshakeWithClientInfo = cmdline.hasOption("hsci");
    readFromHead = cmdline.hasOption("rfh");
    enableBatching = cmdline.hasOption("bt");

    Preconditions.checkArgument(shardId >= 0, "shardId must be >= 0");
    Preconditions.checkArgument(numStreams > 0, "numStreams must be > 0");
    Preconditions.checkArgument(durationMins > 0, "durationMins must be > 0");
    Preconditions.checkArgument(streamPrefix != null, "streamPrefix must be defined");
    Preconditions.checkArgument(hostConnectionCoreSize > 0, "host connection core size must be > 0");
    Preconditions.checkArgument(hostConnectionLimit > 0, "host connection limit must be > 0");

    if (cmdline.hasOption("p")) {
        statsProvider = ReflectionUtils.newInstance(cmdline.getOptionValue("p"), StatsProvider.class);
    } else {
        statsProvider = new NullStatsProvider();
    }

    logger.info("Starting stats provider : {}.", statsProvider.getClass());
    statsProvider.start(conf);

    Worker w = null;
    if (mode.startsWith("read")) {
        w = runReader();
    } else if (mode.startsWith("write")) {
        w = runWriter();
    } else if (mode.startsWith("dlwrite")) {
        w = runDLWriter();
    } else if (mode.startsWith("dlread")) {
        w = runDLReader();
    }

    if (w == null) {
        throw new IOException("Unknown mode " + mode + " to run the benchmark.");
    }

    Thread workerThread = new Thread(w, mode + "-benchmark-thread");
    workerThread.start();

    TimeUnit.MINUTES.sleep(durationMins);

    logger.info("{} minutes passed, exiting...", durationMins);
    w.close();

    if (null != statsProvider) {
        statsProvider.stop();
    }

    Runtime.getRuntime().exit(0);
}

From source file:de.rrze.idmone.utils.jidgen.cli.IdGenOptions.java

/**
 * Fill the internal variable data by parsing a given
 * array of command line options./*from ww w.  ja  v  a  2  s.  c om*/
 * 
 * @param args
 *          the String array containing all command line options
 * @return the data collection
 * @throws ParseException
 */
public HashMap<String, String> parse(String[] args) throws ParseException {
    // get a list of all stored option objects to be processed
    // excluding all dummy options
    Collection<IdGenOption> options = new HashSet<IdGenOption>();
    options.addAll(this.getOptions());
    options.removeAll(this.dummyOptions.values());
    Iterator<IdGenOption> iter = options.iterator();

    // init the parser
    BasicParser parser = new BasicParser();
    CommandLine commandLine = parser.parse(this, args);

    // iterate over all possible options
    while (iter.hasNext()) {
        IdGenOption currentOption = iter.next();
        //logger.trace("Processing option \"" + currentOption.getShortOpt() + "\"");

        if (commandLine.hasOption(currentOption.getShortOpt())) {
            // option was specified
            String value = commandLine.getOptionValue(currentOption.getShortOpt());
            if (value != null) {
                // option has a specified value
                this.data.put(currentOption.getShortOpt(), value);
                logger.info(currentOption.getShortOpt() + " = " + value);
            } else if (currentOption.hasArg()) {
                // option does NOT have a specified value
                logger.error(currentOption.getShortOpt() + " "
                        + Messages.getString("IdGenOptions.MISSING_ARGUMENT"));
                System.out.println(this.getHelp(false));
                System.exit(170);
            } else {
                // at least put an entry with an empty string in the data array
                // to mark that the option was specified
                this.data.put(currentOption.getShortOpt(), "");
            }
        } else {
            // option was NOT specified, so use default if available
            if (currentOption.hasDefaultValue()) {
                // has default
                logger.info(currentOption.getShortOpt() + " " + Messages.getString("IdGenOptions.USING_DEFAULT")
                        + " " + currentOption.getDefaultValue());
                this.data.put(currentOption.getShortOpt(), currentOption.getDefaultValue());
            }
        }
    }

    return this.data;
}