Example usage for org.apache.commons.cli Options addOptionGroup

List of usage examples for org.apache.commons.cli Options addOptionGroup

Introduction

In this page you can find the example usage for org.apache.commons.cli Options addOptionGroup.

Prototype

public Options addOptionGroup(OptionGroup group) 

Source Link

Document

Add the specified option group.

Usage

From source file:com.example.dlp.Redact.java

/** Command line application to redact strings, images using the Data Loss Prevention API. */
public static void main(String[] args) throws Exception {
    OptionGroup optionsGroup = new OptionGroup();
    optionsGroup.setRequired(true);/*from ww w .ja v  a2  s.  com*/
    Option stringOption = new Option("s", "string", true, "redact string");
    optionsGroup.addOption(stringOption);

    Option fileOption = new Option("f", "file path", true, "redact input file path");
    optionsGroup.addOption(fileOption);

    Options commandLineOptions = new Options();
    commandLineOptions.addOptionGroup(optionsGroup);

    Option minLikelihoodOption = Option.builder("minLikelihood").hasArg(true).required(false).build();

    commandLineOptions.addOption(minLikelihoodOption);

    Option replaceOption = Option.builder("r").longOpt("replace string").hasArg(true).required(false).build();
    commandLineOptions.addOption(replaceOption);

    Option infoTypesOption = Option.builder("infoTypes").hasArg(true).required(false).build();
    infoTypesOption.setArgs(Option.UNLIMITED_VALUES);
    commandLineOptions.addOption(infoTypesOption);

    Option outputFilePathOption = Option.builder("o").hasArg(true).longOpt("outputFilePath").required(false)
            .build();
    commandLineOptions.addOption(outputFilePathOption);

    CommandLineParser parser = new DefaultParser();
    HelpFormatter formatter = new HelpFormatter();
    CommandLine cmd;

    try {
        cmd = parser.parse(commandLineOptions, args);
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        formatter.printHelp(Redact.class.getName(), commandLineOptions);
        System.exit(1);
        return;
    }

    String replacement = cmd.getOptionValue(replaceOption.getOpt(), "_REDACTED_");

    List<InfoType> infoTypesList = new ArrayList<>();
    String[] infoTypes = cmd.getOptionValues(infoTypesOption.getOpt());
    if (infoTypes != null) {
        for (String infoType : infoTypes) {
            infoTypesList.add(InfoType.newBuilder().setName(infoType).build());
        }
    }
    Likelihood minLikelihood = Likelihood.valueOf(
            cmd.getOptionValue(minLikelihoodOption.getOpt(), Likelihood.LIKELIHOOD_UNSPECIFIED.name()));

    // string inspection
    if (cmd.hasOption("s")) {
        String source = cmd.getOptionValue(stringOption.getOpt());
        redactString(source, replacement, minLikelihood, infoTypesList);
    } else if (cmd.hasOption("f")) {
        String filePath = cmd.getOptionValue(fileOption.getOpt());
        String outputFilePath = cmd.getOptionValue(outputFilePathOption.getOpt());
        redactImage(filePath, minLikelihood, infoTypesList, outputFilePath);
    }
}

From source file:com.example.dlp.DeIdentification.java

/**
 * Command line application to de-identify data using the Data Loss Prevention API.
 * Supported data format: strings/*from ww w.  ja v a2  s.  c  o m*/
 */
public static void main(String[] args) throws Exception {

    OptionGroup optionsGroup = new OptionGroup();
    optionsGroup.setRequired(true);

    Option deidentifyMaskingOption = new Option("m", "mask", true, "deid with character masking");
    optionsGroup.addOption(deidentifyMaskingOption);

    Option deidentifyFpeOption = new Option("f", "fpe", true, "deid with FFX FPE");
    optionsGroup.addOption(deidentifyFpeOption);

    Options commandLineOptions = new Options();
    commandLineOptions.addOptionGroup(optionsGroup);

    Option maskingCharacterOption = Option.builder("maskingCharacter").hasArg(true).required(false).build();
    commandLineOptions.addOption(maskingCharacterOption);

    Option numberToMaskOption = Option.builder("numberToMask").hasArg(true).required(false).build();
    commandLineOptions.addOption(numberToMaskOption);

    Option alphabetOption = Option.builder("commonAlphabet").hasArg(true).required(false).build();
    commandLineOptions.addOption(alphabetOption);

    Option wrappedKeyOption = Option.builder("wrappedKey").hasArg(true).required(false).build();
    commandLineOptions.addOption(wrappedKeyOption);

    Option keyNameOption = Option.builder("keyName").hasArg(true).required(false).build();
    commandLineOptions.addOption(keyNameOption);

    CommandLineParser parser = new DefaultParser();
    HelpFormatter formatter = new HelpFormatter();
    CommandLine cmd;

    try {
        cmd = parser.parse(commandLineOptions, args);
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        formatter.printHelp(DeIdentification.class.getName(), commandLineOptions);
        System.exit(1);
        return;
    }

    if (cmd.hasOption("m")) {
        // deidentification with character masking
        int numberToMask = Integer.parseInt(cmd.getOptionValue(numberToMaskOption.getOpt(), "0"));
        char maskingCharacter = cmd.getOptionValue(maskingCharacterOption.getOpt(), "*").charAt(0);
        String val = cmd.getOptionValue(deidentifyMaskingOption.getOpt());
        deIdentifyWithMask(val, maskingCharacter, numberToMask);
    } else if (cmd.hasOption("f")) {
        // deidentification with FPE
        String wrappedKey = cmd.getOptionValue(wrappedKeyOption.getOpt());
        String keyName = cmd.getOptionValue(keyNameOption.getOpt());
        String val = cmd.getOptionValue(deidentifyFpeOption.getOpt());
        FfxCommonNativeAlphabet alphabet = FfxCommonNativeAlphabet.valueOf(
                cmd.getOptionValue(alphabetOption.getOpt(), FfxCommonNativeAlphabet.ALPHA_NUMERIC.name()));
        deIdentifyWithFpe(val, alphabet, keyName, wrappedKey);
    }
}

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);//from  w ww . j  a  v  a  2  s  .  co m
    groupOpt.addOption(consumeMessages);
    groupOpt.setRequired(true);

    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);
    }

}

From source file:com.hortonworks.registries.schemaregistry.examples.avro.TruckEventsKafkaAvroSerDesApp.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);//from w ww  . j  a va  2 s.  c om
    groupOpt.addOption(consumeMessages);
    groupOpt.setRequired(true);

    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")) {
                TruckEventsKafkaAvroSerDesApp truckEventsKafkaAvroSerDesApp = new TruckEventsKafkaAvroSerDesApp(
                        commandLine.getOptionValue("p"), commandLine.getOptionValue("s"));
                truckEventsKafkaAvroSerDesApp.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")) {
                TruckEventsKafkaAvroSerDesApp truckEventsKafkaAvroSerDesApp = new TruckEventsKafkaAvroSerDesApp(
                        commandLine.getOptionValue("c"));
                truckEventsKafkaAvroSerDesApp.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);
    }

}

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);//from  w  ww.j  av a  2s. 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:de.burlov.amazon.s3.S3Utils.java

public static void main(String[] args) {
    Options opts = new Options();
    OptionGroup gr = new OptionGroup();
    gr.setRequired(true);// w ww  .jav  a 2s  . 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:com.example.dlp.RiskAnalysis.java

/**
 * Command line application to perform risk analysis using the Data Loss Prevention API.
 * Supported data format: BigQuery tables
 *//*w w w.j  a  v a  2s. co  m*/
public static void main(String[] args) throws Exception {

    OptionGroup optionsGroup = new OptionGroup();
    optionsGroup.setRequired(true);

    Option numericalAnalysisOption = new Option("n", "numerical");
    optionsGroup.addOption(numericalAnalysisOption);

    Option categoricalAnalysisOption = new Option("c", "categorical");
    optionsGroup.addOption(categoricalAnalysisOption);

    Option kanonymityOption = new Option("k", "kAnonymity");
    optionsGroup.addOption(kanonymityOption);

    Option ldiversityOption = new Option("l", "lDiversity");
    optionsGroup.addOption(ldiversityOption);

    Options commandLineOptions = new Options();
    commandLineOptions.addOptionGroup(optionsGroup);

    Option datasetIdOption = Option.builder("datasetId").hasArg(true).required(false).build();
    commandLineOptions.addOption(datasetIdOption);

    Option tableIdOption = Option.builder("tableId").hasArg(true).required(false).build();
    commandLineOptions.addOption(tableIdOption);

    Option projectIdOption = Option.builder("projectId").hasArg(true).required(false).build();
    commandLineOptions.addOption(projectIdOption);

    Option columnNameOption = Option.builder("columnName").hasArg(true).required(false).build();
    commandLineOptions.addOption(columnNameOption);

    Option sensitiveAttributeOption = Option.builder("sensitiveAttribute").hasArg(true).required(false).build();
    commandLineOptions.addOption(sensitiveAttributeOption);

    Option quasiIdColumnNamesOption = Option.builder("quasiIdColumnNames").hasArg(true).required(false).build();
    commandLineOptions.addOption(quasiIdColumnNamesOption);

    CommandLineParser parser = new DefaultParser();
    HelpFormatter formatter = new HelpFormatter();
    CommandLine cmd;

    try {
        cmd = parser.parse(commandLineOptions, args);
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        formatter.printHelp(RiskAnalysis.class.getName(), commandLineOptions);
        System.exit(1);
        return;
    }

    String datasetId = cmd.getOptionValue(datasetIdOption.getOpt());
    String tableId = cmd.getOptionValue(tableIdOption.getOpt());
    // use default project id when project id is not specified
    String projectId = cmd.getOptionValue(projectIdOption.getOpt(), ServiceOptions.getDefaultProjectId());

    if (cmd.hasOption("n")) {
        // numerical stats analysis
        String columnName = cmd.getOptionValue(columnNameOption.getOpt());
        calculateNumericalStats(projectId, datasetId, tableId, columnName);
    } else if (cmd.hasOption("c")) {
        // categorical stats analysis
        String columnName = cmd.getOptionValue(columnNameOption.getOpt());
        calculateCategoricalStats(projectId, datasetId, tableId, columnName);
    } else if (cmd.hasOption("k")) {
        // k-anonymity analysis
        List<String> quasiIdColumnNames = Arrays.asList(cmd.getOptionValues(quasiIdColumnNamesOption.getOpt()));
        calculateKAnonymity(projectId, datasetId, tableId, quasiIdColumnNames);
    } else if (cmd.hasOption("l")) {
        // l-diversity analysis
        String sensitiveAttribute = cmd.getOptionValue(sensitiveAttributeOption.getOpt());
        List<String> quasiIdColumnNames = Arrays.asList(cmd.getOptionValues(quasiIdColumnNamesOption.getOpt()));
        calculateLDiversity(projectId, datasetId, tableId, sensitiveAttribute, quasiIdColumnNames);
    }
}

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);/*from  w w  w.j a  v  a2 s .  c  o m*/
    }

    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: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  ava  2 s. 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:de.unibi.techfak.bibiserv.util.codegen.Main.java

