Path: blob/master/test/jdk/java/net/httpclient/AbstractThrowingPushPromises.java
41152 views
/*1* Copyright (c) 2018, 2019, 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*/222324/**25* This is not a test. Actual tests are implemented by concrete subclasses.26* The abstract class AbstractThrowingPushPromises provides a base framework27* to test what happens when push promise handlers and their28* response body handlers and subscribers throw unexpected exceptions.29* Concrete tests that extend this abstract class will need to include30* the following jtreg tags:31*32* @library /test/lib http2/server33* @build jdk.test.lib.net.SimpleSSLContext HttpServerAdapters34* ReferenceTracker AbstractThrowingPushPromises35* <concrete-class-name>36* @modules java.base/sun.net.www.http37* java.net.http/jdk.internal.net.http.common38* java.net.http/jdk.internal.net.http.frame39* java.net.http/jdk.internal.net.http.hpack40* @run testng/othervm -Djdk.internal.httpclient.debug=true <concrete-class-name>41*/4243import jdk.test.lib.net.SimpleSSLContext;44import org.testng.ITestContext;45import org.testng.annotations.AfterTest;46import org.testng.annotations.AfterClass;47import org.testng.annotations.BeforeMethod;48import org.testng.annotations.BeforeTest;49import org.testng.annotations.DataProvider;5051import javax.net.ssl.SSLContext;52import java.io.BufferedReader;53import java.io.IOException;54import java.io.InputStream;55import java.io.InputStreamReader;56import java.io.OutputStream;57import java.io.UncheckedIOException;58import java.net.URI;59import java.net.URISyntaxException;60import java.net.http.HttpClient;61import java.net.http.HttpHeaders;62import java.net.http.HttpRequest;63import java.net.http.HttpResponse;64import java.net.http.HttpResponse.BodyHandler;65import java.net.http.HttpResponse.BodyHandlers;66import java.net.http.HttpResponse.BodySubscriber;67import java.net.http.HttpResponse.PushPromiseHandler;68import java.nio.ByteBuffer;69import java.nio.charset.StandardCharsets;70import java.util.List;71import java.util.Map;72import java.util.concurrent.CompletableFuture;73import java.util.concurrent.CompletionException;74import java.util.concurrent.CompletionStage;75import java.util.concurrent.ConcurrentHashMap;76import java.util.concurrent.ConcurrentMap;77import java.util.concurrent.Executor;78import java.util.concurrent.Executors;79import java.util.concurrent.Flow;80import java.util.concurrent.atomic.AtomicLong;81import java.util.function.BiPredicate;82import java.util.function.Consumer;83import java.util.function.Function;84import java.util.function.Predicate;85import java.util.function.Supplier;86import java.util.stream.Collectors;87import java.util.stream.Stream;8889import static java.lang.System.out;90import static java.lang.System.err;91import static java.lang.String.format;92import static java.nio.charset.StandardCharsets.UTF_8;93import static org.testng.Assert.assertEquals;94import static org.testng.Assert.assertTrue;9596public abstract class AbstractThrowingPushPromises implements HttpServerAdapters {9798SSLContext sslContext;99HttpTestServer http2TestServer; // HTTP/2 ( h2c )100HttpTestServer https2TestServer; // HTTP/2 ( h2 )101String http2URI_fixed;102String http2URI_chunk;103String https2URI_fixed;104String https2URI_chunk;105106static final int ITERATION_COUNT = 1;107// a shared executor helps reduce the amount of threads created by the test108static final Executor executor = new TestExecutor(Executors.newCachedThreadPool());109static final ConcurrentMap<String, Throwable> FAILURES = new ConcurrentHashMap<>();110static volatile boolean tasksFailed;111static final AtomicLong serverCount = new AtomicLong();112static final AtomicLong clientCount = new AtomicLong();113static final long start = System.nanoTime();114public static String now() {115long now = System.nanoTime() - start;116long secs = now / 1000_000_000;117long mill = (now % 1000_000_000) / 1000_000;118long nan = now % 1000_000;119return String.format("[%d s, %d ms, %d ns] ", secs, mill, nan);120}121122final ReferenceTracker TRACKER = ReferenceTracker.INSTANCE;123private volatile HttpClient sharedClient;124125static class TestExecutor implements Executor {126final AtomicLong tasks = new AtomicLong();127Executor executor;128TestExecutor(Executor executor) {129this.executor = executor;130}131132@Override133public void execute(Runnable command) {134long id = tasks.incrementAndGet();135executor.execute(() -> {136try {137command.run();138} catch (Throwable t) {139tasksFailed = true;140out.printf(now() + "Task %s failed: %s%n", id, t);141err.printf(now() + "Task %s failed: %s%n", id, t);142FAILURES.putIfAbsent("Task " + id, t);143throw t;144}145});146}147}148149protected boolean stopAfterFirstFailure() {150return Boolean.getBoolean("jdk.internal.httpclient.debug");151}152153@BeforeMethod154void beforeMethod(ITestContext context) {155if (stopAfterFirstFailure() && context.getFailedTests().size() > 0) {156throw new RuntimeException("some tests failed");157}158}159160@AfterClass161static final void printFailedTests() {162out.println("\n=========================");163try {164out.printf("%n%sCreated %d servers and %d clients%n",165now(), serverCount.get(), clientCount.get());166if (FAILURES.isEmpty()) return;167out.println("Failed tests: ");168FAILURES.entrySet().forEach((e) -> {169out.printf("\t%s: %s%n", e.getKey(), e.getValue());170e.getValue().printStackTrace(out);171e.getValue().printStackTrace();172});173if (tasksFailed) {174out.println("WARNING: Some tasks failed");175}176} finally {177out.println("\n=========================\n");178}179}180181private String[] uris() {182return new String[] {183http2URI_fixed,184http2URI_chunk,185https2URI_fixed,186https2URI_chunk,187};188}189190@DataProvider(name = "sanity")191public Object[][] sanity() {192String[] uris = uris();193Object[][] result = new Object[uris.length * 2][];194195int i = 0;196for (boolean sameClient : List.of(false, true)) {197for (String uri: uris()) {198result[i++] = new Object[] {uri, sameClient};199}200}201assert i == uris.length * 2;202return result;203}204205enum Where {206BODY_HANDLER, ON_SUBSCRIBE, ON_NEXT, ON_COMPLETE, ON_ERROR, GET_BODY, BODY_CF,207BEFORE_ACCEPTING, AFTER_ACCEPTING;208public Consumer<Where> select(Consumer<Where> consumer) {209return new Consumer<Where>() {210@Override211public void accept(Where where) {212if (Where.this == where) {213consumer.accept(where);214}215}216};217}218}219220private Object[][] variants(List<Thrower> throwers) {221String[] uris = uris();222// reduce traces by always using the same client if223// stopAfterFirstFailure is requested.224List<Boolean> sameClients = stopAfterFirstFailure()225? List.of(true)226: List.of(false, true);227Object[][] result = new Object[uris.length * sameClients.size() * throwers.size()][];228int i = 0;229for (Thrower thrower : throwers) {230for (boolean sameClient : sameClients) {231for (String uri : uris()) {232result[i++] = new Object[]{uri, sameClient, thrower};233}234}235}236assert i == uris.length * sameClients.size() * throwers.size();237return result;238}239240@DataProvider(name = "ioVariants")241public Object[][] ioVariants(ITestContext context) {242if (stopAfterFirstFailure() && context.getFailedTests().size() > 0) {243return new Object[0][];244}245return variants(List.of(246new UncheckedIOExceptionThrower()));247}248249@DataProvider(name = "customVariants")250public Object[][] customVariants(ITestContext context) {251if (stopAfterFirstFailure() && context.getFailedTests().size() > 0) {252return new Object[0][];253}254return variants(List.of(255new UncheckedCustomExceptionThrower()));256}257258private HttpClient makeNewClient() {259clientCount.incrementAndGet();260return TRACKER.track(HttpClient.newBuilder()261.proxy(HttpClient.Builder.NO_PROXY)262.executor(executor)263.sslContext(sslContext)264.build());265}266267HttpClient newHttpClient(boolean share) {268if (!share) return makeNewClient();269HttpClient shared = sharedClient;270if (shared != null) return shared;271synchronized (this) {272shared = sharedClient;273if (shared == null) {274shared = sharedClient = makeNewClient();275}276return shared;277}278}279280// @Test(dataProvider = "sanity")281protected void testSanityImpl(String uri, boolean sameClient)282throws Exception {283HttpClient client = null;284out.printf("%ntestNoThrows(%s, %b)%n", uri, sameClient);285for (int i=0; i< ITERATION_COUNT; i++) {286if (!sameClient || client == null)287client = newHttpClient(sameClient);288289HttpRequest req = HttpRequest.newBuilder(URI.create(uri))290.build();291BodyHandler<Stream<String>> handler =292new ThrowingBodyHandler((w) -> {},293BodyHandlers.ofLines());294Map<HttpRequest, CompletableFuture<HttpResponse<Stream<String>>>> pushPromises =295new ConcurrentHashMap<>();296PushPromiseHandler<Stream<String>> pushHandler = new PushPromiseHandler<>() {297@Override298public void applyPushPromise(HttpRequest initiatingRequest,299HttpRequest pushPromiseRequest,300Function<BodyHandler<Stream<String>>,301CompletableFuture<HttpResponse<Stream<String>>>>302acceptor) {303pushPromises.putIfAbsent(pushPromiseRequest, acceptor.apply(handler));304}305};306HttpResponse<Stream<String>> response =307client.sendAsync(req, BodyHandlers.ofLines(), pushHandler).get();308String body = response.body().collect(Collectors.joining("|"));309assertEquals(URI.create(body).getPath(), URI.create(uri).getPath());310for (HttpRequest promised : pushPromises.keySet()) {311out.printf("%s Received promise: %s%n\tresponse: %s%n",312now(), promised, pushPromises.get(promised).get());313String promisedBody = pushPromises.get(promised).get().body()314.collect(Collectors.joining("|"));315assertEquals(promisedBody, promised.uri().toASCIIString());316}317assertEquals(3, pushPromises.size());318}319}320321// @Test(dataProvider = "variants")322protected void testThrowingAsStringImpl(String uri,323boolean sameClient,324Thrower thrower)325throws Exception326{327String test = format("testThrowingAsString(%s, %b, %s)",328uri, sameClient, thrower);329testThrowing(test, uri, sameClient, BodyHandlers::ofString,330this::checkAsString, thrower);331}332333//@Test(dataProvider = "variants")334protected void testThrowingAsLinesImpl(String uri,335boolean sameClient,336Thrower thrower)337throws Exception338{339String test = format("testThrowingAsLines(%s, %b, %s)",340uri, sameClient, thrower);341testThrowing(test, uri, sameClient, BodyHandlers::ofLines,342this::checkAsLines, thrower);343}344345//@Test(dataProvider = "variants")346protected void testThrowingAsInputStreamImpl(String uri,347boolean sameClient,348Thrower thrower)349throws Exception350{351String test = format("testThrowingAsInputStream(%s, %b, %s)",352uri, sameClient, thrower);353testThrowing(test, uri, sameClient, BodyHandlers::ofInputStream,354this::checkAsInputStream, thrower);355}356357private <T,U> void testThrowing(String name, String uri, boolean sameClient,358Supplier<BodyHandler<T>> handlers,359Finisher finisher, Thrower thrower)360throws Exception361{362out.printf("%n%s%s%n", now(), name);363try {364testThrowing(uri, sameClient, handlers, finisher, thrower);365} catch (Error | Exception x) {366FAILURES.putIfAbsent(name, x);367throw x;368}369}370371private <T,U> void testThrowing(String uri, boolean sameClient,372Supplier<BodyHandler<T>> handlers,373Finisher finisher, Thrower thrower)374throws Exception375{376HttpClient client = null;377for (Where where : Where.values()) {378if (where == Where.ON_ERROR) continue;379if (!sameClient || client == null)380client = newHttpClient(sameClient);381382HttpRequest req = HttpRequest.383newBuilder(URI.create(uri))384.build();385ConcurrentMap<HttpRequest, CompletableFuture<HttpResponse<T>>> promiseMap =386new ConcurrentHashMap<>();387Supplier<BodyHandler<T>> throwing = () ->388new ThrowingBodyHandler(where.select(thrower), handlers.get());389PushPromiseHandler<T> pushHandler = new ThrowingPromiseHandler<>(390where.select(thrower),391PushPromiseHandler.of((r) -> throwing.get(), promiseMap));392out.println("try throwing in " + where);393HttpResponse<T> response = null;394try {395response = client.sendAsync(req, handlers.get(), pushHandler).join();396} catch (Error | Exception x) {397throw x;398}399if (response != null) {400finisher.finish(where, req.uri(), response, thrower, promiseMap);401}402}403}404405interface Thrower extends Consumer<Where>, Predicate<Throwable> {406407}408409interface Finisher<T,U> {410U finish(Where w, URI requestURI, HttpResponse<T> resp, Thrower thrower,411Map<HttpRequest, CompletableFuture<HttpResponse<T>>> promises);412}413414final <T,U> U shouldHaveThrown(Where w, HttpResponse<T> resp, Thrower thrower) {415String msg = "Expected exception not thrown in " + w416+ "\n\tReceived: " + resp417+ "\n\tWith body: " + resp.body();418System.out.println(msg);419throw new RuntimeException(msg);420}421422final List<String> checkAsString(Where w, URI reqURI,423HttpResponse<String> resp,424Thrower thrower,425Map<HttpRequest, CompletableFuture<HttpResponse<String>>> promises) {426Function<HttpResponse<String>, List<String>> extractor =427(r) -> List.of(r.body());428return check(w, reqURI, resp, thrower, promises, extractor);429}430431final List<String> checkAsLines(Where w, URI reqURI,432HttpResponse<Stream<String>> resp,433Thrower thrower,434Map<HttpRequest, CompletableFuture<HttpResponse<Stream<String>>>> promises) {435Function<HttpResponse<Stream<String>>, List<String>> extractor =436(r) -> r.body().collect(Collectors.toList());437return check(w, reqURI, resp, thrower, promises, extractor);438}439440final List<String> checkAsInputStream(Where w, URI reqURI,441HttpResponse<InputStream> resp,442Thrower thrower,443Map<HttpRequest, CompletableFuture<HttpResponse<InputStream>>> promises)444{445Function<HttpResponse<InputStream>, List<String>> extractor = (r) -> {446List<String> result;447try (InputStream is = r.body()) {448result = new BufferedReader(new InputStreamReader(is))449.lines().collect(Collectors.toList());450} catch (Throwable t) {451throw new CompletionException(t);452}453return result;454};455return check(w, reqURI, resp, thrower, promises, extractor);456}457458private final <T> List<String> check(Where w, URI reqURI,459HttpResponse<T> resp,460Thrower thrower,461Map<HttpRequest, CompletableFuture<HttpResponse<T>>> promises,462Function<HttpResponse<T>, List<String>> extractor)463{464List<String> result = extractor.apply(resp);465for (HttpRequest req : promises.keySet()) {466switch (w) {467case BEFORE_ACCEPTING:468throw new RuntimeException("No push promise should have been received" +469" for " + reqURI + " in " + w + ": got " + promises.keySet());470default:471break;472}473HttpResponse<T> presp;474try {475presp = promises.get(req).join();476} catch (Error | Exception x) {477Throwable cause = findCause(x, thrower);478if (cause != null) {479out.println(now() + "Got expected exception in "480+ w + ": " + cause);481continue;482}483throw x;484}485switch (w) {486case BEFORE_ACCEPTING:487case AFTER_ACCEPTING:488case BODY_HANDLER:489case GET_BODY:490case BODY_CF:491return shouldHaveThrown(w, presp, thrower);492default:493break;494}495List<String> presult = null;496try {497presult = extractor.apply(presp);498} catch (Error | Exception x) {499Throwable cause = findCause(x, thrower);500if (cause != null) {501out.println(now() + "Got expected exception for "502+ req + " in " + w + ": " + cause);503continue;504}505throw x;506}507throw new RuntimeException("Expected exception not thrown for "508+ req + " in " + w);509}510final int expectedCount;511switch (w) {512case BEFORE_ACCEPTING:513expectedCount = 0;514break;515default:516expectedCount = 3;517}518assertEquals(promises.size(), expectedCount,519"bad promise count for " + reqURI + " with " + w);520assertEquals(result, List.of(reqURI.toASCIIString()));521return result;522}523524private static Throwable findCause(Throwable x,525Predicate<Throwable> filter) {526while (x != null && !filter.test(x)) x = x.getCause();527return x;528}529530static final class UncheckedCustomExceptionThrower implements Thrower {531@Override532public void accept(Where where) {533out.println(now() + "Throwing in " + where);534throw new UncheckedCustomException(where.name());535}536537@Override538public boolean test(Throwable throwable) {539return UncheckedCustomException.class.isInstance(throwable);540}541542@Override543public String toString() {544return "UncheckedCustomExceptionThrower";545}546}547548static final class UncheckedIOExceptionThrower implements Thrower {549@Override550public void accept(Where where) {551out.println(now() + "Throwing in " + where);552throw new UncheckedIOException(new CustomIOException(where.name()));553}554555@Override556public boolean test(Throwable throwable) {557return UncheckedIOException.class.isInstance(throwable)558&& CustomIOException.class.isInstance(throwable.getCause());559}560561@Override562public String toString() {563return "UncheckedIOExceptionThrower";564}565}566567static final class UncheckedCustomException extends RuntimeException {568UncheckedCustomException(String message) {569super(message);570}571UncheckedCustomException(String message, Throwable cause) {572super(message, cause);573}574}575576static final class CustomIOException extends IOException {577CustomIOException(String message) {578super(message);579}580CustomIOException(String message, Throwable cause) {581super(message, cause);582}583}584585static final class ThrowingPromiseHandler<T> implements PushPromiseHandler<T> {586final Consumer<Where> throwing;587final PushPromiseHandler<T> pushHandler;588ThrowingPromiseHandler(Consumer<Where> throwing, PushPromiseHandler<T> pushHandler) {589this.throwing = throwing;590this.pushHandler = pushHandler;591}592593@Override594public void applyPushPromise(HttpRequest initiatingRequest,595HttpRequest pushPromiseRequest,596Function<BodyHandler<T>,597CompletableFuture<HttpResponse<T>>> acceptor) {598throwing.accept(Where.BEFORE_ACCEPTING);599pushHandler.applyPushPromise(initiatingRequest, pushPromiseRequest, acceptor);600throwing.accept(Where.AFTER_ACCEPTING);601}602}603604static final class ThrowingBodyHandler<T> implements BodyHandler<T> {605final Consumer<Where> throwing;606final BodyHandler<T> bodyHandler;607ThrowingBodyHandler(Consumer<Where> throwing, BodyHandler<T> bodyHandler) {608this.throwing = throwing;609this.bodyHandler = bodyHandler;610}611@Override612public BodySubscriber<T> apply(HttpResponse.ResponseInfo rinfo) {613throwing.accept(Where.BODY_HANDLER);614BodySubscriber<T> subscriber = bodyHandler.apply(rinfo);615return new ThrowingBodySubscriber(throwing, subscriber);616}617}618619static final class ThrowingBodySubscriber<T> implements BodySubscriber<T> {620private final BodySubscriber<T> subscriber;621volatile boolean onSubscribeCalled;622final Consumer<Where> throwing;623ThrowingBodySubscriber(Consumer<Where> throwing, BodySubscriber<T> subscriber) {624this.throwing = throwing;625this.subscriber = subscriber;626}627628@Override629public void onSubscribe(Flow.Subscription subscription) {630//out.println("onSubscribe ");631onSubscribeCalled = true;632throwing.accept(Where.ON_SUBSCRIBE);633subscriber.onSubscribe(subscription);634}635636@Override637public void onNext(List<ByteBuffer> item) {638// out.println("onNext " + item);639assertTrue(onSubscribeCalled);640throwing.accept(Where.ON_NEXT);641subscriber.onNext(item);642}643644@Override645public void onError(Throwable throwable) {646//out.println("onError");647assertTrue(onSubscribeCalled);648throwing.accept(Where.ON_ERROR);649subscriber.onError(throwable);650}651652@Override653public void onComplete() {654//out.println("onComplete");655assertTrue(onSubscribeCalled, "onComplete called before onSubscribe");656throwing.accept(Where.ON_COMPLETE);657subscriber.onComplete();658}659660@Override661public CompletionStage<T> getBody() {662throwing.accept(Where.GET_BODY);663try {664throwing.accept(Where.BODY_CF);665} catch (Throwable t) {666return CompletableFuture.failedFuture(t);667}668return subscriber.getBody();669}670}671672673@BeforeTest674public void setup() throws Exception {675sslContext = new SimpleSSLContext().get();676if (sslContext == null)677throw new AssertionError("Unexpected null sslContext");678679// HTTP/2680HttpTestHandler h2_fixedLengthHandler = new HTTP_FixedLengthHandler();681HttpTestHandler h2_chunkedHandler = new HTTP_ChunkedHandler();682683http2TestServer = HttpTestServer.of(new Http2TestServer("localhost", false, 0));684http2TestServer.addHandler(h2_fixedLengthHandler, "/http2/fixed");685http2TestServer.addHandler(h2_chunkedHandler, "/http2/chunk");686http2URI_fixed = "http://" + http2TestServer.serverAuthority() + "/http2/fixed/x";687http2URI_chunk = "http://" + http2TestServer.serverAuthority() + "/http2/chunk/x";688689https2TestServer = HttpTestServer.of(new Http2TestServer("localhost", true, sslContext));690https2TestServer.addHandler(h2_fixedLengthHandler, "/https2/fixed");691https2TestServer.addHandler(h2_chunkedHandler, "/https2/chunk");692https2URI_fixed = "https://" + https2TestServer.serverAuthority() + "/https2/fixed/x";693https2URI_chunk = "https://" + https2TestServer.serverAuthority() + "/https2/chunk/x";694695serverCount.addAndGet(2);696http2TestServer.start();697https2TestServer.start();698}699700@AfterTest701public void teardown() throws Exception {702String sharedClientName =703sharedClient == null ? null : sharedClient.toString();704sharedClient = null;705Thread.sleep(100);706AssertionError fail = TRACKER.check(500);707try {708http2TestServer.stop();709https2TestServer.stop();710} finally {711if (fail != null) {712if (sharedClientName != null) {713System.err.println("Shared client name is: " + sharedClientName);714}715throw fail;716}717}718}719720static final BiPredicate<String,String> ACCEPT_ALL = (x, y) -> true;721722private static void pushPromiseFor(HttpTestExchange t,723URI requestURI,724String pushPath,725boolean fixed)726throws IOException727{728try {729URI promise = new URI(requestURI.getScheme(),730requestURI.getAuthority(),731pushPath, null, null);732byte[] promiseBytes = promise.toASCIIString().getBytes(UTF_8);733out.printf("TestServer: %s Pushing promise: %s%n", now(), promise);734err.printf("TestServer: %s Pushing promise: %s%n", now(), promise);735HttpHeaders headers;736if (fixed) {737String length = String.valueOf(promiseBytes.length);738headers = HttpHeaders.of(Map.of("Content-Length", List.of(length)),739ACCEPT_ALL);740} else {741headers = HttpHeaders.of(Map.of(), ACCEPT_ALL); // empty742}743t.serverPush(promise, headers, promiseBytes);744} catch (URISyntaxException x) {745throw new IOException(x.getMessage(), x);746}747}748749static class HTTP_FixedLengthHandler implements HttpTestHandler {750@Override751public void handle(HttpTestExchange t) throws IOException {752out.println("HTTP_FixedLengthHandler received request to " + t.getRequestURI());753try (InputStream is = t.getRequestBody()) {754is.readAllBytes();755}756URI requestURI = t.getRequestURI();757for (int i = 1; i<2; i++) {758String path = requestURI.getPath() + "/before/promise-" + i;759pushPromiseFor(t, requestURI, path, true);760}761byte[] resp = t.getRequestURI().toString().getBytes(StandardCharsets.UTF_8);762t.sendResponseHeaders(200, resp.length); //fixed content length763try (OutputStream os = t.getResponseBody()) {764int bytes = resp.length/3;765for (int i = 0; i<2; i++) {766String path = requestURI.getPath() + "/after/promise-" + (i + 2);767os.write(resp, i * bytes, bytes);768os.flush();769pushPromiseFor(t, requestURI, path, true);770}771os.write(resp, 2*bytes, resp.length - 2*bytes);772}773}774775}776777static class HTTP_ChunkedHandler implements HttpTestHandler {778@Override779public void handle(HttpTestExchange t) throws IOException {780out.println("HTTP_ChunkedHandler received request to " + t.getRequestURI());781byte[] resp = t.getRequestURI().toString().getBytes(StandardCharsets.UTF_8);782try (InputStream is = t.getRequestBody()) {783is.readAllBytes();784}785URI requestURI = t.getRequestURI();786for (int i = 1; i<2; i++) {787String path = requestURI.getPath() + "/before/promise-" + i;788pushPromiseFor(t, requestURI, path, false);789}790t.sendResponseHeaders(200, -1); // chunked/variable791try (OutputStream os = t.getResponseBody()) {792int bytes = resp.length/3;793for (int i = 0; i<2; i++) {794String path = requestURI.getPath() + "/after/promise-" + (i + 2);795os.write(resp, i * bytes, bytes);796os.flush();797pushPromiseFor(t, requestURI, path, false);798}799os.write(resp, 2*bytes, resp.length - 2*bytes);800}801}802}803804}805806807