Example usage for com.mongodb DBCollection find

List of usage examples for com.mongodb DBCollection find

Introduction

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

Prototype

public DBCursor find(final DBObject query) 

Source Link

Document

Select documents in collection and get a cursor to the selected documents.

Usage

From source file:cn.vlabs.clb.server.storage.mongo.MongoStorageService.java

License:Apache License

public String queryMd5(String storageKey, String tableName) {
    DB db = options.getCollection(TABLE_TEMP_KEY).getDB();
    DBObject query = new BasicDBObject();
    query.put("storageKey", new ObjectId(storageKey));
    DBCollection fileTable = db.getCollection(tableName + ".files");
    DBCursor cursor = fileTable.find(query);
    if (cursor.hasNext()) {
        DBObject o = cursor.next();/*from w w w  . ja v  a 2 s. co m*/
        return o.get("md5").toString();
    }
    return "";
}

From source file:co.edu.uniandes.csw.Arquidalgos.usuario.persistence._UsuarioPersistence.java

License:MIT License

@SuppressWarnings("unchecked")
public List<UsuarioDTO> getUsuarios() {
    //      Query q = entityManager.createQuery("select u from UsuarioEntity u");
    //      return UsuarioConverter.entity2PersistenceDTOList(q.getResultList());

    List listaUsuarios = new ArrayList();
    DBCollection coll = db.getCollection("UsuarioDTO");
    BasicDBObject query = new BasicDBObject();
    DBCursor cursor = coll.find(query);
    while (cursor.hasNext()) {
        DBObject dBObject = cursor.next();
        UsuarioDTO user = new UsuarioDTO();
        user.setName((String) dBObject.get("name"));
        user.setContrasena((String) dBObject.get("contrasena"));
        user.setEmail((String) dBObject.get("email"));
        user.setFacebookId((String) dBObject.get("facebookId"));

        //TODO imprimir usuarios
        listaUsuarios.add(user);//from w w  w .  ja va2  s.  co m
    }
    cursor.close();
    return listaUsuarios;

}

From source file:com.aankam.servlet.MongoCrudServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./* www .  j a va  2  s. c  o m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    MongoClientURI uri = new MongoClientURI("mongodb://Username:Pasword@ds061721.mongolab.com:61721/cs612");
    MongoClient client = new MongoClient(uri);
    DB db = client.getDB(uri.getDatabase());

    response.setContentType("text/html;charset=UTF-8");

    String serialNo = request.getParameter("serialNo");
    String name = request.getParameter("name");
    String emailId = request.getParameter("emailId");
    String operation = request.getParameter("operation");

    BasicDBObject customer;
    BasicDBObject updateQuery;
    BasicDBObject deleteQuery;
    BasicDBObject searchQuery;
    DBCollection customersCollection;
    customersCollection = db.getCollection("Customers");
    DBObject searchResult = null;
    boolean flag = false;
    DBCursor cursor;
    switch (operation) {
    case "create":
        customer = new BasicDBObject();
        customer.put("serialNo", serialNo);
        customer.put("name", name);
        customer.put("emailId", emailId);
        customersCollection.insert(customer);
        break;
    case "update":
        updateQuery = new BasicDBObject();
        updateQuery.append("serialNo", serialNo);
        cursor = customersCollection.find(updateQuery);
        customer = new BasicDBObject();
        customer.put("serialNo", serialNo);
        customer.put("name", name);
        customer.put("emailId", emailId);
        if (cursor.hasNext()) {
            customersCollection.update(updateQuery, customer);
            flag = true;
        }

        break;
    case "delete":
        deleteQuery = new BasicDBObject();
        deleteQuery.append("serialNo", serialNo);
        customersCollection.remove(deleteQuery);
        break;
    case "search":
        searchQuery = new BasicDBObject();
        searchQuery.append("serialNo", serialNo);
        cursor = customersCollection.find(searchQuery);
        while (cursor.hasNext()) {
            searchResult = cursor.next();
        }
        break;
    default:
        break;

    }
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet MongoCrudServlet</title>");
        out.println("</head>");
        out.println("<body>");

        switch (operation) {
        case "create":
            out.println("<h3>Customer was successfully created.</h3>");
            break;
        case "update":
            if (flag == true) {
                out.println("<h3>Customer was successfully updated.</h3>");
            } else {
                out.println("<h3>Customer was not found to update.</h3>");
            }

            break;
        case "delete":
            out.println("<h3>Customer was successfully deleted.</h3>");
            break;
        case "search":
            if (searchResult != null) {
                out.println("<h3>The following customer was found:</h3>");
                out.println("<h4>Serial No :" + searchResult.get("serialNo") + "</h4>");
                out.println("<h4>Name :" + searchResult.get("name") + "</h4>");
                out.println("<h4>Email Id :" + searchResult.get("emailId") + "</h4>");
            } else {
                out.println("<h3>Customer not found.</h3>");
            }
            break;
        default:
            break;
        }
        out.println("<a href=\"index.html\">Back to Main Form</a>");
        out.println("</body>");
        out.println("</html>");
    }
}

From source file:com.AlertMailerWebPage.servlet.Show.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   www.  ja v  a2 s .  com*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        Properties defaultProps = new Properties();
        InputStream in = GetProcessSpeed.class.getResourceAsStream("configuration.properties");
        defaultProps.load(in);
        in.close();
        String database = (String) defaultProps.get("database_mailerDetails");
        String collection = (String) defaultProps.get("collection_mailerDetails");
        String serverAddress = (String) defaultProps.get("IP_AMDBoard");

        Mongo mongo = new Mongo("localhost", 27017);
        //   Mongo mongo=new Mongo(serverAddress,27017);
        //DB db = mongo.getDB("dashboard" );
        DB db = mongo.getDB(database);

        DBCollection coll = db.getCollection(collection);
        //DBCollection coll=db.getCollection("users");
        DBObject query = new BasicDBObject("AlertMailer", "PRS");
        DBObject query1 = new BasicDBObject("InsertTime", -1);
        //DBObject query = new BasicDBObject("_id",-1);
        DBCursor cursor = coll.find(query).sort(query1).limit(1);

        //String name1= (String)cursor.one().get("name");    
        //while(cursor.hasNext()){
        //    out.println(""+cursor.next()+"");
        //}
        response.setContentType("text/plain");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(cursor.one().toString());
    }
}

From source file:com.andreig.jetty.AggregateServlet.java

License:GNU General Public License

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

    log.fine("doPost()");

    if (!can_read(req)) {
        res.sendError(SC_UNAUTHORIZED);//  ww  w . j a va  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) {
        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.andreig.jetty.SearchServlet.java

License:GNU General Public License

private String search2mongo(Document hits[], DBCollection col) {

    List<ObjectId> values = new ArrayList<ObjectId>();
    for (Document hit : hits) {
        String _id = hit.get("_id");
        ObjectId oid = ObjectId.massageToObjectId(_id);
        values.add(oid);/*w  ww  . ja  v a2 s .co m*/
    }

    BasicDBObject q = new BasicDBObject();
    q.put("_id", new BasicDBObject("$in", values));

    DBCursor c = col.find(q);
    if (c == null || c.count() == 0) {
        return null;
    }

    StringBuilder buf = tl.get();
    // 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(']');

    return buf.toString();

}

From source file:com.andreig.jetty.WriteServlet.java

License:GNU General Public License

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

    log.fine("doDelete()");

    if (!can_write(req)) {
        res.sendError(SC_UNAUTHORIZED);//from ww  w  . j ava 2 s.c  om
        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.andreig.jetty.WriteServlet.java

License:GNU General Public License

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

    log.fine("doPost()");

    if (!can_write(req)) {
        res.sendError(SC_UNAUTHORIZED);/* ww  w. j  a v  a 2s .  c o  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;
                    Search.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.warning("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.aperigeek.dropvault.web.dao.MongoFileService.java

License:Open Source License

public List<Resource> getChildren(Resource resource) {
    DBCollection col = mongo.getDataBase().getCollection("files");

    DBObject filter = new BasicDBObject();
    filter.put("parent", resource.getId());

    List<Resource> children = new ArrayList<Resource>();

    DBCursor cursor = col.find(filter);
    while (cursor.hasNext()) {
        children.add(buildResource(cursor.next()));
    }/*w ww .  j  av a 2 s.  c  o  m*/

    return children;
}

From source file:com.apifest.oauth20.MongoDBManager.java

License:Apache License

@SuppressWarnings("unchecked")
@Override/*from w ww  .j  a va2 s .  c o  m*/
public AccessToken findAccessToken(String accessToken) {
    BasicDBObject dbObject = new BasicDBObject();
    dbObject.put(ACCESS_TOKEN_ID_NAME, accessToken);
    dbObject.put(VALID_NAME, true);
    DBCollection coll = db.getCollection(ACCESS_TOKEN_COLLECTION_NAME);
    List<DBObject> list = coll.find(dbObject).toArray();
    if (list.size() > 1) {
        // throw exception
        log.warn("Several access tokens found");
        return null;
    }
    if (list.size() > 0) {
        Map<String, Object> mapLoaded = list.get(0).toMap();
        // convert details map to String
        if (mapLoaded.get("details") instanceof BasicDBObject) {
            BasicDBObject details = (BasicDBObject) mapLoaded.get("details");
            mapLoaded.put("details", details.toString());
        }
        return AccessToken.loadFromMap(mapLoaded);
    } else {
        log.debug("No access token found");
        return null;
    }
}