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

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

Introduction

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

Prototype

public String getOpt() 

Source Link

Document

Retrieve the name of this Option.

Usage

From source file:org.seedstack.seed.shell.internal.AbstractShell.java

@SuppressWarnings("unchecked")
protected Command createCommandAction(String qualifiedName, List<String> args) {
    if (Strings.isNullOrEmpty(qualifiedName)) {
        throw SeedException.createNew(ShellErrorCode.MISSING_COMMAND);
    }/*from www . j ava 2s  .co m*/

    String commandScope;
    String commandName;

    if (qualifiedName.contains(":")) {
        String[] splitName = qualifiedName.split(":");
        commandScope = splitName[0].trim();
        commandName = splitName[1].trim();
    } else {
        commandScope = null;
        commandName = qualifiedName.trim();
    }

    // Build CLI options
    Options options = new Options();
    for (org.seedstack.seed.core.spi.command.Option option : commandRegistry.getOptionsInfo(commandScope,
            commandName)) {
        options.addOption(option.name(), option.longName(), option.hasArgument(), option.description());
    }

    // Parse the command options
    CommandLine cmd;
    try {
        cmd = commandLineParser.parse(options, args.toArray(new String[args.size()]));
    } catch (ParseException e) {
        throw SeedException.wrap(e, ShellErrorCode.OPTIONS_SYNTAX_ERROR);
    }

    Map<String, String> optionValues = new HashMap<String, String>();
    for (Option option : cmd.getOptions()) {
        optionValues.put(option.getOpt(), option.getValue());
    }

    return commandRegistry.createCommand(commandScope, commandName, cmd.getArgList(), optionValues);
}

From source file:org.seedstack.shell.internal.AbstractShell.java

@SuppressWarnings("unchecked")
Command createCommandAction(String qualifiedName, List<String> args) {
    if (Strings.isNullOrEmpty(qualifiedName)) {
        throw SeedException.createNew(ShellErrorCode.MISSING_COMMAND);
    }//www .j  a  v  a  2 s.c om

    String commandScope;
    String commandName;

    if (qualifiedName.contains(":")) {
        String[] splitName = qualifiedName.split(":");
        commandScope = splitName[0].trim();
        commandName = splitName[1].trim();
    } else {
        commandScope = null;
        commandName = qualifiedName.trim();
    }

    // Build CLI options
    Options options = new Options();
    for (org.seedstack.seed.command.Option option : commandRegistry.getOptionsInfo(commandScope, commandName)) {
        options.addOption(option.name(), option.longName(), option.hasArgument(), option.description());
    }

    // Parse the command options
    CommandLine cmd;
    try {
        cmd = commandLineParser.parse(options, args.toArray(new String[args.size()]));
    } catch (ParseException e) {
        throw SeedException.wrap(e, ShellErrorCode.OPTIONS_SYNTAX_ERROR);
    }

    Map<String, String> optionValues = new HashMap<>();
    for (Option option : cmd.getOptions()) {
        optionValues.put(option.getOpt(), option.getValue());
    }

    return commandRegistry.createCommand(commandScope, commandName, cmd.getArgList(), optionValues);
}

From source file:org.semanticscience.PDBAptamerRetriever.main.RetrieveAptamers.java

private static void printUsage() {
    HelpFormatter hf = new HelpFormatter();
    hf.setOptionComparator(new Comparator() {
        private final String OPTS_ORDER = "helpgetallemmtcflrlffastaDirpdbDirpdbmlDirclickneedlegapOpengapExtend";

        public int compare(Object o1, Object o2) {
            Option opt1 = (Option) o1;
            Option opt2 = (Option) o2;
            return OPTS_ORDER.indexOf(opt1.getOpt()) - OPTS_ORDER.indexOf(opt2.getOpt());
        }/*ww w. ja v a  2 s . c  om*/
    });
    hf.printHelp("java -jar RetrieveAptamers.jar [OPTIONS]", createOptions());
}

From source file:org.shaf.core.process.cmd.CommandLineHandler.java

/**
 * Returns a {@link Process process} settings containing 'key/value' pairs,
 * where 'key' - name of the process class filed and 'value' - value to
 * which this field need to be set./*from   ww w .  ja  va  2 s .  co m*/
 * 
 * @param descr
 *            the process descriptor.
 * @param args
 *            the process arguments.
 * @return the process execution settings.
 * @throws ParseException
 *             if parsing of the command line has failed.
 */
public final static Properties getSettings(final DescriptionContent descr, final String[] args)
        throws ParseException {

    LOG.trace(Strings.repeat("=", 80));
    LOG.trace("| Block for converting the description content and arguments into");
    LOG.trace("| the settings object.");
    LOG.trace("| Content:   " + descr);
    LOG.trace("| Arguments: " + StringUtils.array2string(args));

    /*
     * Converts the process description into the command line options.
     */
    Options options = CommandOptionHandler.getOptions(descr);

    /*
     * Uses the obtained process options to parse command line arguments.
     */
    CommandLine line = new BasicParser().parse(options, args);

    /*
     * Creates process settings object.
     */
    Properties settings = new Properties();
    for (Object elm : options.getOptions()) {

        LOG.trace(Strings.repeat("-", 80));

        /*
         * Converts a single Option or OptionGroup into array of options.
         * Obviously is we converting a single option array will contain
         * only one element.
         */
        Option[] group = new Option[0];
        if (elm instanceof Option) {
            Option o = (Option) elm;
            group = ObjectArrays.concat(group, o);
        } else {
            OptionGroup og = (OptionGroup) elm;
            for (Object e : og.getOptions()) {
                Option o = (Option) e;
                group = ObjectArrays.concat(group, o);
            }
        }

        /*
         * Populates the process execution settings.
         */
        for (Option option : group) {
            LOG.trace("| Select option:   " + option);

            ResourceInfo resInfo = descr.getResourceInfo(option.getOpt());
            SingleOptionInfo optInfo = (SingleOptionInfo) resInfo.getOptionInfo();
            FieldInfo fldInfo = resInfo.getFieldInfo();

            LOG.trace("| Select resource: " + resInfo);

            String fldName = null;
            String fldValue = null;
            if (fldInfo == null) {
                fldName = optInfo.getName();
                if (!Strings.isNullOrEmpty(optInfo.getValue())) {
                    fldValue = line.getOptionValue(optInfo.getName(), optInfo.getValue());
                } else {
                    fldValue = line.getOptionValue(optInfo.getName());
                }
            } else {
                fldName = fldInfo.getName();
                if (boolean.class.getCanonicalName().equals(fldInfo.getType())
                        || Boolean.class.getCanonicalName().equals(fldInfo.getType())) {
                    fldValue = String.valueOf(line.hasOption(optInfo.getName()));
                } else {
                    if (!Strings.isNullOrEmpty(optInfo.getValue())) {
                        fldValue = line.getOptionValue(optInfo.getName(), optInfo.getValue());
                    } else {
                        fldValue = line.getOptionValue(optInfo.getName());
                    }
                }
            }

            if (fldValue != null) {
                settings.put(fldName + ".option", optInfo.getName());
                LOG.trace("| Set: " + fldName + ".option=" + optInfo.getName());

                settings.put(fldName + ".value", fldValue);
                LOG.trace("| Set: " + fldName + ".value=" + fldValue);
            }
        }
    }

    LOG.trace(Strings.repeat("=", 80));

    LOG.debug("Initialized the process settings: " + settings);

    return settings;
}

From source file:org.wildfly.security.tool.ElytronTool.java

/**
 * Main method to call from scripts.//from w w w.  ja v a 2 s .com
 *
 * @param args parameters to pass farther. The first parameter is name or alias of the command.
 */
public static void main(String[] args) {

    Security.addProvider(new WildFlyElytronProvider());

    ElytronTool tool = new ElytronTool();
    if (args != null && args.length > 0) {
        if (args[0].startsWith("{")) {
            tool.scriptName = args[0].substring(1, args[0].indexOf('}'));
            args[0] = args[0].substring(args[0].indexOf('}') + 1);
        }
        Command command = tool.findCommand(args[0]);
        if (command != null && tool.scriptName != null) {
            command.setToolCommand(tool.scriptName);
        }
        String[] newArgs = new String[args.length - 1];
        System.arraycopy(args, 1, newArgs, 0, args.length - 1);
        if (command != null && newArgs.length > 0) {
            try {
                command.execute(newArgs);
                System.exit(command.getStatus());
            } catch (Exception e) {
                if (e instanceof AlreadySelectedException) {
                    Option option = ((AlreadySelectedException) e).getOption();
                    System.err.println(ElytronToolMessages.msg.longOptionDescription(option.getOpt(),
                            option.getLongOpt()));
                }
                if (command.isEnableDebug()) {
                    System.err.println(ElytronToolMessages.msg.commandExecuteException());
                    e.printStackTrace(System.err);
                } else {
                    if (e.getLocalizedMessage() != null && (e.getLocalizedMessage().startsWith("ELYTOOL")
                            || e instanceof org.apache.commons.cli.ParseException)) {
                        System.err.println(ElytronToolMessages.msg.commandExecuteException());
                        System.err.println(e.getLocalizedMessage());
                    } else {
                        System.err.println(ElytronToolMessages.msg.commandExecuteExceptionNoDebug());
                    }
                }
                System.exit(command.getStatus());
            }
        } else if ("--help".equals(args[0]) || "-h".equals(args[0])) {
            tool.generalHelp();
        } else if (command != null) {
            command.help();
        } else {
            if (args[0].trim().isEmpty() && newArgs.length == 0) {
                tool.generalHelp();
            } else {
                System.err.println(ElytronToolMessages.msg.commandOrAliasNotFound(args[0]));
                System.exit(ElytronToolExitStatus_unrecognizedCommand);
            }
        }
    } else {
        // no arguments supplied, print general help message and exist.
        tool.generalHelp();
    }
}

