Java Code Examples for com.mongodb.MongoClient#getDB()
The following examples show how to use
com.mongodb.MongoClient#getDB() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MongoDB.java From jelectrum with MIT License | 6 votes |
public MongoDB(Config config) throws Exception { super(config); conf.require("mongo_db_host"); conf.require("mongo_db_name"); conf.require("mongo_db_connections_per_host"); MongoClientOptions.Builder opts = MongoClientOptions.builder(); opts.connectionsPerHost(conf.getInt("mongo_db_connections_per_host")); opts.threadsAllowedToBlockForConnectionMultiplier(100); opts.socketTimeout(3600000); mc = new MongoClient(new ServerAddress(conf.get("mongo_db_host")), opts.build()); db = mc.getDB(conf.get("mongo_db_name")); open(); }
Example 2
Source File: MongoDBOutputOperator.java From attic-apex-malhar with Apache License 2.0 | 6 votes |
/** * At setup time, init last completed windowId from maxWindowTable * * @param context */ @Override public void setup(OperatorContext context) { operatorId = context.getId(); try { mongoClient = new MongoClient(hostName); db = mongoClient.getDB(dataBase); if (userName != null && passWord != null) { db.authenticate(userName, passWord.toCharArray()); } initLastWindowInfo(); for (String table : tableList) { tableToDocumentList.put(table, new ArrayList<DBObject>()); tableToDocument.put(table, new BasicDBObject()); } } catch (UnknownHostException ex) { logger.debug(ex.toString()); } }
Example 3
Source File: MongoDBTestHelper.java From brooklyn-library with Apache License 2.0 | 6 votes |
public static boolean isConfigServer(AbstractMongoDBServer entity) { LOG.info("Checking if {} is a config server", entity); MongoClient mongoClient = clientForServer(entity); try { DB db = mongoClient.getDB(ADMIN_DB); CommandResult commandResult = db.command("getCmdLineOpts"); Map<?, ?> parsedArgs = (Map<?, ?>)commandResult.get("parsed"); if (parsedArgs == null) return false; Boolean configServer = (Boolean)parsedArgs.get("configsvr"); if (configServer != null) { // v2.5 format return Boolean.TRUE.equals(configServer); } else { // v2.6 format String role = (String) ((Map)parsedArgs.get("sharding")).get("clusterRole"); return "configsvr".equals(role); } } finally { mongoClient.close(); } }
Example 4
Source File: MongoReader.java From deep-spark with Apache License 2.0 | 5 votes |
/** * Init void. * * @param partition the partition */ public void init(Partition partition) { try { List<ServerAddress> addressList = new ArrayList<>(); for (String s : (List<String>) ((DeepPartition) partition).splitWrapper().getReplicas()) { addressList.add(new ServerAddress(s)); } //Credentials List<MongoCredential> mongoCredentials = new ArrayList<>(); if (mongoDeepJobConfig.getUsername() != null && mongoDeepJobConfig.getPassword() != null) { MongoCredential credential = MongoCredential.createMongoCRCredential(mongoDeepJobConfig.getUsername(), mongoDeepJobConfig.getDatabase(), mongoDeepJobConfig.getPassword().toCharArray()); mongoCredentials.add(credential); } mongoClient = new MongoClient(addressList, mongoCredentials); mongoClient.setReadPreference(ReadPreference.valueOf(mongoDeepJobConfig.getReadPreference())); db = mongoClient.getDB(mongoDeepJobConfig.getDatabase()); collection = db.getCollection(mongoDeepJobConfig.getCollection()); dbCursor = collection.find(generateFilterQuery((MongoPartition) partition), mongoDeepJobConfig.getDBFields()); } catch (UnknownHostException e) { throw new DeepExtractorInitializationException(e); } }
Example 5
Source File: MongoSinkUpdateInsteadReplaceTest.java From ingestion with Apache License 2.0 | 5 votes |
private void injectFongo(MongoSink mongoSink) { try { MongoClient mongoClient = fongo.getMongo(); DB mongoDefaultDb = mongoClient.getDB("test"); DBCollection mongoDefaultCollection = mongoDefaultDb.getCollection("test"); setField(mongoSink, "mongoClient", mongoClient); setField(mongoSink, "mongoDefaultDb", mongoDefaultDb); setField(mongoSink, "mongoDefaultCollection", mongoDefaultCollection); } catch (Exception ex) { throw new RuntimeException(ex); } }
Example 6
Source File: DatabaseTools.java From hvdf with Apache License 2.0 | 5 votes |
public static void dropDatabaseByURI(MongoClientURI uri, String dbName) throws UnknownHostException{ MongoClient client = new MongoClient(uri); DB database = client.getDB(dbName); database.dropDatabase(); client.close(); }
Example 7
Source File: MongoWrapper.java From xDrip-plus with GNU General Public License v3.0 | 5 votes |
public DBCollection openMongoDb() throws UnknownHostException { MongoClientURI dbUri = new MongoClientURI(dbUriStr_+"?socketTimeoutMS=180000"); mongoClient_ = new MongoClient(dbUri); DB db = mongoClient_.getDB( dbName_ ); DBCollection coll = db.getCollection(collection_); coll.createIndex(new BasicDBObject(index_, 1)); // create index on "i", ascending return coll; }
Example 8
Source File: MongoDBTestHelper.java From brooklyn-library with Apache License 2.0 | 5 votes |
/** @return The {@link DBObject} representing the object with the given id */ public static DBObject getById(AbstractMongoDBServer entity, String id) { LOG.info("Getting {} from {}", new Object[]{id, entity}); MongoClient mongoClient = clientForServer(entity); // Secondary preferred means the driver will let us read from secondaries too. mongoClient.setReadPreference(ReadPreference.secondaryPreferred()); try { DB db = mongoClient.getDB(TEST_DB); DBCollection testCollection = db.getCollection(TEST_COLLECTION); return testCollection.findOne(new BasicDBObject("_id", new ObjectId(id))); } finally { mongoClient.close(); } }
Example 9
Source File: GroupResourceTest.java From sample-acmegifts with Eclipse Public License 1.0 | 5 votes |
/** Connect to the Mongo database "groups" */ @BeforeClass public static void setup() throws UnknownHostException { int mongoPort = Integer.parseInt(System.getProperty("mongo.test.port")); String mongoHostname = System.getProperty("mongo.test.hostname"); mongo = new MongoClient(mongoHostname, mongoPort); db = mongo.getDB("gifts-group"); }
Example 10
Source File: MongoSinkDynamicTest.java From ingestion with Apache License 2.0 | 5 votes |
private void injectFongo(MongoSink mongoSink) { try { MongoClient mongoClient = fongo.getMongo(); DB mongoDefaultDb = mongoClient.getDB("test"); DBCollection mongoDefaultCollection = mongoDefaultDb.getCollection("test"); setField(mongoSink, "mongoClient", mongoClient); setField(mongoSink, "mongoDefaultDb", mongoDefaultDb); setField(mongoSink, "mongoDefaultCollection", mongoDefaultCollection); } catch (Exception ex) { throw new RuntimeException(ex); } }
Example 11
Source File: MongoAccess.java From sample-acmegifts with Eclipse Public License 1.0 | 5 votes |
/** Get a connection to Mongo */ public synchronized DB getMongoDB() { if (database == null) { try { MongoClient client = new MongoClient(mongoHostname, mongoPort); database = client.getDB("gifts-occasion"); } catch (UnknownHostException uhe) { throw new RuntimeException(uhe); } } return database; }
Example 12
Source File: MongoDBClientSupport.java From brooklyn-library with Apache License 2.0 | 5 votes |
public boolean ping() { MongoClient client = fastClient(); DBObject command = new BasicDBObject("ping", "1"); final DB db = client.getDB("admin"); try { CommandResult status = db.command(command); return status.ok(); } catch (MongoException e) { LOG.warn("Pinging server {} failed with {}", address.getHost(), e); } finally { client.close(); } return false; }
Example 13
Source File: DeviceManagerController.java From SI with BSD 2-Clause "Simplified" License | 5 votes |
public DeviceManagerController() { contextBrokerAddress = "http://" + HeritProperties.getProperty("Globals.fiwareServerHost") + ":" + HeritProperties.getProperty("Globals.fiwareServerPort"); fiwareService = HeritProperties.getProperty("Globals.fiwareService"); fiwareServicePath = HeritProperties.getProperty("Globals.fiwareServicePath"); fiwareAgentAccessKey = HeritProperties.getProperty("Globals.fiwareAgentAccessKey"); fiwareAgentUrl = HeritProperties.getProperty("Globals.fiwareAgentUrl"); // added in 2017-09-18 mongoClient = new MongoClient(HeritProperties.getProperty("Globals.MongoDB.Host"), Integer.parseInt( HeritProperties.getProperty("Globals.MongoDB.Port") ) ); //db = mongoClient.getDatabase(HeritProperties.getProperty("Globals.MongoDB.DBName")); db = mongoClient.getDB(HeritProperties.getProperty("Globals.MongoDB.DBName")); }
Example 14
Source File: MongoAccess.java From sample-acmegifts with Eclipse Public License 1.0 | 5 votes |
/** Get a connection to Mongo. */ public synchronized DB getMongoDB() { if (database == null) { try { MongoClient client = new MongoClient(mongoHostname, mongoPort); database = client.getDB("gifts-user"); } catch (UnknownHostException uhe) { throw new RuntimeException(uhe); } } return database; }
Example 15
Source File: MongoDBClientSupport.java From brooklyn-library with Apache License 2.0 | 5 votes |
private Optional<CommandResult> runDBCommand(String database, final DBObject command) { MongoClient client = client(); try { final DB db = client.getDB(database); final CommandResult[] status = new CommandResult[1]; // The mongoDB client can occasionally fail to connect. Try up to 5 times to run the command boolean commandResult = Repeater.create().backoff(Duration.ONE_SECOND, 1.5, null).limitIterationsTo(5) .until(new Callable<Boolean>() { @Override public Boolean call() throws Exception { try { status[0] = db.command(command); return true; } catch (Exception e) { LOG.warn("Command " + command + " on " + address.getHost() + " failed", e); return false; } } }).run(); if (!commandResult) { return Optional.absent(); } if (!status[0].ok()) { LOG.debug("Unexpected result of {} on {}: {}", new Object[] { command, getServerAddress(), status[0].getErrorMessage() }); } return Optional.of(status[0]); } finally { client.close(); } }
Example 16
Source File: MongoDataProxy.java From Knowage-Server with GNU Affero General Public License v3.0 | 4 votes |
private CommandResult loadData() { logger.debug("IN"); CommandResult result = null; String clientUrl = dataSource.getUrlConnection(); logger.debug("Getting the connection URL and db name"); if (dataSource.getUser() != null && dataSource.getPwd() != null && dataSource.getUser().length() > 0 && dataSource.getPwd().length() > 0) { String authPart = "mongodb://"+dataSource.getUser()+":"+dataSource.getPwd()+"@"; clientUrl = clientUrl.replace("mongodb://", authPart); } logger.debug("MongoDB connection URI:"+clientUrl); MongoClientURI mongoClientURI= new MongoClientURI(clientUrl); MongoClient mongoClient = new MongoClient(new MongoClientURI(clientUrl)); logger.debug("Connecting to mongodb"); String databaseName = mongoClientURI.getDatabase(); logger.debug("Database name: " + databaseName); try { logger.debug("Connecting to the db " + databaseName); DB database = mongoClient.getDB(databaseName); logger.debug("Executing the statement" + statement); result = database.doEval(getDecoredStatement()); } catch (Exception e) { logger.error("Exception executing the MongoDataset", e); throw new SpagoBIRuntimeException("Exception executing the MongoDataset", e); } finally { logger.debug("Closing connection"); mongoClient.close(); } logger.debug("OUT"); return result; }
Example 17
Source File: MongoConfiguration.java From cqrs-sample with MIT License | 4 votes |
public @Bean DB mongoDb() throws Exception { MongoClientURI mcUri = new MongoClientURI(getUrlConnection()); MongoClient mc = new MongoClient(mcUri); mc.getDB(mcUri.getDatabase()); return mc.getDB(mcUri.getDatabase()); }
Example 18
Source File: MongoConfiguration.java From cqrs-sample with MIT License | 4 votes |
public @Bean DB mongoDb() throws Exception { MongoClientURI mcUri = new MongoClientURI(getUrlConnection()); MongoClient mc = new MongoClient(mcUri); mc.getDB(mcUri.getDatabase()); return mc.getDB(mcUri.getDatabase()); }
Example 19
Source File: MongoWrapper.java From xDrip-Experimental with GNU General Public License v3.0 | 3 votes |
public DBCollection openMongoDb() throws UnknownHostException { MongoClientURI dbUri = new MongoClientURI(dbUriStr_+"?socketTimeoutMS=180000"); mongoClient_ = new MongoClient(dbUri); DB db = mongoClient_.getDB( dbName_ ); DBCollection coll = db.getCollection(collection_); coll.createIndex(new BasicDBObject(index_, 1)); // create index on "i", ascending return coll; }
Example 20
Source File: MongoEntityPersister.java From aw-reporting with Apache License 2.0 | 2 votes |
/** * Constructor that opens MongoDB client from URL, and retrives specified database. * * @param mongoConnectionUrl the Mongo connection url * @param mongoDataBaseName the Mongo database name */ public MongoEntityPersister(String mongoConnectionUrl, String mongoDataBaseName) throws UnknownHostException, MongoException { mongoClient = new MongoClient(new MongoClientURI(mongoConnectionUrl)); db = mongoClient.getDB(mongoDataBaseName); }