1 package org.apache.jcs.engine;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import java.io.ByteArrayInputStream;
23 import java.io.ByteArrayOutputStream;
24 import java.io.IOException;
25 import java.io.ObjectInputStream;
26 import java.io.ObjectOutputStream;
27 import java.io.Serializable;
28
29 /***
30 * This will be superceded by the new pluggable serializer infastructure.
31 * <p>
32 * basic utility functions
33 * <p>
34 * TODO move to util
35 */
36 public final class CacheUtils
37 {
38 /*** No instances please. */
39 private CacheUtils()
40 {
41 super();
42 }
43
44 /***
45 * Returns a deeply cloned object.
46 * @param obj
47 * @return
48 * @throws IOException
49 */
50 public static Serializable dup( Serializable obj )
51 throws IOException
52 {
53 return deserialize( serialize( obj ) );
54 }
55
56 /***
57 * Returns the serialized form of the given object in a byte array.
58 * <p>
59 * @param obj
60 * @return
61 * @throws IOException
62 */
63 public static byte[] serialize( Serializable obj )
64 throws IOException
65 {
66 ByteArrayOutputStream baos = new ByteArrayOutputStream();
67 ObjectOutputStream oos = new ObjectOutputStream( baos );
68 try
69 {
70 oos.writeObject( obj );
71 }
72 finally
73 {
74 oos.close();
75 }
76 return baos.toByteArray();
77 }
78
79 /***
80 * Returns the object deserialized from the given byte array.
81 * <p>
82 * @param buf
83 * @return
84 * @throws IOException
85 */
86 public static Serializable deserialize( byte[] buf )
87 throws IOException
88 {
89 ByteArrayInputStream bais = new ByteArrayInputStream( buf );
90 ObjectInputStream ois = new ObjectInputStream( bais );
91 try
92 {
93 return (Serializable) ois.readObject();
94 }
95 catch ( ClassNotFoundException ex )
96 {
97
98 ex.printStackTrace();
99 throw new IllegalStateException( ex.getMessage() );
100 }
101 finally
102 {
103 ois.close();
104 }
105 }
106 }