001/*
002 * Copyright (C) 2008 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.google.common.collect.testing;
018
019import com.google.common.annotations.GwtIncompatible;
020import java.io.ByteArrayInputStream;
021import java.io.ByteArrayOutputStream;
022import java.io.IOException;
023import java.io.ObjectInputStream;
024import java.io.ObjectOutputStream;
025import java.util.Collection;
026import java.util.List;
027
028/**
029 * Reserializes the sets created by another test set generator.
030 *
031 * <p>TODO: make CollectionTestSuiteBuilder test reserialized collections
032 *
033 * @author Jesse Wilson
034 */
035@GwtIncompatible
036public class ReserializingTestCollectionGenerator<E> implements TestCollectionGenerator<E> {
037  private final TestCollectionGenerator<E> delegate;
038
039  ReserializingTestCollectionGenerator(TestCollectionGenerator<E> delegate) {
040    this.delegate = delegate;
041  }
042
043  public static <E> ReserializingTestCollectionGenerator<E> newInstance(
044      TestCollectionGenerator<E> delegate) {
045    return new ReserializingTestCollectionGenerator<>(delegate);
046  }
047
048  @Override
049  public Collection<E> create(Object... elements) {
050    return reserialize(delegate.create(elements));
051  }
052
053  @SuppressWarnings("unchecked")
054  static <T> T reserialize(T object) {
055    try {
056      ByteArrayOutputStream bytes = new ByteArrayOutputStream();
057      ObjectOutputStream out = new ObjectOutputStream(bytes);
058      out.writeObject(object);
059      ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes.toByteArray()));
060      return (T) in.readObject();
061    } catch (IOException | ClassNotFoundException e) {
062      Helpers.fail(e, e.getMessage());
063    }
064    throw new AssertionError("not reachable");
065  }
066
067  @Override
068  public SampleElements<E> samples() {
069    return delegate.samples();
070  }
071
072  @Override
073  public E[] createArray(int length) {
074    return delegate.createArray(length);
075  }
076
077  @Override
078  public Iterable<E> order(List<E> insertionOrder) {
079    return delegate.order(insertionOrder);
080  }
081}