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

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

Introduction

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

Prototype

public List getArgList() 

Source Link

Document

Retrieve any left-over non-recognized options and arguments

Usage

From source file:org.apache.accumulo.core.util.shell.commands.GrepCommand.java

@Override
public int execute(final String fullCommand, final CommandLine cl, final Shell shellState) throws Exception {
    final PrintFile printFile = getOutputFile(cl);

    final String tableName = OptUtil.getTableOpt(cl, shellState);

    if (cl.getArgList().isEmpty()) {
        throw new MissingArgumentException("No terms specified");
    }/*ww  w  .  j  a  v a  2  s .c  o m*/
    final Class<? extends Formatter> formatter = getFormatter(cl, tableName, shellState);
    final ScanInterpreter interpeter = getInterpreter(cl, tableName, shellState);

    // handle first argument, if present, the authorizations list to
    // scan with
    int numThreads = 20;
    if (cl.hasOption(numThreadsOpt.getOpt())) {
        numThreads = Integer.parseInt(cl.getOptionValue(numThreadsOpt.getOpt()));
    }
    final Authorizations auths = getAuths(cl, shellState);
    final BatchScanner scanner = shellState.getConnector().createBatchScanner(tableName, auths, numThreads);
    scanner.setRanges(Collections.singletonList(getRange(cl, interpeter)));

    scanner.setTimeout(getTimeout(cl), TimeUnit.MILLISECONDS);

    for (int i = 0; i < cl.getArgs().length; i++) {
        setUpIterator(Integer.MAX_VALUE - cl.getArgs().length + i, "grep" + i, cl.getArgs()[i], scanner, cl);
    }
    try {
        // handle columns
        fetchColumns(cl, scanner, interpeter);

        // output the records
        printRecords(cl, shellState, scanner, formatter, printFile);
    } finally {
        scanner.close();
    }

    return 0;
}

From source file:org.apache.accumulo.server.util.VerifyTabletAssignments.java

public static void main(String[] args) throws Exception {
    Options opts = new Options();

    Option zooKeeperInstance = new Option("z", "zooKeeperInstance", true,
            "use a zookeeper instance with the given instance name and list of zoo hosts");
    zooKeeperInstance.setArgName("name hosts");
    zooKeeperInstance.setArgs(2);/* ww w.  j  av a2  s.c  om*/
    opts.addOption(zooKeeperInstance);

    Option usernameOption = new Option("u", "user", true, "username (required)");
    usernameOption.setArgName("user");
    usernameOption.setRequired(true);
    opts.addOption(usernameOption);

    Option passwOption = new Option("p", "password", true,
            "password (prompt for password if this option is missing)");
    passwOption.setArgName("pass");
    opts.addOption(passwOption);

    Option verboseOption = new Option("v", "verbose", false, "verbose mode (prints locations of tablets)");
    opts.addOption(verboseOption);

    CommandLine cl = null;
    String user = null;
    String passw = null;
    Instance instance = null;
    ConsoleReader reader = new ConsoleReader();
    try {
        cl = new BasicParser().parse(opts, args);

        if (cl.hasOption(zooKeeperInstance.getOpt())
                && cl.getOptionValues(zooKeeperInstance.getOpt()).length != 2)
            throw new MissingArgumentException(zooKeeperInstance);

        user = cl.getOptionValue(usernameOption.getOpt());
        passw = cl.getOptionValue(passwOption.getOpt());

        if (cl.hasOption(zooKeeperInstance.getOpt())) {
            String[] zkOpts = cl.getOptionValues(zooKeeperInstance.getOpt());
            instance = new ZooKeeperInstance(zkOpts[0], zkOpts[1]);
        } else {
            instance = HdfsZooInstance.getInstance();
        }

        if (passw == null)
            passw = reader.readLine(
                    "Enter current password for '" + user + "'@'" + instance.getInstanceName() + "': ", '*');
        if (passw == null) {
            reader.printNewline();
            return;
        } // user canceled

        if (cl.getArgs().length != 0)
            throw new ParseException("Unrecognized arguments: " + cl.getArgList());

    } catch (ParseException e) {
        PrintWriter pw = new PrintWriter(System.err);
        new HelpFormatter().printHelp(pw, Integer.MAX_VALUE,
                "accumulo " + VerifyTabletAssignments.class.getName(), null, opts, 2, 5, null, true);
        pw.flush();
        System.exit(1);
    }

    Connector conn = instance.getConnector(user, passw.getBytes());

    for (String table : conn.tableOperations().list())
        checkTable(user, passw, table, null, cl.hasOption(verboseOption.getOpt()));

}

