1 2 12 package com.versant.core.jdo.externalizer; 13 14 import com.versant.core.common.BindingSupportImpl; 15 import com.versant.core.common.Utils; 16 17 import javax.jdo.PersistenceManager; 18 import java.lang.reflect.Constructor ; 19 import java.lang.reflect.Method ; 20 import java.io.*; 21 22 30 public class TypeAsBytesExternalizer implements Externalizer, Externalizable { 31 32 public static final String SHORT_NAME = "BYTES"; 33 34 private Class type; 35 private Constructor constructor; 36 private Method toBytes; 37 38 public TypeAsBytesExternalizer(Class type) { 39 this.type = type; 40 init(); 41 } 42 43 public TypeAsBytesExternalizer() { 44 } 45 46 private void init() { 47 try { 48 constructor = type.getConstructor(new Class []{byte[].class}); 49 } catch (NoSuchMethodException e) { 50 throw BindingSupportImpl.getInstance().runtime(type + " does not have a " + 51 "constructor that accepts a byte[]", e); 52 } 53 try { 54 toBytes = type.getMethod("toBytes", null); 55 } catch (NoSuchMethodException e) { 56 throw BindingSupportImpl.getInstance().runtime(type + " does not have a " + 57 "public toBytes() method", e); 58 } 59 if (toBytes.getReturnType() != byte[].class) { 60 throw BindingSupportImpl.getInstance().runtime(type + ".toBytes() does not " + 61 "return byte[]"); 62 } 63 } 64 65 public Object toExternalForm(PersistenceManager pm, Object o) { 66 if (o == null) return null; 67 try { 68 return toBytes.invoke(o, null); 69 } catch (Throwable x) { 70 throw BindingSupportImpl.getInstance().fatalDatastore("Unable to convert instance of " + 71 type.getName() + " '" + Utils.toString(o) + "' to byte[]: " + x, x); 72 } 73 } 74 75 public Object fromExternalForm(PersistenceManager pm, Object o) { 76 if (o == null) return null; 77 if (!(o instanceof byte[])) { 78 throw BindingSupportImpl.getInstance().runtime( 79 "Expected byte[] to create instance of " + 80 type.getName() + ", got: " + Utils.toString(o)); 81 } 82 try { 83 return constructor.newInstance(new Object []{o}); 84 } catch (Throwable x) { 85 throw BindingSupportImpl.getInstance().runtime( 86 "Unable to create instance of " + 87 type.getName() + " from " + Utils.toString(o) + ": " + x, x); 88 } 89 } 90 91 public Class getExternalType() { 92 return byte[].class; 93 } 94 95 public void writeExternal(ObjectOutput out) throws IOException { 96 out.writeObject(type); 97 } 98 99 public void readExternal(ObjectInput in) throws IOException, 100 ClassNotFoundException { 101 type = (Class )in.readObject(); 102 init(); 103 } 104 } 105 106 | Popular Tags |