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.sentry.cli.tools.SentryShellCommon.java

protected void checkRequiredParameter(boolean isRequired, String paramValue, String paramName)
        throws ParseException {
    if (isRequired && StringUtils.isEmpty(paramValue)) {
        throw new ParseException(PREFIX_MESSAGE_MISSING_OPTION + paramName);
    }/* www .  j av  a  2 s.co m*/
}

From source file:org.apache.sentry.provider.db.tools.SentryShellCommon.java

private void checkRequiredParameter(boolean isRequired, String paramValue, String paramName)
        throws ParseException {
    if (isRequired && StringUtils.isEmpty(paramValue)) {
        throw new ParseException(PREFIX_MESSAGE_MISSING_OPTION + paramName);
    }/*from w  w w  .ja v a2s. co  m*/
}

From source file:org.apache.sqoop.tool.SqoopTool.java

/**
 * Configures a SqoopOptions according to the specified arguments.
 * Reads a set of arguments and uses them to configure a SqoopOptions
 * and its embedded configuration (i.e., through GenericOptionsParser.)
 * Stores any unparsed arguments in the extraArguments field.
 *
 * @param args the arguments to parse./*from  w w w  .  j  av a 2 s  . co m*/
 * @param conf if non-null, set as the configuration for the returned
 * SqoopOptions.
 * @param in a (perhaps partially-configured) SqoopOptions. If null,
 * then a new SqoopOptions will be used. If this has a null configuration
 * and conf is null, then a new Configuration will be inserted in this.
 * @param useGenericOptions if true, will also parse generic Hadoop
 * options into the Configuration.
 * @return a SqoopOptions that is fully configured by a given tool.
 */
public SqoopOptions parseArguments(String[] args, Configuration conf, SqoopOptions in,
        boolean useGenericOptions) throws ParseException, SqoopOptions.InvalidOptionsException {
    SqoopOptions out = in;

    if (null == out) {
        out = new SqoopOptions();
    }

    if (null != conf) {
        // User specified a configuration; use it and override any conf
        // that may have been in the SqoopOptions.
        out.setConf(conf);
    } else if (null == out.getConf()) {
        // User did not specify a configuration, but neither did the
        // SqoopOptions. Fabricate a new one.
        out.setConf(new Configuration());
    }

    // This tool is the "active" tool; bind it in the SqoopOptions.
    //TODO(jarcec): Remove the cast when SqoopOptions will be moved
    //              to apache package
    out.setActiveSqoopTool((com.cloudera.sqoop.tool.SqoopTool) this);

    String[] toolArgs = args; // args after generic parser is done.
    if (useGenericOptions) {
        try {
            toolArgs = ConfigurationHelper.parseGenericOptions(out.getConf(), args);
        } catch (IOException ioe) {
            ParseException pe = new ParseException("Could not parse generic arguments");
            pe.initCause(ioe);
            throw pe;
        }
    }

    // Parse tool-specific arguments.
    ToolOptions toolOptions = new ToolOptions();
    configureOptions(toolOptions);
    CommandLineParser parser = new SqoopParser();
    CommandLine cmdLine = parser.parse(toolOptions.merge(), toolArgs, true);
    applyOptions(cmdLine, out);
    this.extraArguments = cmdLine.getArgs();
    return out;
}

From source file:org.apache.storm.loadgen.GenLoad.java

/**
 * Main entry point for GenLoad application.
 * @param args the command line args./*from   w w  w  .java2  s  .com*/
 * @throws Exception on any error.
 */
public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption(Option.builder("h").longOpt("help").desc("Print a help message").build());
    options.addOption(Option.builder("t").longOpt("test-time").argName("MINS").hasArg()
            .desc("How long to run the tests for in mins (defaults to " + TEST_EXECUTE_TIME_DEFAULT + ")")
            .build());
    options.addOption(Option.builder().longOpt("parallel").argName("MULTIPLIER(:TOPO:COMP)?").hasArg()
            .desc("How much to scale the topology up or down in parallelism. "
                    + "The new parallelism will round up to the next whole number. "
                    + "If a topology + component is supplied only that component will be scaled. "
                    + "If topo or component is blank or a '*' all topologies or components matched will be scaled. "
                    + "Only 1 scaling rule, the most specific, will be applied to a component. Providing a topology name is considered more "
                    + "specific than not providing one." + "(defaults to 1.0 no scaling)")
            .build());
    options.addOption(Option.builder().longOpt("throughput").argName("MULTIPLIER(:TOPO:COMP)?").hasArg()
            .desc("How much to scale the topology up or down in throughput. "
                    + "If a topology + component is supplied only that component will be scaled. "
                    + "If topo or component is blank or a '*' all topologies or components matched will be scaled. "
                    + "Only 1 scaling rule, the most specific, will be applied to a component. Providing a topology name is considered more "
                    + "specific than not providing one." + "(defaults to 1.0 no scaling)")
            .build());
    options.addOption(Option.builder().longOpt("local-or-shuffle")
            .desc("replace shuffle grouping with local or shuffle grouping").build());
    options.addOption(Option.builder().longOpt("imbalance").argName("MS(:COUNT)?:TOPO:COMP").hasArg().desc(
            "The number of ms that the first COUNT of TOPO:COMP will wait before processing.  This creates an imbalance "
                    + "that helps test load aware groupings. By default there is no imbalance.  If no count is given it defaults to 1")
            .build());
    options.addOption(Option.builder().longOpt("debug")
            .desc("Print debug information about the adjusted topology before submitting it.").build());
    LoadMetricsServer.addCommandLineOptions(options);
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = null;
    Exception commandLineException = null;
    double executeTime = TEST_EXECUTE_TIME_DEFAULT;
    double globalParallel = 1.0;
    Map<String, Double> topoSpecificParallel = new HashMap<>();
    double globalThroughput = 1.0;
    Map<String, Double> topoSpecificThroughput = new HashMap<>();
    Map<String, SlowExecutorPattern> topoSpecificImbalance = new HashMap<>();
    try {
        cmd = parser.parse(options, args);
        if (cmd.hasOption("t")) {
            executeTime = Double.valueOf(cmd.getOptionValue("t"));
        }
        if (cmd.hasOption("parallel")) {
            for (String stringParallel : cmd.getOptionValues("parallel")) {
                Matcher m = MULTI_PATTERN.matcher(stringParallel);
                if (!m.matches()) {
                    throw new ParseException(
                            "--parallel " + stringParallel + " is not in the format MULTIPLIER(:TOPO:COMP)?");
                }
                double parallel = Double.parseDouble(m.group("value"));
                String topo = m.group("topo");
                if (topo == null || topo.isEmpty()) {
                    topo = "*";
                }
                String comp = m.group("comp");
                if (comp == null || comp.isEmpty()) {
                    comp = "*";
                }
                if ("*".equals(topo) && "*".equals(comp)) {
                    globalParallel = parallel;
                } else {
                    topoSpecificParallel.put(topo + ":" + comp, parallel);
                }
            }
        }
        if (cmd.hasOption("throughput")) {
            for (String stringThroughput : cmd.getOptionValues("throughput")) {
                Matcher m = MULTI_PATTERN.matcher(stringThroughput);
                if (!m.matches()) {
                    throw new ParseException("--throughput " + stringThroughput
                            + " is not in the format MULTIPLIER(:TOPO:COMP)?");
                }
                double throughput = Double.parseDouble(m.group("value"));
                String topo = m.group("topo");
                if (topo == null || topo.isEmpty()) {
                    topo = "*";
                }
                String comp = m.group("comp");
                if (comp == null || comp.isEmpty()) {
                    comp = "*";
                }
                if ("*".equals(topo) && "*".equals(comp)) {
                    globalThroughput = throughput;
                } else {
                    topoSpecificThroughput.put(topo + ":" + comp, throughput);
                }
            }
        }
        if (cmd.hasOption("imbalance")) {
            for (String stringImbalance : cmd.getOptionValues("imbalance")) {
                //We require there to be both a topology and a component in this case, so parse it out as such.
                String[] parts = stringImbalance.split(":");
                if (parts.length < 3 || parts.length > 4) {
                    throw new ParseException(
                            stringImbalance + " does not appear to match the expected pattern");
                } else if (parts.length == 3) {
                    topoSpecificImbalance.put(parts[1] + ":" + parts[2],
                            SlowExecutorPattern.fromString(parts[0]));
                } else { //== 4
                    topoSpecificImbalance.put(parts[2] + ":" + parts[3],
                            SlowExecutorPattern.fromString(parts[0] + ":" + parts[1]));
                }
            }
        }
    } catch (ParseException | NumberFormatException e) {
        commandLineException = e;
    }
    if (commandLineException != null || cmd.hasOption('h')) {
        if (commandLineException != null) {
            System.err.println("ERROR " + commandLineException.getMessage());
        }
        new HelpFormatter().printHelp("GenLoad [options] [captured_file]*", options);
        return;
    }
    Map<String, Object> metrics = new LinkedHashMap<>();
    metrics.put("parallel_adjust", globalParallel);
    metrics.put("throughput_adjust", globalThroughput);
    metrics.put("local_or_shuffle", cmd.hasOption("local-or-shuffle"));
    metrics.put("topo_parallel", topoSpecificParallel.entrySet().stream()
            .map((entry) -> entry.getValue() + ":" + entry.getKey()).collect(Collectors.toList()));
    metrics.put("topo_throuhgput", topoSpecificThroughput.entrySet().stream()
            .map((entry) -> entry.getValue() + ":" + entry.getKey()).collect(Collectors.toList()));
    metrics.put("slow_execs", topoSpecificImbalance.entrySet().stream()
            .map((entry) -> entry.getValue() + ":" + entry.getKey()).collect(Collectors.toList()));

    Config conf = new Config();
    LoadMetricsServer metricServer = new LoadMetricsServer(conf, cmd, metrics);

    metricServer.serve();
    String url = metricServer.getUrl();
    int exitStatus = -1;
    try (NimbusClient client = NimbusClient.getConfiguredClient(conf);
            ScopedTopologySet topoNames = new ScopedTopologySet(client.getClient())) {
        for (String topoFile : cmd.getArgList()) {
            try {
                TopologyLoadConf tlc = readTopology(topoFile);
                tlc = tlc.scaleParallel(globalParallel, topoSpecificParallel);
                tlc = tlc.scaleThroughput(globalThroughput, topoSpecificThroughput);
                tlc = tlc.overrideSlowExecs(topoSpecificImbalance);
                if (cmd.hasOption("local-or-shuffle")) {
                    tlc = tlc.replaceShuffleWithLocalOrShuffle();
                }
                if (cmd.hasOption("debug")) {
                    LOG.info("DEBUGGING: {}", tlc.toYamlString());
                }
                topoNames.add(parseAndSubmit(tlc, url));
            } catch (Exception e) {
                System.err.println("Could Not Submit Topology From " + topoFile);
                e.printStackTrace(System.err);
            }
        }

        metricServer.monitorFor(executeTime, client.getClient(), topoNames);
        exitStatus = 0;
    } catch (Exception e) {
        LOG.error("Error trying to run topologies...", e);
    } finally {
        System.exit(exitStatus);
    }
}

