Path: blob/master/test/jdk/java/net/httpclient/ConcurrentResponses.java
41149 views
/*1* Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223/*24* @test25* @bug 819582326* @summary Buffers given to response body subscribers should not contain27* unprocessed HTTP data28* @modules java.base/sun.net.www.http29* java.net.http/jdk.internal.net.http.common30* java.net.http/jdk.internal.net.http.frame31* java.net.http/jdk.internal.net.http.hpack32* java.logging33* jdk.httpserver34* @library /test/lib http2/server35* @build Http2TestServer36* @build jdk.test.lib.net.SimpleSSLContext37* @run testng/othervm38* -Djdk.httpclient.HttpClient.log=headers,errors,channel39* ConcurrentResponses40*/4142import java.io.IOException;43import java.io.InputStream;44import java.io.OutputStream;45import java.net.InetAddress;46import java.net.InetSocketAddress;47import java.net.URI;48import java.nio.ByteBuffer;49import java.util.HashMap;50import java.util.List;51import java.util.Map;52import java.util.concurrent.CompletableFuture;53import java.util.concurrent.CompletionStage;54import java.util.concurrent.Flow;55import java.util.stream.IntStream;56import javax.net.ssl.SSLContext;57import com.sun.net.httpserver.HttpExchange;58import com.sun.net.httpserver.HttpHandler;59import com.sun.net.httpserver.HttpServer;60import com.sun.net.httpserver.HttpsConfigurator;61import com.sun.net.httpserver.HttpsServer;62import java.net.http.HttpClient;63import java.net.http.HttpRequest;64import java.net.http.HttpResponse;65import java.net.http.HttpResponse.BodyHandler;66import java.net.http.HttpResponse.BodyHandlers;67import java.net.http.HttpResponse.BodySubscriber;68import java.net.http.HttpResponse.BodySubscribers;69import jdk.test.lib.net.SimpleSSLContext;70import org.testng.annotations.AfterTest;71import org.testng.annotations.BeforeTest;72import org.testng.annotations.DataProvider;73import org.testng.annotations.Test;74import static java.nio.charset.StandardCharsets.UTF_8;75import static java.net.http.HttpResponse.BodyHandlers.discarding;76import static org.testng.Assert.assertEquals;77import static org.testng.Assert.assertFalse;78import static org.testng.Assert.fail;7980public class ConcurrentResponses {8182SSLContext sslContext;83HttpServer httpTestServer; // HTTP/1.1 [ 4 servers ]84HttpsServer httpsTestServer; // HTTPS/1.185Http2TestServer http2TestServer; // HTTP/2 ( h2c )86Http2TestServer https2TestServer; // HTTP/2 ( h2 )87String httpFixedURI, httpsFixedURI, httpChunkedURI, httpsChunkedURI;88String http2FixedURI, https2FixedURI, http2VariableURI, https2VariableURI;8990static final int CONCURRENT_REQUESTS = 13;9192static final String ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";93static final int ALPHABET_LENGTH = ALPHABET.length();9495static final String stringOfLength(int requiredLength) {96StringBuilder sb = new StringBuilder(requiredLength);97IntStream.range(0, requiredLength)98.mapToObj(i -> ALPHABET.charAt(i % ALPHABET_LENGTH))99.forEach(c -> sb.append(c));100return sb.toString();101}102103/** An array of different Strings, to be used as bodies. */104static final String[] BODIES = bodies();105106static String[] bodies() {107String[] bodies = new String[CONCURRENT_REQUESTS];108for (int i=0;i<CONCURRENT_REQUESTS; i++) {109// slightly, but still, different bodies110bodies[i] = "Request-" + i + "-body-" + stringOfLength((1024) + i);111}112return bodies;113}114115/**116* Asserts the given response's status code is 200.117* Returns a CF that completes with the given response.118*/119static final <T> CompletionStage<HttpResponse<T>>120assert200ResponseCode(HttpResponse<T> response) {121assertEquals(response.statusCode(), 200);122return CompletableFuture.completedFuture(response);123}124125/**126* Asserts that the given response's body is equal to the given body.127* Returns a CF that completes with the given response.128*/129static final <T> CompletionStage<HttpResponse<T>>130assertbody(HttpResponse<T> response, T body) {131assertEquals(response.body(), body);132return CompletableFuture.completedFuture(response);133}134135@DataProvider(name = "uris")136public Object[][] variants() {137return new Object[][]{138{ httpFixedURI },139{ httpsFixedURI },140{ httpChunkedURI },141{ httpsChunkedURI },142{ http2FixedURI },143{ https2FixedURI },144{ http2VariableURI },145{ https2VariableURI }146};147}148149150// The ofString implementation accumulates data, below a certain threshold151// into the byte buffers it is given.152@Test(dataProvider = "uris")153void testAsString(String uri) throws Exception {154HttpClient client = HttpClient.newBuilder().sslContext(sslContext).build();155156Map<HttpRequest, String> requests = new HashMap<>();157for (int i=0;i<CONCURRENT_REQUESTS; i++) {158HttpRequest request = HttpRequest.newBuilder(URI.create(uri + "?" + i))159.build();160requests.put(request, BODIES[i]);161}162163// initial connection to seed the cache so next parallel connections reuse it164client.sendAsync(HttpRequest.newBuilder(URI.create(uri)).build(), discarding()).join();165166// will reuse connection cached from the previous request ( when HTTP/2 )167CompletableFuture.allOf(requests.keySet().parallelStream()168.map(request -> client.sendAsync(request, BodyHandlers.ofString()))169.map(cf -> cf.thenCompose(ConcurrentResponses::assert200ResponseCode))170.map(cf -> cf.thenCompose(response -> assertbody(response, requests.get(response.request()))))171.toArray(CompletableFuture<?>[]::new))172.join();173}174175// The custom subscriber aggressively attacks any area, between the limit176// and the capacity, in the byte buffers it is given, by writing 'X' into it.177@Test(dataProvider = "uris")178void testWithCustomSubscriber(String uri) throws Exception {179HttpClient client = HttpClient.newBuilder().sslContext(sslContext).build();180181Map<HttpRequest, String> requests = new HashMap<>();182for (int i=0;i<CONCURRENT_REQUESTS; i++) {183HttpRequest request = HttpRequest.newBuilder(URI.create(uri + "?" + i))184.build();185requests.put(request, BODIES[i]);186}187188// initial connection to seed the cache so next parallel connections reuse it189client.sendAsync(HttpRequest.newBuilder(URI.create(uri)).build(), discarding()).join();190191// will reuse connection cached from the previous request ( when HTTP/2 )192CompletableFuture.allOf(requests.keySet().parallelStream()193.map(request -> client.sendAsync(request, CustomSubscriber.handler))194.map(cf -> cf.thenCompose(ConcurrentResponses::assert200ResponseCode))195.map(cf -> cf.thenCompose(response -> assertbody(response, requests.get(response.request()))))196.toArray(CompletableFuture<?>[]::new))197.join();198}199200/**201* A subscriber that wraps ofString, but mucks with any data between limit202* and capacity, if the client mistakenly passes it any that is should not.203*/204static class CustomSubscriber implements BodySubscriber<String> {205static final BodyHandler<String> handler = (r) -> new CustomSubscriber();206private final BodySubscriber<String> ofString = BodySubscribers.ofString(UTF_8);207208@Override209public CompletionStage<String> getBody() {210return ofString.getBody();211}212213@Override214public void onSubscribe(Flow.Subscription subscription) {215ofString.onSubscribe(subscription);216}217218@Override219public void onNext(List<ByteBuffer> buffers) {220// Muck any data beyond the give limit, since there shouldn't221// be any of interest to the HTTP Client.222for (ByteBuffer buffer : buffers) {223if (buffer.isReadOnly())224continue;225226if (buffer.limit() != buffer.capacity()) {227final int limit = buffer.limit();228final int position = buffer.position();229buffer.position(buffer.limit());230buffer.limit(buffer.capacity());231while (buffer.hasRemaining())232buffer.put((byte)'X');233buffer.position(position); // restore original position234buffer.limit(limit); // restore original limit235}236}237ofString.onNext(buffers);238}239240@Override241public void onError(Throwable throwable) {242ofString.onError(throwable);243throwable.printStackTrace();244fail("UNEXPECTED:" + throwable);245}246247@Override248public void onComplete() {249ofString.onComplete();250}251}252253static String serverAuthority(HttpServer server) {254return InetAddress.getLoopbackAddress().getHostName() + ":"255+ server.getAddress().getPort();256}257258@BeforeTest259public void setup() throws Exception {260sslContext = new SimpleSSLContext().get();261if (sslContext == null)262throw new AssertionError("Unexpected null sslContext");263264InetSocketAddress sa = new InetSocketAddress(InetAddress.getLoopbackAddress(), 0);265httpTestServer = HttpServer.create(sa, 0);266httpTestServer.createContext("/http1/fixed", new Http1FixedHandler());267httpFixedURI = "http://" + serverAuthority(httpTestServer) + "/http1/fixed";268httpTestServer.createContext("/http1/chunked", new Http1ChunkedHandler());269httpChunkedURI = "http://" + serverAuthority(httpTestServer) + "/http1/chunked";270271httpsTestServer = HttpsServer.create(sa, 0);272httpsTestServer.setHttpsConfigurator(new HttpsConfigurator(sslContext));273httpsTestServer.createContext("/https1/fixed", new Http1FixedHandler());274httpsFixedURI = "https://" + serverAuthority(httpsTestServer) + "/https1/fixed";275httpsTestServer.createContext("/https1/chunked", new Http1ChunkedHandler());276httpsChunkedURI = "https://" + serverAuthority(httpsTestServer) + "/https1/chunked";277278http2TestServer = new Http2TestServer("localhost", false, 0);279http2TestServer.addHandler(new Http2FixedHandler(), "/http2/fixed");280http2FixedURI = "http://" + http2TestServer.serverAuthority()+ "/http2/fixed";281http2TestServer.addHandler(new Http2VariableHandler(), "/http2/variable");282http2VariableURI = "http://" + http2TestServer.serverAuthority() + "/http2/variable";283284https2TestServer = new Http2TestServer("localhost", true, sslContext);285https2TestServer.addHandler(new Http2FixedHandler(), "/https2/fixed");286https2FixedURI = "https://" + https2TestServer.serverAuthority() + "/https2/fixed";287https2TestServer.addHandler(new Http2VariableHandler(), "/https2/variable");288https2VariableURI = "https://" + https2TestServer.serverAuthority() + "/https2/variable";289290httpTestServer.start();291httpsTestServer.start();292http2TestServer.start();293https2TestServer.start();294}295296@AfterTest297public void teardown() throws Exception {298httpTestServer.stop(0);299httpsTestServer.stop(0);300http2TestServer.stop();301https2TestServer.stop();302}303304interface SendResponseHeadersFunction {305void apply(int responseCode, long responseLength) throws IOException;306}307308// A handler implementation that replies with 200 OK. If the exchange's uri309// has a query, then it must be an integer, which is used as an index to310// select the particular response body, e.g. /http2/x?5 -> BODIES[5]311static void serverHandlerImpl(InputStream inputStream,312OutputStream outputStream,313URI uri,314SendResponseHeadersFunction sendResponseHeadersFunction)315throws IOException316{317try (InputStream is = inputStream;318OutputStream os = outputStream) {319is.readAllBytes();320321String magicQuery = uri.getQuery();322if (magicQuery != null) {323int bodyIndex = Integer.valueOf(magicQuery);324String body = BODIES[bodyIndex];325byte[] bytes = body.getBytes(UTF_8);326sendResponseHeadersFunction.apply(200, bytes.length);327int offset = 0;328// Deliberately attempt to reply with several relatively329// small data frames ( each write corresponds to its own330// data frame ). Additionally, yield, to encourage other331// handlers to execute, therefore increasing the likelihood332// of multiple different-stream related frames in the333// client's read buffer.334while (offset < bytes.length) {335int length = Math.min(bytes.length - offset, 64);336os.write(bytes, offset, length);337os.flush();338offset += length;339Thread.yield();340}341} else {342sendResponseHeadersFunction.apply(200, 1);343os.write('A');344}345}346}347348static class Http1FixedHandler implements HttpHandler {349@Override350public void handle(HttpExchange t) throws IOException {351serverHandlerImpl(t.getRequestBody(),352t.getResponseBody(),353t.getRequestURI(),354(rcode, length) -> t.sendResponseHeaders(rcode, length));355}356}357358static class Http1ChunkedHandler implements HttpHandler {359@Override360public void handle(HttpExchange t) throws IOException {361serverHandlerImpl(t.getRequestBody(),362t.getResponseBody(),363t.getRequestURI(),364(rcode, ignored) -> t.sendResponseHeaders(rcode, 0 /*chunked*/));365}366}367368static class Http2FixedHandler implements Http2Handler {369@Override370public void handle(Http2TestExchange t) throws IOException {371serverHandlerImpl(t.getRequestBody(),372t.getResponseBody(),373t.getRequestURI(),374(rcode, length) -> t.sendResponseHeaders(rcode, length));375}376}377378static class Http2VariableHandler implements Http2Handler {379@Override380public void handle(Http2TestExchange t) throws IOException {381serverHandlerImpl(t.getRequestBody(),382t.getResponseBody(),383t.getRequestURI(),384(rcode, ignored) -> t.sendResponseHeaders(rcode, 0 /* no Content-Length */));385}386}387}388389390