List of usage examples for com.mongodb MongoOptions MongoOptions
@Deprecated
public MongoOptions()
From source file:backend.connections.MongoOptionsFactory.java
License:Apache License
/** * Default constructor for the factory that initializes the defaults. */ public MongoOptionsFactory() { defaults = new MongoOptions(); }
From source file:backend.connections.MongoOptionsFactory.java
License:Apache License
/** * Uses the configured parameters to create a MongoOptions instance. * * @return MongoOptions instance based on the configured properties *//*from www .j a v a2 s .co m*/ public MongoOptions createMongoOptions() { MongoOptions options = new MongoOptions(); options.connectionsPerHost = getConnectionsPerHost(); options.connectTimeout = getConnectionTimeout(); options.maxWaitTime = getMaxWaitTime(); options.threadsAllowedToBlockForConnectionMultiplier = getThreadsAllowedToBlockForConnectionMultiplier(); options.autoConnectRetry = isAutoConnectRetry(); options.socketTimeout = getSocketTimeOut(); if (logger.isDebugEnabled()) { logger.info("Mongo Options"); logger.info("Connections per host :{}", options.connectionsPerHost); logger.info("Connection timeout : {}", options.connectTimeout); logger.info("Max wait timeout : {}", options.maxWaitTime); logger.info("Threads allowed to block : {}", options.threadsAllowedToBlockForConnectionMultiplier); logger.info("Autoconnect retry : {}", options.autoConnectRetry); logger.info("Socket timeout : {}", options.socketTimeout); } return options; }
From source file:com.andreig.jetty.MongoDB.java
License:GNU General Public License
public static Mongo get() { if (db == null) { try {/*from www . j av a2 s. co m*/ List<ServerAddress> addrs = str2addresses(Config.mongo_servers); MongoOptions opts = new MongoOptions(); opts.autoConnectRetry = true; int thrno = Config.server_threadsno; if (thrno < 100) opts.connectionsPerHost = thrno; else opts.connectionsPerHost = 100; opts.threadsAllowedToBlockForConnectionMultiplier = 10; opts.maxWaitTime = 10000; // millisecs db = new Mongo(addrs, opts); write_concern = Config.mongo_safeoperations ? WriteConcern.FSYNC_SAFE : WriteConcern.NORMAL; log.info("getDB():" + db); } catch (UnknownHostException e) { log.severe("Bad host " + e); db = null; } } return db; }
From source file:com.cyslab.craftvm.rest.mongo.MongoDB.java
License:GNU General Public License
public static Mongo get() { if (db == null) { try {//from w ww . j a va 2 s . c o m List<ServerAddress> addrs = str2addresses(Config.mongo_servers); MongoOptions opts = new MongoOptions(); opts.autoConnectRetry = true; int thrno = Config.server_threadsno; if (thrno < 100) opts.connectionsPerHost = thrno; else opts.connectionsPerHost = 100; opts.threadsAllowedToBlockForConnectionMultiplier = 10; opts.maxWaitTime = 10000; // millisecs db = new Mongo(addrs, opts); write_concern = Config.mongo_safeoperations ? WriteConcern.FSYNC_SAFE : WriteConcern.NORMAL; log.info("getDB():" + db); } catch (UnknownHostException e) { log.error("Bad host " + e); db = null; } } return db; }
From source file:com.github.stephenc.mongodb.maven.StartMongoMojo.java
License:Apache License
public void execute() throws MojoExecutionException, MojoFailureException { if (skip) {/*from w ww . j a va 2 s . com*/ getLog().info("Skipping mongodb: mongodb.skip==true"); return; } if (installation == null) { getLog().info("Using mongod from PATH"); } else { getLog().info("Using mongod installed in " + installation); } getLog().info("Using database root of " + databaseRoot); final Logger mongoLogger = Logger.getLogger("com.mongodb"); Level mongoLevel = mongoLogger.getLevel(); try { mongoLogger.setLevel(Level.SEVERE); MongoOptions opts = new MongoOptions(); opts.autoConnectRetry = false; opts.connectionsPerHost = 1; opts.connectTimeout = 50; opts.socketTimeout = 50; Mongo instance; try { instance = new Mongo(new ServerAddress("localhost", port), opts); List<String> databaseNames = instance.getDatabaseNames(); throw new MojoExecutionException("Port " + port + " is already running a MongoDb instance with the following databases " + databaseNames); } catch (MongoException.Network e) { // fine... no instance running } catch (MongoException e) { throw new MojoExecutionException("Port " + port + " is already running a MongoDb instance"); } catch (UnknownHostException e) { // ignore... localhost is always known! } } finally { mongoLogger.setLevel(mongoLevel); } CommandLine commandLine = null; if (installation != null && installation.isDirectory()) { File bin = new File(installation, "bin"); File exe = new File(bin, Os.isFamily(Os.FAMILY_WINDOWS) ? "mongod.exe" : "mongod"); if (exe.isFile()) { commandLine = new CommandLine(exe); } else { throw new MojoExecutionException("Could not find mongo executables in specified installation: " + installation + " expected to find " + exe + " but it does not exist."); } } if (commandLine == null) { commandLine = new CommandLine(Os.isFamily(Os.FAMILY_WINDOWS) ? "mongod.exe" : "mongod"); } if (databaseRoot.isFile()) { throw new MojoExecutionException("Database root " + databaseRoot + " is a file and not a directory"); } if (databaseRoot.isDirectory() && cleanDatabaseRoot) { getLog().info("Cleaning database root directory: " + databaseRoot); try { FileUtils.deleteDirectory(databaseRoot); } catch (IOException e) { throw new MojoExecutionException("Could not clean database root directory " + databaseRoot, e); } } if (!databaseRoot.isDirectory()) { getLog().debug("Creating database root directory: " + databaseRoot); if (!databaseRoot.mkdirs()) { throw new MojoExecutionException("Could not create database root directory " + databaseRoot); } } if (!verbose) { commandLine.addArgument("--quiet"); } commandLine.addArgument("--logpath"); commandLine.addArgument(logPath.getAbsolutePath()); if (logAppend) { commandLine.addArgument("--logappend"); } commandLine.addArgument(auth ? "--auth" : "--noauth"); commandLine.addArgument("--port"); try { // this is a hack to force mongo to use a project property // that we are randomly setting at run-time (reserve-network-port) port = Integer.parseInt(project.getProperties().getProperty("mongodb.port")); } catch (NumberFormatException e) { // no or bad project property } commandLine.addArgument(Integer.toString(port)); commandLine.addArgument("--dbpath"); commandLine.addArgument(databaseRoot.getAbsolutePath()); if (additionalArguments != null) { for (String aa : additionalArguments) { commandLine.addArgument(aa); } } Executor exec = new DefaultExecutor(); DefaultExecuteResultHandler execHandler = new DefaultExecuteResultHandler(); exec.setWorkingDirectory(databaseRoot); ProcessObserver processObserver = new ProcessObserver(new ShutdownHookProcessDestroyer()); exec.setProcessDestroyer(processObserver); LogOutputStream stdout = new MavenLogOutputStream(getLog()); LogOutputStream stderr = new MavenLogOutputStream(getLog()); getLog().info("Executing command line: " + commandLine); exec.setStreamHandler(new PumpStreamHandler(stdout, stderr)); try { exec.execute(commandLine, execHandler); getLog().info("Waiting for MongoDB to start..."); long timeout = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(120); mongoLevel = mongoLogger.getLevel(); try { mongoLogger.setLevel(Level.SEVERE); while (System.currentTimeMillis() < timeout && !execHandler.hasResult()) { MongoOptions opts = new MongoOptions(); opts.autoConnectRetry = false; opts.connectionsPerHost = 1; opts.connectTimeout = 250; opts.socketTimeout = 250; Mongo instance; try { instance = new Mongo(new ServerAddress("localhost", port), opts); List<String> databaseNames = instance.getDatabaseNames(); getLog().info("MongoDb started."); getLog().info("Databases: " + databaseNames); } catch (MongoException.Network e) { // ignore, wait and try again try { Thread.sleep(50); } catch (InterruptedException e1) { // ignore } continue; } catch (MongoException e) { getLog().info("MongoDb started."); getLog().info("Unable to list databases due to " + e.getMessage()); } break; } } finally { mongoLogger.setLevel(mongoLevel); } if (execHandler.hasResult()) { ExecuteException exception = execHandler.getException(); if (exception != null) { throw new MojoFailureException(exception.getMessage(), exception); } throw new MojoFailureException( "Command " + commandLine + " exited with exit code " + execHandler.getExitValue()); } Map pluginContext = session.getPluginContext(getPluginDescriptor(), project); pluginContext.put(ProcessObserver.class.getName() + ":" + Integer.toString(port), processObserver); } catch (IOException e) { throw new MojoExecutionException(e.getMessage(), e); } }
From source file:com.hangum.tadpole.mongodb.core.connection.MongoConnectionManager.java
License:Open Source License
/** * /*from ww w . j a v a 2 s .c o m*/ * @param userDB * @return * @throws Exception */ public static DB getInstance(UserDBDAO userDB) throws MongoDBNotFoundException, Exception { DB db = null; synchronized (dbManager) { try { String searchKey = getKey(userDB); Mongo mongoDB = dbManager.get(searchKey); if (mongoDB == null) { final MongoOptions options = new MongoOptions(); options.connectionsPerHost = 20; options.threadsAllowedToBlockForConnectionMultiplier = 5; options.maxWaitTime = 120000; options.autoConnectRetry = false; options.safe = true; String strReplcaSet = userDB.getExt1(); if (strReplcaSet == null | "".equals(strReplcaSet)) { mongoDB = new Mongo(new DBAddress(userDB.getUrl()), options); } else { List<ServerAddress> listServerList = new ArrayList<ServerAddress>(); listServerList.add(new ServerAddress(userDB.getHost(), Integer.parseInt(userDB.getPort()))); String[] urls = StringUtils.split(strReplcaSet, ","); for (String ipPort : urls) { String[] strIpPort = StringUtils.split(ipPort, ":"); listServerList.add(new ServerAddress(strIpPort[0], Integer.parseInt(strIpPort[1]))); } // options.setReadPreference(ReadPreference.primary()); mongoDB = new Mongo(listServerList, options); } // password ?. db = mongoDB.getDB(userDB.getDb()); if (!"".equals(userDB.getUsers())) { //$NON-NLS-1$ // pass change String passwdDecrypt = ""; try { passwdDecrypt = CipherManager.getInstance().decryption(userDB.getPasswd()); } catch (Exception e) { passwdDecrypt = userDB.getPasswd(); } boolean auth = db.authenticate(userDB.getUsers(), passwdDecrypt.toCharArray()); if (!auth) { throw new Exception(Messages.MongoDBConnection_3); } } // // ? ? ? . // // // db . // List<String> listDB = mongoDB.getDatabaseNames(); // boolean isDB = false; // for (String dbName : listDB) if(userDB.getDb().equals(dbName)) isDB = true; // if(!isDB) { // throw new MongoDBNotFoundException(userDB.getDb() + Messages.MongoDBConnection_0); // } try { // ? ? ? ? . db.getCollectionNames(); } catch (Exception e) { logger.error("error", e); throw new MongoDBNotFoundException(userDB.getDb() + " " + e.getMessage());//Messages.MongoDBConnection_0); } // db map? . dbManager.put(searchKey, mongoDB); } else { db = mongoDB.getDB(userDB.getDb()); } } catch (Exception e) { logger.error("mongodb connection error", e); throw e; } } return db; }
From source file:com.hangum.tadpole.mongodb.core.query.MongoDBQuery.java
License:Open Source License
/** * create database/*from ww w .j a v a 2 s . c o m*/ * * @param userDB * @throws Exception */ public static void createDB(UserDBDAO userDB) throws Exception { MongoOptions options = new MongoOptions(); options.connectionsPerHost = 20; Mongo mongo = new Mongo(userDB.getHost(), Integer.parseInt(userDB.getPort())); DB db = mongo.getDB(userDB.getDb()); db.authenticate(userDB.getUsers(), userDB.getPasswd().toCharArray()); // // ? ? ? ?? . // Set<String> listColNames = db.getCollectionNames(); for (String stringColName : listColNames) { } // }
From source file:com.liferay.mongodb.util.MongoDBUtil.java
License:Open Source License
private MongoOptions _getMongoOptions() { MongoOptions mongoOptions = new MongoOptions(); mongoOptions.autoConnectRetry = GetterUtil.getBoolean(PortletPropsValues.DRIVER_AUTOCONNECT_RETRY, mongoOptions.autoConnectRetry); mongoOptions.connectTimeout = GetterUtil.getInteger(PortletPropsValues.DRIVER_CONNECT_TIMEOUT, mongoOptions.connectTimeout); mongoOptions.connectionsPerHost = GetterUtil.getInteger(PortletPropsValues.DRIVER_CONNECTIONS_PER_HOST, mongoOptions.connectionsPerHost); mongoOptions.maxWaitTime = GetterUtil.getInteger(PortletPropsValues.DRIVER_MAX_WAIT_TIME, mongoOptions.maxWaitTime);//from www .j a v a2s. c o m mongoOptions.socketTimeout = GetterUtil.getInteger(PortletPropsValues.DRIVER_SOCKET_TIMEOUT, mongoOptions.socketTimeout); mongoOptions.threadsAllowedToBlockForConnectionMultiplier = GetterUtil.getInteger( PortletPropsValues.DRIVER_THREADS_ALLOWED_TO_BLOCK, mongoOptions.threadsAllowedToBlockForConnectionMultiplier); return mongoOptions; }
From source file:com.mulesoft.quartz.mongo.MongoDBJobStore.java
License:Open Source License
public void initialize(ClassLoadHelper loadHelper, SchedulerSignaler signaler) throws SchedulerConfigException { this.loadHelper = loadHelper; this.signaler = signaler; if (addresses == null || addresses.length == 0) { throw new SchedulerConfigException("At least one MongoDB address must be specified."); }//from ww w.ja v a 2 s . c o m MongoOptions options = new MongoOptions(); options.safe = true; // need to do this to ensure we get DuplicateKey exceptions try { ArrayList<ServerAddress> serverAddresses = new ArrayList<ServerAddress>(); for (String a : addresses) { serverAddresses.add(new ServerAddress(a)); } mongo = new Mongo(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); } DB db = mongo.getDB(dbName); if (username != null) { db.authenticate(username, password.toCharArray()); } jobCollection = db.getCollection(collectionPrefix + "jobs"); triggerCollection = db.getCollection(collectionPrefix + "triggers"); calendarCollection = db.getCollection(collectionPrefix + "calendars"); locksCollection = db.getCollection(collectionPrefix + "locks"); BasicDBObject keys = new BasicDBObject(); keys.put(JOB_KEY_NAME, 1); keys.put(JOB_KEY_GROUP, 1); jobCollection.ensureIndex(keys, null, true); keys = new BasicDBObject(); keys.put(TRIGGER_KEY_NAME, 1); keys.put(TRIGGER_KEY_GROUP, 1); triggerCollection.ensureIndex(keys, null, true); keys = new BasicDBObject(); keys.put(LOCK_KEY_NAME, 1); keys.put(LOCK_KEY_GROUP, 1); locksCollection.ensureIndex(keys, null, true); // remove all locks for this instance on startup locksCollection.remove(new BasicDBObject(LOCK_INSTANCE_ID, instanceId)); keys = new BasicDBObject(); keys.put(CALENDAR_NAME, 1); calendarCollection.ensureIndex(keys, null, true); }
From source file:com.streamreduce.datasource.MongoFactoryBean.java
License:Apache License
private MongoOptions getMongoOptions() { MongoOptions options = new MongoOptions(); options.autoConnectRetry = autoConnectRetry; options.connectionsPerHost = connectionsPerHost; options.connectTimeout = connectionTimeout; options.socketTimeout = socketTimeout; options.threadsAllowedToBlockForConnectionMultiplier = threadsAllowedToBlockForConnectionMultiplier; return options; }