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.accumulo.server.test.functional.FunctionalTest.java

public static void main(String[] args) throws Exception {
    Parser p = new BasicParser();

    CommandLine cl = null;/*from  w  ww  . j av a2 s . c o m*/
    try {
        cl = p.parse(opts, args);
    } catch (ParseException e) {
        System.out.println("Parse Exception, exiting.");
        return;
    }

    String master = cl.getOptionValue(masterOpt.getOpt(), "localhost");
    String username = cl.getOptionValue(usernameOpt.getOpt(), "root");
    String password = cl.getOptionValue(passwordOpt.getOpt(), "secret");
    String instanceName = cl.getOptionValue(instanceNameOpt.getOpt(), "FuncTest");

    String remainingArgs[] = cl.getArgs();
    String clazz = remainingArgs[0];
    String opt = remainingArgs[1];

    Class<? extends FunctionalTest> testClass = AccumuloClassLoader.loadClass(clazz, FunctionalTest.class);
    FunctionalTest fTest = testClass.newInstance();

    fTest.setMaster(master);
    fTest.setUsername(username);
    fTest.setPassword(password);
    fTest.setInstanceName(instanceName);

    if (opt.equals("getConfig")) {
        Map<String, String> iconfig = fTest.getInitialConfig();
        System.out.println("{");
        for (Entry<String, String> entry : iconfig.entrySet()) {
            System.out.println("'" + entry.getKey() + "':'" + entry.getValue() + "',");
        }
        System.out.println("}");
    } else if (opt.equals("setup")) {
        fTest.setup();
    } else if (opt.equals("run")) {
        fTest.run();
    } else if (opt.equals("cleanup")) {
        fTest.cleanup();
    }

}

From source file:org.apache.accumulo.server.test.QueryMetadataTable.java

public static void main(String[] args)
        throws AccumuloException, AccumuloSecurityException, TableNotFoundException {
    Option usernameOpt = new Option("username", "username", true, "username");
    Option passwordOpt = new Option("password", "password", true, "password");

    Options opts = new Options();

    opts.addOption(usernameOpt);// w  ww.  j  ava2  s .co  m
    opts.addOption(passwordOpt);

    Parser p = new BasicParser();
    CommandLine cl = null;
    try {
        cl = p.parse(opts, args);
    } catch (ParseException e1) {
        System.out.println("Parse Exception, exiting.");
        return;
    }

    if (cl.getArgs().length != 2) {
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp("queryMetadataTable <numQueries> <numThreads> ", opts);
        return;
    }
    String[] rargs = cl.getArgs();

    int numQueries = Integer.parseInt(rargs[0]);
    int numThreads = Integer.parseInt(rargs[1]);
    credentials = new AuthInfo(cl.getOptionValue("username", "root"),
            ByteBuffer.wrap(cl.getOptionValue("password", "secret").getBytes()),
            HdfsZooInstance.getInstance().getInstanceID());

    Connector connector = HdfsZooInstance.getInstance().getConnector(credentials.user, credentials.password);
    Scanner scanner = connector.createScanner(Constants.METADATA_TABLE_NAME, Constants.NO_AUTHS);
    scanner.setBatchSize(20000);
    Text mdrow = new Text(KeyExtent.getMetadataEntry(new Text(Constants.METADATA_TABLE_ID), null));

    HashSet<Text> rowSet = new HashSet<Text>();

    int count = 0;

    for (Entry<Key, Value> entry : scanner) {
        System.out.print(".");
        if (count % 72 == 0) {
            System.out.printf(" %,d\n", count);
        }
        if (entry.getKey().compareRow(mdrow) == 0 && entry.getKey().getColumnFamily()
                .compareTo(Constants.METADATA_CURRENT_LOCATION_COLUMN_FAMILY) == 0) {
            System.out.println(entry.getKey() + " " + entry.getValue());
            location = entry.getValue().toString();
        }

        if (!entry.getKey().getRow().toString().startsWith(Constants.METADATA_TABLE_ID))
            rowSet.add(entry.getKey().getRow());
        count++;

    }

    System.out.printf(" %,d\n", count);

    ArrayList<Text> rows = new ArrayList<Text>(rowSet);

    Random r = new Random();

    ExecutorService tp = Executors.newFixedThreadPool(numThreads);

    long t1 = System.currentTimeMillis();

    for (int i = 0; i < numQueries; i++) {
        int index = r.nextInt(rows.size());
        MDTQuery mdtq = new MDTQuery(rows.get(index));
        tp.submit(mdtq);
    }

    tp.shutdown();

    try {
        tp.awaitTermination(1, TimeUnit.HOURS);
    } catch (InterruptedException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }

    long t2 = System.currentTimeMillis();
    double delta = (t2 - t1) / 1000.0;
    System.out.println("time : " + delta + "  queries per sec : " + (numQueries / delta));
}

From source file:org.apache.accumulo.server.test.TestIngest.java

public static IngestArgs parseArgs(String args[]) {

    Parser p = new BasicParser();
    Options opts = getOptions();/*from ww w. j a va  2 s.  com*/
    CommandLine cl;

    try {
        cl = p.parse(opts, args);
    } catch (ParseException e) {
        System.out.println("Parse Error, exiting.");
        throw new RuntimeException(e);
    }

    if (cl.getArgs().length != 3) {
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp("test_ingest <rows> <start_row> <num_columns>", getOptions());
        throw new RuntimeException();
    }

    IngestArgs ia = new IngestArgs();

    if (cl.hasOption("size")) {
        ia.dataSize = Integer.parseInt(cl.getOptionValue("size"));
    }
    if (cl.hasOption("colf")) {
        ia.columnFamily = cl.getOptionValue("colf");
    }
    if (cl.hasOption("timestamp")) {
        ia.timestamp = Long.parseLong(cl.getOptionValue("timestamp"));
        ia.hasTimestamp = true;
    }
    if (cl.hasOption("mapFile")) {
        ia.outputToMapFile = true;
        ia.outputFile = cl.getOptionValue("mapFile");
    }
    if (cl.hasOption("rfile")) {
        ia.outputToRFile = true;
        ia.outputFile = cl.getOptionValue("rfile");
    }
    if (ia.outputToMapFile && ia.outputToRFile) {
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp("Cannot output to both an rfile and a map file", getOptions());
        throw new RuntimeException();
    }
    ia.delete = cl.hasOption("delete");
    ia.useGet = cl.hasOption("useGet");
    if (cl.hasOption("random")) {
        ia.random = true;
        ia.seed = Integer.parseInt(cl.getOptionValue("random"));
    }
    if (cl.hasOption("stride")) {
        ia.stride = Integer.parseInt(cl.getOptionValue("stride"));
    }
    ia.useTsbw = cl.hasOption("tsbw");

    username = cl.getOptionValue("username", "root");
    passwd = cl.getOptionValue("password", "secret");

    String[] requiredArgs = cl.getArgs();

    ia.rows = Integer.parseInt(requiredArgs[0]);
    ia.startRow = Integer.parseInt(requiredArgs[1]);
    ia.cols = Integer.parseInt(requiredArgs[2]);

    if (cl.hasOption("trace")) {
        ia.trace = true;
    }
    return ia;
}

From source file:org.apache.accumulo.server.test.TestMultiTableIngest.java

public static void main(String[] args) throws Exception {

    Parser p = new BasicParser();
    CommandLine cl = null;/* w  w w  .j av  a2s  .c  o m*/

    try {
        cl = p.parse(opts, args);
    } catch (ParseException e) {
        throw new RuntimeException(e);
    }
    String[] rargs = cl.getArgs();
    if (rargs.length != 0) {
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp("", opts);
    }
    count = Integer.parseInt(cl.getOptionValue(countOpt.getOpt(), "10000"));
    tables = Integer.parseInt(cl.getOptionValue(tablesOpt.getOpt(), "5"));
    readOnly = cl.hasOption(readonlyOpt.getOpt());
    user = cl.getOptionValue(usernameOpt.getOpt(), "root");
    password = cl.getOptionValue(passwordOpt.getOpt(), "secret");

    // create the test table within accumulo
    Connector connector;
    try {
        connector = HdfsZooInstance.getInstance().getConnector(user, password.getBytes());
    } catch (AccumuloException e) {
        throw new RuntimeException(e);
    } catch (AccumuloSecurityException e) {
        throw new RuntimeException(e);
    }
    for (int i = 0; i < tables; i++) {
        tableNames.add(String.format("test_%04d", i));
    }

    if (!readOnly) {
        for (String table : tableNames)
            connector.tableOperations().create(table);

        MultiTableBatchWriter b;
        try {
            b = connector.createMultiTableBatchWriter(10000000, 1000000, 10);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        // populate
        for (int i = 0; i < count; i++) {
            Mutation m = new Mutation(new Text(String.format("%05d", i)));
            m.put(new Text("col" + Integer.toString((i % 3) + 1)), new Text("qual"),
                    new Value("junk".getBytes()));
            b.getBatchWriter(tableNames.get(i % tableNames.size())).addMutation(m);
        }
        try {
            b.close();
        } catch (MutationsRejectedException e) {
            throw new RuntimeException(e);
        }
    }
    try {
        readBack(connector, count);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apache.accumulo.server.test.TestRandomDeletes.java

static public void main(String[] args) {
    Option usernameOpt = new Option("username", "username", true, "username");
    Option passwordOpt = new Option("password", "password", true, "password");

    Options opts = new Options();

    opts.addOption(usernameOpt);//  www .  ja v a2 s. c  o  m
    opts.addOption(passwordOpt);

    Parser p = new BasicParser();
    CommandLine cl = null;
    try {
        cl = p.parse(opts, args);
    } catch (ParseException e1) {
        System.out.println("Parse Exception, exiting.");
        return;
    }
    credentials = new AuthInfo(cl.getOptionValue("username", "root"),
            ByteBuffer.wrap(cl.getOptionValue("password", "secret").getBytes()),
            HdfsZooInstance.getInstance().getInstanceID());

    try {
        long deleted = 0;

        Text t = new Text("test_ingest");

        TreeSet<RowColumn> doomed = scanAll(t);
        log.info("Got " + doomed.size() + " rows");

        long startTime = System.currentTimeMillis();
        while (true) {
            long half = scrambleDeleteHalfAndCheck(t, doomed);
            deleted += half;
            if (half == 0)
                break;
        }
        long stopTime = System.currentTimeMillis();

        long elapsed = (stopTime - startTime) / 1000;
        log.info("deleted " + deleted + " values in " + elapsed + " seconds");
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

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

public static void main(String[] args) {
    boolean everything;

    CommandLine cl = null;//from w w w.j  a  va2 s  .c  om
    Options opts = new Options();
    opts.addOption("u", true, "optional administrator user name");
    opts.addOption("p", true, "optional administrator password");
    opts.addOption("f", "force", false, "force the given server to stop by removing its lock");
    opts.addOption("?", "help", false, "displays the help");
    String user = null;
    byte[] pass = null;
    boolean force = false;

    try {
        cl = new BasicParser().parse(opts, args);
        if (cl.hasOption("?"))
            throw new ParseException("help requested");
        args = cl.getArgs();

        user = cl.hasOption("u") ? cl.getOptionValue("u") : "root";
        pass = cl.hasOption("p") ? cl.getOptionValue("p").getBytes() : null;
        force = cl.hasOption("f");

        if (!((cl.getArgs().length == 1
                && (args[0].equalsIgnoreCase("stopMaster") || args[0].equalsIgnoreCase("stopAll")))
                || (cl.getArgs().length == 2 && args[0].equalsIgnoreCase("stop"))))
            throw new ParseException("Incorrect arguments");

    } catch (ParseException e) {
        // print to the log and to stderr
        if (cl == null || !cl.hasOption("?"))
            log.error(e, e);
        HelpFormatter h = new HelpFormatter();
        StringWriter str = new StringWriter();
        h.printHelp(new PrintWriter(str), h.getWidth(),
                Admin.class.getName() + " stopMaster | stopAll | stop <tserver>", null, opts,
                h.getLeftPadding(), h.getDescPadding(), null, true);
        if (cl != null && cl.hasOption("?"))
            log.info(str.toString());
        else
            log.error(str.toString());
        h.printHelp(new PrintWriter(System.err), h.getWidth(),
                Admin.class.getName() + " stopMaster | stopAll | stop <tserver>", null, opts,
                h.getLeftPadding(), h.getDescPadding(), null, true);
        System.exit(3);
    }

    try {
        AuthInfo creds;
        if (args[0].equalsIgnoreCase("stop")) {
            stopTabletServer(args[1], force);
        } else {
            if (!cl.hasOption("u") && !cl.hasOption("p")) {
                creds = SecurityConstants.getSystemCredentials();
            } else {
                if (pass == null) {
                    try {
                        pass = new ConsoleReader().readLine("Enter current password for '" + user + "': ", '*')
                                .getBytes();
                    } catch (IOException ioe) {
                        log.error("Password not specified and unable to prompt: " + ioe);
                        System.exit(4);
                    }
                }
                creds = new AuthInfo(user, ByteBuffer.wrap(pass),
                        HdfsZooInstance.getInstance().getInstanceID());
            }

            everything = args[0].equalsIgnoreCase("stopAll");
            stopServer(creds, everything);
        }
    } catch (AccumuloException e) {
        log.error(e);
        System.exit(1);
    } catch (AccumuloSecurityException e) {
        log.error(e);
        System.exit(2);
    }
}

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);/*from   ww w .  jav  a  2  s. c o m*/
    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.ShellPluginConfigurationCommand.java

public static <T> Class<? extends T> getPluginClass(final String tableName, final Shell shellState,
        final Class<T> clazz, final Property pluginProp) {
    Iterator<Entry<String, String>> props;
    try {/* w  ww  . ja  v  a  2  s .co m*/
        props = shellState.getConnector().tableOperations().getProperties(tableName).iterator();
    } catch (AccumuloException e) {
        return null;
    } catch (TableNotFoundException e) {
        return null;
    }

    while (props.hasNext()) {
        final Entry<String, String> ent = props.next();
        if (ent.getKey().equals(pluginProp.toString())) {
            Class<? extends T> pluginClazz;
            String[] args = new String[2];
            try {
                Options o = new Options();
                o.addOption(OptUtil.tableOpt());
                args[0] = "-t";
                args[1] = tableName;
                CommandLine cl = new BasicParser().parse(o, args);
                pluginClazz = shellState.getClassLoader(cl, shellState).loadClass(ent.getValue())
                        .asSubclass(clazz);
            } catch (ClassNotFoundException e) {
                LoggerFactory.getLogger(ShellPluginConfigurationCommand.class).error("Class not found {}",
                        e.getMessage());
                return null;
            } catch (ParseException e) {
                LoggerFactory.getLogger(ShellPluginConfigurationCommand.class)
                        .error("Error parsing table: {} {}", Arrays.toString(args), e.getMessage());
                return null;
            } catch (TableNotFoundException e) {
                LoggerFactory.getLogger(ShellPluginConfigurationCommand.class).error("Table not found: {} {}",
                        tableName, e.getMessage());
                return null;
            } catch (Exception e) {
                LoggerFactory.getLogger(ShellPluginConfigurationCommand.class).error("Error: {}",
                        e.getMessage());
                return null;
            }

            return pluginClazz;
        }
    }

    return null;
}

From source file:org.apache.accumulo.shell.Shell.java

public void execCommand(String input, boolean ignoreAuthTimeout, boolean echoPrompt) throws IOException {
    audit.log(Level.INFO, getDefaultPrompt() + input);
    if (echoPrompt) {
        reader.print(getDefaultPrompt());
        reader.println(input);//from   w  w w  .j  a  v  a 2 s .  c  o m
    }

    if (input.startsWith(COMMENT_PREFIX)) {
        return;
    }

    String fields[];
    try {
        fields = new QuotedStringTokenizer(input).getTokens();
    } catch (BadArgumentException e) {
        printException(e);
        ++exitCode;
        return;
    }
    if (fields.length == 0)
        return;

    String command = fields[0];
    fields = fields.length > 1 ? Arrays.copyOfRange(fields, 1, fields.length) : new String[] {};

    Command sc = null;
    if (command.length() > 0) {
        try {
            // Obtain the command from the command table
            sc = commandFactory.get(command);
            if (sc == null) {
                reader.println(String.format(
                        "Unknown command \"%s\".  Enter \"help\" for a list possible commands.", command));
                reader.flush();
                return;
            }

            long duration = System.nanoTime() - lastUserActivity;
            if (!(sc instanceof ExitCommand) && !ignoreAuthTimeout
                    && (duration < 0 || duration > authTimeout)) {
                reader.println("Shell has been idle for too long. Please re-authenticate.");
                boolean authFailed = true;
                do {
                    String pwd = readMaskedLine("Enter current password for '" + connector.whoami() + "': ",
                            '*');
                    if (pwd == null) {
                        reader.println();
                        return;
                    } // user canceled

                    try {
                        authFailed = !connector.securityOperations().authenticateUser(connector.whoami(),
                                new PasswordToken(pwd));
                    } catch (Exception e) {
                        ++exitCode;
                        printException(e);
                    }

                    if (authFailed)
                        reader.print("Invalid password. ");
                } while (authFailed);
                lastUserActivity = System.nanoTime();
            }

            // Get the options from the command on how to parse the string
            Options parseOpts = sc.getOptionsWithHelp();

            // Parse the string using the given options
            CommandLine cl = new BasicParser().parse(parseOpts, fields);

            int actualArgLen = cl.getArgs().length;
            int expectedArgLen = sc.numArgs();
            if (cl.hasOption(helpOption)) {
                // Display help if asked to; otherwise execute the command
                sc.printHelp(this);
            } else if (expectedArgLen != NO_FIXED_ARG_LENGTH_CHECK && actualArgLen != expectedArgLen) {
                ++exitCode;
                // Check for valid number of fixed arguments (if not
                // negative; negative means it is not checked, for
                // vararg-like commands)
                printException(new IllegalArgumentException(String.format(
                        "Expected %d argument%s. There %s %d.", expectedArgLen, expectedArgLen == 1 ? "" : "s",
                        actualArgLen == 1 ? "was" : "were", actualArgLen)));
                sc.printHelp(this);
            } else {
                int tmpCode = sc.execute(input, cl, this);
                exitCode += tmpCode;
                reader.flush();
            }

        } catch (ConstraintViolationException e) {
            ++exitCode;
            printConstraintViolationException(e);
        } catch (TableNotFoundException e) {
            ++exitCode;
            if (getTableName().equals(e.getTableName()))
                setTableName("");
            printException(e);
        } catch (ParseException e) {
            // not really an error if the exception is a missing required
            // option when the user is asking for help
            if (!(e instanceof MissingOptionException && (Arrays.asList(fields).contains("-" + helpOption)
                    || Arrays.asList(fields).contains("--" + helpLongOption)))) {
                ++exitCode;
                printException(e);
            }
            if (sc != null)
                sc.printHelp(this);
        } catch (UserInterruptException e) {
            ++exitCode;
        } catch (Exception e) {
            ++exitCode;
            printException(e);
        }
    } else {
        ++exitCode;
        printException(new BadArgumentException("Unrecognized empty command", command, -1));
    }
    reader.flush();
}

From source file:org.apache.ace.agent.launcher.Launcher.java

public Map<String, String> parseArgs(String... args) throws Exception {
    Options options = new Options();
    addOption(options, 'a', "agent", "ID", "the agent ID to use");
    addOption(options, 's', "serverurl", "URLs", "the Apache ACE server URL(s) to use");
    addOption(options, 'v', "verbose", "enable verbose logging");
    addOption(options, 'c', "config", "FILE", "use configuration file");
    addOption(options, 'h', "help", "prints this message");

    // Start from scratch...
    Map<String, String> config = new HashMap<>();

    CommandLineParser parser = new BasicParser();
    CommandLine command = parser.parse(options, args, false /* stopAtNonOption */);

    if (command.hasOption("h")) {
        printHelp(options);//  w  w  w .  j  ava  2  s.c  o m
        System.exit(0);
    }

    // first map all default properties
    propagateConfiguration(loadDefaultProperties(), config);

    // overwrite with user properties
    if (command.hasOption("c")) {
        propagateConfiguration(loadUserProperties(command.getOptionValue("c")), config);
    }

    // add all non-recognized command line options...
    propagateConfiguration(command.getArgs(), config);

    // convenience debug override...
    if (command.hasOption("v")) {
        config.put("verbose", "true");
        config.put(AgentConstants.CONFIG_LOGGING_LEVEL, "DEBUG");
    }

    // handle overrides...
    if (command.hasOption("s")) {
        config.put(AgentConstants.CONFIG_DISCOVERY_SERVERURLS, command.getOptionValue("s"));
    }
    if (command.hasOption("a")) {
        config.put(AgentConstants.CONFIG_IDENTIFICATION_AGENTID, command.getOptionValue("a"));
    }

    return (m_configuration = config);
}