Skip to content
This repository has been archived by the owner on Sep 22, 2022. It is now read-only.

Commit

Permalink
Fix for #22 - Handling of gzip encoding
Browse files Browse the repository at this point in the history
  • Loading branch information
codami committed Oct 11, 2021
1 parent f93cf52 commit 161f821
Showing 1 changed file with 20 additions and 5 deletions.
25 changes: 20 additions & 5 deletions src/main/java/io/adven/grpc/wiremock/HttpMock.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import java.io.InputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URI;
import java.net.http.HttpClient;
Expand All @@ -22,6 +24,7 @@
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;
import java.util.zip.GZIPInputStream;

import static io.adven.grpc.wiremock.HeaderPropagationInterceptor.HEADERS;

Expand Down Expand Up @@ -86,7 +89,7 @@ public Response request(String path, Object message, Map<String, String> headers
.POST(asJson(message))
.headers(headers.entrySet().stream().flatMap(e -> Stream.of(e.getKey(), e.getValue())).toArray(String[]::new))
.build(),
HttpResponse.BodyHandlers.ofString()
HttpResponse.BodyHandlers.ofInputStream()
)
);
}
Expand All @@ -96,22 +99,34 @@ public Response request(String path, Object message) throws IOException, Interru
}

public static final class Response {
private final HttpResponse<String> httpResponse;
private final HttpResponse<InputStream> httpResponse;

public Response(HttpResponse<String> httpResponse) {
public Response(HttpResponse<InputStream> httpResponse) {
this.httpResponse = httpResponse;
}

public Message getMessage(Class<?> aClass) {
if (httpResponse.statusCode() == 200) {
return ProtoJsonUtil.fromJson(httpResponse.body(), aClass);
return ProtoJsonUtil.fromJson(getBody(), aClass);
}
throw new BadHttpResponseException(httpResponse.statusCode(), httpResponse.body());
throw new BadHttpResponseException(httpResponse.statusCode(), getBody());
}

public int streamSize() {
return httpResponse.headers().firstValue("streamSize").map(Integer::valueOf).orElse(1);
}

private String getBody() {
try {
InputStream bodyStream = httpResponse.body();
if (httpResponse.headers().firstValue("Content-Encoding").orElse("").equals("gzip")) {
bodyStream = new GZIPInputStream(bodyStream);
}
return new String(bodyStream.readAllBytes());
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}

private HttpRequest.BodyPublisher asJson(Object arg) throws IOException {
Expand Down

0 comments on commit 161f821

Please sign in to comment.