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

io.sphere.sdk.client.OneTimeSphereAccessTokenSupplier Maven / Gradle / Ivy

There is a newer version: 1.0.0-M26
Show newest version
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