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

datahub.client.MetadataResponseFuture Maven / Gradle / Ivy

There is a newer version: 1.0.0-beta2
Show newest version
package datahub.client;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicReference;
import lombok.SneakyThrows;
import org.apache.http.HttpResponse;


public class MetadataResponseFuture implements Future {
  private final Future requestFuture;
  private final AtomicReference responseReference;
  private final CountDownLatch responseLatch;
  private final ResponseMapper mapper;

  public MetadataResponseFuture(Future underlyingFuture,
      AtomicReference responseAtomicReference, CountDownLatch responseLatch) {
    this.requestFuture = underlyingFuture;
    this.responseReference = responseAtomicReference;
    this.responseLatch = responseLatch;
    this.mapper = null;
  }

  public MetadataResponseFuture(Future underlyingFuture, ResponseMapper mapper) {
    this.requestFuture = underlyingFuture;
    this.responseReference = null;
    this.responseLatch = null;
    this.mapper = mapper;
  }

  @Override
  public boolean cancel(boolean mayInterruptIfRunning) {
    return requestFuture.cancel(mayInterruptIfRunning);
  }

  @Override
  public boolean isCancelled() {
    return requestFuture.isCancelled();
  }

  @Override
  public boolean isDone() {
    return requestFuture.isDone();
  }

  @SneakyThrows
  @Override
  public MetadataWriteResponse get() throws InterruptedException, ExecutionException {
    HttpResponse response = requestFuture.get();
    if (mapper != null) {
      return mapper.map(response);
    } else {
      // We wait for the callback to fill this out
      responseLatch.await();
      return responseReference.get();
    }
  }

  @Override
  public MetadataWriteResponse get(long timeout, TimeUnit unit)
      throws InterruptedException, ExecutionException, TimeoutException {
    HttpResponse response = requestFuture.get(timeout, unit);
    if (mapper != null) {
      return mapper.map(response);
    } else {
      // We wait for the callback to fill this out
      responseLatch.await();
      return responseReference.get();
    }
  }

  @FunctionalInterface
  public interface ResponseMapper {
    MetadataWriteResponse map(HttpResponse httpResponse);
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy