Java Examples for com.mongodb.DB

The following java examples will help you to understand the usage of com.mongodb.DB. These source code samples are taken from different open source projects.

Example 1
Project: GeoGig-master  File: MongoGraphDatabaseTest.java View source code
@Override
protected MongoGraphDatabase createDatabase(Platform platform) throws Exception {
    final IniMongoProperties properties = new IniMongoProperties();
    final String uri = properties.get("mongodb.uri", String.class).or("mongodb://localhost:27017/");
    final String database = properties.get("mongodb.database", String.class).or("geogig");
    MongoClient client = new MongoClient(new MongoClientURI(uri));
    DB db = client.getDB(database);
    db.dropDatabase();
    MongoConnectionManager manager = new MongoConnectionManager();
    ConfigDatabase config = new TestConfigDatabase(platform);
    MongoGraphDatabase mongoGraphDatabase = new MongoGraphDatabase(manager, config);
    return mongoGraphDatabase;
}
Example 2
Project: cloudtm-data-platform-master  File: MongoDBDialect.java View source code
@Override
public void nextValue(RowKey key, IntegralDataTypeHolder value, int increment, int initialValue) {
    DBCollection currentCollection = this.currentDB.getCollection(key.getTable());
    DBObject query = this.prepareIdObject(key);
    //all columns should match to find the value
    BasicDBObject update = new BasicDBObject();
    //FIXME should "value" be hardcoded?
    //FIXME how to set the initialValue if the document is not present? It seems the inc value is used as initial new value
    Integer incrementObject = increment == 1 ? ONE : Integer.valueOf(increment);
    this.addSubQuery("$inc", update, SEQUENCE_VALUE, incrementObject);
    DBObject result = currentCollection.findAndModify(query, null, null, false, update, false, true);
    Object idFromDB;
    idFromDB = result == null ? null : result.get(SEQUENCE_VALUE);
    if (idFromDB == null) {
        //not inserted yet so we need to add initial value to increment to have the right next value in the DB
        //FIXME that means there is a small hole as when there was not value in the DB, we do add initial value in a non atomic way
        BasicDBObject updateForInitial = new BasicDBObject();
        this.addSubQuery("$inc", updateForInitial, SEQUENCE_VALUE, initialValue);
        currentCollection.findAndModify(query, null, null, false, updateForInitial, false, true);
        //first time we ask this value
        idFromDB = initialValue;
    } else {
        idFromDB = result.get(SEQUENCE_VALUE);
    }
    if (idFromDB.getClass().equals(Integer.class) || idFromDB.getClass().equals(Long.class)) {
        Number id = (Number) idFromDB;
        //idFromDB is the one used and the BD contains the next available value to use
        value.initialize(id.longValue());
    } else {
        throw new HibernateException("Cannot increment a non numeric field");
    }
}
Example 3
Project: acteur-master  File: MongoModuleTest.java View source code
@Test
public void testIt(MongoHarness mongo, MongoClient client, DB db, Fixture f, Dependencies deps) throws IOException, InterruptedException {
    assertNotNull(db);
    assertEquals("testit", db.getName());
    assertNotNull(f.users);
    assertNotNull(f.capped);
    assertEquals("ttusers", f.users.getName());
    assertEquals("cappedStuff", f.capped.getName());
    assertTrue(f.capped.isCapped());
    //
    //        mongo.stop();
    //
    //        Ge ge = new Ge(deps);
    //        Thread t = new Thread(ge);
    //        t.setDaemon(true);
    //        t.start();
    //        ge.await();
    //        Thread.yield();
    //
    //        mongo.start();
    DB db3 = deps.getInstance(DB.class);
    assertNotNull(db3);
    Fixture f1 = deps.getInstance(Fixture.class);
    assertNotSame(f, f1);
    assertEquals("testit", db3.getName());
    //        assertNotNull(ge.db);
    //        assertEquals(db3.getName(), ge.db.getName());
    System.out.println("Test done");
}
Example 4
Project: keycloak-master  File: MongoStoreImpl.java View source code
@Override
public <T extends MongoIdentifiableEntity> T loadEntity(Class<T> type, String id, MongoStoreInvocationContext context) {
    // First look if we already read the object with this oid and type during this transaction. If yes, use it instead of DB lookup
    T cached = context.getLoadedEntity(type, id);
    if (cached != null && type.isAssignableFrom(cached.getClass()))
        return cached;
    DBCollection dbCollection = getDBCollectionForType(type);
    BasicDBObject idQuery = new BasicDBObject("_id", id);
    DBObject dbObject = dbCollection.findOne(idQuery);
    if (dbObject == null)
        return null;
    MapperContext<Object, T> mapperContext = new MapperContext<Object, T>(dbObject, type, null);
    T converted = mapperRegistry.convertDBObjectToApplicationObject(mapperContext);
    // Now add it to loaded objects
    context.addLoadedEntity(converted);
    return converted;
}
Example 5
Project: eclipselink.runtime-master  File: MongoTestSuite.java View source code
/**
     * Initialize test suite.
     */
