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:at.newmedialab.ldpath.template.LDTemplate.java

public static void main(String[] args) {
    Options options = buildOptions();//from  w w w .ja  v  a  2s  .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);
            }
        }

        File template = null;
        if (cmd.hasOption("template")) {
            template = new File(cmd.getOptionValue("template"));
        }

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

        BufferedWriter out = null;
        if (cmd.hasOption("out")) {
            File of = new File(cmd.getOptionValue("out"));
            if (of.canWrite()) {
                out = new BufferedWriter(new FileWriter(of));
            } else {
                log.error("cannot write to output file {}", of);
                System.exit(1);
            }
        } else {
            out = new BufferedWriter(new OutputStreamWriter(System.out));
        }

        if (backend != null && context != null && template != null) {
            TemplateEngine<Value> engine = new TemplateEngine<Value>(backend);

            engine.setDirectoryForTemplateLoading(template.getParentFile());
            engine.processFileTemplate(context, template.getName(), out);
            out.flush();
            out.close();
        }

        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 (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 file");
        e.printStackTrace(System.err);
    } catch (TemplateException e) {
        System.err.println("error while processing template");
        e.printStackTrace(System.err);
    }

}

From source file:dhtaccess.tools.Get.java

public static void main(String[] args) {
    boolean details = false;

    // parse properties
    Properties prop = System.getProperties();
    String gateway = prop.getProperty("dhtaccess.gateway");
    if (gateway == null || gateway.length() <= 0) {
        gateway = DEFAULT_GATEWAY;//from  w ww.  java2  s  .  c  o  m
    }

    // parse options
    Options options = new Options();
    options.addOption("h", "help", false, "print help");
    options.addOption("g", "gateway", true, "gateway URI, list at http://opendht.org/servers.txt");
    options.addOption("d", "details", false, "print secret hash and TTL");

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.out.println("There is an invalid option.");
        e.printStackTrace();
        System.exit(1);
    }

    String optVal;
    if (cmd.hasOption('h')) {
        usage(COMMAND);
        System.exit(1);
    }
    optVal = cmd.getOptionValue('g');
    if (optVal != null) {
        gateway = optVal;
    }
    if (cmd.hasOption('d')) {
        details = true;
    }

    args = cmd.getArgs();

    // parse arguments
    if (args.length < 1) {
        usage(COMMAND);
        System.exit(1);
    }

    // prepare for RPC
    DHTAccessor accessor = null;
    try {
        accessor = new DHTAccessor(gateway);
    } catch (MalformedURLException e) {
        e.printStackTrace();
        System.exit(1);
    }

    for (int index = 0; index < args.length; index++) {
        byte[] key = null;
        try {
            key = args[index].getBytes(ENCODE);
        } catch (UnsupportedEncodingException e1) {
            // NOTREACHED
        }

        // RPC
        if (args.length > 1) {
            System.out.println(args[index] + ":");
        }

        if (details) {
            Set<DetailedGetResult> results = accessor.getDetails(key);

            for (DetailedGetResult r : results) {
                String valString = null;
                try {
                    valString = new String((byte[]) r.getValue(), ENCODE);
                } catch (UnsupportedEncodingException e) {
                    // NOTREACHED
                }

                BigInteger hashedSecure = new BigInteger(1, (byte[]) r.getHashedSecret());

                System.out.println(valString + " " + r.getTTL() + " " + r.getHashType() + " 0x"
                        + ("0000000" + hashedSecure.toString(16)).substring(0, 8));
            }
        } else {
            Set<byte[]> results = accessor.get(key);

            for (byte[] valBytes : results) {
                try {
                    System.out.println(new String((byte[]) valBytes, ENCODE));
                } catch (UnsupportedEncodingException e) {
                    // NOTREACHED
                }
            }
        }
    } // for (int index = 0...
}

From source file:edu.kit.checkstyle.Main.java

/**
 * Loops over the files specified checking them for errors. The exit code
 * is the number of errors found in all the files.
 * @param aArgs the command line arguments
 **///from  w w  w.ja v  a 2s .  c  o m
public static void main(String[] aArgs) {
    // parse the parameters
    final CommandLineParser clp = new PosixParser();
    CommandLine line = null;
    try {
        line = clp.parse(OPTS, aArgs);
    } catch (final ParseException e) {
        e.printStackTrace();
        usage();
    }
    assert line != null;

    // setup the properties
    final Properties properties = System.getProperties();

    final Configuration config = loadConfig(properties);

    AuditListener listener = new QualifiedListener();
    final List<File> files = getFilesToProcess(line);
    final Checker checker = createChecker(config);
    checker.addListener(listener);
    checker.process(files);
    checker.destroy();
    System.exit(0);
}

