Example usage for org.apache.commons.cli CommandLineParser parse

List of usage examples for org.apache.commons.cli CommandLineParser parse

Introduction

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

Prototype

CommandLine parse(Options options, String[] arguments) throws ParseException;

Source Link

Document

Parse the arguments according to the specified options.

Usage

From source file:io.yucca.lucene.IndexUtility.java

public static void main(String[] args) {
    CommandLineParser parser = new PosixParser();
    Options options = new Options();
    initOptions(options);/* w ww.j av a2 s . c om*/
    try {
        final CommandLine line = parser.parse(options, args);
        if (line.hasOption('h')) {
            usage(options);
        }
        if (line.hasOption('s')) {
            String value = line.getOptionValue('s');
            sourceIndexDirectory = new File(value);
            if (sourceIndexDirectory.exists() == false) {
                log.error("Index source directory: {} does not exist!", sourceIndexDirectory);
                System.exit(1);
            }
        } else {
            usage(options);
            System.exit(1);
        }
        if (line.hasOption('d')) {
            String value = line.getOptionValue('d');
            destIndexDirectory = new File(value);
            if (destIndexDirectory.exists() == true) {
                log.error("Index destination directory: {} already exist", destIndexDirectory);
                System.exit(1);
            }
        } else {
            usage(options);
            System.exit(1);
        }
        if (line.hasOption('v')) {
            try {
                String value = line.getOptionValue('v');
                version = Version.parseLeniently(value);
            } catch (Exception e) {
                log.error("Unrecognized index version, exiting");
                usage(options);
                System.exit(1);
            }
        }
        if (line.hasOption('r')) {
            String value = line.getOptionValue('r');
            String[] fields = value.trim().split(" *, *");
            if (fields == null || fields.length == 0) {
                log.error("No fields were given, exiting");
                usage(options);
                System.exit(1);
            }
            (new FieldRemover()).removeFields(sourceIndexDirectory, destIndexDirectory, fields, version);
            System.exit(0);
        }
    } catch (IndexUtilityException e) {
        log.error("Failed to work on index:", e);
        System.exit(1);
    } catch (MissingOptionException e) {
        log.error("Mandatory options is missing!");
        usage(options);
        System.exit(1);
    } catch (ParseException e) {
        log.error("Failed to parse commandline options!");
        usage(options);
        System.exit(1);
    }
}

From source file:at.newmedialab.ldpath.backend.linkeddata.LDQuery.java

public static void main(String[] args) {
    Options options = buildOptions();//from ww  w  .j  a  v  a 2 s . c  o  m

    CommandLineParser parser = new PosixParser();
    try {
        CommandLine cmd = parser.parse(options, args);

        Level logLevel = Level.WARN;

        if (cmd.hasOption("loglevel")) {
            String logLevelName = cmd.getOptionValue("loglevel");
            if ("DEBUG".equals(logLevelName.toUpperCase())) {
                logLevel = Level.DEBUG;
            } else if ("INFO".equals(logLevelName.toUpperCase())) {
                logLevel = Level.INFO;
            } else if ("WARN".equals(logLevelName.toUpperCase())) {
                logLevel = Level.WARN;
            } else if ("ERROR".equals(logLevelName.toUpperCase())) {
                logLevel = Level.ERROR;
            } else {
                log.error("unsupported log level: {}", logLevelName);
            }
        }

        if (logLevel != null) {
            for (String logname : new String[] { "at", "org", "net", "com" }) {

                ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory
                        .getLogger(logname);
                logger.setLevel(logLevel);
            }
        }

        String format = null;
        if (cmd.hasOption("format")) {
            format = cmd.getOptionValue("format");
        }

        GenericSesameBackend backend;
        if (cmd.hasOption("store")) {
            backend = new LDPersistentBackend(new File(cmd.getOptionValue("store")));
        } else {
            backend = new LDMemoryBackend();
        }

        Resource context = null;
        if (cmd.hasOption("context")) {
            context = backend.getRepository().getValueFactory().createURI(cmd.getOptionValue("context"));
        }

        if (backend != null && context != null) {
            LDPath<Value> ldpath = new LDPath<Value>(backend);

            if (cmd.hasOption("path")) {
                String path = cmd.getOptionValue("path");

                for (Value v : ldpath.pathQuery(context, path, null)) {
                    System.out.println(v.stringValue());
                }
            } else if (cmd.hasOption("program")) {
                File file = new File(cmd.getOptionValue("program"));

                Map<String, Collection<?>> result = ldpath.programQuery(context, new FileReader(file));

                for (String field : result.keySet()) {
                    StringBuilder line = new StringBuilder();
                    line.append(field);
                    line.append(" = ");
                    line.append("{");
                    for (Iterator it = result.get(field).iterator(); it.hasNext();) {
                        line.append(it.next().toString());
                        if (it.hasNext()) {
                            line.append(", ");
                        }
                    }
                    line.append("}");
                    System.out.println(line);

                }
            }
        }

        if (backend instanceof LDPersistentBackend) {
            ((LDPersistentBackend) backend).shutdown();
        }

    } catch (ParseException e) {
        System.err.println("invalid arguments");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("LDQuery", options, true);
    } catch (LDPathParseException e) {
        System.err.println("path or program could not be parsed");
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        System.err.println("file or program could not be found");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("LDQuery", options, true);
    } catch (IOException e) {
        System.err.println("could not access cache data directory");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("LDQuery", options, true);
    }

}

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

