List of usage examples for com.mongodb DBCursor close
@Override public void close()
From source file:GeoHazardServices.Inst.java
License:Apache License
@POST @Path("/fetch") @Produces(MediaType.APPLICATION_JSON)/* w ww.j a va 2 s.c om*/ 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("/update") @Produces(MediaType.APPLICATION_JSON)//ww w. j a v a 2 s.co m public String update(@Context HttpServletRequest request, @FormParam("ts") String ts, @FormParam("delay") @DefaultValue("0") int delay, @CookieParam("server_cookie") String session) { /* check session key and find out if the request comes from an authorized user */ User user = signedIn(session); /* create lists for general and user specific earthquake entries */ ArrayList<DBObject> mlist = new ArrayList<DBObject>(); ArrayList<DBObject> ulist = new ArrayList<DBObject>(); ArrayList<DBObject> evtsets = new ArrayList<DBObject>(); /* 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")); /* convert timestamp from String to Date; return on error */ Date timestamp; try { timestamp = sdf.parse(ts); } catch (ParseException e) { e.printStackTrace(); return null; } /* select collection which contain the events */ DBCollection coll = db.getCollection("events"); /* 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)); if (user.inst != null) { users.add(new BasicDBObject("user", institutions.get(user.inst).objId)); } else { users.add(new BasicDBObject("user", institutions.get("gfz").objId)); } 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")) { users.add(new BasicDBObject("user", p)); } } } /* return only entries that are older than 'delay' minutes */ Date upperTimeLimit = new Date(System.currentTimeMillis() - delay * 60 * 1000); /* create DB query - search for newer events related to the general list or the user */ BasicDBList time = new BasicDBList(); time.add(new BasicDBObject("timestamp", new BasicDBObject("$gt", timestamp))); BasicDBObject inQuery = new BasicDBObject("$and", time); inQuery.put("$or", users); boolean first = true; Map<String, List<DBObject>> lists = new HashMap<String, List<DBObject>>(); for (Map.Entry<String, IDataProvider> entry : providers.entrySet()) { lists.put(entry.getKey(), new ArrayList<DBObject>()); } /* walk through the returned entries */ if (user != null) { /* query DB, sort the results by timestamp */ DBCursor cursor = coll.find(inQuery).sort(new BasicDBObject("timestamp", -1)); for (DBObject obj : cursor) { if (first) { timestamp = (Date) obj.get("timestamp"); first = false; } /* get corresponding entry from earthquake collection */ String id = (String) obj.get("id"); BasicDBObject objQuery = new BasicDBObject(); objQuery.put("olduser", new BasicDBObject("$exists", false)); if (delay > 0) objQuery.put("prop.date", new BasicDBObject("$lt", upperTimeLimit)); DBObject obj2 = null; if (obj.get("event").equals("msg_sent")) { objQuery.put("Message-ID", id); obj2 = db.getCollection("messages_sent").findOne(objQuery); } else if (obj.get("event").equals("msg_recv")) { objQuery.put("Message-ID", id); obj2 = db.getCollection("messages_received").findOne(objQuery); } else if (obj.get("event").equals("new_evtset")) { objQuery.put("_id", id); obj2 = db.getCollection("evtsets").findOne(objQuery); } else { objQuery.put("_id", id); obj2 = db.getCollection("eqs").findOne(objQuery); if (obj2 == null) obj2 = db.getCollection("evtsets").findOne(objQuery); } for (Map.Entry<String, IDataProvider> entry : providers.entrySet()) { entry.getValue().add(lists.get(entry.getKey()), obj); } /* */ if (obj2 != null) { /* add event type to entry */ String event = (String) obj.get("event"); obj2.put("event", event); if (obj.get("event").equals("msg_recv")) { obj2.put("Dir", "in"); obj2.put("To", new String[] { user.name }); DBCursor csrUser = db.getCollection("users") .find(new BasicDBObject("_id", obj2.get("SenderID"))); if (csrUser.hasNext()) obj2.put("From", (String) csrUser.next().get("username")); DBCursor csrParent = db.getCollection("eqs") .find(new BasicDBObject("_id", obj2.get("ParentId"))); if (csrParent.hasNext()) obj2.put("parentEvt", csrParent.next()); } if (event.equals("new_evtset")) { evtsets.add(obj2); } else { /* check if entry belongs to general or user specific list */ if (user != null && obj.get("user").equals(user.objId)) { ulist.add(obj2); } else { mlist.add(obj2); } } /* update timestamp */ /* TODO: this is just a temporary solution, because progress events could be delivered multiple times */ if (delay <= 0 || event.equals("new")) { if (first) { timestamp = (Date) obj.get("timestamp"); first = false; } } } } /* clean up query */ cursor.close(); } /* create new JSON object that can be used directly within JavaScript */ JsonObject jsonObj = new JsonObject(); jsonObj.addProperty("serverTime", sdf.format(new Date())); jsonObj.addProperty("ts", sdf.format(timestamp)); jsonObj.add("main", gson.toJsonTree(mlist)); jsonObj.add("user", gson.toJsonTree(ulist)); jsonObj.add("evtsets", gson.toJsonTree(evtsets)); for (Map.Entry<String, IDataProvider> entry : providers.entrySet()) { jsonObj.add(entry.getKey(), gson.toJsonTree(lists.get(entry.getKey()))); } return jsonObj.toString(); }
From source file:GeoHazardServices.Inst.java
License:Apache License
@POST @Path("/search") @Produces(MediaType.APPLICATION_JSON)//from w ww . j a v a2 s . c o 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
@POST @Path("/getShared") @Produces(MediaType.APPLICATION_JSON)/* w w w . jav a 2s .c o m*/ public String getShared(@Context HttpServletRequest request, @FormParam("lnkid") String lnkId, @CookieParam("server_cookie") String session) { Object[] required = { lnkId }; if (!checkParams(request, required)) return jsfailure(); ObjectId objId; try { objId = new ObjectId(lnkId); } catch (IllegalArgumentException e) { return jsfailure(); } DBCollection coll = db.getCollection("shared_links"); BasicDBObject inQuery = new BasicDBObject("_id", objId); DBCursor cursor = coll.find(inQuery); if (!cursor.hasNext()) return jsfailure(); DBObject lnkObj = cursor.next(); Object evtId = lnkObj.get("evtid"); /* store meta data */ User user = signedIn(session); Object userId = null; if (user != null) userId = user.objId; DBObject access = new BasicDBObject("timestamp", new Date()); access.put("user", userId); access.put("ip", getIP(request)); DBObject elem = new BasicDBObject("access", access); DBObject update = new BasicDBObject("$push", elem); db.getCollection("shared_links").findAndModify(inQuery, update); cursor.close(); BasicDBObject event = new BasicDBObject("_id", evtId); cursor = db.getCollection("eqs").find(event); if (!cursor.hasNext()) return jsfailure(); /* needed to preserve the expected date format for JavaScript */ /* TODO: dates are really difficult to parse between different languages * --> we need some consistent way to handle these problems */ JsonObject json = new JsonObject(); json.add("pos", gson.toJsonTree(lnkObj)); json.add("eq", gson.toJsonTree(cursor.next())); cursor.close(); return jssuccess(json); }
From source file:GeoHazardServices.Inst.java
License:Apache License
@POST @Path("/copyToUser") @Produces(MediaType.APPLICATION_JSON)//from w ww . j ava2 s.c o m public String copyToUser(@Context HttpServletRequest request, @FormParam("srcId") String srcId, @CookieParam("server_cookie") String session) { Object[] required = { srcId }; if (!checkParams(request, required)) return jsfailure(); User user = signedIn(session); if (user == null) return jsdenied(); /* do not copy the event again if there is already one copy for that user */ BasicDBObject inQuery = new BasicDBObject("copied", srcId); inQuery.put("user", user.objId); DBCursor cursor = db.getCollection("eqs").find(inQuery); if (cursor.hasNext()) { cursor.close(); return jssuccess(new BasicDBObject("msg", "Copy already exists.")); } cursor.close(); inQuery = new BasicDBObject("_id", srcId); cursor = db.getCollection("eqs").find(inQuery); if (!cursor.hasNext()) return jsfailure(); DBObject obj = cursor.next(); cursor.close(); String id = newRandomId(user.name); obj.put("user", user.objId); obj.put("_id", id); obj.put("id", id); obj.put("timestamp", new Date()); obj.put("copied", srcId); db.getCollection("eqs").insert(obj); /* copy computation results */ cursor = db.getCollection("comp").find(new BasicDBObject("EventID", srcId)); for (DBObject res : cursor) { res.put("EventID", id); res.removeField("_id"); db.getCollection("comp").insert(res); } cursor.close(); return jssuccess(new BasicDBObject("msg", "Event successfully copied.")); }
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 w w . ja va 2 s .c om*/ 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:gov.wa.wsdot.cms.templates.ProjectTemplate.java
License:Open Source License
@Override public ChannelsAndPostingsBase build(ChannelsAndPostingsBase item, HashMap<String, String> controlsMap, HashMap<String, String> genericPropertiesMap) { StringBuilder leftNav = new StringBuilder(); StringBuilder update = new StringBuilder(); StringBuilder pageContent = new StringBuilder(); StringBuilder contact = new StringBuilder(); StringBuilder map = new StringBuilder(); List<String> fundingList = new ArrayList<String>(); MongoClient mongo = null;/*from w ww . jav a 2 s. c om*/ try { mongo = new MongoClient("localhost"); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } DB db = mongo.getDB("projects"); DBCollection projectsCollection = db.getCollection("posts"); BasicDBObject query = new BasicDBObject("Link", "/" + item.getLocation().replace(">>", "/") + "/"); DBCursor cursor = projectsCollection.find(query); try { while (cursor.hasNext()) { DBObject dbObject = cursor.next(); item.setProjectId(dbObject.get("ID").toString()); item.setCounties(dbObject.get("County").toString()); item.setRegions(dbObject.get("Region").toString()); item.setHighways(getHighwayTaxonomy(dbObject.get("Highway").toString())); if (!dbObject.get("Nickel").toString().equalsIgnoreCase("0")) { fundingList.add("Nickel"); } else if (!dbObject.get("Partner").toString().equalsIgnoreCase("0")) { fundingList.add("TPA"); } else if (!dbObject.get("FedStim").toString().equalsIgnoreCase("0")) { fundingList.add("ARRA"); } } String[] fundingArray = fundingList.toArray(new String[fundingList.size()]); item.setFunding(Arrays.toString(fundingArray).replace("[", "").replace("]", "").replace(",", ";")); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { cursor.close(); mongo.close(); } // This can be concatenated into the leftNav field leftNav.append(""); if (controlsMap.get("LeftNav") != null) { leftNav.append(controlsMap.get("LeftNav")); } if (controlsMap.get("LeftNavPlaceholderDefinition2") != null) { leftNav.append(controlsMap.get("LeftNavPlaceholderDefinition2")); } item.setLeftNav(leftNav.toString()); // All this can be concatenated into the projectUpdate field update.append("<p>"); update.append("<strong>" + controlsMap.get("ProjectUpdateDate") + "</strong>"); update.append("</p>"); update.append(controlsMap.get("ProjectUpdate")); item.setUpdate(update.toString()); // All this can be concatenated into the pageContent field if (controlsMap.get("OverviewDefinition") != null) { pageContent.append("<p>"); pageContent.append(controlsMap.get("OverviewDefinition")); pageContent.append("</p>"); } if (controlsMap.get("What") != null) { pageContent.append("<p>"); pageContent.append("<strong>Why is WSDOT " + controlsMap.get("What") + "</strong>"); pageContent.append("<br />"); pageContent.append(controlsMap.get("Why")); pageContent.append("</p>"); } if (controlsMap.get("EndResult") != null) { pageContent.append("<p>"); pageContent.append("<strong>The End Result</strong>"); pageContent.append("<br />"); pageContent.append(controlsMap.get("EndResult")); pageContent.append("</p>"); } if (controlsMap.get("ProjectBenefits") != null) { pageContent.append("<p>"); pageContent.append("<strong>Project Benefits</strong>"); pageContent.append("<br />"); pageContent.append(controlsMap.get("ProjectBenefits")); pageContent.append("</p>"); } if (controlsMap.get("ProjectTimelines") != null) { pageContent.append("<p>"); pageContent.append("<strong>What is the project timeline?</strong>"); pageContent.append("<br />"); pageContent.append(controlsMap.get("ProjectTimelines")); pageContent.append("</p>"); } if (controlsMap.get("Financial") != null) { pageContent.append("<p>"); pageContent.append("<strong>Financial Information</strong>"); pageContent.append("<br />"); pageContent.append(controlsMap.get("Financial")); pageContent.append("</p>"); } item.setPageContent(pageContent.toString()); // This will be separate and go into contact field if (controlsMap.get("Contact") != null) { contact.append("<p>"); contact.append("<strong>How can I get more information?<br />Contact:</strong><br />"); contact.append(controlsMap.get("Contact")); contact.append("</p>"); } item.setContact(contact.toString()); item.setPhase(getProjectPhaseTaxonomy(controlsMap.get("PhaseImage"))); // This can be concatenated into the projectMap field if (controlsMap.get("MapPlaceholder") != null) { map.append(controlsMap.get("MapPlaceholder")); } // FlickrLightbox <- Ignore for now // This appears under Map -> [Flickr Photos] -> RightPlaceHolder if (controlsMap.get("RightPlaceHolder") != null) { map.append(controlsMap.get("RightPlaceHolder")); } item.setLegacyMap(map.toString()); // Process GenericProperties item.setShowSignageDisclaimer(genericPropertiesMap.get("ShowCostEscalation")); item.setShowFinancialTable(genericPropertiesMap.get("ShowFinancialTable")); item.setShowMonthlyUpdateLeftNav(genericPropertiesMap.get("ShowMonthlyUpdateLeftNav")); item.setShowFlickrLightbox(genericPropertiesMap.get("ShowFlickrLightbox")); try { Pattern pattern = Pattern.compile("([\\d+]{10,})"); Matcher matcher = pattern.matcher(genericPropertiesMap.get("FlickrFeedURL")); if (matcher.find()) { item.setFlickrAlbumId(matcher.group(1)); } } catch (NullPointerException e) { } return item; }
From source file:guardar.en.base.de.datos.MainServidor.java
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, ClassNotFoundException { Mongo mongo = new Mongo("localhost", 27017); // nombre de la base de datos DB database = mongo.getDB("paginas"); // coleccion de la db DBCollection collection = database.getCollection("indice"); DBCollection collection_textos = database.getCollection("tabla"); ArrayList<String> lista_textos = new ArrayList(); try {//from w w w . ja v a2 s. c o m ServerSocket servidor = new ServerSocket(4545); // Crear un servidor en pausa hasta que un cliente llegue. while (true) { String aux = new String(); lista_textos.clear(); Socket clienteNuevo = servidor.accept();// Si llega se acepta. // Queda en pausa otra vez hasta que un objeto llegue. ObjectInputStream entrada = new ObjectInputStream(clienteNuevo.getInputStream()); JSONObject request = (JSONObject) entrada.readObject(); String b = (String) request.get("id"); //hacer una query a la base de datos con la palabra que se quiere obtener BasicDBObject query = new BasicDBObject("palabra", b); DBCursor cursor = collection.find(query); ArrayList<DocumentosDB> lista_doc = new ArrayList<>(); // de la query tomo el campo documentos y los agrego a una lista try { while (cursor.hasNext()) { //System.out.println(cursor.next()); BasicDBList campo_documentos = (BasicDBList) cursor.next().get("documentos"); // en el for voy tomando uno por uno los elementos en el campo documentos for (Iterator<Object> it = campo_documentos.iterator(); it.hasNext();) { BasicDBObject dbo = (BasicDBObject) it.next(); //DOC tiene id y frecuencia DocumentosDB doc = new DocumentosDB(); doc.makefn2(dbo); //int id = (int)doc.getId_documento(); //int f = (int)doc.getFrecuencia(); lista_doc.add(doc); //******************************************* //******************************************** //QUERY A LA COLECCION DE TEXTOS /* BasicDBObject query_textos = new BasicDBObject("id", doc.getId_documento());//query DBCursor cursor_textos = collection_textos.find(query_textos); try { while (cursor_textos.hasNext()) { DBObject obj = cursor_textos.next(); String titulo = (String) obj.get("titulo"); titulo = titulo + "\n\n"; String texto = (String) obj.get("texto"); String texto_final = titulo + texto; aux = texto_final; lista_textos.add(texto_final); } } finally { cursor_textos.close(); }*/ //System.out.println(doc.getId_documento()); //System.out.println(doc.getFrecuencia()); } // end for } //end while query } finally { cursor.close(); } // ordeno la lista de menor a mayor Collections.sort(lista_doc, new Comparator<DocumentosDB>() { @Override public int compare(DocumentosDB o1, DocumentosDB o2) { //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. return o1.getFrecuencia().compareTo(o2.getFrecuencia()); } }); int tam = lista_doc.size() - 1; for (int j = tam; j >= 0; j--) { BasicDBObject query_textos = new BasicDBObject("id", (int) lista_doc.get(j).getId_documento().intValue());//query DBCursor cursor_textos = collection_textos.find(query_textos);// lo busco try { while (cursor_textos.hasNext()) { DBObject obj = cursor_textos.next(); String titulo = "*******************************"; titulo += (String) obj.get("titulo"); int f = (int) lista_doc.get(j).getFrecuencia().intValue(); String strinf = Integer.toString(f); titulo += "******************************* frecuencia:" + strinf; titulo = titulo + "\n\n"; String texto = (String) obj.get("texto"); String texto_final = titulo + texto + "\n\n"; aux = aux + texto_final; //lista_textos.add(texto_final); } } finally { cursor_textos.close(); } } //actualizar el cache try { Socket cliente_cache = new Socket("localhost", 4500); // nos conectamos con el servidor ObjectOutputStream mensaje_cache = new ObjectOutputStream(cliente_cache.getOutputStream()); // get al output del servidor, que es cliente : socket del cliente q se conecto al server JSONObject actualizacion_cache = new JSONObject(); actualizacion_cache.put("actualizacion", 1); actualizacion_cache.put("busqueda", b); actualizacion_cache.put("respuesta", aux); mensaje_cache.writeObject(actualizacion_cache); // envio el msj al servidor } catch (Exception ex) { } //RESPONDER DESDE EL SERVIDORIndex al FRONT ObjectOutputStream resp = new ObjectOutputStream(clienteNuevo.getOutputStream());// obtengo el output del cliente para mandarle un msj resp.writeObject(aux); System.out.println("msj enviado desde el servidor"); } } catch (IOException ex) { Logger.getLogger(MainServidor.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:guesslocation.MongoQuery.java
public static void main(String[] args) { {// www . j av a 2 s . com try { // Connect to mongodb MongoClient mongo = new MongoClient("localhost", 27017); // get database // if database doesn't exists, mongodb will create it for you DB db = mongo.getDB("test"); // get collection // if collection doesn't exists, mongodb will create it for you DBCollection collection = db.getCollection("twitter"); DBCollection Outcollection = db.getCollection("user_tw"); DBCursor cursor; BasicDBObject query; //------------------------------------ // ( 1 ) collection.find() --> get all document cursor = collection.find(); System.out.println("( 1 ) .find()"); System.out.println("results --> " + cursor.count()); try { BasicDBObject IDquery = new BasicDBObject(); //2015-05-12T15:15:31Z while (cursor.hasNext()) { DBObject data = cursor.next(); Long v_user_Id = (Long) data.get("user_Id"); if (v_user_Id == null) { continue; } IDquery.append("user_Id", v_user_Id); DBCursor IDcursor = Outcollection.find(IDquery); if (IDcursor.hasNext() == false) { BasicDBObject basicObj = GetUserRecord(v_user_Id, data); try { Outcollection.insert(basicObj); } catch (Exception e) { System.err.println("error on insert " + v_user_Id); } basicObj = null; Thread.sleep(100); Outcollection.ensureIndex(new BasicDBObject("user_Id", 1), new BasicDBObject("unique", true)); } IDcursor.close(); IDquery.clear(); } } catch (InterruptedException ex) { Logger.getLogger(MongoQuery.class.getName()).log(Level.SEVERE, null, ex); } finally { cursor.close(); } System.out.println("---------------------------------"); System.exit(0); } catch (UnknownHostException ex) { Logger.getLogger(MongoQuery.class.getName()).log(Level.SEVERE, null, ex); } } }
From source file:homework.week2.course.UserDAO.java
License:Apache License
public DBObject validateLogin(String username, String password) { DBObject user = null;/*from www . ja v a 2 s.co m*/ // XXX look in the user collection for a user that has this username // assign the result to the user variable. QueryBuilder userQuery = QueryBuilder.start("_id").is(username); DBCursor cursor = usersCollection.find(userQuery.get()); user = cursor.hasNext() ? cursor.next() : null; cursor.close(); if (user == null) { System.out.println("User not in database"); return null; } String hashedAndSalted = user.get("password").toString(); String salt = hashedAndSalted.split(",")[1]; if (!hashedAndSalted.equals(makePasswordHash(password, salt))) { System.out.println("Submitted password is not a match"); return null; } return user; }