Example usage for org.apache.commons.cli OptionBuilder withDescription

List of usage examples for org.apache.commons.cli OptionBuilder withDescription

Introduction

In this page you can find the example usage for org.apache.commons.cli OptionBuilder withDescription.

Prototype

public static OptionBuilder withDescription(String newDescription) 

Source Link

Document

The next Option created will have the specified description

Usage

From source file:org.hammurapi.HammurapiArchiver.java

/**
 * Use it for inspector debugging/*from w ww .  j av a 2 s  . c  o m*/
 * @param args
 */
public static void main(String[] args) {
    System.out.println("Hammurapi 3.18.4 Copyright (C) 2004 Hammurapi Group");

    Options options = new Options();

    Option classPathOption = OptionBuilder.withArgName("classpath").hasArg().withDescription("ClassPath")
            .isRequired(false).create("c");

    options.addOption(classPathOption);

    Option hostIdOption = OptionBuilder.withArgName("hostId").hasArg().withDescription("Host id")
            .isRequired(false).create("H");

    options.addOption(hostIdOption);

    Option titleOption = OptionBuilder.withArgName("title").hasArg().withDescription("Report title")
            .isRequired(false).create("T");

    options.addOption(titleOption);

    Option baseLineOption = OptionBuilder.withDescription("Baseline date").withArgName("date").hasArg()
            .isRequired(false).create("n");

    options.addOption(baseLineOption);

    Option forceOption = OptionBuilder.withDescription("Force reviews on unchanged files").isRequired(false)
            .create("f");

    options.addOption(forceOption);

    Option forceOnWarningsOption = OptionBuilder.withDescription("Do not force reviews of files with warnings")
            .isRequired(false).create("k");

    options.addOption(forceOnWarningsOption);

    Option descriptionOption = OptionBuilder.withDescription("Review description").withArgName("description")
            .hasArg().isRequired(false).create("y");
    options.addOption(descriptionOption);

    //Anu :20050701 Added baselining parameter
    Option baseliningOption = OptionBuilder.withArgName("off|on|set").hasArg()
            .withDescription("Baselining mode").isRequired(false).create("B");

    options.addOption(descriptionOption);

    Option helpOption = OptionBuilder.withDescription("Print this message").isRequired(false).create("h");
    options.addOption(helpOption);

    CommandLineParser parser = new PosixParser();
    CommandLine line = null;
    try {
        line = parser.parse(options, args);
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        System.err.flush();
        printHelpAndExit(options);
    }

    if (line.hasOption("h")) {
        printHelpAndExit(options);
    }

    HammurapiArchiver task = new HammurapiArchiver();
    Project project = new Project();
    task.setProject(project);
    project.setCoreLoader(task.getClass().getClassLoader());

    String[] values = line.getOptionValues('c');
    for (int i = 0; values != null && i < values.length; i++) {
        task.createClasspath().append(new Path(project, values[i]));
    }

    String[] largs = line.getArgs();
    if (largs.length == 0) {
        System.out.println("Output file has to be provided");
        printHelpAndExit(options);
    }

    if (line.hasOption('f')) {
        task.setForce(true);
    }

    if (line.hasOption('k')) {
        task.setForceOnWarnings(false);
    }

    if (line.hasOption('n')) {
        task.setBaseLine(new Date(line.getOptionValue('n')));
    }

    if (line.hasOption('H')) {
        task.setHostId(line.getOptionValue('H'));
    }

    if (line.hasOption('y')) {
        task.setReviewDescription(line.getOptionValue('y'));
    }

    if (line.hasOption('T')) {
        task.setTitle(line.getOptionValue('T'));
    }

    //Anu :20050701 Added for Baselining attribute
    if (line.hasOption('B')) {
        task.setBaselining(line.getOptionValue('B'));
    }

    task.setOutput(new File(largs[0]));

    for (int i = 1; i < largs.length; i++) {
        File file = new File(largs[i]);
        if (file.isFile()) {
            task.srcFiles.add(file);
        } else if (file.isDirectory()) {
            task.createSrc().setDir(file);
        }
    }

    task.setTaskName("har");

    try {
        task.execute();
        System.exit(0);
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(2);
    }
}