/**
 * @param args//from w  w  w. j a  v a 2s  . 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:com.hurence.logisland.util.avro.eventgenerator.DataGenerator.java

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

    // load and verify the options
    CommandLineParser parser = new PosixParser();
    Options opts = loadOptions();//from   w w w.j  a  va  2 s  .c om

    CommandLine cmd = null;
    try {
        cmd = parser.parse(opts, args);
    } catch (org.apache.commons.cli.ParseException parseEx) {
        logger.error("Invalid option");
        printHelp(opts);
        return;
    }

    // check for necessary options
    String fileLoc = cmd.getOptionValue("schemaLocation");
    if (fileLoc == null) {
        logger.error("schemaLocation not specified");
        printHelp(opts);
    }

    //getField string length and check if min is greater than 0

    // Generate the record
    File schemaFile = new File(fileLoc);
    DataGenerator dataGenerator = new DataGenerator(schemaFile);
    GenericRecord record = dataGenerator.generateRandomRecord();
    if (cmd.hasOption(PRINT_AVRO_JSON_OPTNAME)) {
        String outname = cmd.getOptionValue(PRINT_AVRO_JSON_OPTNAME);
        OutputStream outs = System.out;
        if (!outname.equals("-")) {
            outs = new FileOutputStream(outname);
        }
        printAvroJson(record, outs);
        if (!outname.equals("-")) {
            outs.close();
        }
    } else {
        DataGenerator.prettyPrint(record);
    }

}

From source file:com.nextdoor.bender.S3SnsNotifier.java

public static void main(String[] args) throws ParseException, InterruptedException, IOException {
    formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZoneUTC();

    /*//from  ww w .  ja  v a 2s . c o m
     * Parse cli arguments
     */
    Options options = new Options();
    options.addOption(Option.builder().longOpt("bucket").hasArg().required()
            .desc("Name of S3 bucket to list s3 objects from").build());
    options.addOption(Option.builder().longOpt("key-file").hasArg().required()
            .desc("Local file of S3 keys to process").build());
    options.addOption(
            Option.builder().longOpt("sns-arn").hasArg().required().desc("SNS arn to publish to").build());
    options.addOption(Option.builder().longOpt("throttle-ms").hasArg()
            .desc("Amount of ms to wait between publishing to SNS").build());
    options.addOption(Option.builder().longOpt("processed-file").hasArg()
            .desc("Local file to use to store procssed S3 object names").build());
    options.addOption(Option.builder().longOpt("skip-processed").hasArg(false)
            .desc("Whether to skip S3 objects that have been processed").build());
    options.addOption(
            Option.builder().longOpt("dry-run").hasArg(false).desc("If set do not publish to SNS").build());

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

    String bucket = cmd.getOptionValue("bucket");
    String keyFile = cmd.getOptionValue("key-file");
    String snsArn = cmd.getOptionValue("sns-arn");
    String processedFile = cmd.getOptionValue("processed-file", null);
    boolean skipProcessed = cmd.hasOption("skip-processed");
    dryRun = cmd.hasOption("dry-run");
    long throttle = Long.parseLong(cmd.getOptionValue("throttle-ms", "-1"));

    if (processedFile != null) {
        File file = new File(processedFile);

        if (!file.exists()) {
            logger.debug("creating local file to store processed s3 object names: " + processedFile);
            file.createNewFile();
        }
    }

    /*
     * Import S3 keys that have been processed
     */
    if (skipProcessed && processedFile != null) {
        try (BufferedReader br = new BufferedReader(new FileReader(processedFile))) {
            String line;
            while ((line = br.readLine()) != null) {
                alreadyPublished.add(line.trim());
            }
        }
    }

    /*
     * Setup writer for file containing processed S3 keys
     */
    FileWriter fw = null;
    BufferedWriter bw = null;
    if (processedFile != null) {
        fw = new FileWriter(processedFile, true);
        bw = new BufferedWriter(fw);
    }

    /*
     * Create clients
     */
    AmazonS3Client s3Client = new AmazonS3Client();
    AmazonSNSClient snsClient = new AmazonSNSClient();

    /*
     * Get S3 object list
     */
    try (BufferedReader br = new BufferedReader(new FileReader(keyFile))) {
        String line;
        while ((line = br.readLine()) != null) {
            String key = line.trim();

            if (alreadyPublished.contains(key)) {
                logger.info("skipping " + key);
            }

            ObjectMetadata om = s3Client.getObjectMetadata(bucket, key);

            S3EventNotification s3Notification = getS3Notification(key, bucket, om.getContentLength());

            String json = s3Notification.toJson();

            /*
             * Publish to SNS
             */
            if (publish(snsArn, json, snsClient, key) && processedFile != null) {
                bw.write(key + "\n");
                bw.flush();
            }

            if (throttle != -1) {
                Thread.sleep(throttle);
            }

        }
    }

    if (processedFile != null) {
        bw.close();
        fw.close();
    }
}

