PageRenderTime 52ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/PersisterService/src/main/java/org/pasut/persister/GsonMongoMapper.java

https://github.com/LaMaldicionDeMandos/PersisterService
Java | 66 lines | 55 code | 10 blank | 1 comment | 7 complexity | 22bf75fce0fc84d816f075d21079b43d MD5 | raw file
  1. package org.pasut.persister;
  2. import java.lang.reflect.Field;
  3. import java.util.ArrayList;
  4. import java.util.Collection;
  5. import java.util.Collections;
  6. import java.util.HashMap;
  7. import java.util.List;
  8. import java.util.Map;
  9. import org.codehaus.jackson.annotate.JsonProperty;
  10. import org.codehaus.jackson.map.ObjectMapper;
  11. import com.mongodb.BasicDBObject;
  12. import com.mongodb.DBObject;
  13. public class GsonMongoMapper extends GsonMapper implements MongoMapper {
  14. private final ObjectMapper mapper = new ObjectMapper();
  15. public <T> DBObject toDbObject(T value) {
  16. BasicDBObject dbObject = new BasicDBObject();
  17. @SuppressWarnings("unchecked")
  18. Map<String, Object> map = mapper.convertValue(value,HashMap.class);
  19. String id = (String)map.remove("id");
  20. if(id != null){
  21. map.put("_id", id);
  22. }
  23. List<String> sorterList = new ArrayList<String>(map.keySet());
  24. Collections.sort(sorterList);
  25. for(String key : sorterList){
  26. dbObject.put(key,map.get(key));
  27. }
  28. //dbObject.putAll(map);
  29. return dbObject;
  30. }
  31. public <T> T fromDbObject(DBObject object, Class<T> clazz) {
  32. Collection<Field> fields = getJsonPropertyFields(clazz);
  33. for(Field field : fields){
  34. String propertyName = field.getAnnotation(JsonProperty.class).value();
  35. Object propertyValue = object.removeField(propertyName);
  36. object.put(field.getName(), propertyValue);
  37. }
  38. return fromJson(object.toString(), clazz);
  39. }
  40. public <T> List<T> fromDbObject(List<DBObject> list,final Class<T> clazz) {
  41. List<T> newList = new ArrayList<T>();
  42. for(DBObject dbObject : list){
  43. newList.add(fromDbObject(dbObject, clazz));
  44. }
  45. return newList;
  46. }
  47. private <T> Collection<Field> getJsonPropertyFields(Class<T> clazz){
  48. Field[] fields = clazz.getDeclaredFields();
  49. Collection<Field> list = new ArrayList<Field>();
  50. for(Field field : fields){
  51. JsonProperty annotation = field.getAnnotation(JsonProperty.class);
  52. if(annotation!=null) list.add(field);
  53. }
  54. return list;
  55. }
  56. }