Example usage for org.apache.commons.cli CommandLine getOptions

List of usage examples for org.apache.commons.cli CommandLine getOptions

Introduction

In this page you can find the example usage for org.apache.commons.cli CommandLine getOptions.

Prototype

public Option[] getOptions() 

Source Link

Document

Returns an array of the processed Option s.

Usage

From source file:org.jf.smali.main.java

/**
 * Run!//from  w w w  .j a  v a 2s . c o m
 */
public static void main(String[] args) {
    Locale locale = new Locale("en", "US");
    Locale.setDefault(locale);

    CommandLineParser parser = new PosixParser();
    CommandLine commandLine;

    try {
        commandLine = parser.parse(options, args);
    } catch (ParseException ex) {
        usage();
        return;
    }

    int jobs = -1;
    boolean allowOdex = false;
    boolean verboseErrors = false;
    boolean printTokens = false;

    int apiLevel = 15;

    String outputDexFile = "out.dex";

    String[] remainingArgs = commandLine.getArgs();

    Option[] options = commandLine.getOptions();

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

        switch (opt.charAt(0)) {
        case 'v':
            version();
            return;
        case '?':
            while (++i < options.length) {
                if (options[i].getOpt().charAt(0) == '?') {
                    usage(true);
                    return;
                }
            }
            usage(false);
            return;
        case 'o':
            outputDexFile = commandLine.getOptionValue("o");
            break;
        case 'x':
            allowOdex = true;
            break;
        case 'a':
            apiLevel = Integer.parseInt(commandLine.getOptionValue("a"));
            break;
        case 'j':
            jobs = Integer.parseInt(commandLine.getOptionValue("j"));
            break;
        case 'V':
            verboseErrors = true;
            break;
        case 'T':
            printTokens = true;
            break;
        default:
            assert false;
        }
    }

    if (remainingArgs.length == 0) {
        usage();
        return;
    }

    try {
        LinkedHashSet<File> filesToProcess = new LinkedHashSet<File>();

        for (String arg : remainingArgs) {
            File argFile = new File(arg);

            if (!argFile.exists()) {
                throw new RuntimeException("Cannot find file or directory \"" + arg + "\"");
            }

            if (argFile.isDirectory()) {
                getSmaliFilesInDir(argFile, filesToProcess);
            } else if (argFile.isFile()) {
                filesToProcess.add(argFile);
            }
        }

        if (jobs <= 0) {
            jobs = Runtime.getRuntime().availableProcessors();
            if (jobs > 6) {
                jobs = 6;
            }
        }

        boolean errors = false;

        final DexBuilder dexBuilder = DexBuilder.makeDexBuilder(apiLevel);
        ExecutorService executor = Executors.newFixedThreadPool(jobs);
        List<Future<Boolean>> tasks = Lists.newArrayList();

        final boolean finalVerboseErrors = verboseErrors;
        final boolean finalPrintTokens = printTokens;
        final boolean finalAllowOdex = allowOdex;
        final int finalApiLevel = apiLevel;
        for (final File file : filesToProcess) {
            tasks.add(executor.submit(new Callable<Boolean>() {
                @Override
                public Boolean call() throws Exception {
                    return assembleSmaliFile(file, dexBuilder, finalVerboseErrors, finalPrintTokens,
                            finalAllowOdex, finalApiLevel);
                }
            }));
        }

        for (Future<Boolean> task : tasks) {
            while (true) {
                try {
                    if (!task.get()) {
                        errors = true;
                    }
                } catch (InterruptedException ex) {
                    continue;
                }
                break;
            }
        }

        executor.shutdown();

        if (errors) {
            System.exit(1);
        }

        dexBuilder.writeTo(new FileDataStore(new File(outputDexFile)));
    } catch (RuntimeException ex) {
        System.err.println("\nUNEXPECTED TOP-LEVEL EXCEPTION:");
        ex.printStackTrace();
        System.exit(2);
    } catch (Throwable ex) {
        System.err.println("\nUNEXPECTED TOP-LEVEL ERROR:");
        ex.printStackTrace();
        System.exit(3);
    }
}

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

private boolean processCommandLines(String[] args) throws Throwable {

    Options options = new Options();
    options.addOption("?", "help", false, null);
    options.addOption("h", "host", true, null);
    options.addOption("p", "port", true, null);
    options.addOption("t", "timeout", true, null);
    options.addOption("f", "file", false, null);

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

    Option[] opts = line.getOptions();
    for (Option option : opts) {
        String opt = option.getOpt();
        if (opt.equals("?")) {
            printHelp();//from  w  w  w.ja v  a 2s  .  com
            return false;
        } else if (opt.equals("h")) {
            String v = option.getValue();
            if (v != null)
                RuyiCli.INST.host(v);
        } else if (opt.equals("p")) {
            String v = option.getValue();
            if (v != null)
                RuyiCli.INST.port(Integer.parseInt(v));
        } else if (opt.equals("t")) {
            String v = option.getValue();
            if (v != null)
                RuyiCli.INST.timeout(Integer.parseInt(v) * 1000);
        } else if (opt.equals("f")) {
            args = line.getArgs();
            if (args == null || args.length < 1)
                System.out.println("Please specify SCRIPT.");
            else
                RuyiCli.INST.run(args);

            return false;
        } else
            throw new Exception("Unknown option: " + option);
    }

    args = line.getArgs();
    if (args == null || args.length < 1)
        return true;

    String command = args[0];
    int n = args.length;
    if (n > 1) {
        StringBuilder builder = new StringBuilder(256);
        builder.append(command);
        for (int i = 1; i < n; ++i)
            builder.append(' ').append(args[i]);
        command = builder.toString();
    }

    RuyiCli.INST.run(command);
    return false;
}

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 ava2 s  .c  om
    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);/*w w w .  jav  a  2s .  c  o  m*/
    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.ldaptive.cli.AbstractCli.java

