001 package com.khubla.pragmatach.plugin.mongodb.serializer; 002 003 import java.lang.reflect.Field; 004 005 import org.bson.types.ObjectId; 006 007 import com.khubla.pragmatach.framework.api.PragmatachException; 008 import com.khubla.pragmatach.plugin.mongodb.proxy.MongoProxyFactory; 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 BasicObjectSerializer implements ObjectSerializer { 017 /** 018 * the type 019 */ 020 private final Class<?> typeClazz; 021 /** 022 * type utils 023 */ 024 private final ClassTypeUtils typeUtils; 025 026 /** 027 * ctor 028 */ 029 public BasicObjectSerializer(Class<?> typeClazz) { 030 this.typeClazz = typeClazz; 031 typeUtils = new ClassTypeUtils(this.typeClazz); 032 } 033 034 /** 035 * deserialize 036 */ 037 @Override 038 public Object deserialize(DBObject dbObject) throws PragmatachException { 039 try { 040 /* 041 * instance 042 */ 043 final Object object = MongoProxyFactory.getProxyObject(typeClazz); 044 /* 045 * walk the fields 046 */ 047 for (final Field field : typeClazz.getDeclaredFields()) { 048 /* 049 * filter the static ones 050 */ 051 if (false == java.lang.reflect.Modifier.isStatic(field.getModifiers())) { 052 final FieldSerializer fieldSerializer = FieldSerializerFactory.getFieldSerializer(typeClazz, field); 053 fieldSerializer.deserializeField(object, field, dbObject); 054 } 055 } 056 /* 057 * done 058 */ 059 return object; 060 } catch (final Exception e) { 061 throw new PragmatachException("Exception in deserialize", e); 062 } 063 } 064 065 public Class<?> getTypeClazz() { 066 return typeClazz; 067 } 068 069 /** 070 * serialize 071 */ 072 @Override 073 public BasicDBObject serialize(Object object) throws PragmatachException { 074 try { 075 if (null != object) { 076 /* 077 * id generation 078 */ 079 if (typeUtils.isGeneratedId()) { 080 /* 081 * check for an id 082 */ 083 final String id = typeUtils.getId(object); 084 if (null == id) { 085 final ObjectId objectId = new ObjectId(); 086 typeUtils.setId(object, objectId.toString()); 087 } 088 } 089 /* 090 * object node 091 */ 092 final BasicDBObject ret = new BasicDBObject(); 093 /* 094 * walk the fields 095 */ 096 for (final Field field : typeClazz.getDeclaredFields()) { 097 /* 098 * filter the static ones 099 */ 100 if (false == java.lang.reflect.Modifier.isStatic(field.getModifiers())) { 101 final FieldSerializer fieldSerializer = FieldSerializerFactory.getFieldSerializer(typeClazz, field); 102 fieldSerializer.serializeField(ret, object, field); 103 } 104 } 105 /* 106 * done 107 */ 108 return ret; 109 } else { 110 throw new PragmatachException("Cannot serialize null object"); 111 } 112 } catch (final Exception e) { 113 throw new PragmatachException("Exception in serialize", e); 114 } 115 } 116 }