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

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

Introduction

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

Prototype

public String[] getArgs() 

Source Link

Document

Retrieve any left-over non-recognized options and arguments

Usage

From source file:com.inmobi.conduit.distcp.tools.OptionsParser.java

/**
 * The parse method parses the command-line options, and creates
 * a corresponding Options object.//from   w  w w .  ja  v  a2 s  .  co m
 * @param args: Command-line arguments (excluding the options consumed
 *              by the GenericOptionsParser).
 * @return The Options object, corresponding to the specified command-line.
 * @throws IllegalArgumentException: Thrown if the parse fails.
 */
public static DistCpOptions parse(String args[]) throws IllegalArgumentException {

    CommandLineParser parser = new CustomParser();

    CommandLine command;
    try {
        command = parser.parse(cliOptions, args, true);
    } catch (ParseException e) {
        throw new IllegalArgumentException("Unable to parse arguments. " + Arrays.toString(args), e);
    }

    DistCpOptions option;
    Path targetPath;
    List<Path> sourcePaths = new ArrayList<Path>();

    String leftOverArgs[] = command.getArgs();
    if (leftOverArgs == null || leftOverArgs.length < 1) {
        throw new IllegalArgumentException("Target path not specified");
    }

    //Last Argument is the target path
    targetPath = new Path(leftOverArgs[leftOverArgs.length - 1].trim());

    //Copy any source paths in the arguments to the list
    for (int index = 0; index < leftOverArgs.length - 1; index++) {
        sourcePaths.add(new Path(leftOverArgs[index].trim()));
    }

    /* If command has source file listing, use it else, fall back on source paths in args
       If both are present, throw exception and bail */
    if (command.hasOption(DistCpOptionSwitch.SOURCE_FILE_LISTING.getSwitch())) {
        if (!sourcePaths.isEmpty()) {
            throw new IllegalArgumentException("Both source file listing and source paths present");
        }
        option = new DistCpOptions(
                new Path(getVal(command, DistCpOptionSwitch.SOURCE_FILE_LISTING.getSwitch())), targetPath);
    } else {
        if (sourcePaths.isEmpty()) {
            throw new IllegalArgumentException("Neither source file listing nor source paths present");
        }
        option = new DistCpOptions(sourcePaths, targetPath);
    }

    //Process all the other option switches and set options appropriately
    if (command.hasOption(DistCpOptionSwitch.IGNORE_FAILURES.getSwitch())) {
        option.setIgnoreFailures(true);
    }

    if (command.hasOption(DistCpOptionSwitch.PRESERVE_SRC_PATH.getSwitch())) {
        option.setPreserveSrcPath(true);
    }

    if (command.hasOption(DistCpOptionSwitch.ATOMIC_COMMIT.getSwitch())) {
        option.setAtomicCommit(true);
    }

    if (command.hasOption(DistCpOptionSwitch.WORK_PATH.getSwitch()) && option.shouldAtomicCommit()) {
        String workPath = getVal(command, DistCpOptionSwitch.WORK_PATH.getSwitch());
        if (workPath != null && !workPath.isEmpty()) {
            option.setAtomicWorkPath(new Path(workPath));
        }
    } else if (command.hasOption(DistCpOptionSwitch.WORK_PATH.getSwitch())) {
        throw new IllegalArgumentException("-tmp work-path can only be specified along with -atomic");
    }

    if (command.hasOption(DistCpOptionSwitch.LOG_PATH.getSwitch())) {
        option.setLogPath(new Path(getVal(command, DistCpOptionSwitch.LOG_PATH.getSwitch())));
    }

    if (command.hasOption(DistCpOptionSwitch.SYNC_FOLDERS.getSwitch())) {
        option.setSyncFolder(true);
    }

    if (command.hasOption(DistCpOptionSwitch.OVERWRITE.getSwitch())) {
        option.setOverwrite(true);
    }

    if (command.hasOption(DistCpOptionSwitch.DELETE_MISSING.getSwitch())) {
        option.setDeleteMissing(true);
    }

    if (command.hasOption(DistCpOptionSwitch.SKIP_CRC.getSwitch())) {
        option.setSkipCRC(true);
    }

    if (command.hasOption(DistCpOptionSwitch.BLOCKING.getSwitch())) {
        option.setBlocking(false);
    }

    if (command.hasOption(DistCpOptionSwitch.BANDWIDTH.getSwitch())) {
        try {
            Integer mapBandwidth = Integer
                    .parseInt(getVal(command, DistCpOptionSwitch.BANDWIDTH.getSwitch()).trim());
            option.setMapBandwidth(mapBandwidth);
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("Bandwidth specified is invalid: "
                    + getVal(command, DistCpOptionSwitch.BANDWIDTH.getSwitch()), e);
        }
    }

    if (command.hasOption(DistCpOptionSwitch.BANDWIDTH_KB.getSwitch())) {
        try {
            Integer mapBandwidth = Integer
                    .parseInt(getVal(command, DistCpOptionSwitch.BANDWIDTH_KB.getSwitch()).trim());
            option.setMapBandwidthKB(mapBandwidth);
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("Bandwidth specified is invalid: "
                    + getVal(command, DistCpOptionSwitch.BANDWIDTH_KB.getSwitch()), e);
        }
    }

    if (command.hasOption(DistCpOptionSwitch.SSL_CONF.getSwitch())) {
        option.setSslConfigurationFile(command.getOptionValue(DistCpOptionSwitch.SSL_CONF.getSwitch()));
    }

    if (command.hasOption(DistCpOptionSwitch.MAX_MAPS.getSwitch())) {
        try {
            Integer maps = Integer.parseInt(getVal(command, DistCpOptionSwitch.MAX_MAPS.getSwitch()).trim());
            option.setMaxMaps(maps);
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException(
                    "Number of maps is invalid: " + getVal(command, DistCpOptionSwitch.MAX_MAPS.getSwitch()),
                    e);
        }
    }

    if (command.hasOption(DistCpOptionSwitch.COPY_STRATEGY.getSwitch())) {
        option.setCopyStrategy(getVal(command, DistCpOptionSwitch.COPY_STRATEGY.getSwitch()));
    }

    if (command.hasOption(DistCpOptionSwitch.PRESERVE_STATUS.getSwitch())) {
        String attributes = getVal(command, DistCpOptionSwitch.PRESERVE_STATUS.getSwitch());
        if (attributes == null || attributes.isEmpty()) {
            for (FileAttribute attribute : FileAttribute.values()) {
                option.preserve(attribute);
            }
        } else {
            for (int index = 0; index < attributes.length(); index++) {
                option.preserve(FileAttribute.getAttribute(attributes.charAt(index)));
            }
        }
    }

    if (command.hasOption(DistCpOptionSwitch.FILE_LIMIT.getSwitch())) {
        String fileLimitString = getVal(command, DistCpOptionSwitch.FILE_LIMIT.getSwitch().trim());
        try {
            Integer.parseInt(fileLimitString);
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("File-limit is invalid: " + fileLimitString, e);
        }
        LOG.warn(DistCpOptionSwitch.FILE_LIMIT.getSwitch() + " is a deprecated" + " option. Ignoring.");
    }

    if (command.hasOption(DistCpOptionSwitch.SIZE_LIMIT.getSwitch())) {
        String sizeLimitString = getVal(command, DistCpOptionSwitch.SIZE_LIMIT.getSwitch().trim());
        try {
            Long.parseLong(sizeLimitString);
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("Size-limit is invalid: " + sizeLimitString, e);
        }
        LOG.warn(DistCpOptionSwitch.SIZE_LIMIT.getSwitch() + " is a deprecated" + " option. Ignoring.");
    }

    return option;
}

From source file:com.aerospike.yelp.Load.java

private static Parameters parseParameters(String[] args) throws ParseException {
    Parameters params = new Parameters();

    Options options = new Options();
    options.addOption("h", "host", true, "Server hostname (default: localhost)");
    options.addOption("p", "port", true, "Server port (default: 3000)");
    options.addOption("U", "user", true, "User name");
    options.addOption("P", "password", true, "Password");
    options.addOption("n", "namespace", true, "Namespace (default: test)");
    options.addOption("s", "set", true, "Set name (default: yelp)");
    options.addOption("u", "usage", false, "Print usage");

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

    params.host = cl.getOptionValue("h", "localhost");
    String portString = cl.getOptionValue("p", "3000");
    params.port = Integer.parseInt(portString);
    params.user = cl.getOptionValue("U");
    params.password = cl.getOptionValue("P");
    params.namespace = cl.getOptionValue("n", "test");
    params.set = cl.getOptionValue("s", "yelp");

    if (cl.hasOption("u")) {
        usage(options);//  ww  w .  j a  v a2 s. com
        System.exit(0);
    }

    String[] remargs = cl.getArgs();
    if (remargs.length != 1) {
        System.out.println("missing infile parameter");
        usage(options);
        System.exit(1);
    }

    params.infile = remargs[0];

    return params;
}

From source file:heybot.heybot.java

private static void processArgs(String[] args) {
    CommandLine line = getParser(buildOptions(), args);
    if (line.hasOption("help")) {
        printHelp();//ww w  .j  ava 2  s. c o m
    } else if (line.hasOption("version")) {
        printVersionDetailed();
    } else if (line.hasOption("list")) {
        listAllOperations();
    } else if (line.hasOption("list-prefix")) {
        listOperationsStartsWith(line.getOptionValue("list-prefix"));
    } else if (line.hasOption("insert")) {
        if (line.getArgs().length > 0) {
            insertOperationParameters(line.getOptionValue("insert"), line.getArgs());
        } else {
            System.err.println("Ooops! Please add parameters after operation.");
        }
    } else if (line.hasOption("select")) {
        selectOperationParameters(line.getOptionValue("select"));
    } else if (line.hasOption("open")) {
        openOperation(line.getOptionValue("open"));
    } else if (line.hasOption("remove")) {
        removeOperation(line.getOptionValue("remove"));
    } else {
        start(line);
    }
}

From source file:net.mindengine.galen.runner.GalenArguments.java

public static GalenArguments parse(String[] args) throws ParseException {

    args = processSystemProperties(args);

    //TODO Refactor this ugly way of handling command line arguments. It should be separate per action.

    Options options = new Options();
    options.addOption("u", "url", true, "Url for test page");
    options.addOption("j", "javascript", true,
            "Path to javascript file which will be executed after test page loads");
    options.addOption("i", "include", true, "Tags for sections that should be included in test run");
    options.addOption("e", "exclude", true, "Tags for sections that should be excluded from test run");
    options.addOption("s", "size", true, "Browser screen size");
    options.addOption("H", "htmlreport", true, "Path for html output report");
    options.addOption("g", "testngreport", true, "Path for testng xml report");
    options.addOption("r", "recursive", false, "Flag for recursive tests scan");
    options.addOption("p", "parallel-suites", true, "Amount of suites to be run in parallel");
    options.addOption("v", "version", false, "Current version");

    CommandLineParser parser = new PosixParser();

    CommandLine cmd = null;

    try {/*from   w  w w.java 2 s.  com*/
        cmd = parser.parse(options, args);
    } catch (MissingArgumentException e) {
        throw new IllegalArgumentException("Missing value for " + e.getOption().getLongOpt(), e);
    }

    GalenArguments galen = new GalenArguments();

    galen.setOriginal(merge(args));
    String[] leftovers = cmd.getArgs();

    if (leftovers.length > 0) {
        String action = leftovers[0];
        galen.setAction(action);

        if (leftovers.length > 1) {
            List<String> paths = new LinkedList<String>();
            for (int i = 1; i < leftovers.length; i++) {
                paths.add(leftovers[i]);
            }
            galen.setPaths(paths);
        }
    }

    galen.setUrl(cmd.getOptionValue("u"));

    galen.setIncludedTags(convertTags(cmd.getOptionValue("i", "")));
    galen.setExcludedTags(convertTags(cmd.getOptionValue("e", "")));
    galen.setScreenSize(convertScreenSize(cmd.getOptionValue("s")));
    galen.setJavascript(cmd.getOptionValue("javascript"));
    galen.setTestngReport(cmd.getOptionValue("g"));
    galen.setRecursive(cmd.hasOption("r"));
    galen.setHtmlReport(cmd.getOptionValue("H"));
    galen.setParallelSuites(Integer.parseInt(cmd.getOptionValue("p", "0")));
    galen.setPrintVersion(cmd.hasOption("v"));

    verifyArguments(galen);
    return galen;
}

