1 19 package org.apache.cayenne.access.types; 20 21 import java.io.ByteArrayInputStream ; 22 import java.io.ByteArrayOutputStream ; 23 import java.io.ObjectInputStream ; 24 import java.io.ObjectOutputStream ; 25 import java.io.Serializable ; 26 27 import org.apache.cayenne.CayenneRuntimeException; 28 29 36 class SerializableTypeFactory implements ExtendedTypeFactory { 37 38 private ExtendedTypeMap map; 39 40 SerializableTypeFactory(ExtendedTypeMap map) { 41 this.map = map; 42 } 43 44 public ExtendedType getType(Class objectClass) { 45 46 if (Serializable .class.isAssignableFrom(objectClass)) { 47 48 52 ExtendedType bytesType = map.getExplictlyRegisteredType("byte[]"); 54 55 if (bytesType instanceof SerializableType) { 57 throw new IllegalStateException ( 58 "Can't create Serializable ExtendedType for " 59 + objectClass.getName() 60 + ": no ExtendedType exists for byte[]"); 61 } 62 63 return new SerializableType(objectClass, bytesType); 64 } 65 66 return null; 67 } 68 69 72 final class SerializableType extends ExtendedTypeDecorator { 73 74 private Class javaClass; 75 76 SerializableType(Class javaClass, ExtendedType bytesType) { 77 super(bytesType); 78 this.javaClass = javaClass; 79 } 80 81 public String getClassName() { 82 return javaClass.getName(); 83 } 84 85 Object fromJavaObject(Object object) { 86 ByteArrayOutputStream bytes = new ByteArrayOutputStream () { 87 88 public synchronized byte[] toByteArray() { 90 return buf; 91 } 92 }; 93 94 try { 95 ObjectOutputStream out = new ObjectOutputStream (bytes); 96 out.writeObject(object); 97 out.close(); 98 } 99 catch (Exception e) { 100 throw new CayenneRuntimeException("Error serializing object", e); 101 } 102 103 return bytes.toByteArray(); 104 } 105 106 Object toJavaObject(Object object) { 107 byte[] bytes = (byte[]) object; 108 try { 109 return bytes != null && bytes.length > 0 ? new ObjectInputStream ( 110 new ByteArrayInputStream (bytes)).readObject() : null; 111 } 112 catch (Exception e) { 113 throw new CayenneRuntimeException("Error deserializing object", e); 114 } 115 } 116 } 117 } 118 | Popular Tags |