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

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

Introduction

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

Prototype

public ParseException(String message) 

Source Link

Document

Construct a new ParseException with the specified detail message.

Usage

From source file:org.apache.accumulo.examples.simple.client.ReadWriteExample.java

private void configure(String[] args) throws ParseException, AccumuloException, AccumuloSecurityException {
    usernameOpt.setRequired(true);// w  ww  .  ja v a2s. co m
    passwordOpt.setRequired(true);
    opts = new Options();
    addOptions(instanceOpt, zooKeepersOpt, usernameOpt, passwordOpt, scanAuthsOpt, tableNameOpt, createtableOpt,
            deletetableOpt, createEntriesOpt, deleteEntriesOpt, readEntriesOpt, debugOpt);

    // parse command line
    cl = new BasicParser().parse(opts, args);
    if (cl.getArgs().length != 0)
        throw new ParseException("unrecognized options " + cl.getArgList());

    // optionally enable debugging
    if (hasOpt(debugOpt))
        Logger.getLogger(Constants.CORE_PACKAGE_NAME).setLevel(Level.TRACE);

    Instance inst = new ZooKeeperInstance(getOpt(instanceOpt, DEFAULT_INSTANCE_NAME),
            getOpt(zooKeepersOpt, DEFAULT_ZOOKEEPERS));
    conn = inst.getConnector(getRequiredOpt(usernameOpt), getRequiredOpt(passwordOpt).getBytes());
}

From source file:org.apache.accumulo.server.gc.SimpleGarbageCollector.java

public SimpleGarbageCollector(String[] args) throws UnknownHostException {
    Options opts = new Options();
    optVerboseMode = new Option("v", "verbose", false, "extra information will get printed to stdout also");
    optSafeMode = new Option("s", "safemode", false, "safe mode will not delete files");
    optOffline = new Option("o", "offline", false,
            "offline mode will run once and check data files directly; this is dangerous if accumulo is running or not shut down properly");
    optAddress = new Option("a", "address", true, "specify our local address");
    opts.addOption(optVerboseMode);/*w  w w  .j a  v a2 s  .  c o  m*/
    opts.addOption(optSafeMode);
    opts.addOption(optOffline);
    opts.addOption(optAddress);

    try {
        commandLine = new BasicParser().parse(opts, args);
        if (commandLine.getArgs().length != 0)
            throw new ParseException("Extraneous arguments");

        safemode = commandLine.hasOption(optSafeMode.getOpt());
        offline = commandLine.hasOption(optOffline.getOpt());
        verbose = commandLine.hasOption(optVerboseMode.getOpt());
        address = commandLine.getOptionValue(optAddress.getOpt());
    } catch (ParseException e) {
        String str = "Can't parse the command line options";
        log.fatal(str, e);
        throw new IllegalArgumentException(str, e);
    }
}

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

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

    CommandLine cl = null;// w  w w  .  j  a v  a  2 s  . co m
    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   www  . 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.FateCommand.java

@Override
public int execute(final String fullCommand, final CommandLine cl, final Shell shellState)
        throws ParseException, KeeperException, InterruptedException, IOException {
    Instance instance = shellState.getInstance();
    String[] args = cl.getArgs();
    if (args.length <= 0) {
        throw new ParseException("Must provide a command to execute");
    }//www  .  j  ava 2  s. com
    String cmd = args[0];
    boolean failedCommand = false;

    AdminUtil<FateCommand> admin = new AdminUtil<FateCommand>(false);

    String path = ZooUtil.getRoot(instance) + Constants.ZFATE;
    String masterPath = ZooUtil.getRoot(instance) + Constants.ZMASTER_LOCK;
    IZooReaderWriter zk = getZooReaderWriter(shellState.getInstance(),
            cl.getOptionValue(secretOption.getOpt()));
    ZooStore<FateCommand> zs = new ZooStore<FateCommand>(path, zk);

    if ("fail".equals(cmd)) {
        if (args.length <= 1) {
            throw new ParseException("Must provide transaction ID");
        }
        for (int i = 1; i < args.length; i++) {
            if (!admin.prepFail(zs, zk, masterPath, args[i])) {
                System.out.printf("Could not fail transaction: %s%n", args[i]);
                failedCommand = true;
            }
        }
    } else if ("delete".equals(cmd)) {
        if (args.length <= 1) {
            throw new ParseException("Must provide transaction ID");
        }
        for (int i = 1; i < args.length; i++) {
            if (admin.prepDelete(zs, zk, masterPath, args[i])) {
                admin.deleteLocks(zs, zk, ZooUtil.getRoot(instance) + Constants.ZTABLE_LOCKS, args[i]);
            } else {
                System.out.printf("Could not delete transaction: %s%n", args[i]);
                failedCommand = true;
            }
        }
    } else if ("list".equals(cmd) || "print".equals(cmd)) {
        // Parse transaction ID filters for print display
        Set<Long> filterTxid = null;
        if (args.length >= 2) {
            filterTxid = new HashSet<Long>(args.length);
            for (int i = 1; i < args.length; i++) {
                try {
                    Long val = Long.parseLong(args[i], 16);
                    filterTxid.add(val);
                } catch (NumberFormatException nfe) {
                    // Failed to parse, will exit instead of displaying everything since the intention was to potentially filter some data
                    System.out.printf("Invalid transaction ID format: %s%n", args[i]);
                    return 1;
                }
            }
        }

        // Parse TStatus filters for print display
        EnumSet<TStatus> filterStatus = null;
        if (cl.hasOption(statusOption.getOpt())) {
            filterStatus = EnumSet.noneOf(TStatus.class);
            String[] tstat = cl.getOptionValues(statusOption.getOpt());
            for (int i = 0; i < tstat.length; i++) {
                try {
                    filterStatus.add(TStatus.valueOf(tstat[i]));
                } catch (IllegalArgumentException iae) {
                    System.out.printf("Invalid transaction status name: %s%n", tstat[i]);
                    return 1;
                }
            }
        }

        StringBuilder buf = new StringBuilder(8096);
        Formatter fmt = new Formatter(buf);
        admin.print(zs, zk, ZooUtil.getRoot(instance) + Constants.ZTABLE_LOCKS, fmt, filterTxid, filterStatus);
        shellState.printLines(Collections.singletonList(buf.toString()).iterator(),
                !cl.hasOption(disablePaginationOpt.getOpt()));
    } else if ("dump".equals(cmd)) {
        List<Long> txids;

        if (args.length == 1) {
            txids = zs.list();
        } else {
            txids = new ArrayList<>();
            for (int i = 1; i < args.length; i++) {
                txids.add(Long.parseLong(args[i], 16));
            }
        }

        Gson gson = new GsonBuilder().registerTypeAdapter(ReadOnlyRepo.class, new InterfaceSerializer<>())
                .registerTypeAdapter(Repo.class, new InterfaceSerializer<>())
                .registerTypeAdapter(byte[].class, new ByteArraySerializer()).setPrettyPrinting().create();

        List<FateStack> txStacks = new ArrayList<>();

        for (Long txid : txids) {
            List<ReadOnlyRepo<FateCommand>> repoStack = zs.getStack(txid);
            txStacks.add(new FateStack(txid, repoStack));
        }

        System.out.println(gson.toJson(txStacks));
    } else {
        throw new ParseException("Invalid command option");
    }

    return failedCommand ? 1 : 0;
}

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

/**
 * Cursory sanity checks for argument sanity, without considering the mode of the client
 *
 * @param args//from  ww  w. ja  v a2 s . co  m
 * @param cliParser
 *            The parsed arguments.
 * @throws ParseException
 */
private void checkConfSanity(String[] args, CommandLine cliParser) throws ParseException {
    String message = null;

    //Sanity check for no args
    if (args.length == 0) {
        message = "No args specified for client to initialize";
    }
    //AM memory should be a sane value
    else if (amMemory < 0) {
        message = "Invalid memory specified for application master, exiting." + " Specified memory=" + amMemory;
    }
    //we're good!
    else {
        return;
    }
    //default:
    throw new ParseException(message);

}

From source file:org.apache.cassandra.tools.ClusterCmd.java

/**
 * Creates a ClusterProbe using command-line arguments.
 *
 * @param cmdArgs list of arguments passed on the command line
 * @throws ParseException for missing required, or unrecognized options
 * @throws IOException on connection failures
 *///from www . j  a  v a  2  s  .co m
private ClusterCmd(String[] cmdArgs) throws ParseException, IOException, InterruptedException {
    parseArgs(cmdArgs);
    this.host = cmd.getOptionValue(HOST_OPT_SHORT);

    String portNum = cmd.getOptionValue(PORT_OPT_SHORT);
    if (portNum != null) {
        try {
            this.port = Integer.parseInt(portNum);
        } catch (NumberFormatException e) {
            throw new ParseException("Port must be a number");
        }
    } else {
        this.port = defaultPort;
    }

    probe = new NodeProbe(host, port);
}

From source file:org.apache.cassandra.tools.NodeCmd.java

public static void main(String[] args)
        throws IOException, InterruptedException, ConfigurationException, ParseException {
    CommandLineParser parser = new PosixParser();
    ToolCommandLine cmd = null;//from   w  w  w .ja  v  a2s  .c  om

    try {
        cmd = new ToolCommandLine(parser.parse(options, args));
    } catch (ParseException p) {
        badUse(p.getMessage());
    }

    String host = cmd.getOptionValue(HOST_OPT.left);
    int port = DEFAULT_PORT;

    String portNum = cmd.getOptionValue(PORT_OPT.left);
    if (portNum != null) {
        try {
            port = Integer.parseInt(portNum);
        } catch (NumberFormatException e) {
            throw new ParseException("Port must be a number");
        }
    }

    String username = cmd.getOptionValue(USERNAME_OPT.left);
    String password = cmd.getOptionValue(PASSWORD_OPT.left);

    NodeProbe probe = null;
    try {
        probe = username == null ? new NodeProbe(host, port) : new NodeProbe(host, port, username, password);
    } catch (IOException ioe) {
        err(ioe, "Error connection to remote JMX agent!");
    }

    NodeCommand command = null;

    try {
        command = cmd.getCommand();
    } catch (IllegalArgumentException e) {
        badUse(e.getMessage());
    }

    NodeCmd nodeCmd = new NodeCmd(probe);

    // Execute the requested command.
    String[] arguments = cmd.getCommandArguments();

    switch (command) {
    case RING:
        nodeCmd.printRing(System.out);
        break;
    case INFO:
        nodeCmd.printInfo(System.out);
        break;
    case CFSTATS:
        nodeCmd.printColumnFamilyStats(System.out);
        break;
    case DECOMMISSION:
        probe.decommission();
        break;
    case TPSTATS:
        nodeCmd.printThreadPoolStats(System.out);
        break;
    case VERSION:
        nodeCmd.printReleaseVersion(System.out);
        break;
    case COMPACTIONSTATS:
        nodeCmd.printCompactionStats(System.out);
        break;
    case DISABLEGOSSIP:
        probe.stopGossiping();
        break;
    case ENABLEGOSSIP:
        probe.startGossiping();
        break;
    case DISABLETHRIFT:
        probe.stopThriftServer();
        break;
    case ENABLETHRIFT:
        probe.startThriftServer();
        break;

    case DRAIN:
        try {
            probe.drain();
        } catch (ExecutionException ee) {
            err(ee, "Error occured during flushing");
        }
        break;

    case NETSTATS:
        if (arguments.length > 0) {
            nodeCmd.printNetworkStats(InetAddress.getByName(arguments[0]), System.out);
        } else {
            nodeCmd.printNetworkStats(null, System.out);
        }
        break;

    case SNAPSHOT:
    case CLEARSNAPSHOT:
        String tag = cmd.getOptionValue(TAG_OPT.left);
        handleSnapshots(command, tag, arguments, probe);
        break;

    case MOVE:
        if (arguments.length != 1) {
            badUse("Missing token argument for move.");
        }
        probe.move(arguments[0]);
        break;

    case JOIN:
        if (probe.isJoined()) {
            System.err.println("This node has already joined the ring.");
            System.exit(1);
        }

        probe.joinRing();
        break;

    case SETCOMPACTIONTHROUGHPUT:
        if (arguments.length != 1) {
            badUse("Missing value argument.");
        }
        probe.setCompactionThroughput(Integer.valueOf(arguments[0]));
        break;

    case REMOVETOKEN:
        if (arguments.length != 1) {
            badUse("Missing an argument for removetoken (either status, force, or a token)");
        } else if (arguments[0].equals("status")) {
            nodeCmd.printRemovalStatus(System.out);
        } else if (arguments[0].equals("force")) {
            nodeCmd.printRemovalStatus(System.out);
            probe.forceRemoveCompletion();
        } else {
            probe.removeToken(arguments[0]);
        }
        break;

    case CLEANUP:
    case COMPACT:
    case REPAIR:
    case FLUSH:
    case SCRUB:
    case INVALIDATEKEYCACHE:
    case INVALIDATEROWCACHE:
        optionalKSandCFs(command, arguments, probe);
        break;

    case GETCOMPACTIONTHRESHOLD:
        if (arguments.length != 2) {
            badUse("getcompactionthreshold requires ks and cf args.");
        }
        probe.getCompactionThreshold(System.out, arguments[0], arguments[1]);
        break;

    case CFHISTOGRAMS:
        if (arguments.length != 2) {
            badUse("cfhistograms requires ks and cf args");
        }
        nodeCmd.printCfHistograms(arguments[0], arguments[1], System.out);
        break;

    case SETCACHECAPACITY:
        if (arguments.length != 4) {
            badUse("setcachecapacity requires ks, cf, keycachecap, and rowcachecap args.");
        }
        probe.setCacheCapacities(arguments[0], arguments[1], Integer.parseInt(arguments[2]),
                Integer.parseInt(arguments[3]));
        break;

    case SETCOMPACTIONTHRESHOLD:
        if (arguments.length != 4) {
            badUse("setcompactionthreshold requires ks, cf, min, and max threshold args.");
        }
        int minthreshold = Integer.parseInt(arguments[2]);
        int maxthreshold = Integer.parseInt(arguments[3]);
        if ((minthreshold < 0) || (maxthreshold < 0)) {
            badUse("Thresholds must be positive integers");
        }
        if (minthreshold > maxthreshold) {
            badUse("Min threshold cannot be greater than max.");
        }
        if (minthreshold < 2 && maxthreshold != 0) {
            badUse("Min threshold must be at least 2");
        }
        probe.setCompactionThreshold(arguments[0], arguments[1], minthreshold, maxthreshold);
        break;

    default:
        throw new RuntimeException("Unreachable code.");

    }

    System.exit(0);
}

