1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418
|
/*
* Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 8328919
* @summary tests `limiting()` in `HttpResponse.Body{Handlers,Subscribers}`
* @key randomness
* @library /test/lib
* /test/jdk/java/net/httpclient/lib
* @build jdk.httpclient.test.lib.common.HttpServerAdapters
* jdk.test.lib.RandomFactory
* jdk.test.lib.net.SimpleSSLContext
* @run junit HttpResponseLimitingTest
*/
import jdk.httpclient.test.lib.common.HttpServerAdapters.HttpTestServer;
import jdk.test.lib.RandomFactory;
import jdk.test.lib.net.SimpleSSLContext;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpHeaders;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandler;
import java.net.http.HttpResponse.BodyHandlers;
import java.net.http.HttpResponse.BodySubscriber;
import java.net.http.HttpResponse.BodySubscribers;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.Flow.Subscription;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.net.http.HttpClient.Builder.NO_PROXY;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Arrays.copyOfRange;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
class HttpResponseLimitingTest {
private static final Random RANDOM = RandomFactory.getRandom();
private static final byte[] RESPONSE_BODY = "random non-empty body".getBytes(UTF_8);
private static final String RESPONSE_HEADER_NAME = "X-Excessive-Data";
/**
* A header value larger than {@link #RESPONSE_BODY} to verify that {@code limiting()} doesn't affect header parsing.
*/
private static final String RESPONSE_HEADER_VALUE = "!".repeat(RESPONSE_BODY.length + 1);
private static final ServerClientPair HTTP1 = ServerClientPair.of(HttpClient.Version.HTTP_1_1, false);
private static final ServerClientPair HTTPS1 = ServerClientPair.of(HttpClient.Version.HTTP_1_1, true);
private static final ServerClientPair HTTP2 = ServerClientPair.of(HttpClient.Version.HTTP_2, false);
private static final ServerClientPair HTTPS2 = ServerClientPair.of(HttpClient.Version.HTTP_2, true);
private record ServerClientPair(HttpTestServer server, HttpClient client, HttpRequest request) {
private static final SSLContext SSL_CONTEXT = createSslContext();
private static SSLContext createSslContext() {
try {
return new SimpleSSLContext().get();
} catch (IOException exception) {
throw new UncheckedIOException(exception);
}
}
private ServerClientPair {
try {
server.start();
} catch (Exception serverException) {
try {
client.close();
} catch (Exception clientException) {
Exception localClientException = new RuntimeException("failed closing client", clientException);
serverException.addSuppressed(localClientException);
}
throw new RuntimeException("failed closing server", serverException);
}
}
private static ServerClientPair of(HttpClient.Version version, boolean secure) {
// Create the server and the request URI
SSLContext sslContext = secure ? SSL_CONTEXT : null;
HttpTestServer server = createServer(version, sslContext);
String handlerPath = "/";
String requestUriScheme = secure ? "https" : "http";
URI requestUri = URI.create(requestUriScheme + "://" + server.serverAuthority() + handlerPath);
// Register the request handler
server.addHandler(
(exchange) -> {
exchange.getResponseHeaders().addHeader(RESPONSE_HEADER_NAME, RESPONSE_HEADER_VALUE);
exchange.sendResponseHeaders(200, RESPONSE_BODY.length);
try (var outputStream = exchange.getResponseBody()) {
outputStream.write(RESPONSE_BODY);
}
exchange.close();
},
handlerPath);
// Create the client and the request
HttpClient client = createClient(version, sslContext);
HttpRequest request = HttpRequest.newBuilder(requestUri).version(version).build();
// Create the pair
return new ServerClientPair(server, client, request);
}
private static HttpTestServer createServer(HttpClient.Version version, SSLContext sslContext) {
try {
return HttpTestServer.create(version, sslContext);
} catch (IOException exception) {
throw new UncheckedIOException(exception);
}
}
private static HttpClient createClient(HttpClient.Version version, SSLContext sslContext) {
HttpClient.Builder builder = HttpClient.newBuilder().version(version).proxy(NO_PROXY);
if (sslContext != null) {
builder.sslContext(sslContext);
}
return builder.build();
}
private <T> HttpResponse<T> request(BodyHandler<T> downstreamHandler, long capacity) throws Exception {
var handler = BodyHandlers.limiting(downstreamHandler, capacity);
return client.send(request, handler);
}
@Override
public String toString() {
String version = client.version().toString();
return client.sslContext() != null ? version.replaceFirst("_", "S_") : version;
}
}
@AfterAll
static void closeServerClientPairs() {
Exception[] exceptionRef = {null};
Stream
.of(HTTP1, HTTPS1, HTTP2, HTTPS2)
.flatMap(pair -> Stream.<Runnable>of(
pair.client::close,
pair.server::stop))
.forEach(closer -> {
try {
closer.run();
} catch (Exception exception) {
if (exceptionRef[0] == null) {
exceptionRef[0] = exception;
} else {
exceptionRef[0].addSuppressed(exception);
}
}
});
if (exceptionRef[0] != null) {
throw new RuntimeException("failed closing one or more server-client pairs", exceptionRef[0]);
}
}
@ParameterizedTest
@MethodSource("sufficientCapacities")
void testSuccessOnSufficientCapacityForByteArray(ServerClientPair pair, long sufficientCapacity) throws Exception {
HttpResponse<byte[]> response = pair.request(BodyHandlers.ofByteArray(), sufficientCapacity);
verifyHeaders(response.headers());
assertArrayEquals(RESPONSE_BODY, response.body());
}
@ParameterizedTest
@MethodSource("sufficientCapacities")
void testSuccessOnSufficientCapacityForInputStream(ServerClientPair pair, long sufficientCapacity) throws Exception {
HttpResponse<InputStream> response = pair.request(BodyHandlers.ofInputStream(), sufficientCapacity);
verifyHeaders(response.headers());
try (InputStream responseBodyStream = response.body()) {
byte[] responseBodyBuffer = responseBodyStream.readAllBytes();
assertArrayEquals(RESPONSE_BODY, responseBodyBuffer);
}
}
static Arguments[] sufficientCapacities() {
long minExtremeCapacity = RESPONSE_BODY.length;
long maxExtremeCapacity = Long.MAX_VALUE;
long nonExtremeCapacity = RANDOM.nextLong(minExtremeCapacity + 1, maxExtremeCapacity);
return capacityArgs(minExtremeCapacity, nonExtremeCapacity, maxExtremeCapacity);
}
@ParameterizedTest
@MethodSource("insufficientCapacities")
void testFailureOnInsufficientCapacityForByteArray(ServerClientPair pair, long insufficientCapacity) {
BodyHandler<byte[]> handler = responseInfo -> {
verifyHeaders(responseInfo.headers());
return BodySubscribers.limiting(BodySubscribers.ofByteArray(), insufficientCapacity);
};
var exception = assertThrows(IOException.class, () -> pair.request(handler, insufficientCapacity));
assertEquals(exception.getMessage(), "body exceeds capacity: " + insufficientCapacity);
}
@ParameterizedTest
@MethodSource("insufficientCapacities")
void testFailureOnInsufficientCapacityForInputStream(ServerClientPair pair, long insufficientCapacity) throws Exception {
HttpResponse<InputStream> response = pair.request(BodyHandlers.ofInputStream(), insufficientCapacity);
verifyHeaders(response.headers());
try (InputStream responseBodyStream = response.body()) {
var exception = assertThrows(IOException.class, responseBodyStream::readAllBytes);
assertNotNull(exception.getCause());
assertEquals(exception.getCause().getMessage(), "body exceeds capacity: " + insufficientCapacity);
}
}
static Arguments[] insufficientCapacities() {
long minExtremeCapacity = 0;
long maxExtremeCapacity = RESPONSE_BODY.length - 1;
long nonExtremeCapacity = RANDOM.nextLong(minExtremeCapacity + 1, maxExtremeCapacity);
return capacityArgs(minExtremeCapacity, nonExtremeCapacity, maxExtremeCapacity);
}
private static void verifyHeaders(HttpHeaders responseHeaders) {
List<String> responseHeaderValues = responseHeaders.allValues(RESPONSE_HEADER_NAME);
assertEquals(List.of(RESPONSE_HEADER_VALUE), responseHeaderValues);
}
@ParameterizedTest
@MethodSource("invalidCapacities")
void testFailureOnInvalidCapacityForHandler(long invalidCapacity) {
var exception = assertThrows(
IllegalArgumentException.class,
() -> BodyHandlers.limiting(BodyHandlers.ofByteArray(), invalidCapacity));
assertEquals(exception.getMessage(), "capacity must not be negative: " + invalidCapacity);
}
@ParameterizedTest
@MethodSource("invalidCapacities")
void testFailureOnInvalidCapacityForSubscriber(long invalidCapacity) {
var exception = assertThrows(
IllegalArgumentException.class,
() -> BodySubscribers.limiting(BodySubscribers.ofByteArray(), invalidCapacity));
assertEquals(exception.getMessage(), "capacity must not be negative: " + invalidCapacity);
}
static long[] invalidCapacities() {
long minExtremeCapacity = Long.MIN_VALUE;
long maxExtremeCapacity = -1;
long nonExtremeCapacity = RANDOM.nextLong(minExtremeCapacity + 1, maxExtremeCapacity);
return new long[]{minExtremeCapacity, nonExtremeCapacity, maxExtremeCapacity};
}
@Test
void testFailureOnNullDownstreamHandler() {
var exception = assertThrows(NullPointerException.class, () -> BodyHandlers.limiting(null, 0));
assertEquals(exception.getMessage(), "downstreamHandler");
}
@Test
void testFailureOnNullDownstreamSubscriber() {
var exception = assertThrows(NullPointerException.class, () -> BodySubscribers.limiting(null, 0));
assertEquals(exception.getMessage(), "downstreamSubscriber");
}
private static Arguments[] capacityArgs(long... capacities) {
return Stream
.of(HTTP1, HTTPS1, HTTP2, HTTPS2)
.flatMap(pair -> Arrays
.stream(capacities)
.mapToObj(capacity -> Arguments.of(pair, capacity)))
.toArray(Arguments[]::new);
}
@Test
void testSubscriberForCompleteConsumption() {
// Create the subscriber (with sufficient capacity)
ObserverSubscriber downstreamSubscriber = new ObserverSubscriber();
int sufficientCapacity = RESPONSE_BODY.length;
BodySubscriber<String> subscriber = BodySubscribers.limiting(downstreamSubscriber, sufficientCapacity);
// Emit values
subscriber.onSubscribe(DummySubscription.INSTANCE);
byte[] responseBodyPart1 = {RESPONSE_BODY[0]};
byte[] responseBodyPart2 = copyOfRange(RESPONSE_BODY, 1, RESPONSE_BODY.length);
List<ByteBuffer> buffers = toByteBuffers(responseBodyPart1, responseBodyPart2);
subscriber.onNext(buffers);
// Verify the downstream propagation
assertSame(buffers, downstreamSubscriber.lastBuffers);
assertNull(downstreamSubscriber.lastThrowable);
assertFalse(downstreamSubscriber.completed);
}
@Test
void testSubscriberForFailureOnExcess() {
// Create the subscriber (with insufficient capacity)
ObserverSubscriber downstreamSubscriber = new ObserverSubscriber();
int insufficientCapacity = 2;
BodySubscriber<String> subscriber = BodySubscribers.limiting(downstreamSubscriber, insufficientCapacity);
// Emit values
subscriber.onSubscribe(DummySubscription.INSTANCE);
byte[] responseBodyPart1 = {RESPONSE_BODY[0]};
byte[] responseBodyPart2 = copyOfRange(RESPONSE_BODY, 1, RESPONSE_BODY.length);
List<ByteBuffer> buffers = toByteBuffers(responseBodyPart1, responseBodyPart2);
subscriber.onNext(buffers);
// Verify the downstream propagation
assertNull(downstreamSubscriber.lastBuffers);
assertNotNull(downstreamSubscriber.lastThrowable);
assertEquals(
"body exceeds capacity: " + insufficientCapacity,
downstreamSubscriber.lastThrowable.getMessage());
assertFalse(downstreamSubscriber.completed);
}
private static List<ByteBuffer> toByteBuffers(byte[]... buffers) {
return Arrays.stream(buffers).map(ByteBuffer::wrap).collect(Collectors.toList());
}
private static final class ObserverSubscriber implements BodySubscriber<String> {
private List<ByteBuffer> lastBuffers;
private Throwable lastThrowable;
private boolean completed;
@Override
public CompletionStage<String> getBody() {
throw new UnsupportedOperationException();
}
@Override
public void onSubscribe(Subscription subscription) {
subscription.request(Long.MAX_VALUE);
}
@Override
public void onNext(List<ByteBuffer> buffers) {
lastBuffers = buffers;
}
@Override
public void onError(Throwable throwable) {
lastThrowable = throwable;
}
@Override
public void onComplete() {
completed = true;
}
}
private enum DummySubscription implements Subscription {
INSTANCE;
@Override
public void request(long n) {
// Do nothing
}
@Override
public void cancel() {
// Do nothing
}
}
}
|