use of io.servicetalk.http.api.TrailersTransformer in project servicetalk by apple.
the class ConsumeRequestPayloadOnResponsePathTest method test.
private void test(final BiFunction<Single<StreamingHttpResponse>, StreamingHttpRequest, Single<StreamingHttpResponse>> consumeRequestPayload) throws Exception {
try (ServerContext serverContext = HttpServers.forAddress(localAddress(0)).appendServiceFilter(service -> new StreamingHttpServiceFilter(service) {
@Override
public Single<StreamingHttpResponse> handle(final HttpServiceContext ctx, final StreamingHttpRequest request, final StreamingHttpResponseFactory responseFactory) {
return consumeRequestPayload.apply(delegate().handle(ctx, request, responseFactory), request);
}
}).listenStreamingAndAwait((ctx, request, responseFactory) -> {
final StreamingHttpResponse response = responseFactory.ok().addHeader(TRAILER, X_TOTAL_LENGTH).payloadBody(from("Response\n", "Payload\n", "Body\n"), appSerializerUtf8FixLen()).transform(new TrailersTransformer<AtomicInteger, Buffer>() {
@Override
public AtomicInteger newState() {
return new AtomicInteger();
}
@Override
public Buffer accept(final AtomicInteger total, final Buffer chunk) {
total.addAndGet(chunk.readableBytes());
return chunk;
}
@Override
public HttpHeaders payloadComplete(final AtomicInteger total, final HttpHeaders trailers) {
trailers.add(X_TOTAL_LENGTH, String.valueOf(total.get()));
return trailers;
}
@Override
public HttpHeaders catchPayloadFailure(final AtomicInteger __, final Throwable ___, final HttpHeaders trailers) {
return trailers;
}
});
return succeeded(response);
})) {
HttpResponse response;
try (BlockingHttpClient client = HttpClients.forSingleAddress(AddressUtils.serverHostAndPort(serverContext)).buildBlocking()) {
response = client.request(client.post("/").payloadBody(EXPECTED_REQUEST_PAYLOAD, textSerializerUtf8()));
serverLatch.await();
}
assertThat(response.status(), is(OK));
assertThat("Request payload body might be consumed by someone else", errorRef.get(), is(nullValue()));
assertThat(receivedPayload.toString(), is(EXPECTED_REQUEST_PAYLOAD));
assertThat(response.headers().contains(TRAILER, X_TOTAL_LENGTH), is(true));
assertThat(response.trailers().contains(X_TOTAL_LENGTH), is(true));
CharSequence trailerLength = response.trailers().get(X_TOTAL_LENGTH);
assertNotNull(trailerLength);
assertThat("Unexpected response payload: '" + response.payloadBody().toString(UTF_8) + "'", trailerLength.toString(), is(Integer.toString(response.payloadBody().readableBytes())));
}
}
Aggregations