All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.mstream.trader.commons.config.ConfigSupplier Maven / Gradle / Ivy

package io.mstream.trader.commons.config;


import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import ratpack.service.Service;
import ratpack.service.StartEvent;

import javax.inject.Inject;
import java.util.Optional;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

public class ConfigSupplier implements Supplier, Service {

    private static final Logger LOGGER = LogManager.getLogger();

    private final Class configType;
    private final ConfigClient configClient;
    private final ScheduledExecutorService executor;
    private volatile T config;

    @Inject
    public ConfigSupplier(
            @Config Class configType,
            ConfigClient configClient,
            ScheduledExecutorService executor
    ) {
        this.configType = configType;
        this.configClient = configClient;
        this.executor = executor;
    }


    @Override
    public void onStart(StartEvent event) throws Exception {
        executor.scheduleAtFixedRate(
                this::loadConfig,
                0,
                10,
                TimeUnit.SECONDS
        );
    }

    private void loadConfig() {
        if (config != null) {
            return;
        }
        Optional configOpt = configClient.read(configType);
        if (!configOpt.isPresent()) {
            LOGGER.error("config can't be loaded");
        } else {
            config = configOpt.get();
        }
    }

    @Override
    public T get() {
        loadConfig();
        if (config == null) {
            throw new IllegalStateException("config is not loaded");
        }
        return config;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy