Example usage for com.mongodb MongoClient getMongoClientOptions

List of usage examples for com.mongodb MongoClient getMongoClientOptions

Introduction

In this page you can find the example usage for com.mongodb MongoClient getMongoClientOptions.

Prototype

public MongoClientOptions getMongoClientOptions() 

Source Link

Document

Gets the options that this client uses to connect to server.

Usage

From source file:com.ca.apm.mongo.Topology.java

License:Open Source License

protected MongoClient setupDbClient(final String dbHost, final int dbPort) {
    final boolean useSSL = Collector.getBooleanProp(Collector.USE_SSL_PROP, props);
    final String clientTrustStore = Collector.getOptionalStringProp(Collector.SSL_CLIENT_TRUST_STORE_FILE_PROP,
            props);// w  w  w.j  a v a2  s  . c o  m
    final String clientPasswd = Collector.getOptionalStringProp(Collector.SSL_CLIENT_TRUST_STORE_PASSWD_PROP,
            props);

    try {
        MongoClientOptions.Builder builder = new MongoClientOptions.Builder();

        if (useSSL) {
            System.setProperty(Collector.SSL_CLIENT_TRUST_STORE_FILE_PROP, clientTrustStore);
            System.setProperty(Collector.SSL_CLIENT_TRUST_STORE_PASSWD_PROP, clientPasswd);
            builder = builder.socketFactory(SSLSocketFactory.getDefault());
        }

        final MongoClientOptions options = builder.build();
        MongoClient dbClient = new MongoClient(new ServerAddress(dbHost, dbPort), mongoCreds, options);
        logger.log(Level.FINE, "Connected to mongo at {0}", dbClient.getConnectPoint());
        logger.log(Level.FINE, "Client options: " + dbClient.getMongoClientOptions());
        return dbClient;
    } catch (Exception ex) {
        throw new RuntimeException("Can't initialize mongo client", ex);
    }
}

From source file:com.ultratechnica.mongodb.Main.java

License:Apache License

public static void main(String[] args) {

    log.info("=============================================================================================\n"
            + "                       _   _     _                 \n"
            + " |\\/|  _  ._   _   _  | \\ |_)   |_)  _  ._   _ |_  \n"
            + " |  | (_) | | (_| (_) |_/ |_)   |_) (/_ | | (_ | | \n"
            + "               _|                                  \n"
            + "Copyright 2013 Keith Bishop, Ultratechnica Ltd, http://ultratechnica.com\n"
            + "Licensed to Apache "
            + "=============================================================================================\n");
    Options options = getOptions();//from   w ww  .ja v a  2  s .  co m

    CommandLine commandLine = parseArgs(args, options);

    MongoClient client = null;

    if (commandLine.hasOption("host") && commandLine.hasOption("port")) {

        String host = commandLine.getOptionValue("host");
        String port = commandLine.getOptionValue("port");

        try {

            client = new MongoClient(host, Integer.parseInt(port));
        } catch (UnknownHostException e) {
            log.error("Unable to connect to host [{}] on port [{}]", host, port);
        }
    } else if (options.hasOption("host")) {

        String host = commandLine.getOptionValue("host");

        try {
            client = new MongoClient(host);
        } catch (UnknownHostException e) {
            log.error("Unable to connect to host [{}] on default port ()", host);
        }
    } else {

        try {
            client = new MongoClient();
        } catch (UnknownHostException e) {
            log.error("Unable to connect default host ({}) on default port ()", DEFAULT_HOST, DEFAULT_PORT);
        }
    }

    if (client == null) {
        System.out.println("Exiting, due to previous connection errors");
        System.exit(1);
    }

    ServerAddress clientAddress = client.getAddress();
    log.info("Connected to MongoDB [{}]", clientAddress);

    MongoClientOptions mongoClientOptions = client.getMongoClientOptions();

    log.info("=============================================================================================\n"
            + "Using Mongo Client options:\n" + "\tConnections per host: "
            + mongoClientOptions.getConnectionsPerHost() + "\n" + "\tConect timeout: "
            + mongoClientOptions.getConnectTimeout() + " \n" + "\tSocket timeout: "
            + mongoClientOptions.getSocketTimeout() + "\n" + "\tMax Wait time: "
            + mongoClientOptions.getMaxWaitTime() + "\n" + "\tMax Auto connect retry time: "
            + mongoClientOptions.getMaxAutoConnectRetryTime() + "\n"
            + "\tMax threads allowed to block for conneciton multipler: "
            + mongoClientOptions.getThreadsAllowedToBlockForConnectionMultiplier() + "\n" + "\tWrite concern: "
            + mongoClientOptions.getWriteConcern() + "\n" + "\tRead Preference: "
            + mongoClientOptions.getReadPreference() + "\n"
            + "=============================================================================================\n");

    String items = commandLine.getOptionValue("n");

    int numberOfItems = 0;
    try {
        numberOfItems = Integer.parseInt(items);
    } catch (NumberFormatException e) {
        log.error("The parameter provided for -n was not an integer [{}]", items);
        System.exit(1);
    }

    DB local = client.getDB("local");

    DBCollection collection = local.getCollection(DEFAULT_COLLECTION_NAME);

    log.info("Starting benchmark, inserting [{}] items into collection [{}]", numberOfItems,
            DEFAULT_COLLECTION_NAME);

    long startTime = System.currentTimeMillis();

    for (int i = 0; i < numberOfItems; i++) {

        BasicDBObjectBuilder builder = BasicDBObjectBuilder.start().add("timestamp", new Date())
                .add("field1", "123456").add("field2", "2345678")
                .add("field3", "123123231313131232131231231231123132123123123").add("field4", true);

        WriteResult result = collection.insert(builder.get());
        if (!result.getLastError().ok()) {
            log.error("An error occurred [{}]", result.getLastError());
        }
    }

    long endTime = System.currentTimeMillis();

    log.info("Finished benchmarking.");
    long timeTakenMillis = endTime - startTime;

    float timeTaken = (float) timeTakenMillis / 1000;

    log.info("Results:\n\n" + String.format("%-25s %d", "Number of Items inserted:", numberOfItems) + "\n"
            + String.format("%-25s %.2f", "Time elapsed:", timeTaken) + " seconds\n"
            + String.format("%-25s %.2f", "Throughput:", numberOfItems / timeTaken) + " items/sec\n");

    log.info("Removing test data...");
    collection.remove(new BasicDBObject());
    log.info("Cleared collection [test]");
}

From source file:org.nuxeo.directory.mongodb.MongoDBConnectionHelper.java

License:Apache License

/**
 * Initialize a connection to the MongoDB server
 *
 * @param server the server url/*from   w w  w.j a va2  s.  co  m*/
 * @return the MongoDB client
 */
public static MongoClient newMongoClient(String server) {
    if (StringUtils.isBlank(server)) {
        throw new NuxeoException("Missing <server> in MongoDB repository descriptor");
    }
    MongoClientOptions.Builder optionsBuilder = MongoClientOptions.builder()
            // Can help to prevent firewall disconnects
            // inactive connection, option not available from URI
            .socketKeepAlive(true)
            // don't wait for ever by default,
            // can be overridden using URI options
            .connectTimeout(MONGODB_OPTION_CONNECTION_TIMEOUT_MS)
            .socketTimeout(MONGODB_OPTION_SOCKET_TIMEOUT_MS).description("Nuxeo");
    MongoClient client;
    if (server.startsWith("mongodb://")) {
        // allow mongodb:// URI syntax for the server, to pass everything in one string
        client = new MongoClient(new MongoClientURI(server, optionsBuilder));
    } else {
        client = new MongoClient(new ServerAddress(server), optionsBuilder.build());
    }
    if (log.isDebugEnabled()) {
        log.debug("MongoClient initialized with options: " + client.getMongoClientOptions().toString());
    }
    return client;
}

From source file:org.nuxeo.ecm.core.storage.mongodb.MongoDBRepository.java

License:Apache License

public static MongoClient newMongoClient(MongoDBRepositoryDescriptor descriptor) throws UnknownHostException {
    MongoClient ret;
    String server = descriptor.server;
    if (StringUtils.isBlank(server)) {
        throw new NuxeoException("Missing <server> in MongoDB repository descriptor");
    }//  w  w  w  . jav  a  2s .  c  o  m
    MongoClientOptions.Builder optionsBuilder = MongoClientOptions.builder()
            // Can help to prevent firewall disconnects inactive connection, option not available from URI
            .socketKeepAlive(true)
            // don't wait for ever by default, can be overridden using URI options
            .connectTimeout(MONGODB_OPTION_CONNECTION_TIMEOUT_MS)
            .socketTimeout(MONGODB_OPTION_SOCKET_TIMEOUT_MS).description("Nuxeo");
    if (server.startsWith("mongodb://")) {
        // allow mongodb:// URI syntax for the server, to pass everything in one string
        ret = new MongoClient(new MongoClientURI(server, optionsBuilder));
    } else {
        ret = new MongoClient(new ServerAddress(server), optionsBuilder.build());
    }
    if (log.isDebugEnabled()) {
        log.debug("MongoClient initialized with options: " + ret.getMongoClientOptions().toString());
    }
    return ret;
}