From source file:name.martingeisse.ecotools.simulator.ui.Main.java

/**
 * The main method./* w  w w  .  j  a v a  2  s .  c o m*/
 * @param args command-line arguments
 * @throws Exception Any exceptions are passed to the environment.
 */
public static void main(String[] args) throws Exception {

    /** define command-line options **/
    Options options = new Options();
    options.addOption("i", false, "interactive mode (do not start simulation automatically)");
    options.addOption("l", true, "load program");
    options.addOption("r", true, "load ROM contents");
    options.addOption("d", true, "enable disk simulation with the specified disk image file");
    options.addOption("t", true, "enable terminal simulation with the specified number of terminals (0..2)");
    options.addOption("g", false, "enable graphics controller simulation");
    options.addOption("c", false, "enable console simulation");
    options.addOption("C", false, "enable block console simulation");
    options.addOption("o", true, "enable output device simulation and write output to the specified file");
    options.addOption("s", false, "enable null sound device");

    /** print help for the empty command line **/
    if (args.length == 0) {
        showUsgeAndExit(options);
    }

    /** parse the command line **/
    CommandLineParser commandLineParser = new PosixParser();
    CommandLine commandLine;
    try {
        commandLine = commandLineParser.parse(options, args);
    } catch (UnrecognizedOptionException e) {
        System.out.println("unrecognized option: " + e.getOption());
        showUsgeAndExit(options);
        return;
    }

    /** build the simulator configuration **/
    SimulatorConfiguration configuration = new SimulatorConfiguration();

    /** load configuration files **/
    for (String arg : commandLine.getArgs()) {
        configuration.loadConfigurationFile(arg);
    }

    /** interpret the options **/

    if (commandLine.hasOption("l")) {
        configuration.setProgramFilename(commandLine.getOptionValue("l"));
    }

    if (commandLine.hasOption("r")) {
        configuration.setRomFilename(commandLine.getOptionValue("r"));
    }

    if (commandLine.hasOption("d")) {
        configuration.setDiskFilename(commandLine.getOptionValue("d"));
    }

    if (commandLine.hasOption("t")) {
        String terminalCountSpecification = commandLine.getOptionValue("t");
        try {
            configuration.setTerminalCount(
                    (terminalCountSpecification == null) ? 0 : Integer.parseInt(terminalCountSpecification));
        } catch (NumberFormatException e) {
            System.out.println("number format error in number of terminals: " + terminalCountSpecification);
        }
    }

    if (commandLine.hasOption("i")) {
        configuration.setInteractive(true);
    }

    if (commandLine.hasOption("g")) {
        configuration.setGraphics(true);
    }

    if (commandLine.hasOption("c")) {
        configuration.setConsole(true);
    }

    if (commandLine.hasOption("C")) {
        configuration.setBlockConsole(true);
    }

    if (commandLine.hasOption("o")) {
        configuration.setOutputFilename(commandLine.getOptionValue("o"));
    }

    if (commandLine.hasOption("s")) {
        configuration.setSound(true);
    }

    configuration.checkConsistency();
    configuration.deriveSettings();

    /** setup simulation framework and run **/
    EcoSimulatorFramework framework = new EcoSimulatorFramework();
    configuration.applyPreCreate(framework);
    framework.create();
    configuration.applyPostCreate(framework);
    framework.open();
    framework.mainLoop();
    framework.dispose();
    framework.exit();

}

