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

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

Introduction

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

Prototype

BasicParser

Source Link

Usage

From source file:org.apache.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 w  ww.  j  a v  a 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"));
        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"));
    }
    if (cmdline.hasOption("rs")) {
        routingServiceFinagleNameString = cmdline.getOptionValue("rs");
    }
    thriftmux = cmdline.hasOption("mx");
    handshakeWithClientInfo = cmdline.hasOption("hsci");
    readFromHead = cmdline.hasOption("rfh");
    enableBatching = cmdline.hasOption("bt");
    if (cmdline.hasOption("bbs")) {
        batchBufferSize = Integer.parseInt(cmdline.getOptionValue("bbs"));
    }
    if (cmdline.hasOption("bfi")) {
        batchFlushIntervalMicros = Integer.parseInt(cmdline.getOptionValue("bfi"));
    }

    checkArgument(shardId >= 0, "shardId must be >= 0");
    checkArgument(numStreams > 0, "numStreams must be > 0");
    checkArgument(durationMins > 0, "durationMins must be > 0");
    checkArgument(streamPrefix != null, "streamPrefix must be defined");
    checkArgument(hostConnectionCoreSize > 0, "host connection core size must be > 0");
    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:org.apache.distributedlog.service.DistributedLogServerApp.java

private void run() {
    try {//from www .j  ava  2 s  . c  om
        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);
    } catch (ClassNotFoundException cnf) {
        logger.error("Failed to start distributedlog server : ", cnf);
        Runtime.getRuntime().exit(-1);
    }
}

From source file:org.apache.druid.examples.rabbitmq.RabbitMQProducerMain.java

public static void main(String[] args) throws Exception {
    // We use a List to keep track of option insertion order. See below.
    final List<Option> optionList = new ArrayList<Option>();

    optionList.add(OptionBuilder.withLongOpt("help").withDescription("display this help message").create("h"));
    optionList.add(OptionBuilder.withLongOpt("hostname").hasArg()
            .withDescription("the hostname of the AMQP broker [defaults to AMQP library default]").create("b"));
    optionList.add(OptionBuilder.withLongOpt("port").hasArg()
            .withDescription("the port of the AMQP broker [defaults to AMQP library default]").create("n"));
    optionList.add(OptionBuilder.withLongOpt("username").hasArg()
            .withDescription("username to connect to the AMQP broker [defaults to AMQP library default]")
            .create("u"));
    optionList.add(OptionBuilder.withLongOpt("password").hasArg()
            .withDescription("password to connect to the AMQP broker [defaults to AMQP library default]")
            .create("p"));
    optionList.add(OptionBuilder.withLongOpt("vhost").hasArg()
            .withDescription("name of virtual host on the AMQP broker [defaults to AMQP library default]")
            .create("v"));
    optionList.add(OptionBuilder.withLongOpt("exchange").isRequired().hasArg()
            .withDescription("name of the AMQP exchange [required - no default]").create("e"));
    optionList.add(OptionBuilder.withLongOpt("key").hasArg()
            .withDescription("the routing key to use when sending messages [default: 'default.routing.key']")
            .create("k"));
    optionList.add(OptionBuilder.withLongOpt("type").hasArg()
            .withDescription("the type of exchange to create [default: 'topic']").create("t"));
    optionList.add(OptionBuilder.withLongOpt("durable")
            .withDescription("if set, a durable exchange will be declared [default: not set]").create("d"));
    optionList.add(OptionBuilder.withLongOpt("autodelete")
            .withDescription("if set, an auto-delete exchange will be declared [default: not set]")
            .create("a"));
    optionList.add(OptionBuilder.withLongOpt("single")
            .withDescription("if set, only a single message will be sent [default: not set]").create("s"));
    optionList.add(OptionBuilder.withLongOpt("start").hasArg()
            .withDescription("time to use to start sending messages from [default: 2010-01-01T00:00:00]")
            .create());//  w w  w  .jav  a2 s  .c om
    optionList.add(OptionBuilder.withLongOpt("stop").hasArg().withDescription(
            "time to use to send messages until (format: '2013-07-18T23:45:59') [default: current time]")
            .create());
    optionList.add(OptionBuilder.withLongOpt("interval").hasArg()
            .withDescription("the interval to add to the timestamp between messages in seconds [default: 10]")
            .create());
    optionList.add(OptionBuilder.withLongOpt("delay").hasArg()
            .withDescription("the delay between sending messages in milliseconds [default: 100]").create());

    // An extremely silly hack to maintain the above order in the help formatting.
    HelpFormatter formatter = new HelpFormatter();
    // Add a comparator to the HelpFormatter using the ArrayList above to sort by insertion order.
    //noinspection ComparatorCombinators -- don't replace with comparingInt() to preserve comments
    formatter.setOptionComparator((o1, o2) -> {
        // I know this isn't fast, but who cares! The list is short.
        //noinspection SuspiciousMethodCalls
        return Integer.compare(optionList.indexOf(o1), optionList.indexOf(o2));
    });

    // Now we can add all the options to an Options instance. This is dumb!
    Options options = new Options();
    for (Option option : optionList) {
        options.addOption(option);
    }

    CommandLine cmd = null;

    try {
        cmd = new BasicParser().parse(options, args);
    } catch (ParseException e) {
        formatter.printHelp("RabbitMQProducerMain", e.getMessage(), options, null);
        System.exit(1);
    }

    if (cmd.hasOption("h")) {
        formatter.printHelp("RabbitMQProducerMain", options);
        System.exit(2);
    }

    ConnectionFactory factory = new ConnectionFactory();

    if (cmd.hasOption("b")) {
        factory.setHost(cmd.getOptionValue("b"));
    }
    if (cmd.hasOption("u")) {
        factory.setUsername(cmd.getOptionValue("u"));
    }
    if (cmd.hasOption("p")) {
        factory.setPassword(cmd.getOptionValue("p"));
    }
    if (cmd.hasOption("v")) {
        factory.setVirtualHost(cmd.getOptionValue("v"));
    }
    if (cmd.hasOption("n")) {
        factory.setPort(Integer.parseInt(cmd.getOptionValue("n")));
    }

    String exchange = cmd.getOptionValue("e");
    String routingKey = "default.routing.key";
    if (cmd.hasOption("k")) {
        routingKey = cmd.getOptionValue("k");
    }

    boolean durable = cmd.hasOption("d");
    boolean autoDelete = cmd.hasOption("a");
    String type = cmd.getOptionValue("t", "topic");
    boolean single = cmd.hasOption("single");
    int interval = Integer.parseInt(cmd.getOptionValue("interval", "10"));
    int delay = Integer.parseInt(cmd.getOptionValue("delay", "100"));

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ENGLISH);
    Date stop = sdf.parse(cmd.getOptionValue("stop", sdf.format(new Date())));

    Random r = ThreadLocalRandom.current();
    Calendar timer = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.ENGLISH);
    timer.setTime(sdf.parse(cmd.getOptionValue("start", "2010-01-01T00:00:00")));

    String msg_template = "{\"utcdt\": \"%s\", \"wp\": %d, \"gender\": \"%s\", \"age\": %d}";

    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(exchange, type, durable, autoDelete, null);

    do {
        int wp = (10 + r.nextInt(90)) * 100;
        String gender = r.nextBoolean() ? "male" : "female";
        int age = 20 + r.nextInt(70);

        String line = StringUtils.format(msg_template, sdf.format(timer.getTime()), wp, gender, age);

        channel.basicPublish(exchange, routingKey, null, StringUtils.toUtf8(line));

        System.out.println("Sent message: " + line);

        timer.add(Calendar.SECOND, interval);

        Thread.sleep(delay);
    } while ((!single && stop.after(timer.getTime())));

    connection.close();
}

From source file:org.apache.giraph.utils.ConfigurationUtils.java

/**
 * Translate CLI arguments to GiraphRunner or 'bin/hadoop jar' into
 * Configuration Key-Value pairs.//from w  ww .  ja  v a  2s  .  c  o m
 * @param giraphConf the current job Configuration.
 * @param args the raw CLI args to parse
 * @return a CommandLine object, or null if the job run should exit.
 */
public static CommandLine parseArgs(final GiraphConfiguration giraphConf, final String[] args)
        throws ClassNotFoundException, ParseException, IOException {
    // verify we have args at all (can't run without them!)
    if (args.length == 0) {
        throw new IllegalArgumentException("No arguments were provided (try -h)");
    }
    CommandLineParser parser = new BasicParser();
    CommandLine cmd = parser.parse(OPTIONS, args);

    // simply printing help or info, return normally but kill job run
    if (cmd.hasOption("h")) {
        printHelp();
        return null;
    }
    if (cmd.hasOption("la")) {
        printSupportedAlgorithms();
        return null;
    }

    // Be certain that there are no critical args missing, die if so.
    performSanityCheck(cmd);

    // Args are OK; attempt to populate the GiraphConfiguration with them.
    final String vertexClassName = args[0];
    final int workers = Integer.parseInt(cmd.getOptionValue('w'));
    populateGiraphConfiguration(giraphConf, cmd, vertexClassName, workers);

    // validate generic parameters chosen are correct or
    // throw IllegalArgumentException, halting execution.
    @SuppressWarnings("rawtypes")
    GiraphConfigurationValidator<?, ?, ?, ?> gtv = new GiraphConfigurationValidator(giraphConf);
    gtv.validateConfiguration();

    // successfully populated/validated GiraphConfiguration, ready to run job
    return cmd;
}

