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

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

Introduction

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

Prototype

Options

Source Link

Usage

From source file:com.jolbox.benchmark.BenchmarkMain.java

/**
 * @param args/*  w w w .  j a  v  a  2  s.c o m*/
 * @throws ClassNotFoundException 
 * @throws PropertyVetoException 
 * @throws SQLException 
 * @throws NoSuchMethodException 
 * @throws InvocationTargetException 
 * @throws IllegalAccessException 
 * @throws InterruptedException 
 * @throws SecurityException 
 * @throws IllegalArgumentException 
 * @throws NamingException 
 * @throws ParseException 
 */
public static void main(String[] args) throws ClassNotFoundException, SQLException, PropertyVetoException,
        IllegalArgumentException, SecurityException, InterruptedException, IllegalAccessException,
        InvocationTargetException, NoSuchMethodException, NamingException, ParseException {

    Options options = new Options();
    options.addOption("t", "threads", true, "Max number of threads");
    options.addOption("s", "stepping", true, "Stepping of threads");
    options.addOption("p", "poolsize", true, "Pool size");
    options.addOption("h", "help", false, "Help");

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = parser.parse(options, args);
    if (cmd.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("benchmark.jar", options);
        System.exit(1);
    }

    Class.forName("com.jolbox.bonecp.MockJDBCDriver");
    new MockJDBCDriver();
    BenchmarkTests tests = new BenchmarkTests();

    BenchmarkTests.threads = 200;
    BenchmarkTests.stepping = 20;
    BenchmarkTests.pool_size = 200;
    // warm up
    System.out.println("JIT warm up");
    tests.testMultiThreadedConstantDelay(0);

    BenchmarkTests.threads = 200;
    BenchmarkTests.stepping = 5;
    BenchmarkTests.pool_size = 100;

    if (cmd.hasOption("t")) {
        BenchmarkTests.threads = Integer.parseInt(cmd.getOptionValue("t", "400"));
    }
    if (cmd.hasOption("s")) {
        BenchmarkTests.stepping = Integer.parseInt(cmd.getOptionValue("s", "20"));
    }
    if (cmd.hasOption("p")) {
        BenchmarkTests.pool_size = Integer.parseInt(cmd.getOptionValue("p", "200"));
    }

    System.out.println("Starting benchmark tests with " + BenchmarkTests.threads + " threads (stepping "
            + BenchmarkTests.stepping + ") using pool size of " + BenchmarkTests.pool_size + " connections");

    System.out.println("Starting tests");
    plotLineGraph(tests.testMultiThreadedConstantDelay(0), 0, false);
    //      plotLineGraph(tests.testMultiThreadedConstantDelay(10), 10, false);
    //      plotLineGraph(tests.testMultiThreadedConstantDelay(25), 25, false);
    //      plotLineGraph(tests.testMultiThreadedConstantDelay(50), 50, false);
    //      plotLineGraph(tests.testMultiThreadedConstantDelay(75), 75, false);
    //      
    plotBarGraph("Single Thread", "bonecp-singlethread-poolsize-" + BenchmarkTests.pool_size + "-threads-"
            + BenchmarkTests.threads + ".png", tests.testSingleThread());
    plotBarGraph(
            "Prepared Statement\nSingle Threaded", "bonecp-preparedstatement-single-poolsize-"
                    + BenchmarkTests.pool_size + "-threads-" + BenchmarkTests.threads + ".png",
            tests.testPreparedStatementSingleThread());
    //      plotLineGraph(tests.testMultiThreadedConstantDelayWithPreparedStatements(0), 0, true);
    //      plotLineGraph(tests.testMultiThreadedConstantDelayWithPreparedStatements(10), 10, true);
    //      plotLineGraph(tests.testMultiThreadedConstantDelayWithPreparedStatements(25), 25, true);
    //      plotLineGraph(tests.testMultiThreadedConstantDelayWithPreparedStatements(50), 50, true);
    //      plotLineGraph(tests.testMultiThreadedConstantDelayWithPreparedStatements(75), 75, true);

}

From source file:edu.cmu.lti.oaqa.knn4qa.apps.GenTranEmbeddings.java

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

    options.addOption(CommonParams.MEMINDEX_PARAM, null, true, CommonParams.MEMINDEX_DESC);
    options.addOption(CommonParams.GIZA_ROOT_DIR_PARAM, null, true, CommonParams.GIZA_ROOT_DIR_DESC);
    options.addOption(CommonParams.GIZA_ITER_QTY_PARAM, null, true, CommonParams.GIZA_ITER_QTY_DESC);
    options.addOption(OUT_FILE_PARAM, null, true, OUT_FILE_DESC);
    options.addOption(MAX_MODEL_ORDER_PARAM, null, true, MAX_MODEL_ORDER_DESC);
    options.addOption(MIN_PROB_PARAM, null, true, MIN_PROB_DESC);
    options.addOption(MAX_DIGIT_PARAM, null, true, MAX_DIGIT_DESC);
    options.addOption(CommonParams.MAX_WORD_QTY_PARAM, null, true, CommonParams.MAX_WORD_QTY_PARAM);

    CommandLineParser parser = new org.apache.commons.cli.GnuParser();

    try {/*from w  w w .  ja v a 2s  .co m*/
        CommandLine cmd = parser.parse(options, args);

        int maxWordQty = Integer.MAX_VALUE;

        String tmpi = cmd.getOptionValue(CommonParams.MAX_WORD_QTY_PARAM);

        if (null != tmpi) {
            maxWordQty = Integer.parseInt(tmpi);
        }

        String memIndexPref = cmd.getOptionValue(CommonParams.MEMINDEX_PARAM);

        if (null == memIndexPref) {
            Usage("Specify '" + CommonParams.MEMINDEX_DESC + "'", options);
        }
        String gizaRootDir = cmd.getOptionValue(CommonParams.GIZA_ROOT_DIR_PARAM);
        if (null == gizaRootDir) {
            Usage("Specify '" + CommonParams.GIZA_ROOT_DIR_PARAM + "'", options);
        }
        int gizaIterQty = -1;
        if (cmd.hasOption(CommonParams.GIZA_ITER_QTY_PARAM)) {
            gizaIterQty = Integer.parseInt(cmd.getOptionValue(CommonParams.GIZA_ITER_QTY_PARAM));
        }
        if (gizaIterQty <= 0) {
            Usage("Specify '" + CommonParams.GIZA_ITER_QTY_DESC + "'", options);
        }
        int maxModelOrder = -1;
        if (cmd.hasOption(MAX_MODEL_ORDER_PARAM)) {
            maxModelOrder = Integer.parseInt(cmd.getOptionValue(MAX_MODEL_ORDER_PARAM));
        }
        String outFilePrefix = cmd.getOptionValue(OUT_FILE_PARAM);
        if (null == outFilePrefix) {
            Usage("Specify '" + OUT_FILE_DESC + "'", options);
        }

        float minProb = 0;

        if (cmd.hasOption(MIN_PROB_PARAM)) {
            minProb = Float.parseFloat(cmd.getOptionValue(MIN_PROB_PARAM));
        } else {
            Usage("Specify '" + MIN_PROB_DESC + "'", options);
        }

        int maxDigit = 5;
        if (cmd.hasOption(MAX_DIGIT_PARAM)) {
            maxDigit = Integer.parseInt(cmd.getOptionValue(MAX_DIGIT_PARAM));
        }

        // We use unlemmatized text here, because lemmatized dictionary is going to be mostly subset of the unlemmatized one.
        int fieldId = FeatureExtractor.TEXT_UNLEMM_FIELD_ID;

        String memFwdIndxName = FeatureExtractor.indexFileName(memIndexPref,
                FeatureExtractor.mFieldNames[fieldId]);

        FrequentIndexWordFilterAndRecoder filterAndRecoder = new FrequentIndexWordFilterAndRecoder(
                memFwdIndxName, maxWordQty);

        InMemForwardIndex index = new InMemForwardIndex(memFwdIndxName);
        BM25SimilarityLucene simil = new BM25SimilarityLucene(FeatureExtractor.BM25_K1, FeatureExtractor.BM25_B,
                index);
        String prefix = gizaRootDir + "/" + FeatureExtractor.mFieldNames[fieldId] + "/";

        GizaVocabularyReader answVoc = new GizaVocabularyReader(prefix + "source.vcb", filterAndRecoder);
        GizaVocabularyReader questVoc = new GizaVocabularyReader(prefix + "target.vcb", filterAndRecoder);

        GizaTranTableReaderAndRecoder answToQuestTran = new GizaTranTableReaderAndRecoder(
                false /* don't flip a translation table */, prefix + "/output.t1." + gizaIterQty,
                filterAndRecoder, answVoc, questVoc, (float) FeatureExtractor.DEFAULT_PROB_SELF_TRAN, minProb);

        int order = 0;

        System.out.println("Starting to compute the 0-order model");
        HashIntObjMap<SparseVector> currModel = SparseEmbeddingReaderAndRecorder.createTranVecDict(index,
                filterAndRecoder, minProb, answToQuestTran);
        System.out.println("0-order model is computed");
        SparseEmbeddingReaderAndRecorder.saveDict(index, outFilePrefix + ".0", currModel, maxDigit);
        System.out.println("0-order model is saved");

        while (order < maxModelOrder) {
            ++order;
            System.out.println("Starting to compute the " + order + "-order model");
            currModel = SparseEmbeddingReaderAndRecorder.nextOrderDict(currModel, index, minProb,
                    answToQuestTran);
            System.out.println(order + "-order model is computed");
            SparseEmbeddingReaderAndRecorder.saveDict(index, outFilePrefix + "." + order, currModel, maxDigit);
            System.out.println(order + "-order model is saved");
        }

    } catch (ParseException e) {
        Usage("Cannot parse arguments", options);
    } catch (Exception e) {
        System.err.println("Terminating due to an exception: " + e);
        System.exit(1);
    }

    System.out.println("Terminated successfully!");

}

From source file:cz.cuni.mff.ufal.dspace.app.MoveItems.java

/**
 * main method to run the MoveItems action
 * //from  w w w  . ja v a2 s.co  m
 * @param argv
 *            the command line arguments given
 * @throws SQLException
 */
public static void main(String[] argv) throws SQLException {
    // Create an options object and populate it
    CommandLineParser parser = new PosixParser();

    Options options = new Options();

    options.addOption("l", "list", false, "list collections");
    options.addOption("s", "source", true, "source collection ID");
    options.addOption("t", "target", true, "target collection ID");
    options.addOption("i", "inherit", false, "inherit target collection privileges (default false)");
    options.addOption("h", "help", false, "help");

    // Parse the command line arguments
    CommandLine line;
    try {
        line = parser.parse(options, argv);
    } catch (ParseException pe) {
        System.err.println("Error parsing command line arguments: " + pe.getMessage());
        System.exit(1);
        return;
    }

    if (line.hasOption('h') || line.getOptions().length == 0) {
        printHelp(options, 0);
    }

    // Create a context
    Context context;
    try {
        context = new Context();
        context.turnOffAuthorisationSystem();
    } catch (Exception e) {
        System.err.println("Unable to create a new DSpace Context: " + e.getMessage());
        System.exit(1);
        return;
    }

    if (line.hasOption('l')) {
        listCollections(context);
        System.exit(0);
    }

    // Check a filename is given
    if (!line.hasOption('s')) {
        System.err.println("Required parameter -s missing!");
        printHelp(options, 1);
    }

    Boolean inherit;

    // Check a filename is given
    if (line.hasOption('i')) {
        inherit = true;
    } else {
        inherit = false;
    }

    String sourceCollectionIdParam = line.getOptionValue('s');
    Integer sourceCollectionId = null;

    if (sourceCollectionIdParam.matches("\\d+")) {
        sourceCollectionId = Integer.valueOf(sourceCollectionIdParam);
    } else {
        System.err.println("Invalid argument for parameter -s: " + sourceCollectionIdParam);
        printHelp(options, 1);
    }

    // Check source collection ID is given
    if (!line.hasOption('t')) {
        System.err.println("Required parameter -t missing!");
        printHelp(options, 1);
    }
    String targetCollectionIdParam = line.getOptionValue('t');
    Integer targetCollectionId = null;

    if (targetCollectionIdParam.matches("\\d+")) {
        targetCollectionId = Integer.valueOf(targetCollectionIdParam);
    } else {
        System.err.println("Invalid argument for parameter -t: " + targetCollectionIdParam);
        printHelp(options, 1);
    }

    // Check target collection ID is given
    if (targetCollectionIdParam.equals(sourceCollectionIdParam)) {
        System.err.println("Source collection id and target collection id must differ");
        printHelp(options, 1);
    }

    try {

        moveItems(context, sourceCollectionId, targetCollectionId, inherit);

        // Finish off and tidy up
        context.restoreAuthSystemState();
        context.complete();
    } catch (Exception e) {
        context.abort();
        System.err.println("Error committing changes to database: " + e.getMessage());
        System.err.println("Aborting most recent changes.");
        System.exit(1);
    }
}

