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:hivemall.utils.lang.CommandLineUtils.java

public static CommandLine parseOptions(final String[] args, final Options opts) {
    final BasicParser parser = new BasicParser();
    final CommandLine cl;
    try {//from ww w  .ja v a 2  s .  c o  m
        cl = parser.parse(opts, args);
    } catch (ParseException e) {
        throw new IllegalArgumentException(e);
    }
    return cl;
}

From source file:gov.nih.nci.caintegrator.heatmap.invokeCBS2HeatMap.java

public static void ReadOptions(String[] args, HeatMapArgs hma) {
    try {//  w w w.  j  av a  2  s  .c om
        Options opt = new Options();

        opt.addOption("h", false, "Print help for this application");
        opt.addOption("big_bins", true, "name of big bin definition file");
        opt.addOption("small_bins", true, "name of small bin definition file");
        opt.addOption("seg", true, "name of file containing segmented copy number data");
        opt.addOption("samples", true, "name of file specifying samples to include");
        opt.addOption("genomeout", true, "name of genome matrix output file");
        opt.addOption("geneout", true, "name of gene matrix output file");
        opt.addOption("title", true, "title for output heatmap");
        opt.addOption("genes", true, "name of RefSeq gene flat file");
        opt.addOption("gender", true, "name of file mapping patients to gender");
        opt.addOption("protocol", true, "matched or unmatched");
        opt.addOption("scale", true,
                "comma-separated list of real positive numbers for interval upperbounds (default is '0.5,1.5,2.5,3.5,4.5')");
        opt.addOption("minseg", true, "minimum segment length to consider (default = 500)");
        opt.addOption("platform", true, "name of platform");
        opt.addOption("submitter", true, "name of center that submitted the data");
        opt.addOption("contact", true, "contact: name of NCI contact person for this heatmap");
        opt.addOption("cnv_track", true, "name of file with cnv track info");
        opt.addOption("project", true, "project: name of project");
        opt.addOption("base", true, "assumed base (can be float) for log ratio values (defaults to 2)");

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

        if (cl.hasOption("h")) {
            HelpFormatter f = new HelpFormatter();
            f.printHelp("OptionsTip", opt);
            System.exit(0);
        } else {
            if (cl.hasOption("small_bins")) {
                hma.setSmallBinFile(cl.getOptionValue("small_bins"));
            }
            if (cl.hasOption("big_bins")) {
                hma.setBigBinFile(cl.getOptionValue("big_bins"));
            }
            if (cl.hasOption("seg")) {
                hma.setSegmentFile(cl.getOptionValue("seg"));
            }
            if (cl.hasOption("samples")) {
                hma.setSampleFile(cl.getOptionValue("samples"));
            }
            if (cl.hasOption("genomeout")) {
                hma.setGenomeOutFile(cl.getOptionValue("genomeout"));
            }
            if (cl.hasOption("geneout")) {
                hma.setGeneOutFile(cl.getOptionValue("geneout"));
            }
            if (cl.hasOption("title")) {
                hma.setTitle(cl.getOptionValue("title"));
            }
            if (cl.hasOption("genes")) {
                hma.setRefGenesFile(cl.getOptionValue("genes"));
            }
            if (cl.hasOption("gender")) {
                hma.setGenderFile(cl.getOptionValue("gender"));
            }
            if (cl.hasOption("protocol")) {
                hma.setProtocol(cl.getOptionValue("protocol"));
            }
            if (cl.hasOption("scale")) {
                hma.setScale(cl.getOptionValue("scale"));
            }
            if (cl.hasOption("minseg")) {
                hma.setMinSegLength(Integer.parseInt(cl.getOptionValue("minseg")));
            }
            if (cl.hasOption("platform")) {
                hma.setPlatform(cl.getOptionValue("platform"));
            }
            if (cl.hasOption("submitter")) {
                hma.setSubmitter(cl.getOptionValue("submitter"));
            }
            if (cl.hasOption("contact")) {
                hma.setContact(cl.getOptionValue("contact"));
            }
            if (cl.hasOption("cnv_track")) {
                hma.setCnvTrack(cl.getOptionValue("cnv_track"));
            }
            if (cl.hasOption("project")) {
                hma.setProject(cl.getOptionValue("project"));
            }
            if (cl.hasOption("base")) {
                hma.setBase(Integer.parseInt(cl.getOptionValue("base")));
            }
        }
    } catch (ParseException e) {
        e.printStackTrace();
    }
}

