PageRenderTime 647ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 0ms

/app/Persistence/MongoBase.java

https://bitbucket.org/marcosflorez/mvp
Java | 2565 lines | 2128 code | 251 blank | 186 comment | 237 complexity | 85176080efdb52734f551e8bb2edf715 MD5 | raw file
  1. package Persistence;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.IOException;
  5. import java.net.UnknownHostException;
  6. import java.rmi.activation.ActivationSystem;
  7. import java.util.*;
  8. import java.util.regex.Pattern;
  9. import com.fasterxml.jackson.databind.JsonNode;
  10. import com.google.code.geocoder.Geocoder;
  11. import com.google.code.geocoder.GeocoderRequestBuilder;
  12. import com.google.code.geocoder.model.GeocodeResponse;
  13. import com.google.code.geocoder.model.GeocoderRequest;
  14. import com.google.code.geocoder.model.LatLng;
  15. import com.google.gson.Gson;
  16. import com.mongodb.*;
  17. import com.mongodb.util.JSON;
  18. import com.typesafe.config.Config;
  19. import controllers.Application;
  20. import models.*;
  21. import models.Notifications.AddedToFavourites;
  22. import models.Notifications.Following;
  23. import models.Notifications.Notification;
  24. import models.Notifications.Publication;
  25. import org.apache.commons.lang3.StringUtils;
  26. import org.apache.commons.lang3.text.WordUtils;
  27. import org.apache.poi.hssf.usermodel.HSSFSheet;
  28. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  29. import org.apache.poi.ss.usermodel.Row;
  30. import org.bson.types.ObjectId;
  31. import org.springframework.core.task.AsyncTaskExecutor;
  32. import play.Configuration;
  33. import play.Logger;
  34. import Utils.Cripto;
  35. import Utils.RandomString;
  36. import java.text.SimpleDateFormat;
  37. import java.text.DateFormat;
  38. import net.proinf.gramatica.*;
  39. import play.Play;
  40. import play.libs.WS;
  41. import play.mvc.Result;
  42. import play.libs.F;
  43. import com.typesafe.config.ConfigFactory;
  44. public class MongoBase {
  45. final static int MAXRESULTS = 100;
  46. final static int MAXTOPS = 20;
  47. final static int MAXFEEDS = 20;
  48. final static double MAXDISTANCE = 0.00078480615;//en kil�metros
  49. final static ArrayList<String> excepciones = new ArrayList<String>(Arrays.asList("wok", "alioli", "bravioli", "espagueti", "nuggets"));
  50. static DB actualMB;
  51. final static Configuration conf= Play.application().configuration();
  52. static DB connect() {
  53. if (actualMB != null) {
  54. return actualMB;
  55. }
  56. Mongo mongoClient;
  57. try {
  58. mongoClient = new Mongo(conf.getString("mongo.address"),conf.getInt("mongo.port"));
  59. // mongoClient = new Mongo("dharma.mongohq.com", 10031);
  60. //mongoClient = new Mongo("localhost" , 27017);
  61. actualMB = mongoClient.getDB("pitanzas");
  62. actualMB.authenticate("tista", "teto".toCharArray());
  63. return actualMB;
  64. } catch (UnknownHostException e) {
  65. // TODO Auto-generated catch block
  66. Logger.error(e.getMessage());
  67. }
  68. return null;
  69. }
  70. public static boolean checkValidationCode(String code) {
  71. BasicDBObject query = new BasicDBObject("Code", code);
  72. DBCollection coll = MongoBase.connect().getCollection("valCodes");
  73. DBObject retorno = coll.findOne(query);
  74. if (retorno != null) {
  75. return true;
  76. }
  77. Logger.info("Se ha introducido un código de validación INCORRECTO");
  78. return false;
  79. }
  80. public static boolean checkMail(String mail) {
  81. BasicDBObject query = new BasicDBObject("mail", mail);
  82. DBCollection coll = MongoBase.connect().getCollection("users");
  83. DBObject retorno = coll.findOne(query);
  84. if (retorno != null) {
  85. return true;
  86. }
  87. return false;
  88. }
  89. public static User retrieveUser(String mail) {
  90. BasicDBObject query = new BasicDBObject("mail", mail);
  91. DBCollection coll = MongoBase.connect().getCollection("users");
  92. DBObject retorno = coll.findOne(query);
  93. if (retorno == null) {
  94. return null;
  95. }
  96. return new User(retorno);
  97. }
  98. public static String retrievePassword(String mail) {
  99. BasicDBObject query = new BasicDBObject("mail", mail);
  100. DBCollection coll = MongoBase.connect().getCollection("users");
  101. DBObject retorno = coll.findOne(query);
  102. if (retorno == null) {
  103. return null;
  104. }
  105. String password = null;
  106. String encPass = (String) retorno.get("password");
  107. if (encPass == null || encPass.equalsIgnoreCase("")) {
  108. return "";
  109. }
  110. try {
  111. password = Cripto.decrypt(encPass, (String) retorno.get("salt"));
  112. } catch (Exception e) {
  113. Logger.error(e.getMessage());
  114. return null;
  115. }
  116. Logger.info("Se ha recuperado el password de: " + mail);
  117. return password;
  118. }
  119. public static String retrieveClientPassword(String mail) {
  120. BasicDBObject query = new BasicDBObject("mail", mail);
  121. DBCollection coll = MongoBase.connect().getCollection("clients");
  122. DBObject retorno = coll.findOne(query);
  123. if (retorno == null) {
  124. return null;
  125. }
  126. String password = null;
  127. String encPass = (String) retorno.get("password");
  128. if (encPass == null || encPass.equalsIgnoreCase("")) {
  129. return "";
  130. }
  131. try {
  132. password = Cripto.decrypt(encPass, (String) retorno.get("salt"));
  133. } catch (Exception e) {
  134. Logger.error(e.getMessage());
  135. return null;
  136. }
  137. Logger.info("Se ha recuperado el password de: " + mail);
  138. return password;
  139. }
  140. public static String insertUser(User user) {
  141. String salt = RandomString.getRandomString(10);
  142. try {
  143. user.password = Cripto.encrypt(user.password, salt);
  144. } catch (Exception e) {
  145. Logger.error(e.getMessage());
  146. return null;
  147. }
  148. Gson gson = new Gson();
  149. DBObject doc = (DBObject) JSON.parse(gson.toJson(user));
  150. doc.put("salt", salt);
  151. doc.put("followers", new String[]{});
  152. doc.put("favUsers", new String[]{});
  153. doc.put("favVenues", new String[]{});
  154. doc.put("favDishes", new String[]{});
  155. doc.put("favPubs", new String[]{});
  156. DBCollection coll = MongoBase.connect().getCollection("users");
  157. WriteResult resultado = coll.insert(doc);
  158. if (resultado.getError() != null) {
  159. Logger.error(resultado.getError());
  160. return null;
  161. }
  162. Logger.info("Insertado el usuario " + user.user + ":" + user.mail);
  163. addNewFeed(new Feed(user));
  164. return doc.get("_id").toString();
  165. }
  166. public static String insertClient(Client client) {
  167. String salt = RandomString.getRandomString(10);
  168. try {
  169. client.setPassword(Cripto.encrypt(client.getPassword(), salt));
  170. } catch (Exception e) {
  171. Logger.error(e.getMessage());
  172. return null;
  173. }
  174. Gson gson = new Gson();
  175. DBObject doc = client.toDBO();
  176. doc.put("password",client.getPassword());
  177. doc.put("salt", salt);
  178. DBCollection coll = MongoBase.connect().getCollection("clients");
  179. WriteResult resultado = coll.insert(doc);
  180. if (resultado.getError() != null) {
  181. Logger.error(resultado.getError());
  182. return null;
  183. }
  184. Logger.info("Insertado el cliente " + client.getMail());
  185. return doc.get("_id").toString();
  186. }
  187. public static User findUserById(String id) {
  188. DBCollection coll = MongoBase.connect().getCollection("users");
  189. BasicDBObject q = new BasicDBObject();
  190. q.put("_id", new ObjectId(id));
  191. DBObject obj = coll.findOne(q);
  192. User user = new User(obj);
  193. return user;
  194. }
  195. public static String findUserJSONById(String id) {
  196. DBCollection coll = MongoBase.connect().getCollection("users");
  197. BasicDBObject q = new BasicDBObject();
  198. q.put("_id", new ObjectId(id));
  199. DBObject obj = coll.findOne(q);
  200. User user = new User(obj);
  201. return com.mongodb.util.JSON.serialize(obj);
  202. }
  203. public static String findUsersByName(String name) {
  204. DBCollection coll = MongoBase.connect().getCollection("users");
  205. BasicDBObject q = new BasicDBObject();
  206. q.put("user", java.util.regex.Pattern.compile(name,
  207. Pattern.CASE_INSENSITIVE));
  208. DBCursor cursor = coll.find(q);
  209. return "{\"users\":" + com.mongodb.util.JSON.serialize(cursor.toArray(MAXRESULTS)) + "}";
  210. }
  211. public static String findUsersById(List<String> ids) {
  212. DBCollection coll = MongoBase.connect().getCollection("users");
  213. BasicDBObject q = new BasicDBObject();
  214. List<ObjectId> oids = new ArrayList<ObjectId>(ids.size());
  215. for (String id : ids) {
  216. oids.add(new ObjectId(id));
  217. }
  218. q.put("_id", new BasicDBObject("$in", oids));
  219. DBCursor cursor = coll.find(q);
  220. return "{\"users\":" + com.mongodb.util.JSON.serialize(cursor.toArray()) + "}";
  221. }
  222. public static String findUsersFollowed(String followerId) {
  223. DBCollection coll = MongoBase.connect().getCollection("users");
  224. BasicDBObject q = new BasicDBObject();
  225. q.put("userId", followerId);
  226. DBObject user = coll.findOne(q);
  227. ArrayList<Object> al = (ArrayList<Object>) user.get("favUsers");
  228. ArrayList<String> usersId = new ArrayList<String>(al.size());
  229. if (al != null) {
  230. for (Object ob : al) {
  231. usersId.add(ob.toString());
  232. }
  233. }
  234. q = new BasicDBObject("$in", usersId);
  235. return "{\"users\":" + com.mongodb.util.JSON.serialize(coll.find(q).toArray()) + "}";
  236. }
  237. public static String insertFBUser(User user) {
  238. Gson gson = new Gson();
  239. DBObject doc = (DBObject) JSON.parse(gson.toJson(user));
  240. doc.put("followers", new String[]{});
  241. doc.put("favUsers", new String[]{});
  242. doc.put("favVenues", new String[]{});
  243. doc.put("favDishes", new String[]{});
  244. doc.put("favPubs", new String[]{});
  245. DBCollection coll = MongoBase.connect().getCollection("users");
  246. WriteResult resultado = coll.insert(doc);
  247. if (resultado.getError() != null) {
  248. Logger.error(resultado.getError());
  249. return null;
  250. }
  251. Logger.info("Insertado el usuario " + user.user + ":" + user.mail);
  252. addNewFeed(new Feed(user));
  253. return doc.get("_id").toString();
  254. }
  255. public static boolean loginAdmin(String mail, String password) {
  256. BasicDBObject query = new BasicDBObject("mail", mail);
  257. DBCollection coll = MongoBase.connect().getCollection("users");
  258. DBObject retorno = coll.findOne(query);
  259. if (retorno == null) {
  260. Logger.info("Usuario " + mail + " no encontrado");
  261. return false;
  262. }
  263. String admin = (String) retorno.get("admin");
  264. if (admin == null || admin.equalsIgnoreCase("false")) {
  265. Logger.info("El usuario " + mail + " no tiene permisos suficientes");
  266. return false;
  267. }
  268. String decPassword = null;
  269. String encPass = (String) retorno.get("password");
  270. try {
  271. decPassword = Cripto.decrypt(encPass, (String) retorno.get("salt"));
  272. } catch (Exception e) {
  273. Logger.error(e.getMessage());
  274. return false;
  275. }
  276. if (decPassword.equalsIgnoreCase(password)) {
  277. Logger.info("Administrador logueado: " + mail);
  278. return true;
  279. } else {
  280. Logger.info("Error en la password para el usuario" + mail);
  281. }
  282. Logger.info("Se ha reenviado la password a: " + mail);
  283. return false;
  284. }
  285. public static boolean loginVenue(String mail, String password) {
  286. BasicDBObject query = new BasicDBObject("mail", mail);
  287. DBCollection coll = MongoBase.connect().getCollection("clients");
  288. DBObject retorno = coll.findOne(query);
  289. if (retorno == null) {
  290. Logger.info("Usuario " + mail + " no encontrado");
  291. return false;
  292. }
  293. return true;
  294. /* String decPassword = null;
  295. String encPass = (String) retorno.get("password");
  296. try {
  297. decPassword = Cripto.decrypt(encPass, (String) retorno.get("salt"));
  298. } catch (Exception e) {
  299. Logger.error(e.getMessage());
  300. return false;
  301. }
  302. if (decPassword.equalsIgnoreCase(password)) {
  303. Logger.info("Venue logueada: " + mail);
  304. return true;
  305. } else {
  306. Logger.info("Error en la password para el usuario" + mail);
  307. }
  308. return false;*/
  309. }
  310. public static User loginUser(String mail, String password) {
  311. BasicDBObject query = new BasicDBObject("mail", mail);
  312. DBCollection coll = MongoBase.connect().getCollection("users");
  313. DBObject retorno = coll.findOne(query);
  314. if (retorno == null) {
  315. return null;
  316. }
  317. String decPassword = null;
  318. String encPass = (String) retorno.get("password");
  319. if (encPass == null || encPass.equalsIgnoreCase("")) {
  320. return null;
  321. }
  322. try {
  323. decPassword = Cripto.decrypt(encPass, (String) retorno.get("salt"));
  324. } catch (Exception e) {
  325. Logger.error(e.getMessage());
  326. e.printStackTrace();
  327. return null;
  328. }
  329. if (decPassword.equalsIgnoreCase(password)) {
  330. Logger.info("Usuario logueado: " + mail);
  331. return new User(retorno);
  332. }
  333. return null;
  334. }
  335. public static String logUser(String mail, String password) {
  336. BasicDBObject query = new BasicDBObject("mail", mail);
  337. DBCollection coll = MongoBase.connect().getCollection("users");
  338. DBObject retorno = coll.findOne(query);
  339. if (retorno == null) {
  340. return null;
  341. }
  342. String decPassword = null;
  343. String encPass = (String) retorno.get("password");
  344. if (encPass == null || encPass.equalsIgnoreCase("")) {
  345. return null;
  346. }
  347. try {
  348. decPassword = Cripto.decrypt(encPass, (String) retorno.get("salt"));
  349. } catch (Exception e) {
  350. Logger.error(e.getMessage());
  351. e.printStackTrace();
  352. return null;
  353. }
  354. if (decPassword.equalsIgnoreCase(password)) {
  355. Logger.info("Usuario logueado: " + mail);
  356. return com.mongodb.util.JSON.serialize(retorno);
  357. }
  358. return null;
  359. }
  360. public static String loginFBUser(User user, String userId) {
  361. BasicDBObject query = new BasicDBObject("mail", user.getMail());
  362. Logger.debug("loginFB: " + user);
  363. DBCollection coll = MongoBase.connect().getCollection("users");
  364. DBObject retorno = coll.findOne(query);
  365. if (retorno == null) {
  366. insertFBUser(user);
  367. retorno = coll.findOne(query);
  368. if(retorno==null){
  369. return null;
  370. }
  371. return com.mongodb.util.JSON.serialize(retorno);
  372. }
  373. if (retorno.containsField("fbid") && retorno.get("fbid").toString().equalsIgnoreCase(userId)) {
  374. return com.mongodb.util.JSON.serialize(retorno);
  375. } else {
  376. BasicDBObject set = new BasicDBObject("$set", user.toFbUpdateDBO());
  377. WriteResult resultado = coll.update(new BasicDBObject().append("mail", user.getMail()), set);
  378. Logger.info(resultado.toString());
  379. if (resultado.getError() != null) {
  380. Logger.error(resultado.getError());
  381. return null;
  382. }
  383. return com.mongodb.util.JSON.serialize(coll.findOne(query));
  384. }
  385. }
  386. public static boolean consumeValidationCode(String code) {
  387. BasicDBObject query = new BasicDBObject("Code", code);
  388. DBCollection coll = MongoBase.connect().getCollection("valCodes");
  389. WriteResult result = coll.remove(query);
  390. if (result.getError() != null) {
  391. System.out.println(result.getError());
  392. return false;
  393. }
  394. return true;
  395. }
  396. public static String findFeeds() {
  397. DBCollection coll = MongoBase.connect().getCollection("feeds");
  398. BasicDBObject s = new BasicDBObject();
  399. s.put("date", -1);
  400. DBCursor cursor = coll.find().sort(s).limit(MAXFEEDS);
  401. List<DBObject> retorno = cursor.toArray();
  402. return "{\"feeds\":" + com.mongodb.util.JSON.serialize(retorno) + "}";
  403. }
  404. public static List<Feed> findListOfFeeds() {
  405. DBCollection coll = MongoBase.connect().getCollection("feeds");
  406. BasicDBObject s = new BasicDBObject();
  407. s.put("date", -1);
  408. DBCursor cursor = coll.find().sort(s).limit(MAXFEEDS);
  409. List<Feed> retorno = new ArrayList<Feed>();
  410. while (cursor.hasNext()) {
  411. retorno.add(new Feed(cursor.next()));
  412. }
  413. return retorno;
  414. }
  415. public static String findVenues(String cadena) {
  416. /*
  417. * final DBObject textSearchCommand = new BasicDBObject();
  418. * textSearchCommand.put("text", "venues");
  419. * textSearchCommand.put("search", cadena); DB db = MongoBase.connect();
  420. * final CommandResult commandResult = db.command(textSearchCommand);
  421. *
  422. * return commandResult.toString();
  423. */
  424. DBCollection coll = MongoBase.connect().getCollection("venues");
  425. BasicDBObject q = new BasicDBObject();
  426. q.put("searchName", java.util.regex.Pattern.compile(cadena));
  427. DBCursor cursor = coll.find(q).limit(MAXTOPS);
  428. List<DBObject> retorno = cursor.toArray();
  429. return "{\"venues\":" + com.mongodb.util.JSON.serialize(retorno) + "}";
  430. }
  431. public static String findNearbyVenues(float lat, float lon, double dis) {
  432. DB db = MongoBase.connect();
  433. BasicDBObject myCmd = new BasicDBObject();
  434. myCmd.append("geoNear", "venues");
  435. float[] loc = {lat, lon};
  436. myCmd.append("near", loc);
  437. myCmd.append("limit", "10");
  438. myCmd.append("maxDistance", dis);
  439. myCmd.append("spherical", true);
  440. myCmd.append("distanceMultiplier", 6371);
  441. CommandResult myResults = db.command(myCmd);
  442. List<BasicDBObject> retorno = new ArrayList<BasicDBObject>(10);
  443. List<BasicDBObject> results = (List<BasicDBObject>) myResults.get("results");
  444. for (BasicDBObject bdbo : results) {
  445. BasicDBObject venue = (BasicDBObject) bdbo.get("obj");
  446. venue.put("dis", bdbo.get("dis"));
  447. retorno.add(venue);
  448. }
  449. return "{\"venues\":" + com.mongodb.util.JSON.serialize(retorno) + "}";
  450. }
  451. public static String findNearbyVenuesByName(float lat, float lon, double dis, String name) {
  452. DB db = MongoBase.connect();
  453. float[] loc = {lat, lon};
  454. DBObject sphere = new BasicDBObject("$centerSphere", new Object[]{loc, dis});
  455. DBObject geo = new BasicDBObject("$geoWithin", sphere);
  456. DBObject q = new BasicDBObject("coordinates", geo);
  457. q.put("searchName", java.util.regex.Pattern.compile(name));
  458. DBCursor cursor = db.getCollection("venues").find(q).limit(MAXTOPS);
  459. return "{\"venues\":" + com.mongodb.util.JSON.serialize(cursor.toArray()) + "}";
  460. }
  461. public static String findVenuesByCity(String location) {
  462. DBCollection coll = MongoBase.connect().getCollection("venues");
  463. BasicDBObject q = new BasicDBObject();
  464. q.put("address.city", location);
  465. DBCursor cursor = coll.find(q).limit(MAXTOPS);
  466. List<DBObject> retorno = cursor.toArray();
  467. return "{\"venues\":" + com.mongodb.util.JSON.serialize(retorno) + "}";
  468. }
  469. public static String findVenuesByCityAndName(String location, String name) {
  470. DBCollection coll = MongoBase.connect().getCollection("venues");
  471. BasicDBObject q = new BasicDBObject();
  472. q.put("address.city", location);
  473. q.put("searchName", java.util.regex.Pattern.compile(name));
  474. DBCursor cursor = coll.find(q).limit(MAXTOPS);
  475. List<DBObject> retorno = cursor.toArray();
  476. return "{\"venues\":" + com.mongodb.util.JSON.serialize(retorno) + "}";
  477. }
  478. public static String findVenuesByProvince(String location) {
  479. DBCollection coll = MongoBase.connect().getCollection("venues");
  480. BasicDBObject q = new BasicDBObject();
  481. q.put("address.province", location);
  482. DBCursor cursor = coll.find(q).limit(MAXTOPS);
  483. List<DBObject> retorno = cursor.toArray();
  484. return "{\"venues\":" + com.mongodb.util.JSON.serialize(retorno) + "}";
  485. }
  486. public static String findVenuesByProvinceAndName(String location, String name) {
  487. DBCollection coll = MongoBase.connect().getCollection("venues");
  488. BasicDBObject q = new BasicDBObject();
  489. q.put("address.province", location);
  490. q.put("searchName", java.util.regex.Pattern.compile(name));
  491. DBCursor cursor = coll.find(q).limit(MAXTOPS);
  492. List<DBObject> retorno = cursor.toArray();
  493. return "{\"venues\":" + com.mongodb.util.JSON.serialize(retorno) + "}";
  494. }
  495. public static String findNearbyDishesByType(float[] coord, double dis, List<String> tipos) {
  496. DB db = MongoBase.connect();
  497. System.out.println("coordenadas: " + coord);
  498. System.out.println("distancia: " + dis);
  499. System.out.println("tipos: " + tipos);
  500. DBObject sphere = new BasicDBObject("$centerSphere", new Object[]{coord, dis});
  501. DBObject geo = new BasicDBObject("$geoWithin", sphere);
  502. DBObject q = new BasicDBObject("coordinates", geo);
  503. ArrayList<java.util.regex.Pattern> al = new ArrayList<java.util.regex.Pattern>();
  504. for (String tipo : tipos) {
  505. al.add(java.util.regex.Pattern.compile(tipo,
  506. Pattern.UNICODE_CASE));
  507. }
  508. q.put("types", new BasicDBObject("$all", al));
  509. DBCursor cursor = db.getCollection("dishes").find(q).sort(new BasicDBObject("points", -1)).limit(MAXTOPS);
  510. return "{\"dishes\":" + com.mongodb.util.JSON.serialize(cursor.toArray()) + "}";
  511. /*BasicDBObject geo= new BasicDBObject("near", coord);
  512. geo.append("distanceField","dis");
  513. geo.append("spherical","true");
  514. geo.append("maxDistance",dis);
  515. //geo.append("limit",MAXTOPS);
  516. geo.append("distanceMultiplier",6371);
  517. BasicDBObject q=new BasicDBObject();
  518. ArrayList<java.util.regex.Pattern> al=new ArrayList<java.util.regex.Pattern>();
  519. for(String tipo:tipos){
  520. al.add(java.util.regex.Pattern.compile(tipo,
  521. Pattern.UNICODE_CASE));
  522. }
  523. q.put("types",new BasicDBObject("$all", al));
  524. geo.append("query",q);
  525. DBObject near = new BasicDBObject("$geoNear", geo);
  526. DBObject sort = new BasicDBObject("$sort", new BasicDBObject("points", -1) );
  527. DBObject limit = new BasicDBObject("$limit", MAXTOPS);
  528. AggregationOutput output = db.getCollection("dishes").aggregate( near, sort,limit);
  529. return "{\"dishes\":" + com.mongodb.util.JSON.serialize(output.results()) + "}";*/
  530. }
  531. public static String findNearbyDishes(float[] coord, double dis) {
  532. DB db = MongoBase.connect();
  533. DBObject sphere = new BasicDBObject("$centerSphere", new Object[]{coord, dis});
  534. DBObject geo = new BasicDBObject("$geoWithin", sphere);
  535. DBObject q = new BasicDBObject("coordinates", geo);
  536. DBCursor cursor = db.getCollection("dishes").find(q).sort(new BasicDBObject("points", -1)).limit(MAXTOPS);
  537. return "{\"dishes\":" + com.mongodb.util.JSON.serialize(cursor.toArray()) + "}";
  538. }
  539. public static String findDishesByCity(String location) {
  540. DB db = MongoBase.connect();
  541. DBObject limit = new BasicDBObject("$limit", MAXTOPS);
  542. DBObject match = new BasicDBObject("$match", new BasicDBObject("city", location));
  543. DBObject sort = new BasicDBObject("$sort", new BasicDBObject("points", -1));
  544. AggregationOutput output = db.getCollection("dishes").aggregate(match, sort, limit);
  545. return "{\"dishes\":" + com.mongodb.util.JSON.serialize(output.results()) + "}";
  546. }
  547. public static String findDishesByProvince(String location) {
  548. DB db = MongoBase.connect();
  549. BasicDBObject q = new BasicDBObject();
  550. BasicDBObject s = new BasicDBObject();
  551. q.put("province", location);
  552. s.put("points", -1);
  553. DBCursor cursor = db.getCollection("dishes").find(q).sort(s).limit(MAXTOPS);
  554. return "{\"dishes\":" + com.mongodb.util.JSON.serialize(cursor.toArray()) + "}";
  555. }
  556. public static String findDishesByCityAndType(String location, List<String> tipos) {
  557. System.out.println("Buscando platos por ciudad y tipo: "+location+ " "+tipos.get(0)); DB db = MongoBase.connect();
  558. BasicDBObject q = new BasicDBObject();
  559. BasicDBObject s = new BasicDBObject();
  560. ArrayList<java.util.regex.Pattern> al = new ArrayList<java.util.regex.Pattern>();
  561. for (String tipo : tipos) {
  562. al.add(java.util.regex.Pattern.compile(tipo,
  563. Pattern.UNICODE_CASE));
  564. }
  565. q.put("types", new BasicDBObject("$all", al));
  566. q.append("city", location);
  567. s.put("points", -1);
  568. DBCursor cursor = db.getCollection("dishes").find(q).sort(s).limit(MAXTOPS);
  569. return "{\"dishes\":" + com.mongodb.util.JSON.serialize(cursor.toArray()) + "}";
  570. }
  571. public static String findDishesByProvinceAndType(String location, List<String> tipos) {
  572. DB db = MongoBase.connect();
  573. BasicDBObject q = new BasicDBObject();
  574. BasicDBObject s = new BasicDBObject();
  575. ArrayList<java.util.regex.Pattern> al = new ArrayList<java.util.regex.Pattern>();
  576. for (String tipo : tipos) {
  577. al.add(java.util.regex.Pattern.compile(tipo,
  578. Pattern.UNICODE_CASE));
  579. }
  580. q.put("types", new BasicDBObject("$all", al));
  581. q.append("province", location);
  582. s.put("points", -1);
  583. DBCursor cursor = db.getCollection("dishes").find(q).sort(s).limit(MAXTOPS);
  584. return "{\"dishes\":" + com.mongodb.util.JSON.serialize(cursor.toArray()) + "}";
  585. }
  586. public static void consolidate() {
  587. DB db = MongoBase.connect();
  588. DBCollection venues = db.getCollection("venues");
  589. DBCollection dishes = db.getCollection("dishes");
  590. DBCursor cursor = venues.find();
  591. List<DBObject> listaVenues = cursor.toArray(200);
  592. for (DBObject venue : cursor) {
  593. BasicDBObject q = new BasicDBObject();
  594. q.put("venueId", venue.get("_id"));
  595. WriteResult resultado = dishes.updateMulti(new BasicDBObject("venueId", venue.get("_id")), new BasicDBObject("$set", new BasicDBObject("venueName", venue.get("name")).append("coordinates", venue.get("coordinates"))));
  596. 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"))));
  597. }
  598. }
  599. public static void makeSearchNames() {
  600. DB db = MongoBase.connect();
  601. DBCollection venues = db.getCollection("venues");
  602. DBCursor cursor = venues.find();
  603. for (DBObject venue : cursor) {
  604. WriteResult resultado = venues.update(new BasicDBObject("_id", venue.get("_id")), new BasicDBObject("$set", new BasicDBObject("searchName", removeTildes(venue.get("name").toString()).toLowerCase())));
  605. }
  606. }
  607. public static void correct() {
  608. DB db = MongoBase.connect();
  609. DBCollection dishes = db.getCollection("dishes");
  610. DBCursor cursor = dishes.find();
  611. ArrayList<Object> al;
  612. ArrayList<String> types;
  613. DBObject o;
  614. String s;
  615. String tipo;
  616. while (cursor.hasNext()) {
  617. types = new ArrayList<String>();
  618. o = cursor.next();
  619. al = (ArrayList<Object>) o.get("types");
  620. if (al != null) {
  621. for (Object obj : al) {
  622. s = obj.toString();
  623. if (excepciones.contains(s)) {
  624. types.add(s);
  625. } else {
  626. tipo = sinTildes(Gramatica.plural(s).toLowerCase());
  627. types.add(tipo);
  628. Logger.info("Tipo: " + tipo);
  629. }
  630. }
  631. }
  632. dishes.update(new BasicDBObject().append("_id", new ObjectId(o.get("_id").toString())), new BasicDBObject().append("$set", new BasicDBObject("types", types)));
  633. }
  634. }
  635. public static void recalculatePoints() {
  636. DB db = MongoBase.connect();
  637. DBCollection dishes = db.getCollection("dishes");
  638. DBCursor cursor = dishes.find();
  639. DBObject o;
  640. while (cursor.hasNext()) {
  641. o = cursor.next();
  642. if (o.get("points").toString().equalsIgnoreCase("NaN") || (Float.parseFloat(o.get("points").toString())) > 0 || (o.get("reviews") != null)) {
  643. updateDishPoints(o.get("_id").toString(), dishes);
  644. }
  645. }
  646. }
  647. public static List<DBObject> findDishesForVenues(DB dataBase, List<ObjectId> venueIds, String cadena) {
  648. DBCollection coll = dataBase.getCollection("dishes");
  649. BasicDBObject q = new BasicDBObject();
  650. q.put("name", java.util.regex.Pattern.compile(cadena,
  651. Pattern.CASE_INSENSITIVE));
  652. q.put("venueId", new BasicDBObject("$in", venueIds));
  653. BasicDBObject s = new BasicDBObject();
  654. s.put("points", -1);
  655. DBCursor cursor = coll.find(q).sort(s);
  656. return cursor.toArray(MAXRESULTS);
  657. }
  658. public static List<DBObject> findDishesForVenue(DB dataBase, BasicDBObject venue, String cadena) {
  659. DBCollection coll = dataBase.getCollection("dishes");
  660. BasicDBObject q = new BasicDBObject();
  661. q.put("name", java.util.regex.Pattern.compile(cadena,
  662. Pattern.CASE_INSENSITIVE));
  663. q.put("venueId", venue.get("_id"));
  664. DBCursor cursor = coll.find(q).limit(MAXRESULTS);
  665. List<DBObject> retorno = cursor.toArray();
  666. for (DBObject dbo : retorno) {
  667. dbo.put("dis", venue.get("dis"));
  668. dbo.put("venueName", venue.get("name"));
  669. dbo.put("coordinates", venue.get("coordinates"));
  670. }
  671. return cursor.toArray(MAXRESULTS);
  672. }
  673. public static Venue findVenueById(String id) {
  674. /*
  675. * final DBObject textSearchCommand = new BasicDBObject();
  676. * textSearchCommand.put("text", "venues");
  677. * textSearchCommand.put("search", cadena); DB db = MongoBase.connect();
  678. * final CommandResult commandResult = db.command(textSearchCommand);
  679. *
  680. * return commandResult.toString();
  681. */
  682. DBCollection coll = MongoBase.connect().getCollection("venues");
  683. BasicDBObject q = new BasicDBObject();
  684. q.put("_id", new ObjectId(id));
  685. return new Venue(coll.findOne(q));
  686. }
  687. public static String findVenueIdByClientMail(String mail) {
  688. /*
  689. * final DBObject textSearchCommand = new BasicDBObject();
  690. * textSearchCommand.put("text", "venues");
  691. * textSearchCommand.put("search", cadena); DB db = MongoBase.connect();
  692. * final CommandResult commandResult = db.command(textSearchCommand);
  693. *
  694. * return commandResult.toString();
  695. */
  696. Client c=findClientByMail(mail);
  697. DBCollection coll = MongoBase.connect().getCollection("venues");
  698. BasicDBObject q = new BasicDBObject();
  699. q.put("_id", new ObjectId(c.venueId));
  700. return coll.findOne(q).get("_id").toString();
  701. }
  702. public static void deleteDish(String id) {
  703. DBCollection coll = MongoBase.connect().getCollection("dishes");
  704. BasicDBObject q = new BasicDBObject();
  705. q.put("_id", new ObjectId(id));
  706. coll.remove(q);
  707. Logger.info("Se ha borrado un plato :(");
  708. }
  709. public static void deletePub(String id) {
  710. DBCollection coll = MongoBase.connect().getCollection("publications");
  711. BasicDBObject q = new BasicDBObject();
  712. q.put("_id", new ObjectId(id));
  713. coll.remove(q);
  714. Logger.info("Se ha borrado una publicación :(");
  715. }
  716. public static void deleteVenue(String id) {
  717. DBCollection coll = MongoBase.connect().getCollection("venues");
  718. BasicDBObject q = new BasicDBObject();
  719. q.put("_id", new ObjectId(id));
  720. coll.remove(q);
  721. Logger.info("Se ha borrado una Venuelogin :(");
  722. }
  723. public static String findVenueJsonById(String id) {
  724. DBCollection coll = MongoBase.connect().getCollection("venues");
  725. BasicDBObject q = new BasicDBObject();
  726. q.put("_id", new ObjectId(id));
  727. DBObject retorno = coll.findOne(q);
  728. if (retorno == null)
  729. return null;
  730. return com.mongodb.util.JSON.serialize(retorno);
  731. }
  732. public static List<Venue> findListOfVenues(String cadena) {
  733. DBCollection coll = MongoBase.connect().getCollection("venues");
  734. BasicDBObject q = new BasicDBObject();
  735. q.put("searchName", java.util.regex.Pattern.compile(cadena)
  736. );
  737. DBCursor cursor = coll.find(q);
  738. List<Venue> retorno = new ArrayList<Venue>();
  739. while (cursor.hasNext()) {
  740. retorno.add(new Venue(cursor.next()));
  741. }
  742. return retorno;
  743. }
  744. public static List<Venue> findListOfVenuesForCity(String cadena, String location) {
  745. DBCollection coll = MongoBase.connect().getCollection("venues");
  746. BasicDBObject q = new BasicDBObject();
  747. q.put("searchName", java.util.regex.Pattern.compile(cadena));
  748. q.append("address.city", location);
  749. DBCursor cursor = coll.find(q);
  750. List<Venue> retorno = new ArrayList<Venue>();
  751. while (cursor.hasNext()) {
  752. retorno.add(new Venue(cursor.next()));
  753. }
  754. return retorno;
  755. }
  756. public static List<Venue> findListOfVenuesForProvince(String cadena, String location) {
  757. Logger.info("Search: "+cadena);
  758. DBCollection coll = MongoBase.connect().getCollection("venues");
  759. BasicDBObject q = new BasicDBObject();
  760. q.put("searchName", java.util.regex.Pattern.compile(cadena));
  761. q.append("address.province", location);
  762. DBCursor cursor = coll.find(q);
  763. List<Venue> retorno = new ArrayList<Venue>();
  764. while (cursor.hasNext()) {
  765. retorno.add(new Venue(cursor.next()));
  766. }
  767. return retorno;
  768. }
  769. public static List<Venue> findListOfVenues(String cadena, String sort, String order) {
  770. DBCollection coll = MongoBase.connect().getCollection("venues");
  771. BasicDBObject q = new BasicDBObject();
  772. q.put("searchName", java.util.regex.Pattern.compile(cadena));
  773. BasicDBObject s = new BasicDBObject();
  774. if (order.equalsIgnoreCase("-1")) {
  775. s.put(sort, -1);
  776. } else {
  777. s.put(sort, 1);
  778. }
  779. DBCursor cursor = coll.find(q).sort(s);
  780. List<Venue> retorno = new ArrayList<Venue>();
  781. while (cursor.hasNext()) {
  782. retorno.add(new Venue(cursor.next()));
  783. }
  784. return retorno;
  785. }
  786. public static List<Dish> findListOfDishes(String cadena) {
  787. DBCollection coll = MongoBase.connect().getCollection("dishes");
  788. BasicDBObject q = new BasicDBObject();
  789. q.put("name", java.util.regex.Pattern.compile(cadena,
  790. Pattern.CASE_INSENSITIVE));
  791. BasicDBObject s = new BasicDBObject();
  792. s.put("points", -1);
  793. DBCursor cursor = coll.find(q).sort(s);
  794. List<Dish> retorno = new ArrayList<Dish>();
  795. while (cursor.hasNext()) {
  796. retorno.add(new Dish(cursor.next()));
  797. }
  798. return retorno;
  799. }
  800. public static List<Dish> findListOfDishes(int max) {
  801. DBCollection coll = MongoBase.connect().getCollection("dishes");
  802. BasicDBObject s = new BasicDBObject();
  803. s.put("points", -1);
  804. DBCursor cursor = coll.find().sort(s).limit(max);
  805. List<Dish> retorno = new ArrayList<Dish>();
  806. while (cursor.hasNext()) {
  807. // System.out.println("NAME "+cursor.next().get("name"));
  808. retorno.add(new Dish(cursor.next()));
  809. }
  810. return retorno;
  811. }
  812. public static List<Dish> findListOfDishes(String cadena, String sort, String order) {
  813. DBCollection coll = MongoBase.connect().getCollection("dishes");
  814. BasicDBObject q = new BasicDBObject();
  815. q.put("name", java.util.regex.Pattern.compile(cadena,
  816. Pattern.CASE_INSENSITIVE));
  817. BasicDBObject s = new BasicDBObject();
  818. if (order.equalsIgnoreCase("-1")) {
  819. s.put(sort, -1);
  820. } else {
  821. s.put(sort, 1);
  822. }
  823. DBCursor cursor = coll.find(q).sort(s);
  824. List<Dish> retorno = new ArrayList<Dish>();
  825. while (cursor.hasNext()) {
  826. retorno.add(new Dish(cursor.next()));
  827. }
  828. return retorno;
  829. }
  830. public static String findDishesByType(List<String> tipos) {
  831. DB dataBase = MongoBase.connect();
  832. DBCollection coll = dataBase.getCollection("dishes");
  833. BasicDBObject q = new BasicDBObject();
  834. ArrayList<java.util.regex.Pattern> al = new ArrayList<java.util.regex.Pattern>();
  835. for (String tipo : tipos) {
  836. al.add(java.util.regex.Pattern.compile(tipo,
  837. Pattern.UNICODE_CASE));
  838. }
  839. q.put("types", new BasicDBObject("$all", al));
  840. BasicDBObject s = new BasicDBObject();
  841. s.put("points", -1);
  842. DBCursor cursor = coll.find(q).sort(s);
  843. return "{\"dishes\":" + com.mongodb.util.JSON.serialize(cursor.toArray(MAXRESULTS)) + "}";
  844. }
  845. public static List<Dish> findListOfDishesByType(List<String> tipos) {
  846. DB dataBase = MongoBase.connect();
  847. DBCollection coll = dataBase.getCollection("dishes");
  848. BasicDBObject q = new BasicDBObject();
  849. ArrayList<java.util.regex.Pattern> al = new ArrayList<java.util.regex.Pattern>();
  850. for (String tipo : tipos) {
  851. al.add(java.util.regex.Pattern.compile(tipo,
  852. Pattern.UNICODE_CASE));
  853. }
  854. q.put("types", new BasicDBObject("$all", al));
  855. BasicDBObject s = new BasicDBObject();
  856. s.put("points", -1);
  857. DBCursor cursor = coll.find(q).sort(s);
  858. List<DBObject> objetos = cursor.toArray(MAXRESULTS);
  859. ArrayList<Dish> retorno = new ArrayList<Dish>();
  860. int i = 0;
  861. for (DBObject o : objetos) {
  862. retorno.add(new Dish(o));
  863. }
  864. return retorno;
  865. }
  866. public static List<Dish> findListOfDishesByProvinceAndType(List<String> tipos, String province) {
  867. DB dataBase = MongoBase.connect();
  868. DBCollection coll = dataBase.getCollection("dishes");
  869. BasicDBObject q = new BasicDBObject();
  870. ArrayList<java.util.regex.Pattern> al = new ArrayList<java.util.regex.Pattern>();
  871. for (String tipo : tipos) {
  872. al.add(java.util.regex.Pattern.compile(tipo,
  873. Pattern.UNICODE_CASE));
  874. }
  875. q.put("types", new BasicDBObject("$all", al));
  876. q.append("province", province);
  877. BasicDBObject s = new BasicDBObject();
  878. s.put("points", -1);
  879. DBCursor cursor = coll.find(q).sort(s);
  880. List<DBObject> objetos = cursor.toArray(MAXRESULTS);
  881. ArrayList<Dish> retorno = new ArrayList<Dish>();
  882. int i = 0;
  883. for (DBObject o : objetos) {
  884. retorno.add(new Dish(o));
  885. }
  886. return retorno;
  887. }
  888. public static List<Dish> findListOfDishesByCityAndType(List<String> tipos, String city) {
  889. DB dataBase = MongoBase.connect();
  890. DBCollection coll = dataBase.getCollection("dishes");
  891. BasicDBObject q = new BasicDBObject();
  892. ArrayList<java.util.regex.Pattern> al = new ArrayList<java.util.regex.Pattern>();
  893. for (String tipo : tipos) {
  894. al.add(java.util.regex.Pattern.compile(tipo,
  895. Pattern.UNICODE_CASE));
  896. }
  897. q.put("types", new BasicDBObject("$all", al));
  898. q.append("city", city);
  899. BasicDBObject s = new BasicDBObject();
  900. s.put("points", -1);
  901. DBCursor cursor = coll.find(q).sort(s);
  902. List<DBObject> objetos = cursor.toArray(MAXRESULTS);
  903. ArrayList<Dish> retorno = new ArrayList<Dish>();
  904. int i = 0;
  905. for (DBObject o : objetos) {
  906. retorno.add(new Dish(o));
  907. }
  908. return retorno;
  909. }
  910. public static List<Dish> findListOfDishesByType(List<String> tipos, String sort, String order) {
  911. DB dataBase = MongoBase.connect();
  912. DBCollection coll = dataBase.getCollection("dishes");
  913. BasicDBObject q = new BasicDBObject();
  914. ArrayList<java.util.regex.Pattern> al = new ArrayList<java.util.regex.Pattern>();
  915. for (String tipo : tipos) {
  916. al.add(java.util.regex.Pattern.compile(tipo,
  917. Pattern.UNICODE_CASE));
  918. }
  919. q.put("types", new BasicDBObject("$all", al));
  920. BasicDBObject s = new BasicDBObject();
  921. if (order.equalsIgnoreCase("-1")) {
  922. s.put(sort, -1);
  923. } else {
  924. s.put(sort, 1);
  925. }
  926. DBCursor cursor = coll.find(q).sort(s);
  927. List<DBObject> objetos = cursor.toArray(MAXRESULTS);
  928. ArrayList<Dish> retorno = new ArrayList<Dish>();
  929. int i = 0;
  930. for (DBObject o : objetos) {
  931. retorno.add(new Dish(o));
  932. }
  933. return retorno;
  934. }
  935. public static String findDishes(String cadena) {
  936. DB dataBase = MongoBase.connect();
  937. DBCollection coll = dataBase.getCollection("dishes");
  938. BasicDBObject q = new BasicDBObject();
  939. q.put("name", java.util.regex.Pattern.compile(cadena,
  940. Pattern.CASE_INSENSITIVE));
  941. BasicDBObject s = new BasicDBObject();
  942. s.put("points", -1);
  943. DBCursor cursor = coll.find(q).sort(s);
  944. return "{\"dishes\":" + com.mongodb.util.JSON.serialize(cursor.toArray(MAXRESULTS)) + "}";
  945. }
  946. public static String findDishesByVenueId(String id) {
  947. DBCollection coll = MongoBase.connect().getCollection("dishes");
  948. BasicDBObject q = new BasicDBObject();
  949. q.put("venueId", new ObjectId(id));
  950. BasicDBObject s = new BasicDBObject();
  951. s.put("name", -1);
  952. DBCursor cursor = coll.find(q).sort(s);
  953. List<DBObject> retorno = cursor.toArray(MAXRESULTS);
  954. return "{\"dishes\":" + com.mongodb.util.JSON.serialize(retorno) + "}";
  955. }
  956. public static String findPublicationsByVenueId(String id) {
  957. DBCollection coll = MongoBase.connect().getCollection("publications");
  958. BasicDBObject q = new BasicDBObject();
  959. q.put("venueId", id);
  960. BasicDBObject s = new BasicDBObject();
  961. s.put("creationDate", -1);
  962. DBCursor cursor = coll.find(q).sort(s);
  963. List<DBObject> retorno = cursor.toArray(MAXRESULTS);
  964. return "{\"publications\":" + com.mongodb.util.JSON.serialize(retorno) + "}";
  965. }
  966. public static List<Dish> findListOfDishesByVenueId(String id) {
  967. DBCollection coll = MongoBase.connect().getCollection("dishes");
  968. BasicDBObject q = new BasicDBObject();
  969. q.put("venueId", new ObjectId(id));
  970. BasicDBObject s = new BasicDBObject();
  971. s.put("points", -1);
  972. DBCursor cursor = coll.find(q).sort(s);
  973. List<DBObject> objetos = cursor.toArray(MAXRESULTS);
  974. ArrayList<Dish> retorno = new ArrayList<Dish>();
  975. int i = 0;
  976. for (DBObject o : objetos) {
  977. retorno.add(new Dish(o));
  978. }
  979. return retorno;
  980. }
  981. public static List<Dish> findListOfDishesByVenueIdAndName(String id,String filter) {
  982. DBCollection coll = MongoBase.connect().getCollection("dishes");
  983. BasicDBObject q = new BasicDBObject();
  984. q.put("venueId", new ObjectId(id));
  985. q.put("name", java.util.regex.Pattern.compile(filter,
  986. Pattern.CASE_INSENSITIVE));
  987. BasicDBObject s = new BasicDBObject();
  988. s.put("points", -1);
  989. DBCursor cursor = coll.find(q).sort(s);
  990. List<DBObject> objetos = cursor.toArray(MAXRESULTS);
  991. ArrayList<Dish> retorno = new ArrayList<Dish>();
  992. int i = 0;
  993. for (DBObject o : objetos) {
  994. retorno.add(new Dish(o));
  995. }
  996. return retorno;
  997. }
  998. public static List<Dish> findListOfDishesByVenueId(String id,String sort, String order) {
  999. DBCollection coll = MongoBase.connect().getCollection("dishes");
  1000. BasicDBObject q = new BasicDBObject();
  1001. q.put("venueId", new ObjectId(id));
  1002. BasicDBObject s = new BasicDBObject();
  1003. if (order.equalsIgnoreCase("-1")) {
  1004. s.put("sort", -1);}
  1005. else{
  1006. s.put(sort, 1);
  1007. }
  1008. DBCursor cursor = coll.find(q).sort(s);
  1009. List<DBObject> objetos = cursor.toArray(MAXRESULTS);
  1010. ArrayList<Dish> retorno = new ArrayList<Dish>();
  1011. for (DBObject o : objetos) {
  1012. retorno.add(new Dish(o));
  1013. }
  1014. return retorno;
  1015. }
  1016. public static List<Publication> findListOfPublicationsByVenueId(String id) {
  1017. DBCollection coll = MongoBase.connect().getCollection("publications");
  1018. BasicDBObject q = new BasicDBObject();
  1019. q.put("venueId", id);
  1020. DBCursor cursor = coll.find(q);
  1021. List<DBObject> objetos = cursor.toArray(MAXRESULTS);
  1022. ArrayList<Publication> retorno = new ArrayList<Publication>();
  1023. for (DBObject o : objetos) {
  1024. retorno.add(new Publication(o));
  1025. }
  1026. return retorno;
  1027. }
  1028. public static List<Publication> findListOfPublicationsByVenueIdAndTitle(String id,String filter) {
  1029. DBCollection coll = MongoBase.connect().getCollection("publications");
  1030. BasicDBObject q = new BasicDBObject();
  1031. q.put("venueId", id);
  1032. q.put("title", java.util.regex.Pattern.compile(filter,
  1033. Pattern.CASE_INSENSITIVE));
  1034. DBCursor cursor = coll.find(q);
  1035. List<DBObject> objetos = cursor.toArray(MAXRESULTS);
  1036. ArrayList<Publication> retorno = new ArrayList<Publication>();
  1037. for (DBObject o : objetos) {
  1038. retorno.add(new Publication(o));
  1039. }
  1040. return retorno;
  1041. }
  1042. public static List<Publication> findListOfPublicationsByVenueId(String id,String sort, String order) {
  1043. DBCollection coll = MongoBase.connect().getCollection("publications");
  1044. BasicDBObject q = new BasicDBObject();
  1045. q.put("venueId", id);
  1046. BasicDBObject s = new BasicDBObject();
  1047. if (order.equalsIgnoreCase("-1")) {
  1048. s.put("sort", -1);}
  1049. else{
  1050. s.put(sort, 1);
  1051. }
  1052. DBCursor cursor = coll.find(q).sort(s);
  1053. List<DBObject> objetos = cursor.toArray(MAXRESULTS);
  1054. ArrayList<Publication> retorno = new ArrayList<Publication>();
  1055. for (DBObject o : objetos) {
  1056. retorno.add(new Publication(o));
  1057. }
  1058. return retorno;
  1059. }
  1060. public static Dish findDishById(String id) {
  1061. DBCollection coll = MongoBase.connect().getCollection("dishes");
  1062. BasicDBObject q = new BasicDBObject();
  1063. q.put("_id", new ObjectId(id));
  1064. DBObject obj = coll.findOne(q);
  1065. Dish d = new Dish(obj);
  1066. return d;
  1067. }
  1068. public static Publication findPublicationById(String id) {
  1069. DBCollection coll = MongoBase.connect().getCollection("publications");
  1070. BasicDBObject q = new BasicDBObject();
  1071. q.put("_id", new ObjectId(id));
  1072. DBObject obj = coll.findOne(q);
  1073. Publication p = new Publication(obj);
  1074. return p;
  1075. }
  1076. public static String findDishJSONById(String id) {
  1077. DBCollection coll = MongoBase.connect().getCollection("dishes");
  1078. BasicDBObject q = new BasicDBObject();
  1079. q.put("_id", new ObjectId(id));
  1080. DBObject retorno = coll.findOne(q);
  1081. if (retorno == null)
  1082. return null;
  1083. return com.mongodb.util.JSON.serialize(retorno);
  1084. }
  1085. public static boolean updateDish(Dish d) {
  1086. DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
  1087. d.modified = df.format(new Date());
  1088. BasicDBObject doc = d.toDBO();
  1089. DBCollection coll = MongoBase.connect().getCollection("dishes");
  1090. WriteResult resultado = coll.update(new BasicDBObject().append("_id", new ObjectId(d.oid.toString())), doc);
  1091. Logger.info(resultado.toString());
  1092. if (resultado.getError() != null) {
  1093. Logger.error(resultado.getError());
  1094. return false;
  1095. }
  1096. Logger.info("Editado dish desde la web: " + d.name);
  1097. return true;
  1098. }
  1099. public static boolean updatePublication(Publication p) {
  1100. DBObject doc = p.toDBO();
  1101. DBCollection coll = MongoBase.connect().getCollection("publications");
  1102. WriteResult resultado = coll.update(new BasicDBObject().append("_id", new ObjectId(p.pubId.toString())), doc);
  1103. Logger.info(resultado.toString());
  1104. if (resultado.getError() != null) {
  1105. Logger.error(resultado.getError());
  1106. return false;
  1107. }
  1108. Logger.info("Editado dish desde la web: " + p.title);
  1109. return true;
  1110. }
  1111. public static boolean updateUser(User user) {
  1112. DBObject doc;
  1113. if (user.password != null && !user.password.equalsIgnoreCase("")) {
  1114. try {
  1115. String salt = RandomString.getRandomString(10);
  1116. user.password = Cripto.encrypt(user.password, salt);
  1117. doc = user.toUpdateDBO();
  1118. doc.put("salt", salt);
  1119. Logger.info("password encriptado: " + user.password);
  1120. } catch (Exception e) {
  1121. Logger.error(e.getMessage());
  1122. return false;
  1123. }
  1124. } else {
  1125. doc = user.toUpdateDBO();
  1126. }
  1127. DBCollection coll = MongoBase.connect().getCollection("users");
  1128. BasicDBObject set = new BasicDBObject("$set", doc);
  1129. WriteResult resultado = coll.update(new BasicDBObject().append("_id", new ObjectId(user._id.toString())), set);
  1130. Logger.info(resultado.toString());
  1131. if (resultado.getError() != null) {
  1132. Logger.error(resultado.getError());
  1133. return false;
  1134. }
  1135. Logger.info("Editado usuario: " + user.mail);
  1136. return true;
  1137. }
  1138. public static boolean updateClient(Client client) {
  1139. DBObject doc;
  1140. if (client.getPassword() != null && !client.getPassword().equalsIgnoreCase("")) {
  1141. try {
  1142. String salt = RandomString.getRandomString(10);
  1143. client.setPassword( Cripto.encrypt(client.getPassword(), salt));
  1144. doc = client.toDBO();
  1145. doc.put("salt", salt);
  1146. } catch (Exception e) {
  1147. Logger.error(e.getMessage());
  1148. return false;
  1149. }
  1150. } else {
  1151. doc = client.toDBO();
  1152. }
  1153. DBCollection coll = MongoBase.connect().getCollection("clients");
  1154. BasicDBObject set = new BasicDBObject("$set", doc);
  1155. WriteResult resultado = coll.update(new BasicDBObject().append("mail", client.getMail()), set);
  1156. Logger.info(resultado.toString());
  1157. if (resultado.getError() != null) {
  1158. Logger.error(resultado.getError());
  1159. return false;
  1160. }
  1161. return true;
  1162. }
  1163. public static boolean updateClientPassword(String mail,String newPassword) {
  1164. DBObject doc=new BasicDBObject();
  1165. String encPass;
  1166. if (newPassword != null && !newPassword.equalsIgnoreCase("")) {
  1167. try {
  1168. String salt = RandomString.getRandomString(10);
  1169. encPass= Cripto.encrypt(newPassword, salt);
  1170. doc.put("password",encPass);
  1171. doc.put("salt", salt);
  1172. } catch (Exception e) {
  1173. Logger.error(e.getMessage());
  1174. return false;
  1175. }
  1176. } else {
  1177. return false;
  1178. }
  1179. DBCollection coll = MongoBase.connect().getCollection("clients");
  1180. BasicDBObject set = new BasicDBObject("$set", doc);
  1181. WriteResult resultado = coll.update(new BasicDBObject().append("mail", mail), set);
  1182. Logger.info(resultado.toString());
  1183. if (resultado.getError() != null) {
  1184. Logger.error(resultado.getError());
  1185. return false;
  1186. }
  1187. return true;
  1188. }
  1189. public static String findMoreVenues(String cadena, String intento) {
  1190. /*
  1191. * final DBObject textSearchCommand = new BasicDBObject();
  1192. * textSearchCommand.put("text", "venues");
  1193. * textSearchCommand.put("search", cadena); DB db = MongoBase.connect();
  1194. * final CommandResult commandResult = db.command(textSearchCommand);
  1195. *
  1196. * return commandResult.toString();
  1197. */
  1198. DBCollection coll = MongoBase.connect().getCollection("venues");
  1199. BasicDBObject q = new BasicDBObject();
  1200. q.put("name", java.util.regex.Pattern.compile("" + cadena + ""));
  1201. DBCursor cursor = coll.find(q);
  1202. cursor.skip(MAXRESULTS * Integer.parseInt(intento));
  1203. List<DBObject> retorno = cursor.toArray(20);
  1204. return "{\"venues\":" + com.mongodb.util.JSON.serialize(retorno) + "}";
  1205. }
  1206. public static boolean insertVenue(Venue v) {
  1207. DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
  1208. v.date = df.format(new Date());
  1209. v.photoURLs = removeNulls(v.photoURLs);
  1210. v.searchName=removeTildes(v.name).toLowerCase();
  1211. BasicDBObject doc = v.toDBO();
  1212. doc.put("followers", new String[]{});
  1213. ObjectId oid = new ObjectId();
  1214. v.oid = oid;
  1215. doc.append("_id", oid);
  1216. doc.put("numFollowers", 0);
  1217. DBCollection coll = MongoBase.connect().getCollection("venues");
  1218. WriteResult resultado = coll.insert(doc);
  1219. if (resultado.getError() != null) {
  1220. Logger.error(resultado.getError());
  1221. return false;
  1222. }
  1223. addNewFeed(new Feed(v));
  1224. Logger.info("Insertada nueva Venue desde la web: " + v.name);
  1225. return true;
  1226. }
  1227. public static boolean insertVenuesXML() {
  1228. final int NAME = 0;
  1229. final int ADDRESS = 1;
  1230. final int CITY = 2;
  1231. final int POSTAL_CODE = 4;
  1232. final int BAJA = 8;
  1233. final int SUB_ACTIVITY = 12;
  1234. int noCoordCount=0;
  1235. int duplicateCount=0;
  1236. int processedCount=0;
  1237. int googleErrorsCount=0;
  1238. int venuesInserted=0;
  1239. int numeroDeNombresCambiados=0; //con este contador veremos a cuantos nombres le hemos añadido el prefijo "sidrería" o "cafetería"
  1240. DBCollection coll = MongoBase.connect().getCollection("venues");
  1241. DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
  1242. BasicDBObject doc;
  1243. FileInputStream file;
  1244. HSSFWorkbook workbook;
  1245. try {
  1246. file = new FileInputStream(new File("./Establecimientos.xls"));
  1247. //Create Workbook instance holding reference to .xlsx file
  1248. workbook = new HSSFWorkbook(file);
  1249. //Get first/desired sheet from the workbook
  1250. } catch (Exception e) {
  1251. e.printStackTrace();
  1252. return false;
  1253. }
  1254. HSSFSheet sheet = workbook.getSheetAt(0);
  1255. //Iterate through each rows one by one
  1256. Iterator<Row> rowIterator = sheet.iterator();
  1257. Venue venue;
  1258. while (rowIterator.hasNext()) {
  1259. Logger.info("Venues procesadas hasta ahora: "+processedCount);
  1260. Logger.info("Venues insertadas hasta ahora: "+venuesInserted);
  1261. Logger.info("Coordenadas no encontradas hasta ahora "+noCoordCount);
  1262. Logger.info("Errores de GOOGLE "+googleErrorsCount);
  1263. Logger.info("Venues duplicadas hasta ahora "+duplicateCount);
  1264. Logger.info("------------------------------------------------");
  1265. Row row = rowIterator.next();
  1266. processedCount++;
  1267. if (row.getCell(BAJA).getStringCellValue().length() == 0) {
  1268. venue = new Venue();
  1269. //recogemos el nombre y le damos el formato adecuado
  1270. venue.name = row.getCell(NAME).getStringCellValue();
  1271. if (venue.name.contains(", ")) {
  1272. String partes[] = venue.name.split(", ");
  1273. venue.name = partes[1] + " " + partes[0];
  1274. } else if (venue.name.contains(" ,")) {
  1275. String partes[] = venue.name.split(" ,");
  1276. venue.name = partes[1] + " " + partes[0];
  1277. }
  1278. venue.name=WordUtils.capitalizeFully(venue.name);
  1279. if(venue.name.startsWith(" ")){
  1280. venue.name=venue.name.substring(1);
  1281. }
  1282. if(venue.name.endsWith(" ")){
  1283. venue.name=venue.name.substring(0,venue.name.length()-1);
  1284. }
  1285. venue.searchName=venue.searchName.replaceAll("\\+", " ");
  1286. //guardamos el nombre de búsqueda (sin tildes)
  1287. venue.searchName=removeTildes(venue.name).toLowerCase();
  1288. //recogemos ciudad y dirección
  1289. if (row.getCell(CITY).getStringCellValue().length() < 1) {
  1290. venue.address.city = row.getCell(CITY + 1).getStringCellValue();
  1291. } else {
  1292. venue.address.city = WordUtils.capitalizeFully(row.getCell(CITY).getStringCellValue());
  1293. }
  1294. venue.address.street = row.getCell(ADDRESS).getStringCellValue().toLowerCase();
  1295. ////comprobamos que la venue no existe ya en la base de datos
  1296. if(venueExists(venue)){
  1297. duplicateCount++;
  1298. continue;
  1299. }
  1300. venue.insertedBy="toptasting";
  1301. //damos formato a la dirección y buscamos las coordenadas
  1302. String direccionFormateada = venue.address.street.replaceAll(" ", "+");
  1303. direccionFormateada += "+," + venue.address.city.replaceAll(" ", "+");
  1304. final Geocoder geocoder = new Geocoder();
  1305. GeocoderRequest geocoderRequest = new GeocoderRequestBuilder().setAddress("calle+" + direccionFormateada + "+,Asturias").setRegion("es").setLanguage("es").getGeocoderRequest();
  1306. int numIntentos=0;
  1307. boolean geocodingSucces=false;
  1308. GeocodeResponse geocoderResponse=null;
  1309. while(geocodingSucces!=true){
  1310. try{
  1311. numIntentos++;
  1312. geocoderResponse = geocoder.geocode(geocoderRequest);
  1313. geocodingSucces=true;
  1314. }
  1315. catch(NullPointerException npe){
  1316. Logger.error("Error accediendo a google geocoder: intento número "+numIntentos);
  1317. if(numIntentos>4){
  1318. geocodingSucces=true;
  1319. geocoderResponse=null;
  1320. }
  1321. Logger.error("NOS RENDIMOS... GOOGLE GO HOME, YOU ARE DRUNK");
  1322. googleErrorsCount++;
  1323. continue;
  1324. }
  1325. }
  1326. //if geocoderResponse==null es que la búsqueda no tuvo éxito y tenemos que pasar a la siguiente venue
  1327. if(geocoderResponse==null){
  1328. noCoordCount++;
  1329. continue;
  1330. }
  1331. if (geocoderResponse.getResults().size() > 0) {
  1332. LatLng ll = geocoderResponse.getResults().get(0).getGeometry().getLocation();
  1333. venue.coordinates = new double[]{ll.getLat().doubleValue(), ll.getLng().doubleValue()};
  1334. //comprobamos que las coordenadas devueltas están en los márgenes conocidos de asturias
  1335. if(venue.coordinates[0]>43.7||venue.coordinates[0]<42.8){
  1336. noCoordCount++;
  1337. continue;
  1338. }else if((venue.coordinates[1]>-4.51)||(venue.coordinates[1]<-7.184)){
  1339. noCoordCount++;
  1340. continue;
  1341. }
  1342. }else{
  1343. googleErrorsCount++;
  1344. continue;
  1345. }
  1346. venue.address.postalCode = row.getCell(POSTAL_CODE).getStringCellValue();
  1347. venue.address.province = "Asturias";
  1348. venue.types.add("Restaurante");
  1349. String subActivity = row.getCell(SUB_ACTIVITY).getStringCellValue();
  1350. if (subActivity != null && subActivity.length() > 0) {
  1351. venue.types.add(subActivity.toLowerCase());
  1352. if(StringUtils.countMatches(venue.name," ")<1){
  1353. venue.name=WordUtils.capitalize(subActivity)+" "+venue.name;
  1354. numeroDeNombresCambiados++;
  1355. Logger.info("número de nombres cambiados: "+numeroDeNombresCambiados);
  1356. }
  1357. }
  1358. venue.name=WordUtils.capitalizeFully(venue.name);
  1359. venue.date = df.format(new Date());
  1360. venue.photoURLs = removeNulls(venue.photoURLs);
  1361. doc = venue.toDBO();
  1362. doc.put("numFollowers", 0);
  1363. WriteResult resultado = coll.insert(doc);
  1364. if (resultado.getError() != null) {
  1365. Logger.error(resultado.getError());
  1366. return false;
  1367. }
  1368. venuesInserted++;
  1369. Logger.info("Insertada nueva Venue " + venue.name);
  1370. }
  1371. }
  1372. Logger.info("TOTAL número de nombres cambiados: "+numeroDeNombresCambiados);
  1373. Logger.info("TOTAL venues procesadas: "+processedCount);
  1374. Logger.info("TOTAL errores Google: "+googleErrorsCount);
  1375. Logger.info("TOTAL coordenadas no encontradas: "+noCoordCount);
  1376. Logger.info("TOTAL venues duplicadas: "+duplicateCount);
  1377. try{
  1378. file.close();
  1379. }catch(IOException ex){
  1380. ex.printStackTrace();
  1381. }
  1382. return true;
  1383. }
  1384. private static boolean venueExists(Venue venue) {
  1385. Logger.info(venue.searchName+" "+venue.address.city.toLowerCase());
  1386. List<Venue> listaVenues=findListOfVenuesForCity(venue.searchName,venue.address.city.toLowerCase());
  1387. for(Venue v:listaVenues){
  1388. Logger.info(v.searchName+" "+v.address.city);
  1389. if(v.searchName.equalsIgnoreCase(venue.searchName)&&venue.address.city.equalsIgnoreCase(v.address.city)){
  1390. return true;
  1391. }
  1392. }
  1393. return false;
  1394. }
  1395. public static String insertVenueByProvinceAndName(Venue v) {
  1396. DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
  1397. v.date = df.format(new Date());
  1398. BasicDBObject doc = v.toDBO();
  1399. ObjectId oid = new ObjectId();
  1400. v.oid = oid;
  1401. v.searchName=removeTildes(v.name).toLowerCase();
  1402. doc.append("_id", oid);
  1403. DBCollection coll = MongoBase.connect().getCollection("venues");
  1404. WriteResult resultado = coll.insert(doc);
  1405. if (resultado.getError() != null) {
  1406. Logger.error(resultado.getError());
  1407. return null;
  1408. }
  1409. addNewFeed(new Feed(v));
  1410. Logger.info("Insertada nueva Venue desde la web: " + v.name);
  1411. return v.oid.toString();
  1412. }
  1413. public static boolean updateVenue(Venue v) {
  1414. DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
  1415. v.modified = df.format(new Date());
  1416. v.photoURLs = removeNulls(v.photoURLs);
  1417. v.searchName=removeTildes(v.name).toLowerCase();
  1418. BasicDBObject doc = v.toDBO();
  1419. DBCollection coll = MongoBase.connect().getCollection("venues");
  1420. WriteResult resultado = coll.update(new BasicDBObject().append("_id", new ObjectId(v.oid.toString())), doc);
  1421. Logger.info(resultado.toString());
  1422. if (resultado.getError() != null) {
  1423. Logger.error(resultado.getError());
  1424. return false;
  1425. }
  1426. Logger.info("Editada venue desde la web: " + v.name);
  1427. return true;
  1428. }
  1429. public static String insertVenueOnLocation(Venue v) {
  1430. BasicDBObject doc = v.toDBO();
  1431. DBCollection coll = MongoBase.connect().getCollection("venues");
  1432. ObjectId oid = new ObjectId();
  1433. v.oid = oid;
  1434. v.searchName=removeTildes(v.name).toLowerCase();
  1435. doc.append("_id", oid);
  1436. WriteResult resultado = coll.insert(doc);
  1437. if (resultado.getError() != null) {
  1438. Logger.error(resultado.getError());
  1439. return null;
  1440. }
  1441. addNewFeed(new Feed(v));
  1442. Logger.info("Insertada nueva Venue desde la app: " + v.name);
  1443. return oid.toString();
  1444. }
  1445. public static String insertVenueByName(String name) {
  1446. Venue venue = new Venue();
  1447. venue.name = name;
  1448. venue.searchName=removeTildes(name).toLowerCase();
  1449. venue.photoURLs = new String[]{"http://toptasting.s3.amazonaws.com/sinImagenVenue.png"};
  1450. BasicDBObject doc = venue.toDBO();
  1451. ObjectId oid = new ObjectId();
  1452. doc.append("_id", oid);
  1453. DBCollection coll = MongoBase.connect().getCollection("venues");
  1454. WriteResult resultado = coll.insert(doc);
  1455. if (resultado.getError() != null) {
  1456. Logger.error("Error insertando venue " + name);
  1457. Logger.error(resultado.getError());
  1458. return null;
  1459. }
  1460. Logger.info("Insertada nueva Venue: " + name);
  1461. return oid.toString();
  1462. }
  1463. public static String insertDish(Dish dish) {
  1464. DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
  1465. BasicDBObject doc = dish.toDBO();
  1466. ObjectId dishId = new ObjectId();
  1467. doc.append("_id", dishId);
  1468. doc.append("date", df.format(new Date()));
  1469. doc.put("followers", new String[]{});
  1470. DBCollection coll = MongoBase.connect().getCollection("dishes");
  1471. WriteResult resultado = coll.insert(doc);
  1472. if (resultado.getError() != null) {
  1473. Logger.error("Error insertando dish " + dish.name);
  1474. Logger.error(resultado.getError());
  1475. return null;
  1476. }
  1477. Logger.info("Insertado nuevo Plato: " + dish.name);
  1478. return dishId.toString();
  1479. }
  1480. /*public static String insertDish(String name, String venueId) {
  1481. Dish dish = new Dish();
  1482. dish.name = name;
  1483. dish.venueId = new ObjectId(venueId);
  1484. dish.photoURL = "https://s3-eu-west-1.amazonaws.com/toptastingimages/dishes/sinimagen.gif";
  1485. BasicDBObject doc = dish.toDBO();
  1486. ObjectId dishId = new ObjectId();
  1487. doc.append("_id", dishId);
  1488. DBCollection coll = MongoBase.connect().getCollection("dishes");
  1489. WriteResult resultado = coll.insert(doc);
  1490. if (resultado.getError() != null) {
  1491. Logger.error("Error insertando dish " + name);
  1492. Logger.error(resultado.getError());
  1493. return null;
  1494. }
  1495. Logger.info("Insertado nuevo Plato: " + name);
  1496. return dishId.toString();
  1497. }*/
  1498. public static boolean insertReview(Review review, String dishId) {
  1499. //obtenemos la photo del usuario que realiza la review
  1500. String userPhotoURL = getUserPhotoURL(review.userId.toString());
  1501. review.setUserPhotoURL(userPhotoURL);
  1502. // conectamos
  1503. DBCollection coll = MongoBase.connect().getCollection("dishes");
  1504. // creamos la query para dar con el plato y la review correctas
  1505. BasicDBObject query = new BasicDBObject();
  1506. query.append("_id", new ObjectId(dishId));
  1507. Dish d=new Dish(coll.findOne(query));
  1508. updateUserPoints(review, d, coll);
  1509. query.append("reviews.userId", review.userId);
  1510. // creamos el update
  1511. BasicDBObject update = new BasicDBObject();
  1512. update.put("$set", new BasicDBObject("reviews.$", review.toDBO()));
  1513. // hacemos el update
  1514. WriteResult resultado = coll.update(query, update, false, false);
  1515. if (resultado.getError() != null) {
  1516. Logger.error("Error insertando review por el usuario "
  1517. + review.user);
  1518. Logger.error(resultado.getError());
  1519. return false;
  1520. }
  1521. //SI n no es 1, es que no se actualizó nada y entonces tenemos que insertar la review
  1522. if (resultado.getN() < 1) {
  1523. query = new BasicDBObject("_id", new ObjectId(dishId));
  1524. update = new BasicDBObject("$push", new BasicDBObject("reviews", review.toDBO()));
  1525. resultado = coll.update(query, update, true, true);
  1526. }
  1527. else{
  1528. Logger.info("Review actualizada");
  1529. }
  1530. if (resultado.getError() != null) {
  1531. Logger.error("Error insertando review por el usuario "
  1532. + review.user);
  1533. Logger.error(resultado.getError());
  1534. return false;
  1535. }
  1536. updateDishPoints(dishId, coll);
  1537. Logger.info(review.user + " has submitted a new Review!");
  1538. //addNewFeed(new Feed(review, dishId));
  1539. Application.sendNotification(new Notification(review.date, Notification.TYPE.REVIEW, review.toJson()), findUserFollowers(review.userId.toString()));
  1540. return true;
  1541. }
  1542. private static void updateUserPoints(Review review,Dish dish,DBCollection coll) {
  1543. DBCollection users = MongoBase.connect().getCollection("users");
  1544. BasicDBObject q = new BasicDBObject();
  1545. q.put("_id", review.userId);
  1546. DBObject obj = users.findOne(q);
  1547. User user = new User(obj);
  1548. if(user.reviewedDishes.contains(dish.oid.toString())){
  1549. review.repeated=true;
  1550. }
  1551. if(!user.reviewedVenues.contains(dish.venueId.toString())){
  1552. review.firstTimeInVenue=true;
  1553. }
  1554. if(dish.reviews==null||dish.reviews.size()==0){
  1555. review.firstReviewInDish=true;
  1556. }
  1557. BasicDBObject query = new BasicDBObject();
  1558. query.append("venueId", dish.venueId);
  1559. query.append("review", new BasicDBObject("$exists",true).append("$ne",null));
  1560. DBCursor c =coll.find(query);
  1561. if(!c.hasNext()){
  1562. review.firstReviewInVenue=true;
  1563. }
  1564. int points=calculateReviewPoints(review);
  1565. q = new BasicDBObject();
  1566. BasicDBObject u = new BasicDBObject();
  1567. q.put("_id", user._id);
  1568. u.put("$inc", new BasicDBObject().append("points", points));
  1569. if(review.firstTimeInVenue){
  1570. u.append("$push", new BasicDBObject("reviewedVenues", dish.venueId.toString()));
  1571. }
  1572. if(!review.repeated){
  1573. u.append("$push", new BasicDBObject("reviewedDishes", dish.oid.toString()));
  1574. }
  1575. users.update(q, u);
  1576. Logger.info("Actualizando puntos de usuario. Incremento de " +points);
  1577. Logger.info(review.getJsonPoints());
  1578. }
  1579. private static int calculateReviewPoints(Review review) {
  1580. int points=1;
  1581. if(review.repeated){
  1582. return points;
  1583. }
  1584. if(review.firstReviewInDish){
  1585. points++;
  1586. }
  1587. if(review.firstReviewInVenue){
  1588. points++;
  1589. }
  1590. if(review.firstTimeInVenue){
  1591. points++;
  1592. }
  1593. if(!review.photoURL.equalsIgnoreCase("http://toptasting.s3.amazonaws.com/sinImagenDish.png")){
  1594. points++;
  1595. }
  1596. if(review.description!=null&&review.description.length()>5){
  1597. points++;
  1598. }
  1599. return points;
  1600. }
  1601. public static String findReviewsByUserId(ObjectId userId) {
  1602. // conectamos
  1603. DBCollection coll = MongoBase.connect().getCollection("dishes");
  1604. // creamos la query para dar con el usuario
  1605. BasicDBObject query = new BasicDBObject();
  1606. query.put("reviews.userId", userId);
  1607. // hacemos la busqueda
  1608. DBCursor cursor = coll.find(query, new BasicDBObject("reviews.$", 1).append("venueName", 1).append("name", 1));
  1609. if (cursor == null) {
  1610. Logger.error("No se han encontrado reviews para el usuario"
  1611. );
  1612. return "";
  1613. }
  1614. BasicDBList reviews;
  1615. BasicDBObject review;
  1616. for (DBObject dbo : cursor) {
  1617. //ñapa para cambiar los ObjectId a String
  1618. dbo.put("_id", ((ObjectId) dbo.get("_id")).toString());
  1619. reviews = (BasicDBList) dbo.get("reviews");
  1620. review = (BasicDBObject) reviews.get(0);
  1621. review.put("userId", ((ObjectId) review.get("userId")).toString());
  1622. reviews.clear();
  1623. reviews.add(review);
  1624. dbo.put("reviews", reviews);
  1625. }
  1626. return "{\"dishes\":" + com.mongodb.util.JSON.serialize(cursor.toArray()) + "}";
  1627. }
  1628. public static String findDrafts(ObjectId userId) {
  1629. // conectamos
  1630. DBCollection coll = MongoBase.connect().getCollection("users");
  1631. // creamos la query para dar con el usuario
  1632. BasicDBObject query = new BasicDBObject();
  1633. query.put("_id", userId);
  1634. // hacemos la busqueda
  1635. DBObject user = coll.findOne(query);
  1636. if (user == null) {
  1637. Logger.error("No se ha encontrado un usuario buscando sus drafts"
  1638. );
  1639. return "";
  1640. }
  1641. if (user.containsField("drafts")) {
  1642. List<Object> retorno = (List<Object>) user.get("drafts");
  1643. return "{\"drafts\":" + com.mongodb.util.JSON.serialize(retorno) + "}";
  1644. }
  1645. return "{\"drafts\":[] }";
  1646. }
  1647. public static boolean insertDraft(Draft draft) {
  1648. // conectamos
  1649. DBCollection coll = MongoBase.connect().getCollection("users");
  1650. // creamos la query para dar con el plato correcto
  1651. BasicDBObject query = new BasicDBObject();
  1652. query.put("_id", draft.userId);
  1653. // creamos el update
  1654. BasicDBObject update = new BasicDBObject();
  1655. update.put("$push", new BasicDBObject("drafts", draft.toDBO()));
  1656. // hacemos el update
  1657. WriteResult resultado = coll.update(query, update, true, true);
  1658. if (resultado.getError() != null) {
  1659. Logger.error("Error insertando draft por el usuario "
  1660. + draft.user);
  1661. Logger.error(resultado.getError());
  1662. return false;
  1663. }
  1664. Logger.info(draft.user + " ha creado un Draft");
  1665. return true;
  1666. }
  1667. public static boolean completeDraft(Review review, String dishId) {
  1668. // conectamos
  1669. DB db = MongoBase.connect();
  1670. DBCollection coll = db.getCollection("dishes");
  1671. // creamos la query para dar con el plato correcto
  1672. BasicDBObject query = new BasicDBObject();
  1673. query.put("_id", new ObjectId(dishId));
  1674. // creamos el update
  1675. BasicDBObject update = new BasicDBObject();
  1676. update.put("$push", new BasicDBObject("reviews", review.toDBO()));
  1677. // hacemos el update
  1678. WriteResult resultado = coll.update(query, update, true, true);
  1679. if (resultado.getError() != null) {
  1680. Logger.error("Error insertando review por el usuario "
  1681. + review.user);
  1682. Logger.error(resultado.getError());
  1683. return false;
  1684. }
  1685. Logger.info(review.user + " a completado un Draft");
  1686. updateDishPoints(dishId, coll);
  1687. addNewFeed(new Feed(review, dishId));
  1688. deleteDraft(db, review.userId, new ObjectId(dishId));
  1689. return true;
  1690. }
  1691. public static boolean deleteDraft(DB db, ObjectId userId, ObjectId dishId) {
  1692. // conectamos
  1693. DBCollection coll = db.getCollection("users");
  1694. // creamos la query para dar con el plato correcto
  1695. BasicDBObject query = new BasicDBObject();
  1696. query.put("_id", userId);
  1697. // creamos el update
  1698. BasicDBObject update = new BasicDBObject();
  1699. update.put("$pull", new BasicDBObject("drafts", new BasicDBObject().append("dishId", dishId)));
  1700. // hacemos el update
  1701. WriteResult resultado = coll.update(query, update, true, true);
  1702. if (resultado.getError() != null) {
  1703. Logger.error("Error borrando un draft");
  1704. Logger.error(resultado.getError());
  1705. return false;
  1706. }
  1707. Logger.info("Eliminado uni draft ");
  1708. return true;
  1709. }
  1710. public static String getUserPhotoURL(String userId) {
  1711. DBCollection coll = MongoBase.connect().getCollection("users");
  1712. BasicDBObject q = new BasicDBObject();
  1713. Logger.info("USER ID (getPhotoURL): "+userId);
  1714. q.put("_id", new ObjectId(userId));
  1715. DBObject obj = coll.findOne(q);
  1716. if (obj.get("photoURL") != null) {
  1717. return obj.get("photoURL").toString();
  1718. }
  1719. return null;
  1720. }
  1721. public static String getUserPhotoURL(String userId, DBCollection coll) {
  1722. coll = MongoBase.connect().getCollection("users");
  1723. BasicDBObject q = new BasicDBObject();
  1724. q.put("_id", new ObjectId(userId));
  1725. DBObject obj = coll.findOne(q);
  1726. if (obj.get("photoURL") != null) {
  1727. return obj.get("photoURL").toString();
  1728. }
  1729. return null;
  1730. }
  1731. public static boolean deleteDraft(ObjectId userId, ObjectId dishId) {
  1732. // conectamos
  1733. DB db = MongoBase.connect();
  1734. DBCollection coll = db.getCollection("users");
  1735. // creamos la query para dar con el plato correcto
  1736. BasicDBObject query = new BasicDBObject();
  1737. query.put("_id", userId);
  1738. // creamos el update
  1739. BasicDBObject update = new BasicDBObject();
  1740. update.put("$pull", new BasicDBObject("drafts", new BasicDBObject().append("dishId", dishId)));
  1741. // hacemos el update
  1742. WriteResult resultado = coll.update(query, update, true, true);
  1743. if (resultado.getError() != null) {
  1744. Logger.error("Error borrando un draft");
  1745. Logger.error(resultado.getError());
  1746. return false;
  1747. }
  1748. Logger.info("Eliminado un draft ");
  1749. return true;
  1750. }
  1751. public static boolean deleteReview(String userId, String dishId) {
  1752. // conectamos
  1753. DB db = MongoBase.connect();
  1754. DBCollection coll = db.getCollection("dishes");
  1755. Logger.debug("userId: " + userId + " --- dishId: " + dishId);
  1756. // creamos la query para dar con el plato correcto
  1757. BasicDBObject query = new BasicDBObject();
  1758. query.put("_id", new ObjectId(dishId));
  1759. // creamos el update
  1760. BasicDBObject update = new BasicDBObject();
  1761. update.put("$pull", new BasicDBObject("reviews", new BasicDBObject().append("userId", new ObjectId(userId))));
  1762. // hacemos el update
  1763. WriteResult resultado = coll.update(query, update, true, true);
  1764. if (resultado.getError() != null) {
  1765. Logger.error("Error borrando un review");
  1766. Logger.error(resultado.getError());
  1767. return false;
  1768. }
  1769. updateDishPoints(dishId, coll);
  1770. Logger.info("Eliminada una review ");
  1771. return true;
  1772. }
  1773. public static String generateValidationCode(int lenght) {
  1774. RandomString rs = new RandomString(lenght);
  1775. String code = rs.nextString();
  1776. BasicDBObject doc = new BasicDBObject("Code", code);
  1777. DBCollection coll = MongoBase.connect().getCollection("valCodes");
  1778. WriteResult resultado = coll.insert(doc);
  1779. if (resultado.getError() != null) {
  1780. Logger.error(resultado.getError());
  1781. return null;
  1782. }
  1783. Logger.info("Se ha generado un nuevo código de registro");
  1784. return code;
  1785. }
  1786. public static String[] removeNulls(String cadena[]) {
  1787. List<String> list = new ArrayList<String>();
  1788. for (String s : cadena) {
  1789. if (s != null && s.length() > 0) {
  1790. list.add(s);
  1791. }
  1792. }
  1793. return list.toArray(new String[list.size()]);
  1794. }
  1795. public static String findVenueNameById(String venueId) {
  1796. DBCollection coll = MongoBase.connect().getCollection("venues");
  1797. BasicDBObject q = new BasicDBObject();
  1798. q.put("_id", new ObjectId(venueId));
  1799. DBObject venue = coll.findOne(q);
  1800. if (venue != null) {
  1801. return venue.get("name").toString();
  1802. }
  1803. return null;
  1804. }
  1805. public static String updateDishPhoto(String dishId, String photoURL) {
  1806. DBCollection coll = MongoBase.connect().getCollection("dishes");
  1807. BasicDBObject q = new BasicDBObject();
  1808. BasicDBObject u = new BasicDBObject();
  1809. q.put("_id", new ObjectId(dishId));
  1810. u.put("$set", new BasicDBObject().append("photoURL", photoURL));
  1811. coll.update(q, u);
  1812. Logger.info("Actualizando imagen del plato con id: " + dishId);
  1813. return null;
  1814. }
  1815. public static String updateVenueLocation(String venueId,Venue.Address address, double coordinates[] ) {
  1816. DBCollection coll = MongoBase.connect().getCollection("venues");
  1817. BasicDBObject q = new BasicDBObject();
  1818. BasicDBObject u = new BasicDBObject();
  1819. q.put("_id", new ObjectId(venueId));
  1820. u.put("$set", new BasicDBObject().append("address", address.toDBO()).append("coordinates",coordinates));
  1821. coll.update(q, u);
  1822. Logger.info("Actualizando dirección de la Venue " + venueId);
  1823. return null;
  1824. }
  1825. public static Dish updateDishPoints(String dishId, DBCollection coll) {
  1826. BasicDBObject q = new BasicDBObject();
  1827. q.put("_id", new ObjectId(dishId));
  1828. DBObject obj = coll.findOne(q);
  1829. Dish d = new Dish(obj);
  1830. float total = 0.f;
  1831. int elementos = d.reviews.size();
  1832. if (elementos == 0) {
  1833. elementos = 1;
  1834. }
  1835. for (Review r : d.reviews) {
  1836. total += r.points;
  1837. }
  1838. q = new BasicDBObject();
  1839. BasicDBObject u = new BasicDBObject();
  1840. q.put("_id", new ObjectId(dishId));
  1841. u.put("$set", new BasicDBObject().append("points", total / elementos));
  1842. coll.update(q, u);
  1843. d.points=total / elementos;
  1844. Logger.info("Actualizando puntos del plato. Puntos = " + total / elementos);
  1845. return d;
  1846. }
  1847. public static Dish updateDishPoints(Dish d, DBCollection coll) {
  1848. float total = 0.f;
  1849. int elementos = d.reviews.size();
  1850. if (elementos == 0) {
  1851. elementos = 1;
  1852. }
  1853. for (Review r : d.reviews) {
  1854. total += r.points;
  1855. }
  1856. BasicDBObject q = new BasicDBObject();
  1857. BasicDBObject u = new BasicDBObject();
  1858. q.put("_id", d.oid);
  1859. u.put("$set", new BasicDBObject().append("points", total / elementos));
  1860. coll.update(q, u);
  1861. d.points=total / elementos;
  1862. Logger.info("Actualizando puntos del plato. Puntos = " + total / elementos);
  1863. return d;
  1864. }
  1865. public static boolean addNewFeed(Feed f) {
  1866. BasicDBObject doc = f.toDBO();
  1867. DBCollection coll = MongoBase.connect().getCollection("feeds");
  1868. WriteResult resultado = coll.insert(doc);
  1869. if (resultado.getError() != null) {
  1870. Logger.error("Error insertando feed ");
  1871. Logger.error(resultado.getError());
  1872. return false;
  1873. }
  1874. Logger.info("Insertado nuevo feed: " + f.description);
  1875. return true;
  1876. }
  1877. public static String sinTildes(String tustring) {
  1878. tustring = tustring.replace('à', 'a');
  1879. tustring = tustring.replace('é', 'e');
  1880. tustring = tustring.replace('í', 'i');
  1881. tustring = tustring.replace('ó', 'o');
  1882. tustring = tustring.replace('ú', 'u');
  1883. return tustring;
  1884. }
  1885. public static String addGcmId(String userId, String gcmId) {
  1886. DBCollection coll = MongoBase.connect().getCollection("users");
  1887. BasicDBObject q = new BasicDBObject();
  1888. BasicDBObject u = new BasicDBObject();
  1889. q.put("_id", new ObjectId(userId));
  1890. u.put("$set", new BasicDBObject().append("gcmId", gcmId));
  1891. coll.update(q, u);
  1892. Logger.info("Actualizado el gcmId del usuario: " + userId);
  1893. return null;
  1894. }
  1895. public static String addDishToFavourites(String userId, String userName, String dishId, String venueName) {
  1896. DBCollection coll = MongoBase.connect().getCollection("users");
  1897. //obtenemos la photo del usuario que realiza la
  1898. String userPhotoURL = getUserPhotoURL(userId, coll);
  1899. ////////////
  1900. BasicDBObject q = new BasicDBObject();
  1901. BasicDBObject u = new BasicDBObject();
  1902. q.put("_id", new ObjectId(userId));
  1903. u.put("$addToSet", new BasicDBObject().append("favDishes", dishId));
  1904. coll.update(q, u);//añadir follower
  1905. ////////////////////////////////
  1906. coll = MongoBase.connect().getCollection("dishes");
  1907. q = new BasicDBObject("_id", new ObjectId(dishId));
  1908. u = new BasicDBObject("$addToSet", new BasicDBObject("followers", userId));
  1909. coll.update(q, u);//añadir follower
  1910. //u=new BasicDBObject("$inc",new BasicDBObject("numFollowingUsers",1));
  1911. //coll.update(q,u);//incrementar número followings //u=new BasicDBObject("$inc",new BasicDBObject("numFollowingUsers",1));
  1912. //coll.update(q,u);//incrementar número followings
  1913. Logger.info(userName + " ha añadido a su wishlist un plato de " + venueName);
  1914. Application.sendNotification(new AddedToFavourites(userId, userName, userPhotoURL, dishId, venueName, getDate(), Notification.TYPE.ADDED_DISH_TO_FAV).asNotification(), findUserFollowers(userId));
  1915. return null;
  1916. }
  1917. public static String removeDishFromFavourites(String userId, String dishId) {
  1918. DBCollection coll = MongoBase.connect().getCollection("users");
  1919. BasicDBObject q = new BasicDBObject();
  1920. BasicDBObject u = new BasicDBObject();
  1921. q.put("_id", new ObjectId(userId));
  1922. u.put("$pull", new BasicDBObject().append("favDishes", dishId));
  1923. coll.update(q, u);//añadir follower
  1924. ////////////////////////////////
  1925. coll = MongoBase.connect().getCollection("dishes");
  1926. q = new BasicDBObject("_id", new ObjectId(dishId));
  1927. u = new BasicDBObject("$pull", new BasicDBObject("followers", userId));
  1928. coll.update(q, u);//añadir follower
  1929. Logger.info("Eliminado un plato de una wishlist");
  1930. return null;
  1931. }
  1932. public static String addVenueToFavourites(String userId, String userName, String venueId, String venueName) {
  1933. DBCollection coll = MongoBase.connect().getCollection("users");
  1934. //obtenemos la photo del usuario que realiza la review
  1935. String userPhotoURL = getUserPhotoURL(userId, coll);
  1936. ////////////
  1937. BasicDBObject q = new BasicDBObject();
  1938. BasicDBObject u = new BasicDBObject();
  1939. q.put("_id", new ObjectId(userId));
  1940. u.put("$addToSet", new BasicDBObject().append("favVenues", venueId));
  1941. coll.update(q, u);//añadir follower
  1942. ////////////////////////////////
  1943. coll = MongoBase.connect().getCollection("venues");
  1944. q = new BasicDBObject("_id", new ObjectId(venueId));
  1945. u = new BasicDBObject("$addToSet", new BasicDBObject("followers", userId));
  1946. coll.update(q, u);//añadir follower
  1947. //u=new BasicDBObject("$inc",new BasicDBObject("numFollowingUsers",1));
  1948. //coll.update(q,u);//incrementar número followings
  1949. Logger.info(userName + " ha añadido a sus favoritos la venue " + venueName);
  1950. Application.sendNotification(new AddedToFavourites(userId, userName, userPhotoURL, venueId, venueName, getDate(), Notification.TYPE.ADDED_VENUE_TO_FAV).asNotification(), findUserFollowers(userId));
  1951. return null;
  1952. }
  1953. public static String removeVenueFromFavourites(String userId, String venueId) {
  1954. DBCollection coll = MongoBase.connect().getCollection("users");
  1955. BasicDBObject q = new BasicDBObject();
  1956. BasicDBObject u = new BasicDBObject();
  1957. q.put("_id", new ObjectId(userId));
  1958. u.put("$pull", new BasicDBObject().append("favVenues", venueId));
  1959. coll.update(q, u);//añadir follower
  1960. ////////////////////////////////
  1961. coll = MongoBase.connect().getCollection("venues");
  1962. q = new BasicDBObject("_id", new ObjectId(venueId));
  1963. u = new BasicDBObject("$pull", new BasicDBObject("followers", userId));
  1964. coll.update(q, u);//añadir follower
  1965. //u=new BasicDBObject("$inc",new BasicDBObject("numFollowingUsers",1));
  1966. //coll.update(q,u);//incrementar número followings
  1967. Logger.info("Eliminada una venue de favoritos");
  1968. return null;
  1969. }
  1970. public static String addPublicationToFavourites(String userId, String userName, String pubId, String venueId, String venueName) {
  1971. Logger.debug("adding to favourites");//añadir followe
  1972. DBCollection coll = MongoBase.connect().getCollection("users");
  1973. //obtenemos la photo del usuario que realiza la review
  1974. String userPhotoURL = getUserPhotoURL(userId, coll);
  1975. ////////////
  1976. BasicDBObject q = new BasicDBObject();
  1977. BasicDBObject u = new BasicDBObject();
  1978. q.put("_id", new ObjectId(userId));
  1979. u.put("$addToSet", new BasicDBObject().append("favPubs", pubId));
  1980. coll.update(q, u);//añadir follower
  1981. ////////////////////////////////
  1982. coll = MongoBase.connect().getCollection("publications");
  1983. q = new BasicDBObject("_id", new ObjectId(pubId));
  1984. u = new BasicDBObject("$addToSet", new BasicDBObject("followers", userId));
  1985. Logger.debug("Resultado mongodb " + coll.update(q, u).toString());//añadir followe
  1986. //u=new BasicDBObject("$inc",new BasicDBObject("numFollowingUsers",1));
  1987. //coll.update(q,u);//incrementar número followings
  1988. Logger.info(userName + " ha añadido una publicación de " + venueName);
  1989. Application.sendNotification(new AddedToFavourites(userId, userName, userPhotoURL, venueId, venueName, getDate(), Notification.TYPE.ADDED_PUB_TO_FAV).asNotification(), findUserFollowers(userId));
  1990. return null;
  1991. }
  1992. public static String removePublicationFromFavourites(String userId, String pubId) {
  1993. DBCollection coll = MongoBase.connect().getCollection("users");
  1994. BasicDBObject q = new BasicDBObject();
  1995. BasicDBObject u = new BasicDBObject();
  1996. q.put("_id", new ObjectId(userId));
  1997. u.put("$pull", new BasicDBObject().append("favPubs", pubId));
  1998. coll.update(q, u);//añadir follower
  1999. ////////////////////////////////
  2000. coll = MongoBase.connect().getCollection("publications");
  2001. q = new BasicDBObject("_id", new ObjectId(pubId));
  2002. u = new BasicDBObject("$pull", new BasicDBObject("followers", userId));
  2003. coll.update(q, u);//añadir follower
  2004. //u=new BasicDBObject("$inc",new BasicDBObject("numFollowingUsers",1));
  2005. //coll.update(q,u);//incrementar número followings
  2006. Logger.info("Se ha eliminado una publicación de favoritos");
  2007. return null;
  2008. }
  2009. public static String addUserFollower(String followerId, String followerName, String followedId, String followedName) {
  2010. DBCollection coll = MongoBase.connect().getCollection("users");
  2011. String photoURL = getUserPhotoURL(followerId, coll);
  2012. BasicDBObject q = new BasicDBObject();
  2013. BasicDBObject u = new BasicDBObject();
  2014. q.put("_id", new ObjectId(followedId));
  2015. u.put("$addToSet", new BasicDBObject().append("followers", followerId));
  2016. coll.update(q, u);//añadir follower
  2017. //u=new BasicDBObject("$inc",new BasicDBObject("numFollowers",1));
  2018. //coll.update(q,u);//incrementar número followers
  2019. ////////////////////////////////
  2020. q = new BasicDBObject("_id", new ObjectId(followerId));
  2021. u = new BasicDBObject("$addToSet", new BasicDBObject("favUsers", followedId));
  2022. coll.update(q, u);//añadir follower
  2023. //u=new BasicDBObject("$inc",new BasicDBObject("numFollowingUsers",1));
  2024. //coll.update(q,u);//incrementar número followings
  2025. Logger.info("Añadido un nuevo follower a " + followedName);
  2026. Application.sendNotification(new Following(followerId, followedId, followerName, followedName, getDate(), photoURL, Notification.TYPE.FOLLOWING_U).asNotification(), findUserFollowers(followerId));
  2027. Application.sendNotification(new Following(followerId, followedId, followerName, followedName, getDate(), photoURL, Notification.TYPE.FOLLOWING_ME).asNotification(), findNotificationIds(Arrays.asList(new String[]{followedId})));
  2028. return null;
  2029. }
  2030. public static String removeUserFollower(String followerId, String followedId) {
  2031. DBCollection coll = MongoBase.connect().getCollection("users");
  2032. BasicDBObject q = new BasicDBObject();
  2033. BasicDBObject u = new BasicDBObject();
  2034. q.put("_id", new ObjectId(followedId));
  2035. u.put("$pull", new BasicDBObject().append("followers", followerId));
  2036. coll.update(q, u);//añadir follower
  2037. ////////////////////////////////
  2038. q = new BasicDBObject("_id", new ObjectId(followerId));
  2039. u = new BasicDBObject("$pull", new BasicDBObject("favUsers", followedId));
  2040. coll.update(q, u);//añadir follower
  2041. Logger.info("Se ha hecho un unfollow a un usuario");
  2042. return null;
  2043. }
  2044. public static String addInterest(String userId, String userName, String interestName) {
  2045. DBCollection coll = MongoBase.connect().getCollection("interests");
  2046. BasicDBObject q = new BasicDBObject();
  2047. BasicDBObject u = new BasicDBObject();
  2048. q.put("name", interestName);
  2049. u.put("$addToSet", new BasicDBObject().append("followers", userId));
  2050. coll.update(q, u);
  2051. u = new BasicDBObject("$inc", new BasicDBObject("numFollowers", 1));
  2052. coll.update(q, u);
  2053. ///////////////////
  2054. coll = MongoBase.connect().getCollection("users");
  2055. q = new BasicDBObject("_id", userId);
  2056. u = new BasicDBObject("$addToSet", new BasicDBObject("followingInterest", interestName));
  2057. coll.update(q, u);
  2058. Logger.info("Añadido un nuevo follower a " + interestName.toUpperCase());
  2059. // Application.sendNotification(new Following(userId,interestName,userName,interestName,getDate(),Notification.TYPE.ADDED_INTEREST).asNotification(),findUserFollowers(userId));
  2060. return null;
  2061. }
  2062. public static String removeInterest(String userId, String interestName) {
  2063. DBCollection coll = MongoBase.connect().getCollection("interests");
  2064. BasicDBObject q = new BasicDBObject();
  2065. BasicDBObject u = new BasicDBObject();
  2066. q.put("name", interestName);
  2067. u.put("$pull", new BasicDBObject().append("followers", userId));
  2068. coll.update(q, u);
  2069. u = new BasicDBObject("$inc", new BasicDBObject("numFollowers", 1));
  2070. coll.update(q, u);
  2071. ///////////////////
  2072. coll = MongoBase.connect().getCollection("users");
  2073. q = new BasicDBObject("_id", userId);
  2074. u = new BasicDBObject("$pull", new BasicDBObject("followingInterest", interestName));
  2075. coll.update(q, u);
  2076. Logger.info("Eliminado un follower de " + interestName.toUpperCase());
  2077. //Application.sendNotification(new Following(userId,interestName,userName,interestName,getDate(),Notification.TYPE.ADDED_INTEREST).asNotification(),findUserFollowers(userId));
  2078. return null;
  2079. }
  2080. public static String addVenueFollower(String followerId, String followerName, String venueId, String venueName) {
  2081. DBCollection coll = MongoBase.connect().getCollection("venues");
  2082. BasicDBObject q = new BasicDBObject();
  2083. BasicDBObject u = new BasicDBObject();
  2084. q.put("_id", new ObjectId(venueId));
  2085. u.put("$addToSet", new BasicDBObject().append("followers", followerId));
  2086. coll.update(q, u);
  2087. //u=new BasicDBObject("$inc",new BasicDBObject("numFollowers",1));
  2088. //coll.update(q,u);
  2089. Logger.info("Añadido un nuevo follower a " + venueName);
  2090. ///////////////////////
  2091. coll = MongoBase.connect().getCollection("users");
  2092. q = new BasicDBObject("_id", followerId);
  2093. u = new BasicDBObject("$addToSet", new BasicDBObject("followingVenues", venueId));
  2094. coll.update(q, u);
  2095. //u=new BasicDBObject("$inc",new BasicDBObject("numFollowingVenues",1));
  2096. //coll.update(q,u);//incrementar número followings
  2097. //Application.sendNotification(new Following(followerId,venueId,followerName,venueName,getDate(),Notification.TYPE.ADDED_INTEREST).asNotification(),findUserFollowers(followerId));
  2098. return null;
  2099. }
  2100. public static String removeVenueFollower(String followerId, String venueId) {
  2101. DBCollection coll = MongoBase.connect().getCollection("venues");
  2102. BasicDBObject q = new BasicDBObject();
  2103. BasicDBObject u = new BasicDBObject();
  2104. q.put("_id", new ObjectId(venueId));
  2105. u.put("$pull", new BasicDBObject().append("followers", followerId));
  2106. coll.update(q, u);
  2107. Logger.info("Eliminado un follower a una venue");
  2108. ///////////////////////
  2109. coll = MongoBase.connect().getCollection("users");
  2110. q = new BasicDBObject("_id", followerId);
  2111. u = new BasicDBObject("$pull", new BasicDBObject("followingVenues", venueId));
  2112. coll.update(q, u);
  2113. return null;
  2114. }
  2115. public static String findVenuesById(List<String> venueIds) {
  2116. DBCollection coll = MongoBase.connect().getCollection("venues");
  2117. ArrayList<ObjectId> vOids = new ArrayList<ObjectId>(venueIds.size());
  2118. for (String s : venueIds) {
  2119. vOids.add(new ObjectId(s));
  2120. }
  2121. BasicDBObject q = new BasicDBObject();
  2122. q.put("venueId", new BasicDBObject("$in", vOids));
  2123. DBCursor cursor = coll.find(q).limit(vOids.size());
  2124. List<DBObject> retorno = cursor.toArray();
  2125. return "{\"venues\":" + com.mongodb.util.JSON.serialize(retorno) + "}";
  2126. }
  2127. public static String findFavVenuesByUserId(String userId) {
  2128. DBCollection coll = MongoBase.connect().getCollection("users");
  2129. BasicDBObject q = new BasicDBObject("_id", new ObjectId(userId));
  2130. BasicDBObject l = new BasicDBObject("favVenues", 1);
  2131. DBObject user = coll.findOne(q, l);
  2132. Logger.info("USER: " + user);
  2133. List<String> venues = (List<String>) user.get("favVenues");
  2134. ArrayList<ObjectId> listIds = new ArrayList<ObjectId>(venues.size());
  2135. for (String s : venues) {
  2136. listIds.add(new ObjectId(s));
  2137. }
  2138. Logger.info("IDS: " + listIds.get(0).toString());
  2139. coll = MongoBase.connect().getCollection("venues");
  2140. q = new BasicDBObject("_id", new BasicDBObject("$in", listIds));
  2141. DBCursor cursor = coll.find(q);
  2142. List<DBObject> retorno = cursor.toArray();
  2143. return "{\"venues\":" + com.mongodb.util.JSON.serialize(retorno) + "}";
  2144. }
  2145. public static String findFavDishesByUserId(String userId) {
  2146. DBCollection coll = MongoBase.connect().getCollection("users");
  2147. BasicDBObject q = new BasicDBObject("_id", new ObjectId(userId));
  2148. BasicDBObject l = new BasicDBObject("favDishes", 1);
  2149. DBObject user = coll.findOne(q, l);
  2150. Logger.info("USER: " + user);
  2151. List<String> dishes = (List<String>) user.get("favDishes");
  2152. Logger.info("DISHES: " + dishes.get(0));
  2153. ArrayList<ObjectId> listIds = new ArrayList<ObjectId>(dishes.size());
  2154. for (String s : dishes) {
  2155. listIds.add(new ObjectId(s));
  2156. }
  2157. Logger.info("IDS: " + listIds.get(0).toString());
  2158. coll = MongoBase.connect().getCollection("dishes");
  2159. q = new BasicDBObject("_id", new BasicDBObject("$in", listIds));
  2160. DBCursor cursor = coll.find(q);
  2161. List<DBObject> retorno = cursor.toArray();
  2162. return "{\"dishes\":" + com.mongodb.util.JSON.serialize(retorno) + "}";
  2163. }
  2164. public static String findFavPublicationsByUserId(String userId) {
  2165. DBCollection coll = MongoBase.connect().getCollection("users");
  2166. BasicDBObject q = new BasicDBObject("_id", new ObjectId(userId));
  2167. BasicDBObject l = new BasicDBObject("favPubs", 1);
  2168. DBObject user = coll.findOne(q, l);
  2169. Logger.info("USER: " + user);
  2170. List<String> publications = (List<String>) user.get("favPubs");
  2171. coll = MongoBase.connect().getCollection("publications");
  2172. ArrayList<ObjectId> listIds = new ArrayList<ObjectId>(publications.size());
  2173. for (String s : publications) {
  2174. Logger.debug("favoritos: " + s);
  2175. listIds.add(new ObjectId(s));
  2176. }
  2177. // bdl.add(new BasicDBObject("_id",new BasicDBObject("$in",listIds)));
  2178. // bdl.add(new BasicDBObject("publications.followers",userId));
  2179. // q=new BasicDBObject("$and",bdl);
  2180. q = new BasicDBObject("_id", new BasicDBObject("$in", listIds));
  2181. DBCursor cursor = coll.find(q);
  2182. List<DBObject> retorno = cursor.toArray();
  2183. return "{\"publications\":" + com.mongodb.util.JSON.serialize(retorno) + "}";
  2184. }
  2185. public static F.Promise<Result> createPublication(Publication pub) {
  2186. DBCollection coll = MongoBase.connect().getCollection("publications");
  2187. DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
  2188. pub.setCreationDate(df.format(new Date()));
  2189. pub.setPubId(new ObjectId(new Date()).toString());
  2190. coll.insert(pub.toDBO());
  2191. Notification n = new Notification(pub.getDate(), Notification.TYPE.PUBLICATION, pub.toJson(), pub.getPubId());
  2192. return Application.sendNotification(n, findPublicationReceivers(pub));
  2193. }
  2194. public static F.Promise<Result> createGlobalPublication(Publication pub) {
  2195. DBCollection coll = MongoBase.connect().getCollection("users");
  2196. DBCursor dbc = coll.find(new BasicDBObject("gcmId", new BasicDBObject("$exists", true)), new BasicDBObject("gcmId", 1).append("_id", 0));
  2197. ArrayList<String> receivers = new ArrayList<String>(dbc.count());
  2198. for (DBObject dbo : dbc) {
  2199. Logger.debug(dbo.toString());
  2200. receivers.add(dbo.get("gcmId").toString());
  2201. }
  2202. DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
  2203. pub.setCreationDate(df.format(new Date()));
  2204. Notification n = new Notification(pub.getDate(), Notification.TYPE.PUBLICATION, pub.toJson());
  2205. return Application.sendNotification(n, receivers);
  2206. }
  2207. static List<String> findPublicationReceivers(Publication pub) {
  2208. HashSet<String> receivers = new HashSet<String>();
  2209. receivers.addAll(findInterestFollowers(pub.getInterests()));
  2210. receivers.addAll(findVenueFollowers(pub.getVenueId()));
  2211. return findNotificationIds(new ArrayList<String>(receivers));
  2212. }
  2213. static List<String> findVenueFollowers(String venueId) {
  2214. DBCollection coll = MongoBase.connect().getCollection("venues");
  2215. DBObject dbo = coll.findOne(new BasicDBObject("_id", new ObjectId(venueId)), new BasicDBObject("followers", 1).append("_id", 0));
  2216. BasicDBList followers = (BasicDBList) dbo.get("followers");
  2217. if(followers!=null){
  2218. ArrayList<String> receivers = new ArrayList<String>(followers.size());
  2219. for (Object object : followers) {
  2220. Logger.info("cursor: " + object.toString());
  2221. receivers.add(object.toString());
  2222. }
  2223. return receivers;
  2224. }
  2225. return new ArrayList<String>();
  2226. }
  2227. static List<String> findUserFollowers(String userId) {
  2228. DBCollection coll = MongoBase.connect().getCollection("users");
  2229. DBObject dbo = coll.findOne(new BasicDBObject("_id", new ObjectId(userId)), new BasicDBObject("followers", 1).append("_id", 0));
  2230. BasicDBList followers = (BasicDBList) dbo.get("followers");
  2231. ArrayList<String> receivers = new ArrayList<String>(followers.size());
  2232. for (Object object : followers) {
  2233. Logger.info("cursor: " + object.toString());
  2234. receivers.add(object.toString());
  2235. }
  2236. return findNotificationIds(receivers);
  2237. }
  2238. public static List<String> findInterestFollowers(List<String> interests) {
  2239. DBCollection coll = MongoBase.connect().getCollection("interests");
  2240. List lista = coll.distinct("followers", new BasicDBObject("name", new BasicDBObject("$in", interests)));
  2241. return lista;
  2242. }
  2243. static List<String> findNotificationIds(List<String> userIds) {
  2244. DBCollection coll = MongoBase.connect().getCollection("users");
  2245. BasicDBObject q = new BasicDBObject();
  2246. ArrayList<ObjectId> uOids = new ArrayList<ObjectId>(userIds.size());
  2247. for (String s : userIds) {
  2248. uOids.add(new ObjectId(s));
  2249. }
  2250. q.put("_id", new BasicDBObject("$in", uOids));
  2251. DBCursor dbCursor = coll.find(q, new BasicDBObject("_id", 0).append("gcmId", 1));
  2252. ArrayList<String> lista = new ArrayList<String>(dbCursor.count());
  2253. DBObject dbo;
  2254. while (dbCursor.hasNext()) {
  2255. dbo = dbCursor.next();
  2256. if (dbo.get("gcmId") != null) {
  2257. lista.add(dbo.get("gcmId").toString());
  2258. }
  2259. }
  2260. return lista;
  2261. }
  2262. static String getDate() {
  2263. DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
  2264. return df.format(new Date());
  2265. }
  2266. /**
  2267. * Función que elimina acentos de
  2268. * una cadena de texto.
  2269. * @param input
  2270. * @return cadena de texto limpia de acentos .
  2271. */
  2272. public static String removeTildes(String input) {
  2273. // Cadena de caracteres original a sustituir.
  2274. String original = "áàäéèëíìïóòöúùuÁÀÄÉÈËÍÌÏÓÒÖÚÙÜÑ";
  2275. // Cadena de caracteres ASCII que reemplazarán los originales.
  2276. String ascii = "aaaeeeiiiooouuuAAAEEEIIIOOOUUUN";
  2277. String output = input;
  2278. for (int i=0; i<original.length(); i++) {
  2279. // Reemplazamos los caracteres especiales.
  2280. output = output.replace(original.charAt(i), ascii.charAt(i));
  2281. }//for i
  2282. return output;
  2283. }//remove1
  2284. public static Client findClientByMail(String mail) {
  2285. DBCollection coll = MongoBase.connect().getCollection("clients");
  2286. BasicDBObject q = new BasicDBObject();
  2287. q.put("mail", mail);
  2288. DBObject obj = coll.findOne(q);
  2289. return new Client(obj);
  2290. }
  2291. public static void updateVenuePhotos(Venue venue) {
  2292. DBCollection coll = MongoBase.connect().getCollection("venues");
  2293. BasicDBObject q = new BasicDBObject();
  2294. BasicDBObject u = new BasicDBObject();
  2295. q.put("_id", new ObjectId(venue.oid.toString()));
  2296. if(venue.photoURLs[0]==null||venue.photoURLs[0].equalsIgnoreCase("")||venue.photoURLs[0].equalsIgnoreCase("undefined")){
  2297. venue.photoURLs[0]="http://toptasting.s3.amazonaws.com/sinImagenVenue.png";
  2298. }
  2299. u.put("$set", new BasicDBObject().append("photoURLs", venue.photoURLs));
  2300. coll.update(q, u);
  2301. Logger.info("Actualizando fotos de la Venue " + venue.oid.toString());
  2302. }
  2303. public static void updateVenueMenuSections(Venue venue) {
  2304. DBCollection coll = MongoBase.connect().getCollection("venues");
  2305. BasicDBObject q = new BasicDBObject();
  2306. BasicDBObject u = new BasicDBObject();
  2307. q.put("_id", new ObjectId(venue.oid.toString()));
  2308. u.put("$set", new BasicDBObject().append("menuSections", venue.menuSections));
  2309. coll.update(q, u);
  2310. Logger.info("Actualizando secciones de la carta " + venue.name.toString());
  2311. }
  2312. }