List of usage examples for com.mongodb MongoOptions MongoOptions
@Deprecated
public MongoOptions()
From source file:com.streamreduce.storm.MongoClient.java
License:Apache License
/** * Initializes the {@link Mongo} object. * * @param host the host MongoDB is expected to be running on * @param port the port MongoDB is expected to be listening on * @param username the username to authenticate as * @param password the password to the username above *///from ww w.j a v a 2 s. com private void init(String host, int port, String username, String password) { this.host = host; this.port = port; this.username = username; this.password = password; logger.info("Mongo Client Connecting to " + host + ":" + port); try { MongoOptions options = new MongoOptions(); options.autoConnectRetry = true; //options.connectionsPerHost = 50; options.connectTimeout = 1500; options.socketTimeout = 60000; options.threadsAllowedToBlockForConnectionMultiplier = 1000; //options.connectionsPerHost = 50; // * 5, so up to 250 can wait before it dies this.mongo = new Mongo(new ServerAddress(host, port), options); } catch (UnknownHostException e) { MongoException me = new MongoException("Unable to connect to Mongo at " + host + ":" + port, e); logger.error(me.getMessage(), me); throw me; } }
From source file:de.flapdoodle.embed.mongo.tests.MongosSystemForTestFactory.java
License:Apache License
private void configureMongos() throws Exception { CommandResult cr;//from w ww. j ava 2 s . co m MongoOptions mo = new MongoOptions(); mo.autoConnectRetry = true; Mongo mongo = new Mongo( new ServerAddress(this.config.net().getServerAddress().getHostName(), this.config.net().getPort()), mo); DB mongoAdminDB = mongo.getDB(ADMIN_DATABASE_NAME); // Add shard from the replica set list for (Entry<String, List<IMongodConfig>> entry : this.replicaSets.entrySet()) { String replicaName = entry.getKey(); String command = ""; for (IMongodConfig mongodConfig : entry.getValue()) { if (command.isEmpty()) { command = replicaName + "/"; } else { command += ","; } command += mongodConfig.net().getServerAddress().getHostName() + ":" + mongodConfig.net().getPort(); } logger.info("Execute add shard command: " + command); cr = mongoAdminDB.command(new BasicDBObject("addShard", command)); logger.info(cr.toString()); } logger.info("Execute list shards."); cr = mongoAdminDB.command(new BasicDBObject("listShards", 1)); logger.info(cr.toString()); // Enabled sharding at database level logger.info("Enabled sharding at database level"); cr = mongoAdminDB.command(new BasicDBObject("enableSharding", this.shardDatabase)); logger.info(cr.toString()); // Create index in sharded collection logger.info("Create index in sharded collection"); DB db = mongo.getDB(this.shardDatabase); db.getCollection(this.shardCollection).ensureIndex(this.shardKey); // Shard the collection logger.info("Shard the collection: " + this.shardDatabase + "." + this.shardCollection); DBObject cmd = new BasicDBObject(); cmd.put("shardCollection", this.shardDatabase + "." + this.shardCollection); cmd.put("key", new BasicDBObject(this.shardKey, 1)); cr = mongoAdminDB.command(cmd); logger.info(cr.toString()); logger.info("Get info from config/shards"); DBCursor cursor = mongo.getDB("config").getCollection("shards").find(); while (cursor.hasNext()) { DBObject item = cursor.next(); logger.info(item.toString()); } }
From source file:fr.cnes.sitools.datasource.mongodb.business.SitoolsMongoDBDataSourceFactory.java
License:Open Source License
/** * Setup a dataSource for "users". Usage is for all users for consultation functions. * // w ww. j ava2 s . c o m * @param dataSource * the DataSource to update * @return SitoolsDataSource the new DataSource */ public SitoolsMongoDBDataSource setupDataSourceForUsers(MongoDBDataSource dataSource) { String key = dataSource.getId(); SitoolsMongoDBDataSource foundDatasource = dataSources.get(key); if (foundDatasource == null) { Mongo mongo = null; try { MongoOptions options = new MongoOptions(); ServerAddress address = new ServerAddress(dataSource.getUrl(), dataSource.getPortNumber()); options.setConnectionsPerHost(dataSource.getMaxActive()); mongo = new Mongo(address, options); } catch (UnknownHostException e) { logger.log(Level.INFO, null, e); } catch (MongoException e) { logger.log(Level.INFO, null, e); } foundDatasource = new SitoolsMongoDBDataSource(dataSource, mongo); dataSources.put(key, foundDatasource); } return foundDatasource; }
From source file:HAL.libraries.blackboard_client.data_classes.MongoDBConnection.java
License:Open Source License
/** * Creates a new Mongo client for the specified address. * @param address The ServerAddress where the host resides. * @throws GeneralMongoException Connecting to the database server failed. **//*from ww w . ja va 2 s . c om*/ private MongoDBConnection(ServerAddress address) throws GeneralMongoException { try { //Logger.log(LogLevel.NOTIFICATION, "Starting a new mongoclient."); MongoOptions mongoOptions = new MongoOptions(); mongoOptions.connectionsPerHost = Configuration.getPropertyInt(ConfigurationFiles.MONGO_DB_PROPERTIES, "connectionsPerHost"); mongoOptions.threadsAllowedToBlockForConnectionMultiplier = Configuration.getPropertyInt( ConfigurationFiles.MONGO_DB_PROPERTIES, "threadsAllowedToBlockForConnectionMultiplier"); mongoClient = new Mongo(address, mongoOptions); mongoClient.setWriteConcern(WriteConcern.SAFE); } catch (MongoException mongoException) { throw new GeneralMongoException("A mongo exception occurred while connecting.", mongoException); } this.address = address; }
From source file:jc.mongodb.AbstractMongoIT.java
License:Apache License
@Before public void createMongo() throws Exception { MongoOptions options = new MongoOptions(); mongo = new Mongo("localhost", options); mongo.dropDatabase("testdb"); db = mongo.getDB("testdb"); dbCollection = db.getCollection("testcollection"); }
From source file:jp.co.ctc_g.rack.core.config.RackMongoContextConfig.java
License:Apache License
/** * MongoDI????/*from w ww . j av a 2 s .c o m*/ * @return Mongo */ @Bean public MongoOptions mongoOptions() { MongoOptions options = new MongoOptions(); options.setConnectionsPerHost(connectionsPerHost); options.setThreadsAllowedToBlockForConnectionMultiplier(threadAllowedToBlockForConnectionMultiplier); options.setConnectTimeout(connectTimeout); options.setMaxWaitTime(maxWaitTime); options.setAutoConnectRetry(autoConnectRetry); options.setSocketKeepAlive(socketKeepAlive); options.setSocketTimeout(socketTimeout); options.setFsync(fsync); return options; }
From source file:mongoDB.MongoDbClientAllImagesAsByteArrays.java
License:Open Source License
/** * Initialize any state for this DB. Called once per DB instance; there is * one DB instance per client thread.//from w w w . j av a 2s . co m */ public boolean init() throws DBException { // initialize MongoDb driver props = getProperties(); String url = props.getProperty(MONGODB_URL_PROPERTY); database = props.getProperty(MONGODB_DB_PROPERTY); String writeConcernType = props.getProperty(MONGODB_WRITE_CONCERN_PROPERTY, MONGODB_WRITE_CONCERN_PROPERTY_DEFAULT); manipulationArray = Boolean.parseBoolean(props.getProperty(MONGODB_MANIPULATION_ARRAY_PROPERTY, MONGODB_MANIPULATION_ARRAY_PROPERTY_DEFAULT)); friendListReq = Boolean.parseBoolean( props.getProperty(MONGODB_FRNDLIST_REQ_PROPERTY, MONGODB_FRNDLIST_REQ_PROPERTY_DEFAULT)); scanResources = Boolean .parseBoolean(props.getProperty(MONGODB_SCANFORRES_PROPERTY, MONGODB_SCANFORRES_PROPERTY_DEFAULT)); if ("none".equals(writeConcernType)) { // don't return error on writes writeConcern = WriteConcern.NONE; } else if ("strict".equals(writeConcernType)) { // The write will wait for a response from the server and raise an // exception on any error writeConcern = WriteConcern.SAFE; } else if ("normal".equals(writeConcernType)) { // normal error handling - just raise exceptions when problems, don // wait for response form servers writeConcern = WriteConcern.NORMAL; } try { // System.out.println("new database url = "+url); /* * MongoOptions mo = new MongoOptions(); mo.connectionsPerHost = * 100; mongo = new Mongo(new DBAddress(url), mo); */ /* * List<ServerAddress> addrs = new ArrayList<ServerAddress>(); * addrs.add( new ServerAddress( "10.0.0.122" , 27017 ) ); * addrs.add( new ServerAddress( "10.0.0.122" , 10002 ) ); * addrs.add( new ServerAddress( "10.0.0.120" , 10003 ) ); * MongoOptions mongoOptions = new MongoOptions(); mongo = new * Mongo( addrs, mongoOptions); * mongo.setReadPreference(ReadPreference.SECONDARY); */ // System.out.println("mongo connection created with "+url); try { crtcl.acquire(); if (NumThreads == null) { NumThreads = new AtomicInteger(); NumThreads.set(0); MongoOptions mo = new MongoOptions(); mo.connectionsPerHost = 100; String urls[]; if (!url.contains(";")) { //multiple mongos servers url += "/" + database; mongo = new Mongo(new DBAddress(url), mo); } /*else{ // need to append db to url. urls = url.split(";"); List<ServerAddress> addrs = new ArrayList<ServerAddress>(); for(int i=0; i< urls.length; i++){ addrs.add( new ServerAddress(urls[i].split(":")[0] , Integer.parseInt(urls[i].split(":")[1]) ) ); //no need to add the database name here as each action does a mongo.getDB(database) } mongo = new Mongo( addrs); }*/ else { // need to append db to url. urls = url.split(";"); mo = new MongoOptions(); mo.connectionsPerHost = 100; //trying to direct clients to different routers url = urls[(Integer.parseInt(props.getProperty(Client.MACHINE_ID_PROPERTY, "0"))) % urls.length]; url += "/" + database; mongo = new Mongo(new DBAddress(url), mo); } //mongo = new MongoClient(new DBAddress(url)); // checking to see if the connection is established try { Socket socket = mongo.getMongoOptions().socketFactory.createSocket(); socket.connect(mongo.getAddress().getSocketAddress()); socket.close(); } catch (IOException ex) { System.out.println("ERROR: Can't create connection, check if MongDB is running"); return false; } } incrementNumThreads(); } catch (Exception e) { System.out.println("MongoDB init failed to acquire semaphore."); e.printStackTrace(System.out); } finally { crtcl.release(); } } catch (Exception e1) { System.out.println("Could not initialize MongoDB connection pool for Loader: " + e1.toString()); e1.printStackTrace(System.out); return false; } return true; }
From source file:nl.knaw.huygens.timbuctoo.storage.mongo.MongoDB.java
License:Open Source License
@Inject public MongoDB(Configuration config) throws UnknownHostException { MongoOptions options = new MongoOptions(); options.safe = true;/*from w w w.j a v a 2s. com*/ String host = config.getSetting("database.host", "localhost"); int port = config.getIntSetting("database.port", 27017); mongo = new Mongo(new ServerAddress(host, port), options); String dbName = config.getSetting("database.name"); db = mongo.getDB(dbName); String user = config.getSetting("database.user"); if (!user.isEmpty()) { String password = config.getSetting("database.password"); db.authenticate(user, password.toCharArray()); } }
From source file:org.anyframe.logmanager.bundle.core.Activator.java
License:Apache License
/** * @param context/*from w w w. j a va 2 s.com*/ * @throws Exception */ private void initMongo(BundleContext context) throws Exception { if (context == null) { throw new LogManagerBundleException("Context is null."); } String mongoSvr = context.getProperty("mongo.host"); int mongoPort = Integer.parseInt(context.getProperty("mongo.port")); logger.info("MongoDB connect to - " + mongoSvr + ":" + mongoPort); MongoOptions options = new MongoOptions(); options.connectionsPerHost = Integer.parseInt(context.getProperty("mongo.connectionsPerHost")); options.autoConnectRetry = Boolean.parseBoolean(context.getProperty("mongo.autoConnectRetry")); options.connectTimeout = Integer.parseInt(context.getProperty("mongo.connectTimeout")); options.threadsAllowedToBlockForConnectionMultiplier = Integer .parseInt(context.getProperty("mongo.threadsAllowedToBlockForConnectionMultiplier")); options.maxWaitTime = Integer.parseInt(context.getProperty("mongo.maxWaitTime")); options.connectTimeout = Integer.parseInt(context.getProperty("mongo.connectTimeout")); options.socketKeepAlive = Boolean.parseBoolean(context.getProperty("mongo.socketKeepAlive")); options.socketTimeout = Integer.parseInt(context.getProperty("mongo.socketTimeout")); ServerAddress addr = new ServerAddress(mongoSvr, mongoPort); mongo = new Mongo(addr, options); if (mongo != null) { logger.info("MongoDB connected - " + addr.getHost() + ":" + addr.getPort()); } }
From source file:org.apache.sling.mongodb.impl.MongoDBResourceProviderFactory.java
License:Apache License
@Activate protected void activate(final Map<String, Object> props) throws Exception { final String[] roots = PropertiesUtil.toStringArray(props.get(ResourceProvider.ROOTS)); if (roots == null || roots.length == 0) { throw new Exception("Roots configuration is missing."); }/* www. j a va 2 s. c o m*/ if (roots.length > 1) { throw new Exception("Only a single root should be configured."); } if (roots[0] == null || roots[0].trim().length() == 0) { throw new Exception("Roots configuration is missing."); } final String host = PropertiesUtil.toString(props.get(PROP_HOST), DEFAULT_HOST); final int port = PropertiesUtil.toInteger(props.get(PROP_PORT), DEFAULT_PORT); final String db = PropertiesUtil.toString(props.get(PROP_DB), DEFAULT_DB); logger.info("Starting MongoDB resource provider with host={}, port={}, db={}", new Object[] { host, port, db }); final DBAddress address = new DBAddress(host, port, db); final MongoOptions options = new MongoOptions(); options.connectionsPerHost = PropertiesUtil.toInteger(props.get(PROP_NUM_CONNECTIONS), DEFAULT_NUMCONNECTIONS); options.threadsAllowedToBlockForConnectionMultiplier = PropertiesUtil .toInteger(props.get(PROP_THREAD_MULTIPLIER), DEFAULT_THREAD_MULTIPLIER); final Mongo m = new Mongo(address, options); final DB database = m.getDB(db); logger.info("Connected to database {}", database); this.context = new MongoDBContext(database, roots[0], PropertiesUtil.toStringArray(props.get(PROP_FILTER_COLLECTIONS)), this.eventAdmin); }