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:net.sourceforge.jencrypt.CommandLineHelper.java

/**
 * Parse the arguments according to the specified options
 * /*ww w .  j  a  v a 2 s .com*/
 * @param args
 * @param options
 * @return
 * @throws ParseException
 */
private CommandLine parseCommandline(String[] args, Options options) throws ParseException {

    CommandLine commandLine = null;
    CommandLineParser parser = new GnuParser();

    try {
        // parse the command-line arguments
        commandLine = parser.parse(options, args);
    } catch (ParseException exp) {
        throw new ParseException("Parsing failed. Reason: " + exp.getMessage());
    }
    return commandLine;
}

From source file:calculadora.controlador.ControladorComandos.java

/**
 * Metodo que devuelve una excepcion de error de comandos.
 *
 * @return ParseException devuelve la excepcion con el mensaje pertinente
 * @throws ParseException error de comandos.
 *///from   w w  w.j  a v  a 2 s. c o  m
private ParseException errorComandos() throws ParseException {
    return new ParseException("Demasiados comandos, " + "solo se puede realizar una " + "operacion cada vez.");
}

From source file:com.somerledsolutions.pa11y.client.Application.java

private void createTask(CommandLine cl) throws ParseException {

    String accessibilityStandardValue = cl.getOptionValue(OptionsBuilder.STD_OPT);
    if (optionsValidator.validateCreateOptions(cl)
            && optionsValidator.isAccessiblityStandardValid(accessibilityStandardValue)) {
        client.createTask(cl.getOptionValue(OptionsBuilder.NAME_OPT), cl.getOptionValue(OptionsBuilder.URL_OPT),
                accessibilityStandardValue);
    } else {/*ww w  . j av  a2  s. com*/
        throw new ParseException("Accessibility standard: " + accessibilityStandardValue
                + " is not valid. Must be one of Section508, WCAG2A, WCAG2AA, WCAG2AAA");
    }
}

From source file:com.archivas.clienttools.arcmover.cli.AbstractArcCli.java

public static String getProfileNameFromCmdLineAndValidateExistance(CommandLine cmdLine, String option)
        throws ParseException {
    if (!cmdLine.hasOption(option)) {
        throw new ParseException("Missing Option: " + option);
    }// ww  w .j av  a2s. co  m

    String value = cmdLine.getOptionValue(option);
    String retval = null;
    if (value != null) {
        retval = validateProfileNameExists(value);
    }
    if (retval == null) {
        throw new ParseException("Invalid " + option + " : " + value);
    }
    return retval;
}

From source file:com.rapplogic.aru.uploader.CliOptions.java

public Integer getIntegerOption(String arg) throws ParseException {
    String value = commandLine.getOptionValue(arg, defaults.get(arg));

    try {/*w  ww .  ja va2s. c o  m*/
        return Integer.parseInt(value);
    } catch (NumberFormatException e) {
        throw new ParseException("Invalid option value for " + arg);
    }
}

From source file:com.netflix.cc.cli.CmdLineParametersParser.java

private int parseTtmlParameter(Option option, int optionIndex, String parameterName) throws ParseException {
    try {/* ww w. jav a  2 s . c  om*/
        return Integer.parseInt(option.getValue(optionIndex));
    } catch (NumberFormatException e) {
        throw new ParseException(parameterName + " in --ttml must be an integer");
    }
}

From source file:com.diablominer.DiabloMiner.DiabloMiner.java

void execute(String[] args) throws Exception {
    threads.add(Thread.currentThread());

    Options options = new Options();
    options.addOption("u", "user", true, "bitcoin host username");
    options.addOption("p", "pass", true, "bitcoin host password");
    options.addOption("o", "host", true, "bitcoin host IP");
    options.addOption("r", "port", true, "bitcoin host port");
    options.addOption("l", "url", true, "bitcoin host url");
    options.addOption("x", "proxy", true, "optional proxy settings IP:PORT<:username:password>");
    options.addOption("g", "worklifetime", true, "maximum work lifetime in seconds");
    options.addOption("d", "debug", false, "enable debug output");
    options.addOption("dt", "debugtimer", false, "run for 1 minute and quit");
    options.addOption("D", "devices", true, "devices to enable, default all");
    options.addOption("f", "fps", true, "target GPU execution timing");
    options.addOption("na", "noarray", false, "turn GPU kernel array off");
    options.addOption("v", "vectors", true, "vector size in GPU kernel");
    options.addOption("w", "worksize", true, "override GPU worksize");
    options.addOption("ds", "ksource", false, "output GPU kernel source and quit");
    options.addOption("h", "help", false, "this help");

    PosixParser parser = new PosixParser();

    CommandLine line = null;/*from  w w w  .ja  v a  2 s. c om*/

    try {
        line = parser.parse(options, args);

        if (line.hasOption("help")) {
            throw new ParseException("");
        }
    } catch (ParseException e) {
        System.out.println(e.getLocalizedMessage() + "\n");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("DiabloMiner -u myuser -p mypassword [args]\n", "", options,
                "\nRemember to set rpcuser and rpcpassword in your ~/.bitcoin/bitcoin.conf "
                        + "before starting bitcoind or bitcoin --daemon");
        return;
    }

    String splitUrl[] = null;
    String splitUser[] = null;
    String splitPass[] = null;
    String splitHost[] = null;
    String splitPort[] = null;

    if (line.hasOption("url"))
        splitUrl = line.getOptionValue("url").split(",");

    if (line.hasOption("user"))
        splitUser = line.getOptionValue("user").split(",");

    if (line.hasOption("pass"))
        splitPass = line.getOptionValue("pass").split(",");

    if (line.hasOption("host"))
        splitHost = line.getOptionValue("host").split(",");

    if (line.hasOption("port"))
        splitPort = line.getOptionValue("port").split(",");

    int networkStatesCount = 0;

    if (splitUrl != null)
        networkStatesCount = splitUrl.length;

    if (splitUser != null)
        networkStatesCount = Math.max(splitUser.length, networkStatesCount);

    if (splitPass != null)
        networkStatesCount = Math.max(splitPass.length, networkStatesCount);

    if (splitHost != null)
        networkStatesCount = Math.max(splitHost.length, networkStatesCount);

    if (splitPort != null)
        networkStatesCount = Math.max(splitPort.length, networkStatesCount);

    if (networkStatesCount == 0) {
        error("You forgot to give any bitcoin connection info, please add either -l, or -u -p -o and -r");
        System.exit(-1);
    }

    int j = 0;

    for (int i = 0; j < networkStatesCount; i++, j++) {
        String protocol = "http";
        String host = "localhost";
        int port = 8332;
        String path = "/";
        String user = "diablominer";
        String pass = "diablominer";
        byte hostChain = 0;

        if (splitUrl != null && splitUrl.length > i) {
            String[] usernameFix = splitUrl[i].split("@", 3);
            if (usernameFix.length > 2)
                splitUrl[i] = usernameFix[0] + "+++++" + usernameFix[1] + "@" + usernameFix[2];

            URL url = new URL(splitUrl[i]);

            if (url.getProtocol() != null && url.getProtocol().length() > 1)
                protocol = url.getProtocol();

            if (url.getHost() != null && url.getHost().length() > 1)
                host = url.getHost();

            if (url.getPort() != -1)
                port = url.getPort();

            if (url.getPath() != null && url.getPath().length() > 1)
                path = url.getPath();

            if (url.getUserInfo() != null && url.getUserInfo().length() > 1) {
                String[] userPassSplit = url.getUserInfo().split(":");

                user = userPassSplit[0].replace("+++++", "@");

                if (userPassSplit.length > 1 && userPassSplit[1].length() > 1)
                    pass = userPassSplit[1];
            }
        }

        if (splitUser != null && splitUser.length > i)
            user = splitUser[i];

        if (splitPass != null && splitPass.length > i)
            pass = splitPass[i];

        if (splitHost != null && splitHost.length > i)
            host = splitHost[i];

        if (splitPort != null && splitPort.length > i)
            port = Integer.parseInt(splitPort[i]);

        NetworkState networkState;

        try {
            networkState = new JSONRPCNetworkState(this, new URL(protocol, host, port, path), user, pass,
                    hostChain);
        } catch (MalformedURLException e) {
            throw new DiabloMinerFatalException(this, "Malformed connection paramaters");
        }

        if (networkStateHead == null) {
            networkStateHead = networkStateTail = networkState;
        } else {
            networkStateTail.setNetworkStateNext(networkState);
            networkStateTail = networkState;
        }
    }

    networkStateTail.setNetworkStateNext(networkStateHead);

    if (line.hasOption("proxy")) {
        final String[] proxySettings = line.getOptionValue("proxy").split(":");

        if (proxySettings.length >= 2) {
            proxy = new Proxy(Type.HTTP,
                    new InetSocketAddress(proxySettings[0], Integer.valueOf(proxySettings[1])));
        }

        if (proxySettings.length >= 3) {
            Authenticator.setDefault(new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(proxySettings[2], proxySettings[3].toCharArray());
                }
            });
        }
    }

    if (line.hasOption("worklifetime"))
        workLifetime = Integer.parseInt(line.getOptionValue("worklifetime")) * 1000;

    if (line.hasOption("debug"))
        debug = true;

    if (line.hasOption("debugtimer")) {
        debugtimer = true;
    }

    if (line.hasOption("devices")) {
        String devices[] = line.getOptionValue("devices").split(",");
        enabledDevices = new HashSet<String>();
        for (String s : devices) {
            enabledDevices.add(s);

            if (Integer.parseInt(s) == 0) {
                error("Do not use 0 with -D, devices start at 1");
                System.exit(-1);
            }
        }
    }

    if (line.hasOption("fps")) {
        GPUTargetFPS = Float.parseFloat(line.getOptionValue("fps"));

        if (GPUTargetFPS < 0.1) {
            error("--fps argument is too low, adjusting to 0.1");
            GPUTargetFPS = 0.1;
        }
    }

    if (line.hasOption("noarray")) {
        GPUNoArray = true;
    }

    if (line.hasOption("worksize"))
        GPUForceWorkSize = Integer.parseInt(line.getOptionValue("worksize"));

    if (line.hasOption("vectors")) {
        String tempVectors[] = line.getOptionValue("vectors").split(",");

        GPUVectors = new Integer[tempVectors.length];

        try {
            for (int i = 0; i < GPUVectors.length; i++) {
                GPUVectors[i] = Integer.parseInt(tempVectors[i]);

                if (GPUVectors[i] > 16) {
                    error("DiabloMiner now uses comma-seperated vector layouts, use those instead");
                    System.exit(-1);
                } else if (GPUVectors[i] != 1 && GPUVectors[i] != 2 && GPUVectors[i] != 3 && GPUVectors[i] != 4
                        && GPUVectors[i] != 8 && GPUVectors[i] != 16) {
                    error(GPUVectors[i] + " is not a vector length of 1, 2, 3, 4, 8, or 16");
                    System.exit(-1);
                }
            }

            Arrays.sort(GPUVectors, Collections.reverseOrder());
        } catch (NumberFormatException e) {
            error("Cannot parse --vector argument(s)");
            System.exit(-1);
        }
    } else {
        GPUVectors = new Integer[1];
        GPUVectors[0] = 1;
    }

    if (line.hasOption("ds"))
        GPUDebugSource = true;

    info("Started");

    StringBuilder list = new StringBuilder(networkStateHead.getQueryUrl().toString());
    NetworkState networkState = networkStateHead.getNetworkStateNext();

    while (networkState != networkStateHead) {
        list.append(", " + networkState.getQueryUrl());
        networkState = networkState.getNetworkStateNext();
    }

    info("Connecting to: " + list);

    long previousHashCount = 0;
    double previousAdjustedHashCount = 0.0;
    long previousAdjustedStartTime = startTime = (now()) - 1;
    StringBuilder hashMeter = new StringBuilder(80);
    Formatter hashMeterFormatter = new Formatter(hashMeter);

    int deviceCount = 0;

    List<List<? extends DeviceState>> allDeviceStates = new ArrayList<List<? extends DeviceState>>();

    List<? extends DeviceState> GPUDeviceStates = new GPUHardwareType(this).getDeviceStates();
    deviceCount += GPUDeviceStates.size();
    allDeviceStates.add(GPUDeviceStates);

    while (running.get()) {
        for (List<? extends DeviceState> deviceStates : allDeviceStates) {
            for (DeviceState deviceState : deviceStates) {
                deviceState.checkDevice();
            }
        }

        long now = now();
        long currentHashCount = hashCount.get();
        double adjustedHashCount = (double) (currentHashCount - previousHashCount)
                / (double) (now - previousAdjustedStartTime);
        double hashLongCount = (double) currentHashCount / (double) (now - startTime) / 1000.0;

        if (now - startTime > TIME_OFFSET * 2) {
            double averageHashCount = (adjustedHashCount + previousAdjustedHashCount) / 2.0 / 1000.0;

            hashMeter.setLength(0);

            if (!debug) {
                hashMeterFormatter.format("\rmhash: %.1f/%.1f | accept: %d | reject: %d | hw error: %d",
                        averageHashCount, hashLongCount, blocks.get(), rejects.get(), hwErrors.get());
            } else {
                hashMeterFormatter.format("\rmh: %.1f/%.1f | a/r/hwe: %d/%d/%d | gh: ", averageHashCount,
                        hashLongCount, blocks.get(), rejects.get(), hwErrors.get());

                double basisAverage = 0.0;

                for (List<? extends DeviceState> deviceStates : allDeviceStates) {
                    for (DeviceState deviceState : deviceStates) {
                        hashMeterFormatter.format("%.1f ",
                                deviceState.getDeviceHashCount() / 1000.0 / 1000.0 / 1000.0);
                        basisAverage += deviceState.getBasis();
                    }
                }

                basisAverage = 1000 / (basisAverage / deviceCount);

                hashMeterFormatter.format("| fps: %.1f", basisAverage);
            }

            System.out.print(hashMeter);
        } else {
            System.out.print("\rWaiting...");
        }

        if (now() - TIME_OFFSET * 2 > previousAdjustedStartTime) {
            previousHashCount = currentHashCount;
            previousAdjustedHashCount = adjustedHashCount;
            previousAdjustedStartTime = now - 1;
        }

        if (debugtimer && now() > startTime + 60 * 1000) {
            System.out.print("\n");
            info("Debug timer is up, quitting...");
            System.exit(0);
        }

        try {
            if (now - startTime > TIME_OFFSET)
                Thread.sleep(1000);
            else
                Thread.sleep(1);
        } catch (InterruptedException e) {
        }
    }

    hashMeterFormatter.close();
}

From source file:com.symbian.driver.plugins.ftptelnet.TelnetProcess.java

private TelnetProcess(String aTransport) throws ParseException {
    try {/*from w  ww.  j a v  a  2  s  . co m*/
        TIMEOUT_MAX = TDConfig.getInstance().getPreferenceInteger(TDConfig.TOTAL_TIMEOUT);
    } catch (ParseException lParseException) {
        //ignore we have a default value.
    }
    // check transport is valid
    iTransport = aTransport;
    if (!isTransportValid(iTransport)) {
        throw new ParseException("Transport " + iTransport + " incorrect.");
    }
    // try to connect to Telnet Server
    connectTelnet();

}

From source file:com.schatzforensic.byteplotter.Main.java

private int getInteger(CommandLine line, String parameter) throws ParseException {
    if (line.hasOption(parameter)) {
        try {//from www  .  j  ava2s. com
            return Integer.parseInt(line.getOptionValue(parameter));
        } catch (NumberFormatException e) {
            throw new ParseException(parameter);
        }
    } else {
        throw new ParseException(parameter);
    }
}

From source file:com.springrts.springls.CmdLineArgs.java

/**
 * Processes all command line arguments in 'args'.
 * Raises an exception in case of errors.
 * @return whether to exit the application after this method
 *//*from   w w w  .j a  v a 2s  . co  m*/
