PageRenderTime 310ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://github.com/LaMaldicionDeMandos/PersisterService
Java | 44 lines | 36 code | 8 blank | 0 comment | 3 complexity | 564c240ce978b65986cab44b795ff124 MD5 | raw file
  1. package org.pasut.persister;
  2. import java.util.ArrayList;
  3. import java.util.Collection;
  4. import java.util.Map;
  5. import org.codehaus.jackson.map.ObjectMapper;
  6. import com.mongodb.BasicDBList;
  7. import com.mongodb.BasicDBObject;
  8. import com.mongodb.DBObject;
  9. public class ExampleFactory {
  10. private final GsonMongoMapper mapper = new GsonMongoMapper();
  11. public <T> DBObject createExample(T example, String[] properties){
  12. return createDBObjectExample(mapper.toDbObject(example), properties);
  13. }
  14. public DBObject createDBObjectExample(final DBObject object,String[] keys){
  15. DBObject dbObject = new BasicDBObject();
  16. for(String key : keys){
  17. dbObject.put(key, getProperty(object,key));
  18. }
  19. return dbObject;
  20. }
  21. private Object getProperty(final DBObject object, String key){
  22. String[] arrayKey = key.split("\\.");
  23. if(arrayKey.length==1){
  24. if(!(object.get(key) instanceof Collection<?>))
  25. return object.get(key);
  26. else{
  27. return toBasicList((Collection<?>)object.get(key));
  28. }
  29. }
  30. return getProperty(new BasicDBObject((Map<?, ?>)object.get(arrayKey[0])), key.substring(key.indexOf(".")+1));
  31. }
  32. private <T> BasicDBList toBasicList(Collection<T> collection){
  33. Collection<T> copy = new ArrayList<T>(collection);
  34. return (BasicDBList) new ObjectMapper().convertValue(copy, BasicDBList.class);
  35. }
  36. }