Advertisement
Guest User

Class NoSQL

a guest
Nov 21st, 2017
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.41 KB | None | 0 0
  1. package net.practice.nosql;
  2.  
  3. import java.net.UnknownHostException;
  4.  
  5. import net.practice.api.API;
  6. import net.practice.arenas.Arena;
  7. import org.bukkit.Location;
  8.  
  9. import com.mongodb.BasicDBObject;
  10. import com.mongodb.DB;
  11. import com.mongodb.DBCollection;
  12. import com.mongodb.DBCursor;
  13. import com.mongodb.DBObject;
  14. import com.mongodb.MongoClient;
  15. import com.mongodb.MongoClientURI;
  16.  
  17. import net.practice.Main;
  18.  
  19. public class NoSQL {
  20.  
  21. private DB database;
  22. private DBCollection collection;
  23. private String collectionName = "Arenas";
  24.  
  25. @SuppressWarnings({ "resource", "deprecation" })
  26. public void setUp() throws UnknownHostException {
  27. MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost:27017"));
  28. database = mongoClient.getDB("FieldPractice");
  29. collection = database.getCollection(collectionName);
  30. }
  31.  
  32. public void saveArena(Arena arena) {
  33. DBObject obj = new BasicDBObject("_id", arena.getId()).append("loc1", arena.getLocation1()).append("loc2",
  34. arena.getLocation2());
  35. collection.insert(obj);
  36. database.getMongo().close();
  37. }
  38.  
  39. public void loadArena() {
  40. DBObject query = new BasicDBObject();
  41. DBCursor cursor = collection.find(query);
  42. int number = cursor.length();
  43. for (int i = 1; i <= number; i++) {
  44. DBCollection coll = database.getCollection(collectionName);
  45. DBObject searchById = new BasicDBObject("_id", i);
  46. DBObject found = coll.findOne(searchById);
  47. Arena arena;
  48. if (found != null) {
  49. arena = new Arena(i, new API().stringToLocation((String) found.get("loc1")), new API().stringToLocation((String) found.get("loc2")), true);
  50. Main.arena.add(arena);
  51. }
  52. }
  53. database.getMongo().close();
  54. }
  55.  
  56. private void loadArena(Arena arena) {
  57. DBCollection coll = database.getCollection(collectionName);
  58. DBObject searchById = new BasicDBObject("_id", arena.getId());
  59. DBObject found = coll.findOne(searchById);
  60. if (found != null) {
  61. arena = new Arena(arena.getId(), new API().stringToLocation((String) found.get("loc1")), new API().stringToLocation((String) found.get("loc2")), true);
  62. Main.arena.add(arena);
  63. }
  64. }
  65.  
  66. public void setLocation(Arena arena, Location loc, String nameOfLocation) {
  67. collection.update(new BasicDBObject("_id", arena.getId()),
  68. new BasicDBObject("$set", new BasicDBObject(nameOfLocation, new API().locationToString(loc))));
  69. loadArena(arena);
  70. database.getMongo().close();
  71. }
  72.  
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement