List of usage examples for com.mongodb DBCursor next
@Override
public DBObject next()
From source file:com.deftlabs.lock.mongo.impl.LockDao.java
License:Apache License
/** * Check for expired/inactive/dead locks and unlock. *//*from w ww. j a va 2s .c om*/ 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.deliveronthego.CommonAPI.java
@POST @Path("/findDrivers") @Consumes(MediaType.APPLICATION_JSON)//ww w . j a v a 2s. com @Produces(MediaType.APPLICATION_JSON) public Response doDeliveryDetails(String deliver) { System.out.println("inside delivery details"); String message; GraphTraversal g = new GraphTraversal(); try { System.out.println("inside delivery details"); JSONObject deliverJson = new JSONObject(deliver); boolean var = new DbConnection().deliver(deliverJson.getString("emailId"), Double.valueOf(deliverJson.getString("pickupLatitude")), Double.valueOf(deliverJson.getString("pickupLongitude")), Double.valueOf(deliverJson.getString("dropOffLatitude")), Double.valueOf(deliverJson.getString("dropOffLongitude")), deliverJson.getInt("length"), deliverJson.getInt("breadth"), deliverJson.getInt("width")); System.out.println("after delivery details"); if (var) { System.out.println("in success"); message = "Delivery Details Inserted successfully"; JSONObject statusMessage = new JSONObject(); statusMessage.put("message", message); String res = g.findDriver(deliverJson.getString("emailId"), deliverJson.getDouble("pickupLatitude"), deliverJson.getDouble("pickupLongitude"), deliverJson.getDouble("dropOffLatitude"), deliverJson.getDouble("dropOffLongitude")); System.out.println(res); JSONArray jarr = new JSONArray(res); for (int j = 0; j < jarr.length(); j++) { JSONObject json = new JSONObject(jarr.get(j).toString()); String driverId = json.get("driverId").toString(); System.out.println(driverId); mongoclient = getConnection(); DB db = mongoclient.getDB("deliveronthego"); DBCollection driverSourceDetails = db.getCollection("login"); BasicDBObject whereQuery = new BasicDBObject(); whereQuery.put("emailId", driverId); whereQuery.put("userType", "Driver"); DBCursor cursor = driverSourceDetails.find(whereQuery); if (cursor.hasNext()) { BasicDBObject obj = (BasicDBObject) cursor.next(); String regId = obj.getString("regId"); String[] gcmIds = regId.split("\\="); System.out.println(gcmIds[1]); String apiKey = "AIzaSyDzXEIMFY3EGbJ4mjc9xBYyeakjggxuTC0"; Content content = createContent(gcmIds[1], deliverJson.getString("emailId")); DotgGCMPost.post(apiKey, content); DBCollection selection = db.getCollection("selection"); BasicDBObject sel = new BasicDBObject() .append("userEmailId", deliverJson.getString("emailId")) .append("driverEmailId", driverId).append("Accepted", "No"); selection.insert(sel); throw new JSONException("gi"); } else { //System.out.println("cursor=="+cursor.toString()); throw new JSONException("No email found"); } } return Response.status(200).entity(statusMessage).build(); } else { System.out.println("in fail"); message = "Delivery Details Insertion Failed"; JSONObject statusMessage = new JSONObject(); statusMessage.put("message", message); return Response.status(404).entity(statusMessage).build(); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } message = "Delivery Details Insertion Failed"; return Response.status(404).entity(message).build(); }
From source file:com.deliveronthego.DbConnection.java
public boolean login(String emailId, String password, String userType) { mongoclient = getConnection();//from w w w.j a va2 s .c o m @SuppressWarnings("deprecation") DB db = mongoclient.getDB("deliveronthego"); DBCollection login = db.getCollection("login"); if (emailId.contains("@")) { BasicDBObject logInObj = new BasicDBObject(); logInObj.put("emailId", emailId); DBCursor logInCursor = login.find(logInObj); while (logInCursor.hasNext()) { logInCursor.next(); DBObject userDetailObj = logInCursor.curr(); if (userDetailObj != null) { String logInPassword = userDetailObj.get("password").toString(); String loginUserType = userDetailObj.get("userType").toString(); System.out.println(logInPassword); if ((logInPassword != null) && (logInPassword.equalsIgnoreCase(password)) && (loginUserType != null) && (loginUserType.equalsIgnoreCase(userType))) { return true; } else { return false; } } else { return false; } } return true; } else { return false; } }
From source file:com.deliveronthego.DbConnection.java
public String location(String date, double transitionLatitude, double transitionLongitude, double stopLatitude, double stopLongitude, String driverId) { mongoclient = getConnection();//from w ww . j a v a2s . c o m @SuppressWarnings("deprecation") DB db = mongoclient.getDB("deliveronthego"); DBCollection location = db.getCollection("location"); BasicDBObject whereQuery = new BasicDBObject(); whereQuery.put("driverID", driverId); DBCursor locationCursor = location.find(whereQuery); boolean updateFlag = false; while (locationCursor.hasNext()) { locationCursor.next(); DBObject locDB = locationCursor.curr(); System.out.println(locDB); String dateStr = locDB.get("Date").toString(); if (dateStr.equals(date)) { location.update(new BasicDBObject("driverID", driverId), new BasicDBObject("$set", new BasicDBObject("transitionLatitude", transitionLatitude) .append("transitionLongitude", transitionLongitude))); Double previousStopLatitude = (Double) locDB.get("stopLatitude"); Double previousStopLongitude = (Double) locDB.get("stopLongitude"); System.out.println("previousStopLatitude: " + previousStopLatitude); System.out.println("previousStopLongitude: " + previousStopLongitude); /*if((previousStopLatitude==0.0) && (previousStopLongitude==0.0)) { location.update(new BasicDBObject("driverID", driverId), new BasicDBObject("$set", new BasicDBObject("stopLatitude", stopLatitude).append("stopLongitude", stopLongitude))); }*/ } updateFlag = true; } if (!updateFlag) { BasicDBObject locationObj = new BasicDBObject("Date", date.toString()) .append("transitionLatitude", transitionLatitude) .append("transitionLongitude", transitionLongitude).append("stopLatitude", stopLatitude) .append("stopLongitude", stopLongitude).append("driverID", driverId); location.insert(locationObj); return "Location Details Inserted Sucessfully"; } else { return "Location Details Updated"; } }
From source file:com.deliveronthego.DbConnection.java
public String transcationNotification(String driverID, Boolean pickedUp, Boolean delivered) { mongoclient = getConnection();/*from w w w .j ava2 s . co m*/ @SuppressWarnings("deprecation") DB db = mongoclient.getDB("deliveronthego"); DBCollection notification = db.getCollection("notification"); BasicDBObject notificationObj = new BasicDBObject(); notificationObj.append("driverID", driverID); Date date = new Date(); Calendar cal = Calendar.getInstance(); cal.setTime(date); DBCursor notificationCursor = notification.find(notificationObj); if (pickedUp && !delivered) { notificationObj.append("pickedUp", pickedUp.toString()).append("delivered", delivered.toString()) .append("date", cal.toString()); notification.insert(notificationObj); return "New Transaction Data inserted"; } else { if (notificationCursor.hasNext()) { notificationCursor.next(); DBObject notifyObj = notificationCursor.curr(); Date currentDateInDatabase = (Date) notifyObj.get("date"); if (!(boolean) notifyObj.get("delivered") && currentDateInDatabase.before(date)) { notification.update(new BasicDBObject("driverID", driverID), new BasicDBObject("$set", new BasicDBObject("delivered", delivered.toString()))); return "Transaction Completed"; } else { return "Transaction failed to update"; } } else { return "Transaction failed"; } } }
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 w w. ja v a2 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; } }
From source file:com.dilmus.dilshad.scabi.deprecated.DBackFileOld.java
License:Open Source License
public int updateMetaData(String fileName, ObjectId fileID, String type, String contentType) throws IOException, DScabiException, ParseException { int n = 0;//from w w w. j av a 2 s . c om String uploadDate = null; Date datefromDB = null; BasicDBObject documentWhere = new BasicDBObject(); documentWhere.put("_id", fileID); DBCursor cursorExist = m_table.find(documentWhere); n = cursorExist.count(); if (1 == n) { log.debug("updateMetaData() Inside 1 == n"); while (cursorExist.hasNext()) { DBObject ob = cursorExist.next(); log.debug("updateMetaData() result from ob {}", ob.toString()); //datefromDB = (String) ((BasicBSONObject) ob).getString("uploadDate"); datefromDB = ((BasicBSONObject) ob).getDate("uploadDate"); if (null == datefromDB) { throw new DScabiException("updateMetaData() Unable to get uploadDate for file : " + fileName + " fileID : " + fileID.toHexString(), "DBF.UMD.1"); } log.debug("datefromDB : {}", datefromDB); } } else if (0 == n) { log.debug("updateMetaData() No matches for file : " + fileName + " fileID : " + fileID.toHexString()); throw new DScabiException( "updateMetaData() No matches for file : " + fileName + " fileID : " + fileID.toHexString(), "DBF.UMD.2"); } else { log.debug("updateMetaData() Multiple matches for file : " + fileName + " fileID : " + fileID.toHexString()); throw new DScabiException("updateMetaData() Multiple matches for file : " + fileName + " fileID : " + fileID.toHexString(), "DBF.UMD.3"); } Date date = new Date(); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS"); dateFormat.setTimeZone(TimeZone.getTimeZone("ISO")); String putClientDateTime = dateFormat.format(date); // To parse from string : Date date2 = dateFormat.parse(putDateTime); // Uses java.time java 8 : ZonedDateTime now = ZonedDateTime.now( ZoneOffset.UTC ); String millisTime = "" + System.currentTimeMillis(); String nanoTime = "" + System.nanoTime(); /* If datefromDB is String SimpleDateFormat dateFormatFromDB = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); dateFormatFromDB.setTimeZone(TimeZone.getTimeZone("ISO")); CharSequence cs1 = "T"; CharSequence cs2 = "Z"; String s1 = datefromDB.replace(cs1, " "); String s2 = s1.replace(cs2, ""); Date date2 = dateFormatFromDB.parse(s2); uploadDate = dateFormat.format(date2); */ uploadDate = dateFormat.format(datefromDB); log.debug("uploadDate : {}", uploadDate); BasicDBObject documentUpdate = new BasicDBObject(); documentUpdate.append("PutFileName", fileName); documentUpdate.append("PutServerFileID", fileID.toHexString()); documentUpdate.append("PutServerUploadDateTime", uploadDate); documentUpdate.append("PutType", type); documentUpdate.append("PutContentType", contentType); documentUpdate.append("PutClientDateTime", putClientDateTime); documentUpdate.append("PutClientDateTimeInMillis", millisTime); documentUpdate.append("PutClientDateTimeInNano", nanoTime); documentUpdate.append("PutStatus", "Completed"); documentUpdate.append("PutLatestNumber", "1"); BasicDBObject updateObj = new BasicDBObject(); updateObj.put("$set", documentUpdate); WriteResult result = m_table.update(documentWhere, updateObj); if (1 != result.getN()) throw new DScabiException( "Update meta data failed for file : " + fileName + " fileID : " + fileID.toHexString(), "DBF.UMD.4"); handlePreviousVersions(fileName, fileID.toHexString(), uploadDate); return result.getN(); }
From source file:com.dilmus.dilshad.scabi.deprecated.DBackFileOld.java
License:Open Source License
private int handlePreviousVersions(String fileName, String strFileID, String strPutServerUploadDateTime) throws IOException, DScabiException { int m = 0;//from w ww . j a va 2s .c om int n = 0; // It is better to call this only after meta data is updated for currently uploaded file // This will skip checking for given input strFileID, file ID of currently uploaded file removeFilesIncompleteMetaData(fileName, strFileID); BasicDBObject documentFind = new BasicDBObject(); documentFind.put("PutFileName", fileName); documentFind.append("PutServerFileID", strFileID); documentFind.append("PutStatus", "Completed"); documentFind.append("PutLatestNumber", "1"); DBCursor cursor = m_table.find(documentFind); m = cursor.count(); if (1 == m) { log.debug("handlePreviousVersions() Inside 1 == n"); } else if (0 == m) { log.debug("handlePreviousVersions() No matches for file : " + fileName + " strFileID : " + strFileID); throw new DScabiException( "handlePreviousVersions() No matches for file : " + fileName + " strFileID : " + strFileID, "DBF.HPV.1"); } else { log.debug("handlePreviousVersions() Multiple matches for file : " + fileName + " strFileID : " + strFileID); throw new DScabiException("handlePreviousVersions() Multiple matches for file : " + fileName + " strFileID : " + strFileID, "DBF.HPV.2"); } BasicDBObject documentQuery = new BasicDBObject(); documentQuery.put("PutFileName", fileName); documentQuery.append("PutStatus", "Completed"); DBCursor cursorExist = m_table.find(documentQuery); n = cursorExist.count(); if (1 == n) { log.debug( "handlePreviousVersions() Information only : Inside 1 == n. Only one file / current file is found. No previous versions for file : " + fileName + " with PutStatus=Completed"); return 0; } else if (0 == n) { log.debug("handlePreviousVersions() No matches for file : " + fileName + " with PutStatus=Completed"); throw new DScabiException( "handlePreviousVersions()() No matches for file : " + fileName + " with PutStatus=Completed", "DBF.HPV.3"); } else { long lf1 = Long.parseLong(strPutServerUploadDateTime); while (cursorExist.hasNext()) { DBObject ob = cursorExist.next(); log.debug("handlePreviousVersions() result from ob {}", ob.toString()); String fid = (String) ((BasicBSONObject) ob).getString("PutServerFileID"); if (null == fid) { throw new DScabiException("PutServerFileID is missing for one version of file : " + fileName, "DBF.HPV.4"); } /* Don't use. It should be based on date-time and not on file ID if (f.equals(strFileID)) { // proceed with other versions continue; } */ String f = (String) ((BasicBSONObject) ob).getString("PutServerUploadDateTime"); if (null == f) { throw new DScabiException("PutServerUploadDateTime is missing for one version of file : " + fileName + " file ID : " + fid, "DBF.HPV.5"); } String f2 = (String) ((BasicBSONObject) ob).getString("PutLatestNumber"); if (null == f2) { throw new DScabiException("PutLatestNumber is missing for one version of file : " + fileName + " file ID : " + fid, "DBF.HPV.6"); } if (f.equals(strPutServerUploadDateTime) && f2.equals("1")) { // proceed with other versions continue; } long lf2 = Long.parseLong(f); if (lf1 < lf2 && f2.equals("1")) { // proceed with other versions continue; } if (f2.equals("1")) { // all file entries here have PutServerUploadDateTime < strPutServerUploadDateTime // there can be multiple previous versions with PutLatestNumber=1 BasicDBObject documentWhere = new BasicDBObject(); documentWhere.put("PutServerFileID", fid); BasicDBObject documentUpdate = new BasicDBObject(); documentUpdate.append("PutLatestNumber", "2"); BasicDBObject updateObj = new BasicDBObject(); updateObj.put("$set", documentUpdate); // there should be only one entry for file ID fid WriteResult result = m_table.update(documentWhere, updateObj); if (result.getN() <= 0) throw new DScabiException("Update meta data to PutLatestNumber=2 failed for file : " + fileName + " file ID : " + fid, "DBF.HPV.7"); } else { // remove all other versions m_gridFSBucket.delete(new ObjectId(fid)); } } } return 0; }
From source file:com.dilmus.dilshad.scabi.deprecated.DBackFileOld.java
License:Open Source License
private int removeFilesIncompleteMetaData(String fileName, String strFileID) { int n = 0;/*w w w . ja v a 2 s. c o m*/ Set<String> stMetaKeys = new HashSet<String>(); stMetaKeys.add("PutFileName"); stMetaKeys.add("PutServerFileID"); stMetaKeys.add("PutServerUploadDateTime"); stMetaKeys.add("PutType"); stMetaKeys.add("PutContentType"); stMetaKeys.add("PutClientDateTime"); stMetaKeys.add("PutClientDateTimeInMillis"); stMetaKeys.add("PutClientDateTimeInNano"); stMetaKeys.add("PutStatus"); stMetaKeys.add("PutLatestNumber"); BasicDBObject documentQuery = new BasicDBObject(); // "filename" is MongoDB/GridFS specific meta data name inside fs.files collection for each file documentQuery.put("filename", fileName); DBCursor cursorExist = m_table.find(documentQuery); n = cursorExist.count(); if (0 == n) { log.debug("removeFilesIncompleteMetaData() Information only : No file found for file : " + fileName); return 0; } else { while (cursorExist.hasNext()) { DBObject ob = cursorExist.next(); log.debug("removeFilesIncompleteMetaData() result from ob {}", ob.toString()); // "_id" is MongoDB/GridFS specific meta data name inside fs.files collection for each file ObjectId oid = ((BasicBSONObject) ob).getObjectId("_id"); if (null == oid) { // what's the use in throwing exception here? throw new DScabiException("_id is missing for file : " + fileName, "DBF.RFI.1"); // let it continue to cleanup as much as possible continue; } if (oid.toHexString().equals(strFileID)) { log.debug( "removeFilesIncompleteMetaData() Information only : skipping given input file ID : {}", strFileID); continue; } Set<String> st = ob.keySet(); if (st.containsAll(stMetaKeys)) { continue; } else { // remove file m_gridFSBucket.delete(oid); } } } return 0; }
From source file:com.dilmus.dilshad.scabi.deprecated.DBackFileOld.java
License:Open Source License
public int removeAllFilesIncompleteMetaData() { int n = 0;// w w w . j a v a 2 s . c om Set<String> stMetaKeys = new HashSet<String>(); stMetaKeys.add("PutFileName"); stMetaKeys.add("PutServerFileID"); stMetaKeys.add("PutServerUploadDateTime"); stMetaKeys.add("PutType"); stMetaKeys.add("PutContentType"); stMetaKeys.add("PutClientDateTime"); stMetaKeys.add("PutClientDateTimeInMillis"); stMetaKeys.add("PutClientDateTimeInNano"); stMetaKeys.add("PutStatus"); stMetaKeys.add("PutLatestNumber"); DBCursor cursorExist = m_table.find(); n = cursorExist.count(); if (0 == n) { log.debug("removeAllFilesIncompleteMetaData() Information only : No file found"); return 0; } else { while (cursorExist.hasNext()) { DBObject ob = cursorExist.next(); log.debug("removeAllFilesIncompleteMetaData() result from ob {}", ob.toString()); // "_id" is MongoDB/GridFS specific meta data name inside fs.files collection for each file ObjectId oid = ((BasicBSONObject) ob).getObjectId("_id"); if (null == oid) { // what's the use in throwing exception here? throw new DScabiException("_id is missing for file : " + fileName, "DBF.RAF.1"); // let it continue to cleanup as much as possible continue; } Set<String> st = ob.keySet(); if (st.containsAll(stMetaKeys)) { continue; } else { // remove file m_gridFSBucket.delete(oid); } } } return 0; }