From source file:eu.interedition.collatex.tools.CollationPipe.java

public static void start(CommandLine commandLine) throws Exception {
    List<SimpleWitness> witnesses = null;
    Function<String, Stream<String>> tokenizer = SimplePatternTokenizer.BY_WS_OR_PUNCT;
    Function<String, String> normalizer = SimpleTokenNormalizers.LC_TRIM_WS;
    Comparator<Token> comparator = new EqualityTokenComparator();
    CollationAlgorithm collationAlgorithm = null;
    boolean joined = true;

    final String[] witnessSpecs = commandLine.getArgs();
    final InputStream[] inputStreams = new InputStream[witnessSpecs.length];
    for (int wc = 0, wl = witnessSpecs.length; wc < wl; wc++) {
        try {/*w  w w. j av a  2  s .  c  o m*/
            inputStreams[wc] = argumentToInputStream(witnessSpecs[wc]);
        } catch (MalformedURLException urlEx) {
            throw new ParseException("Invalid resource: " + witnessSpecs[wc]);
        }
    }

    if (inputStreams.length < 1) {
        throw new ParseException("No input resource(s) given");
    } else if (inputStreams.length < 2) {
        try (InputStream inputStream = inputStreams[0]) {
            final SimpleCollation collation = JsonProcessor.read(inputStream);
            witnesses = collation.getWitnesses();
            collationAlgorithm = collation.getAlgorithm();
            joined = collation.isJoined();
        }
    }

    final String script = commandLine.getOptionValue("s");
    try {
        final PluginScript pluginScript = (script == null
                ? PluginScript.read("<internal>", new StringReader(""))
                : PluginScript.read(argumentToInput(script)));

        tokenizer = Optional.ofNullable(pluginScript.tokenizer()).orElse(tokenizer);
        normalizer = Optional.ofNullable(pluginScript.normalizer()).orElse(normalizer);
        comparator = Optional.ofNullable(pluginScript.comparator()).orElse(comparator);
    } catch (IOException e) {
        throw new ParseException("Failed to read script '" + script + "' - " + e.getMessage());
    }

    switch (commandLine.getOptionValue("a", "").toLowerCase()) {
    case "needleman-wunsch":
        collationAlgorithm = CollationAlgorithmFactory.needlemanWunsch(comparator);
        break;
    case "medite":
        collationAlgorithm = CollationAlgorithmFactory.medite(comparator, SimpleToken.TOKEN_MATCH_EVALUATOR);
        break;
    case "gst":
        collationAlgorithm = CollationAlgorithmFactory.greedyStringTiling(comparator, 2);
        break;
    default:
        collationAlgorithm = Optional.ofNullable(collationAlgorithm)
                .orElse(CollationAlgorithmFactory.dekker(comparator));
        break;
    }

    if (witnesses == null) {
        final Charset inputCharset = Charset
                .forName(commandLine.getOptionValue("ie", StandardCharsets.UTF_8.name()));
        final boolean xmlMode = commandLine.hasOption("xml");
        final XPathExpression tokenXPath = XPathFactory.newInstance().newXPath()
                .compile(commandLine.getOptionValue("xp", "//text()"));

        witnesses = new ArrayList<>(inputStreams.length);
        for (int wc = 0, wl = inputStreams.length; wc < wl; wc++) {
            try (InputStream stream = inputStreams[wc]) {
                final String sigil = "w" + (wc + 1);
                if (!xmlMode) {
                    final BufferedReader reader = new BufferedReader(
                            new InputStreamReader(stream, inputCharset));
                    final StringWriter writer = new StringWriter();
                    final char[] buf = new char[1024];
                    while (reader.read(buf) != -1) {
                        writer.write(buf);
                    }
                    witnesses.add(new SimpleWitness(sigil, writer.toString(), tokenizer, normalizer));
                } else {
                    final DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance()
                            .newDocumentBuilder();
                    final Document document = documentBuilder.parse(stream);
                    document.normalizeDocument();

                    final SimpleWitness witness = new SimpleWitness(sigil);
                    final NodeList tokenNodes = (NodeList) tokenXPath.evaluate(document,
                            XPathConstants.NODESET);
                    final List<Token> tokens = new ArrayList<>(tokenNodes.getLength());
                    for (int nc = 0; nc < tokenNodes.getLength(); nc++) {
                        final String tokenText = tokenNodes.item(nc).getTextContent();
                        tokens.add(new SimpleToken(witness, tokenText, normalizer.apply(tokenText)));
                    }
                    witness.setTokens(tokens);
                    witnesses.add(witness);
                }
            }
        }
    }

    final VariantGraph variantGraph = new VariantGraph();
    collationAlgorithm.collate(variantGraph, witnesses);

    if (joined && !commandLine.hasOption("t")) {
        VariantGraph.JOIN.apply(variantGraph);
    }

    final String output = commandLine.getOptionValue("o", "-");
    final Charset outputCharset = Charset
            .forName(commandLine.getOptionValue("oe", StandardCharsets.UTF_8.name()));
    final String outputFormat = commandLine.getOptionValue("f", "json").toLowerCase();

    try (PrintWriter out = argumentToOutput(output, outputCharset)) {
        final SimpleVariantGraphSerializer serializer = new SimpleVariantGraphSerializer(variantGraph);
        if ("csv".equals(outputFormat)) {
            serializer.toCsv(out);
        } else if ("dot".equals(outputFormat)) {
            serializer.toDot(out);
        } else if ("graphml".equals(outputFormat) || "tei".equals(outputFormat)) {
            XMLStreamWriter xml = null;
            try {
                xml = XMLOutputFactory.newInstance().createXMLStreamWriter(out);
                xml.writeStartDocument(outputCharset.name(), "1.0");
                if ("graphml".equals(outputFormat)) {
                    serializer.toGraphML(xml);
                } else {
                    serializer.toTEI(xml);
                }
                xml.writeEndDocument();
            } catch (XMLStreamException e) {
                throw new IOException(e);
            } finally {
                if (xml != null) {
                    try {
                        xml.close();
                    } catch (XMLStreamException e) {
                        // ignored
                    }
                }
            }
        } else {
            JsonProcessor.write(variantGraph, out);
        }
    }
}

