Package com.mongodb

Examples of com.mongodb.DBCollection


        return getRole(name);
    }

    @Override
    public Role removeRole(String roleName) throws MongoException {
        DBCollection coll = getCollection();
       
        Role role = getRole(roleName);
        if (role == null) {
            return null;
        }

        WriteResult result = coll.remove(getTemplateObject(role));

        if (result.getLastError() != null) {
            result.getLastError().throwOnError();
        }
View Full Code Here


            // Only the changes are interesting, as the creation and
            // removal are already caught by #addRole and #removeRole....
            Role changedRole = event.getRole();

            try {
                DBCollection coll = getCollection();

                DBObject query = getTemplateObject(changedRole);
                DBObject update = m_helper.serializeUpdate(changedRole);

                WriteResult result = coll.update(query, update, false /* upsert */, false /* multi */);

                if (result.getLastError() != null) {
                    result.getLastError().throwOnError();
                }
            }
View Full Code Here

    private void connectToDB(MongoDB mongoDB, String userName, String password) throws MongoException {
        if (!mongoDB.connect(userName, password)) {
            throw new MongoException("Failed to connect to MongoDB! Authentication failed!");
        }

        DBCollection collection = mongoDB.getCollection();
        if (collection == null) {
            throw new MongoException("Failed to connect to MongoDB! No collection returned!");
        }

        collection.ensureIndex(new BasicDBObject(NAME, 1).append("unique", true));
    }
View Full Code Here

        {
            service.updated(null);

            Mongo mongo = new Mongo();
            DB db = mongo.getDB("ua_repo");
            DBCollection collection = db.getCollection("useradmin");
            // we always get a collection back, regardless if there is an actual MongoDB listening, hence we should do
            // some actual calls that cause a connection to MongoDB to be created...
            collection.remove(new BasicDBObject(), WriteConcern.SAFE);

            CommandResult lastError = db.getLastError();

            return (lastError.getException() == null && collection.getCount() == 0L);
        }
        catch (Exception e)
        {
            // Ignore; apparently, we failed to connect to MongoDB...
        }
View Full Code Here

        assertEquals(0, cappedTestCollection.count());
        final MockEndpoint mock = getMockEndpoint("mock:test");
        final Calendar startTimestamp = Calendar.getInstance();
       
        // get default tracking collection
        DBCollection trackingCol = db.getCollection(MongoDbTailTrackingConfig.DEFAULT_COLLECTION);
        trackingCol.drop();
        trackingCol = db.getCollection(MongoDbTailTrackingConfig.DEFAULT_COLLECTION);
       
        // create a capped collection with max = 1000
        cappedTestCollection = db.createCollection(cappedTestCollectionName,
                BasicDBObjectBuilder.start().add("capped", true).add("size", 1000000000).add("max", 1000).get());
       
        addTestRoutes();
        context.startRoute("tailableCursorConsumer2");
       
        mock.expectedMessageCount(300);
        // pump 300 records
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 1; i <= 300; i++) {
                    Calendar c = (Calendar) (startTimestamp.clone());
                    c.add(Calendar.MINUTE, i);
                    cappedTestCollection.insert(BasicDBObjectBuilder.start("increasing", c.getTime()).add("string", "value" + i).get(), WriteConcern.SAFE);
                }
            }
        });
       
        // start the data pumping
        t.start();
        // before we continue wait for the data pump to end
        t.join();
        mock.assertIsSatisfied();
        mock.reset();
        // ensure that the persisted lastVal is startTimestamp + 300min
        Calendar cal300 = (Calendar) startTimestamp.clone();
        cal300.add(Calendar.MINUTE, 300);
        context.stopRoute("tailableCursorConsumer2");
        assertEquals(cal300.getTime(), trackingCol.findOne(new BasicDBObject("persistentId", "darwin")).get(MongoDbTailTrackingConfig.DEFAULT_FIELD));
        context.startRoute("tailableCursorConsumer2");
       
        // expect 300 messages and not 600
        mock.expectedMessageCount(300);
        // pump 300 records
        t = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 301; i <= 600; i++) {
                    Calendar c = (Calendar) (startTimestamp.clone());
                    c.add(Calendar.MINUTE, i);
                    cappedTestCollection.insert(BasicDBObjectBuilder.start("increasing", c.getTime()).add("string", "value" + i).get(), WriteConcern.SAFE);
                }
            }
        });
        // start the data pumping
        t.start();
        // before we continue wait for the data pump to end
        t.join();
        mock.assertIsSatisfied();
        Object firstBody = mock.getExchanges().get(0).getIn().getBody();
        assertTrue(firstBody instanceof DBObject);
        Calendar cal301 = (Calendar) startTimestamp.clone();
        cal301.add(Calendar.MINUTE, 301);
        assertEquals(cal301.getTime(), ((DBObject) firstBody).get("increasing"));
        // check that the persisted lastVal after stopping the route is startTimestamp + 600min
        context.stopRoute("tailableCursorConsumer2");
        Calendar cal600 = (Calendar) startTimestamp.clone();
        cal600.add(Calendar.MINUTE, 600);
        assertEquals(cal600.getTime(), trackingCol.findOne(new BasicDBObject("persistentId", "darwin")).get(MongoDbTailTrackingConfig.DEFAULT_FIELD));
    }
