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:com.cyslab.craftvm.rest.mongo.QueryServlet.java

License:GNU General Public License

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    log.trace("doPost()");

    // server auth
    if (!can_read(req)) {
        res.sendError(SC_UNAUTHORIZED);/* w  ww. ja va2 s.c  o  m*/
        return;
    }

    String ret = null;

    InputStream is = req.getInputStream();
    String db_name = req.getParameter("dbname");
    String col_name = req.getParameter("colname");
    if (db_name == null || col_name == null) {
        String names[] = req2mongonames(req);
        if (names != null) {
            db_name = names[0];
            col_name = names[1];
        }
        if (db_name == null || col_name == null) {
            error(res, SC_BAD_REQUEST, Status.get("param name missing"));
            return;
        }
    }
    String skip = req.getParameter("skip");
    String limit = req.getParameter("limit");

    String _fields = req.getParameter("fields");
    String fields[] = null;
    if (_fields != null)
        fields = _fields.split("[,]");

    DB db = mongo.getDB(db_name);

    // mongo auth
    String user = req.getParameter("user");
    String passwd = req.getParameter("passwd");
    if (user != null && passwd != null && (!db.isAuthenticated())) {
        boolean auth = db.authenticate(user, passwd.toCharArray());
        if (!auth) {
            res.sendError(SC_UNAUTHORIZED);
            return;
        }
    }

    DBCollection col = db.getCollection(col_name);

    StringBuilder buf = tl.get();
    // reset buf
    buf.setLength(0);

    BufferedReader r = null;
    DBObject q = null, sort = null;

    try {

        r = new BufferedReader(new InputStreamReader(is));
        String data = r.readLine();
        if (data == null) {
            error(res, SC_BAD_REQUEST, Status.get("no data"));
            return;
        }
        try {
            q = (DBObject) JSON.parse(data);
            if (cache != null) {
                buf.append(db_name);
                buf.append(col_name);
                buf.append(data);
            }
        } catch (JSONParseException e) {
            error(res, SC_BAD_REQUEST, Status.get("can not parse data"));
            return;
        }
        // sort param
        data = r.readLine();
        if (data != null) {
            try {
                sort = (DBObject) JSON.parse(data);
            } catch (JSONParseException e) {
                error(res, SC_BAD_REQUEST, Status.get("can not parse sort arg"));
                return;
            }
            if (cache != null)
                buf.append(data);
        }

    } finally {
        if (r != null)
            r.close();
    }

    // limit
    int lim;
    if (limit != null) {
        try {
            lim = Math.min(Integer.parseInt(limit), MAX_FIELDS_TO_RETURN);
        } catch (NumberFormatException e) {
            error(res, SC_BAD_REQUEST, Status.get("can not parse limit"));
            return;
        }
    } else {
        lim = MAX_FIELDS_TO_RETURN;
    }
    if (cache != null) {
        buf.append(";limit=");
        buf.append(lim);
    }

    // skip
    int sk = -1;
    if (skip != null) {
        try {
            sk = Integer.parseInt(skip);
            if (cache != null) {
                buf.append(";skip=");
                buf.append(sk);
            }
        } catch (NumberFormatException e) {
            error(res, SC_BAD_REQUEST, Status.get("can not parse skip"));
            return;
        }
    }

    // fields
    if (cache != null && _fields != null) {
        buf.append(";fields=");
        buf.append(_fields);
    }

    // from cache
    String cache_key = null;
    if (cache != null) {
        cache_key = buf.toString();
        try {
            ret = (String) cache.get(cache_key);
        }
        // some wrong char in key
        catch (IllegalArgumentException e) {
            int l = buf.length();
            for (int i = 0; i < l; i++) {
                if (buf.charAt(i) == ' ')
                    buf.setCharAt(i, '*');
            }
            cache_key = buf.toString();
            ret = (String) cache.get(cache_key);
        }
        if (ret != null) {
            out_str(req, ret, "application/json");
            return;
        }
    }

    // cursor
    DBCursor c;
    if (fields != null) {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        int len = fields.length;
        for (int i = 0; i < len; i++) {
            String s = fields[i];
            sb.append('"');
            sb.append(s);
            sb.append('"');
            sb.append(":1");
            if (i != (len - 1))
                sb.append(",");
        }
        sb.append("}");
        c = col.find(q, (DBObject) JSON.parse(sb.toString()));
    } else
        c = col.find(q);

    if (c == null || c.count() == 0) {
        error(res, SC_NOT_FOUND, Status.get("no documents found"));
        return;
    }

    if (sort != null)
        c.sort(sort);

    res.setIntHeader("X-Documents-Count", c.count());

    c.limit(lim);
    if (sk != -1)
        c.skip(sk);

    // reset buf
    buf.setLength(0);

    int no = 0;
    buf.append("[");
    while (c.hasNext()) {

        DBObject o = c.next();
        if (rm_id)
            o.removeField("_id");
        JSON.serialize(o, buf);
        buf.append(",");
        no++;

    }
    c.close();

    if (no > 0)
        buf.setCharAt(buf.length() - 1, ']');
    else
        buf.append(']');

    res.setIntHeader("X-Documents-Returned", no);

    ret = buf.toString();
    if (cache != null)
        cache.set(cache_key, ret);

    out_str(req, ret, "application/json");

}

From source file:com.cyslab.craftvm.rest.mongo.QueryServlet.java

License:GNU General Public License

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    log.trace("doGet()");

    if (!can_read(req)) {
        res.sendError(SC_UNAUTHORIZED);//from  w ww  .j a  va 2 s  .com
        return;
    }

    String db_name = req.getParameter("dbname");
    String col_name = req.getParameter("colname");
    if (db_name == null || col_name == null) {
        String names[] = req2mongonames(req);
        if (names != null) {
            db_name = names[0];
            col_name = names[1];
        }
        if (db_name == null || col_name == null) {
            error(res, SC_BAD_REQUEST, Status.get("param name missing"));
            return;
        }
    }
    String skip = req.getParameter("skip");
    String limit = req.getParameter("limit");

    DB db = mongo.getDB(db_name);

    // mongo auth
    String user = req.getParameter("user");
    String passwd = req.getParameter("passwd");
    if (user != null && passwd != null && (!db.isAuthenticated())) {
        boolean auth = db.authenticate(user, passwd.toCharArray());
        if (!auth) {
            res.sendError(SC_UNAUTHORIZED);
            return;
        }
    }

    DBCollection col = db.getCollection(col_name);

    DBCursor c = col.find();
    if (c == null || c.count() == 0) {
        error(res, SC_NOT_FOUND, Status.get("no documents found"));
        return;
    }

    res.setIntHeader("X-Documents-Count", c.count());

    if (limit != null) {
        try {
            c.limit(Math.min(Integer.parseInt(limit), MAX_FIELDS_TO_RETURN));
        } catch (NumberFormatException e) {
            error(res, SC_BAD_REQUEST, Status.get("can not parse limit"));
            c.close();
            return;
        }
    } else
        c.limit(MAX_FIELDS_TO_RETURN);

    if (skip != null) {
        try {
            c.skip(Integer.parseInt(skip));
        } catch (NumberFormatException e) {
            error(res, SC_BAD_REQUEST, Status.get("can not parse skip"));
            c.close();
            return;
        }
    }

    StringBuilder buf = tl.get();
    buf.setLength(0);

    int no = 0;
    buf.append("[");
    while (c.hasNext()) {

        DBObject o = c.next();
        if (rm_id)
            o.removeField("_id");
        JSON.serialize(o, buf);
        buf.append(",");
        no++;

    }
    c.close();

    if (no > 0)
        buf.setCharAt(buf.length() - 1, ']');
    else
        buf.append(']');

    res.setIntHeader("X-Documents-Returned", no);

    out_str(req, buf.toString(), "application/json");

}

From source file:com.cyslab.craftvm.rest.mongo.WriteServlet.java

License:GNU General Public License

@Override
protected void doDelete(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    log.trace("doDelete()");

    if (!can_write(req)) {
        res.sendError(SC_UNAUTHORIZED);//from w ww.  ja v a  2  s  .  co  m
        return;
    }

    InputStream is = req.getInputStream();
    String db_name = req.getParameter("dbname");
    String col_name = req.getParameter("colname");
    if (db_name == null || col_name == null) {
        String names[] = req2mongonames(req);
        if (names != null) {
            db_name = names[0];
            col_name = names[1];
        }
        if (db_name == null || col_name == null) {
            error(res, SC_BAD_REQUEST, Status.get("param name missing"));
            return;
        }
    }

    DB db = mongo.getDB(db_name);

    // mongo auth
    String user = req.getParameter("user");
    String passwd = req.getParameter("passwd");
    if (user != null && passwd != null && (!db.isAuthenticated())) {
        boolean auth = db.authenticate(user, passwd.toCharArray());
        if (!auth) {
            res.sendError(SC_UNAUTHORIZED);
            return;
        }
    }

    DBCollection col = db.getCollection(col_name);

    BufferedReader r = null;
    DBObject q = null;
    try {

        r = new BufferedReader(new InputStreamReader(is));
        String data = r.readLine();
        if (data == null) {
            error(res, SC_BAD_REQUEST, Status.get("no data"));
            return;
        }
        try {
            q = (DBObject) JSON.parse(data);
        } catch (JSONParseException e) {
            error(res, SC_BAD_REQUEST, Status.get("can not parse data"));
            return;
        }

    } finally {
        if (r != null)
            r.close();
    }

    // search
    if (do_search) {

        DBCursor c = col.find(q);
        long l = c.count();
        String todelete[] = new String[(int) l];
        int n = 0;

        while (c.hasNext()) {

            DBObject o = c.next();
            ObjectId oid = (ObjectId) o.get("_id");
            String id = oid.toStringMongod();
            todelete[n++] = id;

        }
        c.close();
        search.get_writer().delete(todelete);

    }

    WriteResult wr = col.remove(q, write_concern);

    // return operation status
    if (do_return) {
        out_str(req, wr.toString());
        if (wr.getError() == null) {
            res.setStatus(SC_BAD_REQUEST);
            return;
        }
    }

    res.setStatus(SC_OK);

}

From source file:com.cyslab.craftvm.rest.mongo.WriteServlet.java

License:GNU General Public License

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    log.trace("doPost()");

    if (!can_write(req)) {
        res.sendError(SC_UNAUTHORIZED);//from   w w  w  . j  av a  2s . co m
        return;
    }

    InputStream is = req.getInputStream();
    String db_name = req.getParameter("dbname");
    String col_name = req.getParameter("colname");
    if (db_name == null || col_name == null) {
        String names[] = req2mongonames(req);
        if (names != null) {
            db_name = names[0];
            col_name = names[1];
        }
        if (db_name == null || col_name == null) {
            error(res, SC_BAD_REQUEST, Status.get("param name missing"));
            return;
        }
    }

    boolean upsert = Boolean.parseBoolean(req.getParameter("upsert"));
    boolean multi = Boolean.parseBoolean(req.getParameter("multi"));

    DB db = mongo.getDB(db_name);

    // mongo auth
    String user = req.getParameter("user");
    String passwd = req.getParameter("passwd");
    if (user != null && passwd != null && (!db.isAuthenticated())) {
        boolean auth = db.authenticate(user, passwd.toCharArray());
        if (!auth) {
            res.sendError(SC_UNAUTHORIZED);
            return;
        }
    }

    DBCollection col = db.getCollection(col_name);

    BufferedReader r = null;
    DBObject q = null, o = null;
    try {

        r = new BufferedReader(new InputStreamReader(is));
        String q_s = r.readLine();
        if (q_s == null) {
            error(res, SC_BAD_REQUEST, Status.get("no data"));
            return;
        }
        String o_s = r.readLine();
        if (o_s == null) {
            error(res, SC_BAD_REQUEST, Status.get("obj to update missing"));
            return;
        }
        try {
            q = (DBObject) JSON.parse(q_s);
            o = (DBObject) JSON.parse(o_s);
        } catch (JSONParseException e) {
            error(res, SC_BAD_REQUEST, Status.get("can not parse data"));
            return;
        }

    } finally {
        if (r != null)
            r.close();
    }
    //
    // search
    if (do_search) {

        String fn = col.getFullName();
        DBCursor c = col.find(q);
        int cnt = c.count();
        if (!multi)
            c.limit(1);
        long l = multi ? cnt : 1;
        String toupdate[] = new String[(int) l];
        int n = 0;
        boolean insert = false;

        if (upsert && !multi && cnt == 0)
            insert = true;

        while (c.hasNext()) {

            DBObject _o = c.next();
            ObjectId oid = (ObjectId) _o.get("_id");
            String id = oid.toStringMongod();
            toupdate[n++] = id;

        }
        c.close();

        List<String> flds = Config.search_index_fields.get(fn);
        boolean commit = false;
        Document doc = null;
        Search _writer = search.get_writer();
        if (flds != null && flds.size() > 0) {
            doc = new Document();
            try {
                for (String fld : flds) {
                    String val = (String) o.get(fld);
                    if (val == null)
                        continue;
                    _writer.add_searchable_s(doc, fld, val);
                    commit = true;
                }
                if (commit)
                    _writer.commit(doc);
            } catch (ClassCastException e) {
                error(res, SC_BAD_REQUEST, Status.get("searchable fields must be type String"));
                return;
            } catch (CorruptIndexException e) {
                error(res, SC_BAD_REQUEST, Status.get("Search corrupt index" + e));
                return;
            }
        }
        if (commit && insert)
            log.warn("upsert with search not implemented yet");
        else
            _writer.update(toupdate, doc);

    }

    WriteResult wr = col.update(q, o, upsert, multi, write_concern);

    // return operation status
    if (do_return) {
        out_str(req, wr.toString());
        if (wr.getError() == null) {
            res.setStatus(SC_BAD_REQUEST);
            return;
        }
    }

    res.setStatus(SC_CREATED);

}

From source file:com.damanzano.mongohw2_2.MongoHW2_2.java

public static void main(String[] args) throws UnknownHostException {
    MongoClient client = new MongoClient();
    DB db = client.getDB("students");
    DBCollection collection = db.getCollection("grades");

    DBCursor allGrades = collection.find(new BasicDBObject("type", "homework"))
            .sort(new BasicDBObject("student_id", 1).append("score", 1));
    try {/*from  ww  w  .j  a va 2 s. c  o m*/
        String studentId = "";
        while (allGrades.hasNext()) {
            DBObject grade = allGrades.next();
            System.out.println(grade);
            if (!studentId.equalsIgnoreCase(((Integer) grade.get("student_id")).toString())) {
                System.out.println("Deleting grade " + grade.get("_id").toString() + " for student "
                        + grade.get("student_id").toString());
                collection.remove(grade);
            }
            studentId = ((Integer) grade.get("student_id")).toString();
        }
    } finally {
        allGrades.close();
    }
}

From source file:com.daprota.m2.manager.MongoManager.java

License:Apache License

/**
 * Retrieves user via spceified userName.
 *
 * @param userName A user's userName.// w w  w. j a v  a 2  s .c  om
* @return user if exists. Otherwise returns null.
 */
public User findUserByUserName(String userName) throws MongoException {
    DBCursor dbCur = null;

    try {
        // get a user collection
        DBCollection coll = _db.getCollection("user");
        DBObject query = new BasicDBObject("userName", userName);
        dbCur = coll.find(query);
        boolean hasNext;
        try {
            logger.debug("Call dbCur.hasNext().");
            hasNext = dbCur.hasNext();
        } catch (MongoException ex) {
            logger.error("Search for user {} failed.\n" + ex.toString(), userName);
            throw new MongoException("Search for user " + userName + " failed.");
        }
        if (hasNext) {
            DBObject user = dbCur.next();
            ArrayList<BasicDBObject> roles = (ArrayList<BasicDBObject>) user.get("roles");
            ArrayList<Role> roles2 = new ArrayList<Role>();
            if (roles != null) {
                for (BasicDBObject role : roles) {
                    Role role3 = new Role(role.get("_id").toString(), (String) role.get("name"),
                            (String) role.get("description"));
                    roles2.add(role3);
                }
                logger.debug("User {} roles added.", userName);
            }
            return (new User(user.get("_id").toString(), (String) user.get("userName"),
                    (String) user.get("password"), roles2));
        } else {
            logger.warn("User {} could not be found", userName);
            return null;
        }
    } catch (MongoException ex) {
        logger.error("Search for user {} failed.\n" + ex.toString(), userName);
        throw new MongoException("Search for user " + userName + " failed.");
    } finally {
        dbCur.close();
    }
}

From source file:com.deafgoat.ml.prognosticator.Mongo2CSV.java

License:Apache License

/**
 * Writes the collectionection to a CSV file using the MongoExport command.
 * /*from  w  w w.  j a v a 2 s. co  m*/
 * @param filename
 *            Th name of the file to write the collectionection to
 * @throws IOException
 *             If unable to write to file
 * @throws FileNotFoundException
 *             If the file is not found
 */
public void writeCSV(String filename) throws IOException, FileNotFoundException {
    BufferedWriter out = new BufferedWriter(new FileWriter(filename));
    DBCursor cursor = _collection.find();
    out.write(Mongo2CSV.join(Arrays.asList(_fields), _delimeter) + "\n");
    ArrayList<String> entry = new ArrayList<String>();
    DBObject obj;
    while (cursor.hasNext()) {
        obj = cursor.next();
        for (String field : _fields) {
            entry.add((String) obj.get(field));
        }
        out.write(join(entry, _delimeter) + "\n");
        entry.clear();
    }
    cursor.close();
    out.close();
}

From source file:com.deafgoat.ml.prognosticator.MongoImport.java

License:Apache License

/**
 * Returns all JSON configurations found in the collection.
 * //ww  w  .  j av  a 2  s  . c  o  m
 * @return The set of all JSON configurations found. Null if none is found.
 * @throws JSONException
 *             If the configuration can not be converted to a JSONObject
 */