From source file:cc.twittertools.search.local.RunQueries.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {
    Options options = new Options();

    options.addOption(/*from   w ww . ja v  a2s. c  o  m*/
            OptionBuilder.withArgName("path").hasArg().withDescription("index location").create(INDEX_OPTION));
    options.addOption(OptionBuilder.withArgName("num").hasArg().withDescription("number of results to return")
            .create(NUM_RESULTS_OPTION));
    options.addOption(OptionBuilder.withArgName("file").hasArg()
            .withDescription("file containing topics in TREC format").create(QUERIES_OPTION));
    options.addOption(OptionBuilder.withArgName("similarity").hasArg()
            .withDescription("similarity to use (BM25, LM)").create(SIMILARITY_OPTION));
    options.addOption(
            OptionBuilder.withArgName("string").hasArg().withDescription("runtag").create(RUNTAG_OPTION));
    options.addOption(new Option(VERBOSE_OPTION, "print out complete document"));

    CommandLine cmdline = null;
    CommandLineParser parser = new GnuParser();
    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Error parsing command line: " + exp.getMessage());
        System.exit(-1);
    }

    if (!cmdline.hasOption(QUERIES_OPTION) || !cmdline.hasOption(INDEX_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(RunQueries.class.getName(), options);
        System.exit(-1);
    }

    File indexLocation = new File(cmdline.getOptionValue(INDEX_OPTION));
    if (!indexLocation.exists()) {
        System.err.println("Error: " + indexLocation + " does not exist!");
        System.exit(-1);
    }

    String runtag = cmdline.hasOption(RUNTAG_OPTION) ? cmdline.getOptionValue(RUNTAG_OPTION) : DEFAULT_RUNTAG;

    String topicsFile = cmdline.getOptionValue(QUERIES_OPTION);

    int numResults = 1000;
    try {
        if (cmdline.hasOption(NUM_RESULTS_OPTION)) {
            numResults = Integer.parseInt(cmdline.getOptionValue(NUM_RESULTS_OPTION));
        }
    } catch (NumberFormatException e) {
        System.err.println("Invalid " + NUM_RESULTS_OPTION + ": " + cmdline.getOptionValue(NUM_RESULTS_OPTION));
        System.exit(-1);
    }

    String similarity = "LM";
    if (cmdline.hasOption(SIMILARITY_OPTION)) {
        similarity = cmdline.getOptionValue(SIMILARITY_OPTION);
    }

    boolean verbose = cmdline.hasOption(VERBOSE_OPTION);

    PrintStream out = new PrintStream(System.out, true, "UTF-8");

    IndexReader reader = DirectoryReader.open(FSDirectory.open(indexLocation));
    IndexSearcher searcher = new IndexSearcher(reader);

    if (similarity.equalsIgnoreCase("BM25")) {
        searcher.setSimilarity(new BM25Similarity());
    } else if (similarity.equalsIgnoreCase("LM")) {
        searcher.setSimilarity(new LMDirichletSimilarity(2500.0f));
    }

    QueryParser p = new QueryParser(Version.LUCENE_43, StatusField.TEXT.name, IndexStatuses.ANALYZER);

    TrecTopicSet topics = TrecTopicSet.fromFile(new File(topicsFile));
    for (TrecTopic topic : topics) {
        Query query = p.parse(topic.getQuery());
        Filter filter = NumericRangeFilter.newLongRange(StatusField.ID.name, 0L, topic.getQueryTweetTime(),
                true, true);

        TopDocs rs = searcher.search(query, filter, numResults);

        int i = 1;
        for (ScoreDoc scoreDoc : rs.scoreDocs) {
            Document hit = searcher.doc(scoreDoc.doc);
            out.println(String.format("%s Q0 %s %d %f %s", topic.getId(),
                    hit.getField(StatusField.ID.name).numericValue(), i, scoreDoc.score, runtag));
            if (verbose) {
                out.println("# " + hit.toString().replaceAll("[\\n\\r]+", " "));
            }
            i++;
        }
    }
    reader.close();
    out.close();
}

