List of usage examples for com.mongodb ServerAddress ServerAddress
public ServerAddress(@Nullable final String host, final int port)
From source file:com.buzz.buzzdata.MongoBuzz.java
public MongoBuzz(String host, int port, String db, String userName, String passwd) throws UnknownHostException { MongoCredential credential = MongoCredential.createMongoCRCredential(userName, db, passwd.toCharArray()); mongoClient = new MongoClient(new ServerAddress(host, port), Arrays.asList(credential)); mongoDB = mongoClient.getDB(db);//from w ww . ja va 2 s . c o m }
From source file:com.ca.apm.mongo.Collector.java
License:Open Source License
private MongoClient setupDbClient(final String dbHost, final int dbPort) { final boolean useSSL = getBooleanProp(USE_SSL_PROP); final String clientTrustStore = getOptionalStringProp(SSL_CLIENT_TRUST_STORE_FILE_PROP); final String clientPasswd = getOptionalStringProp(SSL_CLIENT_TRUST_STORE_PASSWD_PROP); try {/* w w w. j a va2s . c om*/ MongoClientOptions.Builder builder = new MongoClientOptions.Builder(); if (useSSL) { System.setProperty(SSL_CLIENT_TRUST_STORE_FILE_PROP, clientTrustStore); System.setProperty(SSL_CLIENT_TRUST_STORE_PASSWD_PROP, clientPasswd); builder = builder.socketFactory(SSLSocketFactory.getDefault()); } final MongoClientOptions options = builder.build(); return new MongoClient(new ServerAddress(dbHost, dbPort), mongoCreds, options); } catch (Exception ex) { throw new RuntimeException("Can't initialize mongo client", ex); } }
From source file:com.ca.apm.mongo.test.MongoReplicaSetForTestFactory.java
License:Open Source License
private void initializeReplicaSet(Entry<String, List<IMongodConfig>> entry) throws Exception { String replicaName = entry.getKey(); List<IMongodConfig> mongoConfigList = entry.getValue(); if (mongoConfigList.size() < 3) { throw new Exception("A replica set must contain at least 3 members."); }// w w w . j a va 2 s.c o m // Create 3 mongod processes for (IMongodConfig mongoConfig : mongoConfigList) { if (!mongoConfig.replication().getReplSetName().equals(replicaName)) { throw new Exception("Replica set name must match in mongo configuration"); } MongodStarter starter = MongodStarter.getDefaultInstance(); MongodExecutable mongodExe = starter.prepare(mongoConfig); MongodProcess process = mongodExe.start(); mongodProcessList.add(process); } Thread.sleep(1000); MongoClientOptions mo = MongoClientOptions.builder().autoConnectRetry(true).build(); MongoClient mongo = new MongoClient( new ServerAddress(mongoConfigList.get(0).net().getServerAddress().getHostName(), mongoConfigList.get(0).net().getPort()), mo); DB mongoAdminDB = mongo.getDB(ADMIN_DATABASE_NAME); CommandResult cr = mongoAdminDB.command(new BasicDBObject("isMaster", 1)); logger.info("isMaster: " + cr); // Build BSON object replica set settings DBObject replicaSetSetting = new BasicDBObject(); replicaSetSetting.put("_id", replicaName); BasicDBList members = new BasicDBList(); int i = 0; for (IMongodConfig mongoConfig : mongoConfigList) { DBObject host = new BasicDBObject(); host.put("_id", i++); host.put("host", mongoConfig.net().getServerAddress().getHostName() + ":" + mongoConfig.net().getPort()); members.add(host); } replicaSetSetting.put("members", members); logger.info(replicaSetSetting.toString()); // Initialize replica set cr = mongoAdminDB.command(new BasicDBObject("replSetInitiate", replicaSetSetting)); logger.info("replSetInitiate: " + cr); Thread.sleep(5000); cr = mongoAdminDB.command(new BasicDBObject("replSetGetStatus", 1)); logger.info("replSetGetStatus: " + cr); // Check replica set status before to proceed while (!isReplicaSetStarted(cr)) { logger.info("Waiting for 3 seconds..."); Thread.sleep(1000); cr = mongoAdminDB.command(new BasicDBObject("replSetGetStatus", 1)); logger.info("replSetGetStatus: " + cr); } mongo.close(); mongo = null; }
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);//from ww w . ja v a 2s.co 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.callidusrobotics.droptables.configuration.MongoFactory.java
License:Open Source License
private MongoClient buildClient(Environment env, String username, String password) throws UnknownHostException { final MongoClient mongoClient; if (StringUtils.isBlank(username)) { mongoClient = new MongoClient(new ServerAddress(host, port)); } else {/*from w w w .j a v a2s . c o m*/ char[] passwordChars = password == null ? new char[0] : password.toCharArray(); mongoClient = new MongoClient(new ServerAddress(host, port), Arrays.asList(MongoCredential.createCredential(username, dbName, passwordChars))); } env.lifecycle().manage(new Managed() { @Override public void start() throws Exception { } @Override public void stop() throws Exception { mongoClient.close(); } }); return mongoClient; }
From source file:com.ccoe.build.alerts.connector.Connector.java
License:Apache License
public static DB connectDB(List<String> location, int port, String dbname) { try {/*w w w . j ava 2s . c om*/ List<ServerAddress> serverAddressList = new ArrayList<ServerAddress>(); ServerAddress serverAddress = null; for (String loc : location) { serverAddress = new ServerAddress(loc, port); serverAddressList.add(serverAddress); } Mongo mongo = new Mongo(serverAddressList); DB db = mongo.getDB(dbname); return db; } catch (UnknownHostException e) { e.printStackTrace(); } catch (MongoException e) { e.printStackTrace(); } return null; }
From source file:com.centurylink.mdw.dataaccess.DatabaseAccess.java
License:Apache License
private static synchronized void openMongoDbClient() { if (mongoClient == null) { String mongoHost = PropertyManager.getProperty(PropertyNames.MDW_MONGODB_HOST); int mongoPort = PropertyManager.getIntegerProperty(PropertyNames.MDW_MONGODB_PORT, 27017); int maxConnections = PropertyManager.getIntegerProperty(PropertyNames.MDW_MONGODB_POOLSIZE, PropertyManager.getIntegerProperty(PropertyNames.MDW_DB_POOLSIZE, 100)); MongoClientOptions.Builder options = MongoClientOptions.builder(); options.socketKeepAlive(true);//from w w w . j a va2 s. c o m if (maxConnections > 100) // MongoClient default is 100 max connections per host options.connectionsPerHost(maxConnections); mongoClient = new MongoClient(new ServerAddress(mongoHost, mongoPort), options.build()); LoggerUtil.getStandardLogger().info(mongoClient.getMongoClientOptions().toString()); } }
From source file:com.centurylink.mdw.mongo.MongoDocumentDb.java
License:Apache License
@Override public void initializeDbClient() { if (mongoClient == null) { MongoClientOptions.Builder options = MongoClientOptions.builder(); if (maxConnections > 100) // MongoClient default is 100 max connections per host options.connectionsPerHost(maxConnections); mongoClient = new MongoClient(new ServerAddress(dbHost, dbPort), options.build()); for (String name : mongoClient.getDatabase("mdw").listCollectionNames()) { createMongoDocIdIndex(name); }// w w w .jav a 2 s. co m LoggerUtil.getStandardLogger().info(mongoClient.getMongoClientOptions().toString()); } }
From source file:com.cyslab.craftvm.rest.mongo.MongoDB.java
License:GNU General Public License
private static List<ServerAddress> str2addresses(String servers) throws UnknownHostException { List<ServerAddress> list = new ArrayList<ServerAddress>(); servers = servers.trim();// w ww . j av a2s .c om String ar[] = servers.split("[,]"); for (String s : ar) { s = s.trim(); String ar2[] = s.split("[:]"); if (ar2 == null || ar2.length != 2) throw new IllegalArgumentException("mongo server must be <server:port>"); int port = 27017; try { port = Integer.parseInt(ar2[1]); } catch (NumberFormatException e) { log.warn("Can not parse port for " + ar[0]); } ServerAddress adr = new ServerAddress(ar2[0], port); list.add(adr); } return list; }
From source file:com.daprota.m2.realm.MongoDBRealm.java
License:Apache License
/** * Open (if necessary) and return a database connection for use by * this Realm.//from w w w . j av a 2 s . c om * * @exception M2Exception if a database error occurs */ protected DbConnection open() { if (!((connectionURL.substring(0, 7)).equals("mongodb"))) { containerLog.error(sm.getString("MongoDBRealm.exception: connectionURL not properly set up")); } String dbName = null; String connectionURL2 = connectionURL.substring(10); if (connectionURL2.indexOf(',') == -1) { if (connectionURL2.indexOf("/") == -1) { containerLog.error("M2 ConnectionManager cannot be initialized. Database name is not provide."); } else { String host = connectionURL2.substring(0, connectionURL2.indexOf(":")); String port = connectionURL2.substring(connectionURL2.indexOf(":") + 1, connectionURL2.indexOf("/")); dbName = connectionURL2.substring(connectionURL2.indexOf("/") + 1); try { MongoClient mongoClient = new MongoClient(host, Integer.parseInt(port)); return (new DbConnection(mongoClient, dbName)); } catch (UnknownHostException e) { containerLog.error(sm.getString("MongoDBRealm.exception"), e); } } } else { String[] hostArray = null; if (connectionURL2.indexOf('/') == -1) { containerLog.error("M2 ConnectionManager cannot be initialized. Database name is not provide."); } else { dbName = connectionURL2.substring(connectionURL2.indexOf("/") + 1); String hostString = connectionURL2.substring(0, connectionURL2.indexOf('/')); hostArray = hostString.split(","); } int length = hostArray.length; int idx = 0; List<ServerAddress> saList = new ArrayList<ServerAddress>(); try { while (idx < length) { String host = hostArray[idx].substring(0, hostArray[idx].indexOf(':')); String port = hostArray[idx].substring(hostArray[idx].indexOf(':') + 1); saList.add(new ServerAddress(host, Integer.parseInt(port))); ++idx; } MongoClient mongoClient = new MongoClient(saList); return (new DbConnection(mongoClient, dbName)); } catch (MongoException e) { containerLog.error(sm.getString("MongoDBRealm.exception"), e); } catch (UnknownHostException e) { containerLog.error(sm.getString("MongoDBRealm.exception"), e); } } return null; }