List of usage examples for com.mongodb Mongo getDB
@Deprecated public DB getDB(final String dbName)
From source file:org.springframework.data.mongodb.core.MongoDbUtils.java
License:Apache License
private static DB doGetDB(Mongo mongo, String databaseName, UserCredentials credentials, boolean allowCreate, String authenticationDatabaseName) { DbHolder dbHolder = (DbHolder) TransactionSynchronizationManager.getResource(mongo); // Do we have a populated holder and TX sync active? if (dbHolder != null && !dbHolder.isEmpty() && TransactionSynchronizationManager.isSynchronizationActive()) { DB db = dbHolder.getDB(databaseName); // DB found but not yet synchronized if (db != null && !dbHolder.isSynchronizedWithTransaction()) { LOGGER.debug("Registering Spring transaction synchronization for existing MongoDB {}.", databaseName);/*from ww w . ja v a2 s. co m*/ TransactionSynchronizationManager .registerSynchronization(new MongoSynchronization(dbHolder, mongo)); dbHolder.setSynchronizedWithTransaction(true); } if (db != null) { return db; } } // Lookup fresh database instance LOGGER.debug("Getting Mongo Database name=[{}]", databaseName); DB db = mongo.getDB(databaseName); if (!(mongo instanceof MongoClient) && requiresAuthDbAuthentication(credentials)) { ReflectiveDbInvoker.authenticate(mongo, db, credentials, authenticationDatabaseName); } // TX sync active, bind new database to thread if (TransactionSynchronizationManager.isSynchronizationActive()) { LOGGER.debug("Registering Spring transaction synchronization for MongoDB instance {}.", databaseName); DbHolder holderToUse = dbHolder; if (holderToUse == null) { holderToUse = new DbHolder(databaseName, db); } else { holderToUse.addDB(databaseName, db); } // synchronize holder only if not yet synchronized if (!holderToUse.isSynchronizedWithTransaction()) { TransactionSynchronizationManager .registerSynchronization(new MongoSynchronization(holderToUse, mongo)); holderToUse.setSynchronizedWithTransaction(true); } if (holderToUse != dbHolder) { TransactionSynchronizationManager.bindResource(mongo, holderToUse); } } // Check whether we are allowed to return the DB. if (!allowCreate && !isDBTransactional(db, mongo)) { throw new IllegalStateException("No Mongo DB bound to thread, " + "and configuration does not allow creation of non-transactional one here"); } return db; }
From source file:org.springframework.data.mongodb.core.ReflectiveDbInvoker.java
License:Apache License
/** * Authenticate against database using provided credentials in case of a MongoDB Java driver version 2. * * @param mongo must not be {@literal null}. * @param db must not be {@literal null}. * @param credentials must not be {@literal null}. * @param authenticationDatabaseName//w w w . java 2s.c o m */ public static void authenticate(Mongo mongo, DB db, UserCredentials credentials, String authenticationDatabaseName) { String databaseName = db.getName(); DB authDb = databaseName.equals(authenticationDatabaseName) ? db : mongo.getDB(authenticationDatabaseName); synchronized (authDb) { Boolean isAuthenticated = (Boolean) invokeMethod(DB_IS_AUTHENTICATED_METHOD, authDb); if (!isAuthenticated) { String username = credentials.getUsername(); String password = credentials.hasPassword() ? credentials.getPassword() : null; Boolean authenticated = (Boolean) invokeMethod(DB_AUTHENTICATE_METHOD, authDb, username, password == null ? null : password.toCharArray()); if (!authenticated) { throw new CannotGetMongoDbConnectionException( "Failed to authenticate to database [" + databaseName + "], " + credentials.toString(), databaseName, credentials); } } } }
From source file:org.stocker.PingVerticle.java
License:Apache License
public void start() { JsonObject appConfig = container.config(); JsonObject dbConfig = appConfig.getObject("mongo-persistor"); Yoke yoke = new Yoke(this.vertx); DB mongoDB = null;//from www . j a v a 2s. c o m try { Mongo mongo = new Mongo(dbConfig.getString("host"), dbConfig.getInteger("port")); mongoDB = mongo.getDB(dbConfig.getString("db_name")); } catch (UnknownHostException e) { e.printStackTrace(); } final DBCollection stockCollection = mongoDB.getCollection("stocks"); //TODO : inject these guys from a shared module which is a singleton instance // these guys -> AsyncHttpClient asyncHttpClient = new AsyncHttpClient(); ZipReader zipReader = new ZipReaderImpl(); StockDBClient stockDBClient = new StockDBClientImpl(stockCollection); StockDataClient stockDataClient = new StockDataClientImpl(asyncHttpClient, zipReader); DataAggregator dataAggregator = new DataAggregator(stockDBClient); PredictionService predictionService = new PredictionService(dataAggregator); // ^ these guys // routes GetPredictionTemplatedRoute getPredictionTemplatedRoute = new GetPredictionTemplatedRoute( predictionService); GetPredictionRoute getPredictionRoute = new GetPredictionRoute(predictionService); UpdateRecordsRoute updateRecordsRoute = new UpdateRecordsRoute(stockDataClient, stockDBClient); GetStockRoute getStockRoute = new GetStockRoute(stockDBClient); GetAggregatedDataTemplatedRoute getAggregatedDataTemplatedRoute = new GetAggregatedDataTemplatedRoute( dataAggregator); GetAggregatedDataRoute getAggregatedDataRoute = new GetAggregatedDataRoute(dataAggregator); Router router = new Router(); router.get("/healthCheck", new HealthCheck()); router.post("/update/stocks/:date", updateRecordsRoute); router.get("/stock/:stock/date/:date", getStockRoute); router.get("/prediction/stock/:stock/type/:type", getPredictionTemplatedRoute); router.get("/prediction/stock/:stock", getPredictionRoute); router.get("/data/stock/:stock/type/:type", getAggregatedDataTemplatedRoute); router.get("/data/stock/:stock", getAggregatedDataRoute); yoke.use(new com.jetdrone.vertx.yoke.middleware.Logger()).use(new BodyParser()).use(router).listen(4080); //populateDB(updateRecordsRoute); container.logger().info("PingVerticle started : 4080"); System.out.println("PingVerticle.start - "); }
From source file:org.thiesen.troy.TroyORMDAOFactory.java
License:Open Source License
private TroyORMDAOFactory(final String database, final String host, final int port, final TypeConversionMap conversionMap) throws UnknownHostException, MongoException { super();/*from w w w.j av a2s . co m*/ final Mongo m = new Mongo(host, port); _dbConnection = m.getDB(database); _conversionMap = conversionMap; }
From source file:org.unitedid.shibboleth.attribute.resolver.provider.dataConnector.MongoDbDataConnector.java
License:Apache License
/** * Creates the mongo database connection *//*from w w w .ja v a 2 s .c om*/ protected void initializeMongoDbConnection() { if (initialized) { log.debug("MongoDB connector initializing!"); Mongo mongoCon = new Mongo(mongoHost); mongoCon.setReadPreference(getPreferredRead()); db = mongoCon.getDB(mongoDbName); if (getMongoUser() != null && getMongoPassword() != null) { boolean dbAuth = db.authenticate(getMongoUser(), getMongoPassword().toCharArray()); if (!dbAuth) { log.error( "MongoDB data connector {} authentication failed for database {}, username or password!", getId(), mongoDbName); throw new MongoException("MongoDB data connector " + getId() + " authentication failed!"); } else { log.debug("MongoDB data connector {} authentication successful!", getId()); } } } }
From source file:org.uom.fit.level2.datavis.repository.ChatServicesImpl.java
@Override public JSONArray getAll() { try {/* w ww. jav a 2 s.c o m*/ Mongo mongo = new Mongo("localhost", 27017); DB db = mongo.getDB("datarepo"); DBCollection collection = db.getCollection("user"); DBCursor cursor = collection.find(); JSON json = new JSON(); String dataUser = json.serialize(cursor); JSONParser parser = new JSONParser(); Object obj = parser.parse(dataUser); JSONArray jsonarray = (JSONArray) obj; return jsonarray; } catch (Exception e) { System.out.println("Exception Error getAll"); return null; } }
From source file:org.uom.fit.level2.datavis.repository.ChatServicesImpl.java
@Override public boolean saveChatData(ChatData chatData) { try {/*from w w w . j ava 2 s . c o m*/ Mongo mongo = new Mongo("localhost", 27017); DB db = mongo.getDB("datarepo"); DBCollection collection = db.getCollection("message"); Gson gson = new Gson(); DBObject dbObject = (DBObject) JSON.parse(gson.toJson(chatData)); WriteResult result = collection.insert(WriteConcern.SAFE, dbObject); return true; } catch (Exception e) { System.out.println("Exception Error createProect"); return false; } }
From source file:org.uom.fit.level2.datavis.repository.ChatServicesImpl.java
@Override public JSONArray getAllChatData(String message) { try {//from ww w . j a v a2s . c o m Mongo mongo = new Mongo("localhost", 27017); DB db = mongo.getDB("chat"); DBCollection collection = db.getCollection("message"); BasicDBObject whereQuery = new BasicDBObject(); BasicDBObject field = new BasicDBObject(); BasicDBObject sortQuery = new BasicDBObject(); whereQuery.put("message", message); field.put("senderName", 1); field.put("message", 1); field.put("receiverName", 1); field.put("imageData", 1); field.put("discription", 1); sortQuery.put("DateTime", 1); DBCursor cursor = collection.find(whereQuery, field).sort(sortQuery); JSON json = new JSON(); String dataUser = json.serialize(cursor); JSONParser parser = new JSONParser(); Object obj = parser.parse(dataUser); JSONArray jsonarray = (JSONArray) obj; return jsonarray; } catch (Exception e) { System.out.println("Exception Error getAll"); return null; } }
From source file:org.uom.fit.level2.datavis.repository.ChatServicesImpl.java
@Override public JSONArray getAllChatDataAllMessage() { try {/* w ww . j av a2 s.c om*/ Mongo mongo = new Mongo("localhost", 27017); DB db = mongo.getDB("chat"); DBCollection collection = db.getCollection("message"); List<String> lst = collection.distinct("message"); String json = new Gson().toJson(lst); JSONArray jsonarray = (JSONArray) new JSONParser().parse(json); return jsonarray; } catch (Exception e) { System.out.println("Exception Error getAllChatDataAllMEssage"); return null; } }
From source file:piecework.repository.concrete.EmbeddedMongoInstance.java
License:Educational Community License
public void importData() throws Exception { Mongo mongo = new Mongo(bindIp, port); DB db = mongo.getDB(dbName); File directory = new File(storePath, "dbs"); if (!directory.exists()) { LOG.debug("No startup data exists"); return;//from w w w. j a va 2 s .co m } File dbDirectory = new File(directory, dbName); if (!dbDirectory.exists()) { LOG.debug("No startup data exists for " + dbName); return; } File[] collectionFiles = dbDirectory.listFiles(); for (File collectionFile : collectionFiles) { if (collectionFile.isFile() && collectionFile.exists()) { String collectionName = collectionFile.getName(); LOG.debug("Loading collection '" + collectionName + "'..."); DBCollection dbCollection = db.getCollection(collectionName); try { LOG.debug("Loading JSON from file '" + collectionFile.getName() + "'"); importCollection(dbCollection, new FileInputStream(collectionFile)); } catch (FileNotFoundException fnfe) { LOG.warn("Unable to initialize local mongo with data from " + collectionFile.getAbsolutePath(), fnfe); } } } mongo.close(); }