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

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

Introduction

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

Prototype

GnuParser

Source Link

Usage

From source file:net.anthonypoon.ngram.rollingregression.Main.java

public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption("a", "action", true, "Action");
    options.addOption("i", "input", true, "input");
    options.addOption("o", "output", true, "output");
    //options.addOption("f", "format", true, "Format");
    options.addOption("u", "upbound", true, "Year up bound");
    options.addOption("l", "lowbound", true, "Year low bound");
    options.addOption("r", "range", true, "Range");
    options.addOption("T", "threshold", true, "Threshold - min count for regression");
    options.addOption("p", "positive-only", false, "Write positive slope only"); // default faluse
    CommandLineParser parser = new GnuParser();
    CommandLine cmd = parser.parse(options, args);
    Configuration conf = new Configuration();
    if (cmd.hasOption("range")) {
        conf.set("range", cmd.getOptionValue("range"));
    }/* www. ja  va  2 s .  com*/
    if (cmd.hasOption("upbound")) {
        conf.set("upbound", cmd.getOptionValue("upbound"));
    } else {
        conf.set("upbound", "9999");
    }
    if (cmd.hasOption("lowbound")) {
        conf.set("lowbound", cmd.getOptionValue("lowbound"));
    } else {
        conf.set("lowbound", "0");
    }
    if (cmd.hasOption("threshold")) {
        conf.set("threshold", cmd.getOptionValue("threshold"));
    }
    if (cmd.hasOption("positive-only")) {
        conf.set("positive-only", "true");
    }
    Job job = Job.getInstance(conf);
    /**
    if (cmd.hasOption("format")) {
    switch (cmd.getOptionValue("format")) {
        case "compressed":
            job.setInputFormatClass(SequenceFileAsTextInputFormat.class);
            break;
        case "text":
            job.setInputFormatClass(KeyValueTextInputFormat.class);
            break;
    }
            
    }**/
    job.setJarByClass(Main.class);
    switch (cmd.getOptionValue("action")) {
    case "get-regression":
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);
        for (String inputPath : cmd.getOptionValue("input").split(",")) {
            MultipleInputs.addInputPath(job, new Path(inputPath), KeyValueTextInputFormat.class,
                    RollingRegressionMapper.class);
        }
        job.setReducerClass(RollingRegressionReducer.class);
        break;
    default:
        throw new IllegalArgumentException("Missing action");
    }

    String timestamp = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss").format(new Date());

    //FileInputFormat.setInputPaths(job, new Path(cmd.getOptionValue("input")));
    FileOutputFormat.setOutputPath(job, new Path(cmd.getOptionValue("output") + "/" + timestamp));
    System.exit(job.waitForCompletion(true) ? 0 : 1);
    /**
    double[] nazismBaseLine = {3, 12, 12, 18, 233, 239, 386, 333, 593, 1244, 1925, 3013, 3120, 3215, 3002, 3355, 2130, 1828, 1406, 1751, 1433, 1033, 881, 1330, 1029, 760, 1288, 1013, 1014};
    InputStream inStream = Main.class.getResourceAsStream("/1g-matrix.txt");
    BufferedReader br = new BufferedReader(new InputStreamReader(inStream));
    String line = "";
    Map<String, Double> result = new HashMap();
    while ((line = br.readLine()) != null) {
    String[] strArray = line.split("\t");
    double[] compareArray = new double[nazismBaseLine.length];
    for (int i = 0; i < nazismBaseLine.length; i ++) {
        compareArray[i] = Double.valueOf(strArray[i + 24]);
    }
    result.put(strArray[0], new PearsonsCorrelation().correlation(nazismBaseLine, compareArray));
    }
    List<Map.Entry<String, Double>> toBeSorted = new ArrayList();
    for (Map.Entry pair : result.entrySet()) {
    toBeSorted.add(pair);
    }
    Collections.sort(toBeSorted, new Comparator<Map.Entry<String, Double>>(){
    @Override
    public int compare(Map.Entry<String, Double> o1, Map.Entry<String, Double> o2) {
        return o2.getValue().compareTo(o1.getValue());
    }
    });
    for (Map.Entry<String, Double> pair : toBeSorted) {
    if (!Double.isNaN(pair.getValue())) {
        System.out.println(pair.getKey() + "\t" + pair.getValue());
    }
    }**/
}

From source file:com.amit.api.compiler.App.java

public static void main(String[] args) {
    Options options = createOptions();//from  www.  java 2 s  .  co m

    CommandLineParser parser = new GnuParser();
    try {
        // parse the command line arguments
        CommandLine cmd = parser.parse(options, args);
        execute(cmd);
    } catch (ParseException exp) {
        System.out.println("Invalid arguments.  Reason: " + exp.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("args", options);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:jlite.cli.ProxyInit.java

public static void main(String[] args) {
    CommandLineParser parser = new GnuParser();
    Options options = setupOptions();//ww w  . ja  v  a 2 s. c  o  m
    HelpFormatter helpFormatter = new HelpFormatter();
    helpFormatter.setSyntaxPrefix("Usage: ");
    CommandLine line = null;
    try {
        line = parser.parse(options, args);
        if (line.hasOption("help")) {
            System.out.println(); // extra line
            helpFormatter.printHelp(100, COMMAND, "\noptions:", options, "\n" + CLI.FOOTER + "\n", false);
            System.out.println(); // extra line
            System.exit(0);
        } else {
            if (line.hasOption("xml")) {
                System.out.println("<output>");
            }
            String[] remArgs = line.getArgs();
            if (remArgs.length > 0) {
                run(remArgs, line);
            } else {
                throw new MissingArgumentException("Missing required argument: <voms>[:<command>]");
            }
        }
    } catch (ParseException e) {
        System.err.println("\n" + e.getMessage() + "\n");
        helpFormatter.printHelp(100, COMMAND, "\noptions:", options, "\n" + CLI.FOOTER + "\n", false);
        System.out.println(); // extra line
        System.exit(-1);
    } catch (Exception e) {
        if ((line != null) && (line.hasOption("xml"))) {
            System.out.println("<error>" + e.getMessage() + "</error>");
        } else {
            System.err.println(e.getMessage());
        }
    } finally {
        if (line.hasOption("xml")) {
            System.out.println("</output>");
        }
    }
    System.out.println(); // extra line
}

From source file:com.rackspacecloud.client.cloudfiles.sample.FilesCopy.java

public static void main(String args[]) throws NoSuchAlgorithmException, FilesException {
    //Build the command line options
    Options options = addCommandLineOptions();

    if (args.length <= 0)
        printHelp(options);// w ww .jav  a2s .  c o  m

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

        if (line.hasOption("help"))
            printHelp(options);

        if (line.hasOption("file") && line.hasOption("folder")) {
            System.err.println("Can not use both -file and -folder on the command line at the same time.");
            System.exit(-1);
        } //if (line.hasOption("file") && line.hasOption("folder"))

        if (line.hasOption("download")) {
            if (line.hasOption("folder")) {
                String localFolder = FilenameUtils.normalize(line.getOptionValue("folder"));
                String containerName = null;
                if (StringUtils.isNotBlank(localFolder)) {
                    File localFolderObj = new File(localFolder);
                    if (localFolderObj.exists() && localFolderObj.isDirectory()) {
                        if (line.hasOption("container")) {
                            containerName = line.getOptionValue("container");
                            if (!StringUtils.isNotBlank(containerName)) {
                                System.err.println(
                                        "You must provide a valid value for the  Container to upload to !");
                                System.exit(-1);
                            } //if (!StringUtils.isNotBlank(ontainerName))                            
                        } else {
                            System.err.println(
                                    "You must provide the -container for a copy operation to work as expected.");
                            System.exit(-1);
                        }

                        System.out.println("Downloading all objects from: " + containerName
                                + " to local folder: " + localFolder);

                        getContainerObjects(localFolderObj, containerName);

                    } else {
                        if (!localFolderObj.exists()) {
                            System.err.println("The local folder: " + localFolder
                                    + " does not exist.  Create it first and then run this command.");
                        }

                        if (!localFolderObj.isDirectory()) {
                            System.err.println(
                                    "The local folder name supplied : " + localFolder + " is not a folder !");
                        }

                        System.exit(-1);
                    }
                }
            }
            System.exit(0);
        } //if (line.hasOption("download"))

        if (line.hasOption("folder")) {
            String containerName = null;
            String folderPath = null;

            if (line.hasOption("container")) {
                containerName = line.getOptionValue("container");
                if (!StringUtils.isNotBlank(containerName)) {
                    System.err.println("You must provide a valid value for the  Container to upload to !");
                    System.exit(-1);
                } //if (!StringUtils.isNotBlank(containerName))

            } else {
                System.err.println("You must provide the -container for a copy operation to work as expected.");
                System.exit(-1);
            }

            folderPath = line.getOptionValue("folder");
            if (StringUtils.isNotBlank(folderPath)) {
                File folder = new File(FilenameUtils.normalize(folderPath));
                if (folder.isDirectory()) {
                    if (line.hasOption("z")) {
                        System.out.println("Zipping: " + folderPath);
                        System.out.println("Nested folders are ignored !");

                        File zipedFolder = zipFolder(folder);
                        String mimeType = FilesConstants.getMimetype(ZIPEXTENSION);
                        copyToCreateContainerIfNeeded(zipedFolder, mimeType, containerName);
                    } else {
                        File[] files = folder.listFiles();
                        for (File f : files) {
                            String mimeType = FilesConstants
                                    .getMimetype(FilenameUtils.getExtension(f.getName()));
                            System.out.println("Uploading :" + f.getName() + " to " + folder.getName());
                            copyToCreateContainerIfNeeded(f, mimeType, containerName);
                            System.out.println(
                                    "Upload :" + f.getName() + " to " + folder.getName() + " completed.");
                        }
                    }
                } else {
                    System.err.println("You must provide a valid folder value for the -folder option !");
                    System.err.println("The value provided is: " + FilenameUtils.normalize(folderPath));
                    System.exit(-1);
                }

            }
        } //if (line.hasOption("folder"))

        if (line.hasOption("file")) {
            String containerName = null;
            String fileNamePath = null;

            if (line.hasOption("container")) {
                containerName = line.getOptionValue("container");
                if (!StringUtils.isNotBlank(containerName) || containerName.indexOf('/') != -1) {
                    System.err.println("You must provide a valid value for the  Container to upload to !");
                    System.exit(-1);
                } //if (!StringUtils.isNotBlank(containerName))
            } else {
                System.err.println("You must provide the -container for a copy operation to work as expected.");
                System.exit(-1);
            }

            fileNamePath = line.getOptionValue("file");
            if (StringUtils.isNotBlank(fileNamePath)) {
                String fileName = FilenameUtils.normalize(fileNamePath);
                String fileExt = FilenameUtils.getExtension(fileNamePath);
                String mimeType = FilesConstants.getMimetype(fileExt);
                File file = new File(fileName);

                if (line.hasOption("z")) {
                    logger.info("Zipping " + fileName);
                    if (!file.isDirectory()) {
                        File zippedFile = zipFile(file);
                        mimeType = FilesConstants.getMimetype(ZIPEXTENSION);
                        copyTo(zippedFile, mimeType, containerName);
                        zippedFile.delete();
                    }

                } //if (line.hasOption("z"))
                else {

                    logger.info("Uploading " + fileName + ".");
                    if (!file.isDirectory())
                        copyTo(file, mimeType, containerName);
                    else {
                        System.err.println(
                                "The path you provided is a folder.  For uploading folders use the -folder option.");
                        System.exit(-1);
                    }
                }
            } //if (StringUtils.isNotBlank(file))
            else {
                System.err.println("You must provide a valid value for the file to upload !");
                System.exit(-1);
            }
        } //if (line.hasOption("file"))
    } //end try        
    catch (ParseException err) {
        System.err.println("Please see the logs for more details. Error Message: " + err.getMessage());
        err.printStackTrace(System.err);
    } //catch( ParseException err )
    catch (FilesAuthorizationException err) {
        logger.fatal("FilesAuthorizationException : Failed to login to your  account !" + err);
        System.err.println("Please see the logs for more details. Error Message: " + err.getMessage());
    } //catch (FilesAuthorizationException err)

    catch (Exception err) {
        logger.fatal("IOException : " + err);
        System.err.println("Please see the logs for more details. Error Message: " + err.getMessage());
    } //catch ( IOException err)
}

From source file:eu.interedition.collatex.http.Server.java

public static void main(String... args) {
    try {/*from www  .  j a  v  a2 s  .c om*/
        final CommandLine commandLine = new GnuParser().parse(OPTIONS, args);
        if (commandLine.hasOption("h")) {
            new HelpFormatter().printHelp("collatex-server [<options> ...]\n", OPTIONS);
            return;
        }

        final Collator collator = new Collator(Integer.parseInt(commandLine.getOptionValue("mpc", "2")),
                Integer.parseInt(commandLine.getOptionValue("mcs", "0")),
                commandLine.getOptionValue("dot", null));
        final String staticPath = System.getProperty("collatex.static.path", "");
        final HttpHandler httpHandler = staticPath.isEmpty()
                ? new CLStaticHttpHandler(Server.class.getClassLoader(), "/static/") {
                    @Override
                    protected void onMissingResource(Request request, Response response) throws Exception {
                        collator.service(request, response);
                    }
                }
                : new StaticHttpHandler(staticPath.replaceAll("/+$", "") + "/") {
                    @Override
                    protected void onMissingResource(Request request, Response response) throws Exception {
                        collator.service(request, response);
                    }
                };

        final NetworkListener httpListener = new NetworkListener("http", "0.0.0.0",
                Integer.parseInt(commandLine.getOptionValue("p", "7369")));

        final CompressionConfig compressionConfig = httpListener.getCompressionConfig();
        compressionConfig.setCompressionMode(CompressionConfig.CompressionMode.ON);
        compressionConfig.setCompressionMinSize(860); // http://webmasters.stackexchange.com/questions/31750/what-is-recommended-minimum-object-size-for-gzip-performance-benefits
        compressionConfig.setCompressableMimeTypes("application/javascript", "application/json",
                "application/xml", "text/css", "text/html", "text/javascript", "text/plain", "text/xml");

        final HttpServer httpServer = new HttpServer();
        httpServer.addListener(httpListener);
        httpServer.getServerConfiguration().addHttpHandler(httpHandler,
                commandLine.getOptionValue("cp", "").replaceAll("/+$", "") + "/*");

        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            if (LOG.isLoggable(Level.INFO)) {
                LOG.info("Stopping HTTP server");
            }
            httpServer.shutdown();
        }));

        httpServer.start();

        Thread.sleep(Long.MAX_VALUE);
    } catch (Throwable t) {
        LOG.log(Level.SEVERE, "Error while parsing command line", t);
        System.exit(1);
    }
}