From source file:com.genentech.chemistry.openEye.apps.SDFCatsIndexer.java

/**
 * @param args//from w w w .  ja  v a 2 s  .  c  o  m
 */
public static void main(String... args) throws IOException { // create command line Options object
    Options options = new Options();
    Option opt = new Option(OPT_INFILE, true,
            "input file oe-supported Use .sdf|.smi to specify the file type.");
    opt.setRequired(true);
    opt.setArgName("fn");
    options.addOption(opt);

    opt = new Option(OPT_OUTFILE, true, "output file oe-supported. Use .sdf|.smi to specify the file type.");
    opt.setRequired(true);
    opt.setArgName("fn");
    options.addOption(opt);

    opt = new Option(OPT_NORMALIZATION, true,
            "Normalization method: Counts|CountsPerAtom|CountsPerFeature(def) multiple allowed");
    opt.setArgName("meth");
    options.addOption(opt);

    opt = new Option(OPT_PRINTDESC, false,
            "Causes the descriptor for describing each linear path in a molceule to be created");
    options.addOption(opt);

    opt = new Option(OPT_RGROUPTYPES, false, "treat RGroup attachement point ([U]) as atom type.");
    options.addOption(opt);

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        System.err.println(e.getMessage());
        exitWithHelp(options);
    }

    String inFile = cmd.getOptionValue(OPT_INFILE);
    String outFile = cmd.getOptionValue(OPT_OUTFILE);

    AtomTyperInterface[] myTypes = CATSIndexer.typers;
    String tagPrefix = "";
    if (cmd.hasOption(OPT_RGROUPTYPES)) {
        myTypes = CATSIndexer.rgroupTypers;
        tagPrefix = "RG";
    }

    if (cmd.hasOption(OPT_PRINTDESC)) {
        SDFCatsIndexer sdfIndexer = new SDFCatsIndexer(myTypes, tagPrefix);
        sdfIndexer.printDescriptors(inFile, outFile);
        sdfIndexer.close();
        return;
    }

    EnumSet<Normalization> normMeth = EnumSet.noneOf(Normalization.class);
    if (cmd.hasOption(OPT_NORMALIZATION))
        for (String n : cmd.getOptionValues(OPT_NORMALIZATION))
            normMeth.add(Normalization.valueOf(n));
    else
        normMeth.add(Normalization.CountsPerFeature);

    SDFCatsIndexer sdfIndexer = new SDFCatsIndexer(myTypes, tagPrefix);
    sdfIndexer.run(inFile, outFile, normMeth);
    sdfIndexer.close();
}

