1/*
2 * Copyright (C) 2008 The Guava Authors
3 *
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
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
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.
15 */
16
17package com.google.common.collect.testing;
18
19import java.io.ByteArrayInputStream;
20import java.io.ByteArrayOutputStream;
21import java.io.IOException;
22import java.io.ObjectInputStream;
23import java.io.ObjectOutputStream;
24import java.util.Collection;
25import java.util.List;
26
27/**
28 * Reserializes the sets created by another test set generator.
29 *
30 * TODO: make CollectionTestSuiteBuilder test reserialized collections
31 *
32 * @author Jesse Wilson
33 */
34public class ReserializingTestCollectionGenerator<E>
35    implements TestCollectionGenerator<E> {
36  private final TestCollectionGenerator<E> delegate;
37
38  ReserializingTestCollectionGenerator(TestCollectionGenerator<E> delegate) {
39    this.delegate = delegate;
40  }
41
42  public static <E> ReserializingTestCollectionGenerator<E> newInstance(
43      TestCollectionGenerator<E> delegate) {
44    return new ReserializingTestCollectionGenerator<E>(delegate);
45  }
46
47  @Override
48  public Collection<E> create(Object... elements) {
49    return reserialize(delegate.create(elements));
50  }
51
52  @SuppressWarnings("unchecked")
53  static <T> T reserialize(T object) {
54    try {
55      ByteArrayOutputStream bytes = new ByteArrayOutputStream();
56      ObjectOutputStream out = new ObjectOutputStream(bytes);
57      out.writeObject(object);
58      ObjectInputStream in = new ObjectInputStream(
59          new ByteArrayInputStream(bytes.toByteArray()));
60      return (T) in.readObject();
61    } catch (IOException e) {
62      Helpers.fail(e, e.getMessage());
63    } catch (ClassNotFoundException e) {
64      Helpers.fail(e, e.getMessage());
65    }
66    throw new AssertionError("not reachable");
67  }
68
69  @Override
70  public SampleElements<E> samples() {
71    return delegate.samples();
72  }
73
74  @Override
75  public E[] createArray(int length) {
76    return delegate.createArray(length);
77  }
78
79  @Override
80  public Iterable<E> order(List<E> insertionOrder) {
81    return delegate.order(insertionOrder);
82  }
83}