From source file:org.apache.eagle.common.config.ConfigOptionParser.java

protected Map<String, String> parseCommand(CommandLine cmd) throws ParseException {
    Map<String, String> result = new HashMap<>();
    if (cmd.hasOption(CONFIG_OPT_FLAG)) {
        String[] values = cmd.getOptionValues(CONFIG_OPT_FLAG);
        for (String value : values) {
            int eqIndex = value.indexOf("=");
            if (eqIndex > 0 && eqIndex < value.length()) {
                String k = value.substring(0, eqIndex);
                String v = value.substring(eqIndex + 1, value.length());
                if (result.containsKey(k)) {
                    throw new ParseException("Duplicated " + CONFIG_OPT_FLAG + " " + value);
                } else {
                    result.put(k, v);/*from ww w.  ja v a  2  s.com*/
                }
            } else {
                throw new ParseException("Invalid format: -" + CONFIG_OPT_FLAG + " " + value + ", required: -"
                        + CONFIG_OPT_FLAG + " key=value");
            }
        }
    }
    return result;
}

From source file:org.apache.falcon.cli.CLIParser.java

/**
 * Parse a array of arguments into a command.
 *
 * @param args array of arguments.// w w  w  .j av a 2  s.c  o m
 * @return the parsed Command.
 * @throws ParseException thrown if the arguments could not be parsed.
 */
public Command parse(String[] args) throws ParseException {
    if (args.length == 0) {
        throw new ParseException("missing sub-command");
    } else {
        if (commands.containsKey(args[0])) {
            GnuParser parser = new GnuParser();
            String[] minusCommand = new String[args.length - 1];
            System.arraycopy(args, 1, minusCommand, 0, minusCommand.length);
            return new Command(args[0],
                    parser.parse(commands.get(args[0]), minusCommand, commandWithArgs.get(args[0])));
        } else {
            throw new ParseException(MessageFormat.format("invalid sub-command [{0}]", args[0]));
        }
    }
}