io.sphere.sdk.client.OneTimeSphereAccessTokenSupplier Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of commercetools-java-client-core Show documentation
Show all versions of commercetools-java-client-core Show documentation
This SDK is announced to be deprecated latest by 31 December 2022, please follow more details on SDK deprecation plan https://docs.commercetools.com/api/releases/2021-08-31-announced-long-term-support-plan-for-commercetools-sdks. We recommend you to use our new SDK here https://docs.commercetools.com/sdk/jvm-sdk#java-sdk-v2.
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() {
rejectExcutionIfClosed("token supplier already closed");
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);
}
}