Example usage for com.mongodb MongoClientOptions.Builder MongoClientOptions.Builder

List of usage examples for com.mongodb MongoClientOptions.Builder MongoClientOptions.Builder

Introduction

In this page you can find the example usage for com.mongodb MongoClientOptions.Builder MongoClientOptions.Builder.

Prototype

MongoClientOptions.Builder

Source Link

Usage

From source file:biopolis.headless.BiopolisPersistencyLayer.java

public BiopolisPersistencyLayer(BiopolisProperties props) throws BiopolisGeneralException, SQLException {
    org.neo4j.jdbc.Driver driver = new org.neo4j.jdbc.Driver();
    this.connNeo4j = driver.connect("jdbc:neo4j://" + props.neo4j_endpoint, new Properties());
    try {/*from   w  w w  . j  a v a 2 s .  c  o  m*/
        System.out.println(props.mongo_host);
        MongoClientOptions mco = new MongoClientOptions.Builder().connectionsPerHost(10)
                .threadsAllowedToBlockForConnectionMultiplier(10).build();
        mongo = new MongoClient(new ServerAddress("localhost"), mco); //addresses is a pre-populated List 
    } catch (MongoException e) {
        e.printStackTrace();
        throw new BiopolisGeneralException("Mongo exception problem");
    } catch (UnknownHostException e) {
        e.printStackTrace();
        throw new BiopolisGeneralException("Mongo connection problem");
    }
    DB dbo = mongo.getDB(BiopolisPersistencyLayer.dbName);
    if (dbo.collectionExists(BiopolisPersistencyLayer.collectionNamePlaces)) {
        this.dbcolPlaces = dbo.getCollection(BiopolisPersistencyLayer.collectionNamePlaces);

    } else {
        this.dbcolPlaces = dbo.createCollection(BiopolisPersistencyLayer.collectionNamePlaces, null);
        this.dbcolPlaces.createIndex(new BasicDBObject("loc", "2dsphere"));
    }

    if (dbo.collectionExists(collectionNameSearches)) {
        this.dbcolSearches = dbo.getCollection(collectionNameSearches);

    } else {
        this.dbcolSearches = dbo.createCollection(collectionNameSearches, null);
        this.dbcolSearches.createIndex(new BasicDBObject("biopolisttl", 1),
                new BasicDBObject("expireAfterSeconds", props.expire_search));
    }
    this.segSZ = props.segment_size;
}

From source file:com.appdynamics.monitors.mongo.MongoDBMonitor.java

License:Apache License

private MongoClientOptions getMongoClientSSLOptions(Configuration config) throws MongoMonitorException {
    MongoClientOptions clientOpts = null;
    if (config.isSsl()) {
        String filePath = config.getPemFilePath();
        if (!Strings.isNullOrEmpty(filePath)) {
            try {
                clientOpts = new MongoClientOptions.Builder().socketFactory(getSocketFactoryFromPEM(filePath))
                        .build();//from   ww  w.  j av a 2  s .co  m
            } catch (Exception e) {
                logger.error("Error establishing ssl socket factory", e);
                throw new MongoMonitorException("Error establishing ssl socket factory");
            }
        } else {
            String msg = "The argument pemFilePath is null or empty in config.yml";
            logger.error(msg);
            throw new MongoMonitorException(msg);
        }
    }
    return clientOpts;
}

From source file:com.englishtown.vertx.GridFSModule.java

License:Open Source License

@Override
public void start() {
    eb = vertx.eventBus();/*w w  w.java 2 s . c  om*/
    logger = container.logger();

    JsonObject config = container.config();
    address = config.getString("address", DEFAULT_ADDRESS);

    host = config.getString("host", "localhost");
    port = config.getInteger("port", 27017);
    dbName = config.getString("db_name", "default_db");
    username = config.getString("username", null);
    password = config.getString("password", null);
    int poolSize = config.getInteger("pool_size", 10);

    JsonArray seedsProperty = config.getArray("seeds");

    try {
        MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
        builder.connectionsPerHost(poolSize);
        if (seedsProperty == null) {
            ServerAddress address = new ServerAddress(host, port);
            mongo = new MongoClient(address, builder.build());
        } else {
            List<ServerAddress> seeds = makeSeeds(seedsProperty);
            mongo = new MongoClient(seeds, builder.build());
        }
        db = mongo.getDB(dbName);
        if (username != null && password != null) {
            db.authenticate(username, password.toCharArray());
        }
    } catch (UnknownHostException e) {
        logger.error("Failed to connect to mongo server", e);
    }

    // Main Message<JsonObject> handler that inspects an "action" field
    eb.registerHandler(address, this);

    // Message<byte[]> handler to save file chunks
    eb.registerHandler(address + "/saveChunk", new Handler<Message<Buffer>>() {
        @Override
        public void handle(Message<Buffer> message) {
            saveChunk(message);
        }
    });

}

From source file:com.mattinsler.guiceymongo.guice.spi.DBProviderModule.java

License:Apache License

private Mongo getConnection(String configuration, String databaseKey)
        throws MongoException, UnknownHostException {
    String connectionKey = getInstance(_injector,
            Key.get(String.class, AnnotationUtil.configuredDatabaseConnection(configuration, databaseKey)));
    if (connectionKey != null) {
        String hostname = getInstance(_injector,
                Key.get(String.class, AnnotationUtil.configuredConnectionHostname(connectionKey)));
        Integer port = getInstance(_injector,
                Key.get(int.class, AnnotationUtil.configuredConnectionPort(connectionKey)));
        List<ServerAddress> seeds = getInstance(_injector,
                Key.get(List.class, AnnotationUtil.configuredConnectionSeeds(connectionKey)));
        ReadPreference readPreference = getInstance(_injector, Key.get(ReadPreference.class,
                AnnotationUtil.configuredConnectionReadPreference(connectionKey)));

        if (seeds != null) {
            if (readPreference == null) {
                return new MongoClient(seeds);
            } else {
                MongoClientOptions options = new MongoClientOptions.Builder().readPreference(readPreference)
                        .build();//from   w  w  w  . j  av a 2 s .  co m
                return new MongoClient(seeds, options);
            }
        } else {
            if (hostname == null) {
                hostname = "localhost";
            }

            if (port == null) {
                return new MongoClient(hostname);
            } else {
                return new MongoClient(hostname, port.intValue());
            }
        }
    }
    return new MongoClient();
}

From source file:com.socialsky.mods.MongoPersistor.java

License:Apache License

@Override
public void start() {
    super.start();

    address = getOptionalStringConfig("address", "vertx.mongopersistor");

    host = getOptionalStringConfig("host", "localhost");
    port = getOptionalIntConfig("port", 27017);
    dbName = getOptionalStringConfig("db_name", "default_db");
    username = getOptionalStringConfig("username", null);
    password = getOptionalStringConfig("password", null);
    readPreference = ReadPreference.valueOf(getOptionalStringConfig("read_preference", "primary"));
    int poolSize = getOptionalIntConfig("pool_size", 10);
    autoConnectRetry = getOptionalBooleanConfig("auto_connect_retry", true);
    socketTimeout = getOptionalIntConfig("socket_timeout", 60000);
    useSSL = getOptionalBooleanConfig("use_ssl", false);

    JsonArray seedsProperty = config.getArray("seeds");

    try {//from  www . j a  va 2 s  .c om
        MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
        builder.connectionsPerHost(poolSize);
        builder.autoConnectRetry(autoConnectRetry);
        builder.socketTimeout(socketTimeout);
        builder.readPreference(readPreference);

        if (useSSL) {
            builder.socketFactory(SSLSocketFactory.getDefault());
        }

        if (seedsProperty == null) {
            ServerAddress address = new ServerAddress(host, port);
            mongo = new MongoClient(address, builder.build());
        } else {
            List<ServerAddress> seeds = makeSeeds(seedsProperty);
            mongo = new MongoClient(seeds, builder.build());
        }

        db = mongo.getDB(dbName);
        if (username != null && password != null) {
            db.authenticate(username, password.toCharArray());
        }
    } catch (UnknownHostException e) {
        logger.error("Failed to connect to mongo server", e);
    }
    eb.registerHandler(address, this);
}

