001/*
002 * Licensed to the author under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 * http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package de.cuioss.test.generator.internal.net.java.quickcheck.generator.support;
018
019import java.io.ByteArrayInputStream;
020import java.io.ByteArrayOutputStream;
021import java.io.IOException;
022import java.io.ObjectInputStream;
023import java.io.ObjectOutputStream;
024
025import de.cuioss.test.generator.internal.net.java.quickcheck.Generator;
026
027/**
028 * A cloning generator which uses object serialization to create clones of the
029 * prototype object. For each call of {@link CloningGenerator#next()} a new copy
030 * of the prototype will be generated.
031 *
032 * @param <T> Type of the prototype object
033 *
034 */
035public class CloningGenerator<T> implements Generator<T> {
036
037    private final T prototype;
038
039    public CloningGenerator(T prototype) {
040        this.prototype = prototype;
041    }
042
043    /**
044     * Generate a new instance of the prototype object.
045     */
046    @Override
047    public T next() {
048        try {
049            return cloneObject();
050        } catch (IOException e) {
051            throw new IllegalArgumentException("prototype " + prototype + " not serializable.", e);
052        } catch (ClassNotFoundException e) {
053            throw new RuntimeException("this should not happen " + e.getMessage(), e);
054        }
055    }
056
057    private T cloneObject() throws IOException, ClassNotFoundException {
058        ByteArrayOutputStream bytesStream = new ByteArrayOutputStream();
059        ObjectOutputStream objectOutputStream = new ObjectOutputStream(bytesStream);
060        objectOutputStream.writeObject(prototype);
061        objectOutputStream.flush();
062        objectOutputStream.close();
063        ObjectInputStream objectInputStream = new ObjectInputStream(
064                new ByteArrayInputStream(bytesStream.toByteArray()));
065        return castObjectToT(objectInputStream);
066    }
067
068    @SuppressWarnings("unchecked")
069    private T castObjectToT(ObjectInputStream objectInputStream) throws IOException, ClassNotFoundException {
070        return (T) objectInputStream.readObject();
071    }
072
073}