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.teavm.cli.TeaVMTestRunner.java

@SuppressWarnings("static-access")
public static void main(String[] args) {
    Options options = new Options();
    options.addOption(OptionBuilder.withArgName("directory").hasArg()
            .withDescription("a directory where to put generated files (current directory by default)")
            .withLongOpt("targetdir").create('d'));
    options.addOption(OptionBuilder.withDescription("causes TeaVM to generate minimized JavaScript file")
            .withLongOpt("minify").create("m"));
    options.addOption(OptionBuilder.withArgName("number").hasArg()
            .withDescription("how many threads should TeaVM run").withLongOpt("threads").create("t"));
    options.addOption(OptionBuilder.withArgName("class name").hasArg()
            .withDescription("qualified class name of test adapter").withLongOpt("adapter").create("a"));
    options.addOption(OptionBuilder.hasArg().hasOptionalArgs().withArgName("class name")
            .withDescription("qualified class names of transformers").withLongOpt("transformers").create("T"));

    if (args.length == 0) {
        printUsage(options);//w  w  w  . j  a  v  a  2 s  .c  o  m
        return;
    }
    CommandLineParser parser = new PosixParser();
    CommandLine commandLine;
    try {
        commandLine = parser.parse(options, args);
    } catch (ParseException e) {
        printUsage(options);
        return;
    }

    TeaVMTestTool tool = new TeaVMTestTool();
    tool.setOutputDir(new File(commandLine.getOptionValue("d", ".")));
    tool.setMinifying(commandLine.hasOption("m"));
    try {
        tool.setNumThreads(Integer.parseInt(commandLine.getOptionValue("t", "1")));
    } catch (NumberFormatException e) {
        System.err.println("Invalid number specified for -t option");
        printUsage(options);
        return;
    }
    if (commandLine.hasOption("a")) {
        tool.setAdapter(instantiateAdapter(commandLine.getOptionValue("a")));
    }
    if (commandLine.hasOption("T")) {
        for (String transformerType : commandLine.getOptionValues("T")) {
            tool.getTransformers().add(instantiateTransformer(transformerType));
        }
    }
    args = commandLine.getArgs();
    if (args.length == 0) {
        System.err.println("You did not specify any test classes");
        printUsage(options);
        return;
    }
    tool.getTestClasses().addAll(Arrays.asList(args));

    tool.setLog(new ConsoleTeaVMToolLog());
    tool.getProperties().putAll(System.getProperties());
    long start = System.currentTimeMillis();
    try {
        tool.generate();
    } catch (TeaVMToolException e) {
        e.printStackTrace(System.err);
        System.exit(-2);
    }
    System.out.println("Operation took " + (System.currentTimeMillis() - start) + " milliseconds");
}

From source file:org.texconverter.TexConverterCommandline.java

/**
 * @param args/*from  w w w .  jav  a2  s.  c  om*/
 *            main args
 */
@SuppressWarnings("static-access")
// commons-cli use is really awkward with qualified access
public static void main(final String[] args) {

    final Option optionInputFile = OptionBuilder.withArgName("file").hasArg().isRequired()
            .withDescription("Required: The input file").create(OPTION_INPUT_FILE);
    final Option optionOutputFile = OptionBuilder.withArgName("file").hasArg().isRequired()
            .withDescription("Required: The output file").create(OPTION_OUTPUT_FILE);
    final Option optionOutputFormat = OptionBuilder.withArgName("type").hasArg().isRequired()
            .withDescription("Required: The desired output format").create(OPTION_OUTPUTFORMAT);
    final Option optionVerbose = OptionBuilder.withDescription("optional: verbose").create(OPTION_VERBOSE);
    final Option optionLocaleCode = OptionBuilder.withArgName("locale").hasArg()
            .withDescription("Optional: The ISO 639-2 3-letter language code, this affects some titles"
                    + " and captions in the document. If not given, the"
                    + " system locale will be used. Refer to the documentation for available language codes.")
            .create(OPTION_LOCALECODE);

    final Option optionMavenDev = OptionBuilder.withArgName("maven").hasOptionalArg()
            .withDescription("Allow to specify that running on devlopment maven mode").create(OPTION_MAVEN_DEV);

    final Options directOptions = new Options();
    directOptions.addOption(optionInputFile);
    directOptions.addOption(optionOutputFile);
    directOptions.addOption(optionOutputFormat);
    directOptions.addOption(optionVerbose);
    directOptions.addOption(optionLocaleCode);
    directOptions.addOption(optionMavenDev);

    final Option optionPropertiesFile = OptionBuilder.withArgName("file").hasArg().isRequired()
            .withDescription("optional: the property file").create(OPTION_PROPFILE);

    final Options propertyOptions = new Options();
    propertyOptions.addOption(optionPropertiesFile);
    propertyOptions.addOption(optionVerbose);

    final CommandLineParser cmdparser = new PosixParser();
    CommandLine commandLine = null;

    String inputFile = null, outputFile = null, outputFormat = null, propertiesFile = null, localeCode = null;
    String mavenDevMode = null;
    try {
        commandLine = cmdparser.parse(propertyOptions, args);

        propertiesFile = commandLine.getOptionValue(OPTION_PROPFILE);

    } catch (final ParseException ex) {

        try {
            commandLine = cmdparser.parse(directOptions, args);

            inputFile = commandLine.getOptionValue(OPTION_INPUT_FILE);
            outputFile = commandLine.getOptionValue(OPTION_OUTPUT_FILE);
            outputFormat = commandLine.getOptionValue(OPTION_OUTPUTFORMAT);
            localeCode = commandLine.getOptionValue(OPTION_LOCALECODE);

            mavenDevMode = commandLine.getOptionValue(OPTION_MAVEN_DEV);
            if (mavenDevMode != null) {
                TexConverter.RESOURCES_PATH = "src/main/resources/";
            }

            if (inputFile != null) {
                inputFile = inputFile.trim();
            }
            if (outputFile != null) {
                outputFile = outputFile.trim();
            }

        } catch (final ParseException e) {

            final HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("java texconverter.jar", "", directOptions,
                    "Alternatively, a single argument specifying a property file can be used:");
            formatter.printHelp("java texconverter.jar", "", propertyOptions,
                    "The option propertiesFile will override any other options except verbose."
                            + " In this text file one or several conversion tasks can be defined."
                            + " Please refer to the readme or the documentation for a description of the files format.");
            System.exit(1);
        }
    }

    final boolean verbose = commandLine.hasOption(OPTION_VERBOSE);

    final TexConverterCommandline converter = new TexConverterCommandline();
    converter.init(null, verbose);
    converter.startConversion(propertiesFile, inputFile, outputFile, outputFormat, localeCode);

    File outFile = new File(outputFile);

    try {
        LOGGER.info("Copy theme ...");
        FileUtils.copyDirectory(new File(TexConverter.RESOURCES_PATH + "style/images"),
                new File(outFile.getParentFile() + "/images"));

        FileUtils.copyFile(new File(TexConverter.RESOURCES_PATH + "style/default.css"),
                new File(outFile.getParentFile() + "/default.css"));

        FileUtils.copyFile(new File(TexConverter.RESOURCES_PATH + "style/script.js"),
                new File(outFile.getParentFile() + "/script.js"));

        LOGGER.info("Copy syntax Highlighter ...");
        FileUtils.copyDirectory(new File(TexConverter.RESOURCES_PATH + "syntaxHighlighter"),
                new File(outFile.getParentFile() + "/syntaxHighlighter"));
    } catch (IOException e) {
        LOGGER.error("can't copy syntaxHighlighter", e);
        System.exit(1);
    }

}

From source file:org.tonguetied.server.Server.java

/**
 * Read and process command line arguments when the server is run.
 * /* w  w  w.  j  a  v  a 2 s  .  c o m*/
 * @param args the arguments to process
 * @throws IllegalArgumentException if the arguments fail to be initialized
 *         correctly
 */