From source file:fr.eolya.utils.nosql.mongodb.MongoDBConnection.java

License:Apache License

/**
 * @param hostName         The MongoDB server host name
 * @param hostPort         The MongoDB server host port
 * @return//from   w  ww.  ja va2  s .  c  o  m
 * @throws UnknownHostException 
 */
public MongoDBConnection(String hostName, int hostPort, String userName, String userPassword)
        throws UnknownHostException {

    MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
    builder.autoConnectRetry(true);
    builder.socketKeepAlive(true);
    builder.writeConcern(WriteConcern.SAFE);

    if ("".equals(hostName))
        hostName = "localhost";
    if (hostPort > 0) {
        ServerAddress addr = new ServerAddress(hostName, hostPort);
        m = new MongoClient(addr, builder.build());
    } else {
        m = new MongoClient(hostName, builder.build());
    }
    this.hostName = hostName;
    this.hostPort = hostPort;
}

From source file:fr.wseduc.gridfs.GridFSPersistor.java

License:Apache License

public void start() {
    super.start();

    address = getOptionalStringConfig("address", "vertx.gridfspersistor");

    host = getOptionalStringConfig("host", "localhost");
    port = getOptionalIntConfig("port", 27017);
    dbName = getOptionalStringConfig("db_name", "default_db");
    username = getOptionalStringConfig("username", null);
    password = getOptionalStringConfig("password", null);
    ReadPreference readPreference = ReadPreference
            .valueOf(getOptionalStringConfig("read_preference", "primary"));
    int poolSize = getOptionalIntConfig("pool_size", 10);
    boolean autoConnectRetry = getOptionalBooleanConfig("auto_connect_retry", true);
    int socketTimeout = getOptionalIntConfig("socket_timeout", 60000);
    boolean useSSL = getOptionalBooleanConfig("use_ssl", false);
    JsonArray seedsProperty = config.getArray("seeds");
    bucket = getOptionalStringConfig("bucket", "fs");

    try {// www .  j av  a 2 s. com
        MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
        builder.connectionsPerHost(poolSize);
        builder.autoConnectRetry(autoConnectRetry);
        builder.socketTimeout(socketTimeout);
        builder.readPreference(readPreference);

        if (useSSL) {
            builder.socketFactory(SSLSocketFactory.getDefault());
        }

        if (seedsProperty == null) {
            ServerAddress address = new ServerAddress(host, port);
            mongo = new MongoClient(address, builder.build());
        } else {
            List<ServerAddress> seeds = makeSeeds(seedsProperty);
            mongo = new MongoClient(seeds, builder.build());
        }

        db = mongo.getDB(dbName);
        if (username != null && password != null) {
            db.authenticate(username, password.toCharArray());
        }
    } catch (UnknownHostException e) {
        logger.error("Failed to connect to mongo server", e);
    }
    eb.registerHandler(address, this);
    eb.registerHandler(address + ".json", new Handler<Message<JsonObject>>() {
        @Override
        public void handle(Message<JsonObject> message) {
            String action = message.body().getString("action", "");
            switch (action) {
            case "write":
                writeTo(message);
                break;
            default:
                sendError(message, "Invalid action");
            }
        }
    });
}

From source file:fr.wseduc.resizer.GridFsFileAccess.java

License:Apache License

public GridFsFileAccess(String host, int port, String dbName, String username, String password, int poolSize)
        throws UnknownHostException {
    MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
    builder.connectionsPerHost(poolSize);
    ServerAddress address = new ServerAddress(host, port);
    mongo = new MongoClient(address, builder.build());
    db = mongo.getDB(dbName);//from w w w. jav a  2s.c  o  m
    if (username != null && password != null) {
        db.authenticate(username, password.toCharArray());
    }
}

From source file:net.handle.server.MongoDBHandleStorage.java

License:Open Source License

/**
 * Initialize the MongoDB storage object with the given settings.
 *//*w ww  .java 2  s  .  co  m*/
public void init(StreamTable config) throws Exception {

    // load the MongoDB driver, if configured. Otherwise this will throw a class not found exception.
    if (config.containsKey(DRIVER_CLASS)) {
        Class.forName(String.valueOf(config.get(DRIVER_CLASS)));
    }

    // get the database URL and other connection parameters
    this.username = (String) config.get(LOGIN);
    this.passwd = (String) config.get(PASSWD);
    setDatabase((String) config.get(DATABASE_NAME));
    this.databaseURL = (StreamVector) config.get(URL);
    StreamVector indices = (StreamVector) config.get(COLLECTION_INDICES);
    if (indices == null) {
        indices = new StreamVector();
        indices.add("handle");
    }
    this.indices = indices.subList(0, indices.size());
    this.collection_nas = (String) config.get(COLLECTION_NAS);
    final String c_s = ((String) config.get(CASE_SENSITIVE, "no")).toLowerCase();
    this.case_sensitive = (c_s.equalsIgnoreCase("yes"));
    this.readOnly = config.getBoolean(READ_ONLY, false);
    if (mongo == null) {
        final MongoClientOptions.Builder builder = new MongoClientOptions.Builder()
                .description("Handle System driver " + getClass())
                .writeConcern(new WriteConcern(config.getInt(WRITECONCERN, 1)))
                .connectionsPerHost(config.getInt(CONNECTIONS_PER_HOST, 11))
                .readPreference(ReadPreference.nearest());

        this.mongo = new MongoDBSingleton((String[]) databaseURL.toArray(new String[databaseURL.size()]),
                builder.build()).getInstance();
        if (username != null && passwd != null) {
            final boolean authenticate = authenticate(database, username, passwd.toCharArray());
            if (!authenticate) {
                throw new HandleException(HandleException.UNABLE_TO_AUTHENTICATE, "Access denied.");
            }
        }
    }
}

From source file:org.apache.gora.mongodb.store.MongoStore.java

License:Apache License

/**
 * Retrieve a client connected to the MongoDB server to be used.
 *
 * @param servers/*from  www . j  a v a  2  s . c  o  m*/
 *          This value should specify the host:port (at least one) for
 *          connecting to remote MongoDB. Multiple values must be separated by
 *          coma.
 * @return a {@link Mongo} instance connected to the server
 * @throws UnknownHostException
 */
private MongoClient getClient(MongoStoreParameters params) throws UnknownHostException {
    // Configure options
    MongoClientOptions.Builder optBuilder = new MongoClientOptions.Builder()
            .dbEncoderFactory(GoraDBEncoder.FACTORY); // Utf8 serialization!
    if (params.getReadPreference() != null) {
        optBuilder.readPreference(ReadPreference.valueOf(params.getReadPreference()));
    }
    if (params.getWriteConcern() != null) {
        optBuilder.writeConcern(WriteConcern.valueOf(params.getWriteConcern()));
    }
    // If configuration contains a login + secret, try to authenticated with DB
    List<MongoCredential> credentials = null;
    if (params.getLogin() != null && params.getSecret() != null) {
        credentials = new ArrayList<MongoCredential>();
        credentials.add(MongoCredential.createCredential(params.getLogin(), params.getDbname(),
                params.getSecret().toCharArray()));
    }
    // Build server address
    List<ServerAddress> addrs = new ArrayList<ServerAddress>();
    Iterable<String> serversArray = Splitter.on(",").split(params.getServers());
    if (serversArray != null) {
        for (String server : serversArray) {
            Iterator<String> paramsIterator = Splitter.on(":").trimResults().split(server).iterator();
            if (!paramsIterator.hasNext()) {
                // No server, use default
                addrs.add(new ServerAddress());
            } else {
                String host = paramsIterator.next();
                if (paramsIterator.hasNext()) {
                    String port = paramsIterator.next();
                    addrs.add(new ServerAddress(host, Integer.parseInt(port)));
                } else {
                    addrs.add(new ServerAddress(host));
                }
            }
        }
    }
    // Connect to the Mongo server
    return new MongoClient(addrs, credentials, optBuilder.build());
}