/app/Persistence/MongoBase.java
Java | 2565 lines | 2128 code | 251 blank | 186 comment | 237 complexity | 85176080efdb52734f551e8bb2edf715 MD5 | raw file
- package Persistence;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.IOException;
- import java.net.UnknownHostException;
- import java.rmi.activation.ActivationSystem;
- import java.util.*;
- import java.util.regex.Pattern;
- import com.fasterxml.jackson.databind.JsonNode;
- import com.google.code.geocoder.Geocoder;
- import com.google.code.geocoder.GeocoderRequestBuilder;
- import com.google.code.geocoder.model.GeocodeResponse;
- import com.google.code.geocoder.model.GeocoderRequest;
- import com.google.code.geocoder.model.LatLng;
- import com.google.gson.Gson;
- import com.mongodb.*;
- import com.mongodb.util.JSON;
- import com.typesafe.config.Config;
- import controllers.Application;
- import models.*;
- import models.Notifications.AddedToFavourites;
- import models.Notifications.Following;
- import models.Notifications.Notification;
- import models.Notifications.Publication;
- import org.apache.commons.lang3.StringUtils;
- import org.apache.commons.lang3.text.WordUtils;
- import org.apache.poi.hssf.usermodel.HSSFSheet;
- import org.apache.poi.hssf.usermodel.HSSFWorkbook;
- import org.apache.poi.ss.usermodel.Row;
- import org.bson.types.ObjectId;
- import org.springframework.core.task.AsyncTaskExecutor;
- import play.Configuration;
- import play.Logger;
- import Utils.Cripto;
- import Utils.RandomString;
- import java.text.SimpleDateFormat;
- import java.text.DateFormat;
- import net.proinf.gramatica.*;
- import play.Play;
- import play.libs.WS;
- import play.mvc.Result;
- import play.libs.F;
- import com.typesafe.config.ConfigFactory;
- public class MongoBase {
- final static int MAXRESULTS = 100;
- final static int MAXTOPS = 20;
- final static int MAXFEEDS = 20;
- final static double MAXDISTANCE = 0.00078480615;//en kil�metros
- final static ArrayList<String> excepciones = new ArrayList<String>(Arrays.asList("wok", "alioli", "bravioli", "espagueti", "nuggets"));
- static DB actualMB;
- final static Configuration conf= Play.application().configuration();
- static DB connect() {
- if (actualMB != null) {
- return actualMB;
- }
- Mongo mongoClient;
- try {
- mongoClient = new Mongo(conf.getString("mongo.address"),conf.getInt("mongo.port"));
- // mongoClient = new Mongo("dharma.mongohq.com", 10031);
- //mongoClient = new Mongo("localhost" , 27017);
- actualMB = mongoClient.getDB("pitanzas");
- actualMB.authenticate("tista", "teto".toCharArray());
- return actualMB;
- } catch (UnknownHostException e) {
- // TODO Auto-generated catch block
- Logger.error(e.getMessage());
- }
- return null;
- }
- public static boolean checkValidationCode(String code) {
- BasicDBObject query = new BasicDBObject("Code", code);
- DBCollection coll = MongoBase.connect().getCollection("valCodes");
- DBObject retorno = coll.findOne(query);
- if (retorno != null) {
- return true;
- }
- Logger.info("Se ha introducido un código de validación INCORRECTO");
- return false;
- }
- public static boolean checkMail(String mail) {
- BasicDBObject query = new BasicDBObject("mail", mail);
- DBCollection coll = MongoBase.connect().getCollection("users");
- DBObject retorno = coll.findOne(query);
- if (retorno != null) {
- return true;
- }
- return false;
- }
- public static User retrieveUser(String mail) {
- BasicDBObject query = new BasicDBObject("mail", mail);
- DBCollection coll = MongoBase.connect().getCollection("users");
- DBObject retorno = coll.findOne(query);
- if (retorno == null) {
- return null;
- }
- return new User(retorno);
- }
- public static String retrievePassword(String mail) {
- BasicDBObject query = new BasicDBObject("mail", mail);
- DBCollection coll = MongoBase.connect().getCollection("users");
- DBObject retorno = coll.findOne(query);
- if (retorno == null) {
- return null;
- }
- String password = null;
- String encPass = (String) retorno.get("password");
- if (encPass == null || encPass.equalsIgnoreCase("")) {
- return "";
- }
- try {
- password = Cripto.decrypt(encPass, (String) retorno.get("salt"));
- } catch (Exception e) {
- Logger.error(e.getMessage());
- return null;
- }
- Logger.info("Se ha recuperado el password de: " + mail);
- return password;
- }
- public static String retrieveClientPassword(String mail) {
- BasicDBObject query = new BasicDBObject("mail", mail);
- DBCollection coll = MongoBase.connect().getCollection("clients");
- DBObject retorno = coll.findOne(query);
- if (retorno == null) {
- return null;
- }
- String password = null;
- String encPass = (String) retorno.get("password");
- if (encPass == null || encPass.equalsIgnoreCase("")) {
- return "";
- }
- try {
- password = Cripto.decrypt(encPass, (String) retorno.get("salt"));
- } catch (Exception e) {
- Logger.error(e.getMessage());
- return null;
- }
- Logger.info("Se ha recuperado el password de: " + mail);
- return password;
- }
- public static String insertUser(User user) {
- String salt = RandomString.getRandomString(10);
- try {
- user.password = Cripto.encrypt(user.password, salt);
- } catch (Exception e) {
- Logger.error(e.getMessage());
- return null;
- }
- Gson gson = new Gson();
- DBObject doc = (DBObject) JSON.parse(gson.toJson(user));
- doc.put("salt", salt);
- doc.put("followers", new String[]{});
- doc.put("favUsers", new String[]{});
- doc.put("favVenues", new String[]{});
- doc.put("favDishes", new String[]{});
- doc.put("favPubs", new String[]{});
- DBCollection coll = MongoBase.connect().getCollection("users");
- WriteResult resultado = coll.insert(doc);
- if (resultado.getError() != null) {
- Logger.error(resultado.getError());
- return null;
- }
- Logger.info("Insertado el usuario " + user.user + ":" + user.mail);
- addNewFeed(new Feed(user));
- return doc.get("_id").toString();
- }
- public static String insertClient(Client client) {
- String salt = RandomString.getRandomString(10);
- try {
- client.setPassword(Cripto.encrypt(client.getPassword(), salt));
- } catch (Exception e) {
- Logger.error(e.getMessage());
- return null;
- }
- Gson gson = new Gson();
- DBObject doc = client.toDBO();
- doc.put("password",client.getPassword());
- doc.put("salt", salt);
- DBCollection coll = MongoBase.connect().getCollection("clients");
- WriteResult resultado = coll.insert(doc);
- if (resultado.getError() != null) {
- Logger.error(resultado.getError());
- return null;
- }
- Logger.info("Insertado el cliente " + client.getMail());
- return doc.get("_id").toString();
- }
- public static User findUserById(String id) {
- DBCollection coll = MongoBase.connect().getCollection("users");
- BasicDBObject q = new BasicDBObject();
- q.put("_id", new ObjectId(id));
- DBObject obj = coll.findOne(q);
- User user = new User(obj);
- return user;
- }
- public static String findUserJSONById(String id) {
- DBCollection coll = MongoBase.connect().getCollection("users");
- BasicDBObject q = new BasicDBObject();
- q.put("_id", new ObjectId(id));
- DBObject obj = coll.findOne(q);
- User user = new User(obj);
- return com.mongodb.util.JSON.serialize(obj);
- }
- public static String findUsersByName(String name) {
- DBCollection coll = MongoBase.connect().getCollection("users");
- BasicDBObject q = new BasicDBObject();
- q.put("user", java.util.regex.Pattern.compile(name,
- Pattern.CASE_INSENSITIVE));
- DBCursor cursor = coll.find(q);
- return "{\"users\":" + com.mongodb.util.JSON.serialize(cursor.toArray(MAXRESULTS)) + "}";
- }
- public static String findUsersById(List<String> ids) {
- DBCollection coll = MongoBase.connect().getCollection("users");
- BasicDBObject q = new BasicDBObject();
- List<ObjectId> oids = new ArrayList<ObjectId>(ids.size());
- for (String id : ids) {
- oids.add(new ObjectId(id));
- }
- q.put("_id", new BasicDBObject("$in", oids));
- DBCursor cursor = coll.find(q);
- return "{\"users\":" + com.mongodb.util.JSON.serialize(cursor.toArray()) + "}";
- }
- public static String findUsersFollowed(String followerId) {
- DBCollection coll = MongoBase.connect().getCollection("users");
- BasicDBObject q = new BasicDBObject();
- q.put("userId", followerId);
- DBObject user = coll.findOne(q);
- ArrayList<Object> al = (ArrayList<Object>) user.get("favUsers");
- ArrayList<String> usersId = new ArrayList<String>(al.size());
- if (al != null) {
- for (Object ob : al) {
- usersId.add(ob.toString());
- }
- }
- q = new BasicDBObject("$in", usersId);
- return "{\"users\":" + com.mongodb.util.JSON.serialize(coll.find(q).toArray()) + "}";
- }
- public static String insertFBUser(User user) {
- Gson gson = new Gson();
- DBObject doc = (DBObject) JSON.parse(gson.toJson(user));
- doc.put("followers", new String[]{});
- doc.put("favUsers", new String[]{});
- doc.put("favVenues", new String[]{});
- doc.put("favDishes", new String[]{});
- doc.put("favPubs", new String[]{});
- DBCollection coll = MongoBase.connect().getCollection("users");
- WriteResult resultado = coll.insert(doc);
- if (resultado.getError() != null) {
- Logger.error(resultado.getError());
- return null;
- }
- Logger.info("Insertado el usuario " + user.user + ":" + user.mail);
- addNewFeed(new Feed(user));
- return doc.get("_id").toString();
- }
- public static boolean loginAdmin(String mail, String password) {
- BasicDBObject query = new BasicDBObject("mail", mail);
- DBCollection coll = MongoBase.connect().getCollection("users");
- DBObject retorno = coll.findOne(query);
- if (retorno == null) {
- Logger.info("Usuario " + mail + " no encontrado");
- return false;
- }
- String admin = (String) retorno.get("admin");
- if (admin == null || admin.equalsIgnoreCase("false")) {
- Logger.info("El usuario " + mail + " no tiene permisos suficientes");
- return false;
- }
- String decPassword = null;
- String encPass = (String) retorno.get("password");
- try {
- decPassword = Cripto.decrypt(encPass, (String) retorno.get("salt"));
- } catch (Exception e) {
- Logger.error(e.getMessage());
- return false;
- }
- if (decPassword.equalsIgnoreCase(password)) {
- Logger.info("Administrador logueado: " + mail);
- return true;
- } else {
- Logger.info("Error en la password para el usuario" + mail);
- }
- Logger.info("Se ha reenviado la password a: " + mail);
- return false;
- }
- public static boolean loginVenue(String mail, String password) {
- BasicDBObject query = new BasicDBObject("mail", mail);
- DBCollection coll = MongoBase.connect().getCollection("clients");
- DBObject retorno = coll.findOne(query);
- if (retorno == null) {
- Logger.info("Usuario " + mail + " no encontrado");
- return false;
- }
- return true;
- /* String decPassword = null;
- String encPass = (String) retorno.get("password");
- try {
- decPassword = Cripto.decrypt(encPass, (String) retorno.get("salt"));
- } catch (Exception e) {
- Logger.error(e.getMessage());
- return false;
- }
- if (decPassword.equalsIgnoreCase(password)) {
- Logger.info("Venue logueada: " + mail);
- return true;
- } else {
- Logger.info("Error en la password para el usuario" + mail);
- }
- return false;*/
- }
- public static User loginUser(String mail, String password) {
- BasicDBObject query = new BasicDBObject("mail", mail);
- DBCollection coll = MongoBase.connect().getCollection("users");
- DBObject retorno = coll.findOne(query);
- if (retorno == null) {
- return null;
- }
- String decPassword = null;
- String encPass = (String) retorno.get("password");
- if (encPass == null || encPass.equalsIgnoreCase("")) {
- return null;
- }
- try {
- decPassword = Cripto.decrypt(encPass, (String) retorno.get("salt"));
- } catch (Exception e) {
- Logger.error(e.getMessage());
- e.printStackTrace();
- return null;
- }
- if (decPassword.equalsIgnoreCase(password)) {
- Logger.info("Usuario logueado: " + mail);
- return new User(retorno);
- }
- return null;
- }
- public static String logUser(String mail, String password) {
- BasicDBObject query = new BasicDBObject("mail", mail);
- DBCollection coll = MongoBase.connect().getCollection("users");
- DBObject retorno = coll.findOne(query);
- if (retorno == null) {
- return null;
- }
- String decPassword = null;
- String encPass = (String) retorno.get("password");
- if (encPass == null || encPass.equalsIgnoreCase("")) {
- return null;
- }
- try {
- decPassword = Cripto.decrypt(encPass, (String) retorno.get("salt"));
- } catch (Exception e) {
- Logger.error(e.getMessage());
- e.printStackTrace();
- return null;
- }
- if (decPassword.equalsIgnoreCase(password)) {
- Logger.info("Usuario logueado: " + mail);
- return com.mongodb.util.JSON.serialize(retorno);
- }
- return null;
- }
- public static String loginFBUser(User user, String userId) {
- BasicDBObject query = new BasicDBObject("mail", user.getMail());
- Logger.debug("loginFB: " + user);
- DBCollection coll = MongoBase.connect().getCollection("users");
- DBObject retorno = coll.findOne(query);
- if (retorno == null) {
- insertFBUser(user);
- retorno = coll.findOne(query);
- if(retorno==null){
- return null;
- }
- return com.mongodb.util.JSON.serialize(retorno);
- }
- if (retorno.containsField("fbid") && retorno.get("fbid").toString().equalsIgnoreCase(userId)) {
- return com.mongodb.util.JSON.serialize(retorno);
- } else {
- BasicDBObject set = new BasicDBObject("$set", user.toFbUpdateDBO());
- WriteResult resultado = coll.update(new BasicDBObject().append("mail", user.getMail()), set);
- Logger.info(resultado.toString());
- if (resultado.getError() != null) {
- Logger.error(resultado.getError());
- return null;
- }
- return com.mongodb.util.JSON.serialize(coll.findOne(query));
- }
- }
- public static boolean consumeValidationCode(String code) {
- BasicDBObject query = new BasicDBObject("Code", code);
- DBCollection coll = MongoBase.connect().getCollection("valCodes");
- WriteResult result = coll.remove(query);
- if (result.getError() != null) {
- System.out.println(result.getError());
- return false;
- }
- return true;
- }
- public static String findFeeds() {
- DBCollection coll = MongoBase.connect().getCollection("feeds");
- BasicDBObject s = new BasicDBObject();
- s.put("date", -1);
- DBCursor cursor = coll.find().sort(s).limit(MAXFEEDS);
- List<DBObject> retorno = cursor.toArray();
- return "{\"feeds\":" + com.mongodb.util.JSON.serialize(retorno) + "}";
- }
- public static List<Feed> findListOfFeeds() {
- DBCollection coll = MongoBase.connect().getCollection("feeds");
- BasicDBObject s = new BasicDBObject();
- s.put("date", -1);
- DBCursor cursor = coll.find().sort(s).limit(MAXFEEDS);
- List<Feed> retorno = new ArrayList<Feed>();
- while (cursor.hasNext()) {
- retorno.add(new Feed(cursor.next()));
- }
- return retorno;
- }
- public static String findVenues(String cadena) {
- /*
- * final DBObject textSearchCommand = new BasicDBObject();
- * textSearchCommand.put("text", "venues");
- * textSearchCommand.put("search", cadena); DB db = MongoBase.connect();
- * final CommandResult commandResult = db.command(textSearchCommand);
- *
- * return commandResult.toString();
- */
- DBCollection coll = MongoBase.connect().getCollection("venues");
- BasicDBObject q = new BasicDBObject();
- q.put("searchName", java.util.regex.Pattern.compile(cadena));
- DBCursor cursor = coll.find(q).limit(MAXTOPS);
- List<DBObject> retorno = cursor.toArray();
- return "{\"venues\":" + com.mongodb.util.JSON.serialize(retorno) + "}";
- }
- public static String findNearbyVenues(float lat, float lon, double dis) {
- DB db = MongoBase.connect();
- BasicDBObject myCmd = new BasicDBObject();
- myCmd.append("geoNear", "venues");
- float[] loc = {lat, lon};
- myCmd.append("near", loc);
- myCmd.append("limit", "10");
- myCmd.append("maxDistance", dis);
- myCmd.append("spherical", true);
- myCmd.append("distanceMultiplier", 6371);
- CommandResult myResults = db.command(myCmd);
- List<BasicDBObject> retorno = new ArrayList<BasicDBObject>(10);
- List<BasicDBObject> results = (List<BasicDBObject>) myResults.get("results");
- for (BasicDBObject bdbo : results) {
- BasicDBObject venue = (BasicDBObject) bdbo.get("obj");
- venue.put("dis", bdbo.get("dis"));
- retorno.add(venue);
- }
- return "{\"venues\":" + com.mongodb.util.JSON.serialize(retorno) + "}";
- }
- public static String findNearbyVenuesByName(float lat, float lon, double dis, String name) {
- DB db = MongoBase.connect();
- float[] loc = {lat, lon};
- DBObject sphere = new BasicDBObject("$centerSphere", new Object[]{loc, dis});
- DBObject geo = new BasicDBObject("$geoWithin", sphere);
- DBObject q = new BasicDBObject("coordinates", geo);
- q.put("searchName", java.util.regex.Pattern.compile(name));
- DBCursor cursor = db.getCollection("venues").find(q).limit(MAXTOPS);
- return "{\"venues\":" + com.mongodb.util.JSON.serialize(cursor.toArray()) + "}";
- }
- public static String findVenuesByCity(String location) {
- DBCollection coll = MongoBase.connect().getCollection("venues");
- BasicDBObject q = new BasicDBObject();
- q.put("address.city", location);
- DBCursor cursor = coll.find(q).limit(MAXTOPS);
- List<DBObject> retorno = cursor.toArray();
- return "{\"venues\":" + com.mongodb.util.JSON.serialize(retorno) + "}";
- }
- public static String findVenuesByCityAndName(String location, String name) {
- DBCollection coll = MongoBase.connect().getCollection("venues");
- BasicDBObject q = new BasicDBObject();
- q.put("address.city", location);
- q.put("searchName", java.util.regex.Pattern.compile(name));
- DBCursor cursor = coll.find(q).limit(MAXTOPS);
- List<DBObject> retorno = cursor.toArray();
- return "{\"venues\":" + com.mongodb.util.JSON.serialize(retorno) + "}";
- }
- public static String findVenuesByProvince(String location) {
- DBCollection coll = MongoBase.connect().getCollection("venues");
- BasicDBObject q = new BasicDBObject();
- q.put("address.province", location);
- DBCursor cursor = coll.find(q).limit(MAXTOPS);
- List<DBObject> retorno = cursor.toArray();
- return "{\"venues\":" + com.mongodb.util.JSON.serialize(retorno) + "}";
- }
- public static String findVenuesByProvinceAndName(String location, String name) {
- DBCollection coll = MongoBase.connect().getCollection("venues");
- BasicDBObject q = new BasicDBObject();
- q.put("address.province", location);
- q.put("searchName", java.util.regex.Pattern.compile(name));
- DBCursor cursor = coll.find(q).limit(MAXTOPS);
- List<DBObject> retorno = cursor.toArray();
- return "{\"venues\":" + com.mongodb.util.JSON.serialize(retorno) + "}";
- }
- public static String findNearbyDishesByType(float[] coord, double dis, List<String> tipos) {
- DB db = MongoBase.connect();
- System.out.println("coordenadas: " + coord);
- System.out.println("distancia: " + dis);
- System.out.println("tipos: " + tipos);
- DBObject sphere = new BasicDBObject("$centerSphere", new Object[]{coord, dis});
- DBObject geo = new BasicDBObject("$geoWithin", sphere);
- DBObject q = new BasicDBObject("coordinates", geo);
- ArrayList<java.util.regex.Pattern> al = new ArrayList<java.util.regex.Pattern>();
- for (String tipo : tipos) {
- al.add(java.util.regex.Pattern.compile(tipo,
- Pattern.UNICODE_CASE));
- }
- q.put("types", new BasicDBObject("$all", al));
- DBCursor cursor = db.getCollection("dishes").find(q).sort(new BasicDBObject("points", -1)).limit(MAXTOPS);
- return "{\"dishes\":" + com.mongodb.util.JSON.serialize(cursor.toArray()) + "}";
- /*BasicDBObject geo= new BasicDBObject("near", coord);
- geo.append("distanceField","dis");
- geo.append("spherical","true");
- geo.append("maxDistance",dis);
- //geo.append("limit",MAXTOPS);
- geo.append("distanceMultiplier",6371);
- BasicDBObject q=new BasicDBObject();
- ArrayList<java.util.regex.Pattern> al=new ArrayList<java.util.regex.Pattern>();
- for(String tipo:tipos){
- al.add(java.util.regex.Pattern.compile(tipo,
- Pattern.UNICODE_CASE));
- }
- q.put("types",new BasicDBObject("$all", al));
- geo.append("query",q);
- DBObject near = new BasicDBObject("$geoNear", geo);
- DBObject sort = new BasicDBObject("$sort", new BasicDBObject("points", -1) );
- DBObject limit = new BasicDBObject("$limit", MAXTOPS);
- AggregationOutput output = db.getCollection("dishes").aggregate( near, sort,limit);
- return "{\"dishes\":" + com.mongodb.util.JSON.serialize(output.results()) + "}";*/
- }
- public static String findNearbyDishes(float[] coord, double dis) {
- DB db = MongoBase.connect();
- DBObject sphere = new BasicDBObject("$centerSphere", new Object[]{coord, dis});
- DBObject geo = new BasicDBObject("$geoWithin", sphere);
- DBObject q = new BasicDBObject("coordinates", geo);
- DBCursor cursor = db.getCollection("dishes").find(q).sort(new BasicDBObject("points", -1)).limit(MAXTOPS);
- return "{\"dishes\":" + com.mongodb.util.JSON.serialize(cursor.toArray()) + "}";
- }
- public static String findDishesByCity(String location) {
- DB db = MongoBase.connect();
- DBObject limit = new BasicDBObject("$limit", MAXTOPS);
- DBObject match = new BasicDBObject("$match", new BasicDBObject("city", location));
- DBObject sort = new BasicDBObject("$sort", new BasicDBObject("points", -1));
- AggregationOutput output = db.getCollection("dishes").aggregate(match, sort, limit);
- return "{\"dishes\":" + com.mongodb.util.JSON.serialize(output.results()) + "}";
- }
- public static String findDishesByProvince(String location) {
- DB db = MongoBase.connect();
- BasicDBObject q = new BasicDBObject();
- BasicDBObject s = new BasicDBObject();
- q.put("province", location);
- s.put("points", -1);
- DBCursor cursor = db.getCollection("dishes").find(q).sort(s).limit(MAXTOPS);
- return "{\"dishes\":" + com.mongodb.util.JSON.serialize(cursor.toArray()) + "}";
- }
- public static String findDishesByCityAndType(String location, List<String> tipos) {
- System.out.println("Buscando platos por ciudad y tipo: "+location+ " "+tipos.get(0)); DB db = MongoBase.connect();
- BasicDBObject q = new BasicDBObject();
- BasicDBObject s = new BasicDBObject();
- ArrayList<java.util.regex.Pattern> al = new ArrayList<java.util.regex.Pattern>();
- for (String tipo : tipos) {
- al.add(java.util.regex.Pattern.compile(tipo,
- Pattern.UNICODE_CASE));
- }
- q.put("types", new BasicDBObject("$all", al));
- q.append("city", location);
- s.put("points", -1);
- DBCursor cursor = db.getCollection("dishes").find(q).sort(s).limit(MAXTOPS);
- return "{\"dishes\":" + com.mongodb.util.JSON.serialize(cursor.toArray()) + "}";
- }
- public static String findDishesByProvinceAndType(String location, List<String> tipos) {
- DB db = MongoBase.connect();
- BasicDBObject q = new BasicDBObject();
- BasicDBObject s = new BasicDBObject();
- ArrayList<java.util.regex.Pattern> al = new ArrayList<java.util.regex.Pattern>();
- for (String tipo : tipos) {
- al.add(java.util.regex.Pattern.compile(tipo,
- Pattern.UNICODE_CASE));
- }
- q.put("types", new BasicDBObject("$all", al));
- q.append("province", location);
- s.put("points", -1);
- DBCursor cursor = db.getCollection("dishes").find(q).sort(s).limit(MAXTOPS);
- return "{\"dishes\":" + com.mongodb.util.JSON.serialize(cursor.toArray()) + "}";
- }
- public static void consolidate() {
- DB db = MongoBase.connect();
- DBCollection venues = db.getCollection("venues");
- DBCollection dishes = db.getCollection("dishes");
- DBCursor cursor = venues.find();
- List<DBObject> listaVenues = cursor.toArray(200);
- for (DBObject venue : cursor) {
- BasicDBObject q = new BasicDBObject();
- q.put("venueId", venue.get("_id"));
- WriteResult resultado = dishes.updateMulti(new BasicDBObject("venueId", venue.get("_id")), new BasicDBObject("$set", new BasicDBObject("venueName", venue.get("name")).append("coordinates", venue.get("coordinates"))));
- WriteResult resultado2 = dishes.updateMulti(new BasicDBObject("venueId", venue.get("_id")), new BasicDBObject("$set", new BasicDBObject("city", ((DBObject) venue.get("address")).get("city")).append("province", ((DBObject) venue.get("address")).get("province"))));
- }
- }
- public static void makeSearchNames() {
- DB db = MongoBase.connect();
- DBCollection venues = db.getCollection("venues");
- DBCursor cursor = venues.find();
- for (DBObject venue : cursor) {
- WriteResult resultado = venues.update(new BasicDBObject("_id", venue.get("_id")), new BasicDBObject("$set", new BasicDBObject("searchName", removeTildes(venue.get("name").toString()).toLowerCase())));
- }
- }
- public static void correct() {
- DB db = MongoBase.connect();
- DBCollection dishes = db.getCollection("dishes");
- DBCursor cursor = dishes.find();
- ArrayList<Object> al;
- ArrayList<String> types;
- DBObject o;
- String s;
- String tipo;
- while (cursor.hasNext()) {
- types = new ArrayList<String>();
- o = cursor.next();
- al = (ArrayList<Object>) o.get("types");
- if (al != null) {
- for (Object obj : al) {
- s = obj.toString();
- if (excepciones.contains(s)) {
- types.add(s);
- } else {
- tipo = sinTildes(Gramatica.plural(s).toLowerCase());
- types.add(tipo);
- Logger.info("Tipo: " + tipo);
- }
- }
- }
- dishes.update(new BasicDBObject().append("_id", new ObjectId(o.get("_id").toString())), new BasicDBObject().append("$set", new BasicDBObject("types", types)));
- }
- }
- public static void recalculatePoints() {
- DB db = MongoBase.connect();
- DBCollection dishes = db.getCollection("dishes");
- DBCursor cursor = dishes.find();
- DBObject o;
- while (cursor.hasNext()) {
- o = cursor.next();
- if (o.get("points").toString().equalsIgnoreCase("NaN") || (Float.parseFloat(o.get("points").toString())) > 0 || (o.get("reviews") != null)) {
- updateDishPoints(o.get("_id").toString(), dishes);
- }
- }
- }
- public static List<DBObject> findDishesForVenues(DB dataBase, List<ObjectId> venueIds, String cadena) {
- DBCollection coll = dataBase.getCollection("dishes");
- BasicDBObject q = new BasicDBObject();
- q.put("name", java.util.regex.Pattern.compile(cadena,
- Pattern.CASE_INSENSITIVE));
- q.put("venueId", new BasicDBObject("$in", venueIds));
- BasicDBObject s = new BasicDBObject();
- s.put("points", -1);
- DBCursor cursor = coll.find(q).sort(s);
- return cursor.toArray(MAXRESULTS);
- }
- public static List<DBObject> findDishesForVenue(DB dataBase, BasicDBObject venue, String cadena) {
- DBCollection coll = dataBase.getCollection("dishes");
- BasicDBObject q = new BasicDBObject();
- q.put("name", java.util.regex.Pattern.compile(cadena,
- Pattern.CASE_INSENSITIVE));
- q.put("venueId", venue.get("_id"));
- DBCursor cursor = coll.find(q).limit(MAXRESULTS);
- List<DBObject> retorno = cursor.toArray();
- for (DBObject dbo : retorno) {
- dbo.put("dis", venue.get("dis"));
- dbo.put("venueName", venue.get("name"));
- dbo.put("coordinates", venue.get("coordinates"));
- }
- return cursor.toArray(MAXRESULTS);
- }
- public static Venue findVenueById(String id) {
- /*
- * final DBObject textSearchCommand = new BasicDBObject();
- * textSearchCommand.put("text", "venues");
- * textSearchCommand.put("search", cadena); DB db = MongoBase.connect();
- * final CommandResult commandResult = db.command(textSearchCommand);
- *
- * return commandResult.toString();
- */
- DBCollection coll = MongoBase.connect().getCollection("venues");
- BasicDBObject q = new BasicDBObject();
- q.put("_id", new ObjectId(id));
- return new Venue(coll.findOne(q));
- }
- public static String findVenueIdByClientMail(String mail) {
- /*
- * final DBObject textSearchCommand = new BasicDBObject();
- * textSearchCommand.put("text", "venues");
- * textSearchCommand.put("search", cadena); DB db = MongoBase.connect();
- * final CommandResult commandResult = db.command(textSearchCommand);
- *
- * return commandResult.toString();
- */
- Client c=findClientByMail(mail);
- DBCollection coll = MongoBase.connect().getCollection("venues");
- BasicDBObject q = new BasicDBObject();
- q.put("_id", new ObjectId(c.venueId));
- return coll.findOne(q).get("_id").toString();
- }
- public static void deleteDish(String id) {
- DBCollection coll = MongoBase.connect().getCollection("dishes");
- BasicDBObject q = new BasicDBObject();
- q.put("_id", new ObjectId(id));
- coll.remove(q);
- Logger.info("Se ha borrado un plato :(");
- }
- public static void deletePub(String id) {
- DBCollection coll = MongoBase.connect().getCollection("publications");
- BasicDBObject q = new BasicDBObject();
- q.put("_id", new ObjectId(id));
- coll.remove(q);
- Logger.info("Se ha borrado una publicación :(");
- }
- public static void deleteVenue(String id) {
- DBCollection coll = MongoBase.connect().getCollection("venues");
- BasicDBObject q = new BasicDBObject();
- q.put("_id", new ObjectId(id));
- coll.remove(q);
- Logger.info("Se ha borrado una Venuelogin :(");
- }
- public static String findVenueJsonById(String id) {
- DBCollection coll = MongoBase.connect().getCollection("venues");
- BasicDBObject q = new BasicDBObject();
- q.put("_id", new ObjectId(id));
- DBObject retorno = coll.findOne(q);
- if (retorno == null)
- return null;
- return com.mongodb.util.JSON.serialize(retorno);
- }
- public static List<Venue> findListOfVenues(String cadena) {
- DBCollection coll = MongoBase.connect().getCollection("venues");
- BasicDBObject q = new BasicDBObject();
- q.put("searchName", java.util.regex.Pattern.compile(cadena)
- );
- DBCursor cursor = coll.find(q);
- List<Venue> retorno = new ArrayList<Venue>();
- while (cursor.hasNext()) {
- retorno.add(new Venue(cursor.next()));
- }
- return retorno;
- }
- public static List<Venue> findListOfVenuesForCity(String cadena, String location) {
- DBCollection coll = MongoBase.connect().getCollection("venues");
- BasicDBObject q = new BasicDBObject();
- q.put("searchName", java.util.regex.Pattern.compile(cadena));
- q.append("address.city", location);
- DBCursor cursor = coll.find(q);
- List<Venue> retorno = new ArrayList<Venue>();
- while (cursor.hasNext()) {
- retorno.add(new Venue(cursor.next()));
- }
- return retorno;
- }
- public static List<Venue> findListOfVenuesForProvince(String cadena, String location) {
- Logger.info("Search: "+cadena);
- DBCollection coll = MongoBase.connect().getCollection("venues");
- BasicDBObject q = new BasicDBObject();
- q.put("searchName", java.util.regex.Pattern.compile(cadena));
- q.append("address.province", location);
- DBCursor cursor = coll.find(q);
- List<Venue> retorno = new ArrayList<Venue>();
- while (cursor.hasNext()) {
- retorno.add(new Venue(cursor.next()));
- }
- return retorno;
- }
- public static List<Venue> findListOfVenues(String cadena, String sort, String order) {
- DBCollection coll = MongoBase.connect().getCollection("venues");
- BasicDBObject q = new BasicDBObject();
- q.put("searchName", java.util.regex.Pattern.compile(cadena));
- BasicDBObject s = new BasicDBObject();
- if (order.equalsIgnoreCase("-1")) {
- s.put(sort, -1);
- } else {
- s.put(sort, 1);
- }
- DBCursor cursor = coll.find(q).sort(s);
- List<Venue> retorno = new ArrayList<Venue>();
- while (cursor.hasNext()) {
- retorno.add(new Venue(cursor.next()));
- }
- return retorno;
- }
- public static List<Dish> findListOfDishes(String cadena) {
- DBCollection coll = MongoBase.connect().getCollection("dishes");
- BasicDBObject q = new BasicDBObject();
- q.put("name", java.util.regex.Pattern.compile(cadena,
- Pattern.CASE_INSENSITIVE));
- BasicDBObject s = new BasicDBObject();
- s.put("points", -1);
- DBCursor cursor = coll.find(q).sort(s);
- List<Dish> retorno = new ArrayList<Dish>();
- while (cursor.hasNext()) {
- retorno.add(new Dish(cursor.next()));
- }
- return retorno;
- }
- public static List<Dish> findListOfDishes(int max) {
- DBCollection coll = MongoBase.connect().getCollection("dishes");
- BasicDBObject s = new BasicDBObject();
- s.put("points", -1);
- DBCursor cursor = coll.find().sort(s).limit(max);
- List<Dish> retorno = new ArrayList<Dish>();
- while (cursor.hasNext()) {
- // System.out.println("NAME "+cursor.next().get("name"));
- retorno.add(new Dish(cursor.next()));
- }
- return retorno;
- }
- public static List<Dish> findListOfDishes(String cadena, String sort, String order) {
- DBCollection coll = MongoBase.connect().getCollection("dishes");
- BasicDBObject q = new BasicDBObject();
- q.put("name", java.util.regex.Pattern.compile(cadena,
- Pattern.CASE_INSENSITIVE));
- BasicDBObject s = new BasicDBObject();
- if (order.equalsIgnoreCase("-1")) {
- s.put(sort, -1);
- } else {
- s.put(sort, 1);
- }
- DBCursor cursor = coll.find(q).sort(s);
- List<Dish> retorno = new ArrayList<Dish>();
- while (cursor.hasNext()) {
- retorno.add(new Dish(cursor.next()));
- }
- return retorno;
- }
- public static String findDishesByType(List<String> tipos) {
- DB dataBase = MongoBase.connect();
- DBCollection coll = dataBase.getCollection("dishes");
- BasicDBObject q = new BasicDBObject();
- ArrayList<java.util.regex.Pattern> al = new ArrayList<java.util.regex.Pattern>();
- for (String tipo : tipos) {
- al.add(java.util.regex.Pattern.compile(tipo,
- Pattern.UNICODE_CASE));
- }
- q.put("types", new BasicDBObject("$all", al));
- BasicDBObject s = new BasicDBObject();
- s.put("points", -1);
- DBCursor cursor = coll.find(q).sort(s);
- return "{\"dishes\":" + com.mongodb.util.JSON.serialize(cursor.toArray(MAXRESULTS)) + "}";
- }
- public static List<Dish> findListOfDishesByType(List<String> tipos) {
- DB dataBase = MongoBase.connect();
- DBCollection coll = dataBase.getCollection("dishes");
- BasicDBObject q = new BasicDBObject();
- ArrayList<java.util.regex.Pattern> al = new ArrayList<java.util.regex.Pattern>();
- for (String tipo : tipos) {
- al.add(java.util.regex.Pattern.compile(tipo,
- Pattern.UNICODE_CASE));
- }
- q.put("types", new BasicDBObject("$all", al));
- BasicDBObject s = new BasicDBObject();
- s.put("points", -1);
- DBCursor cursor = coll.find(q).sort(s);
- List<DBObject> objetos = cursor.toArray(MAXRESULTS);
- ArrayList<Dish> retorno = new ArrayList<Dish>();
- int i = 0;
- for (DBObject o : objetos) {
- retorno.add(new Dish(o));
- }
- return retorno;
- }
- public static List<Dish> findListOfDishesByProvinceAndType(List<String> tipos, String province) {
- DB dataBase = MongoBase.connect();
- DBCollection coll = dataBase.getCollection("dishes");
- BasicDBObject q = new BasicDBObject();
- ArrayList<java.util.regex.Pattern> al = new ArrayList<java.util.regex.Pattern>();
- for (String tipo : tipos) {
- al.add(java.util.regex.Pattern.compile(tipo,
- Pattern.UNICODE_CASE));
- }
- q.put("types", new BasicDBObject("$all", al));
- q.append("province", province);
- BasicDBObject s = new BasicDBObject();
- s.put("points", -1);
- DBCursor cursor = coll.find(q).sort(s);
- List<DBObject> objetos = cursor.toArray(MAXRESULTS);
- ArrayList<Dish> retorno = new ArrayList<Dish>();
- int i = 0;
- for (DBObject o : objetos) {
- retorno.add(new Dish(o));
- }
- return retorno;
- }
- public static List<Dish> findListOfDishesByCityAndType(List<String> tipos, String city) {
- DB dataBase = MongoBase.connect();
- DBCollection coll = dataBase.getCollection("dishes");
- BasicDBObject q = new BasicDBObject();
- ArrayList<java.util.regex.Pattern> al = new ArrayList<java.util.regex.Pattern>();
- for (String tipo : tipos) {
- al.add(java.util.regex.Pattern.compile(tipo,
- Pattern.UNICODE_CASE));
- }
- q.put("types", new BasicDBObject("$all", al));
- q.append("city", city);
- BasicDBObject s = new BasicDBObject();
- s.put("points", -1);
- DBCursor cursor = coll.find(q).sort(s);
- List<DBObject> objetos = cursor.toArray(MAXRESULTS);
- ArrayList<Dish> retorno = new ArrayList<Dish>();
- int i = 0;
- for (DBObject o : objetos) {
- retorno.add(new Dish(o));
- }
- return retorno;
- }
- public static List<Dish> findListOfDishesByType(List<String> tipos, String sort, String order) {
- DB dataBase = MongoBase.connect();
- DBCollection coll = dataBase.getCollection("dishes");
- BasicDBObject q = new BasicDBObject();
- ArrayList<java.util.regex.Pattern> al = new ArrayList<java.util.regex.Pattern>();
- for (String tipo : tipos) {
- al.add(java.util.regex.Pattern.compile(tipo,
- Pattern.UNICODE_CASE));
- }
- q.put("types", new BasicDBObject("$all", al));
- BasicDBObject s = new BasicDBObject();
- if (order.equalsIgnoreCase("-1")) {
- s.put(sort, -1);
- } else {
- s.put(sort, 1);
- }
- DBCursor cursor = coll.find(q).sort(s);
- List<DBObject> objetos = cursor.toArray(MAXRESULTS);
- ArrayList<Dish> retorno = new ArrayList<Dish>();
- int i = 0;
- for (DBObject o : objetos) {
- retorno.add(new Dish(o));
- }
- return retorno;
- }
- public static String findDishes(String cadena) {
- DB dataBase = MongoBase.connect();
- DBCollection coll = dataBase.getCollection("dishes");
- BasicDBObject q = new BasicDBObject();
- q.put("name", java.util.regex.Pattern.compile(cadena,
- Pattern.CASE_INSENSITIVE));
- BasicDBObject s = new BasicDBObject();
- s.put("points", -1);
- DBCursor cursor = coll.find(q).sort(s);
- return "{\"dishes\":" + com.mongodb.util.JSON.serialize(cursor.toArray(MAXRESULTS)) + "}";
- }
- public static String findDishesByVenueId(String id) {
- DBCollection coll = MongoBase.connect().getCollection("dishes");
- BasicDBObject q = new BasicDBObject();
- q.put("venueId", new ObjectId(id));
- BasicDBObject s = new BasicDBObject();
- s.put("name", -1);
- DBCursor cursor = coll.find(q).sort(s);
- List<DBObject> retorno = cursor.toArray(MAXRESULTS);
- return "{\"dishes\":" + com.mongodb.util.JSON.serialize(retorno) + "}";
- }
- public static String findPublicationsByVenueId(String id) {
- DBCollection coll = MongoBase.connect().getCollection("publications");
- BasicDBObject q = new BasicDBObject();
- q.put("venueId", id);
- BasicDBObject s = new BasicDBObject();
- s.put("creationDate", -1);
- DBCursor cursor = coll.find(q).sort(s);
- List<DBObject> retorno = cursor.toArray(MAXRESULTS);
- return "{\"publications\":" + com.mongodb.util.JSON.serialize(retorno) + "}";
- }
- public static List<Dish> findListOfDishesByVenueId(String id) {
- DBCollection coll = MongoBase.connect().getCollection("dishes");
- BasicDBObject q = new BasicDBObject();
- q.put("venueId", new ObjectId(id));
- BasicDBObject s = new BasicDBObject();
- s.put("points", -1);
- DBCursor cursor = coll.find(q).sort(s);
- List<DBObject> objetos = cursor.toArray(MAXRESULTS);
- ArrayList<Dish> retorno = new ArrayList<Dish>();
- int i = 0;
- for (DBObject o : objetos) {
- retorno.add(new Dish(o));
- }
- return retorno;
- }
- public static List<Dish> findListOfDishesByVenueIdAndName(String id,String filter) {
- DBCollection coll = MongoBase.connect().getCollection("dishes");
- BasicDBObject q = new BasicDBObject();
- q.put("venueId", new ObjectId(id));
- q.put("name", java.util.regex.Pattern.compile(filter,
- Pattern.CASE_INSENSITIVE));
- BasicDBObject s = new BasicDBObject();
- s.put("points", -1);
- DBCursor cursor = coll.find(q).sort(s);
- List<DBObject> objetos = cursor.toArray(MAXRESULTS);
- ArrayList<Dish> retorno = new ArrayList<Dish>();
- int i = 0;
- for (DBObject o : objetos) {
- retorno.add(new Dish(o));
- }
- return retorno;
- }
- public static List<Dish> findListOfDishesByVenueId(String id,String sort, String order) {
- DBCollection coll = MongoBase.connect().getCollection("dishes");
- BasicDBObject q = new BasicDBObject();
- q.put("venueId", new ObjectId(id));
- BasicDBObject s = new BasicDBObject();
- if (order.equalsIgnoreCase("-1")) {
- s.put("sort", -1);}
- else{
- s.put(sort, 1);
- }
- DBCursor cursor = coll.find(q).sort(s);
- List<DBObject> objetos = cursor.toArray(MAXRESULTS);
- ArrayList<Dish> retorno = new ArrayList<Dish>();
- for (DBObject o : objetos) {
- retorno.add(new Dish(o));
- }
- return retorno;
- }
- public static List<Publication> findListOfPublicationsByVenueId(String id) {
- DBCollection coll = MongoBase.connect().getCollection("publications");
- BasicDBObject q = new BasicDBObject();
- q.put("venueId", id);
- DBCursor cursor = coll.find(q);
- List<DBObject> objetos = cursor.toArray(MAXRESULTS);
- ArrayList<Publication> retorno = new ArrayList<Publication>();
- for (DBObject o : objetos) {
- retorno.add(new Publication(o));
- }
- return retorno;
- }
- public static List<Publication> findListOfPublicationsByVenueIdAndTitle(String id,String filter) {
- DBCollection coll = MongoBase.connect().getCollection("publications");
- BasicDBObject q = new BasicDBObject();
- q.put("venueId", id);
- q.put("title", java.util.regex.Pattern.compile(filter,
- Pattern.CASE_INSENSITIVE));
- DBCursor cursor = coll.find(q);
- List<DBObject> objetos = cursor.toArray(MAXRESULTS);
- ArrayList<Publication> retorno = new ArrayList<Publication>();
- for (DBObject o : objetos) {
- retorno.add(new Publication(o));
- }
- return retorno;
- }
- public static List<Publication> findListOfPublicationsByVenueId(String id,String sort, String order) {
- DBCollection coll = MongoBase.connect().getCollection("publications");
- BasicDBObject q = new BasicDBObject();
- q.put("venueId", id);
- BasicDBObject s = new BasicDBObject();
- if (order.equalsIgnoreCase("-1")) {
- s.put("sort", -1);}
- else{
- s.put(sort, 1);
- }
- DBCursor cursor = coll.find(q).sort(s);
- List<DBObject> objetos = cursor.toArray(MAXRESULTS);
- ArrayList<Publication> retorno = new ArrayList<Publication>();
- for (DBObject o : objetos) {
- retorno.add(new Publication(o));
- }
- return retorno;
- }
- public static Dish findDishById(String id) {
- DBCollection coll = MongoBase.connect().getCollection("dishes");
- BasicDBObject q = new BasicDBObject();
- q.put("_id", new ObjectId(id));
- DBObject obj = coll.findOne(q);
- Dish d = new Dish(obj);
- return d;
- }
- public static Publication findPublicationById(String id) {
- DBCollection coll = MongoBase.connect().getCollection("publications");
- BasicDBObject q = new BasicDBObject();
- q.put("_id", new ObjectId(id));
- DBObject obj = coll.findOne(q);
- Publication p = new Publication(obj);
- return p;
- }
- public static String findDishJSONById(String id) {
- DBCollection coll = MongoBase.connect().getCollection("dishes");
- BasicDBObject q = new BasicDBObject();
- q.put("_id", new ObjectId(id));
- DBObject retorno = coll.findOne(q);
- if (retorno == null)
- return null;
- return com.mongodb.util.JSON.serialize(retorno);
- }
- public static boolean updateDish(Dish d) {
- DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
- d.modified = df.format(new Date());
- BasicDBObject doc = d.toDBO();
- DBCollection coll = MongoBase.connect().getCollection("dishes");
- WriteResult resultado = coll.update(new BasicDBObject().append("_id", new ObjectId(d.oid.toString())), doc);
- Logger.info(resultado.toString());
- if (resultado.getError() != null) {
- Logger.error(resultado.getError());
- return false;
- }
- Logger.info("Editado dish desde la web: " + d.name);
- return true;
- }
- public static boolean updatePublication(Publication p) {
- DBObject doc = p.toDBO();
- DBCollection coll = MongoBase.connect().getCollection("publications");
- WriteResult resultado = coll.update(new BasicDBObject().append("_id", new ObjectId(p.pubId.toString())), doc);
- Logger.info(resultado.toString());
- if (resultado.getError() != null) {
- Logger.error(resultado.getError());
- return false;
- }
- Logger.info("Editado dish desde la web: " + p.title);
- return true;
- }
- public static boolean updateUser(User user) {
- DBObject doc;
- if (user.password != null && !user.password.equalsIgnoreCase("")) {
- try {
- String salt = RandomString.getRandomString(10);
- user.password = Cripto.encrypt(user.password, salt);
- doc = user.toUpdateDBO();
- doc.put("salt", salt);
- Logger.info("password encriptado: " + user.password);
- } catch (Exception e) {
- Logger.error(e.getMessage());
- return false;
- }
- } else {
- doc = user.toUpdateDBO();
- }
- DBCollection coll = MongoBase.connect().getCollection("users");
- BasicDBObject set = new BasicDBObject("$set", doc);
- WriteResult resultado = coll.update(new BasicDBObject().append("_id", new ObjectId(user._id.toString())), set);
- Logger.info(resultado.toString());
- if (resultado.getError() != null) {
- Logger.error(resultado.getError());
- return false;
- }
- Logger.info("Editado usuario: " + user.mail);
- return true;
- }
- public static boolean updateClient(Client client) {
- DBObject doc;
- if (client.getPassword() != null && !client.getPassword().equalsIgnoreCase("")) {
- try {
- String salt = RandomString.getRandomString(10);
- client.setPassword( Cripto.encrypt(client.getPassword(), salt));
- doc = client.toDBO();
- doc.put("salt", salt);
- } catch (Exception e) {
- Logger.error(e.getMessage());
- return false;
- }
- } else {
- doc = client.toDBO();
- }
- DBCollection coll = MongoBase.connect().getCollection("clients");
- BasicDBObject set = new BasicDBObject("$set", doc);
- WriteResult resultado = coll.update(new BasicDBObject().append("mail", client.getMail()), set);
- Logger.info(resultado.toString());
- if (resultado.getError() != null) {
- Logger.error(resultado.getError());
- return false;
- }
- return true;
- }
- public static boolean updateClientPassword(String mail,String newPassword) {
- DBObject doc=new BasicDBObject();
- String encPass;
- if (newPassword != null && !newPassword.equalsIgnoreCase("")) {
- try {
- String salt = RandomString.getRandomString(10);
- encPass= Cripto.encrypt(newPassword, salt);
- doc.put("password",encPass);
- doc.put("salt", salt);
- } catch (Exception e) {
- Logger.error(e.getMessage());
- return false;
- }
- } else {
- return false;
- }
- DBCollection coll = MongoBase.connect().getCollection("clients");
- BasicDBObject set = new BasicDBObject("$set", doc);
- WriteResult resultado = coll.update(new BasicDBObject().append("mail", mail), set);
- Logger.info(resultado.toString());
- if (resultado.getError() != null) {
- Logger.error(resultado.getError());
- return false;
- }
- return true;
- }
- public static String findMoreVenues(String cadena, String intento) {
- /*
- * final DBObject textSearchCommand = new BasicDBObject();
- * textSearchCommand.put("text", "venues");
- * textSearchCommand.put("search", cadena); DB db = MongoBase.connect();
- * final CommandResult commandResult = db.command(textSearchCommand);
- *
- * return commandResult.toString();
- */
- DBCollection coll = MongoBase.connect().getCollection("venues");
- BasicDBObject q = new BasicDBObject();
- q.put("name", java.util.regex.Pattern.compile("" + cadena + ""));
- DBCursor cursor = coll.find(q);
- cursor.skip(MAXRESULTS * Integer.parseInt(intento));
- List<DBObject> retorno = cursor.toArray(20);
- return "{\"venues\":" + com.mongodb.util.JSON.serialize(retorno) + "}";
- }
- public static boolean insertVenue(Venue v) {
- DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
- v.date = df.format(new Date());
- v.photoURLs = removeNulls(v.photoURLs);
- v.searchName=removeTildes(v.name).toLowerCase();
- BasicDBObject doc = v.toDBO();
- doc.put("followers", new String[]{});
- ObjectId oid = new ObjectId();
- v.oid = oid;
- doc.append("_id", oid);
- doc.put("numFollowers", 0);
- DBCollection coll = MongoBase.connect().getCollection("venues");
- WriteResult resultado = coll.insert(doc);
- if (resultado.getError() != null) {
- Logger.error(resultado.getError());
- return false;
- }
- addNewFeed(new Feed(v));
- Logger.info("Insertada nueva Venue desde la web: " + v.name);
- return true;
- }
- public static boolean insertVenuesXML() {
- final int NAME = 0;
- final int ADDRESS = 1;
- final int CITY = 2;
- final int POSTAL_CODE = 4;
- final int BAJA = 8;
- final int SUB_ACTIVITY = 12;
- int noCoordCount=0;
- int duplicateCount=0;
- int processedCount=0;
- int googleErrorsCount=0;
- int venuesInserted=0;
- int numeroDeNombresCambiados=0; //con este contador veremos a cuantos nombres le hemos añadido el prefijo "sidrería" o "cafetería"
- DBCollection coll = MongoBase.connect().getCollection("venues");
- DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
- BasicDBObject doc;
- FileInputStream file;
- HSSFWorkbook workbook;
- try {
- file = new FileInputStream(new File("./Establecimientos.xls"));
- //Create Workbook instance holding reference to .xlsx file
- workbook = new HSSFWorkbook(file);
- //Get first/desired sheet from the workbook
- } catch (Exception e) {
- e.printStackTrace();
- return false;
- }
- HSSFSheet sheet = workbook.getSheetAt(0);
- //Iterate through each rows one by one
- Iterator<Row> rowIterator = sheet.iterator();
- Venue venue;
- while (rowIterator.hasNext()) {
- Logger.info("Venues procesadas hasta ahora: "+processedCount);
- Logger.info("Venues insertadas hasta ahora: "+venuesInserted);
- Logger.info("Coordenadas no encontradas hasta ahora "+noCoordCount);
- Logger.info("Errores de GOOGLE "+googleErrorsCount);
- Logger.info("Venues duplicadas hasta ahora "+duplicateCount);
- Logger.info("------------------------------------------------");
- Row row = rowIterator.next();
- processedCount++;
- if (row.getCell(BAJA).getStringCellValue().length() == 0) {
- venue = new Venue();
- //recogemos el nombre y le damos el formato adecuado
- venue.name = row.getCell(NAME).getStringCellValue();
- if (venue.name.contains(", ")) {
- String partes[] = venue.name.split(", ");
- venue.name = partes[1] + " " + partes[0];
- } else if (venue.name.contains(" ,")) {
- String partes[] = venue.name.split(" ,");
- venue.name = partes[1] + " " + partes[0];
- }
- venue.name=WordUtils.capitalizeFully(venue.name);
- if(venue.name.startsWith(" ")){
- venue.name=venue.name.substring(1);
- }
- if(venue.name.endsWith(" ")){
- venue.name=venue.name.substring(0,venue.name.length()-1);
- }
- venue.searchName=venue.searchName.replaceAll("\\+", " ");
- //guardamos el nombre de búsqueda (sin tildes)
- venue.searchName=removeTildes(venue.name).toLowerCase();
- //recogemos ciudad y dirección
- if (row.getCell(CITY).getStringCellValue().length() < 1) {
- venue.address.city = row.getCell(CITY + 1).getStringCellValue();
- } else {
- venue.address.city = WordUtils.capitalizeFully(row.getCell(CITY).getStringCellValue());
- }
- venue.address.street = row.getCell(ADDRESS).getStringCellValue().toLowerCase();
- ////comprobamos que la venue no existe ya en la base de datos
- if(venueExists(venue)){
- duplicateCount++;
- continue;
- }
- venue.insertedBy="toptasting";
- //damos formato a la dirección y buscamos las coordenadas
- String direccionFormateada = venue.address.street.replaceAll(" ", "+");
- direccionFormateada += "+," + venue.address.city.replaceAll(" ", "+");
- final Geocoder geocoder = new Geocoder();
- GeocoderRequest geocoderRequest = new GeocoderRequestBuilder().setAddress("calle+" + direccionFormateada + "+,Asturias").setRegion("es").setLanguage("es").getGeocoderRequest();
- int numIntentos=0;
- boolean geocodingSucces=false;
- GeocodeResponse geocoderResponse=null;
- while(geocodingSucces!=true){
- try{
- numIntentos++;
- geocoderResponse = geocoder.geocode(geocoderRequest);
- geocodingSucces=true;
- }
- catch(NullPointerException npe){
- Logger.error("Error accediendo a google geocoder: intento número "+numIntentos);
- if(numIntentos>4){
- geocodingSucces=true;
- geocoderResponse=null;
- }
- Logger.error("NOS RENDIMOS... GOOGLE GO HOME, YOU ARE DRUNK");
- googleErrorsCount++;
- continue;
- }
- }
- //if geocoderResponse==null es que la búsqueda no tuvo éxito y tenemos que pasar a la siguiente venue
- if(geocoderResponse==null){
- noCoordCount++;
- continue;
- }
- if (geocoderResponse.getResults().size() > 0) {
- LatLng ll = geocoderResponse.getResults().get(0).getGeometry().getLocation();
- venue.coordinates = new double[]{ll.getLat().doubleValue(), ll.getLng().doubleValue()};
- //comprobamos que las coordenadas devueltas están en los márgenes conocidos de asturias
- if(venue.coordinates[0]>43.7||venue.coordinates[0]<42.8){
- noCoordCount++;
- continue;
- }else if((venue.coordinates[1]>-4.51)||(venue.coordinates[1]<-7.184)){
- noCoordCount++;
- continue;
- }
- }else{
- googleErrorsCount++;
- continue;
- }
- venue.address.postalCode = row.getCell(POSTAL_CODE).getStringCellValue();
- venue.address.province = "Asturias";
- venue.types.add("Restaurante");
- String subActivity = row.getCell(SUB_ACTIVITY).getStringCellValue();
- if (subActivity != null && subActivity.length() > 0) {
- venue.types.add(subActivity.toLowerCase());
- if(StringUtils.countMatches(venue.name," ")<1){
- venue.name=WordUtils.capitalize(subActivity)+" "+venue.name;
- numeroDeNombresCambiados++;
- Logger.info("número de nombres cambiados: "+numeroDeNombresCambiados);
- }
- }
- venue.name=WordUtils.capitalizeFully(venue.name);
- venue.date = df.format(new Date());
- venue.photoURLs = removeNulls(venue.photoURLs);
- doc = venue.toDBO();
- doc.put("numFollowers", 0);
- WriteResult resultado = coll.insert(doc);
- if (resultado.getError() != null) {
- Logger.error(resultado.getError());
- return false;
- }
- venuesInserted++;
- Logger.info("Insertada nueva Venue " + venue.name);
- }
- }
- Logger.info("TOTAL número de nombres cambiados: "+numeroDeNombresCambiados);
- Logger.info("TOTAL venues procesadas: "+processedCount);
- Logger.info("TOTAL errores Google: "+googleErrorsCount);
- Logger.info("TOTAL coordenadas no encontradas: "+noCoordCount);
- Logger.info("TOTAL venues duplicadas: "+duplicateCount);
- try{
- file.close();
- }catch(IOException ex){
- ex.printStackTrace();
- }
- return true;
- }
- private static boolean venueExists(Venue venue) {
- Logger.info(venue.searchName+" "+venue.address.city.toLowerCase());
- List<Venue> listaVenues=findListOfVenuesForCity(venue.searchName,venue.address.city.toLowerCase());
- for(Venue v:listaVenues){
- Logger.info(v.searchName+" "+v.address.city);
- if(v.searchName.equalsIgnoreCase(venue.searchName)&&venue.address.city.equalsIgnoreCase(v.address.city)){
- return true;
- }
- }
- return false;
- }
- public static String insertVenueByProvinceAndName(Venue v) {
- DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
- v.date = df.format(new Date());
- BasicDBObject doc = v.toDBO();
- ObjectId oid = new ObjectId();
- v.oid = oid;
- v.searchName=removeTildes(v.name).toLowerCase();
- doc.append("_id", oid);
- DBCollection coll = MongoBase.connect().getCollection("venues");
- WriteResult resultado = coll.insert(doc);
- if (resultado.getError() != null) {
- Logger.error(resultado.getError());
- return null;
- }
- addNewFeed(new Feed(v));
- Logger.info("Insertada nueva Venue desde la web: " + v.name);
- return v.oid.toString();
- }
- public static boolean updateVenue(Venue v) {
- DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
- v.modified = df.format(new Date());
- v.photoURLs = removeNulls(v.photoURLs);
- v.searchName=removeTildes(v.name).toLowerCase();
- BasicDBObject doc = v.toDBO();
- DBCollection coll = MongoBase.connect().getCollection("venues");
- WriteResult resultado = coll.update(new BasicDBObject().append("_id", new ObjectId(v.oid.toString())), doc);
- Logger.info(resultado.toString());
- if (resultado.getError() != null) {
- Logger.error(resultado.getError());
- return false;
- }
- Logger.info("Editada venue desde la web: " + v.name);
- return true;
- }
- public static String insertVenueOnLocation(Venue v) {
- BasicDBObject doc = v.toDBO();
- DBCollection coll = MongoBase.connect().getCollection("venues");
- ObjectId oid = new ObjectId();
- v.oid = oid;
- v.searchName=removeTildes(v.name).toLowerCase();
- doc.append("_id", oid);
- WriteResult resultado = coll.insert(doc);
- if (resultado.getError() != null) {
- Logger.error(resultado.getError());
- return null;
- }
- addNewFeed(new Feed(v));
- Logger.info("Insertada nueva Venue desde la app: " + v.name);
- return oid.toString();
- }
- public static String insertVenueByName(String name) {
- Venue venue = new Venue();
- venue.name = name;
- venue.searchName=removeTildes(name).toLowerCase();
- venue.photoURLs = new String[]{"http://toptasting.s3.amazonaws.com/sinImagenVenue.png"};
- BasicDBObject doc = venue.toDBO();
- ObjectId oid = new ObjectId();
- doc.append("_id", oid);
- DBCollection coll = MongoBase.connect().getCollection("venues");
- WriteResult resultado = coll.insert(doc);
- if (resultado.getError() != null) {
- Logger.error("Error insertando venue " + name);
- Logger.error(resultado.getError());
- return null;
- }
- Logger.info("Insertada nueva Venue: " + name);
- return oid.toString();
- }
- public static String insertDish(Dish dish) {
- DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
- BasicDBObject doc = dish.toDBO();
- ObjectId dishId = new ObjectId();
- doc.append("_id", dishId);
- doc.append("date", df.format(new Date()));
- doc.put("followers", new String[]{});
- DBCollection coll = MongoBase.connect().getCollection("dishes");
- WriteResult resultado = coll.insert(doc);
- if (resultado.getError() != null) {
- Logger.error("Error insertando dish " + dish.name);
- Logger.error(resultado.getError());
- return null;
- }
- Logger.info("Insertado nuevo Plato: " + dish.name);
- return dishId.toString();
- }
- /*public static String insertDish(String name, String venueId) {
- Dish dish = new Dish();
- dish.name = name;
- dish.venueId = new ObjectId(venueId);
- dish.photoURL = "https://s3-eu-west-1.amazonaws.com/toptastingimages/dishes/sinimagen.gif";
- BasicDBObject doc = dish.toDBO();
- ObjectId dishId = new ObjectId();
- doc.append("_id", dishId);
- DBCollection coll = MongoBase.connect().getCollection("dishes");
- WriteResult resultado = coll.insert(doc);
- if (resultado.getError() != null) {
- Logger.error("Error insertando dish " + name);
- Logger.error(resultado.getError());
- return null;
- }
- Logger.info("Insertado nuevo Plato: " + name);
- return dishId.toString();
- }*/
- public static boolean insertReview(Review review, String dishId) {
- //obtenemos la photo del usuario que realiza la review
- String userPhotoURL = getUserPhotoURL(review.userId.toString());
- review.setUserPhotoURL(userPhotoURL);
- // conectamos
- DBCollection coll = MongoBase.connect().getCollection("dishes");
- // creamos la query para dar con el plato y la review correctas
- BasicDBObject query = new BasicDBObject();
- query.append("_id", new ObjectId(dishId));
- Dish d=new Dish(coll.findOne(query));
- updateUserPoints(review, d, coll);
- query.append("reviews.userId", review.userId);
- // creamos el update
- BasicDBObject update = new BasicDBObject();
- update.put("$set", new BasicDBObject("reviews.$", review.toDBO()));
- // hacemos el update
- WriteResult resultado = coll.update(query, update, false, false);
- if (resultado.getError() != null) {
- Logger.error("Error insertando review por el usuario "
- + review.user);
- Logger.error(resultado.getError());
- return false;
- }
- //SI n no es 1, es que no se actualizó nada y entonces tenemos que insertar la review
- if (resultado.getN() < 1) {
- query = new BasicDBObject("_id", new ObjectId(dishId));
- update = new BasicDBObject("$push", new BasicDBObject("reviews", review.toDBO()));
- resultado = coll.update(query, update, true, true);
- }
- else{
- Logger.info("Review actualizada");
- }
- if (resultado.getError() != null) {
- Logger.error("Error insertando review por el usuario "
- + review.user);
- Logger.error(resultado.getError());
- return false;
- }
- updateDishPoints(dishId, coll);
- Logger.info(review.user + " has submitted a new Review!");
- //addNewFeed(new Feed(review, dishId));
- Application.sendNotification(new Notification(review.date, Notification.TYPE.REVIEW, review.toJson()), findUserFollowers(review.userId.toString()));
- return true;
- }
- private static void updateUserPoints(Review review,Dish dish,DBCollection coll) {
- DBCollection users = MongoBase.connect().getCollection("users");
- BasicDBObject q = new BasicDBObject();
- q.put("_id", review.userId);
- DBObject obj = users.findOne(q);
- User user = new User(obj);
- if(user.reviewedDishes.contains(dish.oid.toString())){
- review.repeated=true;
- }
- if(!user.reviewedVenues.contains(dish.venueId.toString())){
- review.firstTimeInVenue=true;
- }
- if(dish.reviews==null||dish.reviews.size()==0){
- review.firstReviewInDish=true;
- }
- BasicDBObject query = new BasicDBObject();
- query.append("venueId", dish.venueId);
- query.append("review", new BasicDBObject("$exists",true).append("$ne",null));
- DBCursor c =coll.find(query);
- if(!c.hasNext()){
- review.firstReviewInVenue=true;
- }
- int points=calculateReviewPoints(review);
- q = new BasicDBObject();
- BasicDBObject u = new BasicDBObject();
- q.put("_id", user._id);
- u.put("$inc", new BasicDBObject().append("points", points));
- if(review.firstTimeInVenue){
- u.append("$push", new BasicDBObject("reviewedVenues", dish.venueId.toString()));
- }
- if(!review.repeated){
- u.append("$push", new BasicDBObject("reviewedDishes", dish.oid.toString()));
- }
- users.update(q, u);
- Logger.info("Actualizando puntos de usuario. Incremento de " +points);
- Logger.info(review.getJsonPoints());
- }
- private static int calculateReviewPoints(Review review) {
- int points=1;
- if(review.repeated){
- return points;
- }
- if(review.firstReviewInDish){
- points++;
- }
- if(review.firstReviewInVenue){
- points++;
- }
- if(review.firstTimeInVenue){
- points++;
- }
- if(!review.photoURL.equalsIgnoreCase("http://toptasting.s3.amazonaws.com/sinImagenDish.png")){
- points++;
- }
- if(review.description!=null&&review.description.length()>5){
- points++;
- }
- return points;
- }
- public static String findReviewsByUserId(ObjectId userId) {
- // conectamos
- DBCollection coll = MongoBase.connect().getCollection("dishes");
- // creamos la query para dar con el usuario
- BasicDBObject query = new BasicDBObject();
- query.put("reviews.userId", userId);
- // hacemos la busqueda
- DBCursor cursor = coll.find(query, new BasicDBObject("reviews.$", 1).append("venueName", 1).append("name", 1));
- if (cursor == null) {
- Logger.error("No se han encontrado reviews para el usuario"
- );
- return "";
- }
- BasicDBList reviews;
- BasicDBObject review;
- for (DBObject dbo : cursor) {
- //ñapa para cambiar los ObjectId a String
- dbo.put("_id", ((ObjectId) dbo.get("_id")).toString());
- reviews = (BasicDBList) dbo.get("reviews");
- review = (BasicDBObject) reviews.get(0);
- review.put("userId", ((ObjectId) review.get("userId")).toString());
- reviews.clear();
- reviews.add(review);
- dbo.put("reviews", reviews);
- }
- return "{\"dishes\":" + com.mongodb.util.JSON.serialize(cursor.toArray()) + "}";
- }
- public static String findDrafts(ObjectId userId) {
- // conectamos
- DBCollection coll = MongoBase.connect().getCollection("users");
- // creamos la query para dar con el usuario
- BasicDBObject query = new BasicDBObject();
- query.put("_id", userId);
- // hacemos la busqueda
- DBObject user = coll.findOne(query);
- if (user == null) {
- Logger.error("No se ha encontrado un usuario buscando sus drafts"
- );
- return "";
- }
- if (user.containsField("drafts")) {
- List<Object> retorno = (List<Object>) user.get("drafts");
- return "{\"drafts\":" + com.mongodb.util.JSON.serialize(retorno) + "}";
- }
- return "{\"drafts\":[] }";
- }
- public static boolean insertDraft(Draft draft) {
- // conectamos
- DBCollection coll = MongoBase.connect().getCollection("users");
- // creamos la query para dar con el plato correcto
- BasicDBObject query = new BasicDBObject();
- query.put("_id", draft.userId);
- // creamos el update
- BasicDBObject update = new BasicDBObject();
- update.put("$push", new BasicDBObject("drafts", draft.toDBO()));
- // hacemos el update
- WriteResult resultado = coll.update(query, update, true, true);
- if (resultado.getError() != null) {
- Logger.error("Error insertando draft por el usuario "
- + draft.user);
- Logger.error(resultado.getError());
- return false;
- }
- Logger.info(draft.user + " ha creado un Draft");
- return true;
- }
- public static boolean completeDraft(Review review, String dishId) {
- // conectamos
- DB db = MongoBase.connect();
- DBCollection coll = db.getCollection("dishes");
- // creamos la query para dar con el plato correcto
- BasicDBObject query = new BasicDBObject();
- query.put("_id", new ObjectId(dishId));
- // creamos el update
- BasicDBObject update = new BasicDBObject();
- update.put("$push", new BasicDBObject("reviews", review.toDBO()));
- // hacemos el update
- WriteResult resultado = coll.update(query, update, true, true);
- if (resultado.getError() != null) {
- Logger.error("Error insertando review por el usuario "
- + review.user);
- Logger.error(resultado.getError());
- return false;
- }
- Logger.info(review.user + " a completado un Draft");
- updateDishPoints(dishId, coll);
- addNewFeed(new Feed(review, dishId));
- deleteDraft(db, review.userId, new ObjectId(dishId));
- return true;
- }
- public static boolean deleteDraft(DB db, ObjectId userId, ObjectId dishId) {
- // conectamos
- DBCollection coll = db.getCollection("users");
- // creamos la query para dar con el plato correcto
- BasicDBObject query = new BasicDBObject();
- query.put("_id", userId);
- // creamos el update
- BasicDBObject update = new BasicDBObject();
- update.put("$pull", new BasicDBObject("drafts", new BasicDBObject().append("dishId", dishId)));
- // hacemos el update
- WriteResult resultado = coll.update(query, update, true, true);
- if (resultado.getError() != null) {
- Logger.error("Error borrando un draft");
- Logger.error(resultado.getError());
- return false;
- }
- Logger.info("Eliminado uni draft ");
- return true;
- }
- public static String getUserPhotoURL(String userId) {
- DBCollection coll = MongoBase.connect().getCollection("users");
- BasicDBObject q = new BasicDBObject();
- Logger.info("USER ID (getPhotoURL): "+userId);
- q.put("_id", new ObjectId(userId));
- DBObject obj = coll.findOne(q);
- if (obj.get("photoURL") != null) {
- return obj.get("photoURL").toString();
- }
- return null;
- }
- public static String getUserPhotoURL(String userId, DBCollection coll) {
- coll = MongoBase.connect().getCollection("users");
- BasicDBObject q = new BasicDBObject();
- q.put("_id", new ObjectId(userId));
- DBObject obj = coll.findOne(q);
- if (obj.get("photoURL") != null) {
- return obj.get("photoURL").toString();
- }
- return null;
- }
- public static boolean deleteDraft(ObjectId userId, ObjectId dishId) {
- // conectamos
- DB db = MongoBase.connect();
- DBCollection coll = db.getCollection("users");
- // creamos la query para dar con el plato correcto
- BasicDBObject query = new BasicDBObject();
- query.put("_id", userId);
- // creamos el update
- BasicDBObject update = new BasicDBObject();
- update.put("$pull", new BasicDBObject("drafts", new BasicDBObject().append("dishId", dishId)));
- // hacemos el update
- WriteResult resultado = coll.update(query, update, true, true);
- if (resultado.getError() != null) {
- Logger.error("Error borrando un draft");
- Logger.error(resultado.getError());
- return false;
- }
- Logger.info("Eliminado un draft ");
- return true;
- }
- public static boolean deleteReview(String userId, String dishId) {
- // conectamos
- DB db = MongoBase.connect();
- DBCollection coll = db.getCollection("dishes");
- Logger.debug("userId: " + userId + " --- dishId: " + dishId);
- // creamos la query para dar con el plato correcto
- BasicDBObject query = new BasicDBObject();
- query.put("_id", new ObjectId(dishId));
- // creamos el update
- BasicDBObject update = new BasicDBObject();
- update.put("$pull", new BasicDBObject("reviews", new BasicDBObject().append("userId", new ObjectId(userId))));
- // hacemos el update
- WriteResult resultado = coll.update(query, update, true, true);
- if (resultado.getError() != null) {
- Logger.error("Error borrando un review");
- Logger.error(resultado.getError());
- return false;
- }
- updateDishPoints(dishId, coll);
- Logger.info("Eliminada una review ");
- return true;
- }
- public static String generateValidationCode(int lenght) {
- RandomString rs = new RandomString(lenght);
- String code = rs.nextString();
- BasicDBObject doc = new BasicDBObject("Code", code);
- DBCollection coll = MongoBase.connect().getCollection("valCodes");
- WriteResult resultado = coll.insert(doc);
- if (resultado.getError() != null) {
- Logger.error(resultado.getError());
- return null;
- }
- Logger.info("Se ha generado un nuevo código de registro");
- return code;
- }
- public static String[] removeNulls(String cadena[]) {
- List<String> list = new ArrayList<String>();
- for (String s : cadena) {
- if (s != null && s.length() > 0) {
- list.add(s);
- }
- }
- return list.toArray(new String[list.size()]);
- }
- public static String findVenueNameById(String venueId) {
- DBCollection coll = MongoBase.connect().getCollection("venues");
- BasicDBObject q = new BasicDBObject();
- q.put("_id", new ObjectId(venueId));
- DBObject venue = coll.findOne(q);
- if (venue != null) {
- return venue.get("name").toString();
- }
- return null;
- }
- public static String updateDishPhoto(String dishId, String photoURL) {
- DBCollection coll = MongoBase.connect().getCollection("dishes");
- BasicDBObject q = new BasicDBObject();
- BasicDBObject u = new BasicDBObject();
- q.put("_id", new ObjectId(dishId));
- u.put("$set", new BasicDBObject().append("photoURL", photoURL));
- coll.update(q, u);
- Logger.info("Actualizando imagen del plato con id: " + dishId);
- return null;
- }
- public static String updateVenueLocation(String venueId,Venue.Address address, double coordinates[] ) {
- DBCollection coll = MongoBase.connect().getCollection("venues");
- BasicDBObject q = new BasicDBObject();
- BasicDBObject u = new BasicDBObject();
- q.put("_id", new ObjectId(venueId));
- u.put("$set", new BasicDBObject().append("address", address.toDBO()).append("coordinates",coordinates));
- coll.update(q, u);
- Logger.info("Actualizando dirección de la Venue " + venueId);
- return null;
- }
- public static Dish updateDishPoints(String dishId, DBCollection coll) {
- BasicDBObject q = new BasicDBObject();
- q.put("_id", new ObjectId(dishId));
- DBObject obj = coll.findOne(q);
- Dish d = new Dish(obj);
- float total = 0.f;
- int elementos = d.reviews.size();
- if (elementos == 0) {
- elementos = 1;
- }
- for (Review r : d.reviews) {
- total += r.points;
- }
- q = new BasicDBObject();
- BasicDBObject u = new BasicDBObject();
- q.put("_id", new ObjectId(dishId));
- u.put("$set", new BasicDBObject().append("points", total / elementos));
- coll.update(q, u);
- d.points=total / elementos;
- Logger.info("Actualizando puntos del plato. Puntos = " + total / elementos);
- return d;
- }
- public static Dish updateDishPoints(Dish d, DBCollection coll) {
- float total = 0.f;
- int elementos = d.reviews.size();
- if (elementos == 0) {
- elementos = 1;
- }
- for (Review r : d.reviews) {
- total += r.points;
- }
- BasicDBObject q = new BasicDBObject();
- BasicDBObject u = new BasicDBObject();
- q.put("_id", d.oid);
- u.put("$set", new BasicDBObject().append("points", total / elementos));
- coll.update(q, u);
- d.points=total / elementos;
- Logger.info("Actualizando puntos del plato. Puntos = " + total / elementos);
- return d;
- }
- public static boolean addNewFeed(Feed f) {
- BasicDBObject doc = f.toDBO();
- DBCollection coll = MongoBase.connect().getCollection("feeds");
- WriteResult resultado = coll.insert(doc);
- if (resultado.getError() != null) {
- Logger.error("Error insertando feed ");
- Logger.error(resultado.getError());
- return false;
- }
- Logger.info("Insertado nuevo feed: " + f.description);
- return true;
- }
- public static String sinTildes(String tustring) {
- tustring = tustring.replace('à', 'a');
- tustring = tustring.replace('é', 'e');
- tustring = tustring.replace('í', 'i');
- tustring = tustring.replace('ó', 'o');
- tustring = tustring.replace('ú', 'u');
- return tustring;
- }
- public static String addGcmId(String userId, String gcmId) {
- DBCollection coll = MongoBase.connect().getCollection("users");
- BasicDBObject q = new BasicDBObject();
- BasicDBObject u = new BasicDBObject();
- q.put("_id", new ObjectId(userId));
- u.put("$set", new BasicDBObject().append("gcmId", gcmId));
- coll.update(q, u);
- Logger.info("Actualizado el gcmId del usuario: " + userId);
- return null;
- }
- public static String addDishToFavourites(String userId, String userName, String dishId, String venueName) {
- DBCollection coll = MongoBase.connect().getCollection("users");
- //obtenemos la photo del usuario que realiza la
- String userPhotoURL = getUserPhotoURL(userId, coll);
- ////////////
- BasicDBObject q = new BasicDBObject();
- BasicDBObject u = new BasicDBObject();
- q.put("_id", new ObjectId(userId));
- u.put("$addToSet", new BasicDBObject().append("favDishes", dishId));
- coll.update(q, u);//añadir follower
- ////////////////////////////////
- coll = MongoBase.connect().getCollection("dishes");
- q = new BasicDBObject("_id", new ObjectId(dishId));
- u = new BasicDBObject("$addToSet", new BasicDBObject("followers", userId));
- coll.update(q, u);//añadir follower
- //u=new BasicDBObject("$inc",new BasicDBObject("numFollowingUsers",1));
- //coll.update(q,u);//incrementar número followings //u=new BasicDBObject("$inc",new BasicDBObject("numFollowingUsers",1));
- //coll.update(q,u);//incrementar número followings
- Logger.info(userName + " ha añadido a su wishlist un plato de " + venueName);
- Application.sendNotification(new AddedToFavourites(userId, userName, userPhotoURL, dishId, venueName, getDate(), Notification.TYPE.ADDED_DISH_TO_FAV).asNotification(), findUserFollowers(userId));
- return null;
- }
- public static String removeDishFromFavourites(String userId, String dishId) {
- DBCollection coll = MongoBase.connect().getCollection("users");
- BasicDBObject q = new BasicDBObject();
- BasicDBObject u = new BasicDBObject();
- q.put("_id", new ObjectId(userId));
- u.put("$pull", new BasicDBObject().append("favDishes", dishId));
- coll.update(q, u);//añadir follower
- ////////////////////////////////
- coll = MongoBase.connect().getCollection("dishes");
- q = new BasicDBObject("_id", new ObjectId(dishId));
- u = new BasicDBObject("$pull", new BasicDBObject("followers", userId));
- coll.update(q, u);//añadir follower
- Logger.info("Eliminado un plato de una wishlist");
- return null;
- }
- public static String addVenueToFavourites(String userId, String userName, String venueId, String venueName) {
- DBCollection coll = MongoBase.connect().getCollection("users");
- //obtenemos la photo del usuario que realiza la review
- String userPhotoURL = getUserPhotoURL(userId, coll);
- ////////////
- BasicDBObject q = new BasicDBObject();
- BasicDBObject u = new BasicDBObject();
- q.put("_id", new ObjectId(userId));
- u.put("$addToSet", new BasicDBObject().append("favVenues", venueId));
- coll.update(q, u);//añadir follower
- ////////////////////////////////
- coll = MongoBase.connect().getCollection("venues");
- q = new BasicDBObject("_id", new ObjectId(venueId));
- u = new BasicDBObject("$addToSet", new BasicDBObject("followers", userId));
- coll.update(q, u);//añadir follower
- //u=new BasicDBObject("$inc",new BasicDBObject("numFollowingUsers",1));
- //coll.update(q,u);//incrementar número followings
- Logger.info(userName + " ha añadido a sus favoritos la venue " + venueName);
- Application.sendNotification(new AddedToFavourites(userId, userName, userPhotoURL, venueId, venueName, getDate(), Notification.TYPE.ADDED_VENUE_TO_FAV).asNotification(), findUserFollowers(userId));
- return null;
- }
- public static String removeVenueFromFavourites(String userId, String venueId) {
- DBCollection coll = MongoBase.connect().getCollection("users");
- BasicDBObject q = new BasicDBObject();
- BasicDBObject u = new BasicDBObject();
- q.put("_id", new ObjectId(userId));
- u.put("$pull", new BasicDBObject().append("favVenues", venueId));
- coll.update(q, u);//añadir follower
- ////////////////////////////////
- coll = MongoBase.connect().getCollection("venues");
- q = new BasicDBObject("_id", new ObjectId(venueId));
- u = new BasicDBObject("$pull", new BasicDBObject("followers", userId));
- coll.update(q, u);//añadir follower
- //u=new BasicDBObject("$inc",new BasicDBObject("numFollowingUsers",1));
- //coll.update(q,u);//incrementar número followings
- Logger.info("Eliminada una venue de favoritos");
- return null;
- }
- public static String addPublicationToFavourites(String userId, String userName, String pubId, String venueId, String venueName) {
- Logger.debug("adding to favourites");//añadir followe
- DBCollection coll = MongoBase.connect().getCollection("users");
- //obtenemos la photo del usuario que realiza la review
- String userPhotoURL = getUserPhotoURL(userId, coll);
- ////////////
- BasicDBObject q = new BasicDBObject();
- BasicDBObject u = new BasicDBObject();
- q.put("_id", new ObjectId(userId));
- u.put("$addToSet", new BasicDBObject().append("favPubs", pubId));
- coll.update(q, u);//añadir follower
- ////////////////////////////////
- coll = MongoBase.connect().getCollection("publications");
- q = new BasicDBObject("_id", new ObjectId(pubId));
- u = new BasicDBObject("$addToSet", new BasicDBObject("followers", userId));
- Logger.debug("Resultado mongodb " + coll.update(q, u).toString());//añadir followe
- //u=new BasicDBObject("$inc",new BasicDBObject("numFollowingUsers",1));
- //coll.update(q,u);//incrementar número followings
- Logger.info(userName + " ha añadido una publicación de " + venueName);
- Application.sendNotification(new AddedToFavourites(userId, userName, userPhotoURL, venueId, venueName, getDate(), Notification.TYPE.ADDED_PUB_TO_FAV).asNotification(), findUserFollowers(userId));
- return null;
- }
- public static String removePublicationFromFavourites(String userId, String pubId) {
- DBCollection coll = MongoBase.connect().getCollection("users");
- BasicDBObject q = new BasicDBObject();
- BasicDBObject u = new BasicDBObject();
- q.put("_id", new ObjectId(userId));
- u.put("$pull", new BasicDBObject().append("favPubs", pubId));
- coll.update(q, u);//añadir follower
- ////////////////////////////////
- coll = MongoBase.connect().getCollection("publications");
- q = new BasicDBObject("_id", new ObjectId(pubId));
- u = new BasicDBObject("$pull", new BasicDBObject("followers", userId));
- coll.update(q, u);//añadir follower
- //u=new BasicDBObject("$inc",new BasicDBObject("numFollowingUsers",1));
- //coll.update(q,u);//incrementar número followings
- Logger.info("Se ha eliminado una publicación de favoritos");
- return null;
- }
- public static String addUserFollower(String followerId, String followerName, String followedId, String followedName) {
- DBCollection coll = MongoBase.connect().getCollection("users");
- String photoURL = getUserPhotoURL(followerId, coll);
- BasicDBObject q = new BasicDBObject();
- BasicDBObject u = new BasicDBObject();
- q.put("_id", new ObjectId(followedId));
- u.put("$addToSet", new BasicDBObject().append("followers", followerId));
- coll.update(q, u);//añadir follower
- //u=new BasicDBObject("$inc",new BasicDBObject("numFollowers",1));
- //coll.update(q,u);//incrementar número followers
- ////////////////////////////////
- q = new BasicDBObject("_id", new ObjectId(followerId));
- u = new BasicDBObject("$addToSet", new BasicDBObject("favUsers", followedId));
- coll.update(q, u);//añadir follower
- //u=new BasicDBObject("$inc",new BasicDBObject("numFollowingUsers",1));
- //coll.update(q,u);//incrementar número followings
- Logger.info("Añadido un nuevo follower a " + followedName);
- Application.sendNotification(new Following(followerId, followedId, followerName, followedName, getDate(), photoURL, Notification.TYPE.FOLLOWING_U).asNotification(), findUserFollowers(followerId));
- Application.sendNotification(new Following(followerId, followedId, followerName, followedName, getDate(), photoURL, Notification.TYPE.FOLLOWING_ME).asNotification(), findNotificationIds(Arrays.asList(new String[]{followedId})));
- return null;
- }
- public static String removeUserFollower(String followerId, String followedId) {
- DBCollection coll = MongoBase.connect().getCollection("users");
- BasicDBObject q = new BasicDBObject();
- BasicDBObject u = new BasicDBObject();
- q.put("_id", new ObjectId(followedId));
- u.put("$pull", new BasicDBObject().append("followers", followerId));
- coll.update(q, u);//añadir follower
- ////////////////////////////////
- q = new BasicDBObject("_id", new ObjectId(followerId));
- u = new BasicDBObject("$pull", new BasicDBObject("favUsers", followedId));
- coll.update(q, u);//añadir follower
- Logger.info("Se ha hecho un unfollow a un usuario");
- return null;
- }
- public static String addInterest(String userId, String userName, String interestName) {
- DBCollection coll = MongoBase.connect().getCollection("interests");
- BasicDBObject q = new BasicDBObject();
- BasicDBObject u = new BasicDBObject();
- q.put("name", interestName);
- u.put("$addToSet", new BasicDBObject().append("followers", userId));
- coll.update(q, u);
- u = new BasicDBObject("$inc", new BasicDBObject("numFollowers", 1));
- coll.update(q, u);
- ///////////////////
- coll = MongoBase.connect().getCollection("users");
- q = new BasicDBObject("_id", userId);
- u = new BasicDBObject("$addToSet", new BasicDBObject("followingInterest", interestName));
- coll.update(q, u);
- Logger.info("Añadido un nuevo follower a " + interestName.toUpperCase());
- // Application.sendNotification(new Following(userId,interestName,userName,interestName,getDate(),Notification.TYPE.ADDED_INTEREST).asNotification(),findUserFollowers(userId));
- return null;
- }
- public static String removeInterest(String userId, String interestName) {
- DBCollection coll = MongoBase.connect().getCollection("interests");
- BasicDBObject q = new BasicDBObject();
- BasicDBObject u = new BasicDBObject();
- q.put("name", interestName);
- u.put("$pull", new BasicDBObject().append("followers", userId));
- coll.update(q, u);
- u = new BasicDBObject("$inc", new BasicDBObject("numFollowers", 1));
- coll.update(q, u);
- ///////////////////
- coll = MongoBase.connect().getCollection("users");
- q = new BasicDBObject("_id", userId);
- u = new BasicDBObject("$pull", new BasicDBObject("followingInterest", interestName));
- coll.update(q, u);
- Logger.info("Eliminado un follower de " + interestName.toUpperCase());
- //Application.sendNotification(new Following(userId,interestName,userName,interestName,getDate(),Notification.TYPE.ADDED_INTEREST).asNotification(),findUserFollowers(userId));
- return null;
- }
- public static String addVenueFollower(String followerId, String followerName, String venueId, String venueName) {
- DBCollection coll = MongoBase.connect().getCollection("venues");
- BasicDBObject q = new BasicDBObject();
- BasicDBObject u = new BasicDBObject();
- q.put("_id", new ObjectId(venueId));
- u.put("$addToSet", new BasicDBObject().append("followers", followerId));
- coll.update(q, u);
- //u=new BasicDBObject("$inc",new BasicDBObject("numFollowers",1));
- //coll.update(q,u);
- Logger.info("Añadido un nuevo follower a " + venueName);
- ///////////////////////
- coll = MongoBase.connect().getCollection("users");
- q = new BasicDBObject("_id", followerId);
- u = new BasicDBObject("$addToSet", new BasicDBObject("followingVenues", venueId));
- coll.update(q, u);
- //u=new BasicDBObject("$inc",new BasicDBObject("numFollowingVenues",1));
- //coll.update(q,u);//incrementar número followings
- //Application.sendNotification(new Following(followerId,venueId,followerName,venueName,getDate(),Notification.TYPE.ADDED_INTEREST).asNotification(),findUserFollowers(followerId));
- return null;
- }
- public static String removeVenueFollower(String followerId, String venueId) {
- DBCollection coll = MongoBase.connect().getCollection("venues");
- BasicDBObject q = new BasicDBObject();
- BasicDBObject u = new BasicDBObject();
- q.put("_id", new ObjectId(venueId));
- u.put("$pull", new BasicDBObject().append("followers", followerId));
- coll.update(q, u);
- Logger.info("Eliminado un follower a una venue");
- ///////////////////////
- coll = MongoBase.connect().getCollection("users");
- q = new BasicDBObject("_id", followerId);
- u = new BasicDBObject("$pull", new BasicDBObject("followingVenues", venueId));
- coll.update(q, u);
- return null;
- }
- public static String findVenuesById(List<String> venueIds) {
- DBCollection coll = MongoBase.connect().getCollection("venues");
- ArrayList<ObjectId> vOids = new ArrayList<ObjectId>(venueIds.size());
- for (String s : venueIds) {
- vOids.add(new ObjectId(s));
- }
- BasicDBObject q = new BasicDBObject();
- q.put("venueId", new BasicDBObject("$in", vOids));
- DBCursor cursor = coll.find(q).limit(vOids.size());
- List<DBObject> retorno = cursor.toArray();
- return "{\"venues\":" + com.mongodb.util.JSON.serialize(retorno) + "}";
- }
- public static String findFavVenuesByUserId(String userId) {
- DBCollection coll = MongoBase.connect().getCollection("users");
- BasicDBObject q = new BasicDBObject("_id", new ObjectId(userId));
- BasicDBObject l = new BasicDBObject("favVenues", 1);
- DBObject user = coll.findOne(q, l);
- Logger.info("USER: " + user);
- List<String> venues = (List<String>) user.get("favVenues");
- ArrayList<ObjectId> listIds = new ArrayList<ObjectId>(venues.size());
- for (String s : venues) {
- listIds.add(new ObjectId(s));
- }
- Logger.info("IDS: " + listIds.get(0).toString());
- coll = MongoBase.connect().getCollection("venues");
- q = new BasicDBObject("_id", new BasicDBObject("$in", listIds));
- DBCursor cursor = coll.find(q);
- List<DBObject> retorno = cursor.toArray();
- return "{\"venues\":" + com.mongodb.util.JSON.serialize(retorno) + "}";
- }
- public static String findFavDishesByUserId(String userId) {
- DBCollection coll = MongoBase.connect().getCollection("users");
- BasicDBObject q = new BasicDBObject("_id", new ObjectId(userId));
- BasicDBObject l = new BasicDBObject("favDishes", 1);
- DBObject user = coll.findOne(q, l);
- Logger.info("USER: " + user);
- List<String> dishes = (List<String>) user.get("favDishes");
- Logger.info("DISHES: " + dishes.get(0));
- ArrayList<ObjectId> listIds = new ArrayList<ObjectId>(dishes.size());
- for (String s : dishes) {
- listIds.add(new ObjectId(s));
- }
- Logger.info("IDS: " + listIds.get(0).toString());
- coll = MongoBase.connect().getCollection("dishes");
- q = new BasicDBObject("_id", new BasicDBObject("$in", listIds));
- DBCursor cursor = coll.find(q);
- List<DBObject> retorno = cursor.toArray();
- return "{\"dishes\":" + com.mongodb.util.JSON.serialize(retorno) + "}";
- }
- public static String findFavPublicationsByUserId(String userId) {
- DBCollection coll = MongoBase.connect().getCollection("users");
- BasicDBObject q = new BasicDBObject("_id", new ObjectId(userId));
- BasicDBObject l = new BasicDBObject("favPubs", 1);
- DBObject user = coll.findOne(q, l);
- Logger.info("USER: " + user);
- List<String> publications = (List<String>) user.get("favPubs");
- coll = MongoBase.connect().getCollection("publications");
- ArrayList<ObjectId> listIds = new ArrayList<ObjectId>(publications.size());
- for (String s : publications) {
- Logger.debug("favoritos: " + s);
- listIds.add(new ObjectId(s));
- }
- // bdl.add(new BasicDBObject("_id",new BasicDBObject("$in",listIds)));
- // bdl.add(new BasicDBObject("publications.followers",userId));
- // q=new BasicDBObject("$and",bdl);
- q = new BasicDBObject("_id", new BasicDBObject("$in", listIds));
- DBCursor cursor = coll.find(q);
- List<DBObject> retorno = cursor.toArray();
- return "{\"publications\":" + com.mongodb.util.JSON.serialize(retorno) + "}";
- }
- public static F.Promise<Result> createPublication(Publication pub) {
- DBCollection coll = MongoBase.connect().getCollection("publications");
- DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
- pub.setCreationDate(df.format(new Date()));
- pub.setPubId(new ObjectId(new Date()).toString());
- coll.insert(pub.toDBO());
- Notification n = new Notification(pub.getDate(), Notification.TYPE.PUBLICATION, pub.toJson(), pub.getPubId());
- return Application.sendNotification(n, findPublicationReceivers(pub));
- }
- public static F.Promise<Result> createGlobalPublication(Publication pub) {
- DBCollection coll = MongoBase.connect().getCollection("users");
- DBCursor dbc = coll.find(new BasicDBObject("gcmId", new BasicDBObject("$exists", true)), new BasicDBObject("gcmId", 1).append("_id", 0));
- ArrayList<String> receivers = new ArrayList<String>(dbc.count());
- for (DBObject dbo : dbc) {
- Logger.debug(dbo.toString());
- receivers.add(dbo.get("gcmId").toString());
- }
- DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
- pub.setCreationDate(df.format(new Date()));
- Notification n = new Notification(pub.getDate(), Notification.TYPE.PUBLICATION, pub.toJson());
- return Application.sendNotification(n, receivers);
- }
- static List<String> findPublicationReceivers(Publication pub) {
- HashSet<String> receivers = new HashSet<String>();
- receivers.addAll(findInterestFollowers(pub.getInterests()));
- receivers.addAll(findVenueFollowers(pub.getVenueId()));
- return findNotificationIds(new ArrayList<String>(receivers));
- }
- static List<String> findVenueFollowers(String venueId) {
- DBCollection coll = MongoBase.connect().getCollection("venues");
- DBObject dbo = coll.findOne(new BasicDBObject("_id", new ObjectId(venueId)), new BasicDBObject("followers", 1).append("_id", 0));
- BasicDBList followers = (BasicDBList) dbo.get("followers");
- if(followers!=null){
- ArrayList<String> receivers = new ArrayList<String>(followers.size());
- for (Object object : followers) {
- Logger.info("cursor: " + object.toString());
- receivers.add(object.toString());
- }
- return receivers;
- }
- return new ArrayList<String>();
- }
- static List<String> findUserFollowers(String userId) {
- DBCollection coll = MongoBase.connect().getCollection("users");
- DBObject dbo = coll.findOne(new BasicDBObject("_id", new ObjectId(userId)), new BasicDBObject("followers", 1).append("_id", 0));
- BasicDBList followers = (BasicDBList) dbo.get("followers");
- ArrayList<String> receivers = new ArrayList<String>(followers.size());
- for (Object object : followers) {
- Logger.info("cursor: " + object.toString());
- receivers.add(object.toString());
- }
- return findNotificationIds(receivers);
- }
- public static List<String> findInterestFollowers(List<String> interests) {
- DBCollection coll = MongoBase.connect().getCollection("interests");
- List lista = coll.distinct("followers", new BasicDBObject("name", new BasicDBObject("$in", interests)));
- return lista;
- }
- static List<String> findNotificationIds(List<String> userIds) {
- DBCollection coll = MongoBase.connect().getCollection("users");
- BasicDBObject q = new BasicDBObject();
- ArrayList<ObjectId> uOids = new ArrayList<ObjectId>(userIds.size());
- for (String s : userIds) {
- uOids.add(new ObjectId(s));
- }
- q.put("_id", new BasicDBObject("$in", uOids));
- DBCursor dbCursor = coll.find(q, new BasicDBObject("_id", 0).append("gcmId", 1));
- ArrayList<String> lista = new ArrayList<String>(dbCursor.count());
- DBObject dbo;
- while (dbCursor.hasNext()) {
- dbo = dbCursor.next();
- if (dbo.get("gcmId") != null) {
- lista.add(dbo.get("gcmId").toString());
- }
- }
- return lista;
- }
- static String getDate() {
- DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
- return df.format(new Date());
- }
- /**
- * Función que elimina acentos de
- * una cadena de texto.
- * @param input
- * @return cadena de texto limpia de acentos .
- */
- public static String removeTildes(String input) {
- // Cadena de caracteres original a sustituir.
- String original = "áàäéèëíìïóòöúùuÁÀÄÉÈËÍÌÏÓÒÖÚÙÜÑ";
- // Cadena de caracteres ASCII que reemplazarán los originales.
- String ascii = "aaaeeeiiiooouuuAAAEEEIIIOOOUUUN";
- String output = input;
- for (int i=0; i<original.length(); i++) {
- // Reemplazamos los caracteres especiales.
- output = output.replace(original.charAt(i), ascii.charAt(i));
- }//for i
- return output;
- }//remove1
- public static Client findClientByMail(String mail) {
- DBCollection coll = MongoBase.connect().getCollection("clients");
- BasicDBObject q = new BasicDBObject();
- q.put("mail", mail);
- DBObject obj = coll.findOne(q);
- return new Client(obj);
- }
- public static void updateVenuePhotos(Venue venue) {
- DBCollection coll = MongoBase.connect().getCollection("venues");
- BasicDBObject q = new BasicDBObject();
- BasicDBObject u = new BasicDBObject();
- q.put("_id", new ObjectId(venue.oid.toString()));
- if(venue.photoURLs[0]==null||venue.photoURLs[0].equalsIgnoreCase("")||venue.photoURLs[0].equalsIgnoreCase("undefined")){
- venue.photoURLs[0]="http://toptasting.s3.amazonaws.com/sinImagenVenue.png";
- }
- u.put("$set", new BasicDBObject().append("photoURLs", venue.photoURLs));
- coll.update(q, u);
- Logger.info("Actualizando fotos de la Venue " + venue.oid.toString());
- }
- public static void updateVenueMenuSections(Venue venue) {
- DBCollection coll = MongoBase.connect().getCollection("venues");
- BasicDBObject q = new BasicDBObject();
- BasicDBObject u = new BasicDBObject();
- q.put("_id", new ObjectId(venue.oid.toString()));
- u.put("$set", new BasicDBObject().append("menuSections", venue.menuSections));
- coll.update(q, u);
- Logger.info("Actualizando secciones de la carta " + venue.name.toString());
- }
- }