Example usage for com.mongodb DBCursor count

List of usage examples for com.mongodb DBCursor count

Introduction

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

Prototype

public int count() 

Source Link

Document

Counts the number of objects matching the query.

Usage

From source file:org.anyframe.logmanager.bundle.core.LogCollectionManager.java

License:Apache License

/**
 * @throws Exception/*from   www  .j  a v  a 2s  .c  om*/
 */
public static void startManager() throws Exception {
    BasicDBObject query = new BasicDBObject();
    query.put("agentId", agentId);
    query.put("status", LogManagerConstant.APP_STATUS_ACTIVE);
    DBCursor appCursor = logApplication.find(query);

    logger.info("Application count is {}", appCursor.count());
    if (appCursor.count() > 0) {

        if (timer != null)
            timer.cancel();
        timer = new Timer();

        Iterator<DBObject> i = appCursor.iterator();
        while (i.hasNext()) {
            String appName = i.next().get("appName").toString();
            logger.info("Application name is {}", appName);

            DBCursor logCollectionCursor = logCollection.find(new BasicDBObject("appName", appName)
                    .append("agentId", agentId).append("setLogCollectionActive", true));

            while (logCollectionCursor.hasNext()) {
                setTimerTask(logCollectionCursor.next(), appName);
            }
            logCollectionCursor.close();
        }
    }
    appCursor.close();
    logger.info("HarvestManager is started.");
    updateAgentInfo(LogManagerConstant.AGENT_STATUS_ACTIVE);
}

From source file:org.apache.camel.component.gridfs.GridFsProducer.java

License:Apache License

public void process(Exchange exchange) throws Exception {
    String operation = endpoint.getOperation();
    if (operation == null) {
        operation = exchange.getIn().getHeader(GridFsEndpoint.GRIDFS_OPERATION, String.class);
    }/*  w  w  w .  j a  v  a 2 s .  c o  m*/
    if (operation == null || "create".equals(operation)) {
        final String filename = exchange.getIn().getHeader(Exchange.FILE_NAME, String.class);
        Long chunkSize = exchange.getIn().getHeader(GridFsEndpoint.GRIDFS_CHUNKSIZE, Long.class);

        InputStream ins = exchange.getIn().getMandatoryBody(InputStream.class);
        GridFSInputFile gfsFile = endpoint.getGridFs().createFile(ins, filename, true);
        if (chunkSize != null && chunkSize > 0) {
            gfsFile.setChunkSize(chunkSize);
        }
        final String ct = exchange.getIn().getHeader(Exchange.CONTENT_TYPE, String.class);
        if (ct != null) {
            gfsFile.setContentType(ct);
        }
        String metaData = exchange.getIn().getHeader(GridFsEndpoint.GRIDFS_METADATA, String.class);
        DBObject dbObject = (DBObject) JSON.parse(metaData);
        gfsFile.setMetaData(dbObject);
        gfsFile.save();
        exchange.getIn().setHeader(Exchange.FILE_NAME_PRODUCED, gfsFile.getFilename());
    } else if ("remove".equals(operation)) {
        final String filename = exchange.getIn().getHeader(Exchange.FILE_NAME, String.class);
        endpoint.getGridFs().remove(filename);
    } else if ("findOne".equals(operation)) {
        final String filename = exchange.getIn().getHeader(Exchange.FILE_NAME, String.class);
        GridFSDBFile file = endpoint.getGridFs().findOne(filename);
        if (file != null) {
            exchange.getIn().setHeader(GridFsEndpoint.GRIDFS_METADATA, JSON.serialize(file.getMetaData()));
            exchange.getIn().setHeader(Exchange.FILE_CONTENT_TYPE, file.getContentType());
            exchange.getIn().setHeader(Exchange.FILE_LENGTH, file.getLength());
            exchange.getIn().setHeader(Exchange.FILE_LAST_MODIFIED, file.getUploadDate());
            exchange.getIn().setBody(file.getInputStream(), InputStream.class);
        } else {
            throw new FileNotFoundException("No GridFS file for " + filename);
        }
    } else if ("listAll".equals(operation)) {
        final String filename = exchange.getIn().getHeader(Exchange.FILE_NAME, String.class);
        DBCursor cursor;
        if (filename == null) {
            cursor = endpoint.getGridFs().getFileList();
        } else {
            cursor = endpoint.getGridFs().getFileList(new BasicDBObject("filename", filename));
        }
        exchange.getIn().setBody(new DBCursorFilenameReader(cursor), Reader.class);
    } else if ("count".equals(operation)) {
        final String filename = exchange.getIn().getHeader(Exchange.FILE_NAME, String.class);
        DBCursor cursor;
        if (filename == null) {
            cursor = endpoint.getGridFs().getFileList();
        } else {
            cursor = endpoint.getGridFs().getFileList(new BasicDBObject("filename", filename));
        }
        exchange.getIn().setBody(cursor.count(), Integer.class);
    }

}

From source file:org.apache.camel.component.mongodb.MongoDbProducer.java

License:Apache License

protected void doFindAll(Exchange exchange) throws Exception {
    DBCollection dbCol = calculateCollection(exchange);
    // do not use getMandatoryBody, because if the body is empty we want to retrieve all objects in the collection
    DBObject query = null;/* ww  w .j  a  v  a2s  .  c  om*/
    // do not run around looking for a type converter unless there is a need for it
    if (exchange.getIn().getBody() != null) {
        query = exchange.getIn().getBody(DBObject.class);
    }
    DBObject fieldFilter = exchange.getIn().getHeader(MongoDbConstants.FIELDS_FILTER, DBObject.class);

    // get the batch size and number to skip
    Integer batchSize = exchange.getIn().getHeader(MongoDbConstants.BATCH_SIZE, Integer.class);
    Integer numToSkip = exchange.getIn().getHeader(MongoDbConstants.NUM_TO_SKIP, Integer.class);
    Integer limit = exchange.getIn().getHeader(MongoDbConstants.LIMIT, Integer.class);
    DBObject sortBy = exchange.getIn().getHeader(MongoDbConstants.SORT_BY, DBObject.class);
    DBCursor ret = null;
    try {
        if (query == null && fieldFilter == null) {
            ret = dbCol.find(new BasicDBObject());
        } else if (fieldFilter == null) {
            ret = dbCol.find(query);
        } else {
            ret = dbCol.find(query, fieldFilter);
        }

        if (sortBy != null) {
            ret.sort(sortBy);
        }

        if (batchSize != null) {
            ret.batchSize(batchSize.intValue());
        }

        if (numToSkip != null) {
            ret.skip(numToSkip.intValue());
        }

        if (limit != null) {
            ret.limit(limit.intValue());
        }

        Message resultMessage = prepareResponseMessage(exchange, MongoDbOperation.findAll);
        resultMessage.setBody(ret.toArray());
        resultMessage.setHeader(MongoDbConstants.RESULT_TOTAL_SIZE, ret.count());
        resultMessage.setHeader(MongoDbConstants.RESULT_PAGE_SIZE, ret.size());

    } catch (Exception e) {
        // rethrow the exception
        throw e;
    } finally {
        // make sure the cursor is closed
        if (ret != null) {
            ret.close();
        }
    }

}

From source file:org.basex.modules.MongoDB.java

License:BSD License

/**
 * Convert collection result(DBCursor) into Item {@link Item} element.
 * @param result DBCursor/*from  w ww. j a  v  a2  s .  c o  m*/
 * @return Item
 * @throws QueryException
 */
private Item cursorToItem(final Str handler, final DBCursor cursor) throws QueryException {
    if (cursor != null) {
        try {
            if (cursor.count() == 1) {
                Iterator<DBObject> row = cursor.iterator();
                return objectToItem(handler, row.next());
            } else {
                final Str json = Str.get(JSON.serialize(cursor));
                return returnResult(handler, json);
            }
        } catch (final Exception ex) {
            throw MongoDBErrors.generalExceptionError(ex);
        }
    } else {
        return null;
    }
}

From source file:org.basex.modules.MongoDB.java

License:BSD License

/**
 * MongoDB find with all parameters.//from   w w w  . j av  a2s  .  co  m
 * @param handler Database handler
 * @param col collection
 * @param query Query parameters
 * @param opt options in Map like: {"limit":2}
 * @param field  Projection
 * @return Item
 * @throws QueryException
 */
public Item find(final Str handler, final Item col, final Item query, final Item opt, final Item projection)
        throws QueryException {
    final DB db = getDbHandler(handler);
    db.requestStart();
    try {
        DBObject p = null;
        if (opt != null && opt instanceof Str) {
            p = getDbObjectFromStr(opt);
        } else if (projection != null && projection instanceof Str) {
            p = getDbObjectFromStr(projection);
        }
        final DBObject q = query != null ? getDbObjectFromStr(query) : null;
        final DBCollection coll = db.getCollection(itemToString(col));
        final DBCursor cursor = coll.find(q, p);
        Map options = null;
        options = (opt != null && opt instanceof Map) ? (Map) opt
                : (projection != null && projection instanceof Map) ? (Map) projection : null;
        if (options != null) {
            Value keys = options.keys();
            for (final Item key : keys) {
                if (!(key instanceof Str))
                    throw MongoDBErrors.generalExceptionError("String expected " + key.toJava());
                final String k = ((Str) key).toJava();
                final Value v = options.get(key, null);
                if (v instanceof Str || v.type().instanceOf(SeqType.ITR)) {
                    if (k.equals(LIMIT)) {
                        if (v.type().instanceOf(SeqType.ITR_OM)) {
                            long l = ((Item) v).itr(null);
                            cursor.limit((int) l);
                        } else {
                            throw MongoDBErrors
                                    .generalExceptionError("Number Expected for key '" + key.toJava() + "'");
                        }
                    } else if (k.equals(SKIP)) {
                        //cursor.skip(Token.toInt(v));
                    } else if (k.equals(SORT)) {
                        BasicDBObject sort = new BasicDBObject(k, v);
                        sort.append("name", "-1");
                        cursor.sort((DBObject) sort);
                    } else if (k.equals(COUNT)) {
                        int count = cursor.count();
                        BasicDBObject res = new BasicDBObject();
                        res.append("count", count);
                        return objectToItem(handler, res);
                    } else if (k.equals(EXPLAIN)) {
                        DBObject result = cursor.explain();
                        return objectToItem(handler, result);
                    }
                } else if (v instanceof Map) {
                } else {
                    throw MongoDBErrors.generalExceptionError("Invalid value 2...");
                }
            }
        }
        return cursorToItem(handler, cursor);
    } catch (MongoException e) {
        throw MongoDBErrors.generalExceptionError(e.getMessage());
    } finally {
        db.requestDone();
    }
}

From source file:org.basex.modules.nosql.MongoDB.java

License:BSD License

/**
 * Convert collection result(DBCursor) into Item {@link Item} element.
 * @param handler database handler//www.jav  a 2s.  com
 * @param cursor DBcursor
 * @return Item
 * @throws QueryException query exception
 */
private Item cursorToItem(final Str handler, final DBCursor cursor) throws QueryException {
    if (cursor != null) {
        try {
            if (cursor.count() == 1) {
                Iterator<DBObject> row = cursor.iterator();
                return objectToItem(handler, row.next());
            }
            final Str json = Str.get(JSON.serialize(cursor));
            return returnResult(handler, json);
        } catch (final Exception ex) {
            throw MongoDBErrors.generalExceptionError(ex);
        }
    }
    return null;
}

From source file:org.basex.modules.nosql.MongoDB.java

License:BSD License

/**
 * MongoDB find with all parameters./*  w ww.j ava 2 s. c o  m*/
 * @param handler database handler Database handler
 * @param col collection collection
 * @param query Query parameters
 * @param opt options in Map like: {"limit":2}
 * @param projection projection (selection field)
 * @return Item
 * @throws QueryException query exception
 */
