Example usage for org.apache.commons.cli Option getLongOpt

List of usage examples for org.apache.commons.cli Option getLongOpt

Introduction

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

Prototype

public String getLongOpt() 

Source Link

Document

Retrieve the long name of this Option.

Usage

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

/**
 * Printing out help message/*from   w  ww  . jav  a2  s.  c  o m*/
 */
public static void printHelpMessage() {
    System.out.println("Usage: ./bin/cassandra-staleness [options]\n\nOptions:");

    for (Object o : Session.availableOptions.getOptions()) {
        Option option = (Option) o;
        String upperCaseName = option.getLongOpt().toUpperCase();
        System.out.println(String.format("-%s%s, --%s%s%n\t\t%s%n", option.getOpt(),
                (option.hasArg()) ? " " + upperCaseName : "", option.getLongOpt(),
                (option.hasArg()) ? "=" + upperCaseName : "", option.getDescription()));
    }
}

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

public static void printHelpMessage() {
    System.out.println("Usage: ./bin/cassandra-stress legacy [options]\n\nOptions:");
    System.out.println("THIS IS A LEGACY SUPPORT MODE");

    for (Object o : availableOptions.getOptions()) {
        Option option = (Option) o;
        String upperCaseName = option.getLongOpt().toUpperCase();
        System.out.println(String.format("-%s%s, --%s%s%n\t\t%s%n", option.getOpt(),
                (option.hasArg()) ? " " + upperCaseName : "", option.getLongOpt(),
                (option.hasArg()) ? "=" + upperCaseName : "", option.getDescription()));
    }/*from   ww  w. j a  va  2  s. co m*/
}

From source file:org.apache.flink.table.client.cli.CliOptionsParser.java

private static List<URL> checkUrls(CommandLine line, Option option) {
    if (line.hasOption(option.getOpt())) {
        final String[] urls = line.getOptionValues(option.getOpt());
        return Arrays.stream(urls).distinct().map((url) -> {
            try {
                return Path.fromLocalFile(new File(url).getAbsoluteFile()).toUri().toURL();
            } catch (Exception e) {
                throw new SqlClientException("Invalid path for option '" + option.getLongOpt() + "': " + url,
                        e);// w  ww.j  a v  a 2s  .c o  m
            }
        }).collect(Collectors.toList());
    }
    return null;
}

From source file:org.apache.flink.table.client.config.Deployment.java

/**
 * Parses the given command line options from the deployment properties. Ignores properties
 * that are not defined by options./*from   www .j av a  2  s  .co m*/
 */
public CommandLine getCommandLine(Options commandLineOptions) throws Exception {
    final List<String> args = new ArrayList<>();

    properties.forEach((k, v) -> {
        // only add supported options
        if (commandLineOptions.hasOption(k)) {
            final Option o = commandLineOptions.getOption(k);
            final String argument = "--" + o.getLongOpt();
            // options without args
            if (!o.hasArg()) {
                final Boolean flag = Boolean.parseBoolean(v);
                // add key only
                if (flag) {
                    args.add(argument);
                }
            }
            // add key and value
            else if (!o.hasArgs()) {
                args.add(argument);
                args.add(v);
            }
            // options with multiple args are not supported yet
            else {
                throw new IllegalArgumentException("Option '" + o + "' is not supported yet.");
            }
        }
    });

    return CliFrontendParser.parse(commandLineOptions, args.toArray(new String[args.size()]), true);
}

From source file:org.apache.flink.table.client.config.entries.DeploymentEntry.java

/**
 * Parses the given command line options from the deployment properties. Ignores properties
 * that are not defined by options.//from   www .  j  a va 2s . c om
 */
public CommandLine getCommandLine(Options commandLineOptions) throws Exception {
    final List<String> args = new ArrayList<>();

    properties.asMap().forEach((k, v) -> {
        // only add supported options
        if (commandLineOptions.hasOption(k)) {
            final Option o = commandLineOptions.getOption(k);
            final String argument = "--" + o.getLongOpt();
            // options without args
            if (!o.hasArg()) {
                final Boolean flag = Boolean.parseBoolean(v);
                // add key only
                if (flag) {
                    args.add(argument);
                }
            }
            // add key and value
            else if (!o.hasArgs()) {
                args.add(argument);
                args.add(v);
            }
            // options with multiple args are not supported yet
            else {
                throw new IllegalArgumentException("Option '" + o + "' is not supported yet.");
            }
        }
    });

    return CliFrontendParser.parse(commandLineOptions, args.toArray(new String[args.size()]), true);
}

From source file:org.apache.geronimo.cli.PrintHelper.java

public void printUsage(PrintWriter pw, int width, String app, Options options) {
    // create a list for processed option groups
    ArrayList list = new ArrayList();

    StringBuilder optionsBuff = new StringBuilder();

    // temp variable
    Option option;

    // iterate over the options
    for (Iterator i = options.getOptions().iterator(); i.hasNext();) {
        // get the next Option
        option = (Option) i.next();

        // check if the option is part of an OptionGroup
        OptionGroup group = options.getOptionGroup(option);

        // if the option is part of a group and the group has not already
        // been processed
        if (group != null && !list.contains(group)) {

            // add the group to the processed list
            list.add(group);/*from  w  w  w.j av a2 s . co m*/

            // get the names of the options from the OptionGroup
            Collection names = group.getNames();

            optionsBuff.append("[");

            // for each option in the OptionGroup
            for (Iterator iter = names.iterator(); iter.hasNext();) {
                optionsBuff.append(iter.next());
                if (iter.hasNext()) {
                    optionsBuff.append("|");
                }
            }
            optionsBuff.append("] ");
        } else if (group == null) {
            // if the Option is not part of an OptionGroup
            // if the Option is not a required option
            if (!option.isRequired()) {
                optionsBuff.append("[");
            }

            if (!" ".equals(option.getOpt())) {
                optionsBuff.append("-").append(option.getOpt());
            } else {
                optionsBuff.append("--").append(option.getLongOpt());
            }

            if (option.hasArg()) {
                optionsBuff.append(" ");
            }

            // if the Option has a value
            if (option.hasArg()) {
                optionsBuff.append(option.getArgName());
            }

            // if the Option is not a required option
            if (!option.isRequired()) {
                optionsBuff.append("]");
            }
            optionsBuff.append(" ");
        }
    }

    app = app.replace("$options", optionsBuff.toString());

    // call printWrapped
    printWrapped(pw, width, app.indexOf(' ') + 1, app);
}

From source file:org.apache.geronimo.cli.PrintHelper.java

protected StringBuilder renderOptions(StringBuilder sb, int width, Options options, int leftPad, int descPad,
        boolean displayDesc) {
    final String lpad = createPadding(leftPad);
    final String dpad = createPadding(descPad);

    //first create list containing only <lpad>-a,--aaa where -a is opt and --aaa is
    //long opt; in parallel look for the longest opt string
    //this list will be then used to sort options ascending
    int max = 0;//  w w  w  .  java2s .c  o  m
    StringBuilder optBuf;
    List prefixList = new ArrayList();
    Option option;
    List optList = new ArrayList(options.getOptions());
    Collections.sort(optList, new StringBuilderComparator());
    for (Iterator i = optList.iterator(); i.hasNext();) {
        option = (Option) i.next();
        optBuf = new StringBuilder(8);

        if (option.getOpt().equals(" ")) {
            optBuf.append(lpad).append("   " + defaultLongOptPrefix).append(option.getLongOpt());
        } else {
            optBuf.append(lpad).append(defaultOptPrefix).append(option.getOpt());
            if (option.hasLongOpt()) {
                optBuf.append(',').append(defaultLongOptPrefix).append(option.getLongOpt());
            }

        }

        if (option.hasArg()) {
            if (option.hasArgName()) {
                optBuf.append(" <").append(option.getArgName()).append('>');
            } else {
                optBuf.append(' ');
            }
        }

        prefixList.add(optBuf);
        max = optBuf.length() > max ? optBuf.length() : max;
    }
    int x = 0;
    for (Iterator i = optList.iterator(); i.hasNext();) {
        option = (Option) i.next();
        optBuf = new StringBuilder(prefixList.get(x++).toString());

        if (optBuf.length() < max) {
            optBuf.append(createPadding(max - optBuf.length()));
        }
        optBuf.append(dpad);

        if (displayDesc) {
            optBuf.append(option.getDescription());
        }
        int nextLineTabStop = max + descPad;
        renderWrappedText(sb, width, nextLineTabStop, optBuf.toString());
        if (i.hasNext()) {
            sb.append(defaultNewLine);
            if (displayDesc) {
                sb.append(defaultNewLine);
            }
        }
    }

    return sb;
}

From source file:org.apache.gobblin.runtime.util.JobStateToJsonConverter.java

@SuppressWarnings("all")
public static void main(String[] args) throws Exception {
    Option sysConfigOption = Option.builder("sc").argName("system configuration file")
            .desc("Gobblin system configuration file (required if no state store URL specified)")
            .longOpt("sysconfig").hasArg().build();
    Option storeUrlOption = Option.builder("u").argName("gobblin state store URL")
            .desc("Gobblin state store root path URL (required if no sysconfig specified)").longOpt("storeurl")
            .hasArg().build();/* w w  w. jav a  2  s  . com*/
    Option jobNameOption = Option.builder("n").argName("gobblin job name").desc("Gobblin job name (required)")
            .longOpt("name").hasArg().required().build();
    Option jobIdOption = Option.builder("i").argName("gobblin job id").desc("Gobblin job id").longOpt("id")
            .hasArg().build();
    Option convertAllOption = Option.builder("a")
            .desc("Whether to convert all past job states of the given job").longOpt("all").build();
    Option keepConfigOption = Option.builder("kc").desc("Whether to keep all configuration properties")
            .longOpt("keepConfig").build();
    Option outputToFile = Option.builder("t").argName("output file name").desc("Output file name")
            .longOpt("toFile").hasArg().build();

    Options options = new Options();
    options.addOption(sysConfigOption);
    options.addOption(storeUrlOption);
    options.addOption(jobNameOption);
    options.addOption(jobIdOption);
    options.addOption(convertAllOption);
    options.addOption(keepConfigOption);
    options.addOption(outputToFile);

    CommandLine cmd = null;
    try {
        CommandLineParser parser = new DefaultParser();
        cmd = parser.parse(options, args);
    } catch (ParseException pe) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("JobStateToJsonConverter", options);
        System.exit(1);
    }

    if (!cmd.hasOption(sysConfigOption.getLongOpt()) && !cmd.hasOption(storeUrlOption.getLongOpt())) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("JobStateToJsonConverter", options);
        System.exit(1);
    }

    Properties sysConfig = new Properties();
    if (cmd.hasOption(sysConfigOption.getLongOpt())) {
        sysConfig = JobConfigurationUtils.fileToProperties(cmd.getOptionValue(sysConfigOption.getLongOpt()));
    }

    JobStateToJsonConverter converter = new JobStateToJsonConverter(sysConfig, cmd.getOptionValue('u'),
            cmd.hasOption("kc"));
    StringWriter stringWriter = new StringWriter();
    if (cmd.hasOption('i')) {
        converter.convert(cmd.getOptionValue('n'), cmd.getOptionValue('i'), stringWriter);
    } else {
        if (cmd.hasOption('a')) {
            converter.convertAll(cmd.getOptionValue('n'), stringWriter);
        } else {
            converter.convert(cmd.getOptionValue('n'), stringWriter);
        }
    }

    if (cmd.hasOption('t')) {
        Closer closer = Closer.create();
        try {
            FileOutputStream fileOutputStream = closer.register(new FileOutputStream(cmd.getOptionValue('t')));
            OutputStreamWriter outputStreamWriter = closer.register(
                    new OutputStreamWriter(fileOutputStream, ConfigurationKeys.DEFAULT_CHARSET_ENCODING));
            BufferedWriter bufferedWriter = closer.register(new BufferedWriter(outputStreamWriter));
            bufferedWriter.write(stringWriter.toString());
        } catch (Throwable t) {
            throw closer.rethrow(t);
        } finally {
            closer.close();
        }
    } else {
        System.out.println(stringWriter.toString());
    }
}

From source file:org.apache.hadoop.hdfs.server.diskbalancer.command.Command.java

/**
 * Verifies if the command line options are sane.
 *
 * @param commandName - Name of the command
 * @param cmd         - Parsed Command Line
 *//*  w  w w  .j  a  va 2s  . co  m*/
protected void verifyCommandOptions(String commandName, CommandLine cmd) {
    @SuppressWarnings("unchecked")
    Iterator<Option> iter = cmd.iterator();
    while (iter.hasNext()) {
        Option opt = iter.next();

        if (!validArgs.containsKey(opt.getLongOpt())) {
            String errMessage = String.format("%nInvalid argument found for command %s : %s%n", commandName,
                    opt.getLongOpt());
            StringBuilder validArguments = new StringBuilder();
            validArguments.append(String.format("Valid arguments are : %n"));
            for (Map.Entry<String, String> args : validArgs.entrySet()) {
                String key = args.getKey();
                String desc = args.getValue();
                String s = String.format("\t %s : %s %n", key, desc);
                validArguments.append(s);
            }
            LOG.error(errMessage + validArguments.toString());
            throw new IllegalArgumentException("Invalid Arguments found.");
        }
    }
}

From source file:org.apache.marmotta.loader.core.MarmottaLoader.java

public static Configuration parseOptions(String[] args) throws ParseException {
    Options options = buildOptions();/*  w w  w .  j a  v  a 2 s . c o  m*/

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = parser.parse(options, args);

    Configuration result = new MapConfiguration(new HashMap<String, Object>());

    if (cmd.hasOption('B')) {
        // check backends
        Set<String> existing = Sets
                .newHashSet(Iterators.transform(backends.iterator(), new BackendIdentifierFunction()));
        if (!existing.contains(cmd.getOptionValue('B'))) {
            throw new ParseException("the backend " + cmd.getOptionValue('B') + " does not exist");
        }

        result.setProperty(LoaderOptions.BACKEND, cmd.getOptionValue('B'));
    }

    if (cmd.hasOption('b')) {
        result.setProperty(LoaderOptions.BASE_URI, cmd.getOptionValue('b'));
    }

    if (cmd.hasOption('z')) {
        result.setProperty(LoaderOptions.COMPRESSION, CompressorStreamFactory.GZIP);
    }

    if (cmd.hasOption('j')) {
        result.setProperty(LoaderOptions.COMPRESSION, CompressorStreamFactory.BZIP2);
    }

    if (cmd.hasOption('c')) {
        result.setProperty(LoaderOptions.CONTEXT, cmd.getOptionValue('c'));
    }

    if (cmd.hasOption('t')) {
        RDFFormat fmt = getRDFFormat(cmd.getOptionValue('t'));
        if (fmt == null) {
            throw new ParseException("unrecognized MIME type: " + cmd.getOptionValue('t'));
        }

        result.setProperty(LoaderOptions.FORMAT, fmt.getDefaultMIMEType());
    }

    if (cmd.hasOption('f')) {
        result.setProperty(LoaderOptions.FILES, Arrays.asList(cmd.getOptionValues('f')));
    }

    if (cmd.hasOption('d')) {
        result.setProperty(LoaderOptions.DIRS, Arrays.asList(cmd.getOptionValues('d')));
    }

    if (cmd.hasOption('a')) {
        result.setProperty(LoaderOptions.ARCHIVES, Arrays.asList(cmd.getOptionValues('a')));
    }

    if (cmd.hasOption('s')) {
        result.setProperty(LoaderOptions.STATISTICS_ENABLED, true);
        result.setProperty(LoaderOptions.STATISTICS_GRAPH, cmd.getOptionValue('s'));
    }

    if (cmd.hasOption('D')) {
        for (Map.Entry e : cmd.getOptionProperties("D").entrySet()) {
            result.setProperty(e.getKey().toString(), e.getValue());
        }
    }

    for (LoaderBackend b : backends) {
        for (Option option : b.getOptions()) {
            if (cmd.hasOption(option.getOpt())) {
                String key = String.format("backend.%s.%s", b.getIdentifier(),
                        option.getLongOpt() != null ? option.getLongOpt() : option.getOpt());
                if (option.hasArg()) {
                    if (option.hasArgs()) {
                        result.setProperty(key, Arrays.asList(cmd.getOptionValues(option.getOpt())));
                    } else {
                        result.setProperty(key, cmd.getOptionValue(option.getOpt()));
                    }
                } else {
                    result.setProperty(key, true);
                }
            }
        }
    }

    return result;
}