Example usage for org.apache.commons.cli OptionGroup addOption

List of usage examples for org.apache.commons.cli OptionGroup addOption

Introduction

In this page you can find the example usage for org.apache.commons.cli OptionGroup addOption.

Prototype

public OptionGroup addOption(Option option) 

Source Link

Document

Add the specified Option to this group.

Usage

From source file:com.discursive.jccook.cmdline.SomeApp.java

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

    // Create a Parser
    CommandLineParser parser = new BasicParser();
    Options options = new Options();
    options.addOption("h", "help", false, "Print this usage information");
    options.addOption("v", "verbose", false, "Print out VERBOSE information");

    OptionGroup optionGroup = new OptionGroup();
    optionGroup.addOption(OptionBuilder.hasArg(true).withArgName("file").withLongOpt("file").create('f'));
    optionGroup.addOption(OptionBuilder.hasArg(true).withArgName("email").withLongOpt("email").create('m'));
    options.addOptionGroup(optionGroup);

    // Parse the program arguments
    try {//from  w  w w . j a  va2s  .c o m
        CommandLine commandLine = parser.parse(options, args);

        if (commandLine.hasOption('h')) {
            printUsage(options);
            System.exit(0);
        }

        // ... do important stuff ...
    } catch (Exception e) {
        System.out.println("You provided bad program arguments!");
        printUsage(options);
        System.exit(1);
    }
}

From source file:com.discursive.jccook.cmdline.CliComplexExample.java

public static void main(String[] args) throws Exception {
    CommandLineParser parser = new BasicParser();

    Options options = new Options();
    options.addOption("h", "help", false, "Print this usage information");
    options.addOption("v", "verbose", false, "Print out VERBOSE debugging information");
    OptionGroup optionGroup = new OptionGroup();
    optionGroup.addOption(OptionBuilder.hasArg(true).create('f'));
    optionGroup.addOption(OptionBuilder.hasArg(true).create('m'));
    options.addOptionGroup(optionGroup);

    CommandLine commandLine = parser.parse(options, args);

    boolean verbose = false;
    String file = "";
    String mail = "";

    if (commandLine.hasOption('h')) {
        System.out.println("Help Message");
        System.exit(0);/*  www .  ja v a  2s .com*/
    }

    if (commandLine.hasOption('v')) {
        verbose = true;
    }

    if (commandLine.hasOption('f')) {
        file = commandLine.getOptionValue('f');
    } else if (commandLine.hasOption('m')) {
        mail = commandLine.getOptionValue('m');
    }

    System.exit(0);
}

From source file:de.uni_koblenz.jgralabtest.non_junit_tests.TryCLI.java

/**
 * @param args//from  w  w w .j  a  v a2s. c o m
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub
    OptionHandler oh = new OptionHandler("TryCli", "version 0.0");

    // Option multipleValues = new Option("m", "multiple", true,
    // "Can occur multiple times.");
    // multipleValues.setRequired(true);
    // multipleValues.setArgName("arg");
    // multipleValues.setValueSeparator(',');
    // multipleValues.setArgs(Option.UNLIMITED_VALUES);

    // Option multipleValues2 = new Option("M", "Multiple", true,
    // "Can occur multiple times.");
    // multipleValues2.setRequired(false);
    // multipleValues2.setArgName("arg");
    // multipleValues2.setValueSeparator(',');
    // multipleValues2.setOptionalArg(true);
    // multipleValues2.setArgs(Option.UNLIMITED_VALUES);

    Option test = new Option("t", "test", false, "For testing purpose.");
    test.setRequired(false);
    oh.addOption(test);

    Option test2 = new Option("T", "Test", false, "For testing purpose.");
    test2.setRequired(false);
    oh.addOption(test2);

    OptionGroup og = new OptionGroup();
    og.addOption(test);
    og.addOption(test2);
    og.setRequired(true);
    oh.addOptionGroup(og);

    // oh.addOption(multipleValues);
    // oh.addOption(multipleValues2);

    CommandLine cmd = oh.parse(args);

    if (cmd.hasOption('t')) {
        System.out.println("Test1 set");
    }
    if (cmd.hasOption('T')) {
        System.out.println("Test2 set");
    }

}

From source file:com.dasasian.chok.tool.ZkTool.java

public static void main(String[] args) {
    final Options options = new Options();

    Option lsOption = new Option("ls", true, "list zp path contents");
    lsOption.setArgName("path");
    Option readOption = new Option("read", true, "read and print zp path contents");
    readOption.setArgName("path");
    Option rmOption = new Option("rm", true, "remove zk files");
    rmOption.setArgName("path");
    Option rmrOption = new Option("rmr", true, "remove zk directories");
    rmrOption.setArgName("path");

    OptionGroup actionGroup = new OptionGroup();
    actionGroup.setRequired(true);//  w w w.  jav  a 2  s .c o m
    actionGroup.addOption(lsOption);
    actionGroup.addOption(readOption);
    actionGroup.addOption(rmOption);
    actionGroup.addOption(rmrOption);
    options.addOptionGroup(actionGroup);

    final CommandLineParser parser = new GnuParser();
    HelpFormatter formatter = new HelpFormatter();
    try {
        final CommandLine line = parser.parse(options, args);
        ZkTool zkTool = new ZkTool();
        if (line.hasOption(lsOption.getOpt())) {
            String path = line.getOptionValue(lsOption.getOpt());
            zkTool.ls(path);
        } else if (line.hasOption(readOption.getOpt())) {
            String path = line.getOptionValue(readOption.getOpt());
            zkTool.read(path);
        } else if (line.hasOption(rmOption.getOpt())) {
            String path = line.getOptionValue(rmOption.getOpt());
            zkTool.rm(path, false);
        } else if (line.hasOption(rmrOption.getOpt())) {
            String path = line.getOptionValue(rmrOption.getOpt());
            zkTool.rm(path, true);
        }
        zkTool.close();
    } catch (ParseException e) {
        System.out.println(e.getClass().getSimpleName() + ": " + e.getMessage());
        formatter.printHelp(ZkTool.class.getSimpleName(), options);
    }

}

From source file:com.example.bigquery.QuerySample.java

/** Prompts the user for the required parameters to perform a query. */
public static void main(final String[] args)
        throws IOException, InterruptedException, TimeoutException, ParseException {
    Options options = new Options();

    // Use an OptionsGroup to choose which sample to run.
    OptionGroup samples = new OptionGroup();
    samples.addOption(Option.builder().longOpt("runSimpleQuery").build());
    samples.addOption(Option.builder().longOpt("runStandardSqlQuery").build());
    samples.addOption(Option.builder().longOpt("runPermanentTableQuery").build());
    samples.addOption(Option.builder().longOpt("runUncachedQuery").build());
    samples.addOption(Option.builder().longOpt("runBatchQuery").build());
    samples.isRequired();/*from   w w  w.jav  a 2 s  .  com*/
    options.addOptionGroup(samples);

    options.addOption(Option.builder().longOpt("query").hasArg().required().build());
    options.addOption(Option.builder().longOpt("destDataset").hasArg().build());
    options.addOption(Option.builder().longOpt("destTable").hasArg().build());
    options.addOption(Option.builder().longOpt("allowLargeResults").build());

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(options, args);

    String query = cmd.getOptionValue("query");
    if (cmd.hasOption("runSimpleQuery")) {
        runSimpleQuery(query);
    } else if (cmd.hasOption("runStandardSqlQuery")) {
        runStandardSqlQuery(query);
    } else if (cmd.hasOption("runPermanentTableQuery")) {
        String destDataset = cmd.getOptionValue("destDataset");
        String destTable = cmd.getOptionValue("destTable");
        boolean allowLargeResults = cmd.hasOption("allowLargeResults");
        runQueryPermanentTable(query, destDataset, destTable, allowLargeResults);
    } else if (cmd.hasOption("runUncachedQuery")) {
        runUncachedQuery(query);
    } else if (cmd.hasOption("runBatchQuery")) {
        runBatchQuery(query);
    }
}

From source file:de.burlov.amazon.s3.S3Utils.java

public static void main(String[] args) {
    Options opts = new Options();
    OptionGroup gr = new OptionGroup();
    gr.setRequired(true);/*from w  w  w  . jav a  2  s  .c o  m*/
    gr.addOption(new Option(LIST, false, ""));
    gr.addOption(new Option(DELETE, false, ""));

    opts.addOptionGroup(gr);

    opts.addOption(new Option("k", true, "Access key for AWS account"));
    opts.addOption(new Option("s", true, "Secret key for AWS account"));
    opts.addOption(new Option("b", true, "Bucket"));
    CommandLine cmd = null;
    try {
        cmd = new PosixParser().parse(opts, args);

        String accessKey = cmd.getOptionValue("k");
        if (StringUtils.isBlank(accessKey)) {
            System.out.println("Missing amazon access key");
            return;
        }
        String secretKey = cmd.getOptionValue("s");
        if (StringUtils.isBlank(secretKey)) {
            System.out.println("Missing secret key");
            return;
        }
        String bucket = cmd.getOptionValue("b");
        if (cmd.hasOption(LIST)) {
            if (StringUtils.isBlank(bucket)) {
                printBuckets(accessKey, secretKey);
            } else {
                printBucket(accessKey, secretKey, bucket);
            }
        } else if (cmd.hasOption(DELETE)) {
            if (StringUtils.isBlank(bucket)) {
                System.out.println("Bucket name required");
                return;
            }
            int count = deleteBucket(accessKey, secretKey, bucket);
            System.out.println("Deleted objects in bucket: " + count);
        }
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        printUsage(opts);
        return;
    } catch (Exception e) {
        e.printStackTrace(System.err);
    }
}

From source file:edu.wisc.doit.tcrypt.cli.TokenCrypt.java

public static void main(String[] args) throws IOException {
    // create Options object
    final Options options = new Options();

    // operation opt group
    final OptionGroup cryptTypeGroup = new OptionGroup();
    cryptTypeGroup.addOption(new Option("e", "encrypt", false, "Encrypt a token"));
    cryptTypeGroup.addOption(new Option("d", "decrypt", false, "Decrypt a token"));
    cryptTypeGroup/* w ww. ja va  2 s .c o m*/
            .addOption(new Option("c", "check", false, "Check if the string looks like an encrypted token"));
    cryptTypeGroup.setRequired(true);
    options.addOptionGroup(cryptTypeGroup);

    // token source opt group
    final OptionGroup tokenGroup = new OptionGroup();
    final Option tokenOpt = new Option("t", "token", true, "The token(s) to operate on");
    tokenOpt.setArgs(Option.UNLIMITED_VALUES);
    tokenGroup.addOption(tokenOpt);
    final Option tokenFileOpt = new Option("f", "file", true,
            "A file with one token per line to operate on, if - is specified stdin is used");
    tokenGroup.addOption(tokenFileOpt);
    tokenGroup.setRequired(true);
    options.addOptionGroup(tokenGroup);

    final Option keyOpt = new Option("k", "keyFile", true,
            "Key file to use. Must be a private key for decryption and a public key for encryption");
    keyOpt.setRequired(true);
    options.addOption(keyOpt);

    // create the parser
    final CommandLineParser parser = new GnuParser();
    CommandLine line = null;
    try {
        // parse the command line arguments
        line = parser.parse(options, args);
    } catch (ParseException exp) {
        // automatically generate the help statement
        System.err.println(exp.getMessage());
        final HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java " + TokenCrypt.class.getName(), options, true);
        System.exit(1);
    }

    final Reader keyReader = createKeyReader(line);

    final TokenHandler tokenHandler = createTokenHandler(line, keyReader);

    if (line.hasOption("t")) {
        //tokens on cli
        final String[] tokens = line.getOptionValues("t");
        for (final String token : tokens) {
            handleToken(tokenHandler, token);
        }
    } else {
        //tokens from a file
        final String tokenFile = line.getOptionValue("f");
        final BufferedReader fileReader;
        if ("-".equals(tokenFile)) {
            fileReader = new BufferedReader(new InputStreamReader(System.in));
        } else {
            fileReader = new BufferedReader(new FileReader(tokenFile));
        }

        while (true) {
            final String token = fileReader.readLine();
            if (token == null) {
                break;
            }

            handleToken(tokenHandler, token);
        }
    }
}