From source file:org.apache.accumulo.shell.commands.AddSplitsCommand.java

@Override
public int execute(final String fullCommand, final CommandLine cl, final Shell shellState) throws Exception {
    final String tableName = OptUtil.getTableOpt(cl, shellState);
    final boolean decode = cl.hasOption(base64Opt.getOpt());

    final TreeSet<Text> splits = new TreeSet<Text>();

    if (cl.hasOption(optSplitsFile.getOpt())) {
        splits.addAll(ShellUtil.scanFile(cl.getOptionValue(optSplitsFile.getOpt()), decode));
    } else {//  w  w  w .ja v a 2 s  .  co m
        if (cl.getArgList().isEmpty()) {
            throw new MissingArgumentException("No split points specified");
        }
        for (String s : cl.getArgs()) {
            splits.add(new Text(s.getBytes(Shell.CHARSET)));
        }
    }

    if (!shellState.getConnector().tableOperations().exists(tableName)) {
        throw new TableNotFoundException(null, tableName, null);
    }
    shellState.getConnector().tableOperations().addSplits(tableName, splits);

    return 0;
}

From source file:org.apache.accumulo.shell.commands.GrepCommand.java

@Override
public int execute(final String fullCommand, final CommandLine cl, final Shell shellState) throws Exception {
    final PrintFile printFile = getOutputFile(cl);

    final String tableName = OptUtil.getTableOpt(cl, shellState);

    if (cl.getArgList().isEmpty()) {
        throw new MissingArgumentException("No terms specified");
    }//from   w  ww .j  av a 2 s. c o  m
    final Class<? extends Formatter> formatter = getFormatter(cl, tableName, shellState);
    final ScanInterpreter interpeter = getInterpreter(cl, tableName, shellState);

    // handle first argument, if present, the authorizations list to
    // scan with
    int numThreads = 20;
    if (cl.hasOption(numThreadsOpt.getOpt())) {
        numThreads = Integer.parseInt(cl.getOptionValue(numThreadsOpt.getOpt()));
    }
    final Authorizations auths = getAuths(cl, shellState);
    final BatchScanner scanner = shellState.getConnector().createBatchScanner(tableName, auths, numThreads);
    scanner.setRanges(Collections.singletonList(getRange(cl, interpeter)));

    scanner.setTimeout(getTimeout(cl), TimeUnit.MILLISECONDS);

    setupSampling(tableName, cl, shellState, scanner);

    for (int i = 0; i < cl.getArgs().length; i++) {
        setUpIterator(Integer.MAX_VALUE - cl.getArgs().length + i, "grep" + i, cl.getArgs()[i], scanner, cl);
    }
    try {
        // handle columns
        fetchColumns(cl, scanner, interpeter);

        // output the records
        final FormatterConfig config = new FormatterConfig();
        config.setPrintTimestamps(cl.hasOption(timestampOpt.getOpt()));
        printRecords(cl, shellState, config, scanner, formatter, printFile);
    } finally {
        scanner.close();
    }

    return 0;
}

From source file:org.apache.asterix.aoya.HDFSBackup.java

public static void main(String[] args) throws ParseException, IllegalArgumentException, IOException {

    HDFSBackup back = new HDFSBackup();
    Map<String, String> envs = System.getenv();
    if (envs.containsKey("HADOOP_CONF_DIR")) {
        File hadoopConfDir = new File(envs.get("HADOOP_CONF_DIR"));
        if (hadoopConfDir.isDirectory()) {
            for (File config : hadoopConfDir.listFiles()) {
                if (config.getName().matches("^.*(xml)$")) {
                    back.conf.addResource(new Path(config.getAbsolutePath()));
                }/*from w  ww. ja va 2 s  .  c  o  m*/
            }
        }
    }
    Options opts = new Options();
    opts.addOption("restore", false, "");
    opts.addOption("backup", false, "");
    CommandLine cliParser = new GnuParser().parse(opts, args);
    if (cliParser.hasOption("restore")) {
        back.restore = true;
    }
    if (cliParser.hasOption("backup")) {
        back.backup = true;
    }
    @SuppressWarnings("unchecked")
    List<String> pairs = cliParser.getArgList();

    List<Path[]> sources = new ArrayList<Path[]>(10);
    for (String p : pairs) {
        String[] s = p.split(",");
        sources.add(new Path[] { new Path(s[0]), new Path(s[1]) });
    }

    try {
        if (back.backup) {
            back.performBackup(sources);
        }
        if (back.restore) {
            back.performRestore(sources);
        }
    } catch (IOException e) {
        LOG.fatal("Backup/restoration unsuccessful: " + e.getMessage());
        throw e;
    }
}

From source file:org.apache.batchee.cli.BatchEECLI.java

private static Runnable instantiate(final Class<? extends Runnable> cmd, final CliConfiguration configuration,
        final Map<String, Field> fields, final boolean hasArgs, final CommandLine line)
        throws InstantiationException, IllegalAccessException {
    final Runnable commandInstance = cmd.newInstance();
    if (hasArgs) { // we have few commands we can execute without args even if we have a bunch of config
        for (final Map.Entry<String, Field> option : fields.entrySet()) {
            final String key = option.getKey();
            if (key.isEmpty()) { // arguments, not an option
                final List<String> list = line.getArgList();
                if (list != null) {
                    final Field field = option.getValue();
                    final Type expectedType = field.getGenericType();
                    if (ParameterizedType.class.isInstance(expectedType)) {
                        final ParameterizedType pt = ParameterizedType.class.cast(expectedType);
                        if ((pt.getRawType() == List.class || pt.getRawType() == Collection.class)
                                && pt.getActualTypeArguments().length == 1
                                && pt.getActualTypeArguments()[0] == String.class) {
                            field.set(commandInstance, list);
                        } else {
                            throw new IllegalArgumentException("@Arguments only supports List<String>");
                        }/*from  w w w.  java2  s. co  m*/
                    } else {
                        throw new IllegalArgumentException("@Arguments only supports List<String>");
                    }
                }
            } else {
                final String value = line.getOptionValue(key);
                if (value != null) {
                    final Field field = option.getValue();
                    field.set(commandInstance, configuration.coerce(value, field.getGenericType()));
                }
            }
        }
    }
    return commandInstance;
}

From source file:org.apache.cassandra.contrib.stress.Session.java

public Session(String[] arguments) throws IllegalArgumentException {
    float STDev = 0.1f;
    CommandLineParser parser = new PosixParser();

    try {/*from w  w  w  .  ja v  a2  s  .  com*/
        CommandLine cmd = parser.parse(availableOptions, arguments);

        if (cmd.getArgs().length > 0) {
            System.err.println("Application does not allow arbitrary arguments: "
                    + StringUtils.join(cmd.getArgList(), ", "));
            System.exit(1);
        }

        if (cmd.hasOption("h"))
            throw new IllegalArgumentException("help");

        if (cmd.hasOption("n"))
            numKeys = Integer.parseInt(cmd.getOptionValue("n"));

        if (cmd.hasOption("N"))
            skipKeys = Float.parseFloat(cmd.getOptionValue("N"));

        if (cmd.hasOption("t"))
            threads = Integer.parseInt(cmd.getOptionValue("t"));

        if (cmd.hasOption("c"))
            columns = Integer.parseInt(cmd.getOptionValue("c"));

        if (cmd.hasOption("S"))
            columnSize = Integer.parseInt(cmd.getOptionValue("S"));

        if (cmd.hasOption("C"))
            cardinality = Integer.parseInt(cmd.getOptionValue("C"));

        if (cmd.hasOption("d"))
            nodes = cmd.getOptionValue("d").split(",");

        if (cmd.hasOption("D")) {
            try {
                String node = null;
                List<String> tmpNodes = new ArrayList<String>();
                BufferedReader in = new BufferedReader(
                        new InputStreamReader(new FileInputStream(cmd.getOptionValue("D"))));
                while ((node = in.readLine()) != null) {
                    if (node.length() > 0)
                        tmpNodes.add(node);
                }
                nodes = tmpNodes.toArray(new String[tmpNodes.size()]);
                in.close();
            } catch (IOException ioe) {
                throw new RuntimeException(ioe);
            }
        }

        if (cmd.hasOption("s"))
            STDev = Float.parseFloat(cmd.getOptionValue("s"));

        if (cmd.hasOption("r"))
            random = true;

        if (cmd.hasOption("f")) {
            try {
                out = new PrintStream(new FileOutputStream(cmd.getOptionValue("f")));
            } catch (FileNotFoundException e) {
                System.out.println(e.getMessage());
            }
        }

        if (cmd.hasOption("p"))
            port = Integer.parseInt(cmd.getOptionValue("p"));

        if (cmd.hasOption("m"))
            unframed = Boolean.parseBoolean(cmd.getOptionValue("m"));

        if (cmd.hasOption("o"))
            operation = Stress.Operations.valueOf(cmd.getOptionValue("o").toUpperCase());

        if (cmd.hasOption("u"))
            superColumns = Integer.parseInt(cmd.getOptionValue("u"));

        if (cmd.hasOption("y"))
            columnFamilyType = ColumnFamilyType.valueOf(cmd.getOptionValue("y"));

        if (cmd.hasOption("K")) {
            retryTimes = Integer.valueOf(cmd.getOptionValue("K"));

            if (retryTimes <= 0) {
                throw new RuntimeException("--keep-trying option value should be > 0");
            }
        }

        if (cmd.hasOption("k")) {
            retryTimes = 1;
            ignoreErrors = true;
        }

        if (cmd.hasOption("i"))
            progressInterval = Integer.parseInt(cmd.getOptionValue("i"));

        if (cmd.hasOption("g"))
            keysPerCall = Integer.parseInt(cmd.getOptionValue("g"));

        if (cmd.hasOption("l"))
            replicationFactor = Integer.parseInt(cmd.getOptionValue("l"));

        if (cmd.hasOption("e"))
            consistencyLevel = ConsistencyLevel.valueOf(cmd.getOptionValue("e").toUpperCase());

        if (cmd.hasOption("x"))
            indexType = IndexType.valueOf(cmd.getOptionValue("x").toUpperCase());

        if (cmd.hasOption("R"))
            replicationStrategy = cmd.getOptionValue("R");

        if (cmd.hasOption("O")) {
            String[] pairs = StringUtils.split(cmd.getOptionValue("O"), ',');

            for (String pair : pairs) {
                String[] keyAndValue = StringUtils.split(pair, ':');

                if (keyAndValue.length != 2)
                    throw new RuntimeException("Invalid --strategy-properties value.");

                replicationStrategyOptions.put(keyAndValue[0], keyAndValue[1]);
            }
        }

        averageSizeValues = cmd.hasOption("V");
    } catch (ParseException e) {
        throw new IllegalArgumentException(e.getMessage(), e);
    }

    mean = numKeys / 2;
    sigma = numKeys * STDev;

    operations = new AtomicInteger();
    keys = new AtomicInteger();
    latency = new AtomicLong();
}

From source file:org.apache.cassandra.staleness.Session.java

public Session(String[] arguments) throws IllegalArgumentException {
    float STDev = 0.1f;
    CommandLineParser parser = new PosixParser();

    try {//from   w  w w  .j av  a  2s.  com
        CommandLine cmd = parser.parse(availableOptions, arguments);

        if (cmd.getArgs().length > 0) {
            System.err.println("Application does not allow arbitrary arguments: "
                    + StringUtils.join(cmd.getArgList(), ", "));
            System.exit(1);
        }

        if (cmd.hasOption("h"))
            throw new IllegalArgumentException("help");

        if (cmd.hasOption("n"))
            numKeys = Integer.parseInt(cmd.getOptionValue("n"));

        if (cmd.hasOption("F"))
            numDifferentKeys = Integer.parseInt(cmd.getOptionValue("F"));
        else
            numDifferentKeys = numKeys;

        if (cmd.hasOption("N"))
            skipKeys = Float.parseFloat(cmd.getOptionValue("N"));

        if (cmd.hasOption("t"))
            threads = Integer.parseInt(cmd.getOptionValue("t"));

        if (cmd.hasOption("c"))
            columns = Integer.parseInt(cmd.getOptionValue("c"));

        if (cmd.hasOption("S"))
            columnSize = Integer.parseInt(cmd.getOptionValue("S"));

        if (cmd.hasOption("C"))
            cardinality = Integer.parseInt(cmd.getOptionValue("C"));

        //if (cmd.hasOption("d"))
        //    nodes = cmd.getOptionValue("d").split(",");

        //if (cmd.hasOption("D"))
        //{
        //    try
        //    {
        //        String node = null;
        //        List<String> tmpNodes = new ArrayList<String>();
        //        BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(cmd.getOptionValue("D"))));
        //        while ((node = in.readLine()) != null)
        //        {
        //            if (node.length() > 0)
        //                tmpNodes.add(node);
        //        }
        //        nodes = tmpNodes.toArray(new String[tmpNodes.size()]);
        //        in.close();
        //    }
        //    catch(IOException ioe)
        //    {
        //        throw new RuntimeException(ioe);
        //    }
        //}

        if (cmd.hasOption("s"))
            STDev = Float.parseFloat(cmd.getOptionValue("s"));

        if (cmd.hasOption("r"))
            random = true;

        outFileName = (cmd.hasOption("f")) ? cmd.getOptionValue("f") : null;

        if (cmd.hasOption("p"))
            port = Integer.parseInt(cmd.getOptionValue("p"));

        if (cmd.hasOption("m"))
            unframed = Boolean.parseBoolean(cmd.getOptionValue("m"));

        if (cmd.hasOption("u"))
            superColumns = Integer.parseInt(cmd.getOptionValue("u"));

        if (cmd.hasOption("y"))
            columnFamilyType = ColumnFamilyType.valueOf(cmd.getOptionValue("y"));

        if (cmd.hasOption("K")) {
            retryTimes = Integer.valueOf(cmd.getOptionValue("K"));

            if (retryTimes <= 0) {
                throw new RuntimeException("--keep-trying option value should be > 0");
            }
        }

        if (cmd.hasOption("k")) {
            retryTimes = 1;
            ignoreErrors = true;
        }

        if (cmd.hasOption("i"))
            progressInterval = Integer.parseInt(cmd.getOptionValue("i"));

        if (cmd.hasOption("g"))
            keysPerCall = Integer.parseInt(cmd.getOptionValue("g"));

        if (cmd.hasOption("e"))
            consistencyLevel = ConsistencyLevel.valueOf(cmd.getOptionValue("e").toUpperCase());

        if (cmd.hasOption("x"))
            indexType = IndexType.valueOf(cmd.getOptionValue("x").toUpperCase());

        if (cmd.hasOption("R"))
            replicationStrategy = cmd.getOptionValue("R");

        if (cmd.hasOption("l"))
            replicationStrategyOptions.put("replication_factor",
                    String.valueOf(Integer.parseInt(cmd.getOptionValue("l"))));
        else if (replicationStrategy.endsWith("SimpleStrategy"))
            replicationStrategyOptions.put("replication_factor", "1");

        if (cmd.hasOption("L"))
            enable_cql = true;

        if (cmd.hasOption("P")) {
            if (!enable_cql) {
                System.err
                        .println("-P/--use-prepared-statements is only applicable with CQL (-L/--enable-cql)");
                System.exit(-1);
            }
            use_prepared = true;
        }

        if (cmd.hasOption("O")) {
            String[] pairs = StringUtils.split(cmd.getOptionValue("O"), ',');

            for (String pair : pairs) {
                String[] keyAndValue = StringUtils.split(pair, ':');

                if (keyAndValue.length != 2)
                    throw new RuntimeException("Invalid --strategy-properties value.");

                replicationStrategyOptions.put(keyAndValue[0], keyAndValue[1]);
            }
        }

        if (cmd.hasOption("W"))
            replicateOnWrite = false;

        if (cmd.hasOption("I"))
            compression = cmd.getOptionValue("I");

        averageSizeValues = cmd.hasOption("V");

        try {
            sendToDaemon = cmd.hasOption("send-to") ? InetAddress.getByName(cmd.getOptionValue("send-to"))
                    : null;
        } catch (UnknownHostException e) {
            throw new RuntimeException(e);
        }

        if (cmd.hasOption("Q")) {
            AbstractType comparator = TypeParser.parse(DEFAULT_COMPARATOR);

            String[] names = StringUtils.split(cmd.getOptionValue("Q"), ",");
            columnNames = new ArrayList<ByteBuffer>(names.length);

            for (String columnName : names)
                columnNames.add(comparator.fromString(columnName));
        } else {
            columnNames = null;
        }

        if (cmd.hasOption("Z")) {
            compactionStrategy = cmd.getOptionValue("Z");

            try {
                // validate compaction strategy class
                CFMetaData.createCompactionStrategy(compactionStrategy);
            } catch (ConfigurationException e) {
                System.err.println(e.getMessage());
                System.exit(1);
            }
        }

        if (cmd.hasOption("U")) {
            AbstractType parsed = null;

            try {
                parsed = TypeParser.parse(cmd.getOptionValue("U"));
            } catch (ConfigurationException e) {
                System.err.println(e.getMessage());
                System.exit(1);
            }

            comparator = cmd.getOptionValue("U");
            timeUUIDComparator = parsed instanceof TimeUUIDType;

            if (!(parsed instanceof TimeUUIDType || parsed instanceof AsciiType
                    || parsed instanceof UTF8Type)) {
                System.err.println("Currently supported types are: TimeUUIDType, AsciiType, UTF8Type.");
                System.exit(1);
            }
        } else {
            comparator = null;
            timeUUIDComparator = false;
        }
    } catch (ParseException e) {
        throw new IllegalArgumentException(e.getMessage(), e);
    } catch (ConfigurationException e) {
        throw new IllegalStateException(e.getMessage(), e);
    }

    mean = numDifferentKeys / 2;
    sigma = numDifferentKeys * STDev;

    operations = new AtomicInteger();
    keys = new AtomicInteger();
    latency = new AtomicLong();
}

From source file:org.apache.cassandra.stress.Session.java

public Session(String[] arguments) throws IllegalArgumentException {
    float STDev = 0.1f;
    CommandLineParser parser = new PosixParser();

    try {/*  w  ww  .ja va 2 s.c om*/
        CommandLine cmd = parser.parse(availableOptions, arguments);

        if (cmd.getArgs().length > 0) {
            System.err.println("Application does not allow arbitrary arguments: "
                    + StringUtils.join(cmd.getArgList(), ", "));
            System.exit(1);
        }

        if (cmd.hasOption("h"))
            throw new IllegalArgumentException("help");

        if (cmd.hasOption("n"))
            numKeys = Integer.parseInt(cmd.getOptionValue("n"));

        if (cmd.hasOption("F"))
            numDifferentKeys = Integer.parseInt(cmd.getOptionValue("F"));
        else
            numDifferentKeys = numKeys;

        if (cmd.hasOption("N"))
            skipKeys = Float.parseFloat(cmd.getOptionValue("N"));

        if (cmd.hasOption("t"))
            threads = Integer.parseInt(cmd.getOptionValue("t"));

        if (cmd.hasOption("c"))
            columns = Integer.parseInt(cmd.getOptionValue("c"));

        if (cmd.hasOption("S"))
            columnSize = Integer.parseInt(cmd.getOptionValue("S"));

        if (cmd.hasOption("C"))
            cardinality = Integer.parseInt(cmd.getOptionValue("C"));

        if (cmd.hasOption("d"))
            nodes = cmd.getOptionValue("d").split(",");

        if (cmd.hasOption("D")) {
            try {
                String node = null;
                List<String> tmpNodes = new ArrayList<String>();
                BufferedReader in = new BufferedReader(
                        new InputStreamReader(new FileInputStream(cmd.getOptionValue("D"))));
                while ((node = in.readLine()) != null) {
                    if (node.length() > 0)
                        tmpNodes.add(node);
                }
                nodes = tmpNodes.toArray(new String[tmpNodes.size()]);
                in.close();
            } catch (IOException ioe) {
                throw new RuntimeException(ioe);
            }
        }

        if (cmd.hasOption("s"))
            STDev = Float.parseFloat(cmd.getOptionValue("s"));

        if (cmd.hasOption("r"))
            random = true;

        if (cmd.hasOption("f")) {
            try {
                out = new PrintStream(new FileOutputStream(cmd.getOptionValue("f")));
            } catch (FileNotFoundException e) {
                System.out.println(e.getMessage());
            }
        }

        if (cmd.hasOption("p"))
            port = Integer.parseInt(cmd.getOptionValue("p"));

        if (cmd.hasOption("m"))
            unframed = Boolean.parseBoolean(cmd.getOptionValue("m"));

        if (cmd.hasOption("o"))
            operation = Stress.Operations.valueOf(cmd.getOptionValue("o").toUpperCase());

        if (cmd.hasOption("u"))
            superColumns = Integer.parseInt(cmd.getOptionValue("u"));

        if (cmd.hasOption("y"))
            columnFamilyType = ColumnFamilyType.valueOf(cmd.getOptionValue("y"));

        if (cmd.hasOption("K")) {
            retryTimes = Integer.valueOf(cmd.getOptionValue("K"));

            if (retryTimes <= 0) {
                throw new RuntimeException("--keep-trying option value should be > 0");
            }
        }

        if (cmd.hasOption("k")) {
            retryTimes = 1;
            ignoreErrors = true;
        }

        if (cmd.hasOption("i"))
            progressInterval = Integer.parseInt(cmd.getOptionValue("i"));

        if (cmd.hasOption("g"))
            keysPerCall = Integer.parseInt(cmd.getOptionValue("g"));

        if (cmd.hasOption("e"))
            consistencyLevel = ConsistencyLevel.valueOf(cmd.getOptionValue("e").toUpperCase());

        if (cmd.hasOption("x"))
            indexType = IndexType.valueOf(cmd.getOptionValue("x").toUpperCase());

        if (cmd.hasOption("R"))
            replicationStrategy = cmd.getOptionValue("R");

        if (cmd.hasOption("l"))
            replicationStrategyOptions.put("replication_factor",
                    String.valueOf(Integer.parseInt(cmd.getOptionValue("l"))));
        else if (replicationStrategy.endsWith("SimpleStrategy"))
            replicationStrategyOptions.put("replication_factor", "1");

        if (cmd.hasOption("O")) {
            String[] pairs = StringUtils.split(cmd.getOptionValue("O"), ',');

            for (String pair : pairs) {
                String[] keyAndValue = StringUtils.split(pair, ':');

                if (keyAndValue.length != 2)
                    throw new RuntimeException("Invalid --strategy-properties value.");

                replicationStrategyOptions.put(keyAndValue[0], keyAndValue[1]);
            }
        }

        if (cmd.hasOption("W"))
            replicateOnWrite = false;

        averageSizeValues = cmd.hasOption("V");
    } catch (ParseException e) {
        throw new IllegalArgumentException(e.getMessage(), e);
    }

    mean = numDifferentKeys / 2;
    sigma = numDifferentKeys * STDev;

    operations = new AtomicInteger();
    keys = new AtomicInteger();
    latency = new AtomicLong();
}

