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

io.vrap.rmf.base.client.oauth2.InMemoryTokenSupplier Maven / Gradle / Ivy

There is a newer version: 17.17.0
Show newest version

package io.vrap.rmf.base.client.oauth2;

import java.time.Duration;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;

import io.vrap.rmf.base.client.AuthenticationToken;
import io.vrap.rmf.base.client.AutoCloseableService;

import dev.failsafe.Failsafe;
import dev.failsafe.FailsafeExecutor;
import dev.failsafe.Timeout;
import dev.failsafe.spi.Scheduler;

public class InMemoryTokenSupplier extends AutoCloseableService implements RefreshableTokenSupplier {
    private final TokenSupplier supplier;
    private final Object lock = new Object();
    private volatile CompletableFuture tokenFuture;

    private final FailsafeExecutor failsafeExecutor;

    public InMemoryTokenSupplier(TokenSupplier tokenSupplier) {
        this(Scheduler.DEFAULT, tokenSupplier);
    }

    public InMemoryTokenSupplier(ScheduledExecutorService executorService, TokenSupplier tokenSupplier) {
        this(Scheduler.of(executorService), tokenSupplier);
    }

    public InMemoryTokenSupplier(ExecutorService executorService, TokenSupplier tokenSupplier) {
        this(Scheduler.of(executorService), tokenSupplier);
    }

    public InMemoryTokenSupplier(Scheduler scheduler, TokenSupplier tokenSupplier) {
        this.supplier = tokenSupplier;
        this.failsafeExecutor = Failsafe.with(Timeout. of(Duration.ofSeconds(10))).with(scheduler);
    }

    public CompletableFuture getToken() {
        if (tokenFuture == null)
            synchronized (lock) {
                if (tokenFuture == null) {
                    tokenFuture = failsafeExecutor.getStageAsync(supplier::getToken);
                }
            }
        return tokenFuture;
    }

    public CompletableFuture refreshToken() {
        synchronized (lock) {
            tokenFuture = null;
        }
        return getToken();
    }

    @Override
    protected void internalClose() {
        if (supplier instanceof AutoCloseable)
            closeQuietly((AutoCloseable) supplier);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy