Example usage for org.apache.commons.cli2.builder GroupBuilder create

List of usage examples for org.apache.commons.cli2.builder GroupBuilder create

Introduction

In this page you can find the example usage for org.apache.commons.cli2.builder GroupBuilder create.

Prototype

public Group create() 

Source Link

Document

Creates a new Group instance

Usage

From source file:it.jnrpe.plugin.jmx.CCheckJMX.java

/**
 * @param args/*from  w  w w  . ja  v  a2s. c om*/
 */
public static void main(String[] args) {

    CCheckJMX checkJMX = new CCheckJMX();
    Status status;
    try {
        // query.parse(args);
        // configure a parser
        PluginDefinition pluginDef = PluginRepositoryUtil.parseXmlPluginDefinition(
                JMXQuery.class.getClassLoader(), CCheckJMX.class.getResourceAsStream("/check_jmx_plugin.xml"));
        GroupBuilder gBuilder = new GroupBuilder();
        for (PluginOption po : pluginDef.getOptions()) {
            gBuilder = gBuilder.withOption(po.toOption());
        }
        HelpFormatter hf = new HelpFormatter();
        Parser cliParser = new Parser();
        cliParser.setGroup(gBuilder.create());
        cliParser.setHelpFormatter(hf);
        CommandLine cl = cliParser.parse(args);
        ReturnValue retValue = checkJMX.execute(new PluginCommandLine(cl));
        status = retValue.getStatus();
        System.out.println(retValue.getMessage());
    } catch (Exception ex) {
        status = checkJMX.report(ex, System.out);
    } finally {
        try {
            checkJMX.disconnect();
        } catch (IOException e) {
            status = checkJMX.report(e, System.out);
        }
    }
    System.exit(status.intValue());
}

From source file:egat.cli.Main.java

public static void main(String[] args) {
    final DefaultOptionBuilder optionBuilder = new DefaultOptionBuilder();
    final GroupBuilder groupBuilder = new GroupBuilder();

    Option help = optionBuilder.withLongName("help").withShortName("h").withDescription("print this message")
            .create();/*from   w w w  .  j  a va 2 s. co m*/
    Option version = optionBuilder.withLongName("version").withShortName("v")
            .withDescription("print the version information and exit").create();

    List<CommandHandler> commandHandlers = createCommandHandlers();

    groupBuilder.withName("command");
    for (CommandHandler handler : commandHandlers) {
        groupBuilder.withOption(handler.getCommand());
    }
    Group commandGroup = groupBuilder.create();

    Group mainOptions = groupBuilder.withName("options").withOption(help).withOption(version).create();

    Group options = groupBuilder.withOption(mainOptions).withOption(commandGroup).create();

    Parser parser = new Parser();
    parser.setGroup(options);

    try {
        CommandLine cl = parser.parse(args);

        if (cl.hasOption(version)) {
            printVersion();
        } else {
            boolean commandTriggered = false;

            for (CommandHandler commandHandler : commandHandlers) {
                if (cl.hasOption(commandHandler.getCommand())) {
                    commandHandler.handleCommand(cl);
                    commandTriggered = true;
                }
            }

            if (!commandTriggered) {
                printHelp(options);
            }
        }

    } catch (OptionException e) {
        e.printStackTrace();
        printHelp(options);
    }
}

From source file:it.jnrpe.plugins.TestCommandLineParsing.java

@Test
public void testNoArgumentsOption() throws Exception {
    ClassLoader cl = TestCommandLineParsing.class.getClassLoader();
    PluginDefinition pluginDef = PluginRepositoryUtil.parseXmlPluginDefinition(cl,
            cl.getResourceAsStream("check_mysql_plugin.xml"));

    GroupBuilder gBuilder = new GroupBuilder();

    for (PluginOption po : pluginDef.getOptions()) {
        gBuilder = gBuilder.withOption(po.toOption());
    }// w  w w  .jav a  2s  . c o  m

    Group group = gBuilder.create();
    Parser p = new Parser();
    p.setGroup(group);
    CommandLine cli = p.parse(new String[] { "--hostname", "$ARG1$", "--port", "$ARG2$", "--database", "$ARG3$",
            "--user", "$ARG4$", "--password", "$ARG5$", "--check-slave" });

    Assert.assertTrue(cli.hasOption("--check-slave"));
}

From source file:egat.cli.AbstractCommandHandler.java

protected Command createCommand() {
    final CommandBuilder commandBuilder = new CommandBuilder();

    final GroupBuilder groupBuilder = new GroupBuilder();

    commandBuilder.withName(getCommandName());

    addCommandDescription(commandBuilder);

    addChildOptions(groupBuilder);//ww w  .j  av a 2s . c  o m

    return commandBuilder.withChildren(groupBuilder.create()).create();
}

From source file:it.jnrpe.server.console.PluginCommand.java

private Group getCommandLineGroup() {
    PluginProxy pp = (PluginProxy) plugin;
    GroupBuilder gBuilder = new GroupBuilder();

    for (PluginOption po : pp.getOptions()) {
        gBuilder = gBuilder.withOption(toOption(po));
    }// ww w . j a v a2s.  com

    return gBuilder.create();
}

From source file:it.jnrpe.plugins.PluginProxy.java

/**
 * Instantiate a new plugin proxy.//from   w w  w  .  j  a  v  a2 s .  c o  m
 * 
 * @param plugin
 *            The plugin to be proxied
 * @param pluginDef
 *            The plugin definition of the plugin to be proxied
 */
public PluginProxy(final IPluginInterface plugin, final PluginDefinition pluginDef) {
    proxiedPlugin = plugin;
    proxyedPluginDefinition = pluginDef;
    description = proxyedPluginDefinition.getDescription();

    GroupBuilder gBuilder = new GroupBuilder();

    for (PluginOption po : pluginDef.getOptions()) {
        gBuilder = gBuilder.withOption(po.toOption());
    }

    mainOptionsGroup = gBuilder.create();
}

From source file:com.gsinnovations.howdah.AbstractJob.java

/** Parse the arguments specified based on the options defined using the
 *  various <code>addOption</code> methods. If -h is specified or an
 *  exception is encountered print help and return null. Has the
 *  side effect of setting inputPath and outputPath
 *  if <code>addInputOption</code> or <code>addOutputOption</code>
 *  or <code>mapred.input.dir</code> or <code>mapred.output.dir</code>
 *  are present in the Configuration./*w ww.  j  av  a2s  .c o  m*/
 *
 * @return a Map<String,Sting> containing options and their argument values.
 *  The presence of a flag can be tested using <code>containsKey</code>, while
 *  argument values can be retrieved using <code>get(optionName</code>. The
 *  names used for keys are the option name parameter prefixed by '--'.
 *
 *
 */
public Map<String, String> parseArguments(String[] args) {

    Option helpOpt = addOption(DefaultOptionCreator.helpOption());
    addOption("tempDir", null, "Intermediate output directory", "temp");
    addOption("startPhase", null, "First phase to run", "0");
    addOption("endPhase", null, "Last phase to run", String.valueOf(Integer.MAX_VALUE));

    GroupBuilder gBuilder = new GroupBuilder().withName("Job-Specific Options:");

    for (Option opt : options) {
        gBuilder = gBuilder.withOption(opt);
    }

    Group group = gBuilder.create();

    CommandLine cmdLine;
    try {
        Parser parser = new Parser();
        parser.setGroup(group);
        parser.setHelpOption(helpOpt);
        cmdLine = parser.parse(args);

    } catch (OptionException e) {
        log.error(e.getMessage());
        CommandLineUtil.printHelpWithGenericOptions(group);
        return null;
    }

    if (cmdLine.hasOption(helpOpt)) {
        CommandLineUtil.printHelpWithGenericOptions(group);
        return null;
    }

    try {
        parseDirectories(cmdLine);
    } catch (IllegalArgumentException e) {
        log.error(e.getMessage());
        CommandLineUtil.printHelpWithGenericOptions(group);
        return null;
    }

    argMap = new TreeMap<String, String>();
    maybePut(argMap, cmdLine, this.options.toArray(new Option[this.options.size()]));

    log.info("Command line arguments: {}", argMap);
    return argMap;
}

From source file:my.mahout.AbstractJob.java

/**
 *
 * @param args  The args to parse/*from w  w  w  .  j a v  a 2 s .co  m*/
 * @param inputOptional if false, then the input option, if set, need not be present.  If true and input is an option
 *                      and there is no input, then throw an error
 * @param outputOptional if false, then the output option, if set, need not be present.  If true and output is an
 *                       option and there is no output, then throw an error
 * @return the args parsed into a map.
 */
public Map<String, List<String>> parseArguments(String[] args, boolean inputOptional, boolean outputOptional)
        throws IOException {
    Option helpOpt = addOption(DefaultOptionCreator.helpOption());
    addOption("tempDir", null, "Intermediate output directory", "temp");
    addOption("startPhase", null, "First phase to run", "0");
    addOption("endPhase", null, "Last phase to run", String.valueOf(Integer.MAX_VALUE));

    GroupBuilder gBuilder = new GroupBuilder().withName("Job-Specific Options:");

    for (Option opt : options) {
        gBuilder = gBuilder.withOption(opt);
    }

    group = gBuilder.create();

    CommandLine cmdLine;
    try {
        Parser parser = new Parser();
        parser.setGroup(group);
        parser.setHelpOption(helpOpt);
        cmdLine = parser.parse(args);

    } catch (OptionException e) {
        log.error(e.getMessage());
        CommandLineUtil.printHelpWithGenericOptions(group, e);
        return null;
    }

    if (cmdLine.hasOption(helpOpt)) {
        CommandLineUtil.printHelpWithGenericOptions(group);
        return null;
    }

    try {
        parseDirectories(cmdLine, inputOptional, outputOptional);
    } catch (IllegalArgumentException e) {
        log.error(e.getMessage());
        CommandLineUtil.printHelpWithGenericOptions(group);
        return null;
    }

    argMap = new TreeMap<String, List<String>>();
    maybePut(argMap, cmdLine, this.options.toArray(new Option[this.options.size()]));

    this.tempPath = new Path(getOption("tempDir"));

    if (!hasOption("quiet")) {
        log.info("Command line arguments: {}", argMap);
    }
    return argMap;
}

From source file:com.digitalpebble.behemoth.tika.TikaDriver.java

public int run(String[] args) throws Exception {

    final FileSystem fs = FileSystem.get(getConf());
    GroupBuilder gBuilder = new GroupBuilder().withName("Options:");
    List<Option> options = new ArrayList<Option>();
    Option inputOpt = buildOption("input", "i", "The input path", true, true, null);
    options.add(inputOpt);/*from   w ww . j a va  2s  . c o  m*/
    Option outOpt = buildOption("output", "o", "The output path", true, true, null);
    options.add(outOpt);
    Option tikaOpt = buildOption("tikaProcessor", "t",
            "The fully qualified name of a TikaProcessor class that handles the extraction (optional)", true,
            false, null);
    options.add(tikaOpt);
    Option mimeTypeOpt = buildOption("mimeType", "m", "The mime type to use (optional)", true, false, "");
    options.add(mimeTypeOpt);
    for (Option opt : options) {
        gBuilder = gBuilder.withOption(opt);
    }

    Group group = gBuilder.create();

    try {
        Parser parser = new Parser();
        parser.setGroup(group);
        // TODO catch exceptions with parsing of opts
        CommandLine cmdLine = parser.parse(args);
        Path inputPath = new Path(cmdLine.getValue(inputOpt).toString());
        Path outputPath = new Path(cmdLine.getValue(outOpt).toString());
        String handlerName = null;
        if (cmdLine.hasOption(tikaOpt)) {
            handlerName = cmdLine.getValue(tikaOpt).toString();
        }

        JobConf job = new JobConf(getConf());
        job.setJarByClass(this.getClass());

        if (cmdLine.hasOption(mimeTypeOpt)) {
            String mimeType = cmdLine.getValue(mimeTypeOpt).toString();
            job.set(TikaConstants.TIKA_MIME_TYPE_KEY, mimeType);
        }

        if (handlerName != null && handlerName.equals("") == false) {
            job.set(TIKA_PROCESSOR_KEY, handlerName);
        }

        job.setJobName("Tika : " + inputPath.toString());

        job.setInputFormat(SequenceFileInputFormat.class);
        job.setOutputFormat(SequenceFileOutputFormat.class);

        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(BehemothDocument.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(BehemothDocument.class);

        job.setMapperClass(TikaMapper.class);

        boolean isFilterRequired = BehemothReducer.isRequired(job);
        if (isFilterRequired)
            job.setReducerClass(BehemothReducer.class);
        else {
            job.setNumReduceTasks(0);
        }

        FileInputFormat.addInputPath(job, inputPath);
        FileOutputFormat.setOutputPath(job, outputPath);

        try {
            long start = System.currentTimeMillis();
            JobClient.runJob(job);
            long finish = System.currentTimeMillis();
            if (log.isInfoEnabled()) {
                log.info("TikaDriver completed. Timing: " + (finish - start) + " ms");
            }
        } catch (Exception e) {
            log.error("Exception", e);
            return -1;
            // don't delete the output as some of it could be used
            // fs.delete(outputPath, true);
        } finally {
        }

    } catch (OptionException e) {
        log.error("OptionException", e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.setGroup(group);
        formatter.print();
        return -1;
    }

    return 0;
}

From source file:org.apache.mahout.math.hadoop.decomposer.EigenVerificationJob.java

public static Map<String, String> handleArgs(String[] args) {
    Option eigenInputOpt = buildOption("eigenInput", "ei",
            "The Path for purported eigenVector input files (SequenceFile<WritableComparable,VectorWritable>.",
            null);/*from ww w . j  av  a  2 s. c o m*/
    Option corpusInputOpt = buildOption("corpusInput", "ci",
            "The Path for corpus input files (SequenceFile<WritableComparable,VectorWritable>.");
    Option outOpt = DefaultOptionCreator.outputOption().create();
    Option helpOpt = DefaultOptionCreator.helpOption();
    Option inMemOpt = buildOption("inMemory", "mem", "Buffer eigen matrix into memory (if you have enough!)",
            "false");
    Option errorOpt = buildOption("maxError", "err", "Maximum acceptable error", "0.05");
    Option minEigenValOpt = buildOption("minEigenvalue", "mev", "Minimum eigenvalue to keep the vector for",
            "0.0");

    GroupBuilder gBuilder = new GroupBuilder().withName("Options").withOption(eigenInputOpt)
            .withOption(corpusInputOpt).withOption(helpOpt).withOption(outOpt).withOption(inMemOpt)
            .withOption(errorOpt).withOption(minEigenValOpt);
    Group group = gBuilder.create();

    Map<String, String> argMap = new HashMap<String, String>();

    CommandLine cmdLine;
    try {
        Parser parser = new Parser();
        parser.setGroup(group);
        cmdLine = parser.parse(args);
    } catch (OptionException e) {
        log.error(e.getMessage());
        CommandLineUtil.printHelp(group);
        return null;
    }
    if (cmdLine.hasOption(helpOpt)) {
        CommandLineUtil.printHelp(group);
        return argMap;
    }
    maybePut(argMap, cmdLine, eigenInputOpt, corpusInputOpt, helpOpt, outOpt, inMemOpt, errorOpt,
            minEigenValOpt);
    return argMap;
}