List of usage examples for com.mongodb MongoClientOptions.Builder readPreference
ReadPreference readPreference
To view the source code for com.mongodb MongoClientOptions.Builder readPreference.
Click Source Link
From source file:com.ebay.cloud.cms.mongo.MongoDataSource.java
License:Apache License
public MongoDataSource(String servers, int connectionsPerHost, ReadPreference readPreference, CMSDBConfig config) {// w w w. j a va 2s .co m this.addrs = parseServerString(servers); Collections.sort(addrs, new Comparator<ServerAddress>() { @Override public int compare(ServerAddress s1, ServerAddress s2) { int result = s1.getHost().compareTo(s2.getHost()); if (result != 0) { return result; } else { return s1.getPort() - s2.getPort(); } } }); MongoClientOptions.Builder builder = MongoClientOptions.builder(); builder.socketKeepAlive(false); builder.connectionsPerHost(connectionsPerHost); if (readPreference != null) { builder.readPreference(readPreference); } // set socket timeout if (config != null) { Integer socketTimeOut = (Integer) config.get(CMSDBConfig.MONGO_CONNECTION_SOCKET_TIMEOUT); builder.socketTimeout(socketTimeOut); } MongoClientOptions mongoOptions = builder.build(); this.mongo = new MongoClient(addrs, mongoOptions); }
From source file:com.edgytech.umongo.ConnectDialog.java
License:Apache License
MongoClientOptions getMongoClientOptions() { MongoClientOptions.Builder builder = MongoClientOptions.builder(); // moptions.connectionsPerHost = getIntFieldValue(Item.connectionsPerHost); // moptions.threadsAllowedToBlockForConnectionMultiplier = getIntFieldValue(Item.blockingThreadMultiplier); // moptions.maxWaitTime = getIntFieldValue(Item.maxWaitTime); builder.connectTimeout(getIntFieldValue(Item.connectTimeout)); builder.socketTimeout(getIntFieldValue(Item.socketTimeout)); // moptions.autoConnectRetry = getBooleanFieldValue(Item.autoConnectRetry); if (!getBooleanFieldValue(Item.safeWrites)) { builder.writeConcern(WriteConcern.NONE); }//w w w. j av a 2s. c om // moptions.slaveOk = getBooleanFieldValue(Item.secondaryReads); if (getBooleanFieldValue(Item.secondaryReads)) { builder.readPreference(ReadPreference.secondaryPreferred()); } int stype = getIntFieldValue(Item.socketType); int proxy = getIntFieldValue(Item.proxyType); if (proxy == 1) { // SOCKS proxy final String host = getStringFieldValue(Item.proxyHost); final int port = getIntFieldValue(Item.proxyPort); builder.socketFactory(new SocketFactory() { @Override public Socket createSocket() throws IOException { SocketAddress addr = new InetSocketAddress(host, port); Proxy proxy = new Proxy(Proxy.Type.SOCKS, addr); Socket socket = new Socket(proxy); return socket; } @Override public Socket createSocket(String string, int i) throws IOException, UnknownHostException { SocketAddress addr = new InetSocketAddress(host, port); Proxy proxy = new Proxy(Proxy.Type.SOCKS, addr); Socket socket = new Socket(proxy); InetSocketAddress dest = new InetSocketAddress(string, i); socket.connect(dest); return socket; } @Override public Socket createSocket(String string, int i, InetAddress ia, int i1) throws IOException, UnknownHostException { throw new UnsupportedOperationException("Not supported yet."); } @Override public Socket createSocket(InetAddress ia, int i) throws IOException { SocketAddress addr = new InetSocketAddress(host, port); Proxy proxy = new Proxy(Proxy.Type.SOCKS, addr); Socket socket = new Socket(proxy); InetSocketAddress dest = new InetSocketAddress(ia, i); socket.connect(dest); return socket; } @Override public Socket createSocket(InetAddress ia, int i, InetAddress ia1, int i1) throws IOException { throw new UnsupportedOperationException("Not supported yet."); } }); // // authentication.. only supports 1 global for all proxies :( // final String user = getStringFieldValue(Item.proxyUser); // final String pwd = getStringFieldValue(Item.proxyPassword); // if (!user.isEmpty()) { // Authenticator.setDefault(new Authenticator() { // @Override // protected PasswordAuthentication getPasswordAuthentication() { // PasswordAuthentication p = new PasswordAuthentication(user, pwd.toCharArray()); // return p; // } // }); // } } if (stype == 1) { builder.socketFactory(SSLSocketFactory.getDefault()); } else if (stype == 2) { // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) { } public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) { } } }; try { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); builder.socketFactory(sc.getSocketFactory()); } catch (Exception e) { } } return builder.build(); }
From source file:com.github.maasdi.mongo.wrapper.NoAuthMongoClientWrapper.java
License:Apache License
/** * Utility method to configure Mongo connection options * * @param optsBuilder/*from w w w.jav a 2s.c om*/ * an options builder * @param connTimeout * the connection timeout to use (can be null) * @param socketTimeout * the socket timeout to use (can be null) * @param readPreference * the read preference to use (can be null) * @param writeConcern * the writeConcern to use (can be null) * @param wTimeout * the w timeout to use (can be null) * @param journaled * whether to use journaled writes * @param tagSet * the tag set to use in conjunction with the read preference (can be null) * @param vars * variables to use * @param log * for logging * @throws KettleException * if a problem occurs */ private void configureConnectionOptions(MongoClientOptions.Builder optsBuilder, String connTimeout, String socketTimeout, String readPreference, String writeConcern, String wTimeout, boolean journaled, List<String> tagSet, VariableSpace vars, LogChannelInterface log) throws KettleException { // connection timeout if (!Const.isEmpty(connTimeout)) { String connS = vars.environmentSubstitute(connTimeout); try { int cTimeout = Integer.parseInt(connS); if (cTimeout > 0) { optsBuilder.connectTimeout(cTimeout); } } catch (NumberFormatException n) { throw new KettleException(n); } } // socket timeout if (!Const.isEmpty(socketTimeout)) { String sockS = vars.environmentSubstitute(socketTimeout); try { int sockTimeout = Integer.parseInt(sockS); if (sockTimeout > 0) { optsBuilder.socketTimeout(sockTimeout); } } catch (NumberFormatException n) { throw new KettleException(n); } } if (log != null) { String rpLogSetting = NamedReadPreference.PRIMARY.getName(); if (!Const.isEmpty(readPreference)) { rpLogSetting = readPreference; } log.logBasic( BaseMessages.getString(PKG, "MongoNoAuthWrapper.Message.UsingReadPreference", rpLogSetting)); //$NON-NLS-1$ } DBObject firstTagSet = null; DBObject[] remainingTagSets = new DBObject[0]; if (tagSet != null && tagSet.size() > 0) { if (tagSet.size() > 1) { remainingTagSets = new DBObject[tagSet.size() - 1]; } firstTagSet = (DBObject) JSON.parse(tagSet.get(0).trim()); for (int i = 1; i < tagSet.size(); i++) { remainingTagSets[i - 1] = (DBObject) JSON.parse(tagSet.get(i).trim()); } if (log != null && (!Const.isEmpty(readPreference) && !readPreference.equalsIgnoreCase(NamedReadPreference.PRIMARY.getName()))) { StringBuilder builder = new StringBuilder(); for (String s : tagSet) { builder.append(s).append(" "); //$NON-NLS-1$ } log.logBasic(BaseMessages.getString(PKG, "MongoNoAuthWrapper.Message.UsingReadPreferenceTagSets", //$NON-NLS-1$ builder.toString())); } } else { if (log != null) { log.logBasic( BaseMessages.getString(PKG, "MongoNoAuthWrapper.Message.NoReadPreferenceTagSetsDefined")); //$NON-NLS-1$ } } // read preference if (!Const.isEmpty(readPreference)) { String rp = vars.environmentSubstitute(readPreference); NamedReadPreference preference = NamedReadPreference.byName(rp); if ((firstTagSet != null) && (preference.getPreference() instanceof TaggableReadPreference)) { optsBuilder.readPreference(preference.getTaggableReadPreference(firstTagSet, remainingTagSets)); } else { optsBuilder.readPreference(preference.getPreference()); } } // write concern writeConcern = vars.environmentSubstitute(writeConcern); wTimeout = vars.environmentSubstitute(wTimeout); WriteConcern concern = null; if (Const.isEmpty(writeConcern) && Const.isEmpty(wTimeout) && !journaled) { // all defaults - timeout 0, journal = false, w = 1 concern = new WriteConcern(); concern.setWObject(new Integer(1)); if (log != null) { log.logBasic(BaseMessages.getString(PKG, "MongoNoAuthWrapper.Message.ConfiguringWithDefaultWriteConcern")); //$NON-NLS-1$ } } else { int wt = 0; if (!Const.isEmpty(wTimeout)) { try { wt = Integer.parseInt(wTimeout); } catch (NumberFormatException n) { throw new KettleException(n); } } if (!Const.isEmpty(writeConcern)) { // try parsing as a number first try { int wc = Integer.parseInt(writeConcern); concern = new WriteConcern(wc, wt, false, journaled); } catch (NumberFormatException n) { // assume its a valid string - e.g. "majority" or a custom // getLastError label associated with a tag set concern = new WriteConcern(writeConcern, wt, false, journaled); } } else { concern = new WriteConcern(1, wt, false, journaled); } if (log != null) { String lwc = "w = " + concern.getW() + ", wTimeout = " + concern.getWtimeout() + ", journaled = " + concern.getJ(); log.logBasic( BaseMessages.getString(PKG, "MongoNoAuthWrapper.Message.ConfiguringWithWriteConcern", lwc)); } } optsBuilder.writeConcern(concern); }
From source file:com.ricardolorenzo.identity.user.impl.UserIdentityManagerMongoDB.java
License:Open Source License
public UserIdentityManagerMongoDB(final Properties conf) throws UnknownHostException { this.properties = conf; this.databaseUsers = new Boolean(this.properties.getProperty("mongodb.databaseUsers", "true")); WriteConcern writeConcern = WriteConcern.MAJORITY; String writeConcernType = conf.getProperty("mongodb.writeConcern", "majority").toLowerCase(); if ("majority".equals(writeConcernType)) { writeConcern = WriteConcern.UNACKNOWLEDGED; } else if ("unacknowledged".equals(writeConcernType)) { writeConcern = WriteConcern.UNACKNOWLEDGED; } else if ("acknowledged".equals(writeConcernType)) { writeConcern = WriteConcern.ACKNOWLEDGED; } else if ("journaled".equals(writeConcernType)) { writeConcern = WriteConcern.JOURNALED; } else if ("replica_acknowledged".equals(writeConcernType)) { writeConcern = WriteConcern.REPLICA_ACKNOWLEDGED; }/*from w w w . j av a2 s .co m*/ ReadPreference readPreference = null; String readPreferenceType = conf.getProperty("mongodb.readPreference", "primary").toLowerCase(); if ("primary".equals(readPreferenceType)) { readPreference = ReadPreference.primary(); } else if ("primary_preferred".equals(readPreferenceType)) { readPreference = ReadPreference.primaryPreferred(); } else if ("secondary".equals(readPreferenceType)) { readPreference = ReadPreference.secondary(); } else if ("secondary_preferred".equals(readPreferenceType)) { readPreference = ReadPreference.secondaryPreferred(); } else if ("nearest".equals(readPreferenceType)) { readPreference = ReadPreference.nearest(); } MongoClientOptions.Builder options = MongoClientOptions.builder(); options.writeConcern(writeConcern); options.readPreference(readPreference); try { options.connectionsPerHost(Integer.parseInt(conf.getProperty("mongodb.threads", "100"))); } catch (NumberFormatException e) { options.connectionsPerHost(100); } MongoClientURI mongoClientURI = new MongoClientURI( conf.getProperty("mongodb.url", "mongodb://localhost:27017"), options); if (!this.properties.containsKey("mongodb.database")) { if (mongoClientURI.getDatabase() != null && !mongoClientURI.getDatabase().isEmpty()) { this.properties.setProperty("mongodb.database", mongoClientURI.getDatabase()); } else { this.properties.setProperty("mongodb.database", DEFAULT_DATABASE); } } mongoClient = new MongoClient(mongoClientURI); }
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 w w w . j a v a 2 s . c o m 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:com.streamsets.pipeline.stage.common.mongodb.MongoDBConfig.java
License:Apache License
private MongoClient createClient(Stage.Context context, List<Stage.ConfigIssue> issues, ReadPreference readPreference, WriteConcern writeConcern) { MongoClientOptions.Builder optionBuilder = new MongoClientOptions.Builder() .connectionsPerHost(connectionsPerHost).connectTimeout(connectTimeout) .cursorFinalizerEnabled(cursorFinalizerEnabled).heartbeatConnectTimeout(heartbeatConnectTimeout) .heartbeatFrequency(heartbeatFrequency).heartbeatSocketTimeout(heartbeatSocketTimeout) .localThreshold(localThreshold).maxConnectionIdleTime(maxConnectionIdleTime) .maxConnectionLifeTime(maxConnectionLifeTime).maxWaitTime(maxWaitTime) .minConnectionsPerHost(minConnectionsPerHost).minHeartbeatFrequency(minHeartbeatFrequency) .serverSelectionTimeout(serverSelectionTimeout).socketKeepAlive(socketKeepAlive) .socketTimeout(socketTimeout).sslEnabled(sslEnabled) .sslInvalidHostNameAllowed(sslInvalidHostNameAllowed) .threadsAllowedToBlockForConnectionMultiplier(threadsAllowedToBlockForConnectionMultiplier); // the default value of requiredReplicaSetName is null, so it should be set only if a non-empty string is provided if (!requiredReplicaSetName.isEmpty()) { optionBuilder = optionBuilder.requiredReplicaSetName(requiredReplicaSetName); }//from w ww .j av a2s .co m // read preference is only set by the source if (readPreference != null) { optionBuilder = optionBuilder.readPreference(readPreference); } // write concern is only set by the target if (writeConcern != null) { optionBuilder = optionBuilder.writeConcern(writeConcern); } MongoClientURI mongoURI; List<ServerAddress> servers = new ArrayList<>(); try { mongoURI = new MongoClientURI(connectionString, optionBuilder); } catch (IllegalArgumentException e) { issues.add(context.createConfigIssue(Groups.MONGODB.name(), MONGO_CONFIG_PREFIX + "connectionString", Errors.MONGODB_00, e.toString())); return null; } validateServerList(context, mongoURI.getHosts(), servers, issues); if (!issues.isEmpty()) { return null; } MongoClient mongoClient = null; List<MongoCredential> credentials; try { credentials = createCredentials(); } catch (StageException ex) { issues.add(context.createConfigIssue(Groups.MONGODB.name(), MONGO_CONFIG_PREFIX + "connectionString", Errors.MONGODB_34, ex.toString())); return null; } if (credentials.isEmpty()) { Optional.ofNullable(mongoURI.getCredentials()).ifPresent(credentials::add); } try { if (isSingleMode) { mongoClient = new MongoClient(servers.get(0), credentials, mongoURI.getOptions()); } else { mongoClient = new MongoClient(servers, credentials, mongoURI.getOptions()); } } catch (MongoException e) { issues.add(context.createConfigIssue(Groups.MONGODB.name(), MONGO_CONFIG_PREFIX + "connectionString", Errors.MONGODB_01, e.toString())); } return mongoClient; }
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 {/*from www . ja v a 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); 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:org.apache.gora.mongodb.store.MongoStore.java
License:Apache License
/** * Retrieve a client connected to the MongoDB server to be used. * * @param servers//from w w w .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()); }
From source file:org.craftercms.commons.mongo.MongoClientOptionsFactory.java
License:Open Source License
@Override protected MongoClientOptions createInstance() throws Exception { MongoClientOptions.Builder builder = MongoClientOptions.builder(); builder.alwaysUseMBeans(this.alwaysUseMBeans); builder.connectionsPerHost(this.connectionsPerHost); builder.cursorFinalizerEnabled(this.cursorFinalizerEnabled); builder.connectTimeout(this.connectTimeout); builder.maxWaitTime(this.maxWaitTime); switch (this.readPreference) { case PRIMARY_READ_PREFERENCE: builder.readPreference(ReadPreference.primary()); break;//from w w w. ja v a 2 s .c o m case NEAREST_READ_PREFERENCE: builder.readPreference(ReadPreference.nearest()); break; case SECONDARY_READ_PREFERENCE: builder.readPreference(ReadPreference.secondary()); break; default: builder.readPreference(ReadPreference.primary()); break; } builder.writeConcern(WriteConcern.valueOf(this.writeConcern)); builder.threadsAllowedToBlockForConnectionMultiplier(this.threadsAllowedToBlockForConnectionMultiplier); return builder.build(); }
From source file:org.craftercms.studio.impl.repository.mongodb.data.ClientOptionsFactory.java
License:Open Source License
public void init() { MongoClientOptions.Builder builder = MongoClientOptions.builder(); builder.alwaysUseMBeans(this.alwaysUseMBeans); builder.autoConnectRetry(this.autoConnectRetry); builder.connectionsPerHost(this.connectionsPerHost); builder.cursorFinalizerEnabled(this.cursorFinalizerEnabled); builder.connectTimeout(this.connectTimeout); builder.maxAutoConnectRetryTime(this.maxAutoConnectRetryTime); builder.maxWaitTime(this.maxWaitTime); switch (this.readPreference) { case PRIMARY_READ_PREFERENCE: builder.readPreference(ReadPreference.primary()); break;/*from ww w. j a v a2s. co m*/ case NEAREST_READ_PREFERENCE: builder.readPreference(ReadPreference.nearest()); break; case SECONDARY_READ_PREFERENCE: builder.readPreference(ReadPreference.secondary()); break; default: builder.readPreference(ReadPreference.primary()); break; } builder.socketKeepAlive(this.socketKeepAlive); builder.writeConcern(WriteConcern.valueOf(this.writeConcern)); builder.threadsAllowedToBlockForConnectionMultiplier(this.threadsAllowedToBlockForConnectionMultiplier); this.clientOptions = builder.build(); }