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.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);
    groupOpt.addOption(consumeMessages);
    groupOpt.setRequired(true);/*from   w  w  w .j av  a2  s. c  o  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")) {
                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:it.unipd.dei.ims.falcon.CmdLine.java

public static void main(String[] args) {

    // last argument is always index path
    Options options = new Options();
    // one of these actions has to be specified
    OptionGroup actionGroup = new OptionGroup();
    actionGroup.addOption(new Option("i", true, "perform indexing")); // if dir, all files, else only one file
    actionGroup.addOption(new Option("q", true, "perform a single query"));
    actionGroup.addOption(new Option("b", false, "perform a query batch (read from stdin)"));
    actionGroup.setRequired(true);//from   w ww .jav a  2  s  . c  o m
    options.addOptionGroup(actionGroup);

    // other options
    options.addOption(new Option("l", "segment-length", true, "length of a segment (# of chroma vectors)"));
    options.addOption(
            new Option("o", "segment-overlap", true, "overlap portion of a segment (# of chroma vectors)"));
    options.addOption(new Option("Q", "quantization-level", true, "quantization level for chroma vectors"));
    options.addOption(new Option("k", "min-kurtosis", true, "minimum kurtosis for indexing chroma vectors"));
    options.addOption(new Option("s", "sub-sampling", true, "sub-sampling of chroma features"));
    options.addOption(new Option("v", "verbose", false, "verbose output (including timing info)"));
    options.addOption(new Option("T", "transposition-estimator-strategy", true,
            "parametrization for the transposition estimator strategy"));
    options.addOption(new Option("t", "n-transp", true,
            "number of transposition; if not specified, no transposition is performed"));
    options.addOption(new Option("f", "force-transp", true, "force transposition by an amount of semitones"));
    options.addOption(new Option("p", "pruning", false,
            "enable query pruning; if -P is unspecified, use default strategy"));
    options.addOption(new Option("P", "pruning-custom", true, "custom query pruning strategy"));

    // parse
    HelpFormatter formatter = new HelpFormatter();
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
        if (cmd.getArgs().length != 1)
            throw new ParseException("no index path was specified");
    } catch (ParseException ex) {
        System.err.println("ERROR - parsing command line:");
        System.err.println(ex.getMessage());
        formatter.printHelp("falcon -{i,q,b} [options] index_path", options);
        return;
    }

    // default values
    final float[] DEFAULT_TRANSPOSITION_ESTIMATOR_STRATEGY = new float[] { 0.65192807f, 0.0f, 0.0f, 0.0f,
            0.3532628f, 0.4997167f, 0.0f, 0.41703504f, 0.0f, 0.16297342f, 0.0f, 0.0f };
    final String DEFAULT_QUERY_PRUNING_STRATEGY = "ntf:0.340765*[0.001694,0.995720];ndf:0.344143*[0.007224,0.997113];"
            + "ncf:0.338766*[0.001601,0.995038];nmf:0.331577*[0.002352,0.997884];"; // TODO not the final one

    int hashes_per_segment = Integer.parseInt(cmd.getOptionValue("l", "150"));
    int overlap_per_segment = Integer.parseInt(cmd.getOptionValue("o", "50"));
    int nranks = Integer.parseInt(cmd.getOptionValue("Q", "3"));
    int subsampling = Integer.parseInt(cmd.getOptionValue("s", "1"));
    double minkurtosis = Float.parseFloat(cmd.getOptionValue("k", "-100."));
    boolean verbose = cmd.hasOption("v");
    int ntransp = Integer.parseInt(cmd.getOptionValue("t", "1"));
    TranspositionEstimator tpe = null;
    if (cmd.hasOption("t")) {
        if (cmd.hasOption("T")) {
            // TODO this if branch is yet to test
            Pattern p = Pattern.compile("\\d\\.\\d*");
            LinkedList<Double> tokens = new LinkedList<Double>();
            Matcher m = p.matcher(cmd.getOptionValue("T"));
            while (m.find())
                tokens.addLast(new Double(cmd.getOptionValue("T").substring(m.start(), m.end())));
            float[] strategy = new float[tokens.size()];
            if (strategy.length != 12) {
                System.err.println("invalid transposition estimator strategy");
                System.exit(1);
            }
            for (int i = 0; i < strategy.length; i++)
                strategy[i] = new Float(tokens.pollFirst());
        } else {
            tpe = new TranspositionEstimator(DEFAULT_TRANSPOSITION_ESTIMATOR_STRATEGY);
        }
    } else if (cmd.hasOption("f")) {
        int[] transps = parseIntArray(cmd.getOptionValue("f"));
        tpe = new ForcedTranspositionEstimator(transps);
        ntransp = transps.length;
    }
    QueryPruningStrategy qpe = null;
    if (cmd.hasOption("p")) {
        if (cmd.hasOption("P")) {
            qpe = new StaticQueryPruningStrategy(cmd.getOptionValue("P"));
        } else {
            qpe = new StaticQueryPruningStrategy(DEFAULT_QUERY_PRUNING_STRATEGY);
        }
    }

    // action
    if (cmd.hasOption("i")) {
        try {
            Indexing.index(new File(cmd.getOptionValue("i")), new File(cmd.getArgs()[0]), hashes_per_segment,
                    overlap_per_segment, subsampling, nranks, minkurtosis, tpe, verbose);
        } catch (IndexingException ex) {
            Logger.getLogger(CmdLine.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(CmdLine.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    if (cmd.hasOption("q")) {
        String queryfilepath = cmd.getOptionValue("q");
        doQuery(cmd, queryfilepath, hashes_per_segment, overlap_per_segment, nranks, subsampling, tpe, ntransp,
                minkurtosis, qpe, verbose);
    }
    if (cmd.hasOption("b")) {
        try {
            long starttime = System.currentTimeMillis();
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            String line = null;
            while ((line = in.readLine()) != null && !line.trim().isEmpty())
                doQuery(cmd, line, hashes_per_segment, overlap_per_segment, nranks, subsampling, tpe, ntransp,
                        minkurtosis, qpe, verbose);
            in.close();
            long endtime = System.currentTimeMillis();
            System.out.println(String.format("total time: %ds", (endtime - starttime) / 1000));
        } catch (IOException ex) {
            Logger.getLogger(CmdLine.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:fdtutilscli.Main.java

/**
 * /*w ww .j ava 2 s.  c  o m*/
 * @param args the command line arguments
 */
