1 package org.springframework.security.oauth2.common.util;
2
3 import java.io.ByteArrayInputStream;
4 import java.io.ByteArrayOutputStream;
5 import java.io.IOException;
6 import java.io.ObjectInputStream;
7 import java.io.ObjectOutputStream;
8
9 import org.springframework.core.ConfigurableObjectInputStream;
10
11 public class SerializationUtils {
12
13 public static byte[] serialize(Object state) {
14 ObjectOutputStream oos = null;
15 try {
16 ByteArrayOutputStream bos = new ByteArrayOutputStream(512);
17 oos = new ObjectOutputStream(bos);
18 oos.writeObject(state);
19 oos.flush();
20 return bos.toByteArray();
21 }
22 catch (IOException e) {
23 throw new IllegalArgumentException(e);
24 }
25 finally {
26 if (oos != null) {
27 try {
28 oos.close();
29 }
30 catch (IOException e) {
31
32 }
33 }
34 }
35 }
36
37 public static <T> T deserialize(byte[] byteArray) {
38 ObjectInputStream oip = null;
39 try {
40 oip = new ConfigurableObjectInputStream(new ByteArrayInputStream(byteArray),
41 Thread.currentThread().getContextClassLoader());
42 @SuppressWarnings("unchecked")
43 T result = (T) oip.readObject();
44 return result;
45 }
46 catch (IOException e) {
47 throw new IllegalArgumentException(e);
48 }
49 catch (ClassNotFoundException e) {
50 throw new IllegalArgumentException(e);
51 }
52 finally {
53 if (oip != null) {
54 try {
55 oip.close();
56 }
57 catch (IOException e) {
58
59 }
60 }
61 }
62 }
63
64 }