private static void readArguments(String[] args) throws IllegalArgumentException {
    final Option help = new Option("help", "print this message");
    OptionBuilder.withArgName("file");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("the name and location of the properties file to use");
    final Option propertiesFile = OptionBuilder.create("p");

    Options options = new Options();
    options.addOption(help);
    options.addOption(propertiesFile);

    CommandLineParser parser = new GnuParser();
    try {
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);

        // has the properties file argument been passed?
        if (line.hasOption("p")) {
            // initialise the member variable
            propsFile = line.getOptionValue("p");
        }
        if (line.hasOption("help")) {
            printHelp(options, 0);
        }
    } catch (ParseException pe) {
        // oops, something went wrong
        System.err.println("Parsing failed. Reason: " + pe.getMessage());
        printHelp(options, 1);
    }
}

From source file:org.unigram.docvalidator.Main.java

public static void main(String[] args) throws DocumentValidatorException {
    Options options = new Options();
    options.addOption("h", "help", false, "help");

    OptionBuilder.withLongOpt("format");
    OptionBuilder.withDescription("input data format");
    OptionBuilder.hasArg();//from www.j ava 2s .  c  om
    OptionBuilder.withArgName("FORMAT");
    options.addOption(OptionBuilder.create("f"));

    OptionBuilder.withLongOpt("input");
    OptionBuilder.withDescription("input file");
    OptionBuilder.hasOptionalArgs();
    OptionBuilder.withArgName("INPUT FILE");
    options.addOption(OptionBuilder.create("i"));

    OptionBuilder.withLongOpt("conf");
    OptionBuilder.withDescription("configuration file");
    OptionBuilder.hasArg();
    options.addOption(OptionBuilder.create("c"));

    OptionBuilder.withLongOpt("result-format");
    OptionBuilder.withDescription("output result format");
    OptionBuilder.hasArg();
    OptionBuilder.withArgName("RESULT FORMAT");
    options.addOption(OptionBuilder.create("r"));

    options.addOption("v", "version", false, "print the version information and exit");

    CommandLineParser parser = new BasicParser();
    CommandLine commandLine = null;

    try {
        commandLine = parser.parse(options, args);
    } catch (ParseException e) {
        LOG.error("Error occurred in parsing command line options ");
        printHelp(options);
        System.exit(-1);
    }

    String inputFormat = "plain";
    String[] inputFileNames = null;
    String configFileName = "";
    String resultFormat = "plain";
    Parser.Type parserType;
    Formatter.Type outputFormat;

    if (commandLine.hasOption("h")) {
        printHelp(options);
        System.exit(0);
    }
    if (commandLine.hasOption("v")) {
        System.out.println("1.0");
        System.exit(0);
    }
    if (commandLine.hasOption("f")) {
        inputFormat = commandLine.getOptionValue("f");
    }
    if (commandLine.hasOption("i")) {
        inputFileNames = commandLine.getOptionValues("i");
    }
    if (commandLine.hasOption("c")) {
        configFileName = commandLine.getOptionValue("c");
    }
    if (commandLine.hasOption("r")) {
        resultFormat = commandLine.getOptionValue("r");
    }

    ConfigurationLoader configLoader = new ConfigurationLoader();
    Configuration conf = configLoader.loadConfiguration(configFileName);
    if (conf == null) {
        LOG.error("Failed to initialize the DocumentValidator configuration.");
        System.exit(-1);
    }

    parserType = Parser.Type.valueOf(inputFormat.toUpperCase());
    outputFormat = Formatter.Type.valueOf(resultFormat.toUpperCase());

    DocumentCollection documentCollection = DocumentGenerator.generate(inputFileNames, conf, parserType);

    if (documentCollection == null) {
        LOG.error("Failed to create a DocumentCollection object");
        System.exit(-1);
    }
    ResultDistributor distributor = ResultDistributorFactory.createDistributor(outputFormat, System.out);

    DocumentValidator validator = new DocumentValidator.Builder().setConfiguration(conf)
            .setResultDistributor(distributor).build();

    validator.check(documentCollection);

    System.exit(0);
}

From source file:org.usergrid.standalone.Server.java