From source file:org.hammurapi.HammurapiTask.java

/**
 * @param options/*from  www  .  ja v a2 s. co m*/
 */
protected static void populateOptions(Options options) {
    TaskBase.populateOptions(options);

    Option hostIdOption = OptionBuilder.withArgName("hostId").hasArg().withDescription("Host id")
            .isRequired(false).create("H");

    options.addOption(hostIdOption);

    //Anu 20050701 : Moved to TaskBase.java
    //        Option baseliningOption=OptionBuilder
    //        .withArgName("off|on|set")
    //        .hasArg()
    //        .withDescription("Baselining mode")
    //        .isRequired(false)
    //        .create("B");

    //        options.addOption(baseliningOption);

    Option serverOption = OptionBuilder.withDescription("Database server name").withArgName("database server")
            .hasArg().isRequired(false).create("R");

    options.addOption(serverOption);

    Option driverClassOption = OptionBuilder.withDescription("Database driver class").withArgName("class name")
            .hasArg().isRequired(false).create("L");

    options.addOption(driverClassOption);

    Option connectionUrlOption = OptionBuilder.withDescription("Database connection URL").withArgName("url")
            .hasArg().isRequired(false).create("N");

    options.addOption(connectionUrlOption);

    Option userOption = OptionBuilder.withDescription("Database user").withArgName("user name").hasArg()
            .isRequired(false).create("j");

    options.addOption(userOption);

    Option passwordOption = OptionBuilder.withDescription("Database password").withArgName("password").hasArg()
            .isRequired(false).create("p");

    options.addOption(passwordOption);

    Option baseLineOption = OptionBuilder.withDescription("Baseline date").withArgName("date").hasArg()
            .isRequired(false).create("n");

    options.addOption(baseLineOption);

    Option calculateDependenciesOption = OptionBuilder.withDescription("Calculate dependencies")
            .isRequired(false).create("z");

    options.addOption(calculateDependenciesOption);

    Option storeSourceOption = OptionBuilder.withDescription("Store source").isRequired(false).create("b");

    options.addOption(storeSourceOption);

    Option cloudscapeOption = OptionBuilder.withDescription("Use cloudscape database").isRequired(false)
            .create("a");

    options.addOption(cloudscapeOption);

    Option forceOnWaiversOption = OptionBuilder.withDescription("Do not force reviews on waivers")
            .isRequired(false).create("F");

    options.addOption(forceOnWaiversOption);

}

From source file:org.hammurapi.TaskBase.java

/**
 * @param options//from  w ww. j  ava  2s  .c o  m
 */
protected static void populateOptions(Options options) {
    Option waiverStubsOption = OptionBuilder.withArgName("waiverStubs").hasArg()
            .withDescription("Where to output waiver stubs").isRequired(false).create("w");

    options.addOption(waiverStubsOption);

    Option databaseOption = OptionBuilder.withDescription("Database name").withArgName("local database")
            .hasArg().isRequired(false).create("D");

    options.addOption(databaseOption);

    Option includeInspectorOption = OptionBuilder.withDescription("Enable inspector")
            .withArgName("inspector name").hasArg().isRequired(false).create("I");

    options.addOption(includeInspectorOption);

    Option configFileOption = OptionBuilder.withDescription("Config file").withArgName("file").hasArg()
            .isRequired(false).create("m");

    options.addOption(configFileOption);

    Option configUrlOption = OptionBuilder.withDescription("Config url").withArgName("url").hasArg()
            .isRequired(false).create("q");

    options.addOption(configUrlOption);

    Option unpackDirOption = OptionBuilder.withDescription("Unpack directory").withArgName("directory").hasArg()
            .isRequired(false).create("r");

    options.addOption(unpackDirOption);

    Option excludeInspectorOption = OptionBuilder.withDescription("Disable inspector")
            .withArgName("inspector name").hasArg().isRequired(false).create("X");

    options.addOption(excludeInspectorOption);

    Option archiveFileOption = OptionBuilder.withArgName("archive").hasArg()
            .withDescription("Hammurapi archive").isRequired(false).create("A");

    options.addOption(archiveFileOption);
    Option waiversFileOption = OptionBuilder.withArgName("waivers file").hasArg()
            .withDescription("Waivers File").isRequired(false).create("W");

    options.addOption(waiversFileOption);

    Option forceOption = OptionBuilder.withDescription("Force reviews of unchanged files").isRequired(false)
            .create("f");

    //Anu 20050701 : Baselining.Moved from HammurapiTask.java
    Option baseliningOption = OptionBuilder.withArgName("off|on|set").hasArg()
            .withDescription("Baselining mode").isRequired(false).create("B");

    options.addOption(forceOption);

    Option forceOnWarningsOption = OptionBuilder.withDescription("Do not force reviews of files with warnings")
            .isRequired(false).create("k");

    options.addOption(forceOnWarningsOption);

    Option doNotEvictOption = OptionBuilder.withDescription("Evict bad inspectors").isRequired(false)
            .create("E");

    options.addOption(doNotEvictOption);

    Option waiversUrlOption = OptionBuilder.withArgName("waivers url").hasArg().withDescription("Waivers URL")
            .isRequired(false).create("U");

    options.addOption(waiversUrlOption);

    Option classPathOption = OptionBuilder.withArgName("classpath").hasArg().withDescription("ClassPath")
            .isRequired(false).create("c");

    options.addOption(classPathOption);

    Option sigmaThresholdOption = OptionBuilder.withArgName("sigmaThreshold").hasArg()
            .withDescription("Sigma threshold").isRequired(false).create("s");

    options.addOption(sigmaThresholdOption);

    Option dpmoThresholdOption = OptionBuilder.withArgName("dpmoThreshold").hasArg()
            .withDescription("DPMO Threshold").isRequired(false).create("d");

    options.addOption(dpmoThresholdOption);

    Option severityThresholdOption = OptionBuilder.withArgName("severityThreshold").hasArg()
            .withDescription("Severity threshold").isRequired(false).create("S");

    options.addOption(severityThresholdOption);

    Option noEmbeddedInspectorsOption = OptionBuilder.withDescription("Do not load embedded inspectors")
            .isRequired(false).create("e");

    options.addOption(noEmbeddedInspectorsOption);

    Option inspectorsFileOption = OptionBuilder.withArgName("inspectorsFile").hasArg()
            .withDescription("Inspectors file").isRequired(false).create("i");

    options.addOption(inspectorsFileOption);

    Option inspectorsURLOption = OptionBuilder.withArgName("inspectorsURL").hasArg()
            .withDescription("Inspectors URL").isRequired(false).create("u");

    options.addOption(inspectorsURLOption);

    Option titleOption = OptionBuilder.withArgName("title").hasArg().withDescription("Report title")
            .isRequired(false).create("T");

    options.addOption(titleOption);

    Option debugTypeOption = OptionBuilder.withArgName("debug type").hasArg()
            .withDescription("Jsel type to debug").isRequired(false).create("t");

    options.addOption(debugTypeOption);

    Option listenerOption = OptionBuilder.withArgName("class name").hasArg().withDescription("Review listener")
            .isRequired(false).create("l");

    options.addOption(listenerOption);

    Option debugOption = OptionBuilder.withDescription("Debug").isRequired(false).create("g");

    options.addOption(debugOption);

    Option verboseOption = OptionBuilder.withDescription("Verbose").isRequired(false).create("v");

    options.addOption(verboseOption);

    Option xmlOption = OptionBuilder.withDescription("Output XML").isRequired(false).create("x");

    options.addOption(xmlOption);

    Option suppressOutputOption = OptionBuilder.withDescription("Suppress output").isRequired(false)
            .create("o");

    options.addOption(suppressOutputOption);

    Option descriptionOption = OptionBuilder.withDescription("Review description").withArgName("description")
            .hasArg().isRequired(false).create("y");

    options.addOption(descriptionOption);

    Option helpOption = OptionBuilder.withDescription("Print this message").isRequired(false).create("h");
    options.addOption(helpOption);
}

From source file:org.icefaces.ace.util.cssurlmapper.Main.java