public static void main(String[] args) {
    // check &   validate cmdline options
    OptionGroup opt_g = getCMDLineOptionsGroups();
    Options opt = getCMDLineOptions();
    opt.addOptionGroup(opt_g);

    CommandLineParser cli = new DefaultParser();
    try {/*from   www  . j  a  v  a  2 s .  c o  m*/
        CommandLine cl = cli.parse(opt, args);

        if (cl.hasOption("v")) {
            VerboseOutputFilter.SHOW_VERBOSE = true;
        }

        switch (opt_g.getSelected()) {
        case "V":
            try {
                URL jarUrl = Main.class.getProtectionDomain().getCodeSource().getLocation();
                String jarPath = URLDecoder.decode(jarUrl.getFile(), "UTF-8");
                JarFile jarFile = new JarFile(jarPath);
                Manifest m = jarFile.getManifest();
                StringBuilder versionInfo = new StringBuilder();
                for (Object key : m.getMainAttributes().keySet()) {
                    versionInfo.append(key).append(":").append(m.getMainAttributes().getValue(key.toString()))
                            .append("\n");
                }
                System.out.println(versionInfo.toString());
            } catch (Exception e) {
                log.error("Version info could not be read.");
            }
            break;
        case "h":
            HelpFormatter help = new HelpFormatter();
            String header = ""; //TODO: missing infotext 
            StringBuilder footer = new StringBuilder("Supported configuration properties :");
            help.printHelp("CodeGen -h | -V | -g  [...]", header, opt, footer.toString());
            break;
        case "g":
            // target dir
            if (cl.hasOption("t")) {
                File target = new File(cl.getOptionValue("t"));
                if (target.isDirectory() && target.canExecute() && target.canWrite()) {
                    config.setProperty("target.dir", cl.getOptionValue("t"));
                } else {
                    log.error("Target dir '{}' is inaccessible!", cl.getOptionValue("t"));
                    break;
                }
            } else {
                config.setProperty("target.dir", System.getProperty("java.io.tmpdir"));
            }

            // project dir
            if (cl.hasOption("p")) {
                File project = new File(cl.getOptionValue("p"));
                if (!project.exists()) {
                    if (!project.mkdirs()) {
                        log.error("Project dir '{}' can't be created!", cl.getOptionValue("p"));
                        break;
                    }
                }

                if (project.isDirectory() && project.canExecute() && project.canWrite()) {
                    config.setProperty("project.dir", cl.getOptionValue("p"));
                } else {
                    log.error("Project dir '{}' is inaccessible!", cl.getOptionValue("p"));
                    break;
                }
            }

            generateAppfromXML(cl.getOptionValue("g"));
            break;
        }
    } catch (ParseException e) {
        log.error("ParseException occurred while parsing cmdline arguments!\n{}", e.getLocalizedMessage());
    }

}