Example usage for com.mongodb DBCursor close

List of usage examples for com.mongodb DBCursor close

Introduction

In this page you can find the example usage for com.mongodb DBCursor close.

Prototype

@Override
    public void close() 

Source Link

Usage

From source file:org.apache.streams.mongo.MongoPersistReader.java

License:Apache License

@Override
public StreamsResultSet readAll() {

    DBCursor cursor = collection.find();
    try {//from ww w .j  a v a  2s.  c o  m
        while (cursor.hasNext()) {
            DBObject dbObject = cursor.next();
            StreamsDatum datum = prepareDatum(dbObject);
            write(datum);
        }
    } finally {
        cursor.close();
    }

    return readCurrent();
}

From source file:org.araqne.logdb.mongo.query.MongoFindCommand.java

License:Apache License

@Override
public void run() {
    MongoProfile profile = options.getProfile();

    MongoClient mongo = null;//from  w  ww  .  j a v  a2s .  c o m
    DBCursor cursor = null;
    try {
        mongo = new MongoClient(profile.getAddress(), profile.getCredentials());

        DB db = mongo.getDB(options.getDatabase());
        DBCollection col = db.getCollection(options.getCollection());
        cursor = col.find();

        while (cursor.hasNext()) {
            DBObject doc = cursor.next();

            Map<String, Object> m = convert(doc);
            pushPipe(new Row(m));
        }
    } catch (Throwable t) {
        slog.error("araqne logdb mongo: cannot run mongo.find", t);
    } finally {
        if (cursor != null)
            cursor.close();

        if (mongo != null)
            mongo.close();
    }
}

From source file:org.axonframework.eventsourcing.eventstore.mongo.AbstractEventStorageStrategy.java

License:Apache License

@Override
public List<? extends DomainEventData<?>> findDomainEvents(DBCollection eventCollection,
        String aggregateIdentifier, long firstSequenceNumber, int batchSize) {
    DBCursor cursor = eventCollection
            .find(BasicDBObjectBuilder.start()
                    .add(eventConfiguration().aggregateIdentifierProperty(), aggregateIdentifier)
                    .add(eventConfiguration().sequenceNumberProperty(),
                            new BasicDBObject("$gte", firstSequenceNumber))
                    .get())// w  w  w  . j a  v  a  2 s.c  o m
            .sort(new BasicDBObject(eventConfiguration().sequenceNumberProperty(), ORDER_ASC));
    cursor = applyBatchSize(cursor, batchSize);
    try {
        return stream(cursor.spliterator(), false).flatMap(this::extractDomainEvents)
                .filter(event -> event.getSequenceNumber() >= firstSequenceNumber).limit(batchSize)
                .collect(Collectors.toList());
    } finally {
        cursor.close();
    }
}

From source file:org.axonframework.eventsourcing.eventstore.mongo.AbstractEventStorageStrategy.java

License:Apache License

@Override
public List<? extends TrackedEventData<?>> findTrackedEvents(DBCollection eventCollection,
        TrackingToken lastToken, int batchSize) {
    DBCursor cursor;
    if (lastToken == null) {
        cursor = eventCollection.find(BasicDBObjectBuilder.start().get());
    } else {//from   w ww  .j ava  2 s. c  o  m
        Assert.isTrue(lastToken instanceof LegacyTrackingToken,
                String.format("Token %s is of the wrong type", lastToken));
        LegacyTrackingToken legacyTrackingToken = (LegacyTrackingToken) lastToken;
        cursor = eventCollection.find(BasicDBObjectBuilder.start()
                .add(eventConfiguration.timestampProperty(),
                        new BasicDBObject("$gte", legacyTrackingToken.getTimestamp().toString()))
                .add(eventConfiguration.sequenceNumberProperty(),
                        new BasicDBObject("$gte", legacyTrackingToken.getSequenceNumber()))
                .get());
    }
    cursor = cursor.sort(new BasicDBObject(eventConfiguration().timestampProperty(), ORDER_ASC)
            .append(eventConfiguration().sequenceNumberProperty(), ORDER_ASC));
    cursor = applyBatchSize(cursor, batchSize);
    try {
        return stream(cursor.spliterator(), false).flatMap(this::extractTrackedEvents)
                .filter(event -> event.trackingToken().isAfter(lastToken)).limit(batchSize)
                .collect(Collectors.toList());
    } finally {
        cursor.close();
    }
}

From source file:org.baldeapi.v1.persistence.GenericDAO.java

License:Apache License

public List<DBObject> find(DBObject filter, DBObject sort, int skip, int limit) {

    DBCursor cursor = collection.find(filter).sort(sort).skip(skip).limit(limit);

    List<DBObject> result = null;

    try {/*  ww w  .  java2 s.com*/
        result = cursor.toArray();
    } finally {
        cursor.close();
    }

    return result;

}

From source file:org.baldeapi.v1.persistence.GenericDAO.java

License:Apache License

public List<DBObject> find(DBObject filter, DBObject projection, DBObject sort, int skip, int limit) {

    DBCursor cursor = collection.find(filter, projection).sort(sort).skip(skip).limit(limit);

    List<DBObject> result = null;

    try {/* w w  w  . j  a  v  a 2 s .c  o m*/
        result = cursor.toArray();
    } finally {
        cursor.close();
    }

    return result;

}

From source file:org.canedata.provider.mongodb.entity.MongoEntity.java

License:Apache License