From source file:org.apache.hadoop.hbase.loadtest.LoadTester.java

static CommandLine initAndParseArgs(String[] args) throws ParseException {
    // set the usage object
    USAGE = "bin/hbase org.apache.hadoop.hbase.loadtest.Tester " + "  -" + OPT_ZKNODE + " <Zookeeper node>"
            + "  -" + OPT_TABLE_NAME + " <Table name>" + "  -" + OPT_LOAD + "  -" + OPT_READ + "  -"
            + OPT_TEST_CLUSTER + "  -" + OPT_HELP + "  -" + OPT_INPUT_FILENAME;
    // add options
    options.addOption(OPT_HELP, false, "Help");
    options.addOption(OPT_ZKNODE, true, "Zookeeper node in the HBase cluster" + " (optional)");
    options.addOption(OPT_TABLE_NAME, true, "The name of the table to be read or write (optional)");
    options.addOption(OPT_INPUT_FILENAME, true, "Path to input configuration file (optional)");
    options.addOption(OPT_LOAD, false, "Command to load Data");
    options.addOption(OPT_READ, false,//from  w  w w.  j  a  v a2  s .com
            "Command to read Data assuming all" + " required data had been previously loaded to the table");
    options.addOption(OPT_LOADREAD, false, "Command to load and read Data");
    options.addOption(OPT_DELETE_TABLE, false, "Command to delete table before" + " testing it");
    options.addOption(OPT_TEST_CLUSTER, false, "Command to run a short" + " verification test on cluster."
            + " This also deletes the table if it exists before running the test");
    // parse the passed in options
    CommandLineParser parser = new BasicParser();
    CommandLine cmd = parser.parse(options, args);
    return cmd;
}

From source file:org.apache.hadoop.hbase.util.AbstractHBaseTool.java

protected CommandLine parseArgs(String[] args) throws ParseException {
    options.addOption(SHORT_HELP_OPTION, LONG_HELP_OPTION, false, "Show usage");
    addOptions();/* ww  w. j a  v a  2 s.  c om*/
    CommandLineParser parser = new BasicParser();
    return parser.parse(options, args);
}

From source file:org.apache.hadoop.hdfs.tools.DiskBalancer.java

/**
 * This function parses all command line arguments and returns the appropriate
 * values.//from   w  w w  .  j  a va2s. c o m
 *
 * @param argv - Argv from main
 * @return CommandLine
 */
private CommandLine parseArgs(String[] argv, Options opts) throws org.apache.commons.cli.ParseException {
    BasicParser parser = new BasicParser();
    return parser.parse(opts, argv);
}

From source file:org.apache.hadoop.net.PodCIDRToNodeMapping.java

public static void main(String[] args) throws ParseException {
    Options options = new Options();
    Option nameOption = new Option("n", true, "Name to resolve");
    nameOption.setRequired(true);// w  w w.j a v  a  2 s  . co  m
    options.addOption(nameOption);
    CommandLineParser parser = new BasicParser();
    CommandLine cmd = parser.parse(options, args);

    BasicConfigurator.configure();
    Logger.getRootLogger().setLevel(Level.DEBUG);
    PodCIDRToNodeMapping plugin = new PodCIDRToNodeMapping();
    Configuration conf = new Configuration();
    plugin.setConf(conf);

    String nameToResolve = cmd.getOptionValue(nameOption.getOpt());
    List<String> networkPathDirs = plugin.resolve(Lists.newArrayList(nameToResolve));
    log.info("Resolved " + nameToResolve + " to " + networkPathDirs);
}

From source file:org.apache.hms.client.Client.java

/**
 * Parse command line arguments and construct HMS command for HMS Client Executor class
 * @param args/*from  w w w .  j  av  a2 s .  c om*/
 */
public void run(String[] args) {
    BasicParser parser = new BasicParser();
    try {
        CommandLine cl = parser.parse(opt, args);
        /* Dry run */
        boolean dryRun = false;
        if (cl.hasOption("t")) {
            dryRun = true;
        }

        if (cl.hasOption("q")) {
            String cmdid = cl.getOptionValue("q");
            try {
                CommandStatus cs = queryCommandStatus(cmdid);
                if (cl.hasOption("v")) {
                    System.out.println(JAXBUtil.print(cs));
                } else {
                    System.out.println("Command ID: " + cmdid);
                    System.out.println("Status: " + cs.getStatus());
                    System.out.println("Total actions: " + cs.getTotalActions());
                    System.out.println("Completed actions: " + cs.getCompletedActions());
                }
            } catch (UniformInterfaceException e) {
                if (e.getResponse().getStatus() == Responses.NOT_FOUND) {
                    System.out.println("Command ID:" + cmdid + " does not exist.");
                } else {
                    System.out.println("Unknown error occurred, check stack trace.");
                    System.out.println(ExceptionUtil.getStackTrace(e));
                }
            }
        } else if (cl.hasOption("delete-command")) {
            // TODO: Remove command from the system
            String cmdId = cl.getOptionValue("delete-command");
            if (cmdId == null) {
                throw new RuntimeException("Command ID must be specified for Delete operation");
            }
            // System.out.println(clientRunner.sendToController(new DeleteCommand(cmdId)));        
        } else if (cl.hasOption("delete-cluster")) {
            /* delete a cluster */
            String clusterName = cl.getOptionValue("delete-cluster");
            if (clusterName == null) {
                throw new RuntimeException("cluster name must be specified for DELETE operation");
            }
            URL config = new URL(cl.getOptionValue("config-manifest"));
            if (config == null) {
                throw new RuntimeException("config manifest must be specified for DELETE operation");
            }
            try {
                Response response = deleteCluster(clusterName, config);
                showResponse(response, cl.hasOption("v"));
            } catch (Throwable e) {
                showErrors(e);
            }
        } else if (cl.hasOption("create-cluster")) {
            /* create a cluster */
            String clusterName = cl.getOptionValue("create-cluster");
            if (clusterName == null) {
                throw new RuntimeException("cluster name must be specified for CREATE operation");
            }
            URL nodes = new URL(cl.getOptionValue("nodes"));
            if (nodes == null) {
                throw new RuntimeException("nodes manifest must be specified for CREATE operation");
            }
            URL software = new URL(cl.getOptionValue("software"));
            if (software == null) {
                throw new RuntimeException("software manifest must be specified for CREATE operation");
            }
            URL config = new URL(cl.getOptionValue("config"));
            if (config == null) {
                throw new RuntimeException("config manifest must be specified for CREATE operation");
            }
            Response response = createCluster(clusterName, nodes, software, config);
            showResponse(response, cl.hasOption("v"));
        } else if (cl.hasOption("upgrade-cluster")) {
            /* upgrade a cluster */
            String clusterName = cl.getOptionValue("upgrade-cluster");
            if (clusterName == null) {
                throw new RuntimeException("cluster name must be specified for CREATE operation");
            }
            URL nodes = new URL(cl.getOptionValue("nodes"));
            if (nodes == null) {
                throw new RuntimeException("nodes manifest must be specified for CREATE operation");
            }
            URL software = new URL(cl.getOptionValue("software"));
            if (software == null) {
                throw new RuntimeException("software manifest must be specified for CREATE operation");
            }
            URL config = new URL(cl.getOptionValue("config"));
            if (config == null) {
                throw new RuntimeException("config manifest must be specified for CREATE operation");
            }
            Response response = upgradeCluster(clusterName, nodes, software, config);
            showResponse(response, cl.hasOption("v"));
        } else if (cl.hasOption("cluster-status")) {
            /* check cluster status */
            String clusterId = cl.getOptionValue("cluster-status");
            if (clusterId == null) {
                throw new RuntimeException("Cluster path must be specified for cluster-status operation");
            }
            ClusterManifest cm = clientRunner.checkClusterStatus(clusterId);
            System.out.println(JAXBUtil.print(cm));
        } else if (cl.hasOption("node-status")) {
            /* check node status */
            String nodepath = cl.getOptionValue("node-status");
            if (nodepath == null) {
                throw new RuntimeException("nodePath must be specified for nodestatus operation");
            }
            MachineState ms = clientRunner.checkNodeStatus(nodepath);
            System.out.println(JAXBUtil.print(ms));
        } else if (cl.hasOption("help")) {
            usage();
        } else {
            throw new InvalidActivityException("Invalid arguement.");
        }
    } catch (InvalidActivityException e) {
        usage();
        System.out.println("Argument Error: " + e.getMessage());
    } catch (Throwable e) {
        showErrors(e);
    }
}

From source file:org.apache.isis.core.commons.configbuilder.IsisConfigurationBuilder.java

private boolean parseAndPrimeWith(final Options options, final List<OptionHandler> optionHandlers,
        final String[] args) {
    final BootPrinter printer = new BootPrinter(getClass());
    final CommandLineParser parser = new BasicParser();
    try {/*from w  w  w.  ja v  a  2s  . c  o  m*/
        final CommandLine commandLine = parser.parse(options, args);
        for (final OptionHandler optionHandler : optionHandlers) {
            if (!optionHandler.handle(commandLine, printer, options)) {
                return false;
            }
        }
    } catch (final ParseException e) {
        printer.printErrorMessage(e.getMessage());
        printer.printHelp(options);
        return false;
    }
    return true;
}