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.distribution;
017
018import java.util.Random;
019
020/**
021 * The {@link RandomConfiguration} allows to get and set the seed of the random
022 * number generator.
023 * <p>
024 * Setting the seed allows to run test deterministically with the same generated
025 * objects. The {@link #setSeed(long)} method can be used for that.
026 * </p>
027 * <p>
028 * An the other hand the {@link #initSeed()} method sets a new random seed and
029 * return it. This allows to generate random test objects in one run and repeat
030 * the same test by setting the seed with {@link #setSeed(long)}.
031 * </p>
032 * <p>
033 * You can set the seed for the JVM with {@link #SEED_SYSTEM_PROPERTY}. This
034 * system property will be evaluated at start up. Calling {@link #setSeed(long)}
035 * will overwrite this setting.
036 * </p>
037 */
038public final class RandomConfiguration {
039
040    /**
041     * System property ({@code SEED_SYSTEM_PROPERTY}) to set the {@link Long long}
042     * seed value for the random number generator.
043     * <p>
044     * Note: The actual values generated by the RNG still depend on the execution
045     * order. That may be not under the control of quickcheck.
046     * </p>
047     */
048    public static final String SEED_SYSTEM_PROPERTY = "de.cuioss.test.generator.seed";
049    static final Random random = new Random(); // NOSONAR: owolff: This ist not about cryptography,
050    // therefore sufficient
051    static long lastSeed = 0L;
052
053    private RandomConfiguration() {
054    }
055
056    static {
057        readSystemProperty();
058    }
059
060    public static long initSeed() {
061        long seed = random.nextLong();
062        setSeed(seed);
063        return seed;
064    }
065
066    public static void setSeed(long seed) {
067        lastSeed = seed;
068        random.setSeed(seed);
069    }
070
071    public static long getLastSeed() {
072        return lastSeed;
073    }
074
075    static void readSystemProperty() {
076        String seed = System.getProperty(SEED_SYSTEM_PROPERTY);
077        if (seed == null)
078            return;
079        setSeed(Long.parseLong(seed));
080    }
081}