public User getBooking(final String bookingId) { /** * Creating 'nextUserEmailInQueue' as string buffer because value cannot be reassigned as it is * declared as final */ final User user = new User(); try { final MongoDatabase mdb = MongoDBConnManager.getInstance().getConnection(); final MongoCollection<Document> coll = mdb.getCollection(DBConstants.COLL_BOOKING); final Document findCr = new Document(); findCr.put(DBConstants.BOOKING_ID, bookingId); final ArrayList<Document> lstBkngs = coll.find(findCr).into(new ArrayList<Document>()); for (final Document document : lstBkngs) { user.setEmail(document.getString(DBConstants.EMAIL)); user.setBookingId(document.getString(DBConstants.BOOKING_ID)); } } catch (Exception e) { if (e instanceof com.mongodb.MongoTimeoutException) { throw new ApplicationException(MessagesEnum.MONGODB_IS_DOWN.getMessage(), e); } throw new ApplicationException(MessagesEnum.BOOKINGS_RETRIVAL_FAILED.getMessage(), e); } return user; }
/** * 取得指定住院号的记录 * * @param admissionNum 住院号 * @return 住院记录 */ public record GetRecord(String admissionNum) { try { MongoDAO dao = MongoDAO.GetInstance(); BasicDBObject cond = new BasicDBObject(); cond.append("admission_number", new BasicDBObject("$eq", admissionNum)); FindIterable<Document> result = dao.GetCollection("records").find(cond); MongoCursor<Document> it = result.iterator(); if (it.hasNext()) { Document doc = it.next(); record fol = new record(); fol.setAdmission_number(doc.getString("admission_number")); fol.setName(doc.getString("name")); fol.setWeixin_openid(doc.getString("weixin_openid")); fol.setLeaveTime(doc.getDate("leaveTime")); fol.setInTime(doc.getDate("inTime")); fol.setDisease(doc.getString("disease")); return fol; } return null; } catch (Exception e) { e.printStackTrace(); logger.error(e.toString()); return null; } }
/** * 取得已出院未回访的用户 * * @return */ public List<record> GetleavehospitalRecords() { try { List<record> list = new ArrayList<record>(); MongoDAO dao = MongoDAO.GetInstance(); BasicDBObject cond = new BasicDBObject(); cond.append("leaveHospital", new BasicDBObject("$eq", true)); cond.append("followup", new BasicDBObject("$eq", false)); FindIterable<Document> result = dao.GetCollection("records").find(cond); MongoCursor<Document> it = result.iterator(); while (it.hasNext()) { Document doc = it.next(); record fol = new record(); fol.setAdmission_number(doc.getString("admission_number")); fol.setName(doc.getString("name")); fol.setWeixin_openid(doc.getString("weixin_openid")); fol.setLeaveTime(doc.getDate("leaveTime")); fol.setDisease(doc.getString("disease")); list.add(fol); } return list; } catch (Exception e) { e.printStackTrace(); logger.error(e.toString()); return null; } }
public RuleResult runRule( Document aggregation, Object rightsHolders, BasicBSONList affiliations, Document preferences, Document statsDocument, Document profile, Object context) { RuleResult result = new RuleResult(); try { long max = Long.parseLong(statsDocument.getString("Total Size")); long repoMax = Long.parseLong(profile.getString("Total Size")); if (max > repoMax) { result.setResult(-1, "Total size exceeds maximum allowed (" + repoMax + ")."); } else { result.setResult(1, "Total size is acceptable (<=" + repoMax + ")."); } } catch (NullPointerException npe) { // Just return untriggered result System.out.println("Missing info in TotalSize rule" + npe.getLocalizedMessage()); } catch (NumberFormatException nfe) { // Just return untriggered result System.out.println( "Missing info in MaxDatasetSize rule for repo: " + profile.getString("orgidentifier") + " : " + nfe.getLocalizedMessage()); } return result; }
public void removeOtherBookingsIfAny(String email, String bookingId) { final List<String> extraBookings = new ArrayList<String>(); try { final MongoDatabase mdb = MongoDBConnManager.getInstance().getConnection(); final MongoCollection<Document> coll = mdb.getCollection(DBConstants.COLL_BOOKING); final Document findCr = new Document(); findCr.put(DBConstants.EMAIL, email); final ArrayList<Document> lstBkngs = coll.find(findCr).into(new ArrayList<Document>()); for (final Document document : lstBkngs) { if (!StringUtils.equalsIgnoreCase(bookingId, document.getString(DBConstants.BOOKING_ID))) { extraBookings.add(document.getString(DBConstants.BOOKING_ID)); } } if (!extraBookings.isEmpty()) { QueryBuilder deleteQuery = new QueryBuilder(); deleteQuery .put(DBConstants.BOOKING_ID) .in(extraBookings.toArray(new String[extraBookings.size()])); coll.deleteMany((Bson) deleteQuery.get()); } } catch (Exception e) { e.printStackTrace(); if (e instanceof com.mongodb.MongoTimeoutException) { throw new ApplicationException(MessagesEnum.MONGODB_IS_DOWN.getMessage(), e); } throw new ApplicationException( MessagesEnum.CLOSE_BOOKING_FAILED.getMessage(extraBookings.toString()), e); } }
public static ApplicationObject fromDocument(Document data) { return new ApplicationObject( data.getString("id"), data.getString("name"), (ArrayList<ObjectAttribute>) data.get("attributes"), (ArrayList<ObjectAction>) data.get("actions"), (ArrayList<ObjectActionChain>) data.get("actionChains")); }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); // post 可以直接设置中文字符编号 response.setCharacterEncoding("UTF-8"); response.setContentType("text/html"); PrintWriter out = response.getWriter(); String result = "error"; JSONObject json = null; String phone = request.getParameter("phone").toString().trim(); String pwd = request.getParameter("pwd").toString().trim(); StudentInfo stu = new StudentInfo(); stu.setPhone(phone); stu.setPwd(pwd); try { int temp = 0; MongoCursor<Document> cur = DaoImpl.GetSelectCursor( StudentInfo.class, CreateQueryFromBean.EqualObj(stu), 1, new BasicDBObject()); while (cur.hasNext()) { Document docu = cur.next(); School sch = new School(); sch.set_id(docu.getObjectId("SchoolId")); BasicDBObject obj = new BasicDBObject(); obj.put(StaticString.School_id, 0); obj.put(StaticString.School_ShowUrl, 1); obj.put(StaticString.School_Name, 1); MongoCursor<Document> cursor = DaoImpl.GetSelectCursor(School.class, CreateQueryFromBean.EqualObj(sch), 1, obj); while (cursor.hasNext()) { Document document = cursor.next(); json = jsonUtil.ParaFromDocument(docu); json.put("SchoolImg", document.getString("ShowUrl")); json.put("SchoolName", document.getString("Name")); temp = 1; result = json.toString(); } } if (temp == 0) { result = "LoginError"; } } catch (Exception e1) { result = "error"; } out.println(result); out.flush(); out.close(); }
public void saveOrUpdate(Document widgetDoc) { logger.debug("--> to be save widget -->"); String tableName = "Widget"; MongoDatabase db = mongoClient.getDatabase(widgetDoc.getString("appId")); MongoCollection<Document> collection = db.getCollection(tableName); if (!widgetDoc.containsKey("_id")) { ObjectId objId = new ObjectId(); widgetDoc.put("_id", objId); logger.debug("--> to insert " + tableName + " with " + widgetDoc.toJson()); collection.insertOne(widgetDoc); // 没有数据就执行添加操作 return; } String objectId = widgetDoc.get("_id").toString(); Document matchFields = new Document(); matchFields.put("_id", new ObjectId(objectId)); if (collection.find(matchFields).iterator().hasNext()) { // 有数据就执行更新操作 logger.debug("--> to update " + tableName + " with " + widgetDoc.toJson()); collection.updateOne(matchFields, new Document("$set", widgetDoc)); } else { logger.debug("--> to save " + tableName + " with " + widgetDoc.toJson()); collection.insertOne(widgetDoc); // 没有数据就执行添加操作 } }
/** {@inheritDoc} */ @Override public Set<String> readAllGroups() { Set<String> setOfGroups = new HashSet<String>(); for (Document document : collection.find()) { setOfGroups.add(document.getString(GROUPNAME)); } setOfGroups.remove(null); setOfGroups.remove(""); return setOfGroups; }
/** Read user account from DB */ public static UserAccount readFromDb(String userId) { if (!useMongoDB) { if (virtualDB.containsKey(userId)) { return virtualDB.get(userId); } return null; } if (db == null) { try { connect(); } catch (ParseException e) { e.printStackTrace(); } } FindIterable<Document> iterable = db.getCollection("user_accounts").find(new Document("userID", userId)); if (iterable == null) { return null; } Document doc = iterable.first(); return new UserAccount(userId, doc.getString("userName"), doc.getString("additionalInfo")); }
public static List<String> queryMongoForSimilar(String courtId, String facets) throws Exception { // Query mongo for other facets with these values. System.out.println("Court id is: " + courtId); initializeMap(); List<String> facetList = facetStringToListOfKeys(facets); // Facet list has the keys to get. Query mongo for the document with given courtId, then pull // the values of these keys. MongoConnection mc = new MongoConnection("supremeCourtDataDB.properties"); MongoCollection<Document> collection = mc.getCollection(); int courtIdInt = Integer.parseInt(courtId); Document d = collection.find(eq("courtId", courtIdInt)).first(); System.out.println("Doc with this court id: " + d); Document queryDoc = new Document(); // Build query based on given keys and their values in this doc. for (int i = 0; i < facetList.size(); i++) { String key = facetList.get(i); String tempString; int tempInt; try { tempString = d.getString(key); // queryJSON.put(key, tempString); queryDoc.put(key, tempString); } catch (ClassCastException c) { tempInt = d.getInteger(key); queryDoc.put(key, tempInt); // queryJSON.put(key, tempInt); } } List<String> resultList = new ArrayList<String>(); System.out.println("Querying mongo."); FindIterable<Document> result = collection.find(queryDoc); for (Document doc : result) { String temp = Integer.toString(doc.getInteger("courtId")); resultList.add(temp); } System.out.println("Done!"); return resultList; }
/** * Get data set from CKAN repository * * <p>4 Big Source --> Direct Link */ @SuppressWarnings("unchecked") private void getPackageList() { HttpClient client = new HttpClient(); LOG.info(split.getAction()); GetMethod method = new GetMethod(split.getAction()); method .getParams() .setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); method.setRequestHeader("User-Agent", "Hammer Project - SantaMaria crawler"); method .getParams() .setParameter(HttpMethodParams.USER_AGENT, "Hammer Project - SantaMaria crawler"); try { int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { throw new Exception("Method failed: " + method.getStatusLine()); } byte[] responseBody = method.getResponseBody(); LOG.debug(new String(responseBody)); setOutput(new String(responseBody)); Document document = Document.parse(getOutput()); if (document.containsKey("result")) { ArrayList<Document> docs = (ArrayList<Document>) ((Document) document.get("result")).get("results"); for (Document doc : docs) { this.dataset.add(doc.getString("id")); } LOG.info("SANTA MARIA CKAN3 RECORD READER found" + this.dataset.size()); } } catch (Exception e) { LOG.error(e); } finally { method.releaseConnection(); } }
/** * Test * * @param pArgs * @throws Exception */ @SuppressWarnings("unchecked") public static void main(String[] pArgs) throws Exception { GetCountByCkan3("http://catalog.data.gov/api/action/package_search?start=0&rows=1"); HttpClient client = new HttpClient(); GetMethod method = new GetMethod("http://catalog.data.gov/api/action/package_search?start=0&rows=10"); method .getParams() .setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); method.setRequestHeader("User-Agent", "Hammer Project - SantaMaria crawler"); method .getParams() .setParameter(HttpMethodParams.USER_AGENT, "Hammer Project - SantaMaria crawler"); try { int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { throw new Exception("Method failed: " + method.getStatusLine()); } byte[] responseBody = method.getResponseBody(); LOG.info(new String(responseBody)); Document document = Document.parse(new String(responseBody)); if (document.containsKey("result")) { ArrayList<Document> docs = (ArrayList<Document>) ((Document) document.get("result")).get("results"); for (Document doc : docs) { LOG.info(doc.getString("id")); } } } catch (Exception e) { LOG.error(e); } finally { method.releaseConnection(); } }
/** * Map a Mongo Document object to an Order object. * * @param d Document * @return An Order object with all the information of the Document object. */ public static final Order toOrder(Document d) { ObjectId id = d.get("_id", ObjectId.class); Document c = d.get("customer", Document.class); @SuppressWarnings("unchecked") List<Document> itemsDoc = (List<Document>) d.get("items"); List<Item> items = new ArrayList<>(itemsDoc.size()); for (Document itemDoc : itemsDoc) { items.add(ItemAdapter.toItem(itemDoc)); } Order o = new Order( id == null ? "" : id.toString(), d.getDouble("total"), d.getDate("date"), OrderStatus.findOrderStatus(d.getString("status")), CustomerAdapter.toCustomer(c), items); return o; }
// starts a new session in the sessions table public String startSession(String username) { // get 32 byte random number. that's a lot of bits. SecureRandom generator = new SecureRandom(); byte randomBytes[] = new byte[32]; generator.nextBytes(randomBytes); BASE64Encoder encoder = new BASE64Encoder(); String sessionID = encoder.encode(randomBytes); // build the BSON object Document session = new Document("username", username); session.append("_id", sessionID); sessionsCollection.deleteMany(new Document("username", username)); sessionsCollection.insertOne(session); return session.getString("_id"); }
@SuppressWarnings("unchecked") public List<Comment> get(String id) { MongoCollection<Document> commentCollection = mongoDatabase.getCollection("posts"); List<Comment> comments = new ArrayList<Comment>(); Document query = new Document(); query.put("_id", new ObjectId(id)); Document document = commentCollection.find(query).first(); if (document != null) { ArrayList<Document> list = (ArrayList<Document>) document.get("comments"); for (int i = 0; i < list.size(); i++) { Document com = (Document) list.get(i); Comment comment = new Comment(); comment.setUser(com.getString("user")); comment.setText(com.getString("text")); comment.setDate(com.getDate("date")); comments.add(comment); } } return comments; }
public Map<String, Booking> getAllBookings() { final Map<String, Booking> bookings = new LinkedHashMap<String, Booking>(); try { final MongoDatabase mdb = MongoDBConnManager.getInstance().getConnection(); final MongoCollection<Document> coll = mdb.getCollection(DBConstants.COLL_BOOKING); List<Document> aggregates = new ArrayList<Document>(); Document join = new Document(); Document sortCr = new Document(); /*Document lookup = new Document(); lookup.put("from", DBConstants.COLL_BOXES); lookup.put("localField", DBConstants.BOX_NAME); lookup.put("foreignField", DBConstants.BOX_NAME); lookup.put("as", "join_for_teamname");*/ Document lookup2 = new Document(); lookup2.put("from", DBConstants.COLL_USERS); lookup2.put("localField", DBConstants.EMAIL); lookup2.put("foreignField", DBConstants.EMAIL); lookup2.put("as", "join_for_username"); // join.put("$lookup", lookup); join.put("$lookup", lookup2); sortCr.put("$sort", new Document(DBConstants.TEAM_NAME, 1)); aggregates.add(join); aggregates.add(sortCr); final ArrayList<Document> bookingsFromDB = coll.aggregate(aggregates).into(new ArrayList<Document>()); for (final Document document : bookingsFromDB) { final User user = new User(); user.setUserName( ((Document) document.get("join_for_username", List.class).get(0)) .getString(DBConstants.USER_NAME)); user.setEmail(document.getString(DBConstants.EMAIL)); user.setTeamName( ((Document) document.get("join_for_username", List.class).get(0)) .getString(DBConstants.TEAM_NAME)); user.setBookedDateNTime(document.getDate(DBConstants.BOOKED_DATE_N_TIME)); user.setDateNTime(document.getDate(DBConstants.DATE_N_TIME)); user.setEstimatedUsage(document.getInteger(DBConstants.ESTIMATED_USAGE)); user.setBookingId(document.getString(DBConstants.BOOKING_ID)); if (!bookings.containsKey(document.getString(DBConstants.BOX_NAME))) { Booking bkng = new Booking(); bkng.setBoxName(document.getString(DBConstants.BOX_NAME)); bkng.setBoxOwner(getBoxOwner(document.getString(DBConstants.BOX_NAME))); bkng.addUserToQueue(user); bookings.put(document.getString(DBConstants.BOX_NAME), bkng); } else { Booking bkng = bookings.get(document.getString(DBConstants.BOX_NAME)); bkng.addUserToQueue(user); } } // sort users based on timestamps for (Booking bkng : bookings.values()) { Collections.sort(bkng.getUsersInQueue()); } } catch (Exception e) { if (e instanceof com.mongodb.MongoTimeoutException) { throw new ApplicationException(MessagesEnum.MONGODB_IS_DOWN.getMessage(), e); } throw new ApplicationException(MessagesEnum.BOOKINGS_RETRIVAL_FAILED.getMessage(), e); } return bookings; }
private User formUser(Document document) { User user = new User(); user.setUsername(document.getString(usernameKey)); user.setPassword(document.getString(passwordKey)); return user; }
public static Document meepDocumentBuilder(JsonObject arg, MongoCollection<Document> meepCol) { Document meep = new Document(); if (arg.get("coordinates").isJsonNull()) return null; double longi = arg.getAsJsonObject("coordinates").getAsJsonArray("coordinates").get(0).getAsDouble(); double lat = arg.getAsJsonObject("coordinates").getAsJsonArray("coordinates").get(1).getAsDouble(); BasicDBObject aux = getCloseMeepsQuery(lat, longi); FindIterable<Document> auxCol = meepCol.find(aux); if (auxCol.first() != null) { System.out.println("Received valid tweet but too close to another"); return null; } meep.append( "senderName", arg.getAsJsonObject("user").getAsJsonPrimitive("screen_name").getAsString()); System.out.println( "Received valid tweet at " + lat + "," + longi + " posted by " + meep.getString("senderName")); meep.append("senderId", arg.getAsJsonObject("user").getAsJsonPrimitive("id").getAsInt()); meep.append( "twitterUserPicture", arg.getAsJsonObject("user").getAsJsonPrimitive("profile_image_url").getAsString()); meep.append("message", arg.getAsJsonPrimitive("text").getAsString()); meep.append("type", "tweet"); meep.append("isRoot", true); meep.append("commentCounter", 0); meep.append("likeCounter", 0); meep.append("viewCounter", 0); /*if(arg.getAsJsonObject("entities").has("media")) meep.append("picture", arg.getAsJsonObject("entities").getAsJsonObject("media").get("media_url").getAsString()); else*/ meep.append("picture", null); BasicDBList list = new BasicDBList(); list.add(longi); list.add(lat); Document jobj = new Document(); jobj.append("type", "Point"); jobj.append("coordinates", list); meep.append("location", jobj); BasicDBList comments = new BasicDBList(); meep.append("comments", comments); BasicDBList receipts = new BasicDBList(); meep.append("receipts", receipts); BasicDBList registrees = new BasicDBList(); meep.append("registrees", registrees); BasicDBList likes = new BasicDBList(); meep.append("likes", likes); meep.append("categoryId", Category.TWITTER.getId()); BasicDBList hashtags = new BasicDBList(); HashtagController controller = new HashtagController(); LinkedList<String> aux2 = controller.extractHashtags(arg.getAsJsonPrimitive("text").getAsString()); for (String s : aux2) hashtags.add(s); meep.append("hashtags", hashtags); meep.append("isPublic", true); return meep; }
/** * Rename a directory * * @param u The owner * @param d The directory * @param newName The new name * @return The renamed directory */ public static Directory renameDirectory(User u, Directory d, String newName) { if (d.name == null) // Root can't be renamed return d; MongoCollection<Document> collection = DataBase.getInstance().getCollection("directories"); MongoCollection<Document> collectionFiles = DataBase.getInstance().getCollection("files.files"); Date now = new Date(); String newPath = d.path + newName; String oldPath = d.path + d.name; // Change name BasicDBObject query = new BasicDBObject(); query.put("_id", new ObjectId(d.UID)); query.put("owner", new ObjectId(u.UID)); BasicDBObject update = new BasicDBObject(); update.append("$set", new BasicDBObject().append("name", newName).append("edit", now)); collection.updateOne(query, update); // Update paths query = new BasicDBObject(); query.put("owner", new ObjectId(u.UID)); if (d.getPathList().size() > 0) { String pathRegex = "^/" + String.join("/", d.getPathList()) + "/" + d.name + "/"; query.put("path", new BasicDBObject("$regex", pathRegex)); } else { String pathRegex = "^/" + d.name + "/"; query.put("path", new BasicDBObject("$regex", pathRegex)); } // Update directories for (Document doc : collection.find(query)) { BasicDBObject dirQuery = new BasicDBObject(); dirQuery.put("_id", doc.getObjectId("_id")); update = new BasicDBObject(); update.append( "$set", new BasicDBObject() .append("path", newPath + doc.getString("path").substring(oldPath.length())) .append("edit", now)); collection.updateOne(dirQuery, update); } // Update files for (Document doc : collectionFiles.find(query)) { BasicDBObject fileQuery = new BasicDBObject(); fileQuery.put("_id", doc.getObjectId("_id")); update = new BasicDBObject(); update.append( "$set", new BasicDBObject() .append("path", newPath + doc.getString("path").substring(oldPath.length())) .append("edit", now)); collectionFiles.updateOne(fileQuery, update); } // Return the modified element d.name = newName; return d; }
/** * Move a directory * * @param u * @param d * @param newContainer * @return */ public static Directory moveDirectory(User u, Directory d, Directory newContainer) { if (d.UID == null) return d; MongoCollection<Document> collection = DataBase.getInstance().getCollection("directories"); MongoCollection<Document> collectionFiles = DataBase.getInstance().getCollection("files.files"); Date now = new Date(); // Change path BasicDBObject query = new BasicDBObject(); query.put("_id", new ObjectId(d.UID)); query.put("owner", new ObjectId(u.UID)); String oldPath = d.path; String newPath = newContainer.name == null ? "/" : newContainer.path + newContainer.name + "/"; BasicDBObject update = new BasicDBObject(); update.append("$set", new BasicDBObject().append("path", newPath).append("edit", now)); collection.updateOne(query, update); // Update paths query = new BasicDBObject(); query.put("owner", new ObjectId(u.UID)); if (d.getPathList().size() > 0) { String pathRegex = "^/" + String.join("/", d.getPathList()) + "/" + d.name + "/"; query.put("path", new BasicDBObject("$regex", pathRegex)); } else { String pathRegex = "^/" + d.name + "/"; query.put("path", new BasicDBObject("$regex", pathRegex)); } // Update directories for (Document doc : collection.find(query)) { BasicDBObject dirQuery = new BasicDBObject(); dirQuery.put("_id", doc.getObjectId("_id")); update = new BasicDBObject(); update.append( "$set", new BasicDBObject() .append("path", newPath + doc.getString("path").substring(oldPath.length())) .append("edit", now)); collection.updateOne(dirQuery, update); } // Update files for (Document doc : collectionFiles.find(query)) { BasicDBObject fileQuery = new BasicDBObject(); fileQuery.put("_id", doc.getObjectId("_id")); update = new BasicDBObject(); update.append( "$set", new BasicDBObject() .append("path", newPath + doc.getString("path").substring(oldPath.length())) .append("edit", now)); collectionFiles.updateOne(fileQuery, update); } updateDirectoryDate(u, newContainer); // Update local version d.path = newPath; return d; }