01: /*
02: * Copyright (c) 2003-2006 Terracotta, Inc. All rights reserved.
03: */
04: package com.tctest;
05:
06: import com.tc.object.BaseDSOTestCase;
07:
08: import java.io.ByteArrayInputStream;
09: import java.io.ByteArrayOutputStream;
10: import java.io.IOException;
11: import java.io.ObjectInputStream;
12: import java.io.ObjectOutputStream;
13: import java.io.Serializable;
14: import java.util.concurrent.ConcurrentHashMap;
15: import java.util.concurrent.LinkedBlockingQueue;
16: import java.util.concurrent.locks.ReentrantLock;
17:
18: /*
19: * TODO:: More tests needed. 1) Populated collections needs to be serialized and deserialized. 2) Serialized
20: * instrumented version of collections/objects should be deserializable by uninstrumented versions and vice versa
21: */
22: public class JDK15SerializationTest extends BaseDSOTestCase {
23: public void testConcurrentHashMapSerialization() throws Exception {
24: ConcurrentHashMap m = new ConcurrentHashMap();
25:
26: m.put("key1", "value1");
27: m.put("key2", "value2");
28:
29: checkSerialization(m);
30:
31: }
32:
33: public void testLinkedBlockingQueueSerialization() throws Exception {
34: LinkedBlockingQueue q = new LinkedBlockingQueue();
35: q.put("value1");
36: q.put("value2");
37:
38: checkSerialization(q);
39: }
40:
41: public void testReentrantLockSerialization() throws Exception {
42: ReentrantLock lock = new ReentrantLock();
43:
44: lock.lock();
45: try {
46: ReentrantLock deserializedLock = (ReentrantLock) checkSerialization(lock);
47: assertFalse(deserializedLock.isLocked());
48: assertTrue(lock.isLocked());
49: } finally {
50: lock.unlock();
51: }
52: }
53:
54: private Object checkSerialization(Object o) throws Exception {
55: if (!(o instanceof Serializable)) {
56: System.err.println("Skipping non-serializable "
57: + o.getClass().getName());
58: return null;
59: }
60:
61: return validateSerialization(o);
62: }
63:
64: private Object validateSerialization(Object o) throws Exception {
65: System.out.println("TESTING " + o.getClass());
66: assertTrue(o instanceof Serializable);
67:
68: return deserialize(serialize(o));
69: }
70:
71: private static byte[] serialize(Object obj) throws IOException {
72: ByteArrayOutputStream baos = new ByteArrayOutputStream();
73: ObjectOutputStream oos = new ObjectOutputStream(baos);
74: oos.writeObject(obj);
75: oos.close();
76: return baos.toByteArray();
77: }
78:
79: private static Object deserialize(byte[] data) throws IOException,
80: ClassNotFoundException {
81: ObjectInputStream ois = new ObjectInputStream(
82: new ByteArrayInputStream(data));
83: Object rv = ois.readObject();
84: ois.close();
85: return rv;
86: }
87:
88: }
|