From source file:info.jejking.opengeodb.neo4j.importer.ImporterRunner.java

/**
 * Runs the importer./* w  w  w.j  a v  a2s  .  c  o  m*/
 * 
 * <p>
 * Supply the following arguments:
 * </p>
 * <ol>
 * <li>path to the tab-delimited place file</li>
 * <li>path to the tab-delimited postal code file</li>
 * <li>path to the directory where the Graph DB is to be found/created</li>
 * </ol>
 * 
 * @param args
 *            as above
 * @throws IOException
 * @throws ParseException 
 */
public static void main(String[] args) throws IOException, ParseException {

    initOptions();

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

    if (commandLine.hasOption("h")) {
        HelpFormatter helpFormatter = new HelpFormatter();
        helpFormatter.printHelp("opengeodb2neo4j", options);
    } else {
        String placeFilePath = commandLine.getOptionValue("p");
        String zipFilePath = commandLine.getOptionValue("z");
        String neo4jDirPath = commandLine.getOptionValue("n");
        Importer importer = new Importer();
        importer.doImport(placeFilePath, zipFilePath, neo4jDirPath);
    }

}

From source file:com.rabbitmq.perf.PerfTest.java

public static void main(String[] args) {
    Options options = getOptions();//from  w  ww .j  av a 2 s  .  co  m
    CommandLineParser parser = new GnuParser();
    try {
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption('?')) {
            usage(options);
            System.exit(0);
        }
        String testID = new SimpleDateFormat("HHmmss-SSS").format(Calendar.getInstance().getTime());
        testID = strArg(cmd, 'd', "test-" + testID);
        String exchangeType = strArg(cmd, 't', "direct");
        String exchangeName = strArg(cmd, 'e', exchangeType);
        String queueNames = strArg(cmd, 'u', "");
        String routingKey = strArg(cmd, 'k', null);
        boolean randomRoutingKey = cmd.hasOption('K');
        int samplingInterval = intArg(cmd, 'i', 1);
        float producerRateLimit = floatArg(cmd, 'r', 0.0f);
        float consumerRateLimit = floatArg(cmd, 'R', 0.0f);
        int producerCount = intArg(cmd, 'x', 1);
        int consumerCount = intArg(cmd, 'y', 1);
        int producerTxSize = intArg(cmd, 'm', 0);
        int consumerTxSize = intArg(cmd, 'n', 0);
        long confirm = intArg(cmd, 'c', -1);
        boolean autoAck = cmd.hasOption('a');
        int multiAckEvery = intArg(cmd, 'A', 0);
        int channelPrefetch = intArg(cmd, 'Q', 0);
        int consumerPrefetch = intArg(cmd, 'q', 0);
        int minMsgSize = intArg(cmd, 's', 0);
        int timeLimit = intArg(cmd, 'z', 0);
        int producerMsgCount = intArg(cmd, 'C', 0);
        int consumerMsgCount = intArg(cmd, 'D', 0);
        List<?> flags = lstArg(cmd, 'f');
        int frameMax = intArg(cmd, 'M', 0);
        int heartbeat = intArg(cmd, 'b', 0);
        boolean predeclared = cmd.hasOption('p');

        String uri = strArg(cmd, 'h', "amqp://localhost");

        //setup
        PrintlnStats stats = new PrintlnStats(testID, 1000L * samplingInterval, producerCount > 0,
                consumerCount > 0, (flags.contains("mandatory") || flags.contains("immediate")), confirm != -1);

        ConnectionFactory factory = new ConnectionFactory();
        factory.setShutdownTimeout(0); // So we still shut down even with slow consumers
        factory.setUri(uri);
        factory.setRequestedFrameMax(frameMax);
        factory.setRequestedHeartbeat(heartbeat);

        MulticastParams p = new MulticastParams();
        p.setAutoAck(autoAck);
        p.setAutoDelete(true);
        p.setConfirm(confirm);
        p.setConsumerCount(consumerCount);
        p.setConsumerMsgCount(consumerMsgCount);
        p.setConsumerRateLimit(consumerRateLimit);
        p.setConsumerTxSize(consumerTxSize);
        p.setExchangeName(exchangeName);
        p.setExchangeType(exchangeType);
        p.setFlags(flags);
        p.setMultiAckEvery(multiAckEvery);
        p.setMinMsgSize(minMsgSize);
        p.setPredeclared(predeclared);
        p.setConsumerPrefetch(consumerPrefetch);
        p.setChannelPrefetch(channelPrefetch);
        p.setProducerCount(producerCount);
        p.setProducerMsgCount(producerMsgCount);
        p.setProducerTxSize(producerTxSize);
        p.setQueueNames(Arrays.asList(queueNames.split(",")));
        p.setRoutingKey(routingKey);
        p.setRandomRoutingKey(randomRoutingKey);
        p.setProducerRateLimit(producerRateLimit);
        p.setTimeLimit(timeLimit);

        MulticastSet set = new MulticastSet(stats, factory, p, testID);
        set.run(true);

        stats.printFinal();
    } catch (ParseException exp) {
        System.err.println("Parsing failed. Reason: " + exp.getMessage());
        usage(options);
    } catch (Exception e) {
        System.err.println("Main thread caught exception: " + e);
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:com.ingby.socbox.bischeck.test.JDBCtest.java

static public void main(String[] args)
        throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {

    CommandLineParser parser = new GnuParser();
    CommandLine line = null;/*from ww w. j  a v a 2 s.  c  o  m*/

    // create the Options
    Options options = new Options();
    options.addOption("u", "usage", false, "show usage.");
    options.addOption("c", "connection", true, "the connection url");
    options.addOption("s", "sql", true, "the sql statement to run");
    options.addOption("m", "meta", true, "get the table meta data");
    options.addOption("C", "columns", true, "the number of columns to display, default 1");
    options.addOption("d", "driver", true, "the driver class");
    options.addOption("v", "verbose", false, "verbose outbout");

    try {
        // parse the command line arguments
        line = parser.parse(options, args);
    } catch (org.apache.commons.cli.ParseException e) {
        System.out.println("Command parse error:" + e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("JDBCtest", options);
        Util.ShellExit(1);
    }

    if (line.hasOption("verbose")) {
        verbose = true;
    }

    if (line.hasOption("usage")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("Bischeck", options);
        Util.ShellExit(0);
    }

    String driverclassname = null;
    if (!line.hasOption("driver")) {
        System.out.println("Driver class must be set");
        Util.ShellExit(1);
    } else {
        driverclassname = line.getOptionValue("driver");
        outputln("DriverClass: " + driverclassname);
    }

    String connectionname = null;
    if (!line.hasOption("connection")) {
        System.out.println("Connection url must be set");
        Util.ShellExit(1);
    } else {
        connectionname = line.getOptionValue("connection");
        outputln("Connection: " + connectionname);
    }

    String sql = null;
    String tablename = null;

    if (line.hasOption("sql")) {
        sql = line.getOptionValue("sql");
        outputln("SQL: " + sql);

    }

    if (line.hasOption("meta")) {
        tablename = line.getOptionValue("meta");
        outputln("Table: " + tablename);
    }

    int nrColumns = 1;
    if (line.hasOption("columns")) {
        nrColumns = new Integer(line.getOptionValue("columns"));
    }

    long execStart = 0l;
    long execEnd = 0l;
    long openStart = 0l;
    long openEnd = 0l;
    long metaStart = 0l;
    long metaEnd = 0l;

    Class.forName(driverclassname).newInstance();
    openStart = System.currentTimeMillis();
    Connection conn = DriverManager.getConnection(connectionname);
    openEnd = System.currentTimeMillis();

    if (tablename != null) {
        ResultSet rsCol = null;
        metaStart = System.currentTimeMillis();
        DatabaseMetaData md = conn.getMetaData();
        metaEnd = System.currentTimeMillis();

        rsCol = md.getColumns(null, null, tablename, null);
        if (verbose) {
            tabular("COLUMN_NAME");
            tabular("TYPE_NAME");
            tabular("COLUMN_SIZE");
            tabularlast("DATA_TYPE");
            outputln("");
        }

        while (rsCol.next()) {
            tabular(rsCol.getString("COLUMN_NAME"));
            tabular(rsCol.getString("TYPE_NAME"));
            tabular(rsCol.getString("COLUMN_SIZE"));
            tabularlast(rsCol.getString("DATA_TYPE"));
            outputln("", true);
        }
    }

    if (sql != null) {
        Statement stat = conn.createStatement();
        stat.setQueryTimeout(10);

        execStart = System.currentTimeMillis();
        ResultSet res = stat.executeQuery(sql);
        ResultSetMetaData rsmd = res.getMetaData();
        execEnd = System.currentTimeMillis();

        if (verbose) {
            for (int i = 1; i < nrColumns + 1; i++) {
                if (i != nrColumns)
                    tabular(rsmd.getColumnName(i));
                else
                    tabularlast(rsmd.getColumnName(i));
            }
            outputln("");
        }
        while (res.next()) {
            for (int i = 1; i < nrColumns + 1; i++) {
                if (i != nrColumns)
                    tabular(res.getString(i));
                else
                    tabularlast(res.getString(i));
            }
            outputln("", true);
        }

        stat.close();
        res.close();
    }

    conn.close();

    // Print the execution times
    outputln("Open time: " + (openEnd - openStart) + " ms");

    if (line.hasOption("meta")) {
        outputln("Meta time: " + (metaEnd - metaStart) + " ms");
    }

    if (line.hasOption("sql")) {
        outputln("Exec time: " + (execEnd - execStart) + " ms");
    }
}

From source file:com.rapleaf.hank.cli.AddDomainGroup.java

public static void main(String args[])
        throws InterruptedException, IOException, ParseException, InvalidConfigurationException {
    Options options = new Options();
    options.addOption("n", "name", true, "the name of the domain to be created");
    options.addOption("c", "config", true,
            "path of a valid config file with coordinator connection information");
    try {//  w w w  . j  a va2  s.  c om
        CommandLine line = new GnuParser().parse(options, args);
        CommandLineChecker.check(line, options, new String[] { "config", "name" }, AddDomainGroup.class);
        ClientConfigurator configurator = new YamlClientConfigurator(line.getOptionValue("config"));
        addDomainGroup(configurator, line.getOptionValue("name"));
    } catch (ParseException e) {
        new HelpFormatter().printHelp("add_domain", options);
        throw e;
    }
}

From source file:com.rabbitmq.examples.FileProducer.java

public static void main(String[] args) {
    Options options = new Options();
    options.addOption(new Option("h", "uri", true, "AMQP URI"));
    options.addOption(new Option("p", "port", true, "broker port"));
    options.addOption(new Option("t", "type", true, "exchange type"));
    options.addOption(new Option("e", "exchange", true, "exchange name"));
    options.addOption(new Option("k", "routing-key", true, "routing key"));

    CommandLineParser parser = new GnuParser();

    try {/*  w ww .  jav a2  s  .c om*/
        CommandLine cmd = parser.parse(options, args);

        String uri = strArg(cmd, 'h', "amqp://localhost");
        String exchangeType = strArg(cmd, 't', "direct");
        String exchange = strArg(cmd, 'e', null);
        String routingKey = strArg(cmd, 'k', null);

        ConnectionFactory connFactory = new ConnectionFactory();
        connFactory.setUri(uri);
        Connection conn = connFactory.newConnection();

        final Channel ch = conn.createChannel();

        if (exchange == null) {
            System.err.println("Please supply exchange name to send to (-e)");
            System.exit(2);
        }
        if (routingKey == null) {
            System.err.println("Please supply routing key to send to (-k)");
            System.exit(2);
        }
        ch.exchangeDeclare(exchange, exchangeType);

        for (String filename : cmd.getArgs()) {
            System.out.print("Sending " + filename + "...");
            File f = new File(filename);
            FileInputStream i = new FileInputStream(f);
            byte[] body = new byte[(int) f.length()];
            i.read(body);
            i.close();

            Map<String, Object> headers = new HashMap<String, Object>();
            headers.put("filename", filename);
            headers.put("length", (int) f.length());
            BasicProperties props = new BasicProperties.Builder().headers(headers).build();
            ch.basicPublish(exchange, routingKey, props, body);
            System.out.println(" done.");
        }

        conn.close();
    } catch (Exception ex) {
        System.err.println("Main thread caught exception: " + ex);
        ex.printStackTrace();
        System.exit(1);
    }
}