001 package com.khubla.pragmatach.plugin.mongodb.serializer; 002 003 import java.lang.reflect.Field; 004 005 import org.apache.commons.beanutils.BeanUtils; 006 007 import com.khubla.pragmatach.framework.api.PragmatachException; 008 import com.khubla.pragmatach.plugin.mongodb.MongoDBDAO; 009 import com.khubla.pragmatach.plugin.mongodb.util.ClassTypeUtils; 010 import com.mongodb.BasicDBObject; 011 import com.mongodb.DBObject; 012 013 /** 014 * @author tom 015 */ 016 public class AtomicFieldSerializer implements FieldSerializer { 017 /** 018 * type utils 019 */ 020 private final ClassTypeUtils classTypeUtils; 021 /** 022 * the type 023 */ 024 private final Class<?> typeClazz; 025 026 /** 027 * ctor 028 */ 029 public AtomicFieldSerializer(Class<?> typeClazz) { 030 this.typeClazz = typeClazz; 031 classTypeUtils = new ClassTypeUtils(this.typeClazz); 032 } 033 034 @Override 035 public void deserializeField(Object object, Field field, DBObject dbObject) throws PragmatachException { 036 try { 037 /* 038 * read all fields, treating id as special 039 */ 040 if (field.getName().compareTo(classTypeUtils.getIdFieldName()) != 0) { 041 BeanUtils.setProperty(object, field.getName(), dbObject.get(field.getName())); 042 } else { 043 final String objectId = (String) dbObject.get(MongoDBDAO.ID); 044 if (null == objectId) { 045 throw new PragmatachException("Object '" + dbObject.toString() + "' has null id"); 046 } 047 classTypeUtils.setId(object, objectId); 048 } 049 } catch (final Exception e) { 050 throw new PragmatachException("Exception in deserializeField", e); 051 } 052 } 053 054 @Override 055 public void serializeField(BasicDBObject parentDBObject, Object object, Field field) throws PragmatachException { 056 try { 057 /* 058 * persist all fields, treating id as special 059 */ 060 if (field.getName().compareTo(classTypeUtils.getIdFieldName()) != 0) { 061 final String propertyValue = BeanUtils.getProperty(object, field.getName()); 062 parentDBObject.append(field.getName(), propertyValue); 063 } else { 064 final String id = classTypeUtils.getId(object); 065 parentDBObject.append(MongoDBDAO.ID, id); 066 } 067 } catch (final Exception e) { 068 throw new PragmatachException("Exception in serializeField", e); 069 } 070 } 071 }