
com.chavaillaz.client.common.apache.CompletableFutureCallback Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of common-client Show documentation
Show all versions of common-client Show documentation
Library for the creation of asynchronous clients supporting multiple HTTP clients
package com.chavaillaz.client.common.apache;
import java.util.concurrent.CompletableFuture;
import com.chavaillaz.client.common.AbstractHttpClient;
import com.chavaillaz.client.common.exception.ResponseException;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
import org.apache.hc.client5.http.async.methods.SimpleHttpResponse;
import org.apache.hc.core5.concurrent.FutureCallback;
/**
* Future callback for Apache HTTP Client in order to transfer state to a {@link CompletableFuture}.
* It completes exceptionally if the response code is not in the 2xx or 3xx range (see {@link ResponseException})
* or if a connection failure happens (e.g. timeout).
*/
@Slf4j
@AllArgsConstructor
public class CompletableFutureCallback implements FutureCallback {
private final AbstractHttpClient client;
private final SimpleHttpRequest request;
private final CompletableFuture future;
@Override
public void completed(SimpleHttpResponse response) {
log.debug("Request {} completed: {}", request, response);
if (response.getCode() >= 400) {
future.completeExceptionally(client.responseException(response.getCode(), response.getBodyText()));
} else {
future.complete(response);
}
}
@Override
public void failed(Exception exception) {
log.debug("Request {} failed: {}", request, exception.getMessage());
future.completeExceptionally(exception);
}
@Override
public void cancelled() {
log.debug("Request {} cancelled", request);
future.cancel(false);
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy