List of usage examples for com.mongodb DBCursor next
@Override
public DBObject next()
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 av 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.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);/*from w ww . 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; 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 w w . j a va 2s . c o m return children; }
From source file:com.apifest.oauth20.MongoDBManager.java
License:Apache License
@SuppressWarnings("unchecked") @Override//from w w w .j a v a 2 s .c o m public AuthCode findAuthCode(String authCode, String redirectUri) { BasicDBObject keys = new BasicDBObject(); keys.put(AUTH_CODE_ID_NAME, authCode); keys.put(REDIRECT_URI_NAME, redirectUri); keys.put(VALID_NAME, true); DBCursor list = db.getCollection(AUTH_CODE_COLLECTION_NAME).find(new BasicDBObject(keys)); while (list.hasNext()) { DBObject result = list.next(); Map<String, Object> mapLoaded = result.toMap(); AuthCode loadedAuthCode = AuthCode.loadFromMap(mapLoaded); log.debug(loadedAuthCode.getClientId()); list.close(); return loadedAuthCode; } list.close(); return null; }
From source file:com.apifest.oauth20.MongoDBManager.java
License:Apache License
protected Object getObject(DBCollection coll, BasicDBObject query) { DBCursor cursor = coll.find(query); Object result = null;/* w w w .j av a2 s .c o m*/ try { // TODO: if more than once throw exception while (cursor.hasNext()) { result = cursor.next(); log.debug("found: " + result); } } finally { if (cursor != null) { cursor.close(); } } return result; }
From source file:com.apifest.oauth20.persistence.mongodb.MongoDBManager.java
License:Apache License
@SuppressWarnings("unchecked") @Override/* ww w . ja v a2 s . com*/ public AuthCode findAuthCode(String authCode, String redirectUri) { BasicDBObject keys = new BasicDBObject(); keys.put(AUTH_CODE, authCode); keys.put(ACCESS_TOKEN_REDIRECT_URI, redirectUri); keys.put(ACCESS_TOKEN_VALID, true); DBCursor list = db.getCollection(AUTH_CODE_COLLECTION_NAME).find(new BasicDBObject(keys)); if (list.hasNext()) { DBObject result = list.next(); Map<String, Object> mapLoaded = result.toMap(); AuthCode loadedAuthCode = AuthCode.loadFromMap(mapLoaded); log.debug(loadedAuthCode.getClientId()); list.close(); return loadedAuthCode; } list.close(); return null; }
From source file:com.app.mongoDao.MongoBookDao.java
@Override public List<Book> listBook() { ArrayList<Book> booklist = new ArrayList<>(); try {// ww w.j a va2 s . c o m DBCollection data = DatabaseConfig.configure(); BasicDBObject orderBy = new BasicDBObject("id", 1); DBCursor docs = data.find().sort(orderBy); while (docs.hasNext()) { DBObject doc = docs.next(); Book librarybook = new Book(doc.get("bookname").toString(), doc.get("author").toString()); booklist.add(librarybook); } } catch (Exception e) { e.printStackTrace(); } return booklist; }
From source file:com.appleframework.monitor.action.LogsAction.java
License:Open Source License
@RequestMapping(value = "/projects/{projectName}/logs/download", method = RequestMethod.GET) public void download(final HttpServletResponse response, ModelMap map, @PathVariable String projectName, LogQuery logQuery) throws IOException, ParseException { Project project = projectService.findProject(projectName); final MongoConverter converter = project.fetchMongoTemplate().getConverter(); final DBCursor cursor = logsService.findLogs(projectName, logQuery, 100000); response.setContentType("file/txt;charset=utf-8"); response.addHeader("content-disposition", String.format("attachment; filename=%s.txt", java.net.URLEncoder.encode("logs", "UTF-8"))); response.setStatus(HttpServletResponse.SC_OK); while (cursor.hasNext()) { Log log = converter.read(Log.class, cursor.next()); response.getWriter().println(log.toString()); }/*w ww .j av a2 s . c o m*/ }
From source file:com.appleframework.monitor.action.LogsAction.java
License:Open Source License
@RequestMapping(value = "/projects/{projectName}/logs/more", method = RequestMethod.GET) public void console(final HttpServletResponse response, ModelMap map, @PathVariable String projectName, LogQuery logQuery) throws IOException, ParseException { Project project = projectService.findProject(projectName); map.put("project", project); final MongoConverter converter = project.fetchMongoTemplate().getConverter(); final DBCursor cursor = logsService.findLogs(projectName, logQuery); final StringBuffer buf = new StringBuffer(); FutureTask<String> task = new FutureTask<String>(new Callable<String>() { @Override// ww w . j av a 2 s . c o m public String call() throws Exception { long startTime = System.currentTimeMillis(); //???20 logger.debug("result:"); while (cursor.hasNext()) { Log log = converter.read(Log.class, cursor.next()); buf.insert(0, log.toString() + "\n"); long current = System.currentTimeMillis(); if ((current - startTime) / 1000 >= mongWaitSeconds) break; } return buf.toString(); } }); executor.execute(task); try { task.get(mongWaitSeconds + 5, TimeUnit.SECONDS); cursor.close(); } catch (Exception e) { logger.error("time out ", e); task.cancel(true); } response.setContentType("text/html;charset=UTF-8"); response.getWriter().write(buf.toString()); response.getWriter().flush(); }
From source file:com.arquivolivre.mongocom.management.CollectionManager.java
License:Apache License
/** * Find all documents that match the specified query in the given * collection.//from w ww . j a v a 2 s. co m * * @param <A> generic type of the collection. * @param collectionClass * @param query * @return a list of documents. */ public <A extends Object> List<A> find(Class<A> collectionClass, MongoQuery query) { List<A> resultSet = new ArrayList<>(); DBCursor cursor = null; try { A obj = collectionClass.newInstance(); String collectionName = reflectCollectionName(obj); cursor = db.getCollection(collectionName).find(query.getQuery(), query.getConstraits()); if (query.getSkip() > 0) { cursor = cursor.skip(query.getSkip()); } if (query.getLimit() > 0) { cursor = cursor.limit(query.getLimit()); } while (cursor.hasNext()) { DBObject objDB = cursor.next(); loadObject(obj, objDB); resultSet.add(obj); obj = collectionClass.newInstance(); } } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException ex) { LOG.log(Level.SEVERE, null, ex); } finally { if (cursor != null) { cursor.close(); } } return resultSet; }