public Item find(final Str handler, final Item col, final Item query, final Item opt, final Item projection)
        throws QueryException {
    final DB db = getDbHandler(handler);
    db.requestStart();
    try {
        DBObject p = null;
        if (opt != null && opt instanceof Str) {
            p = getDbObjectFromItem(opt);
        } else if (projection != null && projection instanceof Str) {
            p = getDbObjectFromItem(projection);
        }
        final DBObject q = query != null ? getDbObjectFromItem(query) : null;
        final DBCollection coll = db.getCollection(itemToString(col));
        final DBCursor cursor = coll.find(q, p);
        Map options = null;
        options = (opt != null && opt instanceof Map) ? (Map) opt
                : (projection != null && projection instanceof Map) ? (Map) projection : null;
        if (options != null) {
            Value keys = options.keys();
            for (final Item key : keys) {
                if (!(key instanceof Str))
                    throw MongoDBErrors.generalExceptionError("String expected " + key.toJava());
                final String k = ((Str) key).toJava();
                final Value v = options.get(key, null);
                if (v instanceof Str || v.seqType().instanceOf(SeqType.ITR)) {
                    if (k.equals(LIMIT)) {
                        if (v.seqType().instanceOf(SeqType.ITR_OM)) {
                            long l = ((Item) v).itr(null);
                            cursor.limit((int) l);
                        } else {
                            throw MongoDBErrors
                                    .generalExceptionError("Number Expected for key '" + key.toJava() + "'");
                        }
                    } else if (k.equals(SKIP)) {
                        //cursor.skip(Token.toInt(v));
                    } else if (k.equals(SORT)) {
                        BasicDBObject sort = new BasicDBObject(k, v);
                        sort.append("name", "-1");
                        cursor.sort(sort);
                    } else if (k.equals(COUNT)) {
                        int count = cursor.count();
                        BasicDBObject res = new BasicDBObject();
                        res.append("count", count);
                        return objectToItem(handler, res);
                    } else if (k.equals(EXPLAIN)) {
                        DBObject result = cursor.explain();
                        return objectToItem(handler, result);
                    }
                } else if (v instanceof Map) {
                } else {
                    throw MongoDBErrors.generalExceptionError("Invalid value 2...");
                }
            }
        }
        return cursorToItem(handler, cursor);
    } catch (MongoException e) {
        throw MongoDBErrors.generalExceptionError(e.getMessage());
    } finally {
        db.requestDone();
    }
}

From source file:org.benjp.services.mongodb.ChatServiceImpl.java

License:Open Source License

public int getNumberOfRooms() {
    DBCollection coll = db().getCollection(M_ROOM_PREFIX + M_ROOMS_COLLECTION);
    BasicDBObject query = new BasicDBObject();
    DBCursor cursor = coll.find(query);
    return cursor.count();
}

From source file:org.benjp.services.mongodb.ChatServiceImpl.java

License:Open Source License

public int getNumberOfMessages() {
    int nb = 0;/*from  w w w.  jav  a  2  s. c o  m*/
    DBCollection coll = db().getCollection(M_ROOM_PREFIX + M_ROOMS_COLLECTION);
    BasicDBObject query = new BasicDBObject();
    DBCursor cursor = coll.find(query);
    while (cursor.hasNext()) {
        DBObject dbo = cursor.next();
        String roomId = dbo.get("_id").toString();
        DBCollection collr = db().getCollection(M_ROOM_PREFIX + roomId);
        BasicDBObject queryr = new BasicDBObject();
        DBCursor cursorr = collr.find(queryr);
        //      log.info(roomId+" = "+cursorr.count());
        nb += cursorr.count();
    }

    return nb;
}

From source file:org.benjp.services.mongodb.NotificationServiceImpl.java

License:Open Source License

public int getNumberOfNotifications() {
    DBCollection coll = db().getCollection(M_NOTIFICATIONS);
    BasicDBObject query = new BasicDBObject();
    DBCursor cursor = coll.find(query);
    return cursor.count();
}