From source file:asl.seedscan.DQAWeb.java

public static void main(String args[]) {
    db = new MetricDatabase("", "", "");
    findConsoleHandler();/*from w  w w .j a v  a2 s  .c om*/
    consoleHandler.setLevel(Level.ALL);
    Logger.getLogger("").setLevel(Level.CONFIG);

    // Default locations of config and schema files
    File configFile = new File("dqaweb-config.xml");
    File schemaFile = new File("schemas/DQAWebConfig.xsd");
    boolean parseConfig = true;
    boolean testMode = false;

    ArrayList<File> schemaFiles = new ArrayList<File>();
    schemaFiles.add(schemaFile);
    // ==== Command Line Parsing ====
    Options options = new Options();
    Option opConfigFile = new Option("c", "config-file", true,
            "The config file to use for seedscan. XML format according to SeedScanConfig.xsd.");
    Option opSchemaFile = new Option("s", "schema-file", true,
            "The schame file which should be used to verify the config file format. ");
    Option opTest = new Option("t", "test", false, "Run in test console mode rather than as a servlet.");

    OptionGroup ogConfig = new OptionGroup();
    ogConfig.addOption(opConfigFile);

    OptionGroup ogSchema = new OptionGroup();
    ogConfig.addOption(opSchemaFile);

    OptionGroup ogTest = new OptionGroup();
    ogTest.addOption(opTest);

    options.addOptionGroup(ogConfig);
    options.addOptionGroup(ogSchema);
    options.addOptionGroup(ogTest);

    PosixParser optParser = new PosixParser();
    CommandLine cmdLine = null;
    try {
        cmdLine = optParser.parse(options, args, true);
    } catch (org.apache.commons.cli.ParseException e) {
        logger.severe("Error while parsing command-line arguments.");
        System.exit(1);
    }

    Option opt;
    Iterator iter = cmdLine.iterator();
    while (iter.hasNext()) {
        opt = (Option) iter.next();

        if (opt.getOpt().equals("c")) {
            configFile = new File(opt.getValue());
        } else if (opt.getOpt().equals("s")) {
            schemaFile = new File(opt.getValue());
        } else if (opt.getOpt().equals("t")) {
            testMode = true;
        }
    }
    String query = "";
    System.out.println("Entering Test Mode");
    System.out.println("Enter a query string to view results or type \"help\" for example query strings");
    InputStreamReader input = new InputStreamReader(System.in);
    BufferedReader reader = new BufferedReader(input);
    String result = "";

    while (testMode == true) {
        try {

            System.out.printf("Query: ");
            query = reader.readLine();
            if (query.equals("exit")) {
                testMode = false;
            } else if (query.equals("help")) {
                System.out.println("Need to add some help for people"); //TODO
            } else {
                result = processCommand(query);
            }
            System.out.println(result);
        } catch (IOException err) {
            System.err.println("Error reading line, in DQAWeb.java");
        }
    }
    System.err.printf("DONE.\n");
}

From source file:imageviewer.util.PasswordGenerator.java

