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

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

Introduction

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

Prototype

public boolean hasOptionalArg() 

Source Link

Usage

From source file:de.hsos.ecs.richwps.wpsmonitor.boundary.cli.command.CommandFormatter.java

private String decorateArg(final Option opt) {
    final StringBuilder strBuilder = new StringBuilder();

    if (opt.hasArg()) {
        if (opt.hasOptionalArg()) {
            strBuilder.append("[");
        }//from  w w w. ja v a2  s .  c  om

        strBuilder.append("=").append("<").append(opt.getArgName()).append(">");

        if (opt.hasOptionalArg()) {
            strBuilder.append("]");
        }
    }

    return strBuilder.toString();
}

From source file:net.nicholaswilliams.java.licensing.licensor.interfaces.cli.spi.TestCliOptionsBuilder.java

@Test
public void testHasOptionalArg() {
    Option option = this.builder.hasOptionalArg().create("test");
    assertNotNull("The option should not be null.", option);
    assertTrue("hasOptionalArg should be true.", option.hasOptionalArg());
}

From source file:net.nicholaswilliams.java.licensing.licensor.interfaces.cli.spi.TestCliOptionsBuilder.java

@Test
public void testHasOptionalArgs() {
    Option option = this.builder.hasOptionalArgs().create("test");
    assertNotNull("The option should not be null.", option);
    assertTrue("hasOptionalArg should be true.", option.hasOptionalArg());
    assertEquals("getArgs is not correct.", -2, option.getArgs());
}

From source file:net.nicholaswilliams.java.licensing.licensor.interfaces.cli.spi.TestCliOptionsBuilder.java

@Test
public void testHasOptionalArgsIntArg() {
    Option option = this.builder.hasOptionalArgs(9).create("test");
    assertNotNull("The option should not be null.", option);
    assertTrue("hasOptionalArg should be true.", option.hasOptionalArg());
    assertEquals("getArgs is not correct.", 9, option.getArgs());
}

From source file:com.marklogic.contentpump.utilities.CommandlineOption.java

public CommandlineOption(Option opt) throws IllegalArgumentException {
    super(opt.getOpt(), opt.hasArg(), opt.getDescription());

    this.setLongOpt(opt.getLongOpt());
    this.setRequired(opt.isRequired());
    this.setArgName(opt.getArgName());
    this.setArgs(opt.getArgs());
    this.setOptionalArg(opt.hasOptionalArg());
    this.setType(opt.getType());
    this.setValueSeparator(opt.getValueSeparator());
}

From source file:ch.cyberduck.cli.TerminalOptionsInputValidator.java

public boolean validate(final CommandLine input) {
    for (Option o : input.getOptions()) {
        if (Option.UNINITIALIZED == o.getArgs()) {
            continue;
        }/*from  ww w . j  ava2s .c o m*/
        if (o.hasOptionalArg()) {
            continue;
        }
        if (o.getArgs() != o.getValuesList().size()) {
            console.printf("Missing argument for option %s%n", o.getLongOpt());
            return false;
        }
    }
    final TerminalAction action = TerminalActionFinder.get(input);
    if (null == action) {
        console.printf("%s%n", "Missing argument");
        return false;
    }
    if (input.hasOption(TerminalOptionsBuilder.Params.existing.name())) {
        final String arg = input.getOptionValue(TerminalOptionsBuilder.Params.existing.name());
        if (null == TransferAction.forName(arg)) {
            final Set<TransferAction> actions = new HashSet<TransferAction>(
                    TransferAction.forTransfer(Transfer.Type.download));
            actions.add(TransferAction.cancel);
            console.printf("Invalid argument '%s' for option %s. Must be one of %s%n", arg,
                    TerminalOptionsBuilder.Params.existing.name(), Arrays.toString(actions.toArray()));
            return false;
        }
        switch (action) {
        case download:
            if (!validate(arg, Transfer.Type.download)) {
                return false;
            }
            break;
        case upload:
            if (!validate(arg, Transfer.Type.upload)) {
                return false;
            }
            break;
        case synchronize:
            if (!validate(arg, Transfer.Type.sync)) {
                return false;
            }
            break;
        case copy:
            if (!validate(arg, Transfer.Type.copy)) {
                return false;
            }
            break;
        }
    }
    // Validate arguments
    switch (action) {
    case list:
    case download:
        if (!validate(input.getOptionValue(action.name()))) {
            return false;
        }
        break;
    case upload:
    case copy:
    case synchronize:
        if (!validate(input.getOptionValue(action.name()))) {
            return false;
        }
        break;
    }
    return true;
}

From source file:com.github.lindenb.jvarkit.util.command.CommandFactory.java

public int instanceMain(final String args[]) {
    /* create a new  empty Command  */
    Command cmd = null;/*from   www . j  a v  a2 s. c o m*/

    try {
        /* cmd line */
        final StringBuilder sb = new StringBuilder();
        for (String s : args) {
            if (sb.length() != 0)
                sb.append(" ");
            sb.append(s);
        }
        /* create new options  */
        final Options options = new Options();
        /* get all options and add it to options  */
        fillOptions(options);
        /* create a new CLI parser */
        final CommandLineParser parser = new DefaultParser();
        final CommandLine cli = parser.parse(options, args);

        /* loop over the processed options */
        for (final Option opt : cli.getOptions()) {
            if (opt.hasArg() && !opt.hasOptionalArg() && opt.getValue() == null) {
                LOG.warn("OPTION ####" + opt);
            }
            final Status status = visit(opt);
            switch (status) {
            case EXIT_FAILURE:
                return -1;
            case EXIT_SUCCESS:
                return 0;
            default:
                break;
            }
        }
        cmd = createCommand();

        final Date startDate = new Date();
        LOG.info("Starting JOB at " + startDate + " " + getClass().getName() + " version=" + getVersion() + " "
                + " built=" + getCompileDate());
        LOG.info("Command Line args : "
                + (cmd.getProgramCommandLine().isEmpty() ? "(EMPTY/NO-ARGS)" : cmd.getProgramCommandLine()));
        String hostname = "";
        try {
            hostname = InetAddress.getLocalHost().getHostName();
        } catch (Exception err) {
            hostname = "host";
        }
        LOG.info("Executing as " + System.getProperty("user.name") + "@" + hostname + " on "
                + System.getProperty("os.name") + " " + System.getProperty("os.version") + " "
                + System.getProperty("os.arch") + "; " + System.getProperty("java.vm.name") + " "
                + System.getProperty("java.runtime.version"));

        LOG.debug("initialize " + cmd);
        final Collection<Throwable> initErrors = cmd.initializeKnime();
        if (!(initErrors == null || initErrors.isEmpty())) {
            for (Throwable err : initErrors) {
                LOG.error(err);
            }
            LOG.fatal("Command initialization failed ");
            return -1;
        }

        LOG.debug("calling " + cmd);
        final Collection<Throwable> errors = cmd.call();
        if (!(errors == null || errors.isEmpty())) {
            for (Throwable err : errors) {
                LOG.error(err);
            }
            LOG.fatal("Command failed ");
            return -1;
        }
        LOG.debug("success " + cmd);
        cmd.disposeKnime();
        final Date endDate = new Date();
        final double elapsedMinutes = (endDate.getTime() - startDate.getTime()) / (1000d * 60d);
        final String elapsedString = new DecimalFormat("#,##0.00").format(elapsedMinutes);
        LOG.info("End JOB  [" + endDate + "] " + getName() + " done. Elapsed time: " + elapsedString
                + " minutes.");
        return 0;
    } catch (org.apache.commons.cli.UnrecognizedOptionException err) {
        LOG.fatal("Unknown command (" + err.getOption() + ") , please check your input.", err);
        return -1;
    } catch (Throwable err) {
        LOG.fatal("cannot build command", err);
        return -1;
    } finally {
        if (cmd != null)
            cmd.cleanup();
    }
}

From source file:com.github.lindenb.jvarkit.util.command.Command.java

public int instanceMainWithExceptions(final String args[], final List<Throwable> putExceptionsHere) {
    try {/*  w w w  .  j a  v a 2  s . c  o m*/
        /* cmd line */
        final StringBuilder sb = new StringBuilder();
        for (String s : args) {
            if (sb.length() != 0)
                sb.append(" ");
            sb.append(s);
        }
        this.programCommandLine = sb.toString().replace('\n', ' ').replace('\t', ' ').replace('\"', ' ')
                .replace('\'', ' ');

        /* create new options  */
        final Options options = new Options();
        /* get all options and add it to options  */
        LOG.debug("creating options");
        fillOptions(options);
        /* create a new CLI parser */
        LOG.debug("parsing options");
        final CommandLineParser parser = new DefaultParser();
        this._cliCommand = parser.parse(options, args);
        this.setInputFiles(this._cliCommand.getArgList());

        /* loop over the processed options */
        for (final Option opt : this._cliCommand.getOptions()) {
            if (opt.hasArg() && !opt.hasOptionalArg() && opt.getValue() == null) {
                LOG.info("WARNING OPTION ####" + opt + " with null value ??");
            }
            final Status status = visit(opt);
            switch (status) {
            case EXIT_FAILURE:
                return -1;
            case EXIT_SUCCESS:
                return 0;
            default:
                break;
            }
        }

        final Date startDate = new Date();
        LOG.info("Starting JOB at " + startDate + " " + getClass().getName() + " version=" + getVersion() + " "
                + " built=" + getCompileDate());
        LOG.info("Command Line args : "
                + (this.getProgramCommandLine().isEmpty() ? "(EMPTY/NO-ARGS)" : this.getProgramCommandLine()));
        String hostname = "";
        try {
            hostname = InetAddress.getLocalHost().getHostName();
        } catch (Exception err) {
            hostname = "host";
        }
        LOG.info("Executing as " + System.getProperty("user.name") + "@" + hostname + " on "
                + System.getProperty("os.name") + " " + System.getProperty("os.version") + " "
                + System.getProperty("os.arch") + "; " + System.getProperty("java.vm.name") + " "
                + System.getProperty("java.runtime.version"));

        LOG.debug("initialize");
        final Collection<Throwable> initErrors = this.initializeKnime();
        if (!(initErrors == null || initErrors.isEmpty())) {
            putExceptionsHere.addAll(initErrors);
            for (Throwable err : initErrors) {
                LOG.error(err.getMessage());
            }
            LOG.error("Command initialization failed ");
            return -1;
        }
        LOG.debug("calling");
        final Collection<Throwable> errors = this.call();
        if (!(errors == null || errors.isEmpty())) {
            putExceptionsHere.addAll(initErrors);
            for (Throwable err : errors) {
                LOG.error(err.getMessage());
            }
            LOG.error("Command failed ");
            return -1;
        }
        LOG.debug("success ");
        this.disposeKnime();
        final Date endDate = new Date();
        final double elapsedMinutes = (endDate.getTime() - startDate.getTime()) / (1000d * 60d);
        final String elapsedString = new DecimalFormat("#,##0.00").format(elapsedMinutes);
        LOG.info("End JOB  [" + endDate + "] " + getName() + " done. Elapsed time: " + elapsedString
                + " minutes.");
        return 0;
    } catch (org.apache.commons.cli.UnrecognizedOptionException err) {
        LOG.error("Unknown command (" + err.getOption() + ") , please check your input.", err);
        return -1;
    } catch (Throwable err) {
        LOG.error("cannot execute command", err);
        return -1;
    } finally {
        this.disposeKnime();
    }
}

From source file:de.uni_koblenz.ist.utilities.option_handler.OptionHandler.java

/**
 * Used by the method getUsageString for adding an Option to the String.
 * //from   ww w.  j a va  2s.c o  m
 * @param out
 *            The StringBuilder to write into.
 * @param current
 *            The option to add.
 */
private void appendOption(StringBuilder out, Option current) {
    out.append("-");
    out.append(current.getOpt());
    int numberOfArgs = current.getArgs();
    out.append(" ");
    if (current.hasOptionalArg()) {
        out.append("[");
    }
    if (numberOfArgs == Option.UNLIMITED_VALUES) {
        appendArgName(out, current);
        out.append("{");
        out.append(current.getValueSeparator());
        appendArgName(out, current);
        out.append("}");
    }
    if (numberOfArgs >= 1) {
        appendArgName(out, current);
        for (int i = 1; i < numberOfArgs; i++) {
            out.append(current.getValueSeparator());
            appendArgName(out, current);
        }
    }
    if (current.hasOptionalArg()) {
        out.append("]");
    }
}

From source file:com.cloudera.sqoop.cli.SqoopParser.java

@Override
/**// w w  w  .  j  a v  a 2 s. c  o  m
 * Processes arguments to options but only strips matched quotes.
 */
public void processArgs(Option opt, ListIterator iter) throws ParseException {
    // Loop until an option is found.
    while (iter.hasNext()) {
        String str = (String) iter.next();

        if (getOptions().hasOption(str) && str.startsWith("-")) {
            // found an Option, not an argument.
            iter.previous();
            break;
        }

        // Otherwise, this is a value.
        try {
            // Note that we only strip matched quotes here.
            addValForProcessing.invoke(opt, stripMatchedQuotes(str));
        } catch (IllegalAccessException iae) {
            throw new RuntimeException(iae);
        } catch (java.lang.reflect.InvocationTargetException ite) {
            // Any runtime exception thrown within addValForProcessing()
            // will be wrapped in an InvocationTargetException.
            iter.previous();
            break;
        } catch (RuntimeException re) {
            iter.previous();
            break;
        }
    }

    if (opt.getValues() == null && !opt.hasOptionalArg()) {
        throw new MissingArgumentException(opt);
    }
}