From source file:dk.statsbiblioteket.util.qa.PackageScannerDriver.java

/**
 * @param args The command line arguments.
 * @throws IOException If command line arguments can't be passed or there
 *                     is an error reading class files.
 *///  w ww.  j  a va  2  s.  co m
@SuppressWarnings("deprecation")
public static void main(final String[] args) throws IOException {
    Report report;
    CommandLine cli = null;
    String reportType, projectName, baseSrcDir, targetPackage;
    String[] targets = null;

    // Build command line options
    CommandLineParser cliParser = new PosixParser();
    Options options = new Options();
    options.addOption("h", "help", false, "Print help message and exit");
    options.addOption("n", "name", true, "Project name, default 'Unknown'");
    options.addOption("o", "output", true, "Type of output, 'plain' or 'html', default is html");
    options.addOption("p", "package", true, "Only scan a particular package in input dirs, use dotted "
            + "package notation to refine selections");
    options.addOption("s", "source-dir", true,
            "Base source dir to use in report, can be a URL. " + "@FILE@ and @MODULE@ will be escaped");

    // Parse and validate command line
    try {
        cli = cliParser.parse(options, args);
        targets = cli.getArgs();
        if (args.length == 0 || targets.length == 0 || cli.hasOption("help")) {
            throw new ParseException("Not enough arguments, no input files");
        }
    } catch (ParseException e) {
        printHelp(options);
        System.exit(1);
    }

    // Extract information from command line
    reportType = cli.getOptionValue("output") != null ? cli.getOptionValue("output") : "html";

    projectName = cli.getOptionValue("name") != null ? cli.getOptionValue("name") : "Unknown";

    baseSrcDir = cli.getOptionValue("source-dir") != null ? cli.getOptionValue("source-dir")
            : System.getProperty("user.dir");

    targetPackage = cli.getOptionValue("package") != null ? cli.getOptionValue("package") : "";
    targetPackage = targetPackage.replace(".", File.separator);

    // Set up report type
    if ("plain".equals(reportType)) {
        report = new BasicReport();
    } else {
        report = new HTMLReport(projectName, System.out, baseSrcDir);
    }

    // Do actual scanning of provided targets
    for (String target : targets) {
        PackageScanner scanner;
        File f = new File(target);

        if (f.isDirectory()) {
            scanner = new PackageScanner(report, f, targetPackage);
        } else {
            String filename = f.toString();
            scanner = new PackageScanner(report, f.getParentFile(),
                    filename.substring(filename.lastIndexOf(File.separator) + 1));
        }
        scanner.scan();
    }

    // Cloce the report before we exit
    report.end();
}

From source file:fr.inria.atlanmod.kyanos.benchmarks.KyanosMapCreator.java

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

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input file");
    inputOpt.setArgs(1);/* ww  w  . j a va 2  s.c o m*/
    inputOpt.setRequired(true);

    Option outputOpt = OptionBuilder.create(OUT);
    outputOpt.setArgName("OUTPUT");
    outputOpt.setDescription("Output directory");
    outputOpt.setArgs(1);
    outputOpt.setRequired(true);

    Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS);
    inClassOpt.setArgName("CLASS");
    inClassOpt.setDescription("FQN of EPackage implementation class");
    inClassOpt.setArgs(1);
    inClassOpt.setRequired(true);

    options.addOption(inputOpt);
    options.addOption(outputOpt);
    options.addOption(inClassOpt);

    CommandLineParser parser = new PosixParser();

    try {
        PersistenceBackendFactoryRegistry.getFactories().put(NeoMapURI.NEO_MAP_SCHEME,
                new MapPersistenceBackendFactory());

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

        URI sourceUri = URI.createFileURI(commandLine.getOptionValue(IN));
        URI targetUri = NeoMapURI.createNeoMapURI(new File(commandLine.getOptionValue(OUT)));

        Class<?> inClazz = KyanosMapCreator.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS));
        inClazz.getMethod("init").invoke(null);

        ResourceSet resourceSet = new ResourceSetImpl();

        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("xmi",
                new XMIResourceFactoryImpl());
        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("zxmi",
                new XMIResourceFactoryImpl());
        resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap().put(NeoMapURI.NEO_MAP_SCHEME,
                PersistentResourceFactory.eINSTANCE);

        Resource sourceResource = resourceSet.createResource(sourceUri);
        Map<String, Object> loadOpts = new HashMap<String, Object>();
        if ("zxmi".equals(sourceUri.fileExtension())) {
            loadOpts.put(XMIResource.OPTION_ZIP, Boolean.TRUE);
        }

        Runtime.getRuntime().gc();
        long initialUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
        LOG.log(Level.INFO, MessageFormat.format("Used memory before loading: {0}",
                MessageUtil.byteCountToDisplaySize(initialUsedMemory)));
        LOG.log(Level.INFO, "Loading source resource");
        sourceResource.load(loadOpts);

        LOG.log(Level.INFO, "Source resource loaded");
        Runtime.getRuntime().gc();
        long finalUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
        LOG.log(Level.INFO, MessageFormat.format("Used memory after loading: {0}",
                MessageUtil.byteCountToDisplaySize(finalUsedMemory)));
        LOG.log(Level.INFO, MessageFormat.format("Memory use increase: {0}",
                MessageUtil.byteCountToDisplaySize(finalUsedMemory - initialUsedMemory)));

        Resource targetResource = resourceSet.createResource(targetUri);

        Map<String, Object> saveOpts = new HashMap<String, Object>();
        List<StoreOption> storeOptions = new ArrayList<StoreOption>();
        storeOptions.add(MapResourceOptions.EStoreMapOption.AUTOCOMMIT);
        saveOpts.put(MapResourceOptions.STORE_OPTIONS, storeOptions);
        targetResource.save(saveOpts);

        LOG.log(Level.INFO, "Start moving elements");
        targetResource.getContents().clear();
        targetResource.getContents().addAll(sourceResource.getContents());
        LOG.log(Level.INFO, "End moving elements");
        LOG.log(Level.INFO, "Start saving");
        targetResource.save(saveOpts);
        LOG.log(Level.INFO, "Saved");

        if (targetResource instanceof PersistentResourceImpl) {
            PersistentResourceImpl.shutdownWithoutUnload((PersistentResourceImpl) targetResource);
        } else {
            targetResource.unload();
        }

    } catch (ParseException e) {
        MessageUtil.showError(e.toString());
        MessageUtil.showError("Current arguments: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar <this-file.jar>", options, true);
    } catch (Throwable e) {
        MessageUtil.showError(e.toString());
        e.printStackTrace();
    }
}

From source file:de.jgoestl.massdatagenerator.MassDataGenerator.java

/**
 * @param args the command line arguments
 *//*  www .ja v a2s. c  o m*/
public static void main(String[] args) {
    // CommandLine options
    Options options = new Options();
    options.addOption("i", "input", true, "The input file");
    options.addOption("o", "output", true, "The output file");
    options.addOption("c", "count", true, "The amount of generatet data");
    options.addOption("d", "dateFormat", true, "A custom date format");
    options.addOption("h", "help", false, "Show this");

    CommandLineParser parser = new GnuParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException ex) {
        Logger.getLogger(MassDataGenerator.class.getName()).log(Level.SEVERE, null, ex);
        System.exit(1);
    }

    // Show the help
    if (cmd.hasOption("help") || !cmd.hasOption("input") || !cmd.hasOption("output")
            || !cmd.hasOption("count")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("massDataGenerator", options);

        System.out.println("\nFollowing in your input file will be replaced:");
        System.out.println("#UUID# - A random UUID");
        System.out.println("#SEQ#  - A consecutive number (starting with 1)");
        System.out.println("#DATE# - The current date (YYYY-MM-d h:m:s.S)");

        System.exit(0);
    }

    // Get values and validate
    String inputFilePath = cmd.getOptionValue("input");
    String outputPath = cmd.getOptionValue("output");
    int numberOfData = getNumberOfData(cmd);
    validate(inputFilePath, outputPath, numberOfData);
    DateFormat dateFormat = getDateFormat(cmd);

    // Read, generte and write Data
    String inputString = null;
    inputString = readInputFile(inputFilePath, inputString);
    StringBuilder output = generateOutput(numberOfData, inputString, dateFormat);
    writeOutput(outputPath, output);
}

From source file:com.alibaba.jstorm.flux.Flux.java

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

    options.addOption(option(0, "l", OPTION_LOCAL, "Run the topology in local mode."));

    options.addOption(option(0, "r", OPTION_REMOTE, "Deploy the topology to a remote cluster."));

    options.addOption(option(0, "R", OPTION_RESOURCE,
            "Treat the supplied path as a classpath resource instead of a file."));

    options.addOption(/*from w  ww  . j a  v a  2  s . c  om*/
            option(1, "s", OPTION_SLEEP, "ms", "When running locally, the amount of time to sleep (in ms.) "
                    + "before killing the topology and shutting down the local cluster."));

    options.addOption(option(0, "d", OPTION_DRY_RUN, "Do not run or deploy the topology. Just build, validate, "
            + "and print information about the topology."));

    options.addOption(option(0, "q", OPTION_NO_DETAIL, "Suppress the printing of topology details."));

    options.addOption(option(0, "n", OPTION_NO_SPLASH, "Suppress the printing of the splash screen."));

    options.addOption(option(0, "i", OPTION_INACTIVE, "Deploy the topology, but do not activate it."));

    options.addOption(option(1, "z", OPTION_ZOOKEEPER, "host:port",
            "When running in local mode, use the ZooKeeper at the "
                    + "specified <host>:<port> instead of the in-process ZooKeeper. (requires Storm 0.9.3 or later)"));

    options.addOption(option(1, "f", OPTION_FILTER, "file",
            "Perform property substitution. Use the specified file "
                    + "as a source of properties, and replace keys identified with {$[property name]} with the value defined "
                    + "in the properties file."));

    options.addOption(
            option(0, "e", OPTION_ENV_FILTER, "Perform environment variable substitution. Replace keys"
                    + "identified with `${ENV-[NAME]}` will be replaced with the corresponding `NAME` environment value"));

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

    if (cmd.getArgs().length != 1) {
        usage(options);
        System.exit(1);
    }
    runCli(cmd);
}

From source file:com.thoughtworks.xstream.tools.benchmark.parsers.ParserBenchmark.java

public static void main(String[] args) {
    int counter = 1000;

    Options options = new Options();
    options.addOption("p", "product", true, "Class name of the product to use for benchmark");
    options.addOption("n", true, "Number of repetitions");

    Harness harness = new Harness();
    harness.addMetric(new DeserializationSpeedMetric(0, false) {
        public String toString() {
            return "Initial run deserialization";
        }//  w  ww .ja  v a  2s .  c o m
    });

    Parser parser = new PosixParser();
    try {
        CommandLine commandLine = parser.parse(options, args);
        String name = null;
        if (commandLine.hasOption('p')) {
            name = commandLine.getOptionValue('p');
        }
        if (name == null || name.equals("DOM")) {
            harness.addProduct(new XStreamDom());
        }
        if (name == null || name.equals("JDOM")) {
            harness.addProduct(new XStreamJDom());
        }
        if (name == null || name.equals("DOM4J")) {
            harness.addProduct(new XStreamDom4J());
        }
        if (name == null || name.equals("XOM")) {
            harness.addProduct(new XStreamXom());
        }
        if (name == null || name.equals("BEAStAX")) {
            harness.addProduct(new XStreamBEAStax());
        }
        if (name == null || name.equals("Woodstox")) {
            harness.addProduct(new XStreamWoodstox());
        }
        if (JVM.is16() && (name == null || name.equals("SJSXP"))) {
            harness.addProduct(new XStreamSjsxp());
        }
        if (name == null || name.equals("Xpp3")) {
            harness.addProduct(new XStreamXpp3());
        }
        if (name == null || name.equals("kXML2")) {
            harness.addProduct(new XStreamKXml2());
        }
        if (name == null || name.equals("Xpp3DOM")) {
            harness.addProduct(new XStreamXpp3DOM());
        }
        if (name == null || name.equals("kXML2DOM")) {
            harness.addProduct(new XStreamKXml2DOM());
        }
        if (commandLine.hasOption('n')) {
            counter = Integer.parseInt(commandLine.getOptionValue('n'));
        }
    } catch (ParseException e) {
        e.printStackTrace();
    }

    harness.addMetric(new DeserializationSpeedMetric(counter, false));
    harness.addTarget(new BasicTarget());
    harness.addTarget(new ExtendedTarget());
    harness.addTarget(new ReflectionTarget());
    harness.addTarget(new SerializableTarget());
    harness.addTarget(new JavaBeanTarget());
    if (false) {
        harness.addTarget(new FieldReflection());
        harness.addTarget(new HierarchyLevelReflection());
        harness.addTarget(new InnerClassesReflection());
        harness.addTarget(new StaticInnerClassesReflection());
    }
    harness.run(new TextReporter(new PrintWriter(System.out, true)));
    System.out.println("Done.");
}

From source file:de.egore911.versioning.deployer.Main.java

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

    Options options = new Options();
    options.addOption("help", false, "print this message");
    options.addOption("r", "replace-only", false,
            "only perform replacements (skip downloading, extracting, etc.)");

    CommandLine line;//  w  ww  . ja va  2 s  .c  o  m
    try {
        CommandLineParser parser = new BasicParser();
        line = parser.parse(options, args);
    } catch (ParseException e) {
        System.out.println("Wrong command line parameters:" + e.getMessage());
        showHelp(options);
        System.exit(1);
        return;
    }

    if (line.getArgs().length == 0) {
        LOG.error("Please pass at least one URL as one and only argument");
        System.exit(1);
        return;
    }

    for (String arg : line.getArgs()) {
        perform(arg, line);
    }
}