SimpleGeneratorWatcher.java

package net.morimekta.providence.testing.junit4;

import io.codearte.jfairy.Fairy;
import net.morimekta.providence.testing.generator.GeneratorContext;

import javax.annotation.Nonnull;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Simple non-generic watcher with no extra context on message generation.
 */
public final class SimpleGeneratorWatcher
        extends GeneratorWatcher<SimpleGeneratorWatcher.Context> {
    public static SimpleGeneratorWatcher create() {
        return new SimpleGeneratorWatcher();
    }

    /**
     * Make a simple default message generator.
     */
    public SimpleGeneratorWatcher() {
        super(new Context());
    }

    /**
     * Context for generating messages with information related to each other.
     * Also contains references to basic options affecting the generation
     * like the random generator, and default max collection size.
     */
    public static class Context extends GeneratorContext<Context> {
        private Locale locale;
        private Fairy  fairy;

        public Context() {
            this.locale = Locale.US;
            this.fairy = getFairySingleton(Locale.US);
        }

        @SuppressWarnings("unused")
        public Context(Context copy) {
            super(copy);
            this.locale = copy.locale;
            this.fairy = copy.fairy;
        }

        @Nonnull
        public Context setFairy(Fairy fairy) {
            this.fairy = fairy;
            return this;
        }

        @Nonnull
        public Context setLocale(@Nonnull Locale locale) {
            this.locale = locale;
            this.fairy = getFairySingleton(locale);
            return this;
        }

        /**
         * @return The current fairy instance.
         */
        @Nonnull
        public Fairy getFairy() {
            return fairy;
        }

        @Nonnull
        public Locale getLocale() {
            return locale;
        }
    }

    private static Fairy getFairySingleton(Locale locale) {
        return fairyInstances.computeIfAbsent(locale, l -> Fairy.create(locale));
    }

    private static final Map<Locale,Fairy> fairyInstances = new ConcurrentHashMap<>();
}