public ArrayList<JSONObject> getAllConfigurations() throws JSONException {
    DBCursor cursor = _collection.find();
    ArrayList<JSONObject> configFiles = new ArrayList<JSONObject>();
    try {
        while (cursor.hasNext()) {
            configFiles.add(new JSONObject(cursor.next().toString()));
        }
    } finally {
        cursor.close();
    }
    return configFiles;
}

From source file:com.deftlabs.lock.mongo.impl.LockDao.java

License:Apache License

/**
 * Check for expired/inactive/dead locks and unlock.
 *//* w  ww . j  a  v a  2  s.  c o  m*/
static void expireInactiveLocks(final MongoClient pMongo, final DistributedLockSvcOptions pSvcOptions) {
    // Adjust the time buffer to make sure we do not have small time issues.
    final long queryServerTime = getServerTime(pMongo, pSvcOptions);

    final BasicDBObject query = new BasicDBObject(LockDef.STATE.field, LockState.LOCKED.code());
    query.put(LockDef.LOCK_TIMEOUT_TIME.field, new BasicDBObject(LT, new Date(queryServerTime)));

    final DBCursor cur = getDbCollection(pMongo, pSvcOptions).find(query).batchSize(10);

    try {
        while (cur.hasNext()) {

            final BasicDBObject lockDoc = (BasicDBObject) cur.next();

            final ObjectId lockId = (ObjectId) lockDoc.get(LockDef.LOCK_ID.field);
            final String lockName = lockDoc.getString(LockDef.ID.field);

            final long serverTime = getServerTime(pMongo, pSvcOptions);

            final BasicDBObject toSet = new BasicDBObject();
            toSet.put(LockDef.LIBRARY_VERSION.field, null);
            toSet.put(LockDef.UPDATED.field, new Date(serverTime));
            toSet.put(LockDef.LOCK_ACQUIRED_TIME.field, null);
            toSet.put(LockDef.LOCK_TIMEOUT_TIME.field, null);
            toSet.put(LockDef.LOCK_ID.field, null);
            toSet.put(LockDef.STATE.field, LockState.UNLOCKED.code());
            toSet.put(LockDef.OWNER_APP_NAME.field, null);
            toSet.put(LockDef.OWNER_ADDRESS.field, null);
            toSet.put(LockDef.OWNER_HOSTNAME.field, null);
            toSet.put(LockDef.OWNER_THREAD_ID.field, null);
            toSet.put(LockDef.OWNER_THREAD_NAME.field, null);
            toSet.put(LockDef.OWNER_THREAD_GROUP_NAME.field, null);
            toSet.put(LockDef.LOCK_ATTEMPT_COUNT.field, 0);
            toSet.put(LockDef.INACTIVE_LOCK_TIMEOUT.field, null);

            final BasicDBObject timeoutQuery = new BasicDBObject(LockDef.ID.field, lockName);
            timeoutQuery.put(LockDef.LOCK_ID.field, lockId);
            timeoutQuery.put(LockDef.STATE.field, LockState.LOCKED.code());
            timeoutQuery.put(LockDef.LOCK_TIMEOUT_TIME.field, new BasicDBObject(LT, new Date(serverTime)));

            final BasicDBObject previousLockDoc = (BasicDBObject) getDbCollection(pMongo, pSvcOptions)
                    .findAndModify(timeoutQuery, new BasicDBObject(LockDef.INACTIVE_LOCK_TIMEOUT.field, 1),
                            null, false, new BasicDBObject(SET, toSet), false, false);

            if (previousLockDoc == null)
                continue;

            if (!pSvcOptions.getEnableHistory())
                continue;

            // Insert the history state.
            LockHistoryDao.insert(pMongo, lockName, pSvcOptions,
                    previousLockDoc.getInt(LockDef.INACTIVE_LOCK_TIMEOUT.field), serverTime, LockState.LOCKED,
                    lockId, true);
        }
    } finally {
        if (cur != null)
            cur.close();
    }
}

From source file:com.dhamacher.addressbook.DBController.java

License:Open Source License

/**
 * This methods provides the data that is then published in the JList
 * component of the user view [Main.class]
 *
 * @return An object array for the JList component in the user view
 *///from w ww .j a va 2  s.  c  o m
protected Object[] getContacts() {
    if (collection.count() == 0) {
        Object[] data = { "" };
        return data;
    } else {
        /* Use the database cursor to iterate trough the collection */
        DBCursor cursor = collection.find();

        /* New array based on the size of the collection */
        Object[] data = new Object[(int) collection.count()];
        int i = 0;
        while (cursor.hasNext()) {
            DBObject document = cursor.next();
            data[i] = document.get("first_name") + " " + document.get("last_name");
            i++;
        }
        cursor.close();
        return data;
    }
}