List of usage examples for com.mongodb Mongo Mongo
Mongo(final MongoClientURI mongoURI, @Nullable final MongoDriverInformation mongoDriverInformation)
From source file:org.mobicents.servlet.sip.restcomm.dao.mongodb.MongoDaoManager.java
License:Open Source License
@Override public void start() throws RuntimeException { final String host = configuration.getString("host"); final Integer port = configuration.getInt("port"); final String db = configuration.getString("database"); final String user = configuration.getString("user"); final String password = configuration.getString("password"); // Connect to the MongoDB server. DB database = null;// w ww .ja va 2s .com try { mongo = new Mongo(host, port); database = mongo.getDB(db); if (user != null && !user.isEmpty() && password != null && !password.isEmpty()) { if (!database.authenticate(user, password.toCharArray())) { throw new RuntimeException("Authentication for " + user + " failed."); } } } catch (final UnknownHostException exception) { throw new RuntimeException(exception); } // Instantiate the DAO objects. accountsDao = new MongoAccountsDao(database); applicationsDao = new MongoApplicationsDao(database); announcementsDao = new MongoAnnouncementsDao(database); availablePhoneNumbersDao = new MongoAvailablePhoneNumbersDao(database); callDetailRecordsDao = new MongoCallDetailRecordsDao(database); clientsDao = new MongoClientsDao(database); httpCookiesDao = new MongoHttpCookiesDao(database); incomingPhoneNumbersDao = new MongoIncomingPhoneNumbersDao(database); notificationsDao = new MongoNotificationsDao(database); outgoingCallerIdsDao = new MongoOutgoingCallerIdsDao(database); presenceRecordsDao = new MongoRegistrationsDao(database); recordingsDao = new MongoRecordingsDao(database); sandBoxesDao = new MongoSandBoxesDao(database); shortCodesDao = new MongoShortCodesDao(database); smsMessagesDao = new MongoSmsMessagesDao(database); transcriptionsDao = new MongoTranscriptionsDao(database); gatewaysDao = new MongoGatewaysDao(database); }
From source file:org.mongoste.core.impl.mongodb.MongoStatsEngine.java
License:Open Source License
@Override public void init(Properties properties) throws StatsEngineException { log.info("Mongo Stats Engine initialization: {}", properties); String host = properties.getProperty("host", "localhost"); int port = -1; try {/* ww w.ja v a 2 s . c o m*/ port = Integer.parseInt(properties.getProperty("port", "-1")); mongo = port != -1 ? new Mongo(host, port) : new Mongo(host); } catch (Throwable ex) { throw new StatsEngineException("Initializing mongo connection", ex); } String dbName = properties.getProperty(DB_NAME, DEFAULT_DB_NAME); try { db = mongo.getDB(dbName); } catch (Throwable ex) { throw new StatsEngineException("Getting db " + dbName, ex); } setKeepEvents(Boolean.valueOf(properties.getProperty("events.keep", "true"))); setCountEvents(Boolean.valueOf(properties.getProperty("events.count", "true"))); setTimeScopePrecision(properties.getProperty("precision", DEFAULT_TIMESCOPE_PRECISION.name())); initCollections(); initFunctions(); }
From source file:org.mule.modules.morphia.MorphiaConnector.java
License:Open Source License
/** * Construct a new instance of Morphia// ww w.ja v a 2 s.c o m */ @PostConstruct public void init() throws ClassNotFoundException { this.mongoCache = CacheBuilder.newBuilder().maximumSize(10).build(new CacheLoader<MongoCacheKey, Mongo>() { public Mongo load(MongoCacheKey cacheKey) { return new Mongo(cacheKey.getSeeds(), cacheKey.getOptions()); } }); this.datastoreCache = CacheBuilder.newBuilder().maximumSize(50) .build(new CacheLoader<MorphiaCacheKey, Datastore>() { private Morphia morphia; @Override public Datastore load(MorphiaCacheKey morphiaCacheKey) throws Exception { initMorphia(); List<ServerAddress> seeds = getSeeds(morphiaCacheKey.getHost(), morphiaCacheKey.getPort()); MongoCacheKey mongoCacheKey = new MongoCacheKey(seeds, getMongoOptions()); Mongo mongo = mongoCache.get(mongoCacheKey); Datastore datastore = this.morphia.createDatastore(mongo, morphiaCacheKey.getDatabase(), morphiaCacheKey.getUsername(), morphiaCacheKey.getPassword().toCharArray()); datastore.ensureIndexes(ensureIndexesOnBackground); datastore.ensureCaps(); return datastore; } private void initMorphia() throws ClassNotFoundException { if (morphia == null) { morphia = new Morphia(); if (classes != null) { for (String className : classes) { this.morphia.map(Class.forName(className)); } } if (packages != null) { for (String packageName : packages) { this.morphia.mapPackage(packageName, ignoreInvalidClasses); } } } } private List<ServerAddress> getSeeds(String host, int port) throws UnknownHostException { List<ServerAddress> seeds = new ArrayList<ServerAddress>(); if (host.indexOf(',') != -1) { StringTokenizer tokenizer = new StringTokenizer(host, ","); while (tokenizer.hasMoreTokens()) { seeds.add(new ServerAddress(tokenizer.nextToken(), port)); } } else { seeds.add(new ServerAddress(host, port)); } return seeds; } private MongoOptions getMongoOptions() { MongoOptions options = new MongoOptions(); if (connectionsPerHost != null) options.connectionsPerHost = connectionsPerHost; if (threadsAllowedToBlockForConnectionMultiplier != null) options.threadsAllowedToBlockForConnectionMultiplier = threadsAllowedToBlockForConnectionMultiplier; if (maxWaitTime != null) options.maxWaitTime = maxWaitTime; if (connectTimeout != null) options.connectTimeout = connectTimeout; if (socketTimeout != null) options.socketTimeout = socketTimeout; if (autoConnectRetry != null) options.autoConnectRetry = autoConnectRetry; if (slaveOk != null) options.slaveOk = slaveOk; if (safe != null) options.safe = safe; if (w != null) options.w = w; if (wtimeout != null) options.wtimeout = wtimeout; if (fsync != null) options.fsync = fsync; return options; } }); }
From source file:org.nutz.mongodb.log2mongodb.log4j.MongoDbAppender.java
License:Open Source License
@Override public void activateOptions() { try {// w ww.ja v a 2 s.c o m Mongo mongo = new Mongo(hostname, port); DB database = mongo.getDB(databaseName); if (userName != null && userName.trim().length() > 0) { if (!database.authenticate(userName, password)) { throw new RuntimeException("Unable to authenticate with MongoDB server."); } // Allow password to be GCed password = null; } collection = database.getCollection(collectionName); } catch (Exception e) { errorHandler.error("Unexpected exception while initialising MongoDbAppender.", e, ErrorCode.GENERIC_FAILURE); } }
From source file:org.pentaho.di.trans.steps.mongodbupdate.MongoDbUpdate.java
License:Open Source License
public boolean init(StepMetaInterface stepMetaInterface, StepDataInterface stepDataInterface) { if (super.init(stepMetaInterface, stepDataInterface)) { meta = (MongoDbUpdateMeta) stepMetaInterface; data = (MongoDbUpdateData) stepDataInterface; String hostname = environmentSubstitute(meta.getHostname()); int port = Const.toInt(environmentSubstitute(meta.getPort()), 27017); String db = environmentSubstitute(meta.getDbName()); String collection = environmentSubstitute(meta.getCollection()); try {//from w w w . j a v a 2 s.co m data.primaryQuery = (DBObject) (JSON.parse(environmentSubstitute(meta.getPrimaryQuery()))); } catch (Exception e) { logError(e.getMessage()); data.primaryQuery = (DBObject) (JSON.parse("{}")); } try { data.mongo = new Mongo(hostname, port); data.db = data.mongo.getDB(db); String realUser = environmentSubstitute(meta.getAuthenticationUser()); String realPass = Encr.decryptPasswordOptionallyEncrypted( environmentSubstitute(meta.getAuthenticationPassword())); if (!Const.isEmpty(realUser) || !Const.isEmpty(realPass)) { if (!data.db.authenticate(realUser, realPass.toCharArray())) { throw new KettleException( BaseMessages.getString(PKG, "MongoDbUpdate.ErrorAuthenticating.Exception")); } } data.collection = data.db.getCollection(collection); return true; } catch (Exception e) { logError(BaseMessages.getString(PKG, "MongoDbUpdate.ErrorConnectingToMongoDb.Exception", hostname, "" + port, db, collection), e); return false; } } else { return false; } }
From source file:org.restlet.example.ext.oauth.server.OAuth2Sample.java
License:LGPL
public static void main(String[] args) throws Exception { // Setup MongoDB mongo = new Mongo("localhost", 27017); // Setup Restlet Component component = new Component(); component.getClients().add(Protocol.HTTP); component.getClients().add(Protocol.HTTPS); component.getClients().add(Protocol.RIAP); component.getClients().add(Protocol.CLAP); component.getServers().add(Protocol.HTTP, 8080); component.getDefaultHost().attach("/sample", new SampleApplication()); OAuth2ServerApplication app = new OAuth2ServerApplication(); component.getDefaultHost().attach("/oauth", app); component.getInternalRouter().attach("/oauth", app); component.start();/*ww w. j a va 2s . c o m*/ }
From source file:org.rnott.places.MongoDB.java
License:Apache License
public MongoDB() { // TODO: look into 'strict' write setting /*//from w w w . j a v a 2 s. c o m * http://stackoverflow.com/questions/6520439/how-to-configure-mongodb-java-driver-mongooptions-for-production-use * * autoConnectRetry * Simply means the driver will automatically attempt to reconnect to the server(s) after unexpected disconnects. * In production environments you usually want this set to true. * * connectionsPerHost * the amount of physical connections a single Mongo instance (it's singleton so you usually have one per application) * can establish to a mongod/mongos process. At time of writing the java driver will establish this amount of connections eventually even if the * actual query throughput is low (in order words you will see the "conn" statistic in mongostat rise until it hits this number per app server). * There is no need to set this higher than 100 in most cases but this setting is one of those "test it and see" things. Do note that you will have * to make sure you set this low enough so that the total amount of connections to your server do not exceed db.serverStatus().connections.available. * In production we currently have this at 40. * * connectTimeout * As the name suggest number of milliseconds the driver will wait before a connection attempt is aborted. Keep the default unless there's a * realistic, expected change this will be in the way of otherwise successful connection attempts. * * maxWaitTime * Number of ms a thread will wait for a connection to become available on the connection pool, and raises an exception if this does not happen * in time. Keep default. * * socketTimeout * Standard socket timeout value. Keep default. * * threadsAllowedToBlockForConnectionMultiplier * Number of threads that are allowed to wait for connections to become available if the pool is currently exhausted. This is the setting that will * cause the "com.mongodb.DBPortPool$SemaphoresOut: Out of semaphores to get db connection" exception. It will throw this exception once this thread * queue exceeds the threadsAllowedToBlockForConnectionMultiplier value. If you expect big peaks in throughput that could case large queues temporarily * increase this value. We have it at 1500 at the moment for exactly that reason. If your query load consistently outpaces the server you should just * improve your hardware/scaling situation accordingly. * * slaveOk * Very important for increased read performance if you use replica sets. This basically allows mongo to direct reads to non-primary replica members, * spreading the read load. Note that this can also be configured per query in your code. If you use replica sets (and you should) and you can live * with eventual consistency issues (meaning your secondaries might be slightly behind the primary's state) enable this. * * safe * When enabled the driver is forced to send a getLastError() command to the server after every write operation. This ensures that any possible problems * (unique constraint violations, query issues, etc.) are noticed on the client side and possibly throw an error. It defaults to false but you should set * this to true and change the WriteConcern of your updates if, and only if, you know you will not care about the result of the update and/or desperately * require additional performance. * * w * Oddly named parameter ;). If safe = true and w > 0 it determines the amount of replica set members a write has to be propogated to before considering * it successful. Use this for increased durability at the (considerable) expense of throughput. * * fsync * Durability option that forces mongo to flush to disk after each write when enabled. I've never had any durability issues related to a write backlog so * we have this on false (the default) in production. */ MongoOptions options = new MongoOptions(); options.autoConnectRetry = true; //options.slaveOk = true; see ReadPreference.SECONDARY options.safe = true; options.fsync = true; // durability is a must if (env == null) { //throw new RuntimeException( "Runtime environment is not injected" ); // TODO: runtime environment bean is not being injected env = new Environment(); env.initialize(); } try { ServerAddress addr = new ServerAddress(env.getDatabaseHost(), env.getDatabasePort()); mongo = new Mongo(addr, options); } catch (UnknownHostException e) { throw new RuntimeException("Failed to locate MongoDB", e); } catch (MongoException e) { throw new RuntimeException("Failed MongoDB initialization", e); } // authenticate logger.info("Initializing database: {}", env.getDatabaseName()); logger.info(env.toString()); mongo.getDB(env.getDatabaseName()).authenticate(env.getDatabaseUser(), env.getDatabasePassword().toCharArray()); // initialize Morphia morphia = new Morphia(); // set up mapping for entity types for (Class<?> c : MAPPED_CLASSES) { morphia.map(c); } // enable JSR303 Validation // this is extended so that it can respond to dynamic validation groups // TODO: re-enable validation after figuring out how to deal with Address issues (when embedded in Place, city and postal code may be null) //new DynamicValidationExtension( morphia ); }
From source file:org.sculptor.framework.accessimpl.mongodb.DbManager.java
License:Apache License
@SuppressWarnings("deprecation") private synchronized void init() { if (initialized) { return;//from ww w . j av a 2 s. c o m } 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.springframework.data.document.mongodb.log4j.MongoLog4jAppender.java
License:Apache License
protected void connectToMongo() throws UnknownHostException { this.mongo = new Mongo(host, port); this.db = mongo.getDB(database); }
From source file:org.springframework.social.connect.mongo.ApplicationConfig.java
License:Apache License
public @Bean MongoDbFactory mongoDbFactory() throws Exception { return new SimpleMongoDbFactory( new Mongo(env.getProperty("mongo.hostName"), env.getProperty("mongo.portNumber", Integer.class)), env.getProperty("mongo.databaseName")); }