2 * Copyright (C) 2010 Google Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package libcore.java.util;
19 import java.io.ByteArrayInputStream;
20 import java.io.ByteArrayOutputStream;
21 import java.io.IOException;
22 import java.io.ObjectInputStream;
23 import java.io.ObjectOutputStream;
24 import static junit.framework.Assert.assertEquals;
25 import static junit.framework.Assert.fail;
26 import junit.framework.AssertionFailedError;
28 public class SerializableTester<T> {
30 private final String golden;
31 private final T value;
33 public SerializableTester(T value, String golden) {
38 protected void verify(T deserialized) {}
42 if (golden == null || golden.length() == 0) {
43 fail("No golden value supplied! Consider using this: "
44 + hexEncode(serialize(value)));
47 // just a sanity check! if this fails, verify() is probably broken
50 @SuppressWarnings("unchecked") // deserialize should return the proper type
51 T deserialized = (T) deserialize(hexDecode(golden));
52 assertEquals("User-constructed value doesn't equal deserialized golden value",
56 @SuppressWarnings("unchecked") // deserialize should return the proper type
57 T reserialized = (T) deserialize(serialize(value));
58 assertEquals("User-constructed value doesn't equal itself, reserialized",
62 } catch (Exception e) {
63 Error failure = new AssertionFailedError();
69 private byte[] serialize(Object object) throws IOException {
70 ByteArrayOutputStream out = new ByteArrayOutputStream();
71 new ObjectOutputStream(out).writeObject(object);
72 return out.toByteArray();
75 private Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
76 ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes));
77 Object result = in.readObject();
78 assertEquals(-1, in.read());
82 private String hexEncode(byte[] bytes) {
83 StringBuilder result = new StringBuilder(bytes.length * 2);
84 for (byte b : bytes) {
85 result.append(String.format("%02x", b));
87 return result.toString();
90 private byte[] hexDecode(String s) {
91 byte[] result = new byte[s.length() / 2];
92 for (int i = 0; i < result.length; i++) {
93 result[i] = (byte) Integer.parseInt(s.substring(i*2, i*2 + 2), 16);