From source file:org.apache.wave.pst.PstCommandLine.java

private void checkArgs() throws ParseException {
    if (!hasFile()) {
        throw new ParseException("Must specify file");
    }/*www.  j  a  v a 2  s . c  o  m*/
    if (cl.getArgList().isEmpty()) {
        throw new ParseException("Must specify at least one template");
    }
}

From source file:org.apache.wink.example.googledocs.CLIHelper.java

public void init(String[] args) throws ParseException {
    GnuParser parser = new GnuParser();
    commandLine = parser.parse(options, args);

    boolean hasHostOption = commandLine.hasOption(PROXY_HOST_ORT);
    boolean hasPortOption = commandLine.hasOption(PROXY_PORT_OPT);
    if (hasHostOption && !hasPortOption) {
        throw new ParseException("Proxy host was specified, but proxy port was not.");
    }/*  ww w . j ava 2 s . c om*/
    if (!hasHostOption && hasPortOption) {
        throw new ParseException("Proxy port was specified, but proxy host was not.");
    }
    if (hasHostOption && hasPortOption) {
        hasProxy = true;
    }

}

From source file:org.application.backupsync.client.Main.java

public void go(String[] args) throws ParseException, ClassCastException {
    Boolean exit;/*  w  w  w . j av a2 s .  c  o  m*/
    CommandLine cmd;
    CommandLineParser parser;

    parser = new PosixParser();

    cmd = parser.parse(this.opts, args);
    exit = Boolean.FALSE;

    if (cmd.hasOption("h") || cmd.hasOption("help")) {
        this.printHelp();
    }

    if (!cmd.hasOption("p")) {
        throw new ParseException("No port defined!");
    }

    try (Serve serve = new Serve(Integer.parseInt(cmd.getOptionValue("p")));) {
        serve.open();
        while (!exit) {
            exit = serve.listen();
        }
    } catch (BindException | UnknownHostException | NullPointerException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.blom.martin.stream2gdrive.Stream2GDrive.java

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

    opt.addOption("?", "help", false, "Show usage.");
    opt.addOption("V", "version", false, "Print version information.");
    opt.addOption("v", "verbose", false, "Display progress status.");

    opt.addOption("p", "parent", true, "Operate inside this Google Drive folder instead of root.");
    opt.addOption("o", "output", true, "Override output/destination file name");
    opt.addOption("m", "mime", true, "Override guessed MIME type.");
    opt.addOption("C", "chunk-size", true, "Set transfer chunk size, in MiB. Default is 10.0 MiB.");
    opt.addOption("r", "auto-retry", false,
            "Enable automatic retry with exponential backoff in case of error.");

    opt.addOption(null, "oob", false, "Provide OAuth authentication out-of-band.");

    try {//from   w  w  w .  ja  v a 2  s.co  m
        CommandLine cmd = new GnuParser().parse(opt, args, false);
        args = cmd.getArgs();

        if (cmd.hasOption("version")) {
            String version = "?";
            String date = "?";

            try {
                Properties props = new Properties();
                props.load(resource("/build.properties"));

                version = props.getProperty("version", "?");
                date = props.getProperty("date", "?");
            } catch (Exception ignored) {
            }

            System.err.println(String.format("%s %s. Build %s (%s)", APP_NAME, APP_VERSION, version, date));
            System.err.println();
        }

        if (cmd.hasOption("help")) {
            throw new ParseException(null);
        }

        if (args.length < 1) {
            if (cmd.hasOption("version")) {
                return;
            } else {
                throw new ParseException("<cmd> missing");
            }
        }

        String command = args[0];

        JsonFactory jf = JacksonFactory.getDefaultInstance();
        HttpTransport ht = GoogleNetHttpTransport.newTrustedTransport();
        GoogleClientSecrets gcs = GoogleClientSecrets.load(jf, resource("/client_secrets.json"));

        Set<String> scopes = new HashSet<String>();
        scopes.add(DriveScopes.DRIVE_FILE);
        scopes.add(DriveScopes.DRIVE_METADATA_READONLY);

        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(ht, jf, gcs, scopes)
                .setDataStoreFactory(new FileDataStoreFactory(appDataDir())).build();

        VerificationCodeReceiver vcr = !cmd.hasOption("oob") ? new LocalServerReceiver()
                : new GooglePromptReceiver();

        Credential creds = new AuthorizationCodeInstalledApp(flow, vcr).authorize("user");

        List<HttpRequestInitializer> hrilist = new ArrayList<HttpRequestInitializer>();
        hrilist.add(creds);

        if (cmd.hasOption("auto-retry")) {
            ExponentialBackOff.Builder backoffBuilder = new ExponentialBackOff.Builder()
                    .setInitialIntervalMillis(6 * 1000) // 6 seconds initial retry period
                    .setMaxElapsedTimeMillis(45 * 60 * 1000) // 45 minutes maximum total wait time
                    .setMaxIntervalMillis(15 * 60 * 1000) // 15 minute maximum interval
                    .setMultiplier(1.85).setRandomizationFactor(0.5);
            // Expected total waiting time before giving up = sum([6*1.85^i for i in range(10)])
            // ~= 55 minutes
            // Note that Google API's HttpRequest allows for up to 10 retry.
            hrilist.add(new ExponentialBackOffHttpRequestInitializer(backoffBuilder));
        }
        HttpRequestInitializerStacker hristack = new HttpRequestInitializerStacker(hrilist);

        Drive client = new Drive.Builder(ht, jf, hristack).setApplicationName(APP_NAME + "/" + APP_VERSION)
                .build();

        boolean verbose = cmd.hasOption("verbose");
        float chunkSize = Float.parseFloat(cmd.getOptionValue("chunk-size", "10.0"));

        String root = null;

        if (cmd.hasOption("parent")) {
            root = findWorkingDirectory(client, cmd.getOptionValue("parent"));
        }

        if (command.equals("get")) {
            String file;

            if (args.length < 2) {
                throw new ParseException("<file> missing");
            } else if (args.length == 2) {
                file = args[1];
            } else {
                throw new ParseException("Too many arguments");
            }

            download(client, ht, root, file, cmd.getOptionValue("output", file), verbose, chunkSize);
        } else if (command.equals("put")) {
            String file;

            if (args.length < 2) {
                throw new ParseException("<file> missing");
            } else if (args.length == 2) {
                file = args[1];
            } else {
                throw new ParseException("Too many arguments");
            }

            upload(client, file, root, cmd.getOptionValue("output", new File(file).getName()),
                    cmd.getOptionValue("mime",
                            new javax.activation.MimetypesFileTypeMap().getContentType(file)),
                    verbose, chunkSize);
        } else if (command.equals("trash")) {
            String file;

            if (args.length < 2) {
                throw new ParseException("<file> missing");
            } else if (args.length == 2) {
                file = args[1];
            } else {
                throw new ParseException("Too many arguments");
            }

            trash(client, root, file);
        } else if (command.equals("md5") || command.equals("list")) {
            if (args.length > 1) {
                throw new ParseException("Too many arguments");
            }

            list(client, root, command.equals("md5"));
        } else {
            throw new ParseException("Invalid command: " + command);
        }
    } catch (ParseException ex) {
        PrintWriter pw = new PrintWriter(System.err);
        HelpFormatter hf = new HelpFormatter();

        hf.printHelp(pw, 80, "stream2gdrive [OPTIONS] <cmd> [<options>]",
                "  Commands: get <file>, list, md5, put <file>, trash <file>.", opt, 2, 8,
                "Use '-' as <file> for standard input.");

        if (ex.getMessage() != null && !ex.getMessage().isEmpty()) {
            pw.println();
            hf.printWrapped(pw, 80, String.format("Error: %s.", ex.getMessage()));
        }

        pw.flush();
        System.exit(EX_USAGE);
    } catch (NumberFormatException ex) {
        System.err.println("Invalid decimal number: " + ex.getMessage() + ".");
        System.exit(EX_USAGE);
    } catch (IOException ex) {
        System.err.println("I/O error: " + ex.getMessage() + ".");
        System.exit(EX_IOERR);
    }
}

From source file:org.bonmassar.crappydb.server.config.DefaultConfiguration.java

protected Catalogue fromCatalogue(String value, String paramName) throws ParseException {
    Catalogue c = Catalogue.parseString(value);
    if (null == c)
        throw new ParseException(String.format("Invalid value %s for parameter %s. Allowed values are %s.",
                value, paramName, getStorageAllowedValues()));
    return c;//  w w  w . jav  a  2s  .co  m
}

From source file:org.bonmassar.crappydb.server.config.DefaultConfiguration.java

protected int toInt(String value, String paramName) throws ParseException {
    try {/*from   w  w  w.j  av a 2s  . c o m*/
        return Integer.parseInt(value);
    } catch (NumberFormatException err) {
        throw new ParseException(String.format("Invalid value for parameter %s", paramName));
    }
}