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.helios.dashkuj.domain.Dashboard.java

License:Open Source License

public static void main(String[] args) {
    Jedis jedis = null;// w w  w. j  av  a 2  s  .  com
    Mongo mongo = null;
    DBCursor cursor = null;
    Morphia morphia = null;
    Datastore mongoDs = null;
    try {
        jedis = new Jedis("dashku");
        Map<String, String> apiKeys = jedis.hgetAll("apiKeys");
        log(apiKeys);
        mongo = new Mongo("dashku");
        morphia = new Morphia();
        mongoDs = morphia.createDatastore(mongo, "dashku_development");
        DB db = mongo.getDB("dashku_development");
        DBCollection dbColl = db.getCollection("users");
        cursor = dbColl.find();
        while (cursor.hasNext()) {
            DBObject dbo = cursor.next();
            String apiKey = dbo.get("apiKey").toString();
            String id = dbo.get("_id").toString();
            String user = dbo.get("username").toString();
            log("Inspecting user [" + user + "]");
            if (!apiKeys.containsKey(apiKey)) {
                jedis.hmset("apiKeys", Collections.singletonMap(apiKey, id));
                log("Added missing redis entry [" + apiKey + "] for user [" + user + "]");
            }
        }
        cursor.close();

        //         CommandResult cr = db.command("serverStatus");
        //         Date date = cr.getDate("localTime");
        //         
        //         JsonElement je = new JsonParser().parse(cr.toString());
        //         String jsDate = je.getAsJsonObject().get("localTime").getAsJsonObject().getAsJsonPrimitive("$date").toString();
        //         //log(GsonFactory.getInstance().printer().toJson(je));
        //         log("Date:[" + date + "]");
        //         log("JS-Date:[" + jsDate + "]");
    } catch (Exception ex) {
        ex.printStackTrace(System.err);
    } finally {
        if (jedis != null)
            try {
                jedis.disconnect();
            } catch (Exception ex) {
            }
        if (cursor != null)
            try {
                cursor.close();
            } catch (Exception ex) {
            }
        if (mongo != null)
            try {
                mongo.close();
            } catch (Exception ex) {
            }
    }
}

From source file:org.icgc.dcc.release.job.imports.hadoop.MongoAdminInputFormat.java

License:Open Source License

private static void authenticateAdmin(MongoURI mongoUri, Mongo hadoopMongo) {
    DB admin = hadoopMongo.getDB(MONGO_ADMIN_DATABASE_NAME);
    boolean authenticated = admin.authenticate(mongoUri.getUsername(), mongoUri.getPassword());

    checkState(authenticated, "Could not authenticate user '%s' to database '%s' using MongoURI '%s'", //
            mongoUri.getUsername(), MONGO_ADMIN_DATABASE_NAME, mongoUri);
}

From source file:org.iternine.jeppetto.testsupport.db.MongoDatabase.java

License:Apache License

@Override
public void close() {
    if (mongoDbName == null) {
        return;/*from  ww w. j  a  va 2  s .  c  o  m*/
    }

    try {
        Mongo mongo = new Mongo("127.0.0.1", mongoDbPort);
        DB db = mongo.getDB(mongoDbName);

        db.resetError();
        db.dropDatabase();

        DBObject err = db.getLastError();
        if (err != null && err.get("err") != null) {
            logger.error("Could not drop database {}: {}", mongoDbName, err);
        }

        mongo.dropDatabase(mongoDbName);

        if (mongo.getDatabaseNames().contains(mongoDbName)) {
            logger.error("Database {} will not go away!", mongoDbName);
        }
    } catch (UnknownHostException e) {
        // weird
    } catch (MongoException e) {
        logger.warn("Could not drop database {}: {}", mongoDbName, e.getMessage());
    }
}

From source file:org.javaee7.extra.mongo.PersonSessionBean.java

License:Open Source License

