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 17 package com.google.common.collect.testing; 18 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 java.util.Collection; 25 import 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 */ 34 public class ReserializingTestCollectionGenerator<E> 35 implements TestCollectionGenerator<E> { 36 private final TestCollectionGenerator<E> delegate; 37 ReserializingTestCollectionGenerator(TestCollectionGenerator<E> delegate)38 ReserializingTestCollectionGenerator(TestCollectionGenerator<E> delegate) { 39 this.delegate = delegate; 40 } 41 newInstance( TestCollectionGenerator<E> delegate)42 public static <E> ReserializingTestCollectionGenerator<E> newInstance( 43 TestCollectionGenerator<E> delegate) { 44 return new ReserializingTestCollectionGenerator<E>(delegate); 45 } 46 47 @Override create(Object... elements)48 public Collection<E> create(Object... elements) { 49 return reserialize(delegate.create(elements)); 50 } 51 52 @SuppressWarnings("unchecked") reserialize(T object)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 samples()70 public SampleElements<E> samples() { 71 return delegate.samples(); 72 } 73 74 @Override createArray(int length)75 public E[] createArray(int length) { 76 return delegate.createArray(length); 77 } 78 79 @Override order(List<E> insertionOrder)80 public Iterable<E> order(List<E> insertionOrder) { 81 return delegate.order(insertionOrder); 82 } 83 }