1 package org.apache.jcs.utils.serialization;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import java.io.BufferedInputStream;
23 import java.io.ByteArrayInputStream;
24 import java.io.ByteArrayOutputStream;
25 import java.io.IOException;
26 import java.io.ObjectInputStream;
27 import java.io.ObjectOutputStream;
28 import java.io.Serializable;
29
30 import org.apache.jcs.engine.behavior.IElementSerializer;
31
32 /***
33 * Performs default serialization and de-serialization.
34 * <p>
35 * @author Aaron Smuts
36 */
37 public class StandardSerializer
38 implements IElementSerializer
39 {
40 /***
41 * Serializes an object using default serilaization.
42 */
43 public byte[] serialize( Serializable obj )
44 throws IOException
45 {
46 ByteArrayOutputStream baos = new ByteArrayOutputStream();
47 ObjectOutputStream oos = new ObjectOutputStream( baos );
48 try
49 {
50 oos.writeObject( obj );
51 }
52 finally
53 {
54 oos.close();
55 }
56 return baos.toByteArray();
57 }
58
59 /***
60 * Uses default de-serialization to turn a byte array into an object. All
61 * exceptions are converted into IOExceptions.
62 */
63 public Object deSerialize( byte[] data )
64 throws IOException, ClassNotFoundException
65 {
66 ByteArrayInputStream bais = new ByteArrayInputStream( data );
67 BufferedInputStream bis = new BufferedInputStream( bais );
68 ObjectInputStream ois = new ObjectInputStream( bis );
69 try
70 {
71 try
72 {
73 return ois.readObject();
74 }
75 catch ( IOException e )
76 {
77 throw e;
78 }
79 catch ( ClassNotFoundException e )
80 {
81 throw e;
82 }
83 }
84 finally
85 {
86 ois.close();
87 }
88 }
89 }