private static boolean apply(Configuration configuration, CommandLineParser parser, Options options,
        String[] args) throws ParseException {
    CommandLine cmd = parser.parse(options, args);

    if (cmd.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(Server.getApplicationName(), options);
        return true;
    }

    if (cmd.hasOption("port")) {
        String portStr = cmd.getOptionValue("port");
        int port = Integer.parseInt(portStr);
        if ((port < 1) || (port > 65535)) {
            throw new ParseException("Invalid port specified: " + portStr);
        }
        configuration.setProperty(ServerConfiguration.PORT, port);
    }
    if (cmd.hasOption("database")) {
        configuration.setProperty(ServerConfiguration.USE_DATABASE, true);
    } else if (cmd.hasOption("file-storage")) {
        configuration.setProperty(ServerConfiguration.USE_DATABASE, false);
    } else {
        configuration.setProperty(ServerConfiguration.LAN_MODE, true);
    }
    if (cmd.hasOption("statistics")) {
        configuration.setProperty(ServerConfiguration.STATISTICS_STORE, true);
    }
    if (cmd.hasOption("nat-port")) {
        String portStr = cmd.getOptionValue("port");
        int port = Integer.parseInt(portStr);
        if ((port < 1) || (port > 65535)) {
            throw new ParseException("Invalid NAT traversal port" + " specified: " + portStr);
        }
        configuration.setProperty(ServerConfiguration.NAT_PORT, port);
    }
    if (cmd.hasOption("log-main")) {
        configuration.setProperty(ServerConfiguration.CHANNELS_LOG_REGEX, "^main$");
    }
    if (cmd.hasOption("lan-admin")) {
        String[] usernamePassword = cmd.getOptionValues("lan-admin");

        if (usernamePassword.length < 1) {
            throw new MissingArgumentException("LAN admin user name is missing");
        }
        String username = usernamePassword[0];
        String password = (usernamePassword.length > 1) ? usernamePassword[0]
                : ServerConfiguration.getDefaults().getString(ServerConfiguration.LAN_ADMIN_PASSWORD);

        String error = Account.isOldUsernameValid(username);
        if (error != null) {
            throw new ParseException("LAN admin user name is not valid: " + error);
        }
        error = Account.isPasswordValid(password);
        if (error != null) {
            throw new ParseException("LAN admin password is not valid: " + error);
        }
        configuration.setProperty(ServerConfiguration.LAN_ADMIN_USERNAME, username);
        configuration.setProperty(ServerConfiguration.LAN_ADMIN_PASSWORD, password);
    }
    if (cmd.hasOption("load-args")) {
        File argsFile = new File(cmd.getOptionValue("load-args"));
        Reader inF = null;
        BufferedReader in = null;
        try {
            try {
                inF = new FileReader(argsFile);
                in = new BufferedReader(inF);
                String line;
                List<String> argsList = new LinkedList<String>();
                while ((line = in.readLine()) != null) {
                    String[] argsLine = line.split("[ \t]+");
                    argsList.addAll(Arrays.asList(argsLine));
                }
                String[] args2 = argsList.toArray(new String[argsList.size()]);
                apply(configuration, parser, options, args2);
            } finally {
                if (in != null) {
                    in.close();
                } else if (inF != null) {
                    inF.close();
                }
            }
        } catch (Exception ex) {
            throw new ParseException("invalid load-args argument: " + ex.getMessage());
        }
    }
    if (cmd.hasOption("spring-version")) {
        String version = cmd.getOptionValue("spring-version");
        configuration.setProperty(ServerConfiguration.ENGINE_VERSION, version);
    }

    return false;
}