public static void main(String[] args) {

    CommandLineParser parser = new PosixParser();
    CommandLine line = null;
    Options options = new Options();
    OptionGroup optCommand = new OptionGroup();
    OptionGroup optOutput = new OptionGroup();
    HelpFormatter formatter = new HelpFormatter();
    TRACE trace = TRACE.DEFAULT;

    optCommand.addOption(OptionBuilder.withArgName("ndf odf nif key seperator").hasArgs(5)
            .withValueSeparator(' ').withDescription("Description").create("delta"));
    optCommand.addOption(OptionBuilder.withArgName("dupsfile key seperator").hasArgs(3)
            .withDescription("Description").create("duplicates"));
    optCommand.addOption(OptionBuilder.withLongOpt("help").withDescription("print this message.").create("h"));
    optCommand.addOption(
            OptionBuilder.withLongOpt("version").withDescription("print version information.").create("V"));
    optOutput.addOption(new Option("verbose", "be extra verbose"));
    optOutput.addOption(new Option("quiet", "be extra quiet"));
    optOutput.addOption(new Option("silent", "same as --quiet"));
    options.addOptionGroup(optCommand);
    options.addOptionGroup(optOutput);

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

        if (line.hasOption("verbose")) {
            trace = TRACE.VERBOSE;
        } else if (line.hasOption("quiet") || line.hasOption("silent")) {
            trace = TRACE.QUIET;
        }

        if (line.hasOption("h")) {
            formatter.printHelp(HELP_SYNTAX, HELP_HEADER, options, null, true);
            return;
        } else if (line.hasOption("V")) {
            System.out.println(APP_NAME + " version " + VERSION);
            System.out.println("fDTDeltaBuilder version " + DTDeltaBuilder.version());
            System.out.println("DTDuplicateKeyFinder version " + DTDuplicateKeyFinder.version());
            return;
        } else if (line.hasOption("delta")) {
            String ndf = line.getOptionValues("delta")[0];
            String odf = line.getOptionValues("delta")[1];
            String nif = line.getOptionValues("delta")[2];
            Integer key = (line.getOptionValues("delta").length <= 3) ? DEFAULT_KEY
                    : new Integer(line.getOptionValues("delta")[3]);
            String seperator = (line.getOptionValues("delta").length <= 4) ? DEFAULT_SEPERATOR
                    : line.getOptionValues("delta")[4];

            doDelta(ndf, odf, nif, key.intValue(), seperator, trace);

            return;
        } else if (line.hasOption("duplicates")) {
            String dupsFile = line.getOptionValues("duplicates")[0];
            Integer key = (line.getOptionValues("duplicates").length <= 1) ? DEFAULT_KEY
                    : new Integer(line.getOptionValues("duplicates")[1]);
            String seperator = (line.getOptionValues("duplicates").length <= 2) ? DEFAULT_SEPERATOR
                    : line.getOptionValues("duplicates")[2];
            doDuplicates(dupsFile, key.intValue(), seperator, trace);
            return;
        } else if (args.length == 0) {
            formatter.printHelp(HELP_SYNTAX, HELP_HEADER, options, null, true);
        } else {
            throw new UnrecognizedOptionException(E_MSG_UNREC_OPT);
        }

    } catch (UnrecognizedOptionException e) {
        formatter.printHelp(HELP_SYNTAX, HELP_HEADER, options, HELP_FOOTER + e.getMessage(), true);
    } catch (ParseException e) {
        formatter.printHelp(HELP_SYNTAX, HELP_HEADER, options, HELP_FOOTER + e.getMessage(), true);
    }
}

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 w w  w  .  j  av a 2  s .  c om*/
    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:ca.uhn.hunit.run.TestRunner.java

