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: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 a  v  a2s  .  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;//from w w w .  j a v a 2s  .c om

    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 www.j  a  v  a2  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:mongoDB.MongoDbClientAllImagesAsByteArrays.java

License:Open Source License

@Override
public HashMap<String, String> getInitialStats() {

    HashMap<String, String> stats = new HashMap<String, String>();
    com.mongodb.DB db = null;// ww w  .  j a v a2  s .c  o m
    try {
        db = mongo.getDB(database);
        db.requestStart();
        // get the number of users
        DBCollection collection = db.getCollection("users");
        DBCursor users = collection.find();
        int usercnt = users.count();
        users.close();
        stats.put("usercount", Integer.toString(usercnt));

        // find user offset
        DBObject m = new BasicDBObject().append("_id", 1);
        DBCursor minUser = collection.find(m).limit(1);
        int offset = 0;
        if (minUser.hasNext())
            offset = (Integer) minUser.next().toMap().get("_id");
        minUser.close();
        // get the number of friends per user
        DBObject q = new BasicDBObject().append("_id", offset);
        DBObject queryResult = null;
        queryResult = collection.findOne(q);
        String x = queryResult.get("ConfFriends").toString();
        int frndCount = 0;
        if (x.equals("") || (!x.equals("") && (x.substring(2, x.length() - 1)).equals("")))
            frndCount = 0;
        else {
            x = x.substring(2, x.length() - 1);
            frndCount = x.split(",").length;
        }
        stats.put("avgfriendsperuser", Integer.toString(frndCount));

        x = queryResult.get("PendFriends").toString();
        int pendCount = 0;
        if (x.equals("") || (!x.equals("") && (x.substring(2, x.length() - 1)).equals("")))
            pendCount = 0;
        else {
            x = x.substring(2, x.length() - 1);
            pendCount = x.split(",").length;
        }
        stats.put("avgpendingperuser", Integer.toString(pendCount));

        // find number of resources for the user
        DBCollection resCollection = db.getCollection("resources");
        DBObject res = new BasicDBObject().append("creatorid", Integer.toString(offset));
        DBCursor resQueryResult = null;
        resQueryResult = resCollection.find(res);
        int resCount = resQueryResult.count();
        resQueryResult.close();
        stats.put("resourcesperuser", Integer.toString(resCount));
    } catch (Exception e) {
        e.printStackTrace(System.out);
    } finally {
        if (db != null)
            db.requestDone();
    }
    return stats;
}

From source file:mongodb.MongoDBOperations.java

License:Apache License

public void printQueryResult(DBCollection coll, BasicDBObject queryObject) {
    DBCursor cursor = coll.find(queryObject);
    int count = 0;
    try {/* www  .j  a  v a  2s  . c om*/
        while (cursor.hasNext()) {
            Object loc = cursor.next().get("user_location");
            if (loc != null) {
                String user_location = loc.toString();
                System.out.println(user_location);
            }
            count++;
        }
    } finally {
        cursor.close();
    }
    System.out.println(count + " records found.");
}

From source file:mongodb.MongoDBOperations.java

License:Apache License

public void geoFindAndUpdate(DBCollection coll, BasicDBObject queryObject) {
    int query_count = 0;
    int processed_count = 0;
    int updated_count = 0;
    DBCursor cursor = coll.find(queryObject);
    try {/* w ww .  ja  va 2s.com*/
        query_count = cursor.count();
        while (cursor.hasNext()) {
            BasicDBObject myDoc = (BasicDBObject) cursor.next();
            Object userLocationObj = myDoc.get("user_location");
            String location = String.valueOf(userLocationObj);

            ObjectId ID = (ObjectId) myDoc.get("_id");
            System.out.println("Queried Document: " + myDoc);

            GeoCodingClient gcc = new GeoCodingClient(this.conf);
            Thread.sleep(200);
            DBObject update = gcc.getGeoCode(location);
            //System.out.println(update);

            if (update == null) {
                System.out.print("No updates (update==null)");
                break;
            } else {
                Set<String> keyset = update.keySet();
                if (keyset == null) {
                    System.out.print("No updates (keyset==null)");
                } else if (keyset.contains("geocode")) {
                    updated_count++;
                    coll.update(new BasicDBObject().append("_id", ID),
                            myDoc.append("geocode", update.get("geocode")));
                    System.out.println(
                            "Updated Doc:\n" + coll.find(new BasicDBObject().append("_id", ID)).next());
                    System.out.println("In this run: (" + processed_count + " records processed, "
                            + updated_count + " records updated.)");
                } else if (keyset.contains("status")
                        && update.get("status").toString().contains("OVER_QUERY_LIMIT")) {
                    break;
                }
            }
            processed_count++;
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } finally {
        cursor.close();
        System.out.println("In this run:");
        System.out.println("Total:" + query_count + " record(s) found.");
        System.out.println("Total:" + processed_count + " record(s) processed.");
        System.out.println("Total:" + updated_count + " record(s) updated.");
    }

}

From source file:mongodb.querysix.java

public static void main(String[] args) throws UnknownHostException {
    //Connect to mongoDB
    MongoClient mongo = new MongoClient();
    //Connect to database and collection
    DB db = mongo.getDB("db");
    DBCollection partialCollection = db.getCollection("tags_import");
    //Create object that queries for MovieIDs that contain MST3k
    DBObject partial = new BasicDBObject("tag", "MST3K");
    //Use cursor to walk through collection one step at a time
    DBCursor cursor = partialCollection.find(partial);
    try {/* w w  w. ja  v  a2  s.  c  o  m*/
        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }
    } finally {
        cursor.close();
    }
}

From source file:mx.edu.cide.justiciacotidiana.v1.mongo.MongoInterface.java

License:Open Source License

/**
 * Obtiene la lista de los elementos de una coleccin en formato JSON. Si se proporciona una referencia, se hace un filtrado.
 * @param collectionName Nombre de la coleccin de donde se extraern los elementos.
 * @param query Objeto de referencia para la bsqueda.
 * @return Cadena JSON con el resultado.
 *//*from ww w.j a  v a2 s . com*/
public String listItemsAsJSON(String collectionName, BasicDBObject query) {
    DBCursor cursor = findItems(collectionName, query);
    cursor.sort(new BasicDBObject(FIELD_CREATED, -1));
    StringBuilder ret = new StringBuilder();
    long count = 0;

    if (null != cursor && cursor.hasNext()) {
        count = cursor.size();
    }
    ret.append("{\"count\":").append(count);
    if (cursor.hasNext()) {
        ret.append(", \"items\": [");
        try {
            while (cursor.hasNext()) {
                BasicDBObject t = (BasicDBObject) cursor.next();
                ret.append(Utils.JSON.toJSON(t));
                if (cursor.hasNext())
                    ret.append(",");
            }
        } finally {
            cursor.close();
        }
        ret.append("]");
    }
    ret.append("}");
    return ret.toString();
}

From source file:myControls.Main_view.java

private myPanel getGrid() {
    myPanel pnl = new myPanel();
    myTable table = new myTable();
    pnl.add(table);//from  ww  w .  j a  v a 2s  .co m
    //
    MongoClient mongoClient = null;
    DBCursor cursor = null;
    mongoClient = new MongoClient("localhost", 27017);
    DB db = mongoClient.getDB("kiaan");
    DBCollection coll = db.getCollection("banks");
    cursor = coll.find();
    String[] columnNames = { "id", "name" };
    DefaultTableModel model = new DefaultTableModel(columnNames, 0);
    while (cursor.hasNext()) {
        DBObject obj = cursor.next();
        String first = (String) obj.get("name");
        ObjectId id = (ObjectId) obj.get("_id");
        model.addRow(new Object[] { id, first });
    }
    table.setModel(model);
    cursor.close();
    mongoClient.close();
    //
    return pnl;
}

From source file:net.bluemix.todo.store.MongoStore.java

License:Open Source License

@Override
public Collection<ToDo> getAll() {
    List<ToDo> todos = new ArrayList<ToDo>();
    DBCursor cursor = coll.find();
    while (cursor.hasNext()) {
        todos.add(createToDo(cursor.next()));
    }//from  www  .  j a  v  a  2 s .c o m
    cursor.close();
    return todos;
}