From source file:org.apache.cassandra.stress.settings.Legacy.java

public static StressSettings build(String[] arguments) {
    CommandLineParser parser = new PosixParser();

    final Converter r = new Converter();
    try {/* w  w  w .jav  a2s.c  o  m*/
        CommandLine cmd = parser.parse(availableOptions, arguments);

        if (cmd.getArgs().length > 0) {
            System.err.println(
                    "Application does not allow arbitrary arguments: " + Arrays.asList(cmd.getArgList()));
            System.exit(1);
        }

        if (cmd.hasOption("h"))
            printHelpMessage();

        if (cmd.hasOption("C"))
            System.out.println("Ignoring deprecated option -C");

        if (cmd.hasOption("o"))
            r.setCommand(cmd.getOptionValue("o").toLowerCase());
        else
            r.setCommand("insert");

        if (cmd.hasOption("K"))
            r.add("command", "tries=" + cmd.getOptionValue("K"));

        if (cmd.hasOption("k")) {
            if (!cmd.hasOption("K"))
                r.add("command", "retry=1");
            r.add("command", "ignore_errors");
        }

        if (cmd.hasOption("g"))
            r.add("command", "at-once=" + cmd.getOptionValue("g"));

        if (cmd.hasOption("e"))
            r.add("command", "cl=" + cmd.getOptionValue("e"));

        String numKeys;
        if (cmd.hasOption("n"))
            numKeys = cmd.getOptionValue("n");
        else
            numKeys = "1000000";
        r.add("command", "n=" + numKeys);

        String uniqueKeys;
        if (cmd.hasOption("F"))
            uniqueKeys = cmd.getOptionValue("F");
        else
            uniqueKeys = numKeys;

        if (r.opts.containsKey("write") || r.opts.containsKey("counterwrite")) {
            if (!uniqueKeys.equals(numKeys))
                r.add("-key", "populate=1.." + uniqueKeys);
        } else if (cmd.hasOption("r")) {
            r.add("-key", "dist=uniform(1.." + uniqueKeys + ")");
        } else {
            if (!cmd.hasOption("s"))
                r.add("-key", "dist=gauss(1.." + uniqueKeys + ",5)");
            else
                r.add("-key", String.format("dist=gauss(1..%s,%.2f)", uniqueKeys,
                        0.5 / Float.parseFloat(cmd.getOptionValue("s"))));
        }

        String colCount;
        if (cmd.hasOption("c"))
            colCount = cmd.getOptionValue("c");
        else
            colCount = "5";

        String colSize;
        if (cmd.hasOption("S"))
            colSize = cmd.getOptionValue("S");
        else
            colSize = "34";

        r.add("-col", "n=fixed(" + colCount + ")");
        if (cmd.hasOption("V")) {
            r.add("-col", "size=uniform(1.." + Integer.parseInt(colSize) * 2 + ")");
            r.add("-col", "data=rand()");
        } else {
            r.add("-col", "size=fixed(" + colSize + ")");
            r.add("-col", "data=repeat(1)");
        }
        if (cmd.hasOption("Q"))
            r.add("-col", "names=" + cmd.getOptionValue("Q"));

        if (cmd.hasOption("U"))
            r.add("-col", "comparator=" + cmd.getOptionValue("U"));

        if (cmd.hasOption("y") && cmd.getOptionValue("y").equals("Super"))
            r.add("-col", "super=" + (cmd.hasOption("u") ? cmd.getOptionValue("u") : "1"));

        if (cmd.hasOption("t"))
            r.add("-rate", "threads=" + cmd.getOptionValue("t"));
        else
            r.add("-rate", "threads=50");

        if (cmd.hasOption("th"))
            r.add("-rate", "limit=" + cmd.getOptionValue("th") + "/s");

        if (cmd.hasOption("f"))
            r.add("-log", "file=" + cmd.getOptionValue("f"));

        if (cmd.hasOption("p"))
            r.add("-port", cmd.getOptionValue("p"));

        if (cmd.hasOption("i"))
            r.add("-log", "interval=" + cmd.getOptionValue("i"));
        else
            r.add("-log", "interval=10");

        if (cmd.hasOption("x"))
            r.add("-schema", "index=" + cmd.getOptionValue("x"));

        if (cmd.hasOption("R") || cmd.hasOption("l") || cmd.hasOption("O")) {
            StringBuilder rep = new StringBuilder();
            if (cmd.hasOption("R"))
                rep.append("strategy=").append(cmd.getOptionValue("R"));
            if (cmd.hasOption("l")) {
                if (rep.length() > 0)
                    rep.append(",");
                rep.append("factor=").append(cmd.getOptionValue("l"));
            }
            if (cmd.hasOption("O")) {
                if (rep.length() > 0)
                    rep.append(",");
                rep.append(cmd.getOptionValue("O").replace(':', '='));
            }
            r.add("-schema", "replication(" + rep + ")");
        }

        if (cmd.hasOption("L3"))
            r.add("-mode",
                    (cmd.hasOption("P") ? "prepared" : "") + (cmd.hasOption("b") ? "native" : "") + "cql3");
        else
            r.add("-mode", "thrift");

        if (cmd.hasOption("I"))
            r.add("-schema", "compression=" + cmd.getOptionValue("I"));

        if (cmd.hasOption("d"))
            r.add("-node", cmd.getOptionValue("d"));

        if (cmd.hasOption("D"))
            r.add("-node", "file=" + cmd.getOptionValue("D"));

        if (cmd.hasOption("send-to"))
            r.add("-send-to", cmd.getOptionValue("send-to"));

        if (cmd.hasOption("Z"))
            r.add("-schema", "compaction=" + cmd.getOptionValue("Z"));

        if (cmd.hasOption("ns"))
            r.add("-log", "no-summary");

        if (cmd.hasOption("tf"))
            r.add("-transport", "factory=" + cmd.getOptionValue("tf"));

        if (cmd.hasOption(SSL_TRUSTSTORE))
            r.add("-transport", "truststore=" + cmd.getOptionValue(SSL_TRUSTSTORE));

        if (cmd.hasOption(SSL_TRUSTSTORE_PW))
            r.add("-transport", "truststore-password=" + cmd.getOptionValue(SSL_TRUSTSTORE_PW));

        if (cmd.hasOption(SSL_PROTOCOL))
            r.add("-transport", "ssl-protocol=" + cmd.getOptionValue(SSL_PROTOCOL));

        if (cmd.hasOption(SSL_ALGORITHM))
            r.add("-transport", "ssl-alg=" + cmd.getOptionValue(SSL_ALGORITHM));

        if (cmd.hasOption(SSL_STORE_TYPE))
            r.add("-transport", "store-type=" + cmd.getOptionValue(SSL_STORE_TYPE));

        if (cmd.hasOption(SSL_CIPHER_SUITES))
            r.add("-transport", "ssl-ciphers=" + cmd.getOptionValue(SSL_CIPHER_SUITES));

    } catch (ParseException e) {
        printHelpMessage();
        System.exit(1);
    }

    r.printNewCommand();
    return r.get();
}