Skip to content

Commit

Permalink
complete refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
l-trotta committed Oct 8, 2024
1 parent 0e93afd commit d003cc6
Show file tree
Hide file tree
Showing 9 changed files with 103 additions and 123 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ public Function<List<String>, Boolean> onWarnings() {
}

@Override
public boolean retrieveOriginalJsonResponseOnException() {
public boolean keepResponseBodyOnException() {
return false;
}

Expand All @@ -116,7 +116,7 @@ public abstract static class AbstractBuilder<BuilderT extends AbstractBuilder<Bu
private HeaderMap headers;
private Map<String, String> parameters;
private Function<List<String>, Boolean> onWarnings;
private boolean retrieveOriginalJsonResponseOnException;
private boolean keepResponseBodyOnException;

public AbstractBuilder() {
}
Expand All @@ -125,14 +125,14 @@ public AbstractBuilder(DefaultTransportOptions options) {
this.headers = new HeaderMap(options.headers);
this.parameters = copyOrNull(options.parameters);
this.onWarnings = options.onWarnings;
this.retrieveOriginalJsonResponseOnException = options.retrieveOriginalJsonResponseOnException();
this.keepResponseBodyOnException = options.keepResponseBodyOnException();
}

protected abstract BuilderT self();

@Override
public BuilderT retrieveOriginalJsonResponseOnException(boolean value){
this.retrieveOriginalJsonResponseOnException = value;
public BuilderT keepResponseBodyOnException(boolean value){
this.keepResponseBodyOnException = value;
return self();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -335,11 +335,6 @@ private <ResponseT, ErrorT> ResponseT getApiResponse(

checkJsonContentType(entity.contentType(), clientResp, endpoint);

// We may have to replay it.
if (!entity.isRepeatable()) {
entity = new ByteArrayBinaryData(entity);
}

try (InputStream content = entity.asInputStream()) {
try (JsonParser parser = mapper.jsonProvider().createParser(content)) {
ErrorT error = errorDeserializer.deserialize(parser, mapper);
Expand Down Expand Up @@ -388,18 +383,6 @@ private <ResponseT> ResponseT decodeTransportResponse(
endpoint.id()
);
}
InputStream content = entity.asInputStream();
InputStream contentForException = null;

// if the option to print the original body has been set, the body has to be
// copied first to another stream to be read again by the exception class
if(options().retrieveOriginalJsonResponseOnException()) {
try(ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
entity.writeTo(baos);
content = new ByteArrayInputStream(baos.toByteArray());
contentForException = new ByteArrayInputStream(baos.toByteArray());
}
}

@SuppressWarnings("unchecked")
JsonEndpoint<?, ResponseT, ?> jsonEndpoint = (JsonEndpoint<?, ResponseT, ?>) endpoint;
Expand All @@ -409,12 +392,11 @@ private <ResponseT> ResponseT decodeTransportResponse(
if (responseParser != null) {
checkJsonContentType(entity.contentType(), clientResp, endpoint);
try (
JsonParser parser = mapper.jsonProvider().createParser(content)
JsonParser parser = mapper.jsonProvider().createParser(entity.asInputStream())
) {
response = responseParser.deserialize(parser, mapper);
} catch (Exception e) {
throw new TransportBodyResponseException(
contentForException,
throw new TransportException(
clientResp,
"Failed to decode response",
endpoint.id(),
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public interface TransportOptions {

Function<List<String>, Boolean> onWarnings();

boolean retrieveOriginalJsonResponseOnException();
boolean keepResponseBodyOnException();

Builder toBuilder();

Expand All @@ -62,6 +62,6 @@ interface Builder extends ObjectBuilder<TransportOptions> {

Builder onWarnings(Function<List<String>, Boolean> listener);

Builder retrieveOriginalJsonResponseOnException(boolean value);
Builder keepResponseBodyOnException(boolean value);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import co.elastic.clients.transport.http.HeaderMap;
import co.elastic.clients.transport.http.TransportHttpClient;
import co.elastic.clients.util.BinaryData;
import co.elastic.clients.util.ByteArrayBinaryData;
import co.elastic.clients.util.NoCopyByteArrayOutputStream;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
Expand All @@ -34,8 +35,10 @@
import org.elasticsearch.client.RestClient;

import javax.annotation.Nullable;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.AbstractList;
Expand Down Expand Up @@ -85,10 +88,14 @@ public RestClientOptions createOptions(@Nullable TransportOptions options) {
}

@Override
public Response performRequest(String endpointId, @Nullable Node node, Request request, TransportOptions options) throws IOException {
public Response performRequest(String endpointId, @Nullable Node node, Request request,
TransportOptions options) throws IOException {
RestClientOptions rcOptions = RestClientOptions.of(options);
org.elasticsearch.client.Request restRequest = createRestRequest(request, rcOptions);
org.elasticsearch.client.Response restResponse = restClient.performRequest(restRequest);
if (options.keepResponseBodyOnException()) {
return new RepeatableBodyResponse(restResponse);
}
return new RestResponse(restResponse);
}

Expand All @@ -103,7 +110,7 @@ public CompletableFuture<Response> performRequestAsync(
try {
RestClientOptions rcOptions = RestClientOptions.of(options);
restRequest = createRestRequest(request, rcOptions);
} catch(Throwable thr) {
} catch (Throwable thr) {
// Terminate early
future.completeExceptionally(thr);
return future;
Expand All @@ -112,6 +119,9 @@ public CompletableFuture<Response> performRequestAsync(
future.cancellable = restClient.performRequestAsync(restRequest, new ResponseListener() {
@Override
public void onSuccess(org.elasticsearch.client.Response response) {
if (options.keepResponseBodyOnException()) {
future.complete(new RepeatableBodyResponse(response));
}
future.complete(new RestResponse(response));
}

Expand Down Expand Up @@ -166,7 +176,7 @@ private org.elasticsearch.client.Request createRestRequest(Request request, Rest
if (body != null) {
ContentType ct = null;
String ctStr;
if (( ctStr = requestHeaders.get(HeaderMap.CONTENT_TYPE)) != null) {
if ((ctStr = requestHeaders.get(HeaderMap.CONTENT_TYPE)) != null) {
ct = ContentTypeCache.computeIfAbsent(ctStr, ContentType::parse);
}
clientReq.setEntity(new MultiBufferEntity(body, ct));
Expand Down Expand Up @@ -241,6 +251,51 @@ public void close() throws IOException {
}
}

public class RepeatableBodyResponse extends RestResponse {

BinaryData repeatableBody;

RepeatableBodyResponse(org.elasticsearch.client.Response restResponse) {
super(restResponse);
}

@Nullable
@Override
public BinaryData body() throws IOException {
if(repeatableBody != null) {
return repeatableBody;
}
BinaryData body = super.body();
if (body != null) {
if(body.isRepeatable()){
repeatableBody = body;
}
else{
repeatableBody = new ByteArrayBinaryData(body);
}
}
return repeatableBody;
}

public String getOriginalBodyAsString() throws IOException {
BinaryData body = body();

if (body != null) {
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(body.asInputStream()));
String read;

while ((read = br.readLine()) != null) {
sb.append(read);
}
br.close();
return sb.toString();
}
return null;
}

}

private static class HttpEntityBinaryData implements BinaryData {
private final HttpEntity entity;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public class RestClientOptions implements TransportOptions {

private final RequestOptions options;

boolean retrieveOriginalJsonResponseOnException;
boolean keepResponseBodyOnException;

@VisibleForTesting
static final String CLIENT_META_VALUE = getClientMeta();
Expand All @@ -65,7 +65,8 @@ static RestClientOptions of(@Nullable TransportOptions options) {
return builder.build();
}

public RestClientOptions(RequestOptions options) {
public RestClientOptions(RequestOptions options, boolean keepResponseBodyOnException) {
this.keepResponseBodyOnException = keepResponseBodyOnException;
this.options = addBuiltinHeaders(options.toBuilder()).build();
}

Expand Down Expand Up @@ -102,12 +103,8 @@ public Function<List<String>, Boolean> onWarnings() {
}

@Override
public boolean retrieveOriginalJsonResponseOnException() {
return this.retrieveOriginalJsonResponseOnException;
}

public void setRetrieveOriginalJsonResponseOnException(boolean retrieveOriginalJsonResponseOnException) {
this.retrieveOriginalJsonResponseOnException = retrieveOriginalJsonResponseOnException;
public boolean keepResponseBodyOnException() {
return this.keepResponseBodyOnException;
}

@Override
Expand All @@ -119,6 +116,8 @@ public static class Builder implements TransportOptions.Builder {

private RequestOptions.Builder builder;

private boolean keepResponseBodyOnException;

public Builder(RequestOptions.Builder builder) {
this.builder = builder;
}
Expand Down Expand Up @@ -193,18 +192,19 @@ public TransportOptions.Builder onWarnings(Function<List<String>, Boolean> liste
}

@Override
public TransportOptions.Builder retrieveOriginalJsonResponseOnException(boolean value) {
public TransportOptions.Builder keepResponseBodyOnException(boolean value) {
this.keepResponseBodyOnException = value;
return this;
}

@Override
public RestClientOptions build() {
return new RestClientOptions(addBuiltinHeaders(builder).build());
return new RestClientOptions(addBuiltinHeaders(builder).build(), keepResponseBodyOnException);
}
}

static RestClientOptions initialOptions() {
return new RestClientOptions(SafeResponseConsumer.DEFAULT_REQUEST_OPTIONS);
return new RestClientOptions(SafeResponseConsumer.DEFAULT_REQUEST_OPTIONS, false);
}

private static RequestOptions.Builder addBuiltinHeaders(RequestOptions.Builder builder) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ public Function<List<String>, Boolean> onWarnings() {
}

@Override
public boolean retrieveOriginalJsonResponseOnException() {
public boolean keepResponseBodyOnException() {
return false;
}

Expand Down
Loading

0 comments on commit d003cc6

Please sign in to comment.