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.codinjutsu.tools.nosql.mongo.logic.MongoClient.java

License:Apache License

private MongoResult find(MongoQueryOptions mongoQueryOptions, MongoResult mongoResult,
        DBCollection collection) {/*from w w  w. j  a v  a 2  s .com*/
    DBObject filter = mongoQueryOptions.getFilter();
    DBObject projection = mongoQueryOptions.getProjection();
    DBObject sort = mongoQueryOptions.getSort();

    DBCursor cursor;
    if (projection == null) {
        cursor = collection.find(filter);
    } else {
        cursor = collection.find(filter, projection);
    }

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

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

From source file:org.cryptorchat.json.JsonDBObject.java

License:Apache License

/**
 * This constructor fetch all values from a DBCursor and put the values to
 * an array./*from ww  w .  j ava  2  s.  com*/
 * @param name name of the new array
 * @param cursor the source of the data
 * TODO test for this!!
 */
public JsonDBObject(final String name, final DBCursor cursor) {
    super();
    try {
        final JsonArray array = new JsonArrayImpl();
        while (cursor.hasNext()) {
            final JsonValue value = ParserHelper.parseToJsonValue(cursor.next());
            array.add(value);
        }
        put(name, array);
    } finally {
        cursor.close();
    }
}

From source file:org.cvbase.service.mongodb.MongodbService.java

License:Open Source License

/**
 * {@inheritDoc}/*  www  . ja v  a2s.c  om*/
 *
 * This is an implementation for Mongo DB.
 */
@Override
public <T extends Model> T create(T t) {
    if (t == null) {
        return null;
    }

    BasicDBObject object = new BasicDBObject();

    Class<?> type = t.getClass();
    DBCollection coll = db.getCollection(type.getSimpleName());

    Long key = t.getOid();
    if (key == null) {
        // Set a new object identifier.
        DBCursor cursor = coll.find();
        key = (long) cursor.size() + 1;
        cursor.close();
    }
    t.setOid(key);

    if (find(t.getClass(), key) != null) {
        return null;
    }

    List<Field> fields = getDeclaredFields(type, new LinkedList<Field>());
    List<Method> methods = getDeclaredMethods(type, new LinkedList<Method>());

    for (Field field : fields) {
        for (Method method : methods) {
            // Call a getter method.
            if (("get" + field.getName()).equalsIgnoreCase(method.getName())) {
                try {
                    object.put(field.getName(), method.invoke(t));
                } catch (IllegalAccessException e) {
                    LOG.log(Level.WARNING, "Call of the method " + method.getName() + " is failed", e);
                } catch (InvocationTargetException e) {
                    LOG.log(Level.WARNING, "Call of the method " + method.getName() + " is failed", e);
                }
                break;
            }
        }
    }

    try {
        LOG.log(Level.INFO, "{0}", t);
        WriteResult writeResult = coll.insert(object);
        if (writeResult.getError() != null) {
            LOG.log(Level.WARNING, "Insertion of {0} is failed.", t);
        }
    } catch (MongoException e) {
        LOG.log(Level.SEVERE, "Insertion of " + t + " is failed.", e);
    }

    return t;
}

From source file:org.cvbase.service.mongodb.MongodbService.java

License:Open Source License

/**
 * {@inheritDoc}//from  w w  w.ja v  a  2s.co m
 *
 * This is an implementation for Mongo DB.
 */
@Override
public <T extends Model> T find(Class<T> type, Long oid) {
    T model = null;

    // Do query by an object identifier
    BasicDBObject query = new BasicDBObject();
    query.put(Model.OID, oid);

    DBCollection coll = db.getCollection(type.getSimpleName());
    DBCursor cursor = coll.find(query);
    try {
        if (cursor.hasNext()) {
            DBObject o = cursor.next();
            model = type.newInstance();

            List<Field> fields = getDeclaredFields(type, new LinkedList<Field>());
            List<Method> methods = getDeclaredMethods(type, new LinkedList<Method>());
            for (Field field : fields) {
                for (Method method : methods) {
                    // Call a setter method.
                    if (("set" + field.getName()).equalsIgnoreCase(method.getName())) {
                        try {
                            method.invoke(model, o.get(field.getName()));
                        } catch (IllegalAccessException e) {
                            LOG.log(Level.WARNING, "Call of the method " + method.getName() + " is failed", e);
                        } catch (InvocationTargetException e) {
                            LOG.log(Level.WARNING, "Call of the method " + method.getName() + " is failed", e);
                        }
                        break;
                    }
                }
            }

            LOG.log(Level.INFO, "{0}", model);
        }
    } catch (InstantiationException e) {
        LOG.log(Level.WARNING, "Model with a type " + type.getName() + " can't be created", e);
    } catch (IllegalAccessException e) {
        LOG.log(Level.WARNING, "Model with a type " + type.getName() + " can't be created", e);
    } finally {
        cursor.close();
    }

    return model;
}

From source file:org.cvbase.service.mongodb.MongodbService.java

License:Open Source License

/**
 * {@inheritDoc}/*from   w  w  w  .j  av a  2s.c om*/
 *
 * This is an implementation for Mongo DB.
 */
@Override
public <T extends Model> List<T> find(Class<T> type) {
    List<T> models = new LinkedList<T>();

    DBCollection coll = db.getCollection(type.getSimpleName());
    DBCursor cursor = coll.find();
    try {
        while (cursor.hasNext()) {
            models.add(find(type, (Long) cursor.next().get(Model.OID)));
        }
    } finally {
        cursor.close();
    }

    return models;
}

From source file:org.cvbase.service.mongodb.MongodbService.java

License:Open Source License

/**
 * {@inheritDoc}//from  w  w w .jav  a  2 s .  c  o m
 *
 * This is an implementation for Mongo DB.
 */
@Override
public <T extends Model> List<T> findWithParams(Class<T> type, Map<String, Object> params) {
    List<T> models = new LinkedList<T>();

    // Do query by map parameters.
    BasicDBObject query = new BasicDBObject();
    for (Map.Entry<String, Object> param : params.entrySet()) {
        query.put(param.getKey(), param.getValue());
    }

    DBCollection coll = db.getCollection(type.getSimpleName());
    DBCursor cursor = coll.find(query);
    try {
        DBObject o;
        T model;

        List<Field> fields = getDeclaredFields(type, new LinkedList<Field>());
        List<Method> methods = getDeclaredMethods(type, new LinkedList<Method>());
        while (cursor.hasNext()) {
            o = cursor.next();

            model = type.newInstance();
            for (Field field : fields) {
                for (Method method : methods) {
                    // Call a setter method.
                    if (("set" + field.getName()).equalsIgnoreCase(method.getName())) {
                        try {
                            method.invoke(model, o.get(field.getName()));
                        } catch (IllegalAccessException e) {
                            LOG.log(Level.WARNING, "Call of the method " + method.getName() + " is failed", e);
                        } catch (InvocationTargetException e) {
                            LOG.log(Level.WARNING, "Call of the method " + method.getName() + " is failed", e);
                        }
                        break;
                    }
                }
            }
            models.add(model);

            LOG.log(Level.INFO, "{0}", model);
        }
    } catch (InstantiationException e) {
        LOG.log(Level.WARNING, "Model with a type " + type.getName() + " can't be created", e);
    } catch (IllegalAccessException e) {
        LOG.log(Level.WARNING, "Model with a type " + type.getName() + " can't be created", e);
    } finally {
        cursor.close();
    }

    return models;
}

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

License:Open Source License

protected void showDocuments(CDOServerBrowser browser, PrintStream pout, DBCollection coll) {
    DBCursor cursor = null;

    try {/*from  ww w .  j  a  v  a2s.com*/
        pout.print(
                "<tr><td colspan=\"2\" align=\"center\" bgcolor=\"EEEEEE\"><h4>Documents</h4></td></tr>\r\n");

        int i = 0;
        cursor = coll.find();

        try {
            cursor = cursor.sort(new BasicDBObject("_id", 1));
        } catch (Exception ex) {
            // Ignore
        }

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

            ++i;
            if (i == 1 && showFirstCommit(coll)) {
                continue;
            }

            String bg = (i & 1) == 1 ? "bgcolor=\"DDDDDD\"" : "bgcolor=\"EEEEEE\"";
            pout.print("<tr><td valign=\"top\" " + bg + "><b>" + i + "&nbsp;</b></td><td valign=\"top\">");
            showObject(browser, pout, doc, "");
            pout.print("</td></tr>\r\n");
        }

        pout.print("</table>\r\n");
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

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

License:Open Source License

public Map<String, String> get(Set<String> names) {
    Map<String, String> result = new HashMap<String, String>();
    for (String name : names) {
        DBObject query = new BasicDBObject(ID, name);
        DBCursor cursor = collection.find(query);

        try {/*from  w  ww.ja  va 2s .c  o m*/
            if (cursor.hasNext()) {
                DBObject doc = cursor.next();
                result.put(name, (String) doc.get(VALUE));
            }
        } finally {
            cursor.close();
        }
    }

    return result;
}

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

License:Open Source License

/** 
 * @see org.eclipse.jetty.server.session.SessionDataStore#getExpired(Set)
 *///from   www .  j  a v a 2s . com
@Override
public Set<String> doGetExpired(Set<String> candidates) {
    long now = System.currentTimeMillis();
    long upperBound = now;
    Set<String> expiredSessions = new HashSet<>();

    //firstly ask mongo to verify if these candidate ids have expired - all of
    //these candidates will be for our node
    BasicDBObject query = new BasicDBObject();
    query.append(__ID, new BasicDBObject("$in", candidates));
    query.append(__EXPIRY, new BasicDBObject("$gt", 0).append("$lt", upperBound));

    DBCursor verifiedExpiredSessions = null;
    try {
        verifiedExpiredSessions = _dbSessions.find(query, new BasicDBObject(__ID, 1));
        for (DBObject session : verifiedExpiredSessions) {
            String id = (String) session.get(__ID);
            if (LOG.isDebugEnabled())
                LOG.debug("{} Mongo confirmed expired session {}", _context, id);
            expiredSessions.add(id);
        }
    } finally {
        if (verifiedExpiredSessions != null)
            verifiedExpiredSessions.close();
    }

    //now ask mongo to find sessions last managed by any nodes that expired a while ago 
    //if this is our first expiry check, make sure that we only grab really old sessions
    if (_lastExpiryCheckTime <= 0)
        upperBound = (now - (3 * (1000L * _gracePeriodSec)));
    else
        upperBound = _lastExpiryCheckTime - (1000L * _gracePeriodSec);

    query = new BasicDBObject();
    BasicDBObject gt = new BasicDBObject(__EXPIRY, new BasicDBObject("$gt", 0));
    BasicDBObject lt = new BasicDBObject(__EXPIRY, new BasicDBObject("$lt", upperBound));
    BasicDBList list = new BasicDBList();
    list.add(gt);
    list.add(lt);
    query.append("and", list);

    DBCursor oldExpiredSessions = null;
    try {
        BasicDBObject bo = new BasicDBObject(__ID, 1);
        bo.append(__EXPIRY, 1);

        oldExpiredSessions = _dbSessions.find(query, bo);
        for (DBObject session : oldExpiredSessions) {
            String id = (String) session.get(__ID);
            if (LOG.isDebugEnabled())
                LOG.debug("{} Mongo found old expired session {}", _context,
                        id + " exp=" + session.get(__EXPIRY));
            expiredSessions.add(id);
        }

    } finally {
        oldExpiredSessions.close();
    }

    return expiredSessions;
}

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

License:Open Source License

/** 
 * @see org.eclipse.jetty.server.session.SessionStore#getExpired(Set)
 *///w  w w.  j  a v  a2 s.  c  o  m
@Override
public Set<String> doGetExpired(Set<String> candidates) {
    long now = System.currentTimeMillis();
    long upperBound = now;
    Set<String> expiredSessions = new HashSet<>();

    //firstly ask mongo to verify if these candidate ids have expired - all of
    //these candidates will be for our node
    BasicDBObject query = new BasicDBObject();
    query.put(__ID, new BasicDBObject("$in", candidates));
    query.put(__EXPIRY, new BasicDBObject("$gt", 0));
    query.put(__EXPIRY, new BasicDBObject("$lt", upperBound));

    DBCursor verifiedExpiredSessions = null;
    try {
        verifiedExpiredSessions = _dbSessions.find(query, new BasicDBObject(__ID, 1));
        for (DBObject session : verifiedExpiredSessions) {
            String id = (String) session.get(__ID);
            if (LOG.isDebugEnabled())
                LOG.debug("{} Mongo confirmed expired session {}", _context, id);
            expiredSessions.add(id);
        }
    } finally {
        if (verifiedExpiredSessions != null)
            verifiedExpiredSessions.close();
    }

    //now ask mongo to find sessions last managed by other nodes that expired a while ago 
    //if this is our first expiry check, make sure that we only grab really old sessions
    if (_lastExpiryCheckTime <= 0)
        upperBound = (now - (3 * (1000L * _gracePeriodSec)));
    else
        upperBound = _lastExpiryCheckTime - (1000L * _gracePeriodSec);

    query.clear();
    query.put(__EXPIRY, new BasicDBObject("$gt", 0));
    query.put(__EXPIRY, new BasicDBObject("$lt", upperBound));

    DBCursor oldExpiredSessions = null;
    try {
        oldExpiredSessions = _dbSessions.find(query, new BasicDBObject(__ID, 1));
        for (DBObject session : oldExpiredSessions) {
            String id = (String) session.get(__ID);
            if (LOG.isDebugEnabled())
                LOG.debug("{} Mongo found old expired session {}", _context, id);
            expiredSessions.add(id);
        }

    } finally {
        oldExpiredSessions.close();
    }

    return expiredSessions;
}