public static void main(String[] args) {

    Option help = new Option("help", "Print this message");
    Option file = OptionBuilder.withArgName("file").hasArg().withDescription("Password filename")
            .create("file");
    Option addUser = OptionBuilder.withArgName("add").hasArg().withDescription("Add user profile")
            .create("add");
    Option removeUser = OptionBuilder.withArgName("remove").hasArg().withDescription("Remove user profile")
            .create("remove");
    Option updateUser = OptionBuilder.withArgName("update").hasArg().withValueSeparator()
            .withDescription("Update user profile").create("update");

    file.setRequired(true);//w  w w . java  2  s  .c om
    OptionGroup og = new OptionGroup();
    og.addOption(addUser);
    og.addOption(removeUser);
    og.addOption(updateUser);
    og.setRequired(true);

    Options o = new Options();
    o.addOption(help);
    o.addOption(file);
    o.addOptionGroup(og);

    try {
        CommandLineParser parser = new GnuParser();
        CommandLine line = parser.parse(o, args);
        PasswordGenerator pg = new PasswordGenerator(line);
        pg.execute();
    } catch (UnrecognizedOptionException uoe) {
        System.err.println("Unknown argument: " + uoe.getMessage());
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp("PasswordGenerator", o);
        System.exit(1);
    } catch (MissingOptionException moe) {
        System.err.println("Missing argument: " + moe.getMessage());
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp("PasswordGenerator", o);
        System.exit(1);
    } catch (Exception exc) {
        exc.printStackTrace();
    }
}

From source file:com.hortonworks.registries.schemaregistry.examples.avro.KafkaAvroSerDesApp.java

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

    Option sendMessages = Option.builder("sm").longOpt("send-messages").desc("Send Messages to Kafka")
            .type(Boolean.class).build();
    Option consumeMessages = Option.builder("cm").longOpt("consume-messages")
            .desc("Consume Messages from Kafka").type(Boolean.class).build();

    Option dataFileOption = Option.builder("d").longOpt("data-file").hasArg().desc("Provide a data file")
            .type(String.class).build();
    Option producerFileOption = Option.builder("p").longOpt("producer-config").hasArg()
            .desc("Provide a Kafka producer config file").type(String.class).build();
    Option schemaOption = Option.builder("s").longOpt("schema-file").hasArg().desc("Provide a schema file")
            .type(String.class).build();

    Option consumerFileOption = Option.builder("c").longOpt("consumer-config").hasArg()
            .desc("Provide a Kafka Consumer config file").type(String.class).build();

    OptionGroup groupOpt = new OptionGroup();
    groupOpt.addOption(sendMessages);
    groupOpt.addOption(consumeMessages);
    groupOpt.setRequired(true);/*from   ww  w  .  j a  v a2 s .  co  m*/

    Options options = new Options();
    options.addOptionGroup(groupOpt);
    options.addOption(dataFileOption);
    options.addOption(producerFileOption);
    options.addOption(schemaOption);
    options.addOption(consumerFileOption);

    //showHelpMessage(args, options);

    CommandLineParser parser = new DefaultParser();
    CommandLine commandLine;

    try {
        commandLine = parser.parse(options, args);
        if (commandLine.hasOption("sm")) {
            if (commandLine.hasOption("p") && commandLine.hasOption("d") && commandLine.hasOption("s")) {
                KafkaAvroSerDesApp kafkaAvroSerDesApp = new KafkaAvroSerDesApp(commandLine.getOptionValue("p"),
                        commandLine.getOptionValue("s"));
                kafkaAvroSerDesApp.sendMessages(commandLine.getOptionValue("d"));
            } else {
                LOG.error("please provide following options for sending messages to Kafka");
                LOG.error("-d or --data-file");
                LOG.error("-s or --schema-file");
                LOG.error("-p or --producer-config");
            }
        } else if (commandLine.hasOption("cm")) {
            if (commandLine.hasOption("c")) {
                KafkaAvroSerDesApp kafkaAvroSerDesApp = new KafkaAvroSerDesApp(commandLine.getOptionValue("c"));
                kafkaAvroSerDesApp.consumeMessages();
            } else {
                LOG.error("please provide following options for consuming messages from Kafka");
                LOG.error("-c or --consumer-config");
            }
        }
    } catch (ParseException e) {
        LOG.error("Please provide all the options ", e);
    } catch (Exception e) {
        LOG.error("Failed to send/receive messages ", e);
    }

}