PageRenderTime 111ms CodeModel.GetById 40ms RepoModel.GetById 1ms app.codeStats 0ms

/com.parabolika.server.persist.mongo/src/com/parabolika/server/persist/mongo/MongoPlayerPersistor.java

https://github.com/parabolika/osgi-server
Java | 51 lines | 41 code | 10 blank | 0 comment | 5 complexity | ed0315aafcd699fefe3aea87da6d1bf2 MD5 | raw file
  1. package com.parabolika.server.persist.mongo;
  2. import com.google.gson.Gson;
  3. import com.mongodb.BasicDBObject;
  4. import com.mongodb.DBCollection;
  5. import com.mongodb.DBObject;
  6. import com.mongodb.util.JSON;
  7. import com.parabolika.server.model.Player;
  8. import com.parabolika.server.model.PlayerBuilder;
  9. import com.parabolika.server.persist.IPersistor;
  10. import com.parabolika.server.persist.annotate.Persists;
  11. @Persists(PlayerBuilder.class)
  12. public class MongoPlayerPersistor implements IPersistor<Player, PlayerBuilder, PlayerBuilder> {
  13. private static final Gson GSON = new Gson();
  14. private final MongoContext context;
  15. public MongoPlayerPersistor(MongoContext context) {
  16. this.context = context;
  17. }
  18. @Override
  19. public void put(Player player) {
  20. DBCollection playersCollection = context.getDb().getCollection("players");
  21. DBObject query = new BasicDBObject("username", player.getUsername());
  22. DBObject result = playersCollection.findOne(query);
  23. String json = GSON.toJson(player);
  24. DBObject object = (DBObject) JSON.parse(json);
  25. if(result != null) {
  26. playersCollection.update(result, object);
  27. } else {
  28. playersCollection.save(object);
  29. }
  30. }
  31. @Override
  32. public PlayerBuilder get(PlayerBuilder builder, String key) {
  33. DBCollection playersCollection = context.getDb().getCollection("players");
  34. DBObject query = new BasicDBObject("username", key);
  35. DBObject result = playersCollection.findOne(query);
  36. if(result != null) {
  37. return builder.merge(GSON.fromJson(result.toString(), PlayerBuilder.class));
  38. }
  39. return builder;
  40. }
  41. }