Example usage for com.mongodb Mongo getDB

List of usage examples for com.mongodb Mongo getDB

Introduction

In this page you can find the example usage for com.mongodb Mongo getDB.

Prototype

@Deprecated 
public DB getDB(final String dbName) 

Source Link

Document

Gets a database object.

Usage

From source file:org.cloudifysource.mongodb.AbstractMongoPlugin.java

License:Open Source License

/**
* Opens connection to mongoDB//  www . j a  v  a  2s. c o  m
*/
public void init() {
    try {
        host = (String) config.get("host");
        if (host == null)
            host = DEFAULT_HOST;

        log.info("AbstractMongoPlugin.init: using host " + host);
        int instanseID = serviceContext.getInstanceId();
        log.info("AbstractMongoPlugin.init: InstanceId is " + instanseID);

        port = (Integer) serviceContext.getAttributes().getThisInstance().get("port");
        log.info("AbstractMongoPlugin.init:port is " + port.intValue());

        dbName = (String) config.get("dbName");
        if (dbName == null)
            dbName = DEFAULT_DB_NAME;
        log.info("AbstractMongoPlugin.init:Connecting to mongodb " + dbName + "(" + host + "," + port + ")...");
        Mongo mongo = new Mongo(host, port);
        db = mongo.getDB(dbName);
        log.info("AbstractMongoPlugin.init:Connected to mongodb " + dbName);
        initialized = true;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.datacleaner.connection.MongoDbDatastore.java

License:Open Source License

@Override
protected UsageAwareDatastoreConnection<UpdateableDataContext> createDatastoreConnection() {
    try {/*from w  w  w  .  ja  va 2 s  . co m*/
        final Mongo mongo = new Mongo(_hostname, _port);
        final DB mongoDb = mongo.getDB(_databaseName);
        if (_username != null && _password != null) {
            final boolean authenticated = mongoDb.authenticate(_username, _password);
            if (!authenticated) {
                logger.warn("Autheticate returned false!");
            }
        }

        final UpdateableDataContext dataContext;
        if (_tableDefs == null || _tableDefs.length == 0) {
            dataContext = new MongoDbDataContext(mongoDb);
        } else {
            dataContext = new MongoDbDataContext(mongoDb, _tableDefs);
        }
        return new UpdateableDatastoreConnectionImpl<UpdateableDataContext>(dataContext, this);
    } catch (Exception e) {
        if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        }
        throw new IllegalStateException("Failed to connect to MongoDB instance: " + e.getMessage(), e);
    }
}

From source file:org.eclipse.birt.data.oda.mongodb.impl.MDbConnection.java

License:Open Source License

public static DB getMongoDatabase(Properties connProperties) throws OdaException {
    Mongo mongoInstance = MongoDBDriver.getMongoNode(connProperties);
    if (!mongoInstance.getConnector().isOpen())
        throw new OdaException(Messages.mDbConnection_failedToOpenConn);

    // to avoid potential conflict in shared DB, ReadPreference is exposed
    // as cursorReadPreference in data set property

    String dbName = MongoDBDriver.getDatabaseName(connProperties);
    if (dbName == null || dbName.isEmpty())
        throw new OdaException(Messages.mDbConnection_missingValueDBName);

    // validate whether dbName exists
    Boolean dbExists = existsDatabase(mongoInstance, dbName, connProperties);
    if (dbExists != null && !dbExists) // does not exist for sure
    {//from w w  w  .ja  v a  2s  .co m
        // do not proceed to create new database instance
        throw new OdaException(Messages.bind(Messages.mDbConnection_invalidDatabaseName, dbName));
    }

    DB dbInstance = mongoInstance.getDB(dbName);
    authenticateDB(dbInstance, connProperties);
    return dbInstance;
}

From source file:org.eclipse.birt.data.oda.mongodb.impl.MDbConnection.java

License:Open Source License

private static Boolean existsDatabase(Mongo mongoInstance, String dbName, Properties connProps)
        throws OdaException {
    // check if user authentication is needed
    String username = MongoDBDriver.getUserName(connProps);
    if (username != null && !username.isEmpty()) {
        DB adminDb = mongoInstance.getDB("admin"); //$NON-NLS-1$
        try {//from   www . j av a2 s .co  m
            // login to admin db, so to get the existing database names
            authenticateDB(adminDb, connProps);
        } catch (OdaException ex) {
            // not able to determine if db exists; specified user is probably not a valid login user in admin db
            return null;
        }
    }

    try {
        return mongoInstance.getDatabaseNames().contains(dbName);
    } catch (MongoException ex) {
        throw new OdaException(ex); // unable to get db names
    }
}

From source file:org.eclipse.emf.cdo.server.internal.mongodb.MongoDBStore.java

License:Open Source License

@Override
protected void doActivate() throws Exception {
    InternalRepository repository = getRepository();
    branching = repository.isSupportingBranches();
    if (branching) {
        throw new IllegalStateException("Branching is not supported");
    }// ww w.j  a v a  2s.c  o m

    REPOS.put(repository.getName(), repository);

    super.doActivate();

    Mongo mongo = new Mongo(mongoURI);
    db = mongo.getDB(dbName);

    Set<String> collectionNames = db.getCollectionNames();
    firstStart = !collectionNames.contains(Props.NAME);

    props = new Props(this);
    commits = new Commits(this);
    classes = new Classes(this);

    LifecycleUtil.activate(idHandler);
    setObjectIDTypes(idHandler.getObjectIDTypes());

    Arrays.fill(valueHandlers, new ValueHandler());
    initValueHandlers();

    if (firstStart) {
        firstStart();
    } else {
        reStart();
    }
}

From source file:org.eclipse.emf.cdo.server.internal.mongodb.MongoDBStoreFactory.java

License:Open Source License

protected void dropDatabase(MongoURI mongoURI, String dbName) {
    Mongo mongo = null;

    try {/*from www .  j a v  a2  s .co  m*/
        mongo = new Mongo(mongoURI);
        DB db = mongo.getDB(dbName);
        db.dropDatabase();
    } catch (Exception ex) {
        throw WrappedException.wrap(ex);
    } finally {
        if (mongo != null) {
            mongo.close();
        }
    }
}

From source file:org.eclipse.emf.cdo.tests.mongodb.MongoDBConfig.java

License:Open Source License

protected void dropDatabase(MongoURI mongoURI, String repoName) {
    Mongo mongo = null;

    try {//from   w  w  w .j a  va  2s .  co  m
        mongo = new Mongo(mongoURI);
        DB db = mongo.getDB(repoName);
        if (!db.getCollectionNames().isEmpty()) {
            db.dropDatabase();
        }
    } catch (Exception ex) {
        throw WrappedException.wrap(ex);
    } finally {
        if (mongo != null) {
            mongo.close();
        }
    }
}

From source file:org.eclipse.jetty.nosql.mongodb.MongoSessionDataStoreFactory.java

License:Open Source License

/**
 * @throws MongoException/*from   w  w  w  . j  ava 2 s.co m*/
 * @throws UnknownHostException
 * @see org.eclipse.jetty.server.session.SessionDataStoreFactory#getSessionDataStore(org.eclipse.jetty.server.session.SessionHandler)
 */
@Override
public SessionDataStore getSessionDataStore(SessionHandler handler) throws Exception {
    MongoSessionDataStore store = new MongoSessionDataStore();
    store.setGracePeriodSec(getGracePeriodSec());
    store.setSavePeriodSec(getSavePeriodSec());
    Mongo mongo;

    if (!StringUtil.isBlank(getConnectionString()))
        mongo = new Mongo(new MongoURI(getConnectionString()));
    else if (!StringUtil.isBlank(getHost()) && getPort() != -1)
        mongo = new Mongo(getHost(), getPort());
    else if (!StringUtil.isBlank(getHost()))
        mongo = new Mongo(getHost());
    else
        mongo = new Mongo();
    store.setDBCollection(mongo.getDB(getDbName()).getCollection(getCollectionName()));
    return store;
}

From source file:org.eclipselabs.restlet.mongo.MongoResource.java

License:Open Source License

private DBCollection getCollection() throws UnknownHostException {
    // TODO consider using dependency injection instead of a service tracker for the IMongoDB
    // service//from  w  w  w.  j  a  v  a 2s.  c om

    IMongoDB mongoDB = Activator.getInstance().getMongoDB();
    Mongo mongo = mongoDB.getMongo(new MongoURI("mongodb://localhost"));
    DB db = mongo.getDB((String) getRequestAttributes().get("database"));
    DBCollection collection = db.getCollection((String) getRequestAttributes().get("collection"));
    return collection;
}

From source file:org.einherjer.week2.samples.DotNotationSample.java

License:Apache License

public static void main(String[] args) throws UnknownHostException {
    Mongo client = new Mongo();
    DB db = client.getDB("course");
    DBCollection lines = db.getCollection("dotNotationSample");
    lines.drop();//  w w w  .ja va2 s  . com
    Random rand = new Random();

    // insert 10 lines with random start and end points
    for (int i = 0; i < 10; i++) {
        lines.insert(
                new BasicDBObject("_id", i)
                        .append("start",
                                new BasicDBObject("x", rand.nextInt(90) + 10).append("y",
                                        rand.nextInt(90) + 10))
                        .append("end", new BasicDBObject("x", rand.nextInt(90) + 10).append("y",
                                rand.nextInt(90) + 10)));
    }

    QueryBuilder builder = QueryBuilder.start("start.x").greaterThan(50);

    DBCursor cursor = lines.find(builder.get(), new BasicDBObject("start.y", true).append("_id", false));

    try {
        while (cursor.hasNext()) {
            DBObject cur = cursor.next();
            System.out.println(cur);
        }
    } finally {
        cursor.close();
    }
}