001 package railo.runtime.converter; 002 003 import java.io.ByteArrayInputStream; 004 import java.io.ByteArrayOutputStream; 005 import java.io.IOException; 006 import java.io.InputStream; 007 import java.io.ObjectInputStream; 008 import java.io.ObjectOutputStream; 009 import java.io.OutputStream; 010 import java.io.Serializable; 011 012 import railo.commons.io.IOUtil; 013 import railo.commons.io.res.Resource; 014 import railo.runtime.coder.Base64Coder; 015 import railo.runtime.coder.CoderException; 016 017 018 019 /** 020 * 021 */ 022 public final class JavaConverter { 023 024 /** 025 * serialize a Java Object of Type Serializable 026 * @param o 027 * @return serialized String 028 * @throws IOException 029 */ 030 public static String serialize(Object o) throws IOException { 031 if(!(o instanceof Serializable))throw new IOException("Java Object is not of type Serializable"); 032 return serialize((Serializable)o); 033 } 034 /** 035 * serialize a Java Object of Type Serializable 036 * @param o 037 * @return serialized String 038 * @throws IOException 039 */ 040 public static String serialize(Serializable o) throws IOException { 041 ByteArrayOutputStream baos = new ByteArrayOutputStream(); 042 serialize(o, baos); 043 return Base64Coder.encode(baos.toByteArray()); 044 } 045 046 public static void serialize(Serializable o, railo.commons.io.res.Resource out) throws IOException { 047 serialize(o,out.getOutputStream()); 048 } 049 050 public static void serialize(Serializable o, OutputStream os) throws IOException { 051 ObjectOutputStream oos=null; 052 try { 053 oos = new ObjectOutputStream(os); 054 oos.writeObject(o); 055 } 056 finally { 057 IOUtil.closeEL(oos); 058 IOUtil.closeEL(os); 059 } 060 } 061 062 /** 063 * unserialize a serialized Object 064 * @param str 065 * @return unserialized Object 066 * @throws IOException 067 * @throws ClassNotFoundException 068 * @throws CoderException 069 */ 070 public static Object deserialize(String str) throws IOException, ClassNotFoundException, CoderException { 071 ByteArrayInputStream bais = new ByteArrayInputStream(Base64Coder.decode(str)); 072 return deserialize(bais); 073 } 074 075 public static Object deserialize(InputStream is) throws IOException, ClassNotFoundException { 076 ObjectInputStream ois=null; 077 Object o=null; 078 try { 079 ois = new ObjectInputStream(is); 080 o=ois.readObject(); 081 } 082 finally { 083 IOUtil.closeEL(ois); 084 } 085 return o; 086 } 087 088 public static Object deserialize(Resource res) throws IOException, ClassNotFoundException { 089 return deserialize(res.getInputStream()); 090 } 091 092 093 }