/**
 * @param args/*from www .j  av a2s.c o m*/
 * @throws URISyntaxException
 * @throws JAXBException
 * @throws ConfigurationException
 * @throws InterfaceWontStartException
 * @throws FileNotFoundException
 * @throws ParseException
 */
public static void main(String[] theArgs) throws URISyntaxException, JAXBException, InterfaceWontStartException,
        ConfigurationException, FileNotFoundException, ParseException {
    Options options = new Options();

    OptionGroup fileOptionGroup = new OptionGroup();
    fileOptionGroup.setRequired(false);

    Option option = new Option("f", "file", true, "The path to the file to load the test battery from");
    option.setValueSeparator('=');
    fileOptionGroup.addOption(option);
    option = new Option("c", "classpath", true, "The classpath path to the file to load the test battery from");
    option.setValueSeparator('=');
    fileOptionGroup.addOption(option);
    options.addOptionGroup(fileOptionGroup);

    OptionGroup uiOptionGroup = new OptionGroup();
    option = new Option("g", "gui", false, "Start hUnit in GUI mode (default)");
    uiOptionGroup.addOption(option);
    option = new Option("x", "text", false, "Start hUnit in Text mode");
    uiOptionGroup.addOption(option);
    options.addOptionGroup(uiOptionGroup);

    option = new Option("t", "tests", true, "A comma separated list of tests to execute (default is all)");
    option.setValueSeparator('=');
    option.setRequired(false);
    options.addOption(option);

    Resource defFile = null;
    CommandLine parser;
    boolean textMode = false;

    try {
        parser = new PosixParser().parse(options, theArgs);

        if (parser.hasOption("f")) {
            defFile = new FileSystemResource(parser.getOptionValue("f"));
        } else if (parser.hasOption("c")) {
            defFile = new ClassPathResource(parser.getOptionValue("c"));
        }

        if (parser.hasOption("x")) {
            textMode = true;
        }
    } catch (Exception e) {
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp("java -jar hunit-[version]-jar-with-dependencies.jar [-c FILE|-f FILE] [options]",
                options);

        return;
    }

    String[] testsToExecute = null;

    if (parser.hasOption("t")) {
        testsToExecute = parser.getOptionValue("t").split(",");
    }

    if (textMode) {
        executeInTextMode(defFile, testsToExecute);
    } else {
        executeInGuiMode(defFile, testsToExecute);
    }
}

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// w  w  w .j  ava  2 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.quanticate.opensource.pdftkbox.PDFtkBox.java

public static void main(String[] args) throws Exception {
    // For printing help
    Options optsHelp = new Options();
    optsHelp.addOption(Option.builder("help").required().desc("print this message").build());

    // Normal-style import/export
    Options optsNormal = new Options();
    OptionGroup normal = new OptionGroup();
    Option optExport = Option.builder("export").required().hasArg().desc("export bookmarks from pdf")
            .argName("source-pdf").build();
    normal.addOption(optExport);
    Option optImport = Option.builder("import").required().hasArg().desc("import bookmarks into pdf")
            .argName("source-pdf").build();
    normal.addOption(optImport);//  www.j  a v  a  2s . c o m
    optsNormal.addOptionGroup(normal);
    Option optBookmarks = Option.builder("bookmarks").hasArg().desc("bookmarks definition file")
            .argName("bookmarks").build();
    optsNormal.addOption(optBookmarks);
    Option optOutput = Option.builder("output").hasArg().desc("output to new pdf").argName("pdf").build();
    optsNormal.addOption(optOutput);

    // PDFtk style options
    Options optsPDFtk = new Options();
    OptionGroup pdftk = new OptionGroup();
    Option optDumpData = Option.builder("dump_data").required().desc("dump bookmarks from pdf").build();
    pdftk.addOption(optDumpData);
    Option optUpdateInfo = Option.builder("update_info").required().hasArg().desc("update bookmarks in pdf")
            .argName("bookmarks").build();
    pdftk.addOption(optUpdateInfo);
    optsPDFtk.addOptionGroup(pdftk);
    optsPDFtk.addOption(optOutput);

    // What are we doing?
    CommandLineParser parser = new DefaultParser();

    // Did they want help?
    try {
        parser.parse(optsHelp, args);

        // If we get here, they asked for help
        doPrintHelp(optsHelp, optsNormal, optsPDFtk);
        return;
    } catch (ParseException pe) {
    }

    // Normal-style import/export?
    try {
        CommandLine line = parser.parse(optsNormal, args);

        // Export
        if (line.hasOption(optExport.getOpt())) {
            doExport(line.getOptionValue(optExport.getOpt()), line.getOptionValue(optBookmarks.getOpt()),
                    line.getArgs());
            return;
        }
        // Import with explicit output filename
        if (line.hasOption(optImport.getOpt()) && line.hasOption(optOutput.getOpt())) {
            doImport(line.getOptionValue(optImport.getOpt()), line.getOptionValue(optBookmarks.getOpt()),
                    line.getOptionValue(optOutput.getOpt()), null);
            return;
        }
        // Import with implicit output filename
        if (line.hasOption(optImport.getOpt()) && line.getArgs().length > 0) {
            doImport(line.getOptionValue(optImport.getOpt()), line.getOptionValue(optBookmarks.getOpt()), null,
                    line.getArgs());
            return;
        }
    } catch (ParseException pe) {
    }

    // PDFtk-style
    if (args.length > 1) {
        // Nobble things for PDFtk-style options and Commons CLI
        for (int i = 1; i < args.length; i++) {
            for (Option opt : optsPDFtk.getOptions()) {
                if (args[i].equals(opt.getOpt())) {
                    args[i] = "-" + args[i];
                }
            }
        }
        try {
            // Input file comes first, then arguments
            String input = args[0];
            String[] pargs = new String[args.length - 1];
            System.arraycopy(args, 1, pargs, 0, pargs.length);

            // Parse what's left and check
            CommandLine line = parser.parse(optsPDFtk, pargs);

            if (line.hasOption(optDumpData.getOpt())) {
                doExport(input, line.getOptionValue(optOutput.getOpt()), line.getArgs());
                return;
            }
            if (line.hasOption(optUpdateInfo.getOpt())) {
                doImport(input, line.getOptionValue(optUpdateInfo.getOpt()),
                        line.getOptionValue(optOutput.getOpt()), line.getArgs());
                return;
            }
        } catch (ParseException pe) {
        }
    }

    // If in doubt, print help
    doPrintHelp(optsHelp, optsNormal, optsPDFtk);
}

From source file:com.github.andreax79.meca.Main.java

@SuppressWarnings("static-access")
public static void main(String[] args) {
    // create the command line parser
    CommandLineParser parser = new PosixParser();

    // create the Options
    Options options = new Options();
    options.addOption("X", "suppress-output", false, "don't create the output file");

    OptionGroup boundariesOptions = new OptionGroup();
    boundariesOptions.addOption(new Option("P", "periodic", false, "periodic boundaries (default)"));
    boundariesOptions.addOption(new Option("F", "fixed", false, "fixed-value boundaries"));
    boundariesOptions.addOption(new Option("A", "adiabatic", false, "adiabatic boundaries"));
    boundariesOptions.addOption(new Option("R", "reflective", false, "reflective boundaries"));
    options.addOptionGroup(boundariesOptions);

    OptionGroup colorOptions = new OptionGroup();
    colorOptions.addOption(new Option("bn", "black-white", false, "black and white color scheme (default)"));
    colorOptions.addOption(new Option("ca", "activation-color", false, "activation color scheme"));
    colorOptions.addOption(new Option("co", "omega-color", false, "omega color scheme"));
    options.addOptionGroup(colorOptions);

    options.addOption(OptionBuilder.withLongOpt("rule").withDescription("rule number (required)").hasArg()
            .withArgName("rule").create());

    options.addOption(OptionBuilder.withLongOpt("width").withDescription("space width (required)").hasArg()
            .withArgName("width").create());

    options.addOption(OptionBuilder.withLongOpt("steps").withDescription("number of steps (required)").hasArg()
            .withArgName("steps").create());

    options.addOption(OptionBuilder.withLongOpt("alpha").withDescription("memory factor (default 0)").hasArg()
            .withArgName("alpha").create());

    options.addOption(OptionBuilder.withLongOpt("pattern").withDescription("inititial pattern").hasArg()
            .withArgName("pattern").create());

    options.addOption("s", "single-seed", false, "single cell seed");
    options.addOption("si", "single-seed-inverse", false, "all 1 except one cell");

    options.addOption(OptionBuilder.withLongOpt("update-patter")
            .withDescription("update patter (valid values are " + UpdatePattern.validValues() + ")").hasArg()
            .withArgName("updatepatter").create());

    // test/*  w w  w .  j a v a 2s  .com*/
    // args = new String[]{ "--rule=10", "--steps=500" , "--width=60", "-P" , "-s" };

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

        if (!line.hasOption("rule"))
            throw new ParseException("no rule number (use --rule=XX)");
        int rule;
        try {
            rule = Integer.parseInt(line.getOptionValue("rule"));
            if (rule < 0 || rule > 15)
                throw new ParseException("invalid rule number");
        } catch (NumberFormatException ex) {
            throw new ParseException("invalid rule number");
        }

        if (!line.hasOption("width"))
            throw new ParseException("no space width (use --width=XX)");
        int width;
        try {
            width = Integer.parseInt(line.getOptionValue("width"));
            if (width < 1)
                throw new ParseException("invalid width");
        } catch (NumberFormatException ex) {
            throw new ParseException("invalid width");
        }

        if (!line.hasOption("steps"))
            throw new ParseException("no number of steps (use --steps=XX)");
        int steps;
        try {
            steps = Integer.parseInt(line.getOptionValue("steps"));
            if (width < 1)
                throw new ParseException("invalid number of steps");
        } catch (NumberFormatException ex) {
            throw new ParseException("invalid number of steps");
        }

        double alpha = 0;
        if (line.hasOption("alpha")) {
            try {
                alpha = Double.parseDouble(line.getOptionValue("alpha"));
                if (alpha < 0 || alpha > 1)
                    throw new ParseException("invalid alpha");
            } catch (NumberFormatException ex) {
                throw new ParseException("invalid alpha");
            }
        }

        String pattern = null;
        if (line.hasOption("pattern")) {
            pattern = line.getOptionValue("pattern");
            if (pattern != null)
                pattern = pattern.trim();
        }

        if (line.hasOption("single-seed"))
            pattern = "S";
        else if (line.hasOption("single-seed-inverse"))
            pattern = "SI";

        UpdatePattern updatePatter = UpdatePattern.synchronous;
        if (line.hasOption("update-patter")) {
            try {
                updatePatter = UpdatePattern.getUpdatePattern(line.getOptionValue("update-patter"));
            } catch (IllegalArgumentException ex) {
                throw new ParseException(ex.getMessage());
            }
        }

        Boundaries boundaries = Boundaries.periodic;
        if (line.hasOption("periodic"))
            boundaries = Boundaries.periodic;
        else if (line.hasOption("fixed"))
            boundaries = Boundaries.fixed;
        else if (line.hasOption("adiabatic"))
            boundaries = Boundaries.adiabatic;
        else if (line.hasOption("reflective"))
            boundaries = Boundaries.reflective;

        ColorScheme colorScheme = ColorScheme.noColor;
        if (line.hasOption("black-white"))
            colorScheme = ColorScheme.noColor;
        else if (line.hasOption("activation-color"))
            colorScheme = ColorScheme.activationColor;
        else if (line.hasOption("omega-color"))
            colorScheme = ColorScheme.omegaColor;

        Output output = Output.all;
        if (line.hasOption("suppress-output"))
            output = Output.noOutput;

        Main.drawRule(rule, width, boundaries, updatePatter, steps, alpha, pattern, output, colorScheme);

    } catch (ParseException ex) {
        System.err.println("Copyright (C) 2009 Andrea Bonomi - <andrea.bonomi@gmail.com>");
        System.err.println();
        System.err.println("https://github.com/andreax79/one-neighbor-binary-cellular-automata");
        System.err.println();
        System.err.println("This program is free software; you can redistribute it and/or modify it");
        System.err.println("under the terms of the GNU General Public License as published by the");
        System.err.println("Free Software Foundation; either version 2 of the License, or (at your");
        System.err.println("option) any later version.");
        System.err.println();
        System.err.println("This program is distributed in the hope that it will be useful, but");
        System.err.println("WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY");
        System.err.println("or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License");
        System.err.println("for more details.");
        System.err.println();
        System.err.println("You should have received a copy of the GNU General Public License along");
        System.err.println("with this program; if not, write to the Free Software Foundation, Inc.,");
        System.err.println("59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.)");
        System.err.println();
        System.err.println(ex.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("main", options);

    } catch (IOException ex) {
        System.err.println("IO exception:" + ex.getMessage());
    }

}

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
 *//*from ww  w . j  av a 2  s . c o  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.enioka.jqm.tools.Main.java

/**
 * Startup method for the packaged JAR//ww  w  .  jav a  2s .  c om
 * 
 * @param args
 *            0 is node name
 */
@SuppressWarnings("static-access")
public static void main(String[] args) {
    Helpers.setLogFileName("cli");
    Option o00 = OptionBuilder.withArgName("nodeName").hasArg().withDescription("name of the JQM node to start")
            .isRequired().create("startnode");
    Option o01 = OptionBuilder.withDescription("display help").withLongOpt("help").create("h");
    Option o11 = OptionBuilder.withArgName("applicationname").hasArg()
            .withDescription("name of the application to launch").isRequired().create("enqueue");
    Option o21 = OptionBuilder.withArgName("xmlpath").hasArg()
            .withDescription("path of the XML configuration file to import").isRequired()
            .create("importjobdef");
    Option o31 = OptionBuilder.withArgName("xmlpath").hasArg()
            .withDescription("export all queue definitions into an XML file").isRequired()
            .create("exportallqueues");
    OptionBuilder.withArgName("xmlpath").hasArg()
            .withDescription("export some queue definitions into an XML file").isRequired()
            .create("exportqueuefile");
    OptionBuilder.withArgName("queues").hasArg().withDescription("queues to export").withValueSeparator(',')
            .isRequired().create("queue");
    Option o51 = OptionBuilder.withArgName("xmlpath").hasArg()
            .withDescription("import all queue definitions from an XML file").isRequired()
            .create("importqueuefile");
    Option o61 = OptionBuilder.withArgName("nodeName").hasArg()
            .withDescription("creates a JQM node of this name, or updates it if it exists. Implies -u.")
            .isRequired().create("createnode");
    Option o71 = OptionBuilder.withDescription("display JQM engine version").withLongOpt("version").create("v");
    Option o81 = OptionBuilder.withDescription("upgrade JQM database").withLongOpt("upgrade").create("u");
    Option o91 = OptionBuilder.withArgName("jobInstanceId").hasArg()
            .withDescription("get job instance status by ID").isRequired().withLongOpt("getstatus").create("g");
    Option o101 = OptionBuilder.withArgName("password").hasArg()
            .withDescription("creates or resets root admin account password").isRequired().withLongOpt("root")
            .create("r");
    Option o111 = OptionBuilder.withArgName("option").hasArg()
            .withDescription(
                    "ws handling. Possible values are: enable, disable, ssl, nossl, internalpki, externalapi")
            .isRequired().withLongOpt("gui").create("w");
    Option o121 = OptionBuilder.withArgName("id[,logfilepath]").hasArg().withDescription("single launch mode")
            .isRequired().withLongOpt("gui").create("s");
    Option o131 = OptionBuilder.withArgName("resourcefile").hasArg()
            .withDescription("resource parameter file to use. Default is resources.xml")
            .withLongOpt("resources").create("p");
    Option o141 = OptionBuilder.withArgName("login,password,role1,role2,...").hasArgs(Option.UNLIMITED_VALUES)
            .withValueSeparator(',')
            .withDescription("Create or update a JQM account. Roles must exist beforehand.").create("U");

    Options options = new Options();
    OptionGroup og1 = new OptionGroup();
    og1.setRequired(true);
    og1.addOption(o00);
    og1.addOption(o01);
    og1.addOption(o11);
    og1.addOption(o21);
    og1.addOption(o31);
    og1.addOption(o51);
    og1.addOption(o61);
    og1.addOption(o71);
    og1.addOption(o81);
    og1.addOption(o91);
    og1.addOption(o101);
    og1.addOption(o111);
    og1.addOption(o121);
    og1.addOption(o141);
    options.addOptionGroup(og1);
    OptionGroup og2 = new OptionGroup();
    og2.addOption(o131);
    options.addOptionGroup(og2);

    HelpFormatter formatter = new HelpFormatter();
    formatter.setWidth(160);

    try {
        // Parse arguments
        CommandLineParser parser = new BasicParser();
        CommandLine line = parser.parse(options, args);

        // Other db connection?
        if (line.getOptionValue(o131.getOpt()) != null) {
            jqmlogger.info("Using resource XML file " + line.getOptionValue(o131.getOpt()));
            Helpers.resourceFile = line.getOptionValue(o131.getOpt());
        }

        // Set db connection
        Helpers.registerJndiIfNeeded();

        // Enqueue
        if (line.getOptionValue(o11.getOpt()) != null) {
            enqueue(line.getOptionValue(o11.getOpt()));
        }
        // Get status
        if (line.getOptionValue(o91.getOpt()) != null) {
            getStatus(Integer.parseInt(line.getOptionValue(o91.getOpt())));
        }
        // Import XML
        else if (line.getOptionValue(o21.getOpt()) != null) {
            importJobDef(line.getOptionValue(o21.getOpt()));
        }
        // Start engine
        else if (line.getOptionValue(o00.getOpt()) != null) {
            startEngine(line.getOptionValue(o00.getOpt()));
        }
        // Export all Queues
        else if (line.getOptionValue(o31.getOpt()) != null) {
            exportAllQueues(line.getOptionValue(o31.getOpt()));
        }
        // Import queues
        else if (line.getOptionValue(o51.getOpt()) != null) {
            importQueues(line.getOptionValue(o51.getOpt()));
        }
        // Create node
        else if (line.getOptionValue(o61.getOpt()) != null) {
            createEngine(line.getOptionValue(o61.getOpt()));
        }
        // Upgrade
        else if (line.hasOption(o81.getOpt())) {
            upgrade();
        }
        // Help
        else if (line.hasOption(o01.getOpt())) {
            formatter.printHelp("java -jar jqm-engine.jar", options, true);
        }
        // Version
        else if (line.hasOption(o71.getOpt())) {
            jqmlogger.info("Engine version: " + Helpers.getMavenVersion());
        }
        // Root password
        else if (line.hasOption(o101.getOpt())) {
            root(line.getOptionValue(o101.getOpt()));
        }
        // Web options
        else if (line.hasOption(o111.getOpt())) {
            ws(line.getOptionValue(o111.getOpt()));
        }
        // Web options
        else if (line.hasOption(o121.getOpt())) {
            single(line.getOptionValue(o121.getOpt()));
        }
        // User handling
        else if (line.hasOption(o141.getOpt())) {
            user(line.getOptionValues(o141.getOpt()));
        }
    } catch (ParseException exp) {
        jqmlogger.fatal("Could not read command line: " + exp.getMessage());
        formatter.printHelp("java -jar jqm-engine.jar", options, true);
        return;
    }
}