From source file:com.cloudera.impala.testutil.ImpalaJdbcClient.java

/**
 * Parses command line options//from  www.ja  v a2s. co  m
 */
private static ClientExecOptions parseOptions(String[] args) throws ParseException {
    Options options = new Options();
    options.addOption("i", true, "host:port of target machine impalad is listening on");
    options.addOption("c", true, "Full connection string to use. Overrides host/port value");
    options.addOption("t", true, "SASL/NOSASL, whether to use SASL transport or not");
    options.addOption("q", true, "Query String");
    options.addOption("help", false, "Help");

    BasicParser optionParser = new BasicParser();
    CommandLine cmdArgs = optionParser.parse(options, args);

    String transportOption = cmdArgs.getOptionValue("t");
    if (transportOption == null) {
        LOG.error("Must specify '-t' option, whether to use SASL transport or not.");
        LOG.error("Using the wrong type of transport will cause the program to hang.");
        LOG.error("Usage: " + options.toString());
        System.exit(1);
    }
    if (!transportOption.equalsIgnoreCase("SASL") && !transportOption.equalsIgnoreCase("NOSASL")) {
        LOG.error("Invalid argument " + transportOption + " to '-t' option.");
        LOG.error("Usage: " + options.toString());
        System.exit(1);
    }
    boolean useSasl = transportOption.equalsIgnoreCase("SASL");

    String connStr = cmdArgs.getOptionValue("c", null);

    // If the user didn't specify a custom connection string, build a connection
    // string using HiveServer 2 JDBC driver and no security.
    if (connStr == null) {
        String hostPort = cmdArgs.getOptionValue("i", "localhost:21050");
        connStr = "jdbc:hive2://" + hostPort + "/";
    }
    // Append appropriate auth option to connection string.
    if (useSasl) {
        connStr = connStr + ";auth=none";
    } else {
        // As of Hive 0.11 'noSasl' is case sensitive. See HIVE-4232 for more details.
        connStr = connStr + ";auth=noSasl";
    }

    String query = cmdArgs.getOptionValue("q");
    if (query == null) {
        LOG.error("Must specify a query to execute.");
        LOG.error("Usage: " + options.toString());
        System.exit(1);
    }

    return new ClientExecOptions(connStr, query);
}

From source file:com.cloudera.impala.util.ImpalaJdbcClient.java

/**
 * Parses command line options//from ww w. j  a v  a 2  s  . c  o m
 */
private static ClientExecOptions parseOptions(String[] args) throws ParseException {
    Options options = new Options();
    options.addOption("i", true, "host:port of target machine impalad is listening on");
    options.addOption("c", true, "Full connection string to use. Overrides host/port value");
    options.addOption("t", true, "SASL/NOSASL, whether to use SASL transport or not");
    options.addOption("q", true, "Query String");
    options.addOption("help", false, "Help");

    BasicParser optionParser = new BasicParser();
    CommandLine cmdArgs = optionParser.parse(options, args);

    String transportOption = cmdArgs.getOptionValue("t");
    if (transportOption == null) {
        LOG.error("Must specify '-t' option, whether to use SASL transport or not.");
        LOG.error("Using the wrong type of transport will cause the program to hang.");
        LOG.error("Usage: " + options.toString());
        System.exit(1);
    }
    if (!transportOption.equalsIgnoreCase("SASL") && !transportOption.equalsIgnoreCase("NOSASL")) {
        LOG.error("Invalid argument " + transportOption + " to '-t' option.");
        LOG.error("Usage: " + options.toString());
        System.exit(1);
    }
    boolean useSasl = transportOption.equalsIgnoreCase("SASL");

    String connStr = cmdArgs.getOptionValue("c", null);

    // If the user didn't specify a custom connection string, build a connection
    // string using HiveServer 2 JDBC driver and no security.
    if (connStr == null) {
        String hostPort = cmdArgs.getOptionValue("i", "localhost:21050");
        connStr = "jdbc:hive2://" + hostPort + "/";
    }
    // Append appropriate auth option to connection string.
    if (useSasl) {
        connStr = connStr + SASL_AUTH_SPEC;
    } else {
        connStr = connStr + NOSASL_AUTH_SPEC;
    }

    String query = cmdArgs.getOptionValue("q");
    if (query == null) {
        LOG.error("Must specify a query to execute.");
        LOG.error("Usage: " + options.toString());
        System.exit(1);
    }

    return new ClientExecOptions(connStr, query);
}

From source file:jettyClient.simpleClient.Parameters.java

/**
 * Stores the given command line arguments for the client to use.
 * //from   w w  w.j av a 2s .c o  m
 * @param args
 *            Command line arguments.
 * @return Options for the client to use.
 */
public static ClientOptions setOptions(String[] args) {

    CommandLine line = null;
    Options options = defineOptions();
    BasicParser parser = new BasicParser();

    if (args.length > 0) {
        // Parse the given options
        try {
            line = parser.parse(options, args);
        } catch (ParseException e) {

            if (e instanceof MissingArgumentException) {
                System.out.println("Error: " + e.getMessage());
                logger.debug("MissingArgumentException: " + e.getMessage());
            } else {
                System.out.println("Error: " + e.getMessage());
                logger.debug("ParseException:" + e.getMessage());
            }
            showHelp(options);
        }

        // Print help
        if (line.hasOption(help)) {
            showHelp(options);
        }

        // Set the options read from the command line.
        ClientOptions clientOptions = setOptions(line);

        return clientOptions;

    } else {
        showHelp(options);
    }
    // Unreachable.
    return null;
}

From source file:io.github.agentsoz.abmjadex.super_central.ABMSimStarter.java

private static void parsingArguments(String[] args, Options options) {
    //flags//from w ww.ja va2 s.co m
    boolean isRunningCO = true;
    boolean isForced = false; //Overwrite any existing CO xml file
    boolean isRunningSC = true;
    boolean isLogToConsole = false;
    Level logLevel = Level.INFO;

    Properties prop = null;
    CommandLine line = null;
    BasicParser parser = new BasicParser();
    ArrayList<String> argsList = new ArrayList<String>();

    //Initialize argsList with args
    for (int i = 0; i < args.length; i++) {
        argsList.add(args[i]);
    }

    //Update 04/17/2013
    String[] specificArgs = packageOptionSpecific(args);

    try {
        // parse the command line arguments
        //line = parser.parse(options, args );
        //Update 04/17/2013
        line = parser.parse(options, specificArgs);

        //Commandline required -prop argument to be filled with valid properties file location
        if (line.hasOption(HELP)) {
            //Remove app specific arguments from total arguments
            int helpIndex = argsList.indexOf("-" + HELP);
            if (helpIndex == -1)
                helpIndex = argsList.indexOf("-" + HELP_LONG);
            argsList.remove(helpIndex);

            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("Jadex-ABMS", options);
        }

        if (line.hasOption(PROP)) {
            //Remove app specific arguments from total arguments
            int propIndex = argsList.indexOf("-" + PROP);
            if (propIndex == -1)
                propIndex = argsList.indexOf("-" + PROP_LONG);
            argsList.remove(propIndex + 1);
            argsList.remove(propIndex);

            String propertiesLoc = line.getOptionValue(PROP).replace("\\", "/").replace("\\\\", "/");
            prop = new Properties();

            try {
                prop.load(new FileInputStream(propertiesLoc));
                //Parsing options value into local flags------------------------
                if (line.hasOption(MODE)) {
                    String mode = line.getOptionValue(MODE);
                    if (mode.equalsIgnoreCase(CO_ONLY)) {
                        isRunningSC = false;
                    } else if (mode.equalsIgnoreCase(SC_CO)) {
                        //Default value is to run an SC and a CO
                    } else if (mode.equalsIgnoreCase(SC_ONLY)) {
                        isRunningCO = false;
                    } else {
                        throw new ParseException("Wrong argument for -mode.");
                    }

                    //Remove app specific arguments from total arguments
                    int modeIndex = argsList.indexOf("-" + MODE);
                    argsList.remove(modeIndex + 1);
                    argsList.remove(modeIndex);
                }

                if (line.hasOption(FORCED)) {
                    isForced = true;
                    //Remove app specific arguments from total arguments
                    int modeIndex = argsList.indexOf("-" + FORCED);
                    if (modeIndex == -1)
                        modeIndex = argsList.indexOf("-" + FORCED_LONG);
                    argsList.remove(modeIndex);
                }

                if (line.hasOption(GUI)) {
                    String guiMode = line.getOptionValue(GUI);
                    if (!guiMode.equalsIgnoreCase("true") && !guiMode.equalsIgnoreCase("false"))
                        throw new ParseException("Wrong argument for -gui.");
                } else {
                    argsList.add("-" + GUI);
                    int guiIndex = argsList.indexOf("-" + GUI);
                    argsList.add(guiIndex + 1, "false");
                }

                if (line.hasOption(LOG_CONSOLE)) {
                    isLogToConsole = true;
                    //Remove app specific arguments from total arguments
                    int logCIndex = argsList.indexOf("-" + LOG_CONSOLE);
                    argsList.remove(logCIndex);
                }

                if (line.hasOption(LOG_LVL)) {
                    String level = line.getOptionValue(LOG_LVL);
                    if (level.equalsIgnoreCase("INFO")) {
                        logLevel = Level.INFO;
                    } else if (level.equalsIgnoreCase("ALL")) {
                        logLevel = Level.ALL;
                    } else if (level.equalsIgnoreCase("CONFIG")) {
                        logLevel = Level.CONFIG;
                    } else if (level.equalsIgnoreCase("FINE")) {
                        logLevel = Level.FINE;
                    } else if (level.equalsIgnoreCase("FINER")) {
                        logLevel = Level.FINER;
                    } else if (level.equalsIgnoreCase("FINEST")) {
                        logLevel = Level.FINEST;
                    } else if (level.equalsIgnoreCase("OFF")) {
                        logLevel = Level.OFF;
                    } else if (level.equalsIgnoreCase("SEVERE")) {
                        logLevel = Level.SEVERE;
                    } else if (level.equalsIgnoreCase("WARNING")) {
                        logLevel = Level.WARNING;
                    } else {
                        throw new ParseException("argument for loglvl unknown");
                    }
                    //Remove app specific arguments from total arguments
                    int logLvlIndex = argsList.indexOf("-" + LOG_LVL);
                    argsList.remove(logLvlIndex + 1);
                    argsList.remove(logLvlIndex);
                }

                //Setup logger
                try {
                    ABMBDILoggerSetter.initialized(prop, isLogToConsole, logLevel);
                    ABMBDILoggerSetter.setup(LOGGER);
                } catch (IOException e) {
                    e.printStackTrace();
                    LOGGER.severe(e.getMessage());
                    throw new RuntimeException("Problems with creating logfile");
                }

                //Translate argsList into array------------------------------
                String[] newargs = new String[argsList.size()];
                for (int i = 0; i < argsList.size(); i++) {
                    newargs[i] = argsList.get(i);
                }

                //Running the system----------------------------------------
                if (isRunningSC == true) {
                    runSC(prop);
                }

                if (isRunningCO == true) {
                    runCO(prop, newargs, isForced);
                }

            } catch (IOException e) {
                e.printStackTrace();
                LOGGER.severe(e.getMessage());
            }
        } else {
            throw new ParseException("-prop <properties_location> is a required option");
        }

    } catch (ParseException exp) {
        LOGGER.severe("Unexpected exception:" + exp.getMessage());

        //If its not working print out help info
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("Jadex-ABMS", options);
    }
}

From source file:com.medvision360.medrecord.tools.dumpadl.CommandLineReader.java

/**
 * Parse the command line options./*  www .  jav  a  2s .  c  o m*/
 *
 * @param args The command line arguments.
 */
public void parse(final String[] args) throws ParseException {
    final BasicParser parser = new BasicParser();
    m_commandLine = parser.parse(m_options, args);
}

From source file:com.twitter.distributedlog.service.MonitorServiceApp.java

private void run() {
    try {/*from   w w  w .  j a  va2 s.  c o  m*/
        logger.info("Running monitor service.");
        BasicParser parser = new BasicParser();
        CommandLine cmdline = parser.parse(options, args);
        runCmd(cmdline);
    } catch (ParseException pe) {
        printUsage();
        Runtime.getRuntime().exit(-1);
    } catch (IOException ie) {
        logger.error("Failed to start monitor service : ", ie);
        Runtime.getRuntime().exit(-1);
    }
}

From source file:com.twitter.distributedlog.benchmark.stream.StreamBenchmark.java

protected void parseCommandLine(String[] args) throws Exception {
    BasicParser parser = new BasicParser();
    CommandLine cmdline = parser.parse(options, args);
    if (cmdline.hasOption("h")) {
        printUsage();/*from  www  . ja va 2s. c o  m*/
        System.exit(0);
    }
    if (cmdline.hasOption("u")) {
        this.uri = URI.create(cmdline.getOptionValue("u"));
    } else {
        printUsage();
        System.exit(0);
    }
    this.conf = new DistributedLogConfiguration();
    if (cmdline.hasOption("c")) {
        String configFile = cmdline.getOptionValue("c");
        this.conf.loadConf(new File(configFile).toURI().toURL());
    }
    if (cmdline.hasOption("p")) {
        statsProvider = ReflectionUtils.newInstance(cmdline.getOptionValue("p"), StatsProvider.class);
    } else {
        statsProvider = new NullStatsProvider();
    }
    if (cmdline.hasOption("s")) {
        this.streamName = cmdline.getOptionValue("s");
    } else {
        printUsage();
        System.exit(0);
    }
    parseCommandLine(cmdline);
}

From source file:com.twitter.distributedlog.service.DistributedLogServerApp.java

private void run() {
    try {/*  w ww  .ja  v  a  2 s  .com*/
        logger.info("Running distributedlog server : args = {}", Arrays.toString(args));
        BasicParser parser = new BasicParser();
        CommandLine cmdline = parser.parse(options, args);
        runCmd(cmdline);
    } catch (ParseException pe) {
        logger.error("Argument error : {}", pe.getMessage());
        printUsage();
        Runtime.getRuntime().exit(-1);
    } catch (IllegalArgumentException iae) {
        logger.error("Argument error : {}", iae.getMessage());
        printUsage();
        Runtime.getRuntime().exit(-1);
    } catch (ConfigurationException ce) {
        logger.error("Configuration error : {}", ce.getMessage());
        printUsage();
        Runtime.getRuntime().exit(-1);
    } catch (IOException ie) {
        logger.error("Failed to start distributedlog server : ", ie);
        Runtime.getRuntime().exit(-1);
    }
}