1 package org.sapia.ubik.rmi; 2 3 import java.io.ByteArrayInputStream ; 4 import java.io.ByteArrayOutputStream ; 5 import java.io.IOException ; 6 import java.io.InputStream ; 7 import java.io.ObjectInputStream ; 8 import java.io.ObjectOutputStream ; 9 import java.io.ObjectStreamClass ; 10 import java.rmi.server.RMIClassLoader ; 11 12 13 21 public class Utils { 22 23 public static Object deserialize(byte[] bytes) 24 throws IOException , ClassNotFoundException { 25 ObjectInputStream ois = new ObjectInputStream (new ByteArrayInputStream ( 26 bytes)); 27 Object o = ois.readObject(); 28 29 return o; 30 } 31 32 public static Object deserialize(byte[] bytes, ClassLoader loader) 33 throws IOException , ClassNotFoundException { 34 ObjectInputStream ois = new ObjectInputStreamEx(new ByteArrayInputStream ( 35 bytes), loader); 36 Object o = ois.readObject(); 37 38 return o; 39 } 40 41 public static Object deserialize(byte[] bytes, ClassLoader loader, String codebase) 42 throws IOException , ClassNotFoundException { 43 RMIClassLoader.getClassLoader(codebase); 44 ObjectInputStream ois = new ObjectInputStreamEx(new ByteArrayInputStream ( 45 bytes), loader); 46 Object o = ois.readObject(); 47 48 return o; 49 } 50 51 public static byte[] serialize(Object o) throws IOException { 52 ByteArrayOutputStream bos = new ByteArrayOutputStream (); 53 ObjectOutputStream ous = new ObjectOutputStream (bos); 54 ous.writeObject(o); 55 ous.flush(); 56 ous.close(); 57 58 return bos.toByteArray(); 59 } 60 61 static final class ObjectInputStreamEx extends ObjectInputStream { 62 private ClassLoader _loader; 63 64 ObjectInputStreamEx(InputStream is, ClassLoader loader) 65 throws IOException { 66 super(is); 67 _loader = loader; 68 } 69 70 73 protected Class resolveClass(ObjectStreamClass desc) 74 throws IOException , ClassNotFoundException { 75 if (_loader != null) { 76 return _loader.loadClass(desc.getName()); 77 } else { 78 return super.resolveClass(desc); 79 } 80 } 81 } 82 } 83 | Popular Tags |