From source file:edu.vassar.cs.cmpu331.tvi.Main.java

public static void main(String[] args) {
    Options options = new Options().addOption("t", "trace", false, "Enable tracing.")
            .addOption("d", "debug", false, "Enable debug output.")
            .addOption("s", "size", true, "Sets amount of memory available.")
            .addOption("v", "version", false, "Prints the TVI version number.")
            .addOption("r", "renumber", true, "Renumbers the lines in a files.")
            .addOption("h", "help", false, "Prints this help message");
    CommandLineParser parser = new DefaultParser();
    try {/*from  w w  w .  java  2s  .  com*/
        CommandLine opts = parser.parse(options, args);
        if (opts.hasOption('h')) {
            help(options);
            return;
        }
        if (opts.hasOption('v')) {
            System.out.println();
            System.out.println("The Vassar Interpreter v" + Version.getVersion());
            System.out.println(COPYRIGHT);
            System.out.println();
            return;
        }
        if (opts.hasOption('r')) {
            int returnCode = 0;
            try {
                renumber(opts.getOptionValue('r'));
            } catch (IOException e) {
                e.printStackTrace();
                returnCode = 1;
            }
            System.exit(returnCode);
        }
        files = opts.getArgs();
        if (files.length == 0) {
            System.out.println("ERROR: No file names given.");
            help(options);
            System.exit(1);
        }
        if (opts.hasOption('s')) {
            try {
                memory = Integer.parseInt(opts.getOptionValue('s'));
            } catch (NumberFormatException e) {
                System.out.println("ERROR: Invalid --size parameter.");
                help(options);
                System.exit(1);
            }
        }
        if (opts.hasOption('t')) {
            tracing = true;
        }
        if (opts.hasOption('d')) {
            debugging = true;
        }
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        help(options);
        System.exit(1);
    }
    Main app = new Main();
    Arrays.stream(files).forEach(app::run);
}

From source file:io.anserini.index.IndexGov2.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption(//w  w  w. j  a v a  2  s  .  com
            OptionBuilder.withArgName("path").hasArg().withDescription("input data path").create(INPUT_OPTION));
    options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("output index path")
            .create(INDEX_OPTION));
    options.addOption(OptionBuilder.withArgName("num").hasArg().withDescription("number of indexer threads")
            .create(THREADS_OPTION));
    options.addOption(OptionBuilder.withArgName("num").hasArg()
            .withDescription("max number of documents to index (-1 to index everything)")
            .create(DOCLIMIT_OPTION));

    options.addOption(POSITIONS_OPTION, false, "index positions");
    options.addOption(OPTIMIZE_OPTION, false, "merge all index segments");

    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(INPUT_OPTION) || !cmdline.hasOption(INDEX_OPTION)
            || !cmdline.hasOption(THREADS_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.setWidth(100);
        formatter.printHelp(IndexGov2.class.getCanonicalName(), options);
        System.exit(-1);
    }

    final String dirPath = cmdline.getOptionValue(INDEX_OPTION);
    final String dataDir = cmdline.getOptionValue(INPUT_OPTION);
    final int docCountLimit = cmdline.hasOption(DOCLIMIT_OPTION)
            ? Integer.parseInt(cmdline.getOptionValue(DOCLIMIT_OPTION))
            : -1;
    final int numThreads = Integer.parseInt(cmdline.getOptionValue(THREADS_OPTION));

    final boolean doUpdate = cmdline.hasOption(UPDATE_OPTION);
    final boolean positions = cmdline.hasOption(POSITIONS_OPTION);
    final boolean optimize = cmdline.hasOption(OPTIMIZE_OPTION);

    final Analyzer a = new EnglishAnalyzer();
    final TrecContentSource trecSource = createGov2Source(dataDir);
    final Directory dir = FSDirectory.open(Paths.get(dirPath));

    LOG.info("Index path: " + dirPath);
    LOG.info("Doc limit: " + (docCountLimit == -1 ? "all docs" : "" + docCountLimit));
    LOG.info("Threads: " + numThreads);
    LOG.info("Positions: " + positions);
    LOG.info("Optimize (merge segments): " + optimize);

    final IndexWriterConfig config = new IndexWriterConfig(a);

    if (doUpdate) {
        config.setOpenMode(IndexWriterConfig.OpenMode.APPEND);
    } else {
        config.setOpenMode(IndexWriterConfig.OpenMode.CREATE);
    }

    final IndexWriter writer = new IndexWriter(dir, config);
    Gov2IndexThreads threads = new Gov2IndexThreads(writer, positions, trecSource, numThreads, docCountLimit);
    LOG.info("Indexer: start");

    final long t0 = System.currentTimeMillis();

    threads.start();

    while (!threads.done()) {
        Thread.sleep(100);
    }
    threads.stop();

    final long t1 = System.currentTimeMillis();
    LOG.info("Indexer: indexing done (" + (t1 - t0) / 1000.0 + " sec); total " + writer.maxDoc() + " docs");
    if (!doUpdate && docCountLimit != -1 && writer.maxDoc() != docCountLimit) {
        throw new RuntimeException("w.maxDoc()=" + writer.maxDoc() + " but expected " + docCountLimit);
    }
    if (threads.failed.get()) {
        throw new RuntimeException("exceptions during indexing");
    }

    final long t2;
    t2 = System.currentTimeMillis();

    final Map<String, String> commitData = new HashMap<String, String>();
    commitData.put("userData", "multi");
    writer.setCommitData(commitData);
    writer.commit();
    final long t3 = System.currentTimeMillis();
    LOG.info("Indexer: commit multi (took " + (t3 - t2) / 1000.0 + " sec)");

    if (optimize) {
        LOG.info("Indexer: merging all segments");
        writer.forceMerge(1);
        final long t4 = System.currentTimeMillis();
        LOG.info("Indexer: segments merged (took " + (t4 - t3) / 1000.0 + " sec)");
    }

    LOG.info("Indexer: at close: " + writer.segString());
    final long tCloseStart = System.currentTimeMillis();
    writer.close();
    LOG.info("Indexer: close took " + (System.currentTimeMillis() - tCloseStart) / 1000.0 + " sec");
    dir.close();
    final long tFinal = System.currentTimeMillis();
    LOG.info("Indexer: finished (" + (tFinal - t0) / 1000.0 + " sec)");
    LOG.info("Indexer: net bytes indexed " + threads.getBytesIndexed());
    LOG.info("Indexer: " + (threads.getBytesIndexed() / 1024. / 1024. / 1024. / ((tFinal - t0) / 3600000.))
            + " GB/hour plain text");
}

From source file:com.jones_systems.Tieout.java

public static void main(String[] args) {

    String testFilename = null;//from   w w  w  .  ja  va  2 s. c o  m

    Options options = new Options();

    //options.addOption("f", "filename", true, "the file to use for the Tieout check");
    Option filename = OptionBuilder.withArgName("filename").hasArg()
            .withDescription("the file name of the XML test file").create("filename");
    options.addOption(filename);

    CommandLineParser parser = new GnuParser();

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

        if (line.hasOption("filename")) {
            testFilename = line.getOptionValue("filename");
        } else {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("tieout", options);
            System.exit(2);
        }

    } catch (ParseException exp) {

    }

    File testfile = new File(testFilename);

    if (!testfile.exists()) {
        System.err.println("Cannot find file!");
        System.exit(1);
    }

    System.out.println("Starting test with file: " + testFilename);

    Tieout ts = new Tieout(testfile);
    boolean connected = ts.connectDatasources();

    if (!connected) {
        System.err.print("Could not connect to all datasources");
        System.exit(1);
    }

    ts.runTests();

}