From source file:it.tizianofagni.sparkboost.MPBoostLearnerExe.java

public static void main(String[] args) {
    Options options = new Options();
    options.addOption("b", "binaryProblem", false,
            "Indicate if the input dataset contains a binary problem and not a multilabel one");
    options.addOption("z", "labels0based", false,
            "Indicate if the labels IDs in the dataset to classifyLibSvmWithResults are already assigned in the range [0, numLabels-1] included");
    options.addOption("l", "enableSparkLogging", false, "Enable logging messages of Spark");
    options.addOption("w", "windowsLocalModeFix", true,
            "Set the directory containing the winutils.exe command");
    options.addOption("dp", "documentPartitions", true, "The number of document partitions");
    options.addOption("fp", "featurePartitions", true, "The number of feature partitions");
    options.addOption("lp", "labelPartitions", true, "The number of label partitions");

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = null;/*from   www.j  a v  a2 s . co m*/
    String[] remainingArgs = null;
    try {
        cmd = parser.parse(options, args);
        remainingArgs = cmd.getArgs();
        if (remainingArgs.length != 3)
            throw new ParseException("You need to specify all mandatory parameters");
    } catch (ParseException e) {
        System.out.println("Parsing failed.  Reason: " + e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(
                MPBoostLearnerExe.class.getSimpleName() + " [OPTIONS] <inputFile> <outputFile> <numIterations>",
                options);
        System.exit(-1);
    }

    boolean binaryProblem = false;
    if (cmd.hasOption("b"))
        binaryProblem = true;
    boolean labels0Based = false;
    if (cmd.hasOption("z"))
        labels0Based = true;
    boolean enablingSparkLogging = false;
    if (cmd.hasOption("l"))
        enablingSparkLogging = true;

    if (cmd.hasOption("w")) {
        System.setProperty("hadoop.home.dir", cmd.getOptionValue("w"));
    }

    String inputFile = remainingArgs[0];
    String outputFile = remainingArgs[1];
    int numIterations = Integer.parseInt(remainingArgs[2]);

    long startTime = System.currentTimeMillis();

    // Disable Spark logging.
    if (!enablingSparkLogging) {
        Logger.getLogger("org").setLevel(Level.OFF);
        Logger.getLogger("akka").setLevel(Level.OFF);
    }

    // Create and configure Spark context.
    SparkConf conf = new SparkConf().setAppName("Spark MPBoost learner");
    JavaSparkContext sc = new JavaSparkContext(conf);

    // Create and configure learner.
    MpBoostLearner learner = new MpBoostLearner(sc);
    learner.setNumIterations(numIterations);

    if (cmd.hasOption("dp")) {
        learner.setNumDocumentsPartitions(Integer.parseInt(cmd.getOptionValue("dp")));
    }
    if (cmd.hasOption("fp")) {
        learner.setNumFeaturesPartitions(Integer.parseInt(cmd.getOptionValue("fp")));
    }
    if (cmd.hasOption("lp")) {
        learner.setNumLabelsPartitions(Integer.parseInt(cmd.getOptionValue("lp")));
    }

    // Build classifier with MPBoost learner.
    BoostClassifier classifier = learner.buildModel(inputFile, labels0Based, binaryProblem);

    // Save classifier to disk.
    DataUtils.saveModel(sc, classifier, outputFile);

    long endTime = System.currentTimeMillis();
    System.out.println("Execution time: " + (endTime - startTime) + " milliseconds.");
}

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

/**
 * @param args//from w w w  .  java2 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);
    options.addOption(opt);

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

    opt = new Option(OPT_SMARTS_FILE, true, "Optional: to overwrite atom type definition file.");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_PRINT_COUNTS, false,
            "If set the count of each atom type is added to the output file.");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_VALIDATE_ASSIGNMENT, false,
            "Print warning if no atomtype matches an atom in a candidte molecule.");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_SUPRESS_ZERO, false, "If given atom type counts with count=0 will not be added.");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_NEUTRALIZE, true, "y|n to neutralize molecule if possible (default=y)");
    opt.setRequired(false);
    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);
    }
    args = cmd.getArgs();

    if (cmd.hasOption("d")) {
        System.err.println("Start debugger and press return:");
        new BufferedReader(new InputStreamReader(System.in)).readLine();
    }

    String inFile = cmd.getOptionValue(OPT_INFILE);
    String outFile = cmd.getOptionValue(OPT_OUTFILE);
    String smartsFile = cmd.getOptionValue(OPT_SMARTS_FILE);
    boolean outputCount = cmd.hasOption(OPT_PRINT_COUNTS);
    boolean outputZero = !cmd.hasOption(OPT_SUPRESS_ZERO);
    boolean neutralize = !"n".equalsIgnoreCase(cmd.getOptionValue(OPT_NEUTRALIZE));
    boolean ValidateAssignment = cmd.hasOption(OPT_VALIDATE_ASSIGNMENT);

    SDFALogP sdfALogP = new SDFALogP(smartsFile, outFile, outputZero, neutralize, ValidateAssignment);

    sdfALogP.run(inFile, outputCount);
    sdfALogP.close();
}

From source file:com.twentyn.patentScorer.PatentScorer.java

public static void main(String[] args) throws Exception {
    System.out.println("Starting up...");
    System.out.flush();//from  w ww  .  j  a  v a 2 s  . c  om
    Options opts = new Options();
    opts.addOption(Option.builder("i").longOpt("input").hasArg().required()
            .desc("Input file or directory to score").build());
    opts.addOption(Option.builder("o").longOpt("output").hasArg().required()
            .desc("Output file to which to write score JSON").build());
    opts.addOption(Option.builder("h").longOpt("help").desc("Print this help message and exit").build());
    opts.addOption(Option.builder("v").longOpt("verbose").desc("Print verbose log output").build());

    HelpFormatter helpFormatter = new HelpFormatter();
    CommandLineParser cmdLineParser = new DefaultParser();
    CommandLine cmdLine = null;
    try {
        cmdLine = cmdLineParser.parse(opts, args);
    } catch (ParseException e) {
        System.out.println("Caught exception when parsing command line: " + e.getMessage());
        helpFormatter.printHelp("DocumentIndexer", opts);
        System.exit(1);
    }

    if (cmdLine.hasOption("help")) {
        helpFormatter.printHelp("DocumentIndexer", opts);
        System.exit(0);
    }

    if (cmdLine.hasOption("verbose")) {
        // With help from http://stackoverflow.com/questions/23434252/programmatically-change-log-level-in-log4j2
        LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
        Configuration ctxConfig = ctx.getConfiguration();
        LoggerConfig logConfig = ctxConfig.getLoggerConfig(LogManager.ROOT_LOGGER_NAME);
        logConfig.setLevel(Level.DEBUG);

        ctx.updateLoggers();
        LOGGER.debug("Verbose logging enabled");
    }

    String inputFileOrDir = cmdLine.getOptionValue("input");
    File splitFileOrDir = new File(inputFileOrDir);
    if (!(splitFileOrDir.exists())) {
        LOGGER.error("Unable to find directory at " + inputFileOrDir);
        System.exit(1);
    }

    try (FileWriter writer = new FileWriter(cmdLine.getOptionValue("output"))) {
        PatentScorer scorer = new PatentScorer(PatentModel.getModel(), writer);
        PatentCorpusReader corpusReader = new PatentCorpusReader(scorer, splitFileOrDir);
        corpusReader.readPatentCorpus();
    }
}

From source file:edu.freiburg.dbis.rdd.RddExtractor.java

/**
 * @param args/*ww w .j a va 2s. com*/
 */
public static void main(String[] args) {
    String Classname = RddExtractor.class.getName();
    // Creating and parsing commandline options
    Options options = createOptions();
    CommandLineParser parser = new BasicParser();
    HelpFormatter help = new HelpFormatter();
    CommandLine cmd = null;

    try {
        cmd = parser.parse(options, args);
        if (cmd.hasOption("h")) {
            help.printHelp(Classname, options);
            return;
        }
        // XOR (either input-file or sparql-endpoint) --> Throw error if it is the same
        if (cmd.hasOption("i") == cmd.hasOption("e")) {
            help.printHelp(Classname, options);
            System.err.println(
                    "Use either the the option to read from an input file or (XOR) the option to send queries against an SPARQL Endpoint");
            return;
        }
        // the graph variable can only be used with the sparql-enpoint
        if ((cmd.hasOption("g") == true) && (cmd.hasOption("e") == false)) {
            help.printHelp(Classname, options);
            System.err.println(
                    "The graph variable can only be used when sending queries against a SPARQL Endpoint");
            return;
        }

    } catch (ParseException e) {
        help.printHelp(Classname, options);
        System.err.println("Command line parsing failed. Reason: " + e.getMessage());
        return;
    }

    String INPUT_FILE = cmd.getOptionValue("i");
    String OUTPUT_FILE = cmd.getOptionValue("o");
    String ENDPOINTURL = cmd.getOptionValue("e");
    String VIRTUOSO_GRAPH_NAME = cmd.getOptionValue("g");
    String WA = cmd.getOptionValue("w");
    String propertyFile = "src/main/resources/log4j.properties2";
    if (cmd.hasOption("v")) {
        propertyFile = "src/main/resources/log4j.properties";
    } else if (cmd.hasOption("l")) {
        propertyFile = cmd.getOptionValue("l");
    }
    //      String propertyFile = (cmd.hasOption("l")) ? cmd.getOptionValue("l") : "src/main/resources/log4j.properties2";

    PropertyConfigurator.configure(propertyFile);

    logger.debug("INPUT FILE  : " + INPUT_FILE);
    logger.debug("OUTPUT FILE : " + OUTPUT_FILE);
    logger.debug("ENDPOINT URL: " + ENDPOINTURL);
    logger.debug("GRAPH NAME  : " + VIRTUOSO_GRAPH_NAME);
    logger.debug("WORLD ASSUMP: " + WA);

    long start = System.currentTimeMillis();
    long end = 0;
    logger.info("Starting The Generator");
    Backend back = new Backend(INPUT_FILE, OUTPUT_FILE, ENDPOINTURL, VIRTUOSO_GRAPH_NAME, WA);
    end = System.currentTimeMillis();
    logger.info("Runtime of Generator in ms: " + (end - start));
}

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

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

    options.addOption("i1", null, true, "Input file 1");
    options.addOption("i2", null, true, "Input file 2");
    options.addOption("o", null, true, "Output file");

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

    try {/*from  w w  w.  j  a v  a2 s .c om*/
        CommandLine cmd = parser.parse(options, args);

        InputStream input1 = null, input2 = null;

        if (cmd.hasOption("i1")) {
            input1 = CompressUtils.createInputStream(cmd.getOptionValue("i1"));
        } else {
            Usage("Specify 'Input file 1'");
        }
        if (cmd.hasOption("i2")) {
            input2 = CompressUtils.createInputStream(cmd.getOptionValue("i2"));
        } else {
            Usage("Specify 'Input file 2'");
        }

        HashSet<String> hSubj = new HashSet<String>();

        BufferedWriter out = null;

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

            out = new BufferedWriter(new OutputStreamWriter(CompressUtils.createOutputStream(outFile)));
        } else {
            Usage("Specify 'Output file'");
        }

        XmlIterator inpIter2 = new XmlIterator(input2, YahooAnswersReader.DOCUMENT_TAG);

        int docNum = 1;
        for (String oneRec = inpIter2.readNext(); !oneRec.isEmpty(); oneRec = inpIter2.readNext(), ++docNum) {
            if (docNum % 10000 == 0) {
                System.out.println(String.format(
                        "Loaded and memorized questions for %d documents from the second input file", docNum));
            }
            ParsedQuestion q = YahooAnswersParser.parse(oneRec, false);
            hSubj.add(q.mQuestion);
        }

        XmlIterator inpIter1 = new XmlIterator(input1, YahooAnswersReader.DOCUMENT_TAG);

        System.out.println("=============================================");
        System.out.println("Memoization is done... now let's diff!!!");
        System.out.println("=============================================");

        docNum = 1;
        int skipOverlapQty = 0, skipErrorQty = 0;
        for (String oneRec = inpIter1.readNext(); !oneRec.isEmpty(); ++docNum, oneRec = inpIter1.readNext()) {
            if (docNum % 10000 == 0) {
                System.out.println(String.format("Processed %d documents from the first input file", docNum));
            }

            oneRec = oneRec.trim() + System.getProperty("line.separator");

            ParsedQuestion q = null;
            try {
                q = YahooAnswersParser.parse(oneRec, false);
            } catch (Exception e) {
                // If <bestanswer>...</bestanswer> is missing we may end up here...
                // This is a bit funny, because this element is supposed to be mandatory,
                // but it's not.
                System.err.println("Skipping due to parsing error, exception: " + e);
                skipErrorQty++;
                continue;
            }
            if (hSubj.contains(q.mQuestion.trim())) {
                //System.out.println(String.format("Skipping uri='%s', question='%s'", q.mQuestUri, q.mQuestion));
                skipOverlapQty++;
                continue;
            }

            out.write(oneRec);
        }
        System.out.println(
                String.format("Processed %d documents, skipped because of overlap/errors %d/%d documents",
                        docNum - 1, skipOverlapQty, skipErrorQty));
        out.close();
    } catch (ParseException e) {
        Usage("Cannot parse arguments");
    } catch (Exception e) {
        e.printStackTrace();
        System.err.println("Terminating due to an exception: " + e);
        System.exit(1);
    }
}

From source file:fr.tpt.s3.mcdag.scheduling.Main.java

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

    /* Command line options */
    Options options = new Options();

    Option input = new Option("i", "input", true, "MC-DAG XML Models");
    input.setRequired(true);/*  www  .j  a v a 2  s .  c  o  m*/
    input.setArgs(Option.UNLIMITED_VALUES); // Sets maximum number of threads to be launched
    options.addOption(input);

    Option outSched = new Option("os", "out-scheduler", false, "Write the scheduling tables into a file.");
    outSched.setRequired(false);
    options.addOption(outSched);

    Option outPrism = new Option("op", "out-prism", false, "Write PRISM model into a file.");
    outPrism.setRequired(false);
    options.addOption(outPrism);

    Option jobs = new Option("j", "jobs", true, "Number of threads to be launched.");
    jobs.setRequired(false);
    options.addOption(jobs);

    Option debugOpt = new Option("d", "debug", false, "Enabling debug.");
    debugOpt.setRequired(false);
    options.addOption(debugOpt);

    Option preemptOpt = new Option("p", "preempt", false, "Count for preemptions.");
    preemptOpt.setRequired(false);
    options.addOption(preemptOpt);

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

    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        formatter.printHelp("MC-DAG framework", options);

        System.exit(1);
        return;
    }

    String inputFilePath[] = cmd.getOptionValues("input");
    boolean bOutSched = cmd.hasOption("out-scheduler");
    boolean bOutPrism = cmd.hasOption("out-prism");
    boolean debug = cmd.hasOption("debug");
    boolean preempt = cmd.hasOption("preempt");
    boolean levels = cmd.hasOption("n-levels");
    int nbFiles = inputFilePath.length;

    int nbJobs = 1;
    if (cmd.hasOption("jobs"))
        nbJobs = Integer.parseInt(cmd.getOptionValue("jobs"));

    if (debug)
        System.out.println("[DEBUG] Launching " + inputFilePath.length + " thread(s).");

    int i_files = 0;
    ExecutorService executor = Executors.newFixedThreadPool(nbJobs);

    /* Launch threads to solve allocation */
    while (i_files != nbFiles) {
        SchedulingThread ft = new SchedulingThread(inputFilePath[i_files], bOutSched, bOutPrism, debug,
                preempt);

        ft.setLevels(levels);
        executor.execute(ft);
        i_files++;
    }

    executor.shutdown();
    executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
    System.out.println("[FRAMEWORK Main] DONE");
}

From source file:cc.twittertools.search.api.TrecSearchThriftLoadGenerator.java

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

    options.addOption(new Option(HELP_OPTION, "show help"));
    options.addOption(OptionBuilder.withArgName("port").hasArg().withDescription("port").create(PORT_OPTION));
    options.addOption(OptionBuilder.withArgName("index").hasArg().withDescription("host").create(HOST_OPTION));
    options.addOption(/* ww w.  j  ava  2 s.  c  om*/
            OptionBuilder.withArgName("num").hasArg().withDescription("threads").create(THREADS_OPTION));
    options.addOption(OptionBuilder.withArgName("num").hasArg().withDescription("number of queries to process")
            .create(LIMIT_OPTION));
    options.addOption(
            OptionBuilder.withArgName("string").hasArg().withDescription("group id").create(GROUP_OPTION));
    options.addOption(
            OptionBuilder.withArgName("string").hasArg().withDescription("access token").create(TOKEN_OPTION));

    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(HELP_OPTION) || !cmdline.hasOption(HOST_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(TrecSearchThriftServer.class.getName(), options);
        System.exit(-1);
    }

    String host = cmdline.getOptionValue(HOST_OPTION);
    int port = cmdline.hasOption(PORT_OPTION) ? Integer.parseInt(cmdline.getOptionValue(PORT_OPTION))
            : DEFAULT_PORT;
    int numThreads = cmdline.hasOption(THREADS_OPTION)
            ? Integer.parseInt(cmdline.getOptionValue(THREADS_OPTION))
            : DEFAULT_THREADS;
    int limit = cmdline.hasOption(LIMIT_OPTION) ? Integer.parseInt(cmdline.getOptionValue(LIMIT_OPTION))
            : Integer.MAX_VALUE;

    String group = cmdline.hasOption(GROUP_OPTION) ? cmdline.getOptionValue(GROUP_OPTION) : null;
    String token = cmdline.hasOption(TOKEN_OPTION) ? cmdline.getOptionValue(TOKEN_OPTION) : null;

    String queryFile = "data/queries.trec2005efficiency.txt";
    new TrecSearchThriftLoadGenerator(new File(queryFile), limit).withThreads(numThreads)
            .withCredentials(group, token).run(host, port);
}