Path: blob/master/test/jdk/java/net/httpclient/AbstractThrowingPushPromises.java
66644 views
/*1* Copyright (c) 2018, 2021, 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.ITestResult;46import org.testng.SkipException;47import org.testng.annotations.AfterTest;48import org.testng.annotations.AfterClass;49import org.testng.annotations.BeforeMethod;50import org.testng.annotations.BeforeTest;51import org.testng.annotations.DataProvider;5253import javax.net.ssl.SSLContext;54import java.io.BufferedReader;55import java.io.IOException;56import java.io.InputStream;57import java.io.InputStreamReader;58import java.io.OutputStream;59import java.io.UncheckedIOException;60import java.net.URI;61import java.net.URISyntaxException;62import java.net.http.HttpClient;63import java.net.http.HttpHeaders;64import java.net.http.HttpRequest;65import java.net.http.HttpResponse;66import java.net.http.HttpResponse.BodyHandler;67import java.net.http.HttpResponse.BodyHandlers;68import java.net.http.HttpResponse.BodySubscriber;69import java.net.http.HttpResponse.PushPromiseHandler;70import java.nio.ByteBuffer;71import java.nio.charset.StandardCharsets;72import java.util.Arrays;73import java.util.List;74import java.util.Map;75import java.util.concurrent.CompletableFuture;76import java.util.concurrent.CompletionException;77import java.util.concurrent.CompletionStage;78import java.util.concurrent.ConcurrentHashMap;79import java.util.concurrent.ConcurrentMap;80import java.util.concurrent.Executor;81import java.util.concurrent.Executors;82import java.util.concurrent.Flow;83import java.util.concurrent.atomic.AtomicLong;84import java.util.concurrent.atomic.AtomicReference;85import java.util.function.BiPredicate;86import java.util.function.Consumer;87import java.util.function.Function;88import java.util.function.Predicate;89import java.util.function.Supplier;90import java.util.stream.Collectors;91import java.util.stream.Stream;9293import static java.lang.System.out;94import static java.lang.System.err;95import static java.lang.String.format;96import static java.nio.charset.StandardCharsets.UTF_8;97import static org.testng.Assert.assertEquals;98import static org.testng.Assert.assertTrue;99100public abstract class AbstractThrowingPushPromises implements HttpServerAdapters {101102SSLContext sslContext;103HttpTestServer http2TestServer; // HTTP/2 ( h2c )104HttpTestServer https2TestServer; // HTTP/2 ( h2 )105String http2URI_fixed;106String http2URI_chunk;107String https2URI_fixed;108String https2URI_chunk;109110static final int ITERATION_COUNT = 1;111// a shared executor helps reduce the amount of threads created by the test112static final Executor executor = new TestExecutor(Executors.newCachedThreadPool());113static final ConcurrentMap<String, Throwable> FAILURES = new ConcurrentHashMap<>();114static volatile boolean tasksFailed;115static final AtomicLong serverCount = new AtomicLong();116static final AtomicLong clientCount = new AtomicLong();117static final long start = System.nanoTime();118public static String now() {119long now = System.nanoTime() - start;120long secs = now / 1000_000_000;121long mill = (now % 1000_000_000) / 1000_000;122long nan = now % 1000_000;123return String.format("[%d s, %d ms, %d ns] ", secs, mill, nan);124}125126final ReferenceTracker TRACKER = ReferenceTracker.INSTANCE;127private volatile HttpClient sharedClient;128129static class TestExecutor implements Executor {130final AtomicLong tasks = new AtomicLong();131Executor executor;132TestExecutor(Executor executor) {133this.executor = executor;134}135136@Override137public void execute(Runnable command) {138long id = tasks.incrementAndGet();139executor.execute(() -> {140try {141command.run();142} catch (Throwable t) {143tasksFailed = true;144out.printf(now() + "Task %s failed: %s%n", id, t);145err.printf(now() + "Task %s failed: %s%n", id, t);146FAILURES.putIfAbsent("Task " + id, t);147throw t;148}149});150}151}152153protected boolean stopAfterFirstFailure() {154return Boolean.getBoolean("jdk.internal.httpclient.debug");155}156157final AtomicReference<SkipException> skiptests = new AtomicReference<>();158void checkSkip() {159var skip = skiptests.get();160if (skip != null) throw skip;161}162static String name(ITestResult result) {163var params = result.getParameters();164return result.getName()165+ (params == null ? "()" : Arrays.toString(result.getParameters()));166}167168@BeforeMethod169void beforeMethod(ITestContext context) {170if (stopAfterFirstFailure() && context.getFailedTests().size() > 0) {171if (skiptests.get() == null) {172SkipException skip = new SkipException("some tests failed");173skip.setStackTrace(new StackTraceElement[0]);174skiptests.compareAndSet(null, skip);175}176}177}178179@AfterClass180static final void printFailedTests(ITestContext context) {181out.println("\n=========================");182try {183// Exceptions should already have been added to FAILURES184// var failed = context.getFailedTests().getAllResults().stream()185// .collect(Collectors.toMap(r -> name(r), ITestResult::getThrowable));186// FAILURES.putAll(failed);187188out.printf("%n%sCreated %d servers and %d clients%n",189now(), serverCount.get(), clientCount.get());190if (FAILURES.isEmpty()) return;191out.println("Failed tests: ");192FAILURES.entrySet().forEach((e) -> {193out.printf("\t%s: %s%n", e.getKey(), e.getValue());194e.getValue().printStackTrace(out);195e.getValue().printStackTrace();196});197if (tasksFailed) {198out.println("WARNING: Some tasks failed");199}200} finally {201out.println("\n=========================\n");202}203}204205private String[] uris() {206return new String[] {207http2URI_fixed,208http2URI_chunk,209https2URI_fixed,210https2URI_chunk,211};212}213214@DataProvider(name = "sanity")215public Object[][] sanity() {216String[] uris = uris();217Object[][] result = new Object[uris.length * 2][];218219int i = 0;220for (boolean sameClient : List.of(false, true)) {221for (String uri: uris()) {222result[i++] = new Object[] {uri, sameClient};223}224}225assert i == uris.length * 2;226return result;227}228229enum Where {230BODY_HANDLER, ON_SUBSCRIBE, ON_NEXT, ON_COMPLETE, ON_ERROR, GET_BODY, BODY_CF,231BEFORE_ACCEPTING, AFTER_ACCEPTING;232public Consumer<Where> select(Consumer<Where> consumer) {233return new Consumer<Where>() {234@Override235public void accept(Where where) {236if (Where.this == where) {237consumer.accept(where);238}239}240};241}242}243244private Object[][] variants(List<Thrower> throwers) {245String[] uris = uris();246// reduce traces by always using the same client if247// stopAfterFirstFailure is requested.248List<Boolean> sameClients = stopAfterFirstFailure()249? List.of(true)250: List.of(false, true);251Object[][] result = new Object[uris.length * sameClients.size() * throwers.size()][];252int i = 0;253for (Thrower thrower : throwers) {254for (boolean sameClient : sameClients) {255for (String uri : uris()) {256result[i++] = new Object[]{uri, sameClient, thrower};257}258}259}260assert i == uris.length * sameClients.size() * throwers.size();261return result;262}263264@DataProvider(name = "ioVariants")265public Object[][] ioVariants(ITestContext context) {266if (stopAfterFirstFailure() && context.getFailedTests().size() > 0) {267return new Object[0][];268}269return variants(List.of(270new UncheckedIOExceptionThrower()));271}272273@DataProvider(name = "customVariants")274public Object[][] customVariants(ITestContext context) {275if (stopAfterFirstFailure() && context.getFailedTests().size() > 0) {276return new Object[0][];277}278return variants(List.of(279new UncheckedCustomExceptionThrower()));280}281282private HttpClient makeNewClient() {283clientCount.incrementAndGet();284return TRACKER.track(HttpClient.newBuilder()285.proxy(HttpClient.Builder.NO_PROXY)286.executor(executor)287.sslContext(sslContext)288.build());289}290291HttpClient newHttpClient(boolean share) {292if (!share) return makeNewClient();293HttpClient shared = sharedClient;294if (shared != null) return shared;295synchronized (this) {296shared = sharedClient;297if (shared == null) {298shared = sharedClient = makeNewClient();299}300return shared;301}302}303304// @Test(dataProvider = "sanity")305protected void testSanityImpl(String uri, boolean sameClient)306throws Exception {307HttpClient client = null;308out.printf("%ntestNoThrows(%s, %b)%n", uri, sameClient);309for (int i=0; i< ITERATION_COUNT; i++) {310if (!sameClient || client == null)311client = newHttpClient(sameClient);312313HttpRequest req = HttpRequest.newBuilder(URI.create(uri))314.build();315BodyHandler<Stream<String>> handler =316new ThrowingBodyHandler((w) -> {},317BodyHandlers.ofLines());318Map<HttpRequest, CompletableFuture<HttpResponse<Stream<String>>>> pushPromises =319new ConcurrentHashMap<>();320PushPromiseHandler<Stream<String>> pushHandler = new PushPromiseHandler<>() {321@Override322public void applyPushPromise(HttpRequest initiatingRequest,323HttpRequest pushPromiseRequest,324Function<BodyHandler<Stream<String>>,325CompletableFuture<HttpResponse<Stream<String>>>>326acceptor) {327pushPromises.putIfAbsent(pushPromiseRequest, acceptor.apply(handler));328}329};330HttpResponse<Stream<String>> response =331client.sendAsync(req, BodyHandlers.ofLines(), pushHandler).get();332String body = response.body().collect(Collectors.joining("|"));333assertEquals(URI.create(body).getPath(), URI.create(uri).getPath());334for (HttpRequest promised : pushPromises.keySet()) {335out.printf("%s Received promise: %s%n\tresponse: %s%n",336now(), promised, pushPromises.get(promised).get());337String promisedBody = pushPromises.get(promised).get().body()338.collect(Collectors.joining("|"));339assertEquals(promisedBody, promised.uri().toASCIIString());340}341assertEquals(3, pushPromises.size());342}343}344345// @Test(dataProvider = "variants")346protected void testThrowingAsStringImpl(String uri,347boolean sameClient,348Thrower thrower)349throws Exception350{351String test = format("testThrowingAsString(%s, %b, %s)",352uri, sameClient, thrower);353testThrowing(test, uri, sameClient, BodyHandlers::ofString,354this::checkAsString, thrower);355}356357//@Test(dataProvider = "variants")358protected void testThrowingAsLinesImpl(String uri,359boolean sameClient,360Thrower thrower)361throws Exception362{363String test = format("testThrowingAsLines(%s, %b, %s)",364uri, sameClient, thrower);365testThrowing(test, uri, sameClient, BodyHandlers::ofLines,366this::checkAsLines, thrower);367}368369//@Test(dataProvider = "variants")370protected void testThrowingAsInputStreamImpl(String uri,371boolean sameClient,372Thrower thrower)373throws Exception374{375String test = format("testThrowingAsInputStream(%s, %b, %s)",376uri, sameClient, thrower);377testThrowing(test, uri, sameClient, BodyHandlers::ofInputStream,378this::checkAsInputStream, thrower);379}380381private <T,U> void testThrowing(String name, String uri, boolean sameClient,382Supplier<BodyHandler<T>> handlers,383Finisher finisher, Thrower thrower)384throws Exception385{386checkSkip();387out.printf("%n%s%s%n", now(), name);388try {389testThrowing(uri, sameClient, handlers, finisher, thrower);390} catch (Error | Exception x) {391FAILURES.putIfAbsent(name, x);392throw x;393}394}395396private <T,U> void testThrowing(String uri, boolean sameClient,397Supplier<BodyHandler<T>> handlers,398Finisher finisher, Thrower thrower)399throws Exception400{401HttpClient client = null;402for (Where where : Where.values()) {403if (where == Where.ON_ERROR) continue;404if (!sameClient || client == null)405client = newHttpClient(sameClient);406407HttpRequest req = HttpRequest.408newBuilder(URI.create(uri))409.build();410ConcurrentMap<HttpRequest, CompletableFuture<HttpResponse<T>>> promiseMap =411new ConcurrentHashMap<>();412Supplier<BodyHandler<T>> throwing = () ->413new ThrowingBodyHandler(where.select(thrower), handlers.get());414PushPromiseHandler<T> pushHandler = new ThrowingPromiseHandler<>(415where.select(thrower),416PushPromiseHandler.of((r) -> throwing.get(), promiseMap));417out.println("try throwing in " + where);418HttpResponse<T> response = null;419try {420response = client.sendAsync(req, handlers.get(), pushHandler).join();421} catch (Error | Exception x) {422throw x;423}424if (response != null) {425finisher.finish(where, req.uri(), response, thrower, promiseMap);426}427}428}429430interface Thrower extends Consumer<Where>, Predicate<Throwable> {431432}433434interface Finisher<T,U> {435U finish(Where w, URI requestURI, HttpResponse<T> resp, Thrower thrower,436Map<HttpRequest, CompletableFuture<HttpResponse<T>>> promises);437}438439final <T,U> U shouldHaveThrown(Where w, HttpResponse<T> resp, Thrower thrower) {440String msg = "Expected exception not thrown in " + w441+ "\n\tReceived: " + resp442+ "\n\tWith body: " + resp.body();443System.out.println(msg);444throw new RuntimeException(msg);445}446447final List<String> checkAsString(Where w, URI reqURI,448HttpResponse<String> resp,449Thrower thrower,450Map<HttpRequest, CompletableFuture<HttpResponse<String>>> promises) {451Function<HttpResponse<String>, List<String>> extractor =452(r) -> List.of(r.body());453return check(w, reqURI, resp, thrower, promises, extractor);454}455456final List<String> checkAsLines(Where w, URI reqURI,457HttpResponse<Stream<String>> resp,458Thrower thrower,459Map<HttpRequest, CompletableFuture<HttpResponse<Stream<String>>>> promises) {460Function<HttpResponse<Stream<String>>, List<String>> extractor =461(r) -> r.body().collect(Collectors.toList());462return check(w, reqURI, resp, thrower, promises, extractor);463}464465final List<String> checkAsInputStream(Where w, URI reqURI,466HttpResponse<InputStream> resp,467Thrower thrower,468Map<HttpRequest, CompletableFuture<HttpResponse<InputStream>>> promises)469{470Function<HttpResponse<InputStream>, List<String>> extractor = (r) -> {471List<String> result;472try (InputStream is = r.body()) {473result = new BufferedReader(new InputStreamReader(is))474.lines().collect(Collectors.toList());475} catch (Throwable t) {476throw new CompletionException(t);477}478return result;479};480return check(w, reqURI, resp, thrower, promises, extractor);481}482483private final <T> List<String> check(Where w, URI reqURI,484HttpResponse<T> resp,485Thrower thrower,486Map<HttpRequest, CompletableFuture<HttpResponse<T>>> promises,487Function<HttpResponse<T>, List<String>> extractor)488{489List<String> result = extractor.apply(resp);490for (HttpRequest req : promises.keySet()) {491switch (w) {492case BEFORE_ACCEPTING:493throw new RuntimeException("No push promise should have been received" +494" for " + reqURI + " in " + w + ": got " + promises.keySet());495default:496break;497}498HttpResponse<T> presp;499try {500presp = promises.get(req).join();501} catch (Error | Exception x) {502Throwable cause = findCause(x, thrower);503if (cause != null) {504out.println(now() + "Got expected exception in "505+ w + ": " + cause);506continue;507}508throw x;509}510switch (w) {511case BEFORE_ACCEPTING:512case AFTER_ACCEPTING:513case BODY_HANDLER:514case GET_BODY:515case BODY_CF:516return shouldHaveThrown(w, presp, thrower);517default:518break;519}520List<String> presult = null;521try {522presult = extractor.apply(presp);523} catch (Error | Exception x) {524Throwable cause = findCause(x, thrower);525if (cause != null) {526out.println(now() + "Got expected exception for "527+ req + " in " + w + ": " + cause);528continue;529}530throw x;531}532throw new RuntimeException("Expected exception not thrown for "533+ req + " in " + w);534}535final int expectedCount;536switch (w) {537case BEFORE_ACCEPTING:538expectedCount = 0;539break;540default:541expectedCount = 3;542}543assertEquals(promises.size(), expectedCount,544"bad promise count for " + reqURI + " with " + w);545assertEquals(result, List.of(reqURI.toASCIIString()));546return result;547}548549private static Throwable findCause(Throwable x,550Predicate<Throwable> filter) {551while (x != null && !filter.test(x)) x = x.getCause();552return x;553}554555static final class UncheckedCustomExceptionThrower implements Thrower {556@Override557public void accept(Where where) {558out.println(now() + "Throwing in " + where);559throw new UncheckedCustomException(where.name());560}561562@Override563public boolean test(Throwable throwable) {564return UncheckedCustomException.class.isInstance(throwable);565}566567@Override568public String toString() {569return "UncheckedCustomExceptionThrower";570}571}572573static final class UncheckedIOExceptionThrower implements Thrower {574@Override575public void accept(Where where) {576out.println(now() + "Throwing in " + where);577throw new UncheckedIOException(new CustomIOException(where.name()));578}579580@Override581public boolean test(Throwable throwable) {582return UncheckedIOException.class.isInstance(throwable)583&& CustomIOException.class.isInstance(throwable.getCause());584}585586@Override587public String toString() {588return "UncheckedIOExceptionThrower";589}590}591592static final class UncheckedCustomException extends RuntimeException {593UncheckedCustomException(String message) {594super(message);595}596UncheckedCustomException(String message, Throwable cause) {597super(message, cause);598}599}600601static final class CustomIOException extends IOException {602CustomIOException(String message) {603super(message);604}605CustomIOException(String message, Throwable cause) {606super(message, cause);607}608}609610static final class ThrowingPromiseHandler<T> implements PushPromiseHandler<T> {611final Consumer<Where> throwing;612final PushPromiseHandler<T> pushHandler;613ThrowingPromiseHandler(Consumer<Where> throwing, PushPromiseHandler<T> pushHandler) {614this.throwing = throwing;615this.pushHandler = pushHandler;616}617618@Override619public void applyPushPromise(HttpRequest initiatingRequest,620HttpRequest pushPromiseRequest,621Function<BodyHandler<T>,622CompletableFuture<HttpResponse<T>>> acceptor) {623throwing.accept(Where.BEFORE_ACCEPTING);624pushHandler.applyPushPromise(initiatingRequest, pushPromiseRequest, acceptor);625throwing.accept(Where.AFTER_ACCEPTING);626}627}628629static final class ThrowingBodyHandler<T> implements BodyHandler<T> {630final Consumer<Where> throwing;631final BodyHandler<T> bodyHandler;632ThrowingBodyHandler(Consumer<Where> throwing, BodyHandler<T> bodyHandler) {633this.throwing = throwing;634this.bodyHandler = bodyHandler;635}636@Override637public BodySubscriber<T> apply(HttpResponse.ResponseInfo rinfo) {638throwing.accept(Where.BODY_HANDLER);639BodySubscriber<T> subscriber = bodyHandler.apply(rinfo);640return new ThrowingBodySubscriber(throwing, subscriber);641}642}643644static final class ThrowingBodySubscriber<T> implements BodySubscriber<T> {645private final BodySubscriber<T> subscriber;646volatile boolean onSubscribeCalled;647final Consumer<Where> throwing;648ThrowingBodySubscriber(Consumer<Where> throwing, BodySubscriber<T> subscriber) {649this.throwing = throwing;650this.subscriber = subscriber;651}652653@Override654public void onSubscribe(Flow.Subscription subscription) {655//out.println("onSubscribe ");656onSubscribeCalled = true;657throwing.accept(Where.ON_SUBSCRIBE);658subscriber.onSubscribe(subscription);659}660661@Override662public void onNext(List<ByteBuffer> item) {663// out.println("onNext " + item);664assertTrue(onSubscribeCalled);665throwing.accept(Where.ON_NEXT);666subscriber.onNext(item);667}668669@Override670public void onError(Throwable throwable) {671//out.println("onError");672assertTrue(onSubscribeCalled);673throwing.accept(Where.ON_ERROR);674subscriber.onError(throwable);675}676677@Override678public void onComplete() {679//out.println("onComplete");680assertTrue(onSubscribeCalled, "onComplete called before onSubscribe");681throwing.accept(Where.ON_COMPLETE);682subscriber.onComplete();683}684685@Override686public CompletionStage<T> getBody() {687throwing.accept(Where.GET_BODY);688try {689throwing.accept(Where.BODY_CF);690} catch (Throwable t) {691return CompletableFuture.failedFuture(t);692}693return subscriber.getBody();694}695}696697698@BeforeTest699public void setup() throws Exception {700sslContext = new SimpleSSLContext().get();701if (sslContext == null)702throw new AssertionError("Unexpected null sslContext");703704// HTTP/2705HttpTestHandler h2_fixedLengthHandler = new HTTP_FixedLengthHandler();706HttpTestHandler h2_chunkedHandler = new HTTP_ChunkedHandler();707708http2TestServer = HttpTestServer.of(new Http2TestServer("localhost", false, 0));709http2TestServer.addHandler(h2_fixedLengthHandler, "/http2/fixed");710http2TestServer.addHandler(h2_chunkedHandler, "/http2/chunk");711http2URI_fixed = "http://" + http2TestServer.serverAuthority() + "/http2/fixed/x";712http2URI_chunk = "http://" + http2TestServer.serverAuthority() + "/http2/chunk/x";713714https2TestServer = HttpTestServer.of(new Http2TestServer("localhost", true, sslContext));715https2TestServer.addHandler(h2_fixedLengthHandler, "/https2/fixed");716https2TestServer.addHandler(h2_chunkedHandler, "/https2/chunk");717https2URI_fixed = "https://" + https2TestServer.serverAuthority() + "/https2/fixed/x";718https2URI_chunk = "https://" + https2TestServer.serverAuthority() + "/https2/chunk/x";719720serverCount.addAndGet(2);721http2TestServer.start();722https2TestServer.start();723}724725@AfterTest726public void teardown() throws Exception {727String sharedClientName =728sharedClient == null ? null : sharedClient.toString();729sharedClient = null;730Thread.sleep(100);731AssertionError fail = TRACKER.check(500);732try {733http2TestServer.stop();734https2TestServer.stop();735} finally {736if (fail != null) {737if (sharedClientName != null) {738System.err.println("Shared client name is: " + sharedClientName);739}740throw fail;741}742}743}744745static final BiPredicate<String,String> ACCEPT_ALL = (x, y) -> true;746747private static void pushPromiseFor(HttpTestExchange t,748URI requestURI,749String pushPath,750boolean fixed)751throws IOException752{753try {754URI promise = new URI(requestURI.getScheme(),755requestURI.getAuthority(),756pushPath, null, null);757byte[] promiseBytes = promise.toASCIIString().getBytes(UTF_8);758out.printf("TestServer: %s Pushing promise: %s%n", now(), promise);759err.printf("TestServer: %s Pushing promise: %s%n", now(), promise);760HttpHeaders headers;761if (fixed) {762String length = String.valueOf(promiseBytes.length);763headers = HttpHeaders.of(Map.of("Content-Length", List.of(length)),764ACCEPT_ALL);765} else {766headers = HttpHeaders.of(Map.of(), ACCEPT_ALL); // empty767}768t.serverPush(promise, headers, promiseBytes);769} catch (URISyntaxException x) {770throw new IOException(x.getMessage(), x);771}772}773774static class HTTP_FixedLengthHandler implements HttpTestHandler {775@Override776public void handle(HttpTestExchange t) throws IOException {777out.println("HTTP_FixedLengthHandler received request to " + t.getRequestURI());778try (InputStream is = t.getRequestBody()) {779is.readAllBytes();780}781URI requestURI = t.getRequestURI();782for (int i = 1; i<2; i++) {783String path = requestURI.getPath() + "/before/promise-" + i;784pushPromiseFor(t, requestURI, path, true);785}786byte[] resp = t.getRequestURI().toString().getBytes(StandardCharsets.UTF_8);787t.sendResponseHeaders(200, resp.length); //fixed content length788try (OutputStream os = t.getResponseBody()) {789int bytes = resp.length/3;790for (int i = 0; i<2; i++) {791String path = requestURI.getPath() + "/after/promise-" + (i + 2);792os.write(resp, i * bytes, bytes);793os.flush();794pushPromiseFor(t, requestURI, path, true);795}796os.write(resp, 2*bytes, resp.length - 2*bytes);797}798}799800}801802static class HTTP_ChunkedHandler implements HttpTestHandler {803@Override804public void handle(HttpTestExchange t) throws IOException {805out.println("HTTP_ChunkedHandler received request to " + t.getRequestURI());806byte[] resp = t.getRequestURI().toString().getBytes(StandardCharsets.UTF_8);807try (InputStream is = t.getRequestBody()) {808is.readAllBytes();809}810URI requestURI = t.getRequestURI();811for (int i = 1; i<2; i++) {812String path = requestURI.getPath() + "/before/promise-" + i;813pushPromiseFor(t, requestURI, path, false);814}815t.sendResponseHeaders(200, -1); // chunked/variable816try (OutputStream os = t.getResponseBody()) {817int bytes = resp.length/3;818for (int i = 0; i<2; i++) {819String path = requestURI.getPath() + "/after/promise-" + (i + 2);820os.write(resp, i * bytes, bytes);821os.flush();822pushPromiseFor(t, requestURI, path, false);823}824os.write(resp, 2*bytes, resp.length - 2*bytes);825}826}827}828829}830831832