List of usage examples for com.mongodb DBCursor toArray
public List<DBObject> toArray()
From source file:edu.slu.filter.RequestServerAuthenticationFilter.java
@Override protected String doIntercept(ActionInvocation ai) throws Exception { //get remote server host ip HttpServletRequest request = ServletActionContext.getRequest(); String requestIP = request.getRemoteAddr(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); //check if the domain name and ip is in database BasicDBObject query = new BasicDBObject(); query.append("ip", requestIP); DB db = MongoDBUtil.getDb();/*from w ww .jav a 2 s . c o m*/ DBCollection coll = db.getCollection(Constant.COLLECTION_ACCEPTEDSERVER); DBCursor cursor = coll.find(query); List<DBObject> ls_results = cursor.toArray(); if (ls_results.size() > 0) { System.out.println("[Modifying Data Request]: ip ========== " + requestIP + "@" + sdf.format(new Date()) + " +++++ From Registered Server"); } else { System.out.println("[Modifying Data Request]: ip ========== " + requestIP + "@" + sdf.format(new Date()) + " +++++ Not From Registered Server"); } if (ls_results.size() > 0) { return ai.invoke(); } else { System.out.println("403 because session ip not registered"); HttpServletResponse respond_403 = ServletActionContext.getResponse(); respond_403.setStatus(403); respond_403.addHeader("Access-Control-Allow-Origin", "*"); PrintWriter out = respond_403.getWriter(); out.write("You must register with this service. Visit <a>" + Constant.RERUM_PREFIX + "</a>"); //return ai.invoke(); return "403"; } }
From source file:eu.cassandra.csn.mongo.MongoQueries.java
License:Apache License
/** * // www .j a va 2 s . c o m * @param edgeType * @return */ public static HashMap<String, Vector<InstallationInfo>> getInstallationsKL(int edgeType) { HashMap<String, Vector<InstallationInfo>> installations = new HashMap<String, Vector<InstallationInfo>>(); DBCursor cursor = DBConn.getConn().getCollection("installations").find().limit(limit); Vector<InstallationInfo> instInfos = new Vector<InstallationInfo>(); List<DBObject> insts = cursor.toArray(); double[][] dataForKL = new double[Math.min(insts.size(), limit)][]; cursor.close(); for (int i = 0; i < Math.min(insts.size(), limit); i++) { DBObject obj = insts.get(i); String id = obj.get("_id").toString(); String name = null; if (obj.containsField("name")) name = obj.get("name").toString(); String instType = null; if (obj.containsField("type")) instType = obj.get("type").toString(); InstallationInfo instInfo = new InstallationInfo(id, name, instType, null); instInfos.add(instInfo); DBCursor cursor2 = DBConn.getConn().getCollection("inst_results").find(new BasicDBObject("inst_id", id)) .sort(new BasicDBObject("tick", 1)); List<DBObject> res = cursor2.toArray(); cursor2.close(); double[] data1Inst = new double[res.size()]; for (int j = 0; j < Math.min(insts.size(), limit); j++) { data1Inst[j] = Double.parseDouble(res.get(j).get("p").toString()); } dataForKL[i] = data1Inst; } double[][] results = ConsumptionDetector.estimateKLD(dataForKL); for (int i = 0; i < instInfos.size(); i++) { instInfos.get(i).setKlValuesWithOtherInsts(results[i]); } installations.put("ALL", instInfos); return installations; }
From source file:FloodPrototype.FloodProvider.java
License:Apache License
@Override public List<DBObject> fetch(User user, Date maxTimestamp, int limit) { List<DBObject> list = new ArrayList<DBObject>(); BasicDBObject query = new BasicDBObject("user", user.objId); query.append("timestamp", new BasicDBObject("$lte", maxTimestamp)); DBCursor cursor = db.getCollection("floodsims").find(query).sort(new BasicDBObject("timestamp", -1)) .limit(limit);/* ww w .j a va 2s . c o m*/ list = cursor.toArray(); return list; }
From source file:generate.ShowArticlesAction.java
public String execute() throws ClassNotFoundException, SQLException, IOException { List<DBObject> documents = new ArrayList<>(); System.out.println("Mark 0"); try {/*w w w . j a v a2s . c o m*/ MongoClient mongo = new MongoClient(); DB db = mongo.getDB("Major"); DBCollection collection = db.getCollection("ConceptMap"); DBCursor cursor = collection.find(); documents = cursor.toArray(); cursor.close(); } catch (MongoException e) { System.out.println("ERRRRRORRR: " + e.getMessage()); return ERROR; } catch (UnknownHostException ex) { Logger.getLogger(MapGenerateAction.class.getName()).log(Level.SEVERE, null, ex); } System.out.println("Mark 1"); Map<String, ArrayList<String>> chap_to_section = new HashMap<>(); Map<String, String> id_to_section = new HashMap<>(); for (DBObject document : documents) { String c_name = document.get("ChapterName").toString(); boolean has_key = chap_to_section.containsKey(c_name); ArrayList<String> sections = new ArrayList<>(); sections.add(document.get("SectionName").toString()); if (has_key) { sections.addAll(chap_to_section.get(c_name)); chap_to_section.put(c_name, sections); } else { chap_to_section.put(c_name, sections); } id_to_section.put(document.get("SectionName").toString(), document.get("UniqueID").toString()); } FileWriter file = null; try { file = new FileWriter("/home/chanakya/NetBeansProjects/Concepto/web/Chapters_Sections.json"); } catch (IOException ex) { Logger.getLogger(ShowArticlesAction.class.getName()).log(Level.SEVERE, null, ex); } JSONArray jarr = new JSONArray(); for (String key : chap_to_section.keySet()) { JSONObject jobj = new JSONObject(); JSONArray arr = new JSONArray(); for (String val : chap_to_section.get(key)) { JSONObject temp = new JSONObject(); temp.put("name", val); temp.put("id", id_to_section.get(val).toString()); arr.add(temp); } jobj.put("sname", arr); jobj.put("cname", key); jarr.add(jobj); } System.out.println("Mark 2"); //JSONObject obj = new JSONObject(); //obj.put("cmap", jarr); file.write(jarr.toJSONString()); file.flush(); file.close(); System.out.println("Mark 3"); return SUCCESS; }
From source file:GeoHazardServices.Inst.java
License:Apache License
@POST @Path("/fetch") @Produces(MediaType.APPLICATION_JSON)/*from www .j a va 2 s. c o m*/ public String fetch(@Context HttpServletRequest request, @FormParam("limit") @DefaultValue("0") int limit, @FormParam("delay") @DefaultValue("0") int delay, @FormParam("undersea") @DefaultValue("false") boolean undersea, @CookieParam("server_cookie") String session) { /* check session key and find out if the request comes from an authorized user */ User user = signedIn(session); /* returns null if user is not logged in */ /* create lists for general and user specific earthquake entries */ ArrayList<DBObject> mlist = new ArrayList<DBObject>(); ArrayList<DBObject> ulist = new ArrayList<DBObject>(); /* we want all entries since the beginning of time */ Date maxTimestamp = new Date(); /* used to convert to desired time format used by MongoDB */ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); /* select collection which contain the earthquake entries */ DBCollection coll = db.getCollection("eqs"); //ArrayList<User> users = new ArrayList<User>( institutions.values() ); ArrayList<User> users = new ArrayList<User>(); users.add(user); if (user != null) { if (user.inst != null) { users.add(institutions.get(user.inst)); } else { users.add(institutions.get("gfz")); } DBCursor csr = db.getCollection("users").find( new BasicDBObject("username", user.name).append("provider", new BasicDBObject("$ne", null))); if (csr.hasNext()) { for (Object p : (BasicDBList) csr.next().get("provider")) { DBObject inst = db.getCollection("institutions").findOne(new BasicDBObject("_id", p)); if (inst != null) users.add(institutions.get(inst.get("name"))); } } } /* return only entries that are older than 'delay' minutes */ Date upperTimeLimit = new Date(System.currentTimeMillis() - delay * 60 * 1000); /* get earthquakes for each of the given users */ for (User curUser : users) { if (curUser == null) continue; /* create DB query */ BasicDBObject inQuery = new BasicDBObject("user", curUser.objId); if (undersea) inQuery.append("prop.sea_area", new BasicDBObject("$ne", null)); if (delay > 0) inQuery.append("prop.date", new BasicDBObject("$lt", upperTimeLimit)); inQuery.append("depr", new BasicDBObject("$ne", true)); inQuery.append("evtset", null); /* query DB, sort the results by date and limit the number of returned entries */ DBCursor cursor = coll.find(inQuery).sort(new BasicDBObject("prop.date", -1)); if (limit > 0) cursor = cursor.limit(limit); /* walk through the returned entries */ for (DBObject obj : cursor) { obj.removeField("image"); /* check if entry belongs to general or user specific list */ if (user != null && obj.get("user").equals(user.objId)) { ulist.add(obj); } else { mlist.add(obj); } /* update timestamp */ Date timestamp = (Date) obj.get("timestamp"); if (timestamp.after(maxTimestamp)) { maxTimestamp = timestamp; } } /* clean up query */ cursor.close(); } /* create new JSON object that can be used directly within JavaScript */ JsonObject jsonObj = new JsonObject(); jsonObj.add("main", gson.toJsonTree(mlist)); jsonObj.add("user", gson.toJsonTree(ulist)); if (user != null) { List<DBObject> msglist = msg(limit, user); if (!msglist.isEmpty()) { Date timestamp = (Date) msglist.get(0).get("CreatedTime"); if (timestamp.after(maxTimestamp)) { maxTimestamp = timestamp; } } jsonObj.add("msg", gson.toJsonTree(msglist)); } else { jsonObj.add("msg", gson.toJsonTree(new ArrayList<DBObject>())); } List<DBObject> evtsets = new ArrayList<DBObject>(); if (user != null) { BasicDBObject query = new BasicDBObject("user", user.objId); query.append("timestamp", new BasicDBObject("$lte", maxTimestamp)); DBCursor cursor = db.getCollection("evtsets").find(query).sort(new BasicDBObject("timestamp", -1)) .limit(100); evtsets = cursor.toArray(); } jsonObj.add("evtsets", gson.toJsonTree(evtsets)); /* TODO */ if (user != null) { for (Map.Entry<String, IDataProvider> entry : providers.entrySet()) { List<DBObject> list = entry.getValue().fetch(user, maxTimestamp, limit); jsonObj.add(entry.getKey(), gson.toJsonTree(list)); } } jsonObj.addProperty("ts", sdf.format(maxTimestamp)); return jsonObj.toString(); }
From source file:GeoHazardServices.Inst.java
License:Apache License
@POST @Path("/search") @Produces(MediaType.APPLICATION_JSON)/*from w w w. j a va2 s . co m*/ public String search(@Context HttpServletRequest request, @FormParam("text") String text, @CookieParam("server_cookie") String session) { /* check session key and find out if the request comes from an authorized user */ User user = signedIn(session); /* create list of DB objects that contains all desired users */ BasicDBList users = new BasicDBList(); for (User curUser : institutions.values()) users.add(new BasicDBObject("user", curUser.objId)); if (user != null) users.add(new BasicDBObject("user", user.objId)); DBCollection coll = db.getCollection("eqs"); DBCollection msgColl = db.getCollection("messages_sent"); DBCollection recvColl = db.getCollection("messages_received"); DBCollection evtsetColl = db.getCollection("evtsets"); List<DBObject> refinements = coll.find(new BasicDBObject("id", text)).toArray(); BasicDBList list = new BasicDBList(); list.add(new BasicDBObject("_id", text)); list.add(new BasicDBObject("id", text)); list.add(new BasicDBObject("root", text)); list.add(new BasicDBObject("parent", text)); for (DBObject obj : refinements) { String compId = (String) obj.get("_id"); list.add(new BasicDBObject("root", compId)); list.add(new BasicDBObject("parent", compId)); } BasicDBList and = new BasicDBList(); and.add(new BasicDBObject("$or", list)); and.add(new BasicDBObject("$or", users)); BasicDBObject inQuery = new BasicDBObject("$and", and); BasicDBObject sort = new BasicDBObject("timestamp", -1); sort.put("prop.date", -1); DBCursor cursor = coll.find(inQuery).sort(sort); List<DBObject> results = new ArrayList<DBObject>(); results.addAll(cursor.toArray()); cursor.close(); /* TODO: generalize field names */ list = new BasicDBList(); list.add(new BasicDBObject("EventID", text)); list.add(new BasicDBObject("ParentId", text)); for (DBObject obj : refinements) { String compId = (String) obj.get("_id"); list.add(new BasicDBObject("EventID", compId)); list.add(new BasicDBObject("ParentId", compId)); } and = new BasicDBList(); and.add(new BasicDBObject("$or", list)); and.add(new BasicDBObject("SenderID", user.objId)); inQuery = new BasicDBObject("$and", and); cursor = msgColl.find(inQuery).sort(new BasicDBObject("CreatedTime", -1)); for (DBObject obj : cursor) { obj.put("kind", "msg"); obj.put("Dir", "out"); results.add(obj); } cursor.close(); and = new BasicDBList(); and.add(new BasicDBObject("$or", list)); and.add(new BasicDBObject("ReceiverID", user.objId)); inQuery = new BasicDBObject("$and", and); cursor = recvColl.find(inQuery).sort(new BasicDBObject("CreatedTime", -1)); for (DBObject obj : cursor) { obj.put("kind", "msg"); obj.put("Dir", "in"); results.add(obj); } cursor.close(); DBObject evtset = evtsetColl.findOne(new BasicDBObject("_id", text)); if (evtset != null) { List<DBObject> evts = coll.find(new BasicDBObject("id", new BasicDBObject("$in", evtset.get("evtids")))) .toArray(); results.addAll(evts); } /* returning only cursor.toArray().toString() makes problems with the date fields */ return gson.toJsonTree(results).toString(); }
From source file:GeoHazardServices.Inst.java
License:Apache License
private List<DBObject> msg(int limit, User user) { if (user == null) return null; DBCollection coll = db.getCollection("messages_sent"); BasicDBObject inQuery = new BasicDBObject("SenderID", user.objId); /* query DB, sort the results by date and limit the number of returned entries */ DBCursor cursor = coll.find(inQuery).sort(new BasicDBObject("CreatedTime", -1)); if (limit > 0) cursor = cursor.limit(limit);/* w ww . j a va 2 s . co m*/ List<DBObject> result = cursor.toArray(); cursor.close(); inQuery = new BasicDBObject("ReceiverID", user.objId); coll = db.getCollection("messages_received"); cursor = coll.find(inQuery).sort(new BasicDBObject("CreatedTime", -1)); if (limit > 0) cursor = cursor.limit(limit); for (DBObject obj : cursor) { DBCursor csrUser = db.getCollection("users").find(new BasicDBObject("_id", obj.get("SenderID"))); if (csrUser.hasNext()) obj.put("From", (String) csrUser.next().get("username")); obj.put("To", new String[] { user.name }); obj.put("Dir", "in"); result.add(obj); } cursor.close(); Collections.sort(result, new DateComparator("CreatedTime", -1)); /* add parent event as sub-object because we want to show it on click */ for (DBObject msg : result) { DBCursor csr = db.getCollection("eqs").find(new BasicDBObject("_id", msg.get("ParentId"))); if (csr.hasNext()) { DBObject obj = csr.next(); obj.removeField("image"); msg.put("parentEvt", obj); } } return result; }
From source file:GeoHazardServices.Inst.java
License:Apache License
@POST @Path("/getCFCZ") @Produces(MediaType.APPLICATION_JSON)//from w w w .j av a2 s.c o m public String getCFCZ() { DBCollection coll = db.getCollection("cfcz"); DBCursor cursor = coll.find(); return cursor.toArray().toString(); }
From source file:gov.llnl.iscr.iris.LDAHandler.java
License:Open Source License
/** * sets the threshold value to be used for filtering "junk" topics * to a value obtained by thresholding the topic semantic coherence scores * at the percentile value given./*from ww w .j a v a 2s . c o m*/ * @param thresholdPercentile * @return */ public LDAHandler setTopicThreshold(float thresholdPercentile) { DBCursor semcoCur = model.getSemcoValues(); int semcoCount = semcoCur.count(); int limit = (int) (thresholdPercentile * semcoCount) - 1; this.topicThreshold = (Double) semcoCur.toArray().get(limit).get("semco"); return this; }
From source file:gov.llnl.iscr.iris.LDAHandler.java
License:Open Source License
/** * sets the list of topics that are related to the enriched topic list; * call {@link LDAHandler#getRelatedTopicSet()} on the returned * LDAHandler to retrieve the list.// w ww . j a v a 2 s . com * @return */ public LDAHandler setRelatedTopicSet() { relatedSet = new ArrayList<Integer>(); if (enrichedSet != null) { List<DBCursor> curList = model.getRelatedTopics(enrichedSet); for (DBCursor cur : curList) { List<Integer> temp = filterTopics(cur.toArray(), topicThreshold, TopicType.RELATED); relatedSet.add(temp.get(0)); relatedSet.add(temp.get(1)); } } else { System.err.println("Related Topics Set cannot be populated!"); System.err.println("Ensure enriched topic set has been established."); } return this; }