List of usage examples for com.mongodb ServerAddress ServerAddress
public ServerAddress()
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 2s .c om*/ * 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.apache.tapestry5.internal.mongodb.MongoDBSourceImpl.java
License:Apache License
public MongoDBSourceImpl(Logger logger, @Symbol(MongoDBSymbols.CONNECTIONS_PER_HOSTS) int connectionPerHost, @Symbol(MongoDBSymbols.READ_PREFERENCE) ReadPreference readPreference, @Symbol(MongoDBSymbols.WRITE_CONCERN) WriteConcern writeConcern, List<ServerAddress> serverAddresses) { this.logger = logger; MongoClientOptions options = new MongoClientOptions.Builder().connectionsPerHost(connectionPerHost) .writeConcern(writeConcern).readPreference(readPreference).build(); if (serverAddresses.isEmpty()) { try {/*from w ww . j a v a 2s. c o m*/ mongoClient = new MongoClient(new ServerAddress(), options); } catch (UnknownHostException uhe) { throw new RuntimeException(uhe); } } else { mongoClient = new MongoClient(serverAddresses, options); } }
From source file:org.axonframework.eventsourcing.eventstore.mongo.MongoFactory.java
License:Apache License
/** * Creates a mongo instance based on the provided configuration. Read javadoc of the class to learn about the * configuration options. A new Mongo instance is created each time this method is called. * * @return a new Mongo instance each time this method is called. *//*w ww . ja v a2 s. com*/ public Mongo createMongo() { Mongo mongo; if (mongoAddresses.isEmpty()) { try { mongo = new Mongo(new ServerAddress(), mongoOptions); } catch (UnknownHostException e) { throw new IllegalStateException( String.format("No addresses were provided, but could not find IP for default host: %s", ServerAddress.defaultHost()), e); } } else { mongo = new Mongo(mongoAddresses, mongoOptions); } mongo.setWriteConcern(defaultWriteConcern()); return mongo; }
From source file:org.axonframework.mongo.eventsourcing.eventstore.MongoFactory.java
License:Apache License
/** * Creates a mongo instance based on the provided configuration. Read javadoc of the class to learn about the * configuration options. A new Mongo instance is created each time this method is called. * * @return a new Mongo instance each time this method is called. *//* w ww . jav a 2s . c o m*/ public MongoClient createMongo() { MongoClient mongo; if (mongoAddresses.isEmpty()) { mongo = new MongoClient(new ServerAddress(), mongoOptions); } else { mongo = new MongoClient(mongoAddresses, mongoOptions); } mongo.setWriteConcern(defaultWriteConcern()); return mongo; }
From source file:org.datanucleus.store.mongodb.ConnectionFactoryImpl.java
License:Open Source License
/** * Constructor.//from ww w . ja v a 2 s. c o m * @param storeMgr Store Manager * @param resourceType Type of resource (tx, nontx) */ public ConnectionFactoryImpl(StoreManager storeMgr, String resourceType) { super(storeMgr, resourceType); // "mongodb:[server]" String url = storeMgr.getConnectionURL(); if (url == null) { throw new NucleusException( "You haven't specified persistence property 'datanucleus.ConnectionURL' (or alias)"); } String remains = url.substring(7).trim(); if (remains.indexOf(':') == 0) { remains = remains.substring(1); } // Split into any replica sets try { List<ServerAddress> serverAddrs = new ArrayList<ServerAddress>(); if (remains.length() == 0) { // "mongodb:" serverAddrs.add(new ServerAddress()); } else { StringTokenizer tokeniser = new StringTokenizer(remains, ","); boolean firstServer = true; while (tokeniser.hasMoreTokens()) { String token = tokeniser.nextToken(); String serverName = "localhost"; if (firstServer) { // Set dbName int dbNameSepPos = token.indexOf("/"); if (dbNameSepPos >= 0) { if (dbNameSepPos < token.length()) { String dbNameStr = token.substring(dbNameSepPos + 1); if (dbNameStr.length() > 0) { dbName = dbNameStr; } else { // Use default ("DataNucleus") } } if (dbNameSepPos > 0) { // Server name is not empty so use it serverName = token.substring(0, dbNameSepPos); } } else { if (token.length() > 0) { // No "/" specified so just take all of token serverName = token; } } } else { // Subsequent replica-set so use full token as server name serverName = token; } // Create a ServerAddress for this specification ServerAddress addr = null; int portSeparatorPos = serverName.indexOf(':'); if (portSeparatorPos > 0) { addr = new ServerAddress(serverName.substring(0, portSeparatorPos), Integer.valueOf(serverName.substring(portSeparatorPos + 1)).intValue()); } else { addr = new ServerAddress(serverName); } serverAddrs.add(addr); firstServer = false; } } // Create the Mongo connection pool if (NucleusLogger.CONNECTION.isDebugEnabled()) { NucleusLogger.CONNECTION.debug(LOCALISER.msg("MongoDB.ServerConnect", dbName, serverAddrs.size(), StringUtils.collectionToString(serverAddrs))); } if (serverAddrs.size() == 1) { mongo = new MongoClient(serverAddrs.get(0), getMongodbOptions(storeMgr)); } else { mongo = new MongoClient(serverAddrs, getMongodbOptions(storeMgr)); } } catch (UnknownHostException e) { throw new NucleusDataStoreException("Unable to connect to mongodb", e); } catch (MongoException me) { throw new NucleusDataStoreException("Unable to connect to mongodb", me); } }
From source file:org.fornax.cartridges.sculptor.framework.accessimpl.mongodb.DbManager.java
License:Apache License
private synchronized void init() { if (initialized) { return;/*from w w w.j a v a 2s .c om*/ } if (dbname == null) { throw new IllegalStateException("MongoDB dbname not defined"); } try { if (dbUrl1 == null || dbUrl1.equals("")) { // default host/port, but with options mongo = new Mongo(new ServerAddress(), options); } else if (dbUrl2 != null && !dbUrl2.equals("")) { DBAddress left = new DBAddress(urlWithDbname(dbUrl1)); DBAddress right = new DBAddress(urlWithDbname(dbUrl2)); mongo = new Mongo(left, right, options); } else { DBAddress left = new DBAddress(urlWithDbname(dbUrl1)); mongo = new Mongo(left, options); } db = mongo.getDB(dbname); initialized = true; } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } }
From source file:org.grails.datastore.gorm.mongo.bean.factory.GMongoFactoryBean.java
License:Apache License
public void afterPropertiesSet() throws UnknownHostException { // apply defaults - convenient when used to configure for tests // in an application context if (mongo != null) { return;// www . ja v a 2 s . c o m } ServerAddress defaultOptions = new ServerAddress(); if (mongoOptions == null) mongoOptions = new MongoOptions(); if (replicaPair != null) { if (replicaPair.size() < 2) { throw new DatastoreConfigurationException("A replica pair must have two server entries"); } mongo = new GMongo(replicaPair.get(0), replicaPair.get(1), mongoOptions); } else if (replicaSetSeeds != null) { mongo = new GMongo(replicaSetSeeds, mongoOptions); } else { String mongoHost = host != null ? host : defaultOptions.getHost(); if (port != null) { mongo = new GMongo(new ServerAddress(mongoHost, port), mongoOptions); } else { mongo = new GMongo(mongoHost, mongoOptions); } } }
From source file:org.grails.datastore.gorm.mongo.bean.factory.MongoClientFactoryBean.java
License:Apache License
public void afterPropertiesSet() throws UnknownHostException { // apply defaults - convenient when used to configure for tests // in an application context if (mongo != null) { return;//from w w w . j a va 2 s . c o m } ServerAddress defaultOptions = new ServerAddress(); List<MongoCredential> credentials = new ArrayList<MongoCredential>(); if (mongoOptions == null) { MongoClientOptions.Builder builder = MongoClientOptions.builder(); builder.codecRegistry(CodecRegistries.fromRegistries(codecRegistries)); mongoOptions = builder.build(); } // If username/pw exists and we are not authenticated, authenticate now if (username != null && password != null) { credentials.add(MongoCredential.createCredential(username, database, password.toCharArray())); } if (replicaPair != null) { if (replicaPair.size() < 2) { throw new DatastoreConfigurationException("A replica pair must have two server entries"); } mongo = new MongoClient(replicaPair, credentials, mongoOptions); } else if (replicaSetSeeds != null) { mongo = new MongoClient(replicaSetSeeds, credentials, mongoOptions); } else if (clientURI != null) { mongo = new MongoClient(clientURI); } else if (connectionString != null) { mongo = new MongoClient(new MongoClientURI(connectionString)); } else { String mongoHost = host != null ? host : defaultOptions.getHost(); if (port != null) { mongo = new MongoClient(new ServerAddress(mongoHost, port), credentials, mongoOptions); } else { mongo = new MongoClient(new ServerAddress(host), credentials, mongoOptions); } } }
From source file:org.grails.datastore.mapping.mongo.MongoDatastore.java
License:Apache License
public void afterPropertiesSet() throws Exception { if (mongo == null) { ServerAddress defaults = new ServerAddress(); MongoFactoryBean dbFactory = new MongoFactoryBean(); dbFactory.setHost(read(String.class, MONGO_HOST, connectionDetails, defaults.getHost())); dbFactory.setPort(read(Integer.class, MONGO_PORT, connectionDetails, defaults.getPort())); if (mongoOptions != null) { dbFactory.setMongoOptions(mongoOptions); }/*from w w w. j av a 2 s . com*/ dbFactory.afterPropertiesSet(); mongo = dbFactory.getObject(); } for (PersistentEntity entity : mappingContext.getPersistentEntities()) { // Only create Mongo templates for entities that are mapped with Mongo if (!entity.isExternal()) { createMongoTemplate(entity, mongo); } } }
From source file:org.sculptor.framework.accessimpl.mongodb.DbManager.java
License:Apache License
@SuppressWarnings("deprecation") private synchronized void init() { if (initialized) { return;/*from www .j a v a2s .c om*/ } if (dbname == null) { throw new IllegalStateException("MongoDB dbname not defined"); } try { if (dbUrl1 == null || dbUrl1.equals("")) { // default host/port, but with options mongo = new Mongo(new ServerAddress(), options); } else if (dbUrl2 != null && !dbUrl2.equals("")) { DBAddress left = new DBAddress(urlWithDbname(dbUrl1)); DBAddress right = new DBAddress(urlWithDbname(dbUrl2)); mongo = new Mongo(left, right, options); } else { DBAddress left = new DBAddress(urlWithDbname(dbUrl1)); mongo = new Mongo(left, options); } db = mongo.getDB(dbname); initialized = true; } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } }