1 package org.jbpm.context.exe.converter; 2 3 import java.io.*; 4 import org.apache.commons.codec.binary.*; 5 import org.jbpm.context.exe.*; 6 7 public class SerializableToStringConverter implements Converter { 8 9 private static final long serialVersionUID = 1L; 10 11 public boolean supports(Class clazz) { 12 return (Serializable.class.isAssignableFrom(clazz)); 13 } 14 15 private Object getBase64() { 16 try { 17 return new Base64(); 18 } catch (RuntimeException e) { 19 throw new RuntimeException ("for storing serializable objects as variables, you need to put the commons-codec-x.x.jar in the classpath", e); 20 } 21 } 22 23 public Object convert(Object o) { 24 byte[] bytes = null; 25 try { 26 ByteArrayOutputStream baos = new ByteArrayOutputStream(); 27 ObjectOutputStream oos = new ObjectOutputStream(baos); 28 oos.writeObject(o); 29 oos.flush(); 30 bytes = baos.toByteArray(); 31 } catch (IOException e) { 32 throw new RuntimeException ("couldn't serialize '"+o+"'", e); 33 } 34 35 bytes = ((Base64)getBase64()).encode(bytes); 37 return new String (bytes); 39 } 40 41 public Object revert(Object o) { 42 byte[] bytes = ((String )o).getBytes(); 44 bytes = ((Base64)getBase64()).decode(bytes); 46 47 try { 48 ByteArrayInputStream bais = new ByteArrayInputStream(bytes); 49 ObjectInputStream ois = new ObjectInputStream(bais); 50 return ois.readObject(); 51 } catch (Exception e) { 52 throw new RuntimeException ("couldn't deserialize object", e); 53 } 54 } 55 } 56 | Popular Tags |