001/*
002 * Copyright © 2025 CUI-OpenSource-Software (info@cuioss.de)
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 */
016package de.cuioss.test.generator.internal.net.java.quickcheck.generator.support;
017
018import de.cuioss.test.generator.internal.net.java.quickcheck.Generator;
019
020import java.io.ByteArrayInputStream;
021import java.io.ByteArrayOutputStream;
022import java.io.IOException;
023import java.io.ObjectInputStream;
024import java.io.ObjectOutputStream;
025
026/**
027 * A cloning generator which uses object serialization to create clones of the
028 * prototype object. For each call of {@link CloningGenerator#next()} a new copy
029 * of the prototype will be generated.
030 *
031 * @param <T> Type of the prototype object
032 *
033 */
034public class CloningGenerator<T> implements Generator<T> {
035
036    private final T prototype;
037
038    public CloningGenerator(T prototype) {
039        this.prototype = prototype;
040    }
041
042    /**
043     * Generate a new instance of the prototype object.
044     */
045    @Override
046    public T next() {
047        try {
048            return cloneObject();
049        } catch (IOException e) {
050            throw new IllegalArgumentException("prototype " + prototype + " not serializable.", e);
051        } catch (ClassNotFoundException e) {
052            throw new IllegalStateException("this should not happen " + e.getMessage(), e);
053        }
054    }
055
056    private T cloneObject() throws IOException, ClassNotFoundException {
057        ByteArrayOutputStream bytesStream = new ByteArrayOutputStream();
058        ObjectOutputStream objectOutputStream = new ObjectOutputStream(bytesStream);
059        objectOutputStream.writeObject(prototype);
060        objectOutputStream.flush();
061        objectOutputStream.close();
062        ObjectInputStream objectInputStream = new ObjectInputStream(
063                new ByteArrayInputStream(bytesStream.toByteArray()));
064        return castObjectToT(objectInputStream);
065    }
066
067    @SuppressWarnings("unchecked")
068    private T castObjectToT(ObjectInputStream objectInputStream) throws IOException, ClassNotFoundException {
069        return (T) objectInputStream.readObject();
070    }
071
072}