1 package org.apache.turbine.util;
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 import java.util.Map;
29
30
31
32
33
34
35
36
37 public abstract class ObjectUtils
38 {
39
40
41
42
43
44
45
46
47
48 public static byte[] serializeMap(Map<String, Object> map)
49 throws Exception
50 {
51 byte[] byteArray = null;
52
53 for (Object value : map.values())
54 {
55 if (! (value instanceof Serializable))
56 {
57 throw new Exception("Could not serialize, value is not serializable:" + value);
58 }
59 }
60
61 ByteArrayOutputStream baos = null;
62 ObjectOutputStream out = null;
63 try
64 {
65
66 baos = new ByteArrayOutputStream(1024);
67 out = new ObjectOutputStream(baos);
68
69 out.writeObject(map);
70 out.flush();
71
72 byteArray = baos.toByteArray();
73 }
74 finally
75 {
76 if (out != null)
77 {
78 out.close();
79 }
80 if (baos != null)
81 {
82 baos.close();
83 }
84 }
85
86 return byteArray;
87 }
88
89
90
91
92
93
94
95
96 @SuppressWarnings("unchecked")
97 public static <T> T deserialize(byte[] objectData)
98 {
99 T object = null;
100
101 if (objectData != null)
102 {
103
104 ObjectInputStream in = null;
105 ByteArrayInputStream bin = new ByteArrayInputStream(objectData);
106
107 try
108 {
109 in = new ObjectInputStream(bin);
110
111
112
113 object = (T)in.readObject();
114 }
115 catch (Exception e)
116 {
117
118 }
119 finally
120 {
121 try
122 {
123 if (in != null)
124 {
125 in.close();
126 }
127 bin.close();
128 }
129 catch (IOException e)
130 {
131
132 }
133 }
134 }
135 return object;
136 }
137 }