List of usage examples for com.mongodb DBCursor close
@Override public void close()
From source file:com.sample.MyGroceryListServlet.java
License:Open Source License
/** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) *//* w ww .j a v a 2s . c o m*/ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Reference: http://docs.mongodb.org/ecosystem/tutorial/getting-started-with-java-driver/#getting-started-with-java-driver String envVars = System.getenv("VCAP_SERVICES"); DBObject dbO = (DBObject) JSON.parse(envVars); String parsedString = dbO.get("mongodb").toString(); // Remove trailing and starting array brackets (otherwise it won't be valid JSON) parsedString = parsedString.replaceFirst("\\[ ", ""); parsedString = parsedString.replaceFirst("\\]$", ""); // Get the credentials dbO = (DBObject) JSON.parse(parsedString); parsedString = dbO.get("credentials").toString(); // For debugging only // System.out.println(parsedString); dbO = (DBObject) JSON.parse(parsedString); System.out.println("Host name : " + dbO.get("hostname")); String hostName = dbO.get("hostname").toString(); int port = Integer.parseInt(dbO.get("port").toString()); String dbName = dbO.get("db").toString(); String userName = dbO.get("username").toString(); String password = dbO.get("password").toString(); Mongo mongoClient = new Mongo(hostName, port); DB db = mongoClient.getDB(dbName); db.authenticate(userName, password.toCharArray()); // Clean up old entries DBCollection coll = db.getCollection("testCollection"); coll.drop(); BasicDBObject lastAddedObject = null; for (String curItem : myGroceryList) { lastAddedObject = new BasicDBObject("i", curItem); coll.insert(lastAddedObject); } response.getWriter().println("<b>My grocery list is:</b>"); coll.remove(lastAddedObject); DBCollection loadedCollection = db.getCollection("testCollection"); DBCursor cursor = loadedCollection.find(); try { response.getWriter().println("<ul>"); while (cursor.hasNext()) { response.getWriter().println("<li>" + cursor.next().get("i") + "</li>"); } response.getWriter().println("</ul>"); } finally { cursor.close(); } }
From source file:com.sanaldiyar.projects.nanohttpd.mongodbbasedsessionhandler.MongoDBBasedSessionHandler.java
/** * Request parser for session. Gets and builds session information * * @param request the request/*from w w w. j a v a2 s. com*/ * @return session manager */ @Override public NanoSessionManager parseRequest(Request request) { MongoDBBasedSessionManager nanoSessionManager = null; DBObject session = null; String sessionid = null; for (Cookie cookie : request.getCookies()) { if (cookie.getName().equals(SESSIONCOOKIEID)) { sessionid = cookie.getValue(); break; } } DBCollection sessions = managers.getCollection("sessions"); if (sessionid != null) { DBCursor cursor = sessions.find(new BasicDBObject("sessionid", sessionid)); List<DBObject> result = cursor.toArray(); cursor.close(); if (result.size() == 1) { session = result.get(0); } if (session != null) { if (((Date) session.get("expires")).getTime() <= new Date().getTime()) { sessions.remove(new BasicDBObject().append("sessionid", sessionid)); session = null; } } } if (session == null) { do { sessionid = new BigInteger(128, srng).toString(32); } while (sessions.findOne(new BasicDBObject().append("sessionid", sessionid)) != null && !sessionid.equals("0")); session = new BasicDBObject(); nanoSessionManager = new MongoDBBasedSessionManager(session); nanoSessionManager.setSessionID(sessionid); sessions.insert(session); } else { nanoSessionManager = new MongoDBBasedSessionManager(session); } return nanoSessionManager; }
From source file:com.seyren.mongo.MongoStore.java
License:Apache License
protected SeyrenResponse executeQueryAndCollectResponse(DBObject query) { List<Check> checks = new ArrayList<Check>(); DBCursor dbc = getChecksCollection().find(query); while (dbc.hasNext()) { checks.add(mapper.checkFrom(dbc.next())); }//from w w w .j a v a 2 s.c o m dbc.close(); return new SeyrenResponse<Check>().withValues(checks).withTotal(dbc.count()); }
From source file:com.seyren.mongo.MongoStore.java
License:Apache License
@Override public SeyrenResponse<Check> getChecksByState(Set<String> states, Boolean enabled) { List<Check> checks = new ArrayList<Check>(); DBObject query = new BasicDBObject(); query.put("state", object("$in", states.toArray())); if (enabled != null) { query.put("enabled", enabled); }/* w w w. j a va 2 s. c o m*/ DBCursor dbc = getChecksCollection().find(query); while (dbc.hasNext()) { checks.add(mapper.checkFrom(dbc.next())); } dbc.close(); return new SeyrenResponse<Check>().withValues(checks).withTotal(dbc.count()); }
From source file:com.seyren.mongo.MongoStore.java
License:Apache License
@Override public SeyrenResponse<Alert> getAlerts(String checkId, int start, int items) { DBCursor dbc = getAlertsCollection().find(object("checkId", checkId)).sort(object("timestamp", -1)) .skip(start).limit(items);/*from w w w . j av a 2s.co m*/ List<Alert> alerts = new ArrayList<Alert>(); while (dbc.hasNext()) { alerts.add(mapper.alertFrom(dbc.next())); } dbc.close(); return new SeyrenResponse<Alert>().withValues(alerts).withItems(items).withStart(start) .withTotal(dbc.count()); }
From source file:com.seyren.mongo.MongoStore.java
License:Apache License
@Override public SeyrenResponse<Alert> getAlerts(int start, int items) { DBCursor dbc = getAlertsCollection().find().sort(object("timestamp", -1)).skip(start).limit(items); List<Alert> alerts = new ArrayList<Alert>(); while (dbc.hasNext()) { alerts.add(mapper.alertFrom(dbc.next())); }/* w ww.j a v a2s . co m*/ dbc.close(); return new SeyrenResponse<Alert>().withValues(alerts).withItems(items).withStart(start) .withTotal(dbc.count()); }
From source file:com.seyren.mongo.MongoStore.java
License:Apache License
@Override public Alert getLastAlertForTargetOfCheck(String target, String checkId) { DBObject query = object("checkId", checkId).with("targetHash", TargetHash.create(target)); DBCursor cursor = getAlertsCollection().find(query).sort(object("timestamp", -1)).limit(1); try {/*from www .j a va 2 s . c om*/ while (cursor.hasNext()) { return mapper.alertFrom(cursor.next()); } } finally { cursor.close(); } return null; }
From source file:com.sfelf.connectors.mongoOplogCursorConnector.java
License:Open Source License
/** * <b>OplogCursor</b> - Establishes a tailable cursor to the mongoDB oplog for the specified namespace and operations * and returns the results to the Mulesoft inbound endpoint. The returned payload is a {@link DBObject}. * <p/>/* w ww .ja v a 2 s. c om*/ * Throws a {@link MongoOplogCursorException} if any unexpected issues arise while trying to * establish the tailable cursor or while processing the results from the cursor. * <p/> * {@sample.xml ../../../doc/mongoOplogCursor-connector.xml.sample mongooplogcursor:oplogCursor} * @param namespace The exact namespace (ex. database.collection) for which the endpoint should return messages when * entries are logged in the oplog for that namespace. * @param fullDocument {@link Boolean} to control if messages will include the full oplog document or just the following fields: * <ul> * <li>ts - timestamp * <li>op - operation (i=insert, u=update, d=delete) * <li>ns - namespace * <li>o._id - _id of the record inserted or updated * <li>o2._id - _id of the record updated * </ul> * @param monitorInserts {@link Boolean} to control if messages will be generated for Inserts (Optional: defaults to false) * @param monitorUpdates {@link Boolean} to control if messages will be generated for Updates (Optional: defaults to false) * @param monitorDeletes {@link Boolean} to control if messages will be generated for Deletes (Optional: defaults to false) * @param callback The callback to be called when a message is received * <p/> * @throws MongoOplogCursorException If {@link #isConnected() isConnected} == false */ @Source(primaryNodeOnly = true, exchangePattern = MessageExchangePattern.ONE_WAY) public void oplogCursor( @FriendlyName("Namespace") @Placement(group = "Query Options", order = 1) String namespace, @FriendlyName("Return full document") @Optional @Placement(group = "Query Options", order = 2) @Default("false") Boolean fullDocument, @FriendlyName("Monitor Insert Operations") @Optional @Placement(group = "Operations", order = 3) @Default("false") Boolean monitorInserts, @FriendlyName("Monitor Update Operations") @Optional @Placement(group = "Operations", order = 4) @Default("false") Boolean monitorUpdates, @FriendlyName("Monitor Delete Operations") @Optional @Placement(group = "Operations", order = 5) @Default("false") Boolean monitorDeletes, SourceCallback callback) throws MongoOplogCursorException { if (!isConnected()) { throw new MongoOplogCursorException( "Unable to initiate cursor because MongoClient is not connected: " + mongoClient); } DBCollection log = getCollection(logDB, logCollection, true); DBCollection oplog = getCollection(oplogDB, OPLOG_COLLECTION_NAME, false); BSONTimestamp lastTimestamp = getLastTimestamp(oplog, log, namespace); LOGGER.debug("Last Timestamp: " + lastTimestamp); while (!Thread.interrupted()) { DBObject query = getOplogQuery(lastTimestamp, namespace, monitorInserts, monitorUpdates, monitorDeletes); DBCursor cursor = createCursor(oplog, query, fullDocument); LOGGER.debug("New cursor: " + cursor.toString()); try { while (cursor.hasNext()) { final DBObject doc = cursor.next(); LOGGER.debug("New document: " + doc); if (doc != null) { callback.process(doc); lastTimestamp = (BSONTimestamp) doc.get("ts"); updateLastTimestampLog(log, namespace, lastTimestamp); LOGGER.debug("Updated Last Timestamp: " + lastTimestamp); } else { LOGGER.debug("Sleeping until next document ready"); Thread.sleep(NO_DOC_SLEEP_TIME); } } } catch (Exception e) { LOGGER.debug( "Caught Exception while reading from cursor: " + e.getClass() + " - " + e.getMessage()); } finally { LOGGER.debug("Closing Cursor and attempting to acquire a new cursor"); try { cursor.close(); } catch (Exception e) { LOGGER.debug("Caught Exception while closing cursor: " + e.getClass() + " - " + e.getMessage()); } } } LOGGER.debug("Thread Interrupted:" + "\n" + "log = " + log + "\n" + "oplog = " + oplog); }
From source file:com.sitewhere.mongodb.device.MongoDeviceEventManagement.java
License:Open Source License
@Override public ISearchResults<IDeviceEvent> listDeviceEvents(String assignmentToken, IDateRangeSearchCriteria criteria) throws SiteWhereException { DBCollection events = getMongoClient().getEventsCollection(getTenant()); BasicDBObject query = new BasicDBObject(MongoDeviceEvent.PROP_DEVICE_ASSIGNMENT_TOKEN, assignmentToken); MongoPersistence.addDateSearchCriteria(query, MongoDeviceEvent.PROP_EVENT_DATE, criteria); BasicDBObject sort = new BasicDBObject(MongoDeviceEvent.PROP_EVENT_DATE, -1) .append(MongoDeviceEvent.PROP_RECEIVED_DATE, -1); int offset = Math.max(0, criteria.getPageNumber() - 1) * criteria.getPageSize(); DBCursor cursor = events.find(query).skip(offset).limit(criteria.getPageSize()).sort(sort); List<IDeviceEvent> matches = new ArrayList<IDeviceEvent>(); SearchResults<IDeviceEvent> results = new SearchResults<IDeviceEvent>(matches); try {//from ww w .jav a 2 s. com results.setNumResults(cursor.count()); while (cursor.hasNext()) { DBObject match = cursor.next(); matches.add(MongoPersistence.unmarshalEvent(match)); } } finally { cursor.close(); } return results; }
From source file:com.sitewhere.mongodb.device.MongoDeviceManagement.java
License:Open Source License
@Override public ISearchResults<IDeviceEvent> listDeviceEvents(String assignmentToken, IDateRangeSearchCriteria criteria) throws SiteWhereException { DBCollection events = getMongoClient().getEventsCollection(); BasicDBObject query = new BasicDBObject(MongoDeviceEvent.PROP_DEVICE_ASSIGNMENT_TOKEN, assignmentToken); MongoPersistence.addDateSearchCriteria(query, MongoDeviceEvent.PROP_EVENT_DATE, criteria); BasicDBObject sort = new BasicDBObject(MongoDeviceEvent.PROP_EVENT_DATE, -1) .append(MongoDeviceEvent.PROP_RECEIVED_DATE, -1); int offset = Math.max(0, criteria.getPageNumber() - 1) * criteria.getPageSize(); DBCursor cursor = events.find(query).skip(offset).limit(criteria.getPageSize()).sort(sort); List<IDeviceEvent> matches = new ArrayList<IDeviceEvent>(); SearchResults<IDeviceEvent> results = new SearchResults<IDeviceEvent>(matches); try {//from w w w.jav a 2 s. com results.setNumResults(cursor.count()); while (cursor.hasNext()) { DBObject match = cursor.next(); matches.add(MongoPersistence.unmarshalEvent(match)); } } finally { cursor.close(); } return results; }