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;
019import de.cuioss.test.generator.internal.net.java.quickcheck.ObjectGenerator;
020
021import java.lang.reflect.Method;
022import java.util.HashMap;
023import java.util.Map;
024
025/**
026 * {@link ObjectGenerator} implementation that can generate object graphs with
027 * default primitive value generators.
028 */
029public class ObjectDefaultMappingGenerator<T> extends ObjectGeneratorImpl<T> {
030
031    private static final Map<Class<?>, Generator<?>> RETURN_TYPE_TO_GENERATOR = new HashMap<>();
032
033    static {
034        map(new IntegerGenerator(), Integer.class, int.class);
035        map(new StringGenerator(), String.class);
036        map(new LongGenerator(), Long.class, long.class);
037        map(new DoubleGenerator(), Double.class, double.class, Number.class);
038        map(new ByteGenerator(), byte.class, Byte.class);
039    }
040
041    public ObjectDefaultMappingGenerator(Class<T> objectType) {
042        super(objectType);
043        mapMethodsToGenerators();
044    }
045
046    private static void map(Generator<?> generator, Class<?>... classes) {
047        for (Class<?> c : classes) {
048            RETURN_TYPE_TO_GENERATOR.put(c, generator);
049        }
050    }
051
052    private void mapMethodsToGenerators() {
053        for (Method method : definition.getType().getMethods()) {
054            Class<?> returnType = method.getReturnType();
055            Generator<?> generator = RETURN_TYPE_TO_GENERATOR.get(returnType);
056            if (generator == null && returnType.isInterface()) {
057                generator = buildGenerator(returnType);
058            }
059            definition.defineMapping(method, generator);
060        }
061    }
062
063    private <R> ObjectDefaultMappingGenerator<R> buildGenerator(Class<R> returnType) {
064        return new ObjectDefaultMappingGenerator<>(returnType);
065    }
066}