io.vrap.rmf.base.client.oauth2.InMemoryTokenSupplier Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of rmf-java-base Show documentation
Show all versions of rmf-java-base Show documentation
The e-commerce SDK from commercetools Composable Commerce for Java
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);
}
}