public List<Fields> list(int offset, int count) {
    if (logger.isDebug())
        logger.debug("Listing entities, Database is {0}, Collection is {1}, offset is {2}, count is {3}.",
                getSchema(), getName(), offset, count);
    List<Fields> rlt = new ArrayList<Fields>();

    BasicDBObject options = new BasicDBObject();
    DBCursor cursor = null;

    try {//from  w w  w  . j a v a  2 s  .  co  m
        validateState();

        MongoExpressionFactory expFactory = new MongoExpressionFactory.Impl();
        BasicDBObject projection = new BasicDBObject();
        Limiter limiter = new Limiter.Default();
        BasicDBObject sorter = new BasicDBObject();

        IntentParser.parse(getIntent(), expFactory, null, projection, limiter, sorter, options);

        if (!options.isEmpty())
            prepareOptions(options);

        if (null != getCache()) {// cache
            cursor = getCollection().find(expFactory.toQuery(), new BasicDBObject().append("_id", 1));
        } else {// no cache
            // projection
            if (projection.isEmpty())
                cursor = getCollection().find(expFactory.toQuery());
            else
                cursor = getCollection().find(expFactory.toQuery(), projection);
        }

        // sort
        if (!sorter.isEmpty())
            cursor.sort(sorter);

        if (offset > 0)
            limiter.offset(offset);

        if (count > 0)
            limiter.count(count);

        if (limiter.offset() > 0)
            cursor.skip(limiter.offset());
        if (limiter.count() > 0)
            cursor.limit(limiter.count());

        if (null != getCache()) {
            Map<Object, MongoFields> missedCacheHits = new HashMap<Object, MongoFields>();

            while (cursor.hasNext()) {
                BasicDBObject dbo = (BasicDBObject) cursor.next();
                Object key = dbo.get("_id");
                String cacheKey = getKey().concat("#").concat(key.toString());

                MongoFields ele = null;
                if (getCache().isAlive(cacheKey)) {// load from cache
                    MongoFields mf = (MongoFields) getCache().restore(cacheKey);
                    if (null != mf)
                        ele = mf.clone();// pooling
                }

                if (null != ele && !projection.isEmpty())
                    ele.project(projection.keySet());

                if (null == ele) {
                    ele = new MongoFields(this, getIntent());
                    missedCacheHits.put(key, ele);
                }

                rlt.add(ele);
            }

            // load missed cache hits.
            if (!missedCacheHits.isEmpty()) {
                loadForMissedCacheHits(missedCacheHits, projection.keySet());
                missedCacheHits.clear();
            }

            if (logger.isDebug())
                logger.debug("Listed entities hit cache ...");
        } else {
            while (cursor.hasNext()) {
                BasicDBObject dbo = (BasicDBObject) cursor.next();

                rlt.add(new MongoFields(this, getIntent(), dbo));
            }

            if (logger.isDebug())
                logger.debug("Listed entities ...");
        }

        return rlt;
    } catch (AnalyzeBehaviourException abe) {
        if (logger.isDebug())
            logger.debug(abe, "Analyzing behaviour failure, cause by: {0}.", abe.getMessage());

        throw new RuntimeException(abe);
    } finally {
        if (!options.getBoolean(Options.RETAIN))
            getIntent().reset();

        if (cursor != null)
            cursor.close();
    }
}

From source file:org.canedata.provider.mongodb.entity.MongoEntity.java

License:Apache License

private void loadForMissedCacheHits(Map<Object, MongoFields> missed, Set<String> proj) {
    Set<Object> ids = missed.keySet();
    if (logger.isDebug())
        logger.debug("Loading data for missed cache hits, _id is {0}.", Arrays.toString(ids.toArray()));

    BasicDBObject query = new BasicDBObject();
    query.append("_id", new BasicDBObject().append("$in", ids.toArray()));

    DBCursor cursor = null;
    try {//w  ww  . jav  a2  s.c o  m
        cursor = getCollection().find(query);
        while (cursor.hasNext()) {
            BasicDBObject dbo = (BasicDBObject) cursor.next();

            Object id = dbo.get("_id");

            if (logger.isDebug())
                logger.debug("Loaded data for missed cache hits, _id is {0}.", id.toString());

            MongoFields mf = missed.get(id).putTarget(dbo);
            getCache().cache(mf.clone());
            if (!proj.isEmpty())
                mf.project(proj);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
}

From source file:org.canedata.provider.mongodb.entity.MongoEntity.java

License:Apache License

private void invalidateCache(BasicDBObject query) {
    DBCursor cursor = null;

    try {/*from  ww w.java  2  s  . co m*/
        cursor = getCollection().find(query, new BasicDBObject().append("_id", 1));

        while (cursor.hasNext()) {
            String key = cursor.next().get("_id").toString();
            String cacheKey = getKey().concat("#").concat(key);
            getCache().remove(cacheKey);

            if (logger.isDebug())
                logger.debug("Invalidated cache key is {0}.", cacheKey);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
}

From source file:org.codinjutsu.tools.mongo.logic.MongoManager.java

License:Apache License

private MongoCollectionResult find(MongoQueryOptions mongoQueryOptions,
        MongoCollectionResult mongoCollectionResult, DBCollection collection) {
    DBObject filter = mongoQueryOptions.getFilter();
    DBObject projection = mongoQueryOptions.getProjection();
    DBObject sort = mongoQueryOptions.getSort();

    DBCursor cursor;
    if (projection == null) {
        cursor = collection.find(filter);
    } else {/*  www  .j a va2  s  .  com*/
        cursor = collection.find(filter, projection);
    }

    if (sort != null) {
        cursor = cursor.sort(sort);
    }

    try {
        int index = 0;
        while (cursor.hasNext() && index < mongoQueryOptions.getResultLimit()) {
            mongoCollectionResult.add(cursor.next());
            index++;
        }
    } finally {
        cursor.close();
    }
    return mongoCollectionResult;
}