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

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

Introduction

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

Prototype

public String[] getValues() 

Source Link

Document

Return the values of this Option as a String array or null if there are no values

Usage

From source file:org.apache.blur.shell.AddColumnDefinitionCommand.java

@Override
public void doit(PrintWriter out, Blur.Iface client, String[] args)
        throws CommandException, TException, BlurException {
    if (args.length < 5) {
        throw new CommandException("Invalid args: " + help());
    }//ww w. j av a2 s  .  c  o  m
    CommandLine cmd = parse(args, out);

    ColumnDefinition columnDefinition = new ColumnDefinition();
    columnDefinition.setFamily(args[2]);
    columnDefinition.setColumnName(args[3]);
    columnDefinition.setFieldType(args[4]);
    if (cmd.hasOption("s")) {
        columnDefinition.setSubColumnName(cmd.getOptionValue("s"));
    }
    if (cmd.hasOption("F")) {
        columnDefinition.setFieldLessIndexed(true);
    }
    if (cmd.hasOption("S")) {
        columnDefinition.setSortable(true);
    }
    if (cmd.hasOption("p")) {
        Option[] options = cmd.getOptions();
        for (Option option : options) {
            if (option.getOpt().equals("p")) {
                String[] values = option.getValues();
                columnDefinition.putToProperties(values[0], values[1]);
            }
        }
    }
    if (cmd.hasOption('M')) {
        columnDefinition.setMultiValueField(true);
    } else {
        columnDefinition.setMultiValueField(false);
    }

    if (!client.addColumnDefinition(args[1], columnDefinition)) {
        out.println(
                "Column Definition was not added, check to see if the column has already been added to the table.");
    }
}

From source file:org.apache.blur.shell.CreateTableCommand.java

private Map<String, String> getProps(CommandLine cmd, String opt) {
    Map<String, String> props = new HashMap<String, String>();
    Option[] options = cmd.getOptions();
    for (Option option : options) {
        if (option.getOpt().equals(opt)) {
            String[] values = option.getValues();
            props.put(values[0], values[1]);
        }//from  w ww.  j a v  a2s  .co  m
    }
    return props;
}

From source file:org.apache.commons.jci.examples.commandline.CommandlineCompiler.java

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

    final Options options = new Options();

    options.addOption(OptionBuilder.withArgName("a.jar:b.jar").hasArg().withValueSeparator(':')
            .withDescription("Specify where to find user class files").create("classpath"));

    options.addOption(OptionBuilder.withArgName("release").hasArg()
            .withDescription("Provide source compatibility with specified release").create("source"));

    options.addOption(OptionBuilder.withArgName("release").hasArg()
            .withDescription("Generate class files for specific VM version").create("target"));

    options.addOption(OptionBuilder.withArgName("path").hasArg()
            .withDescription("Specify where to find input source files").create("sourcepath"));

    options.addOption(OptionBuilder.withArgName("directory").hasArg()
            .withDescription("Specify where to place generated class files").create("d"));

    options.addOption(OptionBuilder.withArgName("num").hasArg()
            .withDescription("Stop compilation after these number of errors").create("Xmaxerrs"));

    options.addOption(OptionBuilder.withArgName("num").hasArg()
            .withDescription("Stop compilation after these number of warning").create("Xmaxwarns"));

    options.addOption(OptionBuilder.withDescription("Generate no warnings").create("nowarn"));

    //        final HelpFormatter formatter = new HelpFormatter();
    //        formatter.printHelp("jci", options);

    final CommandLineParser parser = new GnuParser();
    final CommandLine cmd = parser.parse(options, args, true);

    ClassLoader classloader = CommandlineCompiler.class.getClassLoader();
    File sourcepath = new File(".");
    File targetpath = new File(".");
    int maxerrs = 10;
    int maxwarns = 10;
    final boolean nowarn = cmd.hasOption("nowarn");

    final JavaCompiler compiler = new JavaCompilerFactory().createCompiler("eclipse");
    final JavaCompilerSettings settings = compiler.createDefaultSettings();

    for (Iterator it = cmd.iterator(); it.hasNext();) {
        final Option option = (Option) it.next();
        if ("classpath".equals(option.getOpt())) {
            final String[] values = option.getValues();
            final URL[] urls = new URL[values.length];
            for (int i = 0; i < urls.length; i++) {
                urls[i] = new File(values[i]).toURL();
            }//from   w w w . j  a  va2s .  c  o m
            classloader = new URLClassLoader(urls);
        } else if ("source".equals(option.getOpt())) {
            settings.setSourceVersion(option.getValue());
        } else if ("target".equals(option.getOpt())) {
            settings.setTargetVersion(option.getValue());
        } else if ("sourcepath".equals(option.getOpt())) {
            sourcepath = new File(option.getValue());
        } else if ("d".equals(option.getOpt())) {
            targetpath = new File(option.getValue());
        } else if ("Xmaxerrs".equals(option.getOpt())) {
            maxerrs = Integer.parseInt(option.getValue());
        } else if ("Xmaxwarns".equals(option.getOpt())) {
            maxwarns = Integer.parseInt(option.getValue());
        }
    }

    final ResourceReader reader = new FileResourceReader(sourcepath);
    final ResourceStore store = new FileResourceStore(targetpath);

    final int maxErrors = maxerrs;
    final int maxWarnings = maxwarns;
    compiler.setCompilationProblemHandler(new CompilationProblemHandler() {
        int errors = 0;
        int warnings = 0;

        public boolean handle(final CompilationProblem pProblem) {

            if (pProblem.isError()) {
                System.err.println(pProblem);

                errors++;

                if (errors >= maxErrors) {
                    return false;
                }
            } else {
                if (!nowarn) {
                    System.err.println(pProblem);
                }

                warnings++;

                if (warnings >= maxWarnings) {
                    return false;
                }
            }

            return true;
        }
    });

    final String[] resource = cmd.getArgs();

    for (int i = 0; i < resource.length; i++) {
        System.out.println("compiling " + resource[i]);
    }

    final CompilationResult result = compiler.compile(resource, reader, store, classloader);

    System.out.println(result.getErrors().length + " errors");
    System.out.println(result.getWarnings().length + " warnings");

}

From source file:org.apache.flex.compiler.clients.ASC.java

/**
 * Apache Common CLI did the lexer work. This function does the parser work
 * to construct an {@code ASC} job from the command-line options.
 * //  w w  w  . j a  v  a  2 s .  c o  m
 * @param line - the tokenized command-line
 * @return a new ASC client for the given command-line configuration; null
 * if no arguments were given.
 */
private Boolean createClient(final CommandLine line) throws ParseException {
    // First, process parsed command line options.
    final Option[] options = line.getOptions();

    if (options == null)
        return false;

    for (int i = 0; i < options.length; i++) {
        final Option option = options[i];
        final String shortName = option.getOpt();

        if ("import".equals(shortName)) {
            String[] imports = option.getValues();
            for (int j = 0; j < imports.length; j++) {
                this.addImportFilename(imports[j]);
            }
        } else if ("in".equals(shortName)) {
            String[] includes = option.getValues();
            for (int j = 0; j < includes.length; j++) {
                this.addIncludeFilename(includes[j]);
            }
        } else if ("swf".equals(shortName)) {
            String[] swfValues = option.getValue().split(",");
            if (swfValues.length < 3)
                throw new MissingArgumentException(
                        "The swf option requires three arguments, only " + swfValues.length + " were found.");

            for (int j = 0; j < swfValues.length; j++) {
                String value = swfValues[j];
                if (j == 0)
                    this.setSymbolClass(value);
                else if (j == 1)
                    this.setWidth(value);
                else if (j == 2)
                    this.setHeight(value);
                else if (j == 3)
                    this.setFrameRate(value);
            }
        } else if ("use".equals(shortName)) {
            String[] namespaces = option.getValues();
            for (String namespace : namespaces) {
                this.addNamespace(namespace);
            }
        } else if ("config".equals(shortName)) {
            String[] config = option.getValues();
            if (config.length == 2) {
                // The config option will have been split around '='
                // e.g. CONFIG::Foo='hi' will be split into
                // 2 values - 'CONFIG::Foo' and 'hi'
                String name = config[0];
                String value = config[1];
                value = fixupMissingQuote(value);
                this.putConfigVar(name, value);
            }
        } else if ("strict".equals(shortName) || "!".equals(shortName)) {
            this.setUseStaticSemantics(true);
        } else if ("d".equals(shortName)) {
            this.setEmitDebugInfo(true);
        } else if ("warnings".equals(shortName) || "coach".equals(shortName)) {
            if ("coach".equals(shortName))
                err.println("'coach' has been deprecated. Please use 'warnings' instead.");
            this.setShowWarnings(true);
        } else if ("log".equals(shortName)) {
            this.setShowLog(true);
        } else if ("md".equals(shortName)) {
            this.setEmitMetadata(true);
        } else if ("merge".equals(shortName)) {
            this.setMergeABCs(true);
        } else if ("language".equals(shortName)) {
            String value = option.getValue();
            this.setLocale(getLocaleForLanguage(value));
        } else if ("doc".equals(shortName)) {
            this.setEmitDocInfo(true);
        } else if ("avmtarget".equals(shortName)) {
            String value = option.getValue();
            this.setTargetAVM(value);
        } else if ("AS3".equals(shortName)) {
            this.setDialect("AS3");
        } else if ("ES".equals(shortName)) {
            this.setDialect("ES");
        } else if ("o".equalsIgnoreCase(shortName) || "optimize".equalsIgnoreCase(shortName)) {
            this.setOptimize(true);
        } else if ("o2".equalsIgnoreCase(shortName)) {
            this.setOptimize(true);
        } else if ("out".equalsIgnoreCase(shortName)) {
            this.setOutputBasename(option.getValue());
        } else if ("outdir".equalsIgnoreCase(shortName)) {
            this.setOutputDirectory(option.getValue());
        } else if ("abcfuture".equals(shortName)) {
            this.setABCFuture(true);
        } else if ("p".equals(shortName)) {
            this.setShowParseTrees(true);
        } else if ("i".equals(shortName)) {
            this.setShowInstructions(true);
        } else if ("m".equals(shortName)) {
            this.setShowMachineCode(true);
        } else if ("f".equals(shortName)) {
            this.setShowFlowGraph(true);
        } else if ("exe".equals(shortName)) {
            String exe = option.getValue();
            this.setAvmplusFilename(exe);
        } else if ("movieclip".equals(shortName)) {
            this.setMakeMovieClip(true);
        } else if ("ES4".equals(shortName)) {
            this.setDialect("ES4");
        } else if ("li".equals(shortName)) {
            this.internalLibraries.add(option.getValue());
        } else if ("le".equals(shortName)) {
            this.externalLibraries.add(option.getValue());
        } else if ("parallel".equals(shortName)) {
            this.setParallel(true);
        } else if ("inline".equals(shortName)) {
            this.setMergeABCs(true); // inlining requires merging of ABCs
            this.setEnableInlining(true);
        } else if ("removedeadcode".equals(shortName)) {
            this.setRemoveDeadCode(true);
        } else {
            throw new UnrecognizedOptionException("Unrecognized option '" + shortName + "'", shortName);
        }
    }

    // Then any remaining arguments that were not options are interpreted as
    // source files to compile.
    final String[] remainingArgs = line.getArgs();
    if (remainingArgs != null) {
        for (int i = 0; i < remainingArgs.length; i++) {
            this.addSourceFilename(remainingArgs[i]);
        }
    } else {
        throw new MissingArgumentException(
                "At least one source file must be specified after the list of options.");
    }

    return true;
}

From source file:org.apache.helix.task.TaskDriver.java

/** Ensures options argument counts are correct */
private static boolean checkOptionArgsNumber(Option[] options) {
    for (Option option : options) {
        int argNb = option.getArgs();
        String[] args = option.getValues();
        if (argNb == 0) {
            if (args != null && args.length > 0) {
                System.err.println(option.getArgName() + " shall have " + argNb + " arguments (was "
                        + Arrays.toString(args) + ")");
                return false;
            }/*from  w w  w .  j av  a2  s  .  c om*/
        } else {
            if (args == null || args.length != argNb) {
                System.err.println(option.getArgName() + " shall have " + argNb + " arguments (was "
                        + Arrays.toString(args) + ")");
                return false;
            }
        }
    }
    return true;
}

From source file:org.apache.helix.tools.JmxDumper.java

private static boolean checkOptionArgsNumber(Option[] options) {
    for (Option option : options) {
        int argNb = option.getArgs();
        String[] args = option.getValues();
        if (argNb == 0) {
            if (args != null && args.length > 0) {
                System.err.println(option.getArgName() + " shall have " + argNb + " arguments (was "
                        + Arrays.toString(args) + ")");
                return false;
            }/*w  ww.  java 2  s  .  c o m*/
        } else {
            if (args == null || args.length != argNb) {
                System.err.println(option.getArgName() + " shall have " + argNb + " arguments (was "
                        + Arrays.toString(args) + ")");
                return false;
            }
        }
    }
    return true;
}

From source file:org.jruyi.launcher.Main.java

private static boolean processCommandLines(String[] args) throws Exception {
    Options options = new Options();
    options.addOption("?", "help", false, null);
    options.addOption("v", "version", false, null);
    Option o = new Option("D", true, null);
    o.setArgs(Option.UNLIMITED_VALUES);
    options.addOption(o);//from   www  .  j a  v  a  2 s  .c  o m
    options.addOption("r", "run", true, null);

    CommandLine line = new PosixParser().parse(options, args);

    Option[] opts = line.getOptions();
    for (Option option : opts) {
        String opt = option.getOpt();
        if (opt.equals("?")) {
            printHelp();
            return false;
        } else if (opt.equals("v")) {
            MainHolder.INST.printVersion();
            return false;
        } else if (opt.equals("D")) {
            handleSystemProps(option.getValues());
        } else if (opt.equals("r")) {
            System.setProperty(JRUYI_INST_NAME, option.getValue().trim());
        } else
            throw new Exception("Unknown option: " + option);
    }

    return true;
}

From source file:org.jumpmind.symmetric.AbstractCommandLauncher.java

public void execute(String args[]) {
    PosixParser parser = new PosixParser();
    Options options = new Options();
    buildOptions(options);/*from   w  ww  .  j  a  v  a 2s  .c om*/
    try {
        CommandLine line = parser.parse(options, args);

        if (line.hasOption(HELP) || (line.getArgList().contains(HELP)) || ((args == null || args.length == 0)
                && line.getOptions().length == 0 && printHelpIfNoOptionsAreProvided())) {
            printHelp(line, options);
            System.exit(2);
        }

        configureLogging(line);
        configurePropertiesFile(line);

        if (line.getOptions() != null) {
            for (Option option : line.getOptions()) {
                log.info("Option: name={}, value={}",
                        new Object[] { option.getLongOpt() != null ? option.getLongOpt() : option.getOpt(),
                                ArrayUtils.toString(option.getValues()) });
            }
        }

        executeWithOptions(line);

    } catch (ParseException e) {
        System.err.println(e.getMessage());
        printUsage(options);
        System.exit(4);
    } catch (Exception e) {
        System.err.println("-------------------------------------------------------------------------------");
        System.err.println("An exception occurred.  Please see the following for details:");
        System.err.println("-------------------------------------------------------------------------------");

        ExceptionUtils.printRootCauseStackTrace(e, System.err);
        System.err.println("-------------------------------------------------------------------------------");
        System.exit(1);
    }
}

From source file:org.lib4j.cli.Options.java

public static Options parse(final Cli binding, final Class<?> mainClass, final String[] args) {
    final Set<String> requiredNames = new HashSet<>();
    final Map<String, String> nameToAltName = new HashMap<>();
    final org.apache.commons.cli.Options apacheOptions = new org.apache.commons.cli.Options();
    apacheOptions.addOption(null, "help", false, "Print help and usage.");
    short argumentsMinOccurs = 0;
    short argumentsMaxOccurs = 0;
    final Cli.Arguments cliArguments;
    if (binding != null) {
        cliArguments = binding.getArguments();
        if (cliArguments != null) {
            argumentsMinOccurs = cliArguments.getMinOccurs();
            argumentsMaxOccurs = "unbounded".equals(cliArguments.getMaxOccurs()) ? Short.MAX_VALUE
                    : Short.parseShort(cliArguments.getMaxOccurs());
            if (argumentsMaxOccurs < argumentsMinOccurs) {
                logger.error("minOccurs > maxOccurs on <arguments> element");
                System.exit(1);//  ww  w.j av a2 s  .co m
            }
        }

        if (binding.getOption() != null) {
            for (final Cli.Option option : binding.getOption()) {
                final Cli.Option.Name optionName = option.getName();
                final String longName = optionName.getLong() == null ? null : optionName.getLong();
                final String shortName = optionName.getShort() == null ? null : optionName.getShort();
                final String name = longName != null ? longName : shortName;
                if (longName == null && shortName == null) {
                    logger.error("both [long] and [short] option names are null in cli spec");
                    System.exit(1);
                }

                nameToAltName.put(name, shortName != null ? shortName : longName);
                OptionBuilder.withLongOpt(name == longName ? longName : null);

                // Record which options are required
                if (option.getArgument() != null) {
                    final Cli.Option.Argument argument = option.getArgument();
                    final boolean isRequired = Use.REQUIRED == argument.getUse();
                    if (isRequired) {
                        OptionBuilder.isRequired();
                        requiredNames.add(longName);
                    }

                    final int maxOccurs = argument.getMaxOccurs() == null ? 1
                            : "unbounded".equals(argument.getMaxOccurs()) ? Integer.MAX_VALUE
                                    : Integer.parseInt(argument.getMaxOccurs());
                    if (maxOccurs == 1) {
                        if (isRequired)
                            OptionBuilder.hasArgs(1);
                        else
                            OptionBuilder.hasOptionalArgs(1);
                    } else if (maxOccurs == Integer.MAX_VALUE) {
                        if (isRequired)
                            OptionBuilder.hasArgs();
                        else
                            OptionBuilder.hasOptionalArgs();
                    } else {
                        if (isRequired)
                            OptionBuilder.hasArgs(maxOccurs);
                        else
                            OptionBuilder.hasOptionalArgs(maxOccurs);
                    }

                    final char valueSeparator = argument.getValueSeparator() != null
                            ? argument.getValueSeparator().charAt(0)
                            : ' ';
                    OptionBuilder
                            .withArgName(formatArgumentName(argument.getLabel(), maxOccurs, valueSeparator));
                    OptionBuilder.withValueSeparator(valueSeparator);
                    if (option.getDescription() == null) {
                        logger.error("missing <description> for " + name + " option");
                        System.exit(1);
                    }

                    final StringBuilder description = new StringBuilder(option.getDescription());
                    if (option.getArgument().getDefault() != null)
                        description.append("\nDefault: ").append(option.getArgument().getDefault());

                    OptionBuilder.withDescription(description.toString());
                }

                apacheOptions.addOption(OptionBuilder.create(shortName));
            }
        }
    } else {
        cliArguments = null;
    }

    final Map<String, Option> optionsMap = new HashMap<>();
    final Set<String> specifiedLongNames;
    CommandLine commandLine = null;
    if (args != null && args.length != 0) {
        specifiedLongNames = new HashSet<>();
        final CommandLineParser parser = new PosixParser();
        do {
            try {
                commandLine = parser.parse(apacheOptions, args);
            } catch (final UnrecognizedOptionException e) {
                if (e.getMessage().startsWith("Unrecognized option: ")) {
                    final String unrecognizedOption = e.getMessage().substring(21);
                    logger.error("Unrecognized option: " + unrecognizedOption);
                    for (int i = 0; i < args.length; i++)
                        if (args[i].equals(unrecognizedOption))
                            args[i] = "--help";
                } else {
                    throw new IllegalArgumentException(e);
                }
            } catch (final org.apache.commons.cli.ParseException e) {
                Options.trapPrintHelp(apacheOptions, cliArguments, null, System.err);
            }
        } while (commandLine == null);
    } else {
        specifiedLongNames = null;
    }

    final Collection<String> arguments = commandLine != null ? commandLine.getArgList() : null;
    if (arguments != null && arguments.size() > 0) {
        if (argumentsMaxOccurs < arguments.size() || arguments.size() < argumentsMinOccurs) {
            Options.trapPrintHelp(apacheOptions, cliArguments, null, System.err);
        }
    } else if (argumentsMinOccurs > 0) {
        Options.trapPrintHelp(apacheOptions, cliArguments, null, System.err);
    }

    if (commandLine != null) {
        for (final org.apache.commons.cli.Option option : commandLine.getOptions()) {
            specifiedLongNames.add(option.getLongOpt());
            if ("help".equals(option.getLongOpt()))
                Options.trapPrintHelp(apacheOptions, cliArguments, null, System.out);

            final String optionName = option.getLongOpt() != null ? option.getLongOpt() : option.getOpt();
            optionsMap.put(optionName,
                    option.getValue() != null
                            ? new Option(optionName, option.getValueSeparator(), option.getValues())
                            : new Option(optionName, option.getValueSeparator(), "true"));
        }
    }

    // See if some arguments are missing
    if (requiredNames.size() != 0) {
        if (specifiedLongNames != null)
            requiredNames.removeAll(specifiedLongNames);

        if (requiredNames.size() != 0) {
            final StringBuilder builder = new StringBuilder();
            for (final String longName : requiredNames) {
                final String shortName = nameToAltName.get(longName);
                if (shortName.equals(longName))
                    builder.append("\nMissing argument: -").append(shortName);
                else
                    builder.append("\nMissing argument: -").append(shortName).append(",--").append(longName);
            }

            Options.trapPrintHelp(apacheOptions, cliArguments, builder.substring(1), System.out);
        }
    }

    // Include default values for options that are not specified
    if (binding.getOption() != null) {
        for (final Cli.Option option : binding.getOption()) {
            if (option.getArgument() != null && option.getArgument().getDefault() != null) {
                final String optionName = option.getName().getLong() != null ? option.getName().getLong()
                        : option.getName().getShort();
                if (!optionsMap.containsKey(optionName)) {
                    final String valueSeparator = option.getArgument().getValueSeparator();
                    final String defaultValue = option.getArgument().getDefault();
                    optionsMap.put(optionName,
                            valueSeparator != null
                                    ? new Option(optionName, valueSeparator.charAt(0), defaultValue)
                                    : new Option(optionName, defaultValue));
                }
            }
        }
    }

    // Check pattern for specified and default options
    if (binding.getOption() != null) {
        final StringBuilder builder = new StringBuilder();
        for (final Cli.Option option : binding.getOption()) {
            if (option.getArgument() != null && option.getArgument().getPattern() != null) {
                final String optionName = option.getName().getLong() != null ? option.getName().getLong()
                        : option.getName().getShort();
                final Option opt = optionsMap.get(optionName);
                if (opt != null) {
                    for (final String value : opt.getValues()) {
                        if (!value.matches(option.getArgument().getPattern())) {
                            if (option.getName().getLong() == null || option.getName().getShort() == null)
                                builder.append("\nIncorrect argument form: -").append(optionName);
                            else
                                builder.append("\nIncorrect argument form: -")
                                        .append(option.getName().getShort()).append(",--")
                                        .append(option.getName().getLong());

                            builder.append(' ').append(value).append("\n  Required: ")
                                    .append(option.getArgument().getPattern());
                        }
                    }
                }
            }
        }

        if (builder.length() > 0)
            Options.trapPrintHelp(apacheOptions, cliArguments, builder.substring(1), System.out);
    }

    return new Options(mainClass, args, optionsMap.values(), arguments == null || arguments.size() == 0 ? null
            : arguments.toArray(new String[arguments.size()]));
}

From source file:org.lib4j.cli.Options.java

public String getOption(final String name) {
    final Option options = optionNameToOption.get(name);
    if (options == null || options.getValues().length == 0)
        return null;

    if (options.getValues().length == 1)
        return options.getValues()[0];

    return Arrays.stream(options.getValues()).reduce(String.valueOf(options.getValueSeparator()),
            String::concat);//  w  w  w.  jav  a2s  . c  o  m
}