public static void main(String[] args) {

    Options options = new Options();

    Option helpOpt = OptionBuilder.withDescription("print this message").withLongOpt("help").create('h');
    Option rootDirOpt = OptionBuilder.withArgName("directory").hasArg()
            .withDescription("root directory containing all CSS files to be processed").withLongOpt("root-dir")
            .create('r');
    Option fileOpt = OptionBuilder.withArgName("file").hasArg().withDescription("individual file to process")
            .withLongOpt("file").create('f');
    Option libraryNameOpt = OptionBuilder.withArgName("name").hasArg()
            .withDescription("name of JSF resource library to include in mapped URLs (required)")
            .withLongOpt("library-name").create('l');
    Option referenceDirOpt = OptionBuilder.withArgName("directory").hasArg()
            .withDescription("directory to use as starting point when building relative paths to resources")
            .withLongOpt("reference-dir").create('n');
    Option outputDirOpt = OptionBuilder.withArgName("directory").hasArg()
            .withDescription("directory to where all output files will be written (required)")
            .withLongOpt("output-dir").create('o');

    options.addOption(helpOpt);//from   w w  w .  ja  v a  2  s .c om
    options.addOption(rootDirOpt);
    options.addOption(fileOpt);
    options.addOption(libraryNameOpt);
    options.addOption(referenceDirOpt);
    options.addOption(outputDirOpt);

    PosixParser posixParser = new PosixParser();

    String libraryNameVal = null;
    String fileVal = null;
    String rootDirVal = null;
    String referenceDirVal = null;
    String outputDirVal = null;

    File rootDir = null;
    File file = null;
    File referenceDir = null;
    File outputDir = null;

    try {
        CommandLine line = posixParser.parse(options, args);

        // check for help option first
        if (line.hasOption('h')) {
            printHelp(options);
            Runtime.getRuntime().exit(0);
        }

        // make sure library name was specified
        if (line.hasOption('l')) {
            libraryNameVal = line.getOptionValue('l');
        } else {
            throw new MissingOptionException("ERROR: library name was not supplied.");
        }

        // check for root directory or file
        if (line.hasOption('f')) {
            fileVal = line.getOptionValue('f');
        }

        if (line.hasOption('r')) {
            rootDirVal = line.getOptionValue('r');
        }

        if (fileVal == null && rootDirVal == null) {
            throw new MissingOptionException("ERROR: either file or root directory must be specified.");
        }

        if (rootDirVal != null) {
            rootDir = new File(rootDirVal);
            if (!rootDir.exists()) {
                throw new Exception("ERROR: root directory does not exist.");
            } else if (!rootDir.isDirectory()) {
                throw new Exception("ERROR: root directory is not a real directory.");
            }
        } else { // file must be non-null then
            file = new File(fileVal);
            if (!file.exists()) {
                throw new Exception("ERROR: input file does not exist.");
            } else if (!file.isFile()) {
                throw new Exception("ERROR: input file is not a real file.");
            }
        }

        // check for output directory
        if (line.hasOption('o')) {
            outputDirVal = line.getOptionValue('o');
            outputDir = new File(outputDirVal);
            outputDir.mkdirs();
            if (!outputDir.exists()) {
                throw new Exception("ERROR: could not create output directory.");
            } else if (!outputDir.isDirectory()) {
                throw new Exception("ERROR: output directory is not a real directory.");
            }
        } else {
            throw new MissingOptionException("ERROR: output directory was not supplied.");
        }

        // check for reference directory
        if (line.hasOption('n')) {
            referenceDirVal = line.getOptionValue('n');
            referenceDir = new File(referenceDirVal);
            if (!referenceDir.exists()) {
                throw new Exception("ERROR: reference directory does not exist.");
            } else if (!referenceDir.isDirectory()) {
                throw new Exception("ERROR: reference directory is not a real directory.");
            }
            String referenceDirPath = referenceDir.getCanonicalPath();
            if (rootDir != null) {
                String rootDirPath = rootDir.getCanonicalPath();
                if (!rootDirPath.startsWith(referenceDirPath)) {
                    throw new Exception("ERROR: reference directory must be an ancestor of root directory.");
                }
            } else { // file must be non-null then
                String filePath = file.getCanonicalPath();
                if (!filePath.startsWith(referenceDirPath)) {
                    throw new Exception("ERROR: reference directory must be an ancestor of input file.");
                }
            }
        }

    } catch (ParseException e) {
        System.out.println(e.getMessage());
        System.out.println();
        printHelp(options);
        Runtime.getRuntime().exit(0);
    } catch (Exception e) {
        System.out.println(e.getMessage());
        Runtime.getRuntime().exit(0);
    }

    // all input was validated, so proceed with file processing

    if (rootDir != null) {
        if (referenceDir != null) {
            processDirectory(rootDir, libraryNameVal, referenceDir, outputDir);
        } else {
            processDirectory(rootDir, libraryNameVal, rootDir, outputDir);
        }
    } else {
        processFile(file, libraryNameVal, referenceDir, outputDir);
    }
}

From source file:org.isatools.isatab.commandline.ContentsShellCommand.java

@SuppressWarnings("static-access")
public static void main(String[] args) {

    try {/*from   w  ww . j a  v a  2  s  . com*/
        Options clopts = createCommonOptions();
        clopts.addOption(OptionBuilder.withDescription("List all the studies and their permissions/ownership")
                .withLongOpt("studies").create("s"));
        clopts.addOption(OptionBuilder.withDescription("List all the users").withLongOpt("users").create("u"));

        CommandLine cmdl = AbstractImportLayerShellCommand.parseCommandLine(clopts, args,
                ContentsShellCommand.class);

        boolean isStudies = cmdl.hasOption("s"), isUsers = cmdl.hasOption("u");
        if (!isStudies && !isUsers) {
            printUsage(clopts);
            System.exit(1);
        }

        args = cmdl.getArgs();
        setup(args);
        setupLog4JPath(cmdl, null);

        // Need to initialize this here, otherwise above config will fail
        log = Logger.getLogger(ContentsShellCommand.class);

        Properties hibProps = AbstractImportLayerShellCommand.getHibernateProperties();
        hibProps.setProperty("hibernate.search.indexing_strategy", "event");
        hibProps.setProperty("hibernate.hbm2ddl.auto", "update");
        hibProps.setProperty("hbm2ddl.drop", "false");

        EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("BIIEntityManager",
                hibProps);
        EntityManager entityManager = entityManagerFactory.createEntityManager();

        EntityTransaction transaction = entityManager.getTransaction();
        transaction.begin();

        PermissionManager permMgr = new PermissionManager(entityManager);
        if (isStudies) {
            List<Study> studies = permMgr.getStudies();
            if (studies == null || studies.size() == 0) {
                log.info("No study in the BII DB");
            } else {
                for (Study s : studies) {
                    log.info(PermissionManager.formatStudy(s));
                }
            }
        } else {
            List<Person> persons = permMgr.getUsers();
            if (persons == null || persons.size() == 0) {
                log.info("No user in the BII DB");
            } else {
                for (Person u : persons) {
                    log.info(PermissionManager.formatUser(u));
                }
            }
        }

        log.info("\n");

        System.exit(0);
    } catch (Exception ex) {
        String msg = "ERROR: problem while running the Permission Manager: " + ex.getMessage();
        if (log == null) {
            out.println(msg + "\n");
            ex.printStackTrace();
        } else {
            log.fatal(msg, ex);
        }
        System.exit(1);
    }
}

From source file:org.jdag.launcher.JDAGLauncher.java

/**
 * CTOR//from  w w  w.ja va 2  s. c o  m
 */
@SuppressWarnings("static-access")
public JDAGLauncher(String[] args) {
    try {
        Option classPathFileOption = OptionBuilder.withDescription("<the file containing class path>").hasArg()
                .create(OPTION_JDAG_HOME);

        Options options = new Options();
        options.addOption(classPathFileOption);
        CommandLineParser commandLineParser = new GnuParser();
        CommandLine commandLine = commandLineParser.parse(options, args);

        if (!commandLine.hasOption(OPTION_JDAG_HOME)) {
            LOG.severe("The file containing class path is not specified" + " Hence aborting");
        }

        File libDir = new File(commandLine.getOptionValue(OPTION_JDAG_HOME) + File.separator + LIB_DIR);

        if (!libDir.exists()) {
            throw new RuntimeException("Not able to resolve the library directory" + " Please check "
                    + libDir.getAbsolutePath() + " exists");
        }

        File[] dependentLibraries = libDir.listFiles();
        if (dependentLibraries.length == 0) {
            throw new RuntimeException("Not able to locate dependent jars " + " in " + libDir);
        }

        StringBuilder builder = new StringBuilder();
        File confDir = new File(commandLine.getOptionValue(OPTION_JDAG_HOME) + File.separator + CONF_DIR);
        if (!confDir.exists()) {
            throw new RuntimeException(
                    "Unable to locate the conf directory" + "  " + confDir.getAbsolutePath());
        }
        builder.append(confDir.getAbsolutePath());
        for (File f : dependentLibraries) {
            builder.append(File.pathSeparator);
            builder.append(f.getAbsolutePath());
        }
        myClassPath = builder.toString();
        File f = new File(ClassLoader.getSystemClassLoader().getResource(TOPOLOGY_FILE).getFile());

        myTopologyConfiguration = new XMLConfiguration(f);

    } catch (ConfigurationException e) {
        LOG.log(Level.SEVERE, "Exception when loading the topology file", e);
        throw new RuntimeException(e);
    } catch (ParseException e) {
        LOG.log(Level.SEVERE, "Exception while parsing command line arguments", e);
        throw new RuntimeException(e);
    }
}

From source file:org.jrman.main.JRMan.java

private static Options prepareOptions() {
    Options options = new Options();
    OptionBuilder.withLongOpt("help");
    OptionBuilder.withDescription("show this usage information and exits");
    options.addOption(OptionBuilder.create(OPTION_HELP));
    OptionBuilder.withLongOpt("version");
    OptionBuilder.withDescription("show application version and exits");
    options.addOption(OptionBuilder.create(OPTION_VERSION));
    OptionBuilder.withLongOpt("display");
    OptionBuilder.withDescription("always show image in a framebuffer display (implicitly add such "
            + "display if not already present)");
    options.addOption(OptionBuilder.create(OPTION_FRAMEBUFFER));
    OptionBuilder.withLongOpt("progress");
    OptionBuilder.withDescription("show per frame rendering progress");
    options.addOption(OptionBuilder.create(OPTION_PROGRESS));
    OptionBuilder.withLongOpt("first");
    OptionBuilder.withDescription("start rendering from <frame>");
    OptionBuilder.hasArg();//from   w  w w.  j a  v  a 2s.c  o m
    OptionBuilder.withType(new Integer(1));
    OptionBuilder.withArgName("frame");
    options.addOption(OptionBuilder.create(OPTION_FIRSTFRAME));
    OptionBuilder.withLongOpt("end");
    OptionBuilder.withDescription("stop rendering after <frame>");
    OptionBuilder.hasArg();
    OptionBuilder.withArgName("frame");
    options.addOption(OptionBuilder.create(OPTION_LASTFRAME));
    OptionBuilder.withLongOpt("stats");
    OptionBuilder.withDescription("print end of frame statistics");
    // TODO implement level of detail for rendering statistics
    //OptionBuilder.hasOptionalArg();
    //OptionBuilder.withType(new Integer(1));
    //OptionBuilder.withArgName("level");
    options.addOption(OptionBuilder.create(OPTION_STATISTICS));
    OptionBuilder.withLongOpt("quality");
    OptionBuilder.withDescription("higher rendering quality (slightly slower)");
    options.addOption(OptionBuilder.create(OPTION_QUALITY));
    return options;
}

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);//from w  ww.j av  a  2s  .  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);// w ww  . ja va  2  s .c o m
            }
        }

        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.lilyproject.cli.BaseCliTool.java

/**
 * Return the CLI options. When overriding, call super and add your own
 * options./*from  www  .ja  va2 s.c o m*/
 */
public List<Option> getOptions() {
    List<Option> options = new ArrayList<Option>();

    helpOption = new Option("h", "help", false, "Shows help");
    options.add(helpOption);

    versionOption = new Option("v", "version", false, "Shows the version");
    options.add(versionOption);

    logConfOption = OptionBuilder.withArgName("config").hasArg()
            .withDescription("log4j config file (.properties or .xml)").create("log");
    options.add(logConfOption);

    dumpLogConfOption = OptionBuilder.withDescription("Dump default log4j configuration").create("dumplog");
    options.add(dumpLogConfOption);

    return options;
}