View Full Code Here

    public void testCustomTailTrackLocation() throws Exception {
        assertEquals(0, cappedTestCollection.count());
        final MockEndpoint mock = getMockEndpoint("mock:test");
       
        // get the custom tracking collection and drop it (tailTrackDb=einstein&tailTrackCollection=curie&tailTrackField=newton)
        DBCollection trackingCol = mongo.getDB("einstein").getCollection("curie");
        trackingCol.drop();
        trackingCol = mongo.getDB("einstein").getCollection("curie");
       
        // create a capped collection with max = 1000
        cappedTestCollection = db.createCollection(cappedTestCollectionName,
                BasicDBObjectBuilder.start().add("capped", true).add("size", 1000000000).add("max", 1000).get());
       
        addTestRoutes();
        context.startRoute("tailableCursorConsumer3");
       
        mock.expectedMessageCount(300);
        // pump 300 records
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 1; i <= 300; i++) {
                    cappedTestCollection.insert(BasicDBObjectBuilder.start("increasing", i).add("string", "value" + i).get(), WriteConcern.SAFE)
                }
            }
        });
       
        // start the data pumping
        t.start();
        // before we continue wait for the data pump to end
        t.join();
        mock.assertIsSatisfied();
        mock.reset();
       
        // stop the route to ensure that our lastVal is persisted, and check it
        context.stopRoute("tailableCursorConsumer3");
        // ensure that the persisted lastVal is 300, newton is the name of the trackingField we are using
        assertEquals(300, trackingCol.findOne(new BasicDBObject("persistentId", "darwin")).get("newton"));
        context.startRoute("tailableCursorConsumer3");
       
        // expect 300 messages and not 600
        mock.expectedMessageCount(300);
        // pump 300 records
        t = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 301; i <= 600; i++) {
                    cappedTestCollection.insert(BasicDBObjectBuilder.start("increasing", i).add("string", "value" + i).get(), WriteConcern.SAFE)
                }
            }
        });
        // start the data pumping
        t.start();
        // before we continue wait for the data pump to end
        t.join();
        mock.assertIsSatisfied();
        // check that the first received body contains increasing=301 and not increasing=1, i.e. it's not starting from the top
        Object firstBody = mock.getExchanges().get(0).getIn().getBody();
        assertTrue(firstBody instanceof DBObject);
        assertEquals(301, ((DBObject) firstBody).get("increasing"));
        // check that the persisted lastVal after stopping the route is 600, newton is the name of the trackingField we are using
        context.stopRoute("tailableCursorConsumer3");
        assertEquals(600, trackingCol.findOne(new BasicDBObject("persistentId", "darwin")).get("newton"));

    }
View Full Code Here

        resultMessage.setBody(ret);
        resultMessage.setHeader(MongoDbConstants.RESULT_TOTAL_SIZE, ret == null ? 0 : 1);
    }

    protected void doCount(Exchange exchange) throws Exception {
        DBCollection dbCol = calculateCollection(exchange);
        DBObject query = exchange.getIn().getBody(DBObject.class);
        Long answer;
        if (query == null) {
            answer = dbCol.count();
        } else {
            answer = dbCol.count(query);
        }
        Message resultMessage = prepareResponseMessage(exchange, MongoDbOperation.count);
        resultMessage.setBody(answer);
    }
View Full Code Here

    *
    * @param exchange
    * @throws Exception
    */
    protected void doAggregate(Exchange exchange) throws Exception {
        DBCollection dbCol = calculateCollection(exchange);
        DBObject query = exchange.getIn().getMandatoryBody(DBObject.class);

        // Impossible with java driver to get the batch size and number to skip
        Iterable<DBObject> dbIterator = null;
        AggregationOutput aggregationResult = null;

        // Allow body to be a pipeline
        // @see http://docs.mongodb.org/manual/core/aggregation/
        if (query instanceof BasicDBList) {
            BasicDBList queryList = (BasicDBList)query;
            aggregationResult = dbCol.aggregate((DBObject)queryList.get(0), queryList
                .subList(1, queryList.size()).toArray(new BasicDBObject[queryList.size() - 1]));
        } else {
            aggregationResult = dbCol.aggregate(query);
        }

        dbIterator = aggregationResult.results();
        Message resultMessage = prepareResponseMessage(exchange, MongoDbOperation.aggregate);
        resultMessage.setBody(dbIterator);
View Full Code Here

        String dynamicCollection = exchange.getIn().getHeader(MongoDbConstants.COLLECTION, String.class);
               
        @SuppressWarnings("unchecked")
        List<DBObject> dynamicIndex = exchange.getIn().getHeader(MongoDbConstants.COLLECTION_INDEX, List.class);

        DBCollection dbCol = null;
       
        if (dynamicDB == null && dynamicCollection == null) {
            dbCol = endpoint.getDbCollection();
        } else {
            DB db = null;

            if (dynamicDB == null) {
                db = endpoint.getDb();
            } else {
                db = endpoint.getMongoConnection().getDB(dynamicDB);
            }

            if (dynamicCollection == null) {
                dbCol = db.getCollection(endpoint.getCollection());
            } else {
                dbCol = db.getCollection(dynamicCollection);

                // on the fly add index
                if (dynamicIndex == null) {
                    endpoint.ensureIndex(dbCol, endpoint.createIndex());
                } else {
                    endpoint.ensureIndex(dbCol, dynamicIndex);
                }
            }
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug("Dynamic database and/or collection selected: {}->{}", dbCol.getDB().getName(), dbCol.getName());
        }
        return dbCol;
    }
View Full Code Here

        Object result = template.requestBodyAndHeaders("direct:dynamicityEnabled", body, headers);

        assertEquals("Response isn't of type WriteResult", WriteResult.class, result.getClass());

        DBCollection dynamicCollection = mongo.getDB("otherDB").getCollection("otherCollection");

        List<DBObject> indexInfos = dynamicCollection.getIndexInfo();

        BasicDBObject key1 = (BasicDBObject) indexInfos.get(1).get("key");
        BasicDBObject key2 = (BasicDBObject) indexInfos.get(2).get("key");

        assertTrue("No index on the field a", key1.containsField("a") && "1".equals(key1.getString("a")));
        assertTrue("No index on the field b", key2.containsField("b") && "-1".equals(key2.getString("b")));

        DBObject b = dynamicCollection.findOne("testInsertDynamicityEnabledDBAndCollection");
        assertNotNull("No record with 'testInsertDynamicityEnabledDBAndCollection' _id", b);

        b = testCollection.findOne("testInsertDynamicityEnabledDBOnly");
        assertNull("There is a record with 'testInsertDynamicityEnabledDBAndCollection' _id in the test collection", b);
View Full Code Here

TOP

Related Classes of com.mongodb.DBCollection

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.