/app/Persistence/MongoBase.java
Java | 2565 lines | 2128 code | 251 blank | 186 comment | 237 complexity | 85176080efdb52734f551e8bb2edf715 MD5 | raw file
Large files files are truncated, but you can click here to view the full 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");
- BasicDBObje…
Large files files are truncated, but you can click here to view the full file