1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.log4j.util;
19
20 import junit.framework.TestCase;
21
22 import java.io.ByteArrayInputStream;
23 import java.io.ByteArrayOutputStream;
24 import java.io.File;
25 import java.io.FileInputStream;
26 import java.io.FileOutputStream;
27 import java.io.IOException;
28 import java.io.ObjectInputStream;
29 import java.io.ObjectOutputStream;
30
31
32
33
34
35
36
37 public class SerializationTestHelper {
38
39
40
41 private SerializationTestHelper() {
42 }
43
44
45
46
47
48
49
50
51
52 public static Object serializeClone(final Object obj)
53 throws IOException, ClassNotFoundException {
54 ByteArrayOutputStream memOut = new ByteArrayOutputStream();
55 ObjectOutputStream objOut = new ObjectOutputStream(memOut);
56 objOut.writeObject(obj);
57 objOut.close();
58
59 ByteArrayInputStream src = new ByteArrayInputStream(memOut.toByteArray());
60 ObjectInputStream objIs = new ObjectInputStream(src);
61
62 return objIs.readObject();
63 }
64
65
66
67
68
69
70
71 public static Object deserializeStream(final String witness)
72 throws Exception {
73 FileInputStream fileIs = new FileInputStream(witness);
74 ObjectInputStream objIs = new ObjectInputStream(fileIs);
75
76 return objIs.readObject();
77 }
78
79
80
81
82
83
84
85
86
87
88
89 public static void assertSerializationEquals(
90 final String witness, final Object obj, final int[] skip,
91 final int endCompare) throws Exception {
92 ByteArrayOutputStream memOut = new ByteArrayOutputStream();
93 ObjectOutputStream objOut = new ObjectOutputStream(memOut);
94 objOut.writeObject(obj);
95 objOut.close();
96
97 assertStreamEquals(witness, memOut.toByteArray(), skip, endCompare);
98 }
99
100
101
102
103
104
105
106
107
108 public static void assertStreamEquals(
109 final String witness, final byte[] actual, final int[] skip,
110 final int endCompare) throws IOException {
111 File witnessFile = new File(witness);
112
113 if (witnessFile.exists()) {
114 int skipIndex = 0;
115 byte[] expected = new byte[actual.length];
116 FileInputStream is = new FileInputStream(witnessFile);
117 int bytesRead = is.read(expected);
118 is.close();
119
120 if(bytesRead < endCompare) {
121 TestCase.assertEquals(bytesRead, actual.length);
122 }
123
124 int endScan = actual.length;
125
126 if (endScan > endCompare) {
127 endScan = endCompare;
128 }
129
130 for (int i = 0; i < endScan; i++) {
131 if ((skipIndex < skip.length) && (skip[skipIndex] == i)) {
132 skipIndex++;
133 } else {
134 if (expected[i] != actual[i]) {
135 TestCase.assertEquals(
136 "Difference at offset " + i, expected[i], actual[i]);
137 }
138 }
139 }
140 } else {
141
142
143
144 FileOutputStream os = new FileOutputStream(witnessFile);
145 os.write(actual);
146 os.close();
147 TestCase.fail("Writing witness file " + witness);
148 }
149 }
150 }