From source file:com.marklogic.contentpump.ContentPump.java

public static int runCommand(String[] args) throws IOException {
    // get command
    String cmd = args[0];//from  www .j av a2  s  . com
    if (cmd.equalsIgnoreCase("help")) {
        printUsage();
        return 1;
    } else if (cmd.equalsIgnoreCase("version")) {
        logVersions();
        return 1;
    }

    Command command = Command.forName(cmd);

    // get options arguments
    String[] optionArgs = Arrays.copyOfRange(args, 1, args.length);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Command: " + command);
        StringBuilder buf = new StringBuilder();
        for (String arg : optionArgs) {
            buf.append(arg);
            buf.append(' ');
        }
        LOG.debug("Arguments: " + buf);
    }

    // parse hadoop specific options
    Configuration conf = new Configuration();
    GenericOptionsParser genericParser = new GenericOptionsParser(conf, optionArgs);
    String[] remainingArgs = genericParser.getRemainingArgs();

    // parse command specific options
    CommandlineOptions options = new CommandlineOptions();
    command.configOptions(options);
    CommandLineParser parser = new GnuParser();
    CommandLine cmdline;
    try {
        cmdline = parser.parse(options, remainingArgs);
    } catch (Exception e) {
        LOG.error("Error parsing command arguments: ");
        LOG.error(e.getMessage());
        // Print the command usage message and exit.    
        command.printUsage(command, options.getPublicOptions());
        return 1; // Exit on exception here.
    }

    for (String arg : cmdline.getArgs()) {
        LOG.error("Unrecognized argument: " + arg);
        // Print the command usage message and exit.
        command.printUsage(command, options.getPublicOptions());
        return 1; // Exit on exception here.
    }

    // check running mode and hadoop conf dir configuration 
    String mode = cmdline.getOptionValue(MODE);
    String hadoopConfDir = System.getenv(HADOOP_CONFDIR_ENV_NAME);
    if (cmdline.hasOption(HADOOP_CONF_DIR)) {
        hadoopConfDir = cmdline.getOptionValue(HADOOP_CONF_DIR);
    }

    boolean distributed = hadoopConfDir != null && (mode == null || mode.equals(MODE_DISTRIBUTED));
    if (MODE_DISTRIBUTED.equalsIgnoreCase(mode) && !distributed) {
        LOG.error("Cannot run in distributed mode.  HADOOP_CONF_DIR is " + "not configured.");
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Running in: " + (distributed ? "distributed " : "local") + "mode");
        if (distributed) {
            LOG.debug("HADOOP_CONF_DIR is set to " + hadoopConfDir);
        }
    }
    conf.set(EXECUTION_MODE, distributed ? MODE_DISTRIBUTED : MODE_LOCAL);

    if (distributed) {
        if (!cmdline.hasOption(SPLIT_INPUT) && Command.getInputType(cmdline).equals(InputType.DELIMITED_TEXT)) {
            conf.setBoolean(ConfigConstants.CONF_SPLIT_INPUT, true);
        }
        File hdConfDir = new File(hadoopConfDir);
        try {
            checkHadoopConfDir(hdConfDir);
        } catch (IllegalArgumentException e) {
            LOG.error("Error found with Hadoop home setting", e);
            System.err.println(e.getMessage());
            return 1;
        }
        // set new class loader based on Hadoop Conf Dir
        try {
            setClassLoader(hdConfDir, conf);
        } catch (Exception e) {
            LOG.error("Error configuring class loader", e);
            System.err.println(e.getMessage());
            return 1;
        }
    } else { // running in local mode
        // Tell Hadoop that we are running in local mode.  This is useful
        // when the user has Hadoop home or their Hadoop conf dir in their
        // classpath but want to run in local mode.
        conf.set(CONF_MAPREDUCE_JOBTRACKER_ADDRESS, "local");
    }

    // create job
    Job job = null;
    try {
        if (distributed) {
            // So far all jobs created by mlcp are map only,
            // so set number of reduce tasks to 0.
            conf.setInt("mapreduce.job.reduces", 0);
            // No speculative runs since speculative tasks don't get to 
            // clean up sessions properly
            conf.setBoolean("mapreduce.map.speculative", false);
        } else {
            // set working directory
            conf.set(CONF_MAPREDUCE_JOB_WORKING_DIR, System.getProperty("user.dir"));
        }
        job = command.createJob(conf, cmdline);
    } catch (Exception e) {
        // Print exception message.
        e.printStackTrace();
        return 1;
    }

    LOG.info("Job name: " + job.getJobName());
    // run job
    try {
        if (distributed) {
            // submit job
            submitJob(job);
        } else {
            runJobLocally(job, cmdline, command);
        }
        return 0;
    } catch (Exception e) {
        LOG.error("Error running a ContentPump job", e);
        e.printStackTrace(System.err);
        return 1;
    }
}

From source file:com.puppycrawl.tools.checkstyle.Main.java

/**
 * Util method to convert CommandLine type to POJO object.
 * @param cmdLine command line object//  w  ww  .  j av  a2  s  .com
 * @return command line option as POJO object
 */
private static CliOptions convertCliToPojo(CommandLine cmdLine) {
    final CliOptions conf = new CliOptions();
    conf.format = cmdLine.getOptionValue(OPTION_F_NAME);
    if (conf.format == null) {
        conf.format = PLAIN_FORMAT_NAME;
    }
    conf.outputLocation = cmdLine.getOptionValue(OPTION_O_NAME);
    conf.configLocation = cmdLine.getOptionValue(OPTION_C_NAME);
    conf.propertiesLocation = cmdLine.getOptionValue(OPTION_P_NAME);
    conf.files = getFilesToProcess(cmdLine.getArgs());
    return conf;
}

From source file:com.linkedin.databus2.relay.DatabusRelayMain.java

public static String[] processLocalArgs(String[] cliArgs) throws IOException, ParseException {
    CommandLineParser cliParser = new GnuParser();
    Options cliOptions = constructCommandLineOptions();

    CommandLine cmd = cliParser.parse(cliOptions, cliArgs, true);
    // Options here has to be up front
    if (cmd.hasOption(DB_RELAY_CONFIG_FILE_OPT_NAME)) {
        String opt = cmd.getOptionValue(DB_RELAY_CONFIG_FILE_OPT_NAME);
        LOG.info("DbConfig command line=" + opt);
        _dbRelayConfigFiles = opt.split(",");
        LOG.info("DB Relay Config File = " + Arrays.toString(_dbRelayConfigFiles));
    }/*w w w.  j ava 2s. co  m*/

    // return what left over args
    return cmd.getArgs();
}

From source file:com.quest.orahive.HiveJdbcClient.java

private static String[] parseGeneralOptions(Options opts, Configuration conf, String[] args) {

    opts = buildGeneralOptions(opts);//from  w w w .  ja va  2  s .co  m
    CommandLineParser parser = new GnuParser();
    try {
        CommandLine commandLine = parser.parse(opts, args, true);
        processGeneralOptions(conf, commandLine);
        return commandLine.getArgs();
    } catch (ParseException e) {
        LOG.warn("options parsing failed: " + e.getMessage());

        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("general options are: ", opts);
    }
    return args;
}

From source file:groovy.ui.InteractiveShell.java

/**
 * Process cli args when the shell is invoked via main().
 *
 * @noinspection AccessStaticViaInstance
 *///  w  ww.  j  a  va2s . co  m
private static void processCommandLineArguments(final String[] args) throws Exception {
    assert args != null;

    //
    // TODO: Let this take a single, optional argument which is a file or URL to run?
    //

    Options options = new Options();

    options.addOption(OptionBuilder.withLongOpt("help")
            .withDescription(MESSAGES.getMessage("cli.option.help.description")).create('h'));

    options.addOption(OptionBuilder.withLongOpt("version")
            .withDescription(MESSAGES.getMessage("cli.option.version.description")).create('V'));

    //
    // TODO: Add more options, maybe even add an option to prime the buffer from a URL or File?
    //

    //
    // FIXME: This does not currently barf on unsupported options short options, though it does for long ones.
    //        Same problem with commons-cli 1.0 and 1.1
    //

    CommandLineParser parser = new PosixParser();
    CommandLine line = parser.parse(options, args, true);
    String[] lineargs = line.getArgs();

    // Puke if there were arguments, we don't support any right now
    if (lineargs.length != 0) {
        System.err.println(MESSAGES.format("cli.info.unexpected_args",
                new Object[] { DefaultGroovyMethods.join(lineargs, " ") }));
        System.exit(1);
    }

    PrintWriter writer = new PrintWriter(System.out);

    if (line.hasOption('h')) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(writer, 80, // width
                "groovysh [options]", "", options, 4, // left pad
                4, // desc pad
                "", false); // auto usage

        writer.flush();
        System.exit(0);
    }

    if (line.hasOption('V')) {
        writer.println(MESSAGES.format("cli.info.version", new Object[] { InvokerHelper.getVersion() }));
        writer.flush();
        System.exit(0);
    }
}