public Options createOptions() {

    Options options = new Options();
    OptionBuilder.withDescription("Initialize database");
    Option initOption = OptionBuilder.create("init");

    OptionBuilder.withDescription("Start database");
    Option dbOption = OptionBuilder.create("db");

    OptionBuilder.withDescription("Http port");
    OptionBuilder.hasArg();//from  w  ww.j  a v a  2 s. co m
    OptionBuilder.withArgName("PORT");
    OptionBuilder.withLongOpt("port");
    OptionBuilder.withType(Number.class);
    Option portOption = OptionBuilder.create('p');

    options.addOption(initOption);
    options.addOption(dbOption);
    options.addOption(portOption);

    return options;
}

From source file:org.vbossica.springbox.cliapp.ModuleLauncher.java

@SuppressWarnings("AccessStaticViaInstance")
private void process(final String[] args) {
    Options options = new Options()
            .addOption(OptionBuilder.withLongOpt(HELP_OPTION).withDescription("shows this help").create('h'))
            .addOption(OptionBuilder.hasArg().withArgName("name").withDescription("name of the package to scan")
                    .create(PACKAGE_OPTION))
            .addOption(OptionBuilder.withDescription("lists all registered modules").create(LIST_OPTION))
            .addOption(OptionBuilder.hasArg().withArgName("name")
                    .withDescription("name of the module to execute").create(MODULE_OPTION));

    String packageName = null;/* www.  java2 s.c o  m*/

    try {
        CommandLine cmd = new PosixParser().parse(options, args, true);
        if (cmd.hasOption(HELP_OPTION) && !cmd.hasOption(MODULE_OPTION)) {
            printHelp(options);
            return;
        }
        if (cmd.hasOption(PACKAGE_OPTION)) {
            packageName = cmd.getOptionValue(PACKAGE_OPTION);
        }
        if (cmd.hasOption(LIST_OPTION)) {
            listModules(packageName, System.out);
            return;
        }
        if (cmd.hasOption(MODULE_OPTION)) {
            String tool = cmd.getOptionValue(MODULE_OPTION);
            initializeTool(packageName, cmd, tool);
        } else {
            System.err.println("missing module definition");
        }
    } catch (Exception ex) {
        System.err.println(ex.getMessage());
        printHelp(options);
    }
}

From source file:org.vivoweb.harvester.util.args.ArgParser.java

/**
 * Create the Options from this ArgParser
 *//*  w  ww. j a  v  a2 s  .  c o  m*/
@SuppressWarnings("static-access")
private void createOptions() {
    this.parser = new Options();
    for (ArgDef arg : getArgDefs()) {
        OptionBuilder ob = OptionBuilder.isRequired(false);
        if (arg.getLongOption() != null) {
            ob = ob.withLongOpt(arg.getLongOption());
            this.optMap.put(arg.getLongOption(), arg);
        }
        if (arg.getDescription() != null) {
            ob = ob.withDescription(arg.getDescription());
        }
        if (arg.hasParameter()) {
            ob = ob.withArgName(arg.getParameterDescription());
            int num = arg.numParameters();
            if (num == 1) {
                ob = ob.hasArg(arg.isParameterRequired());
            } else if (num == -1) {
                if (arg.isParameterRequired()) {
                    ob = ob.hasArgs();
                } else {
                    if (arg.isParameterValueMap()) {
                        ob = ob.hasOptionalArgs(2).withValueSeparator();
                    } else {
                        ob = ob.hasOptionalArgs();
                    }
                }
            } else {
                if (arg.isParameterRequired()) {
                    ob = ob.hasArgs(num);
                } else {
                    ob = ob.hasOptionalArgs(num);
                }
            }
        }
        Option o;
        if (arg.getShortOption() != null) {
            o = ob.create(arg.getShortOption().charValue());
            this.optMap.put(arg.getShortOption().toString(), arg);
        } else {
            o = ob.create();
        }
        this.parser.addOption(o);
    }
}

From source file:org.waveprotocol.box.server.robots.agent.AbstractCliRobotAgent.java

/**
 * Initializes basic options. Override if more options needed.
 *
 * @return the command options./*from   w  w  w  .j ava2 s.co  m*/
 */
protected Options initOptions() {
    // Create Options.
    Options options = new Options();
    // The robot has only "help" option.
    @SuppressWarnings({ "static-access", "static" })
    Option help = OptionBuilder.withDescription("Displays help for the command.").create("help");
    options.addOption(help);
    return options;
}

From source file:org.waveprotocol.wave.examples.fedone.FlagBinder.java

/**
 * Parse command line arguments.//from  ww w .  ja v a  2  s  . co  m
 *
 * @param args argv from command line
 * @return a Guice module configured with flag support.
 * @throws ParseException on bad command line args
 */
public static Module parseFlags(String[] args, Class<?>... flagSettings) throws ParseException {
    Options options = new Options();

    List<Field> fields = new ArrayList<Field>();
    for (Class<?> settings : flagSettings) {
        fields.addAll(Arrays.asList(settings.getDeclaredFields()));
    }

    // Reflect on flagSettings class and absorb flags
    final Map<Flag, Field> flags = new LinkedHashMap<Flag, Field>();
    for (Field field : fields) {
        if (!field.isAnnotationPresent(Flag.class)) {
            continue;
        }

        // Validate target type
        if (!supportedFlagTypes.contains(field.getType())) {
            throw new IllegalArgumentException(
                    field.getType() + " is not one of the supported flag types " + supportedFlagTypes);
        }

        Flag flag = field.getAnnotation(Flag.class);
        OptionBuilder.withLongOpt(flag.name());
        OptionBuilder.hasArg();
        final OptionBuilder option = OptionBuilder.withArgName(flag.name().toUpperCase());
        if (flag.defaultValue().isEmpty()) {
            OptionBuilder.withDescription(flag.description());
        } else {
            OptionBuilder.withDescription(flag.description() + "(default: " + flag.defaultValue() + ")");
        }

        options.addOption(OptionBuilder.create());

        flags.put(flag, field);
    }

    // Parse up our cmd line
    CommandLineParser parser = new PosixParser();
    final CommandLine cmd = parser.parse(options, args);

    // Now validate them
    for (Flag flag : flags.keySet()) {
        if (flag.defaultValue().isEmpty()) {
            String help = !"".equals(flag.description()) ? flag.description() : flag.name();
            mandatoryOption(cmd, flag.name(), "must supply " + help, options);
        }
    }

    // bundle everything up in an injectable guice module
    return new AbstractModule() {

        @Override
        protected void configure() {
            // We must iterate the flags a third time when binding.
            // Note: do not collapse these loops as that will damage
            // early error detection. The runtime is still O(n) in flag count.
            for (Map.Entry<Flag, Field> entry : flags.entrySet()) {
                Class<?> type = entry.getValue().getType();
                Flag flag = entry.getKey();

                // Skip non-mandatory, missing flags.
                //          if (!flag.mandatory()) {
                //            continue;
                //          }

                String flagValue = cmd.getOptionValue(flag.name());
                // Coerce String flag or defaultValue into target type.
                // NOTE(dhanji): only supported types are int, String and boolean.
                if (flagValue == null ||
                // The empty string is a valid value for a string type.
                (flagValue.isEmpty() && (int.class.equals(type) || boolean.class.equals(type)))) {
                    // Use the default.
                    if (int.class.equals(type)) {
                        bindConstant().annotatedWith(Names.named(flag.name()))
                                .to(Integer.parseInt(flag.defaultValue()));
                    } else if (boolean.class.equals(type)) {
                        bindConstant().annotatedWith(Names.named(flag.name()))
                                .to(Boolean.parseBoolean(flag.defaultValue()));
                    } else {
                        bindConstant().annotatedWith(Names.named(flag.name())).to(flag.defaultValue());
                    }
                } else {
                    if (int.class.equals(type)) {
                        bindConstant().annotatedWith(Names.named(flag.name())).to(Integer.parseInt(flagValue));
                    } else if (boolean.class.equals(type)) {
                        bindConstant().annotatedWith(Names.named(flag.name()))
                                .to(Boolean.parseBoolean(flagValue));
                    } else {
                        bindConstant().annotatedWith(Names.named(flag.name())).to(flagValue);
                    }
                }
            }
        }
    };
}