@PostConstruct
private void initDB() {
    try {/* w ww.  j  a v a 2  s  . c o  m*/
        // Start embedded Mongo
        MongodStarter runtime = MongodStarter.getDefaultInstance();
        mongodExe = runtime.prepare(new MongodConfigBuilder().version(Version.Main.PRODUCTION)
                .net(new Net(MONGO_PORT, Network.localhostIsIPv6())).build());
        mongod = mongodExe.start();

        // Get an instance of Mongo
        Mongo m = new Mongo("localhost", MONGO_PORT);
        DB db = m.getDB("personDB");
        personCollection = db.getCollection("persons");
        if (personCollection == null) {
            personCollection = db.createCollection("persons", null);
        }
    } catch (MongoException | IOException ex) {
        Logger.getLogger(PersonSessionBean.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.jeo.mongo.MongoOpts.java

License:Open Source License

public DB connect() throws IOException {
    ServerAddress server = new ServerAddress(host, port);
    Mongo mongo = new Mongo(server);
    DB database = mongo.getDB(db);
    database.authenticate(user, passwd != null ? passwd.get() : new char[] {});

    return database;
}

From source file:org.jimmyray.mongo.events.TailableCursorExample.java

License:Apache License

public static void main(final String[] pArgs) throws Exception {
    final Mongo mongo = new Mongo(new MongoURI("mongodb://127.0.0.1:29009"));

    mongo.getDB("testTailableCursor").dropDatabase();

    // Create the capped collection
    final BasicDBObject conf = new BasicDBObject("capped", true);
    conf.put("size", 20971520); // 20 MB
    mongo.getDB("testTailableCursor").createCollection("test", conf);

    final AtomicBoolean readRunning = new AtomicBoolean(true);
    final AtomicBoolean writeRunning = new AtomicBoolean(true);

    final AtomicLong writeCounter = new AtomicLong(0);
    final AtomicLong readCounter = new AtomicLong(0);

    final ArrayList<Thread> writeThreads = new ArrayList<Thread>();
    final ArrayList<Thread> readThreads = new ArrayList<Thread>();

    for (int idx = 0; idx < 10; idx++) {
        final Thread writeThread = new Thread(new Writer(mongo, writeRunning, writeCounter));
        final Thread readThread = new Thread(new Reader(mongo, readRunning, readCounter));
        writeThread.start();/*  ww  w .  j a va  2s . c  o m*/
        readThread.start();
        writeThreads.add(writeThread);
        readThreads.add(readThread);
    }

    // Run for five minutes
    //Thread.sleep(300000);
    Thread.sleep(20000);
    writeRunning.set(false);
    Thread.sleep(5000);
    readRunning.set(false);
    Thread.sleep(5000);

    for (final Thread readThread : readThreads)
        readThread.interrupt();
    for (final Thread writeThread : writeThreads)
        writeThread.interrupt();

    System.out.println("----- write count: " + writeCounter.get());
    System.out.println("----- read count: " + readCounter.get());
}

From source file:org.jongo.bench.BenchUtil.java

License:Apache License

public static DBCollection getCollectionFromDriver() throws UnknownHostException {
    Mongo nativeMongo = new MongoClient();
    return nativeMongo.getDB("jongo").getCollection("benchmark");
}

From source file:org.jongo.bench.BenchUtil.java

License:Apache License

public static MongoCollection getCollectionFromJongo(Mapper mapper) throws UnknownHostException {
    Mongo mongo = new MongoClient();
    DB db = mongo.getDB("jongo");
    Jongo jongo = new Jongo(db, mapper);
    return jongo.getCollection("benchmark");
}

From source file:org.jwebsocket.gaming.pingpong.plugin.PingPongPlugIn.java

License:Apache License

/**
 *
 * @param aConfiguration// ww w . j  a v  a 2 s.  c o  m
 */
public PingPongPlugIn(PluginConfiguration aConfiguration) {
    super(aConfiguration);
    setNamespace(NS_PINGPONG);

    int lDay = Integer.parseInt(aConfiguration.getSettings().get("dbDay").toString());
    int lTime = Integer.parseInt(aConfiguration.getSettings().get("dbTime").toString());
    int lWidth = Integer.parseInt(aConfiguration.getSettings().get("sWidth").toString());
    int lHeight = Integer.parseInt(aConfiguration.getSettings().get("sHeight").toString());

    // getting the database connection
    ConnectionManager lCM = (ConnectionManager) JWebSocketBeanFactory.getInstance()
            .getBean(JWebSocketServerConstants.CONNECTION_MANAGER_BEAN_ID);
    if (lCM.isValid(NS_PINGPONG)) {
        mPingpongGame = new PingpongGame(lWidth, lHeight, 2);
        Mongo lMongo = (Mongo) lCM.getConnection(NS_PINGPONG);
        DBCollection lCollection = lMongo.getDB("pingpongame").getCollection("user");
        mUserServiceImpl = new UserServiceImpl(lCollection, lDay);
        Tools.getTimer().scheduleAtFixedRate(mUserServiceImpl, 0, lTime * 1000 * 60 * 60 * 24);
    } else {

        mLog.error("Invalid MongoDB database connection, please check that the current "
                + "connection configuration (conf/Resources/bootstrap.xml) is correct "
                + "or consider to install and run MongoDB server. " + "PingPong plug-in cannot start!");
        throw new RuntimeException("Missing required valid database connection for PingPong plug-in!");
    }

    if (mLog.isInfoEnabled()) {
        mLog.info("PingPong plug-in successfully instantiated.");
    }
}

From source file:org.jwebsocket.plugins.monitoring.MonitoringPlugIn.java

License:Apache License

/**
 *
 * @param aConfiguration// ww w . j  a  v a  2  s. co m
 */
public MonitoringPlugIn(PluginConfiguration aConfiguration) {
    super(aConfiguration);
    if (mLog.isDebugEnabled()) {
        mLog.debug("Instantiating Monitoring plug-in...");
    }
    // specify default name space for monitoring plugin
    this.setNamespace(NS_MONITORING);

    // Getting server exchanges
    mFormat = new SimpleDateFormat("MM/dd/yyyy");

    mDBExchanges = null;
    ConnectionManager lCM = (ConnectionManager) JWebSocketBeanFactory.getInstance()
            .getBean(JWebSocketServerConstants.CONNECTION_MANAGER_BEAN_ID);
    try {
        Mongo lMongo = (Mongo) lCM.getConnection(NS_MONITORING);
        DB lDB = lMongo.getDB(DB_NAME);
        if (null != lDB) {
            mDBExchanges = lDB.getCollection(DB_COL_EXCHANGES);
            mUsePlugInsColl = lDB.getCollection(DB_COL_PLUGINS_USAGE);
        } else {
            mLog.error("Mongo db_charting collection could not be obtained.");
        }

        if (null == mDBExchanges) {
            mLog.error("MongoDB collection exchanges_server could not be obtained.");
        } else if (mLog.isInfoEnabled()) {
            mLog.info("Monitoring Plug-in successfully instantiated.");
        }
    } catch (Exception lEx) {
        mLog.error("Invalid MongoDB database connection, please check that the current "
                + "connection configuration (conf/Resources/bootstrap.xml) is correct "
                + "or consider to install and run MongoDB server. " + "Monitoring plug-in cannot start!");
        throw new RuntimeException("Missing required valid database connection for MonitoringPlugIn!");
    }
}