From source file:org.wildfly.swarm.proc.Monitor.java

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

    Options options = new Options();

    options.addOption(Option.builder("b").longOpt("base").required(true)
            .desc("the WildFly Swarm examples directory").hasArg().build());

    options.addOption(Option.builder("a").longOpt("archive").required(false)
            .desc("the directory with previous performance results").hasArg().build());

    options.addOption(Option.builder("o").longOpt("output").required(false)
            .desc("the .csv file to store the current test results").hasArg().build());

    options.addOption(Option.builder("skip").longOpt("skip-tests").required(false)
            .desc("skip test execution phase").build());

    options.addOption(Option.builder("n").longOpt("number-iterations").required(false).hasArg()
            .desc("number of iterations per test").build());

    options.addOption(Option.builder("w").longOpt("workdir").required(true).hasArg()
            .desc("where to store testing artifacts").build());

    options.addOption(Option.builder("c").longOpt("comparison-csv").required(false).hasArg()
            .desc("the .csv file to store the comparison").build());

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = null;/*  w  w w  .j a v  a  2  s  .  c  om*/
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        usage(options);
    }

    for (Option opt : options.getOptions()) {
        if (opt.isRequired() && !cmd.hasOption(opt.getOpt())) {
            usage(options);
        }
    }

    // perform tests
    new Monitor(cmd).run();
}

From source file:org.zend.sdkcli.internal.commands.UsageCommand.java

private void printCommandUsage() {
    System.out.println("Usage:");
    System.out.println("  zend action [action options] [global options]");
    System.out.println();//from  www.j a v a 2 s  .  c om
    System.out.println("Global options:");

    final Options options = new Options();
    DetectOptionUtility.addOption(AbstractCommand.class, options, false);

    for (Object obj : options.getOptions()) {
        Option o = (Option) obj;
        System.out.printf("  -%-3s %s\n", o.getOpt(), o.getDescription());
    }
    System.out.println();
    System.out.println("Valid actions are composed of a verb and an optional direct object:");
}

From source file:org.zend.sdkcli.internal.commands.UsageCommand.java

private void printCommandOptions(CommandType type) {
    Options opts = new Options();
    System.out.println();//w  w  w  .  j  a va 2  s .c  o m

    // get command specific options
    DetectOptionUtility.addOption(CommandFactory.createCommand(type).getClass(), opts, true);

    if (opts.getOptions().size() > 0) {
        System.out.println("Options:");
        Collection collection = opts.getOptions();
        for (Object o : collection) {
            Option opt = (Option) o;
            System.out.printf("  -%-3s %s%s\n", opt.getOpt(), opt.getDescription(),
                    opt.isRequired() ? " [required]" : "");
        }
    } else {
        System.out.println("  No options");
    }

    System.out.println();
}

From source file:oxis.yologp.CommandLineMain.java

public void printHelp() {

    for (Object obj : options.getOptions().toArray(new Option[0])) {
        Option opt = (Option) obj;
        System.out.println(//from w  w w . j  ava  2 s .  co m
                String.format("  -%s|--%-30s ", opt.getOpt(), opt.getLongOpt()) + opt.getDescription());
    }
    System.exit(0);
}

From source file:pl.nask.hsn2.GenericCmdParams.java

private void printOptions() {
    Option[] opts = cmd.getOptions();
    for (Option op : opts) {
        LOGGER.info("Command line option: {}. Value from command line: {}, default value={}",
                new Object[] { op.getOpt(), op.getValue(), getDefaultValue(op.getOpt()) });
    }/*w  w w  .  j a v a2 s .c  o m*/
}