Example usage for com.mongodb DBCursor hasNext

List of usage examples for com.mongodb DBCursor hasNext

Introduction

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

Prototype

@Override
public boolean hasNext() 

Source Link

Document

Checks if there is another object available.

Usage

From source file:com.cedac.security.oauth2.provider.client.MongoClientDetailsService.java

License:Apache License

public List<ClientDetails> listClientDetails() {
    DBCursor cursor = null;
    try {/*from w  w  w  .  j  a  va 2 s .c  om*/
        cursor = getClientDetailsCollection().find();
        List<ClientDetails> clientDetails = new ArrayList<ClientDetails>();
        while (cursor.hasNext()) {
            clientDetails.add(toClientDetails(cursor.next()));
        }
        return clientDetails;
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

From source file:com.cedac.security.oauth2.provider.token.store.MongoTokenStore.java

License:Apache License

public Collection<OAuth2AccessToken> findTokensByClientId(String clientId) {
    List<OAuth2AccessToken> accessTokens = new ArrayList<OAuth2AccessToken>();

    DBObject query = new BasicDBObject(clientIdFieldName, clientId);
    DBObject projection = new BasicDBObject(tokenFieldName, 1);
    DBCursor cursor = null;
    try {//from   w  w  w.  j  av  a2 s  . c  o m
        cursor = getAccessTokenCollection().find(query, projection);
        if (cursor.count() > 0) {
            while (cursor.hasNext()) {
                OAuth2AccessToken token = mapAccessToken(cursor.next());
                if (token != null) {
                    accessTokens.add(token);
                }
            }
        } else {
            LOG.info("Failed to find access token for clientId {}", clientId);
        }
        return accessTokens;
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

From source file:com.cedac.security.oauth2.provider.token.store.MongoTokenStore.java

License:Apache License

public Collection<OAuth2AccessToken> findTokensByUserName(String userName) {
    List<OAuth2AccessToken> accessTokens = new ArrayList<OAuth2AccessToken>();

    DBObject query = new BasicDBObject(usernameFieldName, userName);
    DBObject projection = new BasicDBObject(tokenFieldName, 1);
    DBCursor cursor = null;
    try {//from  ww  w .  ja  v a 2s.c o m
        cursor = getAccessTokenCollection().find(query, projection);
        if (cursor.count() > 0) {
            while (cursor.hasNext()) {
                OAuth2AccessToken token = mapAccessToken(cursor.next());
                if (token != null) {
                    accessTokens.add(token);
                }
            }
        } else {
            LOG.info("Failed to find access token for username {}.", userName);
        }
        return accessTokens;
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

From source file:com.cedac.security.oauth2.provider.token.store.MongoTokenStore.java

License:Apache License

public Collection<OAuth2AccessToken> findTokensByClientIdAndUserName(String clientId, String userName) {
    List<OAuth2AccessToken> accessTokens = new ArrayList<OAuth2AccessToken>();

    DBObject query = new BasicDBObject(clientIdFieldName, clientId).append(usernameFieldName, userName);
    DBObject projection = new BasicDBObject(tokenFieldName, 1);
    DBCursor cursor = null;
    try {/*from w  w  w  .j  av  a 2  s  . c om*/
        cursor = getAccessTokenCollection().find(query, projection);
        if (cursor.count() > 0) {
            while (cursor.hasNext()) {
                OAuth2AccessToken token = mapAccessToken(cursor.next());
                if (token != null) {
                    accessTokens.add(token);
                }
            }
        } else {
            LOG.info("Failed to find access token for clientId {} and username {}.", clientId, userName);
        }
        return accessTokens;
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

From source file:com.chdi.kundenverwaltung.KundenVerwaltungsLogic.java

public List<Customer> findAllCustomer() {
    List<Customer> customers = new ArrayList<Customer>();

    DBCollection table = db.getCollection("user");

    DBCursor cursor = table.find();

    while (cursor.hasNext()) {

        DBObject tobj = cursor.next();//from  www  . jav  a  2s  . com
        Customer tmp = new Customer((String) tobj.get("ID"), (String) tobj.get("CompanyName"),
                (String) tobj.get("Name"), (String) tobj.get("Adress"));
        customers.add(tmp);
    }

    return customers;
}

From source file:com.ciphertool.sherlock.dao.NGramDao.java

License:Open Source License

/**
 * Returns a list of top N NGrams. We have to use the low-level MongoDB API because otherwise the query takes
 * forever due to the limitation of Spring Data not providing cursor functionality.
 *//*  ww w  .  ja  v a2s. c om*/
public List<NGram> findTopMostFrequentByNumWords(int numWordsQueryParam, int top) {
    DBCollection collection = mongoOperations.getCollection(DatabaseConstants.NGRAM_COLLECTION);

    DBCursor cursor;

    if (top > 0) {
        cursor = collection.find(new BasicDBObject("numWords", numWordsQueryParam))
                .sort(new BasicDBObject("frequencyWeight", -1)).limit(top);
    } else {
        cursor = collection.find(new BasicDBObject("numWords", numWordsQueryParam))
                .sort(new BasicDBObject("frequencyWeight", -1));
    }

    List<NGram> results = new ArrayList<NGram>();
    while (cursor.hasNext()) {
        DBObject next = cursor.next();

        String nGram = (String) next.get("nGram");
        Integer numWords = (Integer) next.get("numWords");
        Long frequencyWeight = (Long) next.get("frequencyWeight");

        results.add(new NGram(nGram, numWords, frequencyWeight));
    }

    return results;
}

From source file:com.conventus.mongodb.dao.MongoDBGenericDAO.java

public List<T> readAll() {
    List<T> data = new ArrayList<T>();
    DBCursor cursor = this.col.find();
    while (cursor.hasNext()) {
        DBObject doc = cursor.next();/*from  w w  w  .  ja  va 2  s.  c  om*/
        T obj = this.converter.toObject(doc);
        data.add(obj);
    }
    return data;
}

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

License:GNU General Public License

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

    log.trace("doPost()");

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

    InputStream is = req.getInputStream();
    String db_name = req.getParameter("dbname");
    String col_name = req.getParameter("colname");
    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);
    DBCollection col = db.getCollection(col_name);

    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);
        } 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;
            }
        }

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

    DBCursor c;
    if (sort == null)
        c = col.find(q);
    else
        c = col.find(q).sort(sort);
    if (c == null) {
        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();
    // reset buf
    buf.setLength(0);

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

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

    }

    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.AggregateServlet.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);//  w  w w . ja  v  a  2s .com
        return;
    }

    String db_name = req.getParameter("dbname");
    String col_name = req.getParameter("colname");
    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);
    DBCollection col = db.getCollection(col_name);

    DBCursor c = col.find();
    if (c == null) {
        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();
        JSON.serialize(o, buf);
        buf.append(",");
        no++;

    }

    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.GridfsServlet.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.  co  m*/
        return;
    }

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

    if (bucket_name == null)
        bucket_name = "fs";

    DB db = mongo.getDB(db_name);

    String fs_cache_key = db_name + bucket_name;
    GridFS fs = fs_cache.get(fs_cache_key);
    if (fs == null) {
        fs = new GridFS(db, bucket_name);
        fs_cache.put(fs_cache_key, fs);
    }

    // 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;
        }
    }

    String op = req.getParameter("op");
    if (op == null)
        op = "get";

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

    // list
    if ("get".equals(op)) {

        String file_name = req.getParameter("filename");
        if (file_name == null) {
            error(res, SC_BAD_REQUEST, Status.get("param name missing"));
            return;
        }

        GridFSDBFile db_file = fs.findOne(file_name);
        if (db_file == null) {
            error(res, SC_NOT_FOUND, Status.get("file does not exists"));
            return;
        }

        res.setContentLength((int) db_file.getLength());
        String ct = db_file.getContentType();
        if (ct != null)
            res.setContentType(ct);
        OutputStream os = res.getOutputStream();
        long l;
        while ((l = db_file.writeTo(os)) > 0)
            ;
        os.flush();
        os.close();

    }
    // list
    else if ("list".equals(op)) {

        DBCursor c = fs.getFileList();
        if (c == null) {
            error(res, SC_NOT_FOUND, Status.get("no documents found"));
            return;
        }

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

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

        }

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

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

    }
    // info
    else if ("info".equals(op)) {

        String file_name = req.getParameter("filename");
        if (file_name == null) {
            error(res, SC_BAD_REQUEST, Status.get("param name missing"));
            return;
        }

        GridFSDBFile db_file = fs.findOne(file_name);
        if (db_file == null) {
            error(res, SC_NOT_FOUND, Status.get("no documents found"));
            return;
        }

        buf.append("{");
        buf.append(String.format("\"ContentType\":%s,", db_file.getContentType()));
        buf.append(String.format("\"Length\":%d,", db_file.getLength()));
        buf.append(String.format("\"MD5\":%s", db_file.getMD5()));
        buf.append("}");

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

    } else
        res.sendError(SC_BAD_REQUEST);

}