public void testSetup() {
    EntityManager em = createEntityManager();
    // First clear old database.
    beginTransaction(em);
    DB db = ((MongoConnection) em.unwrap(javax.resource.cci.Connection.class)).getDB();
    db.dropDatabase();
    commitTransaction(em);
    beginTransaction(em);
    try {
        for (int index = 0; index < 10; index++) {
            existingOrder = new Order();
            existingOrder.orderedBy = "ACME";
            existingOrder.address = new Address();
            existingOrder.address.city = "Ottawa";
            existingOrder.address.addressee = "Bob Jones";
            existingOrder.address.state = "CA";
            existingOrder.address.country = "Mexico";
            existingOrder.address.zipCode = "12345";
            LineItem line = new LineItem();
            line.itemName = "stuff";
            line.itemPrice = new BigDecimal("10.99");
            line.lineNumber = 1;
            line.quantity = 100;
            existingOrder.lineItems.add(line);
            line = new LineItem();
            line.itemName = "more stuff";
            line.itemPrice = new BigDecimal("20.99");
            line.lineNumber = 2;
            line.quantity = 50;
            existingOrder.lineItems.add(line);
            existingOrder.comments.add("priority order");
            existingOrder.comments.add("next day");
            em.persist(existingOrder);
        }
        commitTransaction(em);
    } finally {
        closeEntityManagerAndTransaction(em);
    }
    clearCache();
}
Example 6
Project: cdo-master  File: MongoDBBrowserPage.java View source code
public void display(CDOServerBrowser browser, InternalRepository repository, PrintStream out) {
    IMongoDBStore store = (IMongoDBStore) repository.getStore();
    DB db = (DB) store.getDB();
    out.print("<table border=\"0\">\r\n");
    out.print("<tr>\r\n");
    out.print("<td valign=\"top\">\r\n");
    String collection = showCollections(browser, out, db, repository.getName());
    out.print("</td>\r\n");
    out.print("<td>   </td>\r\n");
    if (collection != null) {
        out.print("<td valign=\"top\">\r\n");
        showCollection(browser, out, db, collection);
        out.print("</td>\r\n");
    }
    out.print("</tr>\r\n");
    out.print("</table>\r\n");
}
Example 7
Project: deep-spark-master  File: MongoNativeExtractor.java View source code
@Override
public Partition[] getPartitions(S config) {
    MongoClient mongoClient = null;
    try {
        mongoDeepJobConfig = initConfig(config, mongoDeepJobConfig);
        DBCollection collection;
        ServerAddress address = new ServerAddress(mongoDeepJobConfig.getHost());
        List<ServerAddress> addressList = new ArrayList<>();
        addressList.add(address);
        mongoClient = new MongoClient(addressList);
        mongoClient.setReadPreference(ReadPreference.nearest());
        DB db = mongoClient.getDB(mongoDeepJobConfig.getDatabase());
        collection = db.getCollection(mongoDeepJobConfig.getCollection());
        return isShardedCollection(collection) ? calculateShardChunks(collection) : calculateSplits(collection);
    } catch (UnknownHostException e) {
        throw new DeepGenericException(e);
    } finally {
        if (mongoClient != null) {
            mongoClient.close();
        }
    }
}
Example 8
Project: usergrid-master  File: MongoQueryTest.java View source code
@Test
public void stringEqual() throws Exception {
    UUID appId = emf.lookupApplication("test-organization/test-app");
    EntityManager em = emf.getEntityManager(appId);
    Map<String, Object> properties = new LinkedHashMap<String, Object>();
    properties.put("name", "Kings of Leon");
    properties.put("genre", "Southern Rock");
    properties.put("founded", 2000);
    em.create("stringequal", properties);
    properties = new LinkedHashMap<String, Object>();
    properties.put("name", "Stone Temple Pilots");
    properties.put("genre", "Rock");
    properties.put("founded", 1986);
    em.create("stringequal", properties);
    properties = new LinkedHashMap<String, Object>();
    properties.put("name", "Journey");
    properties.put("genre", "Classic Rock");
    properties.put("founded", 1973);
    em.create("stringequal", properties);
    // See http://www.mongodb.org/display/DOCS/Java+Tutorial
    Mongo m = new Mongo("localhost", 27017);
    DB db = m.getDB("test-organization/test-app");
    db.authenticate("test", "test".toCharArray());
    Set<String> colls = db.getCollectionNames();
    assertTrue(colls.contains("stringequals"));
    DBCollection coll = db.getCollection("stringequals");
    DBCursor cur = coll.find();
    int count = 0;
    while (cur.hasNext()) {
        cur.next();
        count++;
    }
    assertEquals(3, count);
    BasicDBObject query = new BasicDBObject();
    query.put("genre", "Southern Rock");
    cur = coll.find(query);
    assertTrue(cur.hasNext());
    DBObject result = cur.next();
    assertEquals("Kings of Leon", result.get("name"));
    assertEquals("Southern Rock", result.get("genre"));
    assertFalse(cur.hasNext());
}
Example 9
Project: WaveInCloud-master  File: MongoDbStore.java View source code
@Override
public AccountData getAccount(ParticipantId id) {
    DBObject query = getDBObjectForParticipant(id);
    DBObject result = getAccountCollection().findOne(query);
    if (result == null) {
        return null;
    }
    DBObject human = (DBObject) result.get(ACCOUNT_HUMAN_DATA_FIELD);
    if (human != null) {
        return objectToHuman(id, human);
    }
    DBObject robot = (DBObject) result.get(ACCOUNT_ROBOT_DATA_FIELD);
    if (robot != null) {
        return objectToRobot(id, robot);
    }
    throw new IllegalStateException("DB object contains neither a human nor a robot");
}
Example 10
Project: wave-protocol-master  File: MongoDbStore.java View source code
@Override
public AccountData getAccount(ParticipantId id) {
    DBObject query = getDBObjectForParticipant(id);
    DBObject result = getAccountCollection().findOne(query);
    if (result == null) {
        return null;
    }
    DBObject human = (DBObject) result.get(ACCOUNT_HUMAN_DATA_FIELD);
    if (human != null) {
        return objectToHuman(id, human);
    }
    DBObject robot = (DBObject) result.get(ACCOUNT_ROBOT_DATA_FIELD);
    if (robot != null) {
        return objectToRobot(id, robot);
    }
    throw new IllegalStateException("DB object contains neither a human nor a robot");
}
Example 11
Project: incubator-wave-master  File: MongoDbStore.java View source code
@Override
public AccountData getAccount(ParticipantId id) {
    DBObject query = getDBObjectForParticipant(id);
    DBObject result = getAccountCollection().findOne(query);
    if (result == null) {
        return null;
    }
    DBObject human = (DBObject) result.get(ACCOUNT_HUMAN_DATA_FIELD);
    if (human != null) {
        return objectToHuman(id, human);
    }
    DBObject robot = (DBObject) result.get(ACCOUNT_ROBOT_DATA_FIELD);
    if (robot != null) {
        return objectToRobot(id, robot);
    }
    throw new IllegalStateException("DB object contains neither a human nor a robot");
}
Example 12
Project: xDrip-master  File: NightscoutUploader.java View source code
private boolean doMongoUpload(SharedPreferences prefs, List<BgReading> glucoseDataSets, List<Calibration> meterRecords, List<Calibration> calRecords) {
    SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss a");
    format.setTimeZone(TimeZone.getDefault());
    String dbURI = prefs.getString("cloud_storage_mongodb_uri", null);
    String collectionName = prefs.getString("cloud_storage_mongodb_collection", null);
    String dsCollectionName = prefs.getString("cloud_storage_mongodb_device_status_collection", "devicestatus");
    if (dbURI != null && collectionName != null) {
        try {
            // connect to db
            MongoClientURI uri = new MongoClientURI(dbURI.trim());
            MongoClient client = new MongoClient(uri);
            // get db
            DB db = client.getDB(uri.getDatabase());
            // get collection
            DBCollection dexcomData = db.getCollection(collectionName.trim());
            Log.i(TAG, "The number of EGV records being sent to MongoDB is " + glucoseDataSets.size());
            for (BgReading record : glucoseDataSets) {
                // make db object
                BasicDBObject testData = new BasicDBObject();
                testData.put("device", "xDrip-" + prefs.getString("dex_collection_method", "BluetoothWixel"));
                testData.put("date", record.timestamp);
                testData.put("dateString", format.format(record.timestamp));
                testData.put("sgv", Math.round(record.calculated_value));
                testData.put("direction", record.slopeName());
                testData.put("type", "sgv");
                testData.put("filtered", record.filtered_data * 1000);
                testData.put("unfiltered", record.age_adjusted_raw_value * 1000);
                testData.put("rssi", 100);
                testData.put("noise", Integer.valueOf(record.noiseValue()));
                dexcomData.update(testData, testData, true, false, WriteConcern.UNACKNOWLEDGED);
            }
            Log.i(TAG, "The number of MBG records being sent to MongoDB is " + meterRecords.size());
            for (Calibration meterRecord : meterRecords) {
                // make db object
                BasicDBObject testData = new BasicDBObject();
                testData.put("device", "xDrip-" + prefs.getString("dex_collection_method", "BluetoothWixel"));
                testData.put("type", "mbg");
                testData.put("date", meterRecord.timestamp);
                testData.put("dateString", format.format(meterRecord.timestamp));
                testData.put("mbg", meterRecord.bg);
                dexcomData.update(testData, testData, true, false, WriteConcern.UNACKNOWLEDGED);
            }
            for (Calibration calRecord : calRecords) {
                // make db object
                BasicDBObject testData = new BasicDBObject();
                testData.put("device", "xDrip-" + prefs.getString("dex_collection_method", "BluetoothWixel"));
                testData.put("date", calRecord.timestamp);
                testData.put("dateString", format.format(calRecord.timestamp));
                if (calRecord.check_in) {
                    testData.put("slope", (long) (calRecord.first_slope));
                    testData.put("intercept", (long) ((calRecord.first_intercept)));
                    testData.put("scale", calRecord.first_scale);
                } else {
                    testData.put("slope", (long) (calRecord.slope * 1000));
                    testData.put("intercept", (long) ((calRecord.intercept * -1000) / (calRecord.slope * 1000)));
                    testData.put("scale", 1);
                }
                testData.put("type", "cal");
                dexcomData.update(testData, testData, true, false, WriteConcern.UNACKNOWLEDGED);
            }
            // TODO: quick port from original code, revisit before release
            DBCollection dsCollection = db.getCollection(dsCollectionName);
            BasicDBObject devicestatus = new BasicDBObject();
            devicestatus.put("uploaderBattery", getBatteryLevel());
            devicestatus.put("created_at", new Date());
            dsCollection.insert(devicestatus, WriteConcern.UNACKNOWLEDGED);
            client.close();
            return true;
        } catch (Exception e) {
            Log.e(TAG, "Unable to upload data to mongo");
        }
    }
    return false;
}