List of usage examples for com.mongodb MongoClientOptions builder
public static Builder builder()
From source file:com.github.nlloyd.hornofmongo.adaptor.Mongo.java
License:Open Source License
private void initMongoConnection() throws UnknownHostException { if ((innerMongo == null)) { MongoClientOptions.Builder builder = MongoClientOptions.builder(); if (mongoOptions != null) { //Restore previous options builder.description(mongoOptions.description); builder.connectionsPerHost(mongoOptions.connectionsPerHost); builder.threadsAllowedToBlockForConnectionMultiplier( mongoOptions.threadsAllowedToBlockForConnectionMultiplier); builder.maxWaitTime(mongoOptions.maxWaitTime); builder.connectTimeout(mongoOptions.connectTimeout); builder.socketTimeout(mongoOptions.socketTimeout); builder.socketKeepAlive(mongoOptions.socketKeepAlive); }//from ww w . j ava2s .c o m MongoClientOptions clientOptions = builder.dbEncoderFactory(HornOfMongoBSONEncoder.FACTORY).build(); this.innerMongo = new com.mongodb.MongoClient(this.hosts, clientOptions); if (options != 0) this.innerMongo.setOptions(options); } if (mongoScope.useMongoShellWriteConcern()) innerMongo.setWriteConcern(WriteConcern.UNACKNOWLEDGED); }
From source file:com.hurence.logisland.service.mongodb.AbstractMongoDBControllerService.java
License:Apache License
protected Builder getClientOptions(final SSLContext sslContext) { MongoClientOptions.Builder builder = MongoClientOptions.builder(); builder.sslEnabled(true);//from w w w .j a va2s .c om builder.socketFactory(sslContext.getSocketFactory()); return builder; }
From source file:com.impetus.client.mongodb.MongoDBClientFactory.java
License:Apache License
/** * On set mongo server properties.// www . j av a2 s. co m * * @param contactNode * the contact node * @param defaultPort * the default port * @param poolSize * the pool size * @param addrs * the addrs * @return the mongo client * @throws UnknownHostException * the unknown host exception */ private MongoClient onSetMongoServerProperties(String contactNode, String defaultPort, String poolSize, List<ServerAddress> addrs) throws UnknownHostException { MongoClient mongo = null; MongoClientOptions mo = null; MongoDBSchemaMetadata metadata = MongoDBPropertyReader.msmd; ClientProperties cp = metadata != null ? metadata.getClientProperties() : null; Properties propsFromCp = null; if (cp != null) { DataStore dataStore = metadata != null ? metadata.getDataStore() : null; List<Server> servers = dataStore != null && dataStore.getConnection() != null ? dataStore.getConnection().getServers() : null; if (servers != null && !servers.isEmpty()) { for (Server server : servers) { addrs.add( new ServerAddress(server.getHost().trim(), Integer.parseInt(server.getPort().trim()))); } } propsFromCp = dataStore != null && dataStore.getConnection() != null ? dataStore.getConnection().getProperties() : null; } else { for (String node : contactNode.split(Constants.COMMA)) { if (StringUtils.countMatches(node, Constants.COLON) == 1) { // node is given with hostname and port // count == 1 is to exclude IPv6 addresses String host = node.split(":")[0]; int port = Integer.parseInt(node.split(Constants.COLON)[1]); addrs.add(new ServerAddress(host.trim(), port)); } else { addrs.add(new ServerAddress(node.trim(), Integer.parseInt(defaultPort.trim()))); } } } MongoClientOptions.Builder b = new PopulateMongoOptions(propsFromCp, externalProperties).prepareBuilder(); mo = b.build(); if (mo.getConnectionsPerHost() <= 0 && !StringUtils.isEmpty(poolSize)) { mo = b.connectionsPerHost(Integer.parseInt(poolSize)).build(); } mongo = new MongoClient(addrs, mo); return mongo; }
From source file:com.jim.im.config.GenericMongoConfig.java
License:Open Source License
@Bean @ConditionalOnMissingBean public MongoClientOptions mongoClientOptions() { return MongoClientOptions.builder().build(); }
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 ww . j a va2 s. c o 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.meltmedia.dropwizard.mongo.MongoBundle.java
License:Apache License
MongoClient buildClient(MongoConfiguration configuration) { try {//from ww w. j av a 2 s .c o m // build the seed server list. List<ServerAddress> servers = new ArrayList<>(); for (Server seed : configuration.getSeeds()) { servers.add(new ServerAddress(seed.getHost(), seed.getPort())); } log.info("Found {} mongo seed servers", servers.size()); for (ServerAddress server : servers) { log.info("Found mongo seed server {}:{}", server.getHost(), server.getPort()); } // build the credentials Credentials credentialConfig = configuration.getCredentials(); List<MongoCredential> credentials = credentialConfig == null ? Collections.<MongoCredential>emptyList() : Collections.singletonList(MongoCredential.createCredential(credentialConfig.getUserName(), configuration.getDatabase(), credentialConfig.getPassword().toCharArray())); if (credentials.isEmpty()) { log.info("Found {} mongo credentials.", credentials.size()); } else { for (MongoCredential credential : credentials) { log.info("Found mongo credential for {} on database {}.", credential.getUserName(), credential.getSource()); } } // build the options. MongoClientOptions options = new MongoClientOptions.Builder() .writeConcern(writeConcern(configuration.getWriteConcern())).build(); log.info("Mongo database is {}", configuration.getDatabase()); return new MongoClient(servers, credentials, options); } catch (Exception e) { throw new RuntimeException("Could not configure MongoDB client.", e); } }
From source file:com.novemberain.quartz.mongodb.MongoDBJobStore.java
License:Open Source License
private Mongo connectToMongoDB() throws SchedulerConfigException { if (mongoUri != null) { return connectToMongoDB(mongoUri); }// w ww. java 2 s .com MongoClientOptions.Builder optionsBuilder = MongoClientOptions.builder(); optionsBuilder.writeConcern(WriteConcern.SAFE); if (mongoOptionAutoConnectRetry != null) optionsBuilder.autoConnectRetry(mongoOptionAutoConnectRetry); if (mongoOptionMaxConnectionsPerHost != null) optionsBuilder.connectionsPerHost(mongoOptionMaxConnectionsPerHost); if (mongoOptionConnectTimeoutMillis != null) optionsBuilder.connectTimeout(mongoOptionConnectTimeoutMillis); if (mongoOptionSocketTimeoutMillis != null) optionsBuilder.socketTimeout(mongoOptionSocketTimeoutMillis); if (mongoOptionSocketKeepAlive != null) optionsBuilder.socketKeepAlive(mongoOptionSocketKeepAlive); if (mongoOptionThreadsAllowedToBlockForConnectionMultiplier != null) optionsBuilder.threadsAllowedToBlockForConnectionMultiplier( mongoOptionThreadsAllowedToBlockForConnectionMultiplier); MongoClientOptions options = optionsBuilder.build(); try { ArrayList<ServerAddress> serverAddresses = new ArrayList<ServerAddress>(); for (String a : addresses) { serverAddresses.add(new ServerAddress(a)); } return new MongoClient(serverAddresses, options); } catch (UnknownHostException e) { throw new SchedulerConfigException("Could not connect to MongoDB", e); } catch (MongoException e) { throw new SchedulerConfigException("Could not connect to MongoDB", e); } }
From source file:com.ott.bookings.auth.form.impl.MongoTockenStore.java
License:Apache License
/** * Create the {@link MongoClient}./* ww w. java 2 s .co m*/ * */ private void getConnection() { try { /* create the client using the Mongo options */ ReadPreference readPreference = ReadPreference.primaryPreferred(); if (this.useSlaves) { readPreference = ReadPreference.secondaryPreferred(); } MongoClientOptions options = MongoClientOptions.builder().connectTimeout(connectionTimeoutMs) .maxWaitTime(connectionWaitTimeoutMs).connectionsPerHost(maxPoolSize).writeConcern(writeConcern) .readPreference(readPreference).build(); log.info("[Mongo Token Store]: Connecting to MongoDB [" + this.hostsString + "]"); /* connect */ this.mongoClient = new MongoClient(getServerAddresses(), options); /* get a connection to our db */ log.info("[Mongo Token Store]: Using Database [" + this.dbName + "]"); this.db = this.mongoClient.getDB(this.dbName); /* get a reference to the collection */ this.collection = this.db.getCollection(this.collectionName); log.info("[Mongo Token Store]: Store ready."); } catch (UnknownHostException uhe) { log.error("Unable to Connect to MongoDB", uhe); } catch (MongoException me) { log.error("Unable to Connect to MongoDB", me); } }
From source file:com.redhat.jielicious.storage.mongo.ThermostatMongoStorage.java
License:Open Source License
public static void start(Map<String, String> mongoConfiguration) { String username = null;/*from w ww .j a va 2s. co m*/ char[] password = null; String host = "127.0.0.1"; int port = 27518; int timeout = 1000; if (mongoConfiguration.containsKey(MongoConfiguration.MONGO_DB.toString())) { dbName = mongoConfiguration.get(MongoConfiguration.MONGO_DB.toString()); } if (mongoConfiguration.containsKey(MongoConfiguration.MONGO_USERNAME.toString())) { username = mongoConfiguration.get(MongoConfiguration.MONGO_USERNAME.toString()); } if (mongoConfiguration.containsKey(MongoConfiguration.MONGO_PASSWORD.toString())) { password = mongoConfiguration.get(MongoConfiguration.MONGO_PASSWORD.toString()).toCharArray(); } if (mongoConfiguration.containsKey(MongoConfiguration.MONGO_URL.toString())) { try { URI url = new URI(mongoConfiguration.get(MongoConfiguration.MONGO_URL.toString())); host = url.getHost(); port = url.getPort(); } catch (URISyntaxException e) { // Do nothing. Defaults will be used. } } if (mongoConfiguration.containsKey(MongoConfiguration.MONGO_SERVER_TIMEOUT.toString())) { timeout = Integer.valueOf(mongoConfiguration.get(MongoConfiguration.MONGO_SERVER_TIMEOUT.toString())); } ServerAddress address = new ServerAddress(host, port); if (username != null && password != null) { MongoCredential credential = MongoCredential.createCredential(username, dbName, password); mongoClient = new MongoClient(address, Collections.singletonList(credential), new MongoClientOptions.Builder().serverSelectionTimeout(timeout).connectTimeout(0) .socketTimeout(0).build()); } else { mongoClient = new MongoClient(address, new MongoClientOptions.Builder().serverSelectionTimeout(timeout) .connectTimeout(0).socketTimeout(0).build()); } Logger mongoLog = Logger.getLogger("org.mongodb.driver"); mongoLog.setLevel(Level.OFF); }
From source file:com.redhat.lightblue.mongo.config.metadata.MongoConfiguration.java
License:Open Source License
/** * Returns an options object with defaults overriden where there is a valid override. * * @return/* w w w. jav a 2 s . c o m*/ */ public MongoClientOptions getMongoClientOptions() { MongoClientOptions.Builder builder = MongoClientOptions.builder(); if (connectionsPerHost != null) { builder.connectionsPerHost(connectionsPerHost); } if (ssl != null && ssl.booleanValue()) { // taken from MongoClientURI, written this way so we don't have to construct a URI to connect builder.socketFactory(SSLSocketFactory.getDefault()); } return builder.build(); }