/**
 * Reads the options from the supplied command line and returns a properties
 * containing those options./*w  w  w. j  a  va2s  .  c  om*/
 *
 * @param  domain  to place property names in
 * @param  line  command line
 *
 * @return  properties for each option and value
 */
protected Properties getPropertiesFromOptions(final String domain, final CommandLine line) {
    final Properties props = new Properties();
    for (Option o : line.getOptions()) {
        if (o.hasArg()) {
            // if provider property, split the value
            // else add the domain to the ldaptive properties
            if (o.getOpt().equals(OPT_PROVIDER_PROPERTIES)) {
                final String[] s = o.getValue().split("=");
                props.setProperty(s[0], s[1]);
            } else {
                props.setProperty(domain + o.getOpt(), o.getValue());
            }
        }
    }
    return props;
}

From source file:org.LexGrid.LexBIG.admin.ListExtensions.java

/**
 * Primary entry point for the program.//from   www . j  ava  2 s.  c  om
 * 
 * @throws Exception
 */
public void run(String[] args) throws Exception {
    synchronized (ResourceManager.instance()) {

        // Parse the command line ...
        CommandLine cl = null;
        Options options = getCommandOptions();
        try {
            cl = new BasicParser().parse(options, args);
        } catch (ParseException e) {
            Util.displayCommandOptions("ListExtensions", options, "ListExtensions -a", e);
            return;
        }

        // Interpret provided values ...
        boolean listAll = cl.hasOption("a") || cl.getOptions().length == 0;
        LexBIGService lbs = LexBIGServiceImpl.defaultInstance();
        LexBIGServiceManager lbsm = lbs.getServiceManager(null);

        // Generic extensions ...
        if (listAll || cl.hasOption("g")) {
            list("GENERIC EXTENSIONS", lbs.getGenericExtensions().enumerateExtensionDescription());
        }
        // Index extensions ...
        if (listAll || cl.hasOption("i")) {
            list("INDEX EXTENSIONS (NOTE: DOES NOT INCLUDE BUILT-IN INDICES REQUIRED BY THE RUNTIME)",
                    lbsm.getIndexExtensions().enumerateExtensionDescription());
        }
        // Match algorithms ...
        if (listAll || cl.hasOption("m")) {
            list("MATCH ALGORITHMS", lbs.getMatchAlgorithms().enumerateModuleDescription());
        }
        // Filter algorithms ...
        if (listAll || cl.hasOption("f")) {
            list("MATCH ALGORITHMS", lbs.getFilterExtensions().enumerateExtensionDescription());
        }
        // Sort algorithms ...
        if (listAll || cl.hasOption("s")) {
            list("SORT ALGORITHMS", lbs.getSortAlgorithms(null).enumerateSortDescription());
        }
    }
}

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);/* w w w . j  a v  a 2  s. c  o 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.libx4j.cli.Options.java

public static Options parse(final cli_cli binding, final Class<?> mainClass, final String[] args)
        throws OptionsException {
    final Set<String> requiredNames = new HashSet<String>();
    final Map<String, String> nameToAltName = new HashMap<String, String>();
    final org.apache.commons.cli.Options apacheOptions = new org.apache.commons.cli.Options();
    apacheOptions.addOption(null, "help", false, "Print help and usage.");
    int argumentsMinOccurs = 0;
    int argumentsMaxOccurs = 0;
    final cli_cli._arguments cliArguments;
    if (binding != null) {
        cliArguments = binding._arguments(0);
        if (!cliArguments.isNull()) {
            argumentsMinOccurs = cliArguments._minOccurs$().text();
            argumentsMaxOccurs = "unbounded".equals(cliArguments._maxOccurs$().text()) ? Integer.MAX_VALUE
                    : Integer.parseInt(cliArguments._maxOccurs$().text());
            if (argumentsMaxOccurs < argumentsMinOccurs) {
                logger.error("minOccurs > maxOccurs on <arguments> element");
                System.exit(1);//from w  w  w  .  j  a  va 2 s  .com
            }
        }

        if (binding._option() != null) {
            for (final cli_cli._option option : binding._option()) {
                final cli_cli._option._name optionName = option._name(0);
                final String longName = optionName._long$().isNull() ? null : optionName._long$().text();
                final String shortName = optionName._short$().isNull() ? null : optionName._short$().text();
                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._argument() != null && option._argument().size() != 0) {
                    final cli_cli._option._argument argument = option._argument(0);
                    final boolean isRequired = $cli_use.required.text().equals(argument._use$().text());
                    if (isRequired) {
                        OptionBuilder.isRequired();
                        requiredNames.add(longName);
                    }

                    final int maxOccurs = argument._maxOccurs$().isNull() ? 1
                            : "unbounded".equals(argument._maxOccurs$().text()) ? Integer.MAX_VALUE
                                    : Integer.parseInt(argument._maxOccurs$().text());
                    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._valueSeparator$().text() != null
                            ? argument._valueSeparator$().text().charAt(0)
                            : ' ';
                    OptionBuilder.withArgName(
                            formatArgumentName(argument._label$().text(), maxOccurs, valueSeparator));
                    OptionBuilder.withValueSeparator(valueSeparator);
                    if (option._description(0).isNull()) {
                        logger.error("missing <description> for " + name + " option");
                        System.exit(1);
                    }

                    final StringBuilder description = new StringBuilder(option._description(0).text());
                    if (!option._argument(0)._default$().isNull())
                        description.append("\nDefault: ").append(option._argument(0)._default$().text());

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

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

    final Map<String, Option> optionsMap = new HashMap<String, Option>();
    final Set<String> specifiedLongNames;
    CommandLine commandLine = null;
    if (args != null && args.length != 0) {
        specifiedLongNames = new HashSet<String>();
        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 OptionsException(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._option() != null) {
        for (final cli_cli._option option : binding._option()) {
            if (!option._argument(0)._default$().isNull()) {
                final String optionName = !option._name(0)._long$().isNull() ? option._name(0)._long$().text()
                        : option._name(0)._short$().text();
                if (!optionsMap.containsKey(optionName)) {
                    final String valueSeparator = option._argument(0)._valueSeparator$().text();
                    final String defaultValue = option._argument(0)._default$().text();
                    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._option() != null) {
        final StringBuilder builder = new StringBuilder();
        for (final cli_cli._option option : binding._option()) {
            if (!option._argument(0)._pattern$().isNull()) {
                final String optionName = !option._name(0)._long$().isNull() ? option._name(0)._long$().text()
                        : option._name(0)._short$().text();
                final Option opt = optionsMap.get(optionName);
                if (opt != null) {
                    for (final String value : opt.getValues()) {
                        if (!value.matches(option._argument(0)._pattern$().text())) {
                            if (option._name(0)._long$().isNull() || option._name(0)._short$().isNull())
                                builder.append("\nIncorrect argument form: -").append(optionName);
                            else
                                builder.append("\nIncorrect argument form: -")
                                        .append(option._name(0)._short$().text()).append(",--")
                                        .append(option._name(0)._long$().text());

                            builder.append(" ").append(value).append("\n  Required: ")
                                    .append(option._argument(0)._pattern$().text());
                        }
                    }
                }
            }
        }

        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.lsc.opendj.LdapServer.java

private static void parseOptionsForConfiguration(String[] args) {
    try {/*from   w  w w. ja  v a  2s  .  c o  m*/
        CommandLine cmdLine = getOptionsCmdLine(args);

        if (cmdLine.getOptions().length > 0 && !cmdLine.hasOption("h")) {
            if (cmdLine.hasOption("f")) {
                Configuration.setUp(new File(cmdLine.getOptionValue("f")).getAbsolutePath(), false);
            }
        } else {
            printHelp(options);
        }
    } catch (ParseException e) {
        if (LOGGER.isErrorEnabled()) {
            StringBuilder sbf = new StringBuilder();
            for (String arg : args) {
                sbf.append(arg).append(" ");
            }
            LOGGER.error("Unable to parse options : {}({})", sbf.toString(), e);
        }
        LOGGER.debug(e.toString(), e);
    } catch (LscException e) {
        LOGGER.warn("Error while loading configuration: " + e.toString());
    }
}

From source file:org.lsc.opendj.LdapServer.java

/**
 * Manage command line options//from   w  ww .j  a v  a2  s . c  om
 * @param args command line
 * @return the status code (0: OK, >=1 : failed)
 * @throws Exception 
 */
private static int usage(String[] args) throws Exception {
    try {
        CommandLine cmdLine = getOptionsCmdLine(args);

        if (cmdLine.getOptions().length > 0 && !cmdLine.hasOption("h")) {
            if (cmdLine.hasOption("a")) {
                start();
            } else if (cmdLine.hasOption("o")) {
                stop();
            }
        } else {
            printHelp(options);
            return 1;
        }
    } catch (ParseException e) {
        if (LOGGER.isErrorEnabled()) {
            StringBuilder sbf = new StringBuilder();
            for (String arg : args) {
                sbf.append(arg).append(" ");
            }
            LOGGER.error("Unable to parse options : {}({})", sbf.toString(), e);
        }
        LOGGER.debug(e.toString(), e);
        return 1;
    }
    return 0;
}