Example usage for com.mongodb DBCursor iterator

List of usage examples for com.mongodb DBCursor iterator

Introduction

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

Prototype

@Override
public Iterator<DBObject> iterator() 

Source Link

Document

Creates a copy of this cursor object that can be iterated.

Usage

From source file:mongoDB.MongoDbClientAllImagesAsByteArrays.java

License:Open Source License

@Override
public int viewTopKResources(int requesterID, int profileOwnerID, int k,
        Vector<HashMap<String, ByteIterator>> result) {
    int retVal = 0;
    if (profileOwnerID < 0 || requesterID < 0 || k < 0)
        return -1;

    com.mongodb.DB db = null;/*from   w w  w  .j  ava  2  s .  c o m*/

    try {
        db = mongo.getDB(database);
        db.requestStart();
        if (scanResources) {
            DBCollection collection = db.getCollection("resources");
            // find all resources that belong to profileOwnerID
            // sort them by _id desc coz we want latest ones and get the top
            // k
            DBObject q = new BasicDBObject().append("walluserid", Integer.toString(profileOwnerID));
            DBCursor queryResult = null;
            queryResult = collection.find(q);
            // DBObject s = new BasicDBObject().append("_id", -1); //desc
            DBObject s = new BasicDBObject(); // desc
            s.put("_id", -1);
            queryResult = queryResult.sort(s);
            queryResult = queryResult.limit(k);
            Iterator it = queryResult.iterator();
            while (it.hasNext()) {
                HashMap<String, ByteIterator> vals = new HashMap<String, ByteIterator>();
                DBObject oneRes = new BasicDBObject();
                oneRes.putAll((DBObject) it.next());
                vals.putAll(oneRes.toMap());
                // needed to do this so the coreworkload will not need to
                // know the datastore type
                if (vals.get("_id") != null) {
                    String tmp = vals.get("_id") + "";
                    vals.remove("_id");
                    vals.put("rid", new ObjectByteIterator(tmp.getBytes()));
                }
                if (vals.get("walluserid") != null) {
                    String tmp = vals.get("walluserid") + "";
                    vals.remove("walluserid");
                    vals.put("walluserid", new ObjectByteIterator(tmp.getBytes()));
                }
                if (vals.get("creatorid") != null) {
                    String tmp = vals.get("creatorid") + "";
                    vals.remove("creatorid");
                    vals.put("creatorid", new ObjectByteIterator(tmp.getBytes()));
                }
                result.add(vals);
            }
            queryResult.close();

        } else {
            DBCollection collection = db.getCollection("users");
            DBObject q = new BasicDBObject().append("_id", profileOwnerID);
            DBObject queryResult = null;
            queryResult = collection.findOne(q);
            String x = queryResult.get("wallResources").toString();
            if (!x.equals("[ ]")) {
                x = x.substring(1, x.length() - 1);
                String resourceIds[] = x.split(",");
                BasicDBObject query = new BasicDBObject();
                List<Integer> list = new ArrayList<Integer>();
                for (int i = resourceIds.length - 1; i >= resourceIds.length
                        - Math.min(k, resourceIds.length); i--) { // to
                    // limit
                    // it
                    list.add(Integer.parseInt(resourceIds[i].trim()));
                }
                collection = db.getCollection("resources");
                query.put("_id", new BasicDBObject("$in", list));
                DBCursor cursor = collection.find(query);
                while (cursor.hasNext()) {
                    HashMap<String, ByteIterator> vals = new HashMap<String, ByteIterator>();
                    vals.putAll(cursor.next().toMap());
                    if (vals.get("_id") != null) {
                        String tmp = vals.get("_id") + "";
                        vals.remove("_id");
                        vals.put("rid", new ObjectByteIterator(tmp.getBytes()));
                    }
                    if (vals.get("walluserid") != null) {
                        String tmp = vals.get("walluserid") + "";
                        vals.remove("walluserid");
                        vals.put("walluserid", new ObjectByteIterator(tmp.getBytes()));
                    }
                    if (vals.get("creatorid") != null) {
                        String tmp = vals.get("creatorid") + "";
                        vals.remove("creatorid");
                        vals.put("creatorid", new ObjectByteIterator(tmp.getBytes()));
                    }
                    result.add(vals);
                }
                cursor.close();
            }
        }
    } catch (Exception e) {
        System.out.println(e.toString());
        retVal = -1;
    } finally {
        if (db != null) {
            db.requestDone();
        }
    }
    return retVal;

}

From source file:mongoDB.MongoDbClientAllImagesAsByteArrays.java

License:Open Source License

public int getCreatedResources(int creatorID, Vector<HashMap<String, ByteIterator>> result) {
    int retVal = 0;
    if (creatorID < 0)
        return -1;

    com.mongodb.DB db = null;/*w w w  . ja v  a  2  s. com*/

    try {
        db = mongo.getDB(database);
        db.requestStart();
        DBCollection collection = db.getCollection("resources");
        // find all resources that belong to profileOwnerID
        // sort them by _id desc coz we want latest ones and get the top k
        DBObject q = new BasicDBObject().append("creatorid", Integer.toString(creatorID));
        DBCursor queryResult = null;
        queryResult = collection.find(q);
        // DBObject s = new BasicDBObject().append("_id", -1); //desc
        DBObject s = new BasicDBObject(); // desc
        s.put("_id", -1);
        queryResult = queryResult.sort(s);
        Iterator it = queryResult.iterator();
        while (it.hasNext()) {
            HashMap<String, ByteIterator> vals = new HashMap<String, ByteIterator>();
            DBObject oneRes = new BasicDBObject();
            oneRes.putAll((DBObject) it.next());
            vals.putAll(oneRes.toMap());
            // needed to do this so the coreworkload will not need to know
            // the datastore typr
            if (vals.get("_id") != null) {
                String tmp = vals.get("_id") + "";
                vals.remove("_id");
                vals.put("rid", new ObjectByteIterator(tmp.getBytes()));
            }
            if (vals.get("creatorid") != null) {
                String tmp = vals.get("creatorid") + "";
                vals.remove("creatorid");
                vals.put("creatorid", new ObjectByteIterator(tmp.getBytes()));
            }
            result.add(vals);
        }
        queryResult.close();

    } catch (Exception e) {
        System.out.println(e.toString());
        retVal = -1;
    } finally {
        if (db != null) {
            db.requestDone();
        }
    }
    return retVal;

}

From source file:mongoDB.MongoDbClientAllImagesAsByteArrays.java

License:Open Source License

@Override
public int viewCommentOnResource(int requesterID, int profileOwnerID, int resourceID,
        Vector<HashMap<String, ByteIterator>> result) {
    int retVal = 0;
    if (profileOwnerID < 0 || requesterID < 0 || resourceID < 0)
        return -1;

    com.mongodb.DB db = null;/*from  w  w w.j av a 2 s.c  o m*/

    try {
        db = mongo.getDB(database);
        db.requestStart();
        if (!manipulationArray) {
            DBCollection collection = db.getCollection("manipulation");
            // find all resources that belong to profileOwnerID
            // sort them by _id desc coz we want latest ones and get the top
            // k
            DBObject q = new BasicDBObject().append("rid", Integer.toString(resourceID));
            DBCursor queryResult = null;
            queryResult = collection.find(q);
            Iterator<DBObject> it = queryResult.iterator();
            while (it.hasNext()) {
                HashMap<String, ByteIterator> vals = new HashMap<String, ByteIterator>();
                DBObject oneRes = new BasicDBObject();
                oneRes.putAll((DBObject) it.next());
                vals.putAll(oneRes.toMap());
                result.add(vals);
            }
            queryResult.close();
        } else {
            DBCollection collection = db.getCollection("resources");
            DBObject q = new BasicDBObject().append("_id", resourceID);
            DBObject queryResult = null;
            queryResult = collection.findOne(q);
            if (queryResult.get("Manipulations") != "" && queryResult.get("Manipulations") != null) {
                ArrayList<DBObject> mans = (ArrayList<DBObject>) queryResult.get("Manipulations");
                for (int i = 0; i < mans.size(); i++) {
                    result.add((HashMap<String, ByteIterator>) mans.get(i).toMap());
                }
            }
        }

    } catch (Exception e) {
        System.out.println(e.toString());
        retVal = -1;
    } finally {
        if (db != null) {
            db.requestDone();
        }
    }
    return retVal;
}

From source file:net.cit.tetrad.rrd.dao.MongoStatusToMonitorImpl.java

License:Open Source License

public List<Object> readMongoShards(Mongo mongo, String collection, String databaseName)
        throws MongoException, Exception {
    List<Object> dboLst = new ArrayList<Object>();
    try {/*from w  w  w.  j  a  va2s .  co  m*/
        DB db = mongo.getDB(databaseName);
        DBCollection dbcollection = db.getCollectionFromString(collection);
        DBCursor cr = dbcollection.find();
        Iterator<DBObject> it = cr.iterator();
        DBObject dbo;
        while (it.hasNext()) {
            dbo = it.next();
            Map<String, Object> deviceStatus = new HashMap<String, Object>();
            deviceStatus = JasonUtil.getEntryValue(dbo, "", deviceStatus);
            dboLst.add(deviceStatus);
        }
    } catch (DataAccessResourceFailureException e) {
        e.printStackTrace();
        throw new MongoException(e.getMessage());
    } catch (MongoException e) {
        e.printStackTrace();
        throw e;
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    } finally {

    }
    return dboLst;
}

From source file:net.ymate.platform.persistence.mongodb.support.MongoDBHelper.java

License:Apache License

public Iterable<DBObject> mapReduce(String collectionName, String map, String reduce, String outputTarget,
        OutputType type, OrderBy order, int pageNumber, int pageSize, DBObject query) throws OperatorException {
    MapReduceOutput _output = getCollection(collectionName).mapReduce(map, reduce, outputTarget, type, query);
    CommandResult _result = _output.getCommandResult();
    if (!_result.ok()) {
        throw new OperatorException(_result.getErrorMessage());
    }// w  w w .  j a  v a2s  .c o m
    DBCollection _collection = _output.getOutputCollection();
    DBCursor _cursor = null;
    if (order != null) {
        _cursor = _collection.find().sort(order.toDBObject());
    } else {
        _cursor = _collection.find();
    }
    if (pageNumber > 0 && pageSize > 0) {
        _cursor.skip((pageNumber - 1) * pageSize).limit(pageSize);
    }
    List<DBObject> _results = new ArrayList<DBObject>();
    for (Iterator<DBObject> _it = _cursor.iterator(); _it.hasNext();) {
        _results.add(_it.next());
    }
    return _results;
}

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

License:Apache License

/**
 * @throws Exception//  ww  w . j  a v a  2  s  .  co m
 */
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.bananaforscale.cormac.dao.gridfs.GridFsDataServiceImpl.java

License:Apache License

/**
 * Returns all the files in a bucket.//from  w w w .  java  2  s.  c o  m
 *
 * @param databaseName the database
 * @param bucketName the bucket
 * @return the files in the bucket
 * @throws DatasourceException
 * @throws NotFoundException
 */
@Override
public List<String> getAll(String databaseName, String bucketName)
        throws DatasourceException, NotFoundException {
    try {
        if (!databaseExists(databaseName)) {
            throw new NotFoundException("The database doesn't exist in the datasource");
        }
        if (!bucketExists(databaseName, bucketName)) {
            throw new NotFoundException("The bucket doesn't exist in the database");
        }
        DB mongoDatabase = mongoClient.getDB(databaseName);
        GridFS gfsBucket = new GridFS(mongoDatabase, bucketName);
        DBCursor cursor = gfsBucket.getFileList();
        Iterator<DBObject> curIter = cursor.iterator();
        List<String> fileList = new ArrayList<>();
        while (curIter.hasNext()) {
            DBObject current = curIter.next();
            fileList.add(JSON.serialize(current));
        }
        return fileList;
    } catch (MongoException ex) {
        logger.error("An error occured while retrieving file list", ex);
        throw new DatasourceException("An error occured while retrieving file list");
    }

}

From source file:org.bananaforscale.cormac.dao.gridfs.GridFsDataServiceImpl.java

License:Apache License

/**
 * Removes all files in a bucket./*ww  w.  j  a va  2s.  co  m*/
 *
 * @param databaseName the database
 * @param bucketName the bucket
 * @return a status message with the outcome of the operation
 * @throws DatasourceException
 * @throws NotFoundException
 */
@Override
public boolean removeAll(String databaseName, String bucketName) throws DatasourceException, NotFoundException {
    try {
        if (!databaseExists(databaseName)) {
            throw new NotFoundException("The database doesn't exist in the datasource");
        }
        DB mongoDatabase = mongoClient.getDB(databaseName);
        GridFS gfsBucket = new GridFS(mongoDatabase, bucketName); // TODO: determine behavior if bucket doesnt exist
        DBCursor cursor = gfsBucket.getFileList();
        Iterator<DBObject> curIter = cursor.iterator();
        while (curIter.hasNext()) {
            DBObject current = curIter.next();
            gfsBucket.remove(current);
        }
        return true;
    } catch (MongoException ex) {
        logger.error("An error occured while removing files", ex);
        throw new DatasourceException("An error occured while removing files");
    }
}

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

License:BSD License

/**
 * Convert collection result(DBCursor) into Item {@link Item} element.
 * @param result DBCursor/*from  ww w.j av  a 2  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.nosql.MongoDB.java

License:BSD License

/**
 * Convert collection result(DBCursor) into Item {@link Item} element.
 * @param handler database handler//from   ww  w .ja v a 2  s  . c  om
 * @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;
}