io.sphere.sdk.client.OneTimeSphereAccessTokenSupplier Maven / Gradle / Ivy
package io.sphere.sdk.client;
import java.util.Optional;
import java.util.concurrent.CompletionStage;
//document auto closing
final class OneTimeSphereAccessTokenSupplier extends AutoCloseableService implements SphereAccessTokenSupplier {
private final SphereAccessTokenSupplier delegate;
private final boolean shouldCloseAutomatically;
private boolean isClosed = false;
private Optional> tokenFuture = Optional.empty();
private OneTimeSphereAccessTokenSupplier(final SphereAccessTokenSupplier delegate, final boolean shouldCloseAutomatically) {
this.delegate = delegate;
this.shouldCloseAutomatically = shouldCloseAutomatically;
}
@Override
protected synchronized void internalClose() {
if (shouldCloseAutomatically && !isClosed) {
delegate.close();
isClosed = true;
}
}
@Override
public final synchronized CompletionStage get() {
final CompletionStage future = tokenFuture.orElseGet(() -> {
final CompletionStage tokenFuture = fetchToken();
this.tokenFuture = Optional.of(tokenFuture);
return tokenFuture;
});
return future;
}
private CompletionStage fetchToken() {
final CompletionStage result = delegate.get();
if (shouldCloseAutomatically) {
result.whenComplete((a, b) -> close());
}
return result;
}
public static SphereAccessTokenSupplier of(final SphereAccessTokenSupplier delegate, final boolean shouldCloseAutomatically) {
return new OneTimeSphereAccessTokenSupplier(delegate, shouldCloseAutomatically);
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy