KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jbpm > context > exe > converter > SerializableToStringConverter


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 JavaDoc clazz) {
12     return (Serializable.class.isAssignableFrom(clazz));
13   }
14
15   private Object JavaDoc getBase64() {
16     try {
17       return new Base64();
18     } catch (RuntimeException JavaDoc e) {
19       throw new RuntimeException JavaDoc("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 JavaDoc convert(Object JavaDoc 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 JavaDoc("couldn't serialize '"+o+"'", e);
33     }
34     
35     // encode the value using base64 encoding
36
bytes = ((Base64)getBase64()).encode(bytes);
37     // create a string with the encoded value
38
return new String JavaDoc(bytes);
39   }
40
41   public Object JavaDoc revert(Object JavaDoc o) {
42     // get the value of the text
43
byte[] bytes = ((String JavaDoc)o).getBytes();
44     // decode the value of the serializedValue
45
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 JavaDoc e) {
52       throw new RuntimeException JavaDoc("couldn't deserialize object", e);
53     }
54   }
55 }
56
Popular Tags