Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/test/jdk/java/net/httpclient/AbstractThrowingPushPromises.java
41152 views
1
/*
2
* Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved.
3
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4
*
5
* This code is free software; you can redistribute it and/or modify it
6
* under the terms of the GNU General Public License version 2 only, as
7
* published by the Free Software Foundation.
8
*
9
* This code is distributed in the hope that it will be useful, but WITHOUT
10
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12
* version 2 for more details (a copy is included in the LICENSE file that
13
* accompanied this code).
14
*
15
* You should have received a copy of the GNU General Public License version
16
* 2 along with this work; if not, write to the Free Software Foundation,
17
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18
*
19
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20
* or visit www.oracle.com if you need additional information or have any
21
* questions.
22
*/
23
24
25
/**
26
* This is not a test. Actual tests are implemented by concrete subclasses.
27
* The abstract class AbstractThrowingPushPromises provides a base framework
28
* to test what happens when push promise handlers and their
29
* response body handlers and subscribers throw unexpected exceptions.
30
* Concrete tests that extend this abstract class will need to include
31
* the following jtreg tags:
32
*
33
* @library /test/lib http2/server
34
* @build jdk.test.lib.net.SimpleSSLContext HttpServerAdapters
35
* ReferenceTracker AbstractThrowingPushPromises
36
* <concrete-class-name>
37
* @modules java.base/sun.net.www.http
38
* java.net.http/jdk.internal.net.http.common
39
* java.net.http/jdk.internal.net.http.frame
40
* java.net.http/jdk.internal.net.http.hpack
41
* @run testng/othervm -Djdk.internal.httpclient.debug=true <concrete-class-name>
42
*/
43
44
import jdk.test.lib.net.SimpleSSLContext;
45
import org.testng.ITestContext;
46
import org.testng.annotations.AfterTest;
47
import org.testng.annotations.AfterClass;
48
import org.testng.annotations.BeforeMethod;
49
import org.testng.annotations.BeforeTest;
50
import org.testng.annotations.DataProvider;
51
52
import javax.net.ssl.SSLContext;
53
import java.io.BufferedReader;
54
import java.io.IOException;
55
import java.io.InputStream;
56
import java.io.InputStreamReader;
57
import java.io.OutputStream;
58
import java.io.UncheckedIOException;
59
import java.net.URI;
60
import java.net.URISyntaxException;
61
import java.net.http.HttpClient;
62
import java.net.http.HttpHeaders;
63
import java.net.http.HttpRequest;
64
import java.net.http.HttpResponse;
65
import java.net.http.HttpResponse.BodyHandler;
66
import java.net.http.HttpResponse.BodyHandlers;
67
import java.net.http.HttpResponse.BodySubscriber;
68
import java.net.http.HttpResponse.PushPromiseHandler;
69
import java.nio.ByteBuffer;
70
import java.nio.charset.StandardCharsets;
71
import java.util.List;
72
import java.util.Map;
73
import java.util.concurrent.CompletableFuture;
74
import java.util.concurrent.CompletionException;
75
import java.util.concurrent.CompletionStage;
76
import java.util.concurrent.ConcurrentHashMap;
77
import java.util.concurrent.ConcurrentMap;
78
import java.util.concurrent.Executor;
79
import java.util.concurrent.Executors;
80
import java.util.concurrent.Flow;
81
import java.util.concurrent.atomic.AtomicLong;
82
import java.util.function.BiPredicate;
83
import java.util.function.Consumer;
84
import java.util.function.Function;
85
import java.util.function.Predicate;
86
import java.util.function.Supplier;
87
import java.util.stream.Collectors;
88
import java.util.stream.Stream;
89
90
import static java.lang.System.out;
91
import static java.lang.System.err;
92
import static java.lang.String.format;
93
import static java.nio.charset.StandardCharsets.UTF_8;
94
import static org.testng.Assert.assertEquals;
95
import static org.testng.Assert.assertTrue;
96
97
public abstract class AbstractThrowingPushPromises implements HttpServerAdapters {
98
99
SSLContext sslContext;
100
HttpTestServer http2TestServer; // HTTP/2 ( h2c )
101
HttpTestServer https2TestServer; // HTTP/2 ( h2 )
102
String http2URI_fixed;
103
String http2URI_chunk;
104
String https2URI_fixed;
105
String https2URI_chunk;
106
107
static final int ITERATION_COUNT = 1;
108
// a shared executor helps reduce the amount of threads created by the test
109
static final Executor executor = new TestExecutor(Executors.newCachedThreadPool());
110
static final ConcurrentMap<String, Throwable> FAILURES = new ConcurrentHashMap<>();
111
static volatile boolean tasksFailed;
112
static final AtomicLong serverCount = new AtomicLong();
113
static final AtomicLong clientCount = new AtomicLong();
114
static final long start = System.nanoTime();
115
public static String now() {
116
long now = System.nanoTime() - start;
117
long secs = now / 1000_000_000;
118
long mill = (now % 1000_000_000) / 1000_000;
119
long nan = now % 1000_000;
120
return String.format("[%d s, %d ms, %d ns] ", secs, mill, nan);
121
}
122
123
final ReferenceTracker TRACKER = ReferenceTracker.INSTANCE;
124
private volatile HttpClient sharedClient;
125
126
static class TestExecutor implements Executor {
127
final AtomicLong tasks = new AtomicLong();
128
Executor executor;
129
TestExecutor(Executor executor) {
130
this.executor = executor;
131
}
132
133
@Override
134
public void execute(Runnable command) {
135
long id = tasks.incrementAndGet();
136
executor.execute(() -> {
137
try {
138
command.run();
139
} catch (Throwable t) {
140
tasksFailed = true;
141
out.printf(now() + "Task %s failed: %s%n", id, t);
142
err.printf(now() + "Task %s failed: %s%n", id, t);
143
FAILURES.putIfAbsent("Task " + id, t);
144
throw t;
145
}
146
});
147
}
148
}
149
150
protected boolean stopAfterFirstFailure() {
151
return Boolean.getBoolean("jdk.internal.httpclient.debug");
152
}
153
154
@BeforeMethod
155
void beforeMethod(ITestContext context) {
156
if (stopAfterFirstFailure() && context.getFailedTests().size() > 0) {
157
throw new RuntimeException("some tests failed");
158
}
159
}
160
161
@AfterClass
162
static final void printFailedTests() {
163
out.println("\n=========================");
164
try {
165
out.printf("%n%sCreated %d servers and %d clients%n",
166
now(), serverCount.get(), clientCount.get());
167
if (FAILURES.isEmpty()) return;
168
out.println("Failed tests: ");
169
FAILURES.entrySet().forEach((e) -> {
170
out.printf("\t%s: %s%n", e.getKey(), e.getValue());
171
e.getValue().printStackTrace(out);
172
e.getValue().printStackTrace();
173
});
174
if (tasksFailed) {
175
out.println("WARNING: Some tasks failed");
176
}
177
} finally {
178
out.println("\n=========================\n");
179
}
180
}
181
182
private String[] uris() {
183
return new String[] {
184
http2URI_fixed,
185
http2URI_chunk,
186
https2URI_fixed,
187
https2URI_chunk,
188
};
189
}
190
191
@DataProvider(name = "sanity")
192
public Object[][] sanity() {
193
String[] uris = uris();
194
Object[][] result = new Object[uris.length * 2][];
195
196
int i = 0;
197
for (boolean sameClient : List.of(false, true)) {
198
for (String uri: uris()) {
199
result[i++] = new Object[] {uri, sameClient};
200
}
201
}
202
assert i == uris.length * 2;
203
return result;
204
}
205
206
enum Where {
207
BODY_HANDLER, ON_SUBSCRIBE, ON_NEXT, ON_COMPLETE, ON_ERROR, GET_BODY, BODY_CF,
208
BEFORE_ACCEPTING, AFTER_ACCEPTING;
209
public Consumer<Where> select(Consumer<Where> consumer) {
210
return new Consumer<Where>() {
211
@Override
212
public void accept(Where where) {
213
if (Where.this == where) {
214
consumer.accept(where);
215
}
216
}
217
};
218
}
219
}
220
221
private Object[][] variants(List<Thrower> throwers) {
222
String[] uris = uris();
223
// reduce traces by always using the same client if
224
// stopAfterFirstFailure is requested.
225
List<Boolean> sameClients = stopAfterFirstFailure()
226
? List.of(true)
227
: List.of(false, true);
228
Object[][] result = new Object[uris.length * sameClients.size() * throwers.size()][];
229
int i = 0;
230
for (Thrower thrower : throwers) {
231
for (boolean sameClient : sameClients) {
232
for (String uri : uris()) {
233
result[i++] = new Object[]{uri, sameClient, thrower};
234
}
235
}
236
}
237
assert i == uris.length * sameClients.size() * throwers.size();
238
return result;
239
}
240
241
@DataProvider(name = "ioVariants")
242
public Object[][] ioVariants(ITestContext context) {
243
if (stopAfterFirstFailure() && context.getFailedTests().size() > 0) {
244
return new Object[0][];
245
}
246
return variants(List.of(
247
new UncheckedIOExceptionThrower()));
248
}
249
250
@DataProvider(name = "customVariants")
251
public Object[][] customVariants(ITestContext context) {
252
if (stopAfterFirstFailure() && context.getFailedTests().size() > 0) {
253
return new Object[0][];
254
}
255
return variants(List.of(
256
new UncheckedCustomExceptionThrower()));
257
}
258
259
private HttpClient makeNewClient() {
260
clientCount.incrementAndGet();
261
return TRACKER.track(HttpClient.newBuilder()
262
.proxy(HttpClient.Builder.NO_PROXY)
263
.executor(executor)
264
.sslContext(sslContext)
265
.build());
266
}
267
268
HttpClient newHttpClient(boolean share) {
269
if (!share) return makeNewClient();
270
HttpClient shared = sharedClient;
271
if (shared != null) return shared;
272
synchronized (this) {
273
shared = sharedClient;
274
if (shared == null) {
275
shared = sharedClient = makeNewClient();
276
}
277
return shared;
278
}
279
}
280
281
// @Test(dataProvider = "sanity")
282
protected void testSanityImpl(String uri, boolean sameClient)
283
throws Exception {
284
HttpClient client = null;
285
out.printf("%ntestNoThrows(%s, %b)%n", uri, sameClient);
286
for (int i=0; i< ITERATION_COUNT; i++) {
287
if (!sameClient || client == null)
288
client = newHttpClient(sameClient);
289
290
HttpRequest req = HttpRequest.newBuilder(URI.create(uri))
291
.build();
292
BodyHandler<Stream<String>> handler =
293
new ThrowingBodyHandler((w) -> {},
294
BodyHandlers.ofLines());
295
Map<HttpRequest, CompletableFuture<HttpResponse<Stream<String>>>> pushPromises =
296
new ConcurrentHashMap<>();
297
PushPromiseHandler<Stream<String>> pushHandler = new PushPromiseHandler<>() {
298
@Override
299
public void applyPushPromise(HttpRequest initiatingRequest,
300
HttpRequest pushPromiseRequest,
301
Function<BodyHandler<Stream<String>>,
302
CompletableFuture<HttpResponse<Stream<String>>>>
303
acceptor) {
304
pushPromises.putIfAbsent(pushPromiseRequest, acceptor.apply(handler));
305
}
306
};
307
HttpResponse<Stream<String>> response =
308
client.sendAsync(req, BodyHandlers.ofLines(), pushHandler).get();
309
String body = response.body().collect(Collectors.joining("|"));
310
assertEquals(URI.create(body).getPath(), URI.create(uri).getPath());
311
for (HttpRequest promised : pushPromises.keySet()) {
312
out.printf("%s Received promise: %s%n\tresponse: %s%n",
313
now(), promised, pushPromises.get(promised).get());
314
String promisedBody = pushPromises.get(promised).get().body()
315
.collect(Collectors.joining("|"));
316
assertEquals(promisedBody, promised.uri().toASCIIString());
317
}
318
assertEquals(3, pushPromises.size());
319
}
320
}
321
322
// @Test(dataProvider = "variants")
323
protected void testThrowingAsStringImpl(String uri,
324
boolean sameClient,
325
Thrower thrower)
326
throws Exception
327
{
328
String test = format("testThrowingAsString(%s, %b, %s)",
329
uri, sameClient, thrower);
330
testThrowing(test, uri, sameClient, BodyHandlers::ofString,
331
this::checkAsString, thrower);
332
}
333
334
//@Test(dataProvider = "variants")
335
protected void testThrowingAsLinesImpl(String uri,
336
boolean sameClient,
337
Thrower thrower)
338
throws Exception
339
{
340
String test = format("testThrowingAsLines(%s, %b, %s)",
341
uri, sameClient, thrower);
342
testThrowing(test, uri, sameClient, BodyHandlers::ofLines,
343
this::checkAsLines, thrower);
344
}
345
346
//@Test(dataProvider = "variants")
347
protected void testThrowingAsInputStreamImpl(String uri,
348
boolean sameClient,
349
Thrower thrower)
350
throws Exception
351
{
352
String test = format("testThrowingAsInputStream(%s, %b, %s)",
353
uri, sameClient, thrower);
354
testThrowing(test, uri, sameClient, BodyHandlers::ofInputStream,
355
this::checkAsInputStream, thrower);
356
}
357
358
private <T,U> void testThrowing(String name, String uri, boolean sameClient,
359
Supplier<BodyHandler<T>> handlers,
360
Finisher finisher, Thrower thrower)
361
throws Exception
362
{
363
out.printf("%n%s%s%n", now(), name);
364
try {
365
testThrowing(uri, sameClient, handlers, finisher, thrower);
366
} catch (Error | Exception x) {
367
FAILURES.putIfAbsent(name, x);
368
throw x;
369
}
370
}
371
372
private <T,U> void testThrowing(String uri, boolean sameClient,
373
Supplier<BodyHandler<T>> handlers,
374
Finisher finisher, Thrower thrower)
375
throws Exception
376
{
377
HttpClient client = null;
378
for (Where where : Where.values()) {
379
if (where == Where.ON_ERROR) continue;
380
if (!sameClient || client == null)
381
client = newHttpClient(sameClient);
382
383
HttpRequest req = HttpRequest.
384
newBuilder(URI.create(uri))
385
.build();
386
ConcurrentMap<HttpRequest, CompletableFuture<HttpResponse<T>>> promiseMap =
387
new ConcurrentHashMap<>();
388
Supplier<BodyHandler<T>> throwing = () ->
389
new ThrowingBodyHandler(where.select(thrower), handlers.get());
390
PushPromiseHandler<T> pushHandler = new ThrowingPromiseHandler<>(
391
where.select(thrower),
392
PushPromiseHandler.of((r) -> throwing.get(), promiseMap));
393
out.println("try throwing in " + where);
394
HttpResponse<T> response = null;
395
try {
396
response = client.sendAsync(req, handlers.get(), pushHandler).join();
397
} catch (Error | Exception x) {
398
throw x;
399
}
400
if (response != null) {
401
finisher.finish(where, req.uri(), response, thrower, promiseMap);
402
}
403
}
404
}
405
406
interface Thrower extends Consumer<Where>, Predicate<Throwable> {
407
408
}
409
410
interface Finisher<T,U> {
411
U finish(Where w, URI requestURI, HttpResponse<T> resp, Thrower thrower,
412
Map<HttpRequest, CompletableFuture<HttpResponse<T>>> promises);
413
}
414
415
final <T,U> U shouldHaveThrown(Where w, HttpResponse<T> resp, Thrower thrower) {
416
String msg = "Expected exception not thrown in " + w
417
+ "\n\tReceived: " + resp
418
+ "\n\tWith body: " + resp.body();
419
System.out.println(msg);
420
throw new RuntimeException(msg);
421
}
422
423
final List<String> checkAsString(Where w, URI reqURI,
424
HttpResponse<String> resp,
425
Thrower thrower,
426
Map<HttpRequest, CompletableFuture<HttpResponse<String>>> promises) {
427
Function<HttpResponse<String>, List<String>> extractor =
428
(r) -> List.of(r.body());
429
return check(w, reqURI, resp, thrower, promises, extractor);
430
}
431
432
final List<String> checkAsLines(Where w, URI reqURI,
433
HttpResponse<Stream<String>> resp,
434
Thrower thrower,
435
Map<HttpRequest, CompletableFuture<HttpResponse<Stream<String>>>> promises) {
436
Function<HttpResponse<Stream<String>>, List<String>> extractor =
437
(r) -> r.body().collect(Collectors.toList());
438
return check(w, reqURI, resp, thrower, promises, extractor);
439
}
440
441
final List<String> checkAsInputStream(Where w, URI reqURI,
442
HttpResponse<InputStream> resp,
443
Thrower thrower,
444
Map<HttpRequest, CompletableFuture<HttpResponse<InputStream>>> promises)
445
{
446
Function<HttpResponse<InputStream>, List<String>> extractor = (r) -> {
447
List<String> result;
448
try (InputStream is = r.body()) {
449
result = new BufferedReader(new InputStreamReader(is))
450
.lines().collect(Collectors.toList());
451
} catch (Throwable t) {
452
throw new CompletionException(t);
453
}
454
return result;
455
};
456
return check(w, reqURI, resp, thrower, promises, extractor);
457
}
458
459
private final <T> List<String> check(Where w, URI reqURI,
460
HttpResponse<T> resp,
461
Thrower thrower,
462
Map<HttpRequest, CompletableFuture<HttpResponse<T>>> promises,
463
Function<HttpResponse<T>, List<String>> extractor)
464
{
465
List<String> result = extractor.apply(resp);
466
for (HttpRequest req : promises.keySet()) {
467
switch (w) {
468
case BEFORE_ACCEPTING:
469
throw new RuntimeException("No push promise should have been received" +
470
" for " + reqURI + " in " + w + ": got " + promises.keySet());
471
default:
472
break;
473
}
474
HttpResponse<T> presp;
475
try {
476
presp = promises.get(req).join();
477
} catch (Error | Exception x) {
478
Throwable cause = findCause(x, thrower);
479
if (cause != null) {
480
out.println(now() + "Got expected exception in "
481
+ w + ": " + cause);
482
continue;
483
}
484
throw x;
485
}
486
switch (w) {
487
case BEFORE_ACCEPTING:
488
case AFTER_ACCEPTING:
489
case BODY_HANDLER:
490
case GET_BODY:
491
case BODY_CF:
492
return shouldHaveThrown(w, presp, thrower);
493
default:
494
break;
495
}
496
List<String> presult = null;
497
try {
498
presult = extractor.apply(presp);
499
} catch (Error | Exception x) {
500
Throwable cause = findCause(x, thrower);
501
if (cause != null) {
502
out.println(now() + "Got expected exception for "
503
+ req + " in " + w + ": " + cause);
504
continue;
505
}
506
throw x;
507
}
508
throw new RuntimeException("Expected exception not thrown for "
509
+ req + " in " + w);
510
}
511
final int expectedCount;
512
switch (w) {
513
case BEFORE_ACCEPTING:
514
expectedCount = 0;
515
break;
516
default:
517
expectedCount = 3;
518
}
519
assertEquals(promises.size(), expectedCount,
520
"bad promise count for " + reqURI + " with " + w);
521
assertEquals(result, List.of(reqURI.toASCIIString()));
522
return result;
523
}
524
525
private static Throwable findCause(Throwable x,
526
Predicate<Throwable> filter) {
527
while (x != null && !filter.test(x)) x = x.getCause();
528
return x;
529
}
530
531
static final class UncheckedCustomExceptionThrower implements Thrower {
532
@Override
533
public void accept(Where where) {
534
out.println(now() + "Throwing in " + where);
535
throw new UncheckedCustomException(where.name());
536
}
537
538
@Override
539
public boolean test(Throwable throwable) {
540
return UncheckedCustomException.class.isInstance(throwable);
541
}
542
543
@Override
544
public String toString() {
545
return "UncheckedCustomExceptionThrower";
546
}
547
}
548
549
static final class UncheckedIOExceptionThrower implements Thrower {
550
@Override
551
public void accept(Where where) {
552
out.println(now() + "Throwing in " + where);
553
throw new UncheckedIOException(new CustomIOException(where.name()));
554
}
555
556
@Override
557
public boolean test(Throwable throwable) {
558
return UncheckedIOException.class.isInstance(throwable)
559
&& CustomIOException.class.isInstance(throwable.getCause());
560
}
561
562
@Override
563
public String toString() {
564
return "UncheckedIOExceptionThrower";
565
}
566
}
567
568
static final class UncheckedCustomException extends RuntimeException {
569
UncheckedCustomException(String message) {
570
super(message);
571
}
572
UncheckedCustomException(String message, Throwable cause) {
573
super(message, cause);
574
}
575
}
576
577
static final class CustomIOException extends IOException {
578
CustomIOException(String message) {
579
super(message);
580
}
581
CustomIOException(String message, Throwable cause) {
582
super(message, cause);
583
}
584
}
585
586
static final class ThrowingPromiseHandler<T> implements PushPromiseHandler<T> {
587
final Consumer<Where> throwing;
588
final PushPromiseHandler<T> pushHandler;
589
ThrowingPromiseHandler(Consumer<Where> throwing, PushPromiseHandler<T> pushHandler) {
590
this.throwing = throwing;
591
this.pushHandler = pushHandler;
592
}
593
594
@Override
595
public void applyPushPromise(HttpRequest initiatingRequest,
596
HttpRequest pushPromiseRequest,
597
Function<BodyHandler<T>,
598
CompletableFuture<HttpResponse<T>>> acceptor) {
599
throwing.accept(Where.BEFORE_ACCEPTING);
600
pushHandler.applyPushPromise(initiatingRequest, pushPromiseRequest, acceptor);
601
throwing.accept(Where.AFTER_ACCEPTING);
602
}
603
}
604
605
static final class ThrowingBodyHandler<T> implements BodyHandler<T> {
606
final Consumer<Where> throwing;
607
final BodyHandler<T> bodyHandler;
608
ThrowingBodyHandler(Consumer<Where> throwing, BodyHandler<T> bodyHandler) {
609
this.throwing = throwing;
610
this.bodyHandler = bodyHandler;
611
}
612
@Override
613
public BodySubscriber<T> apply(HttpResponse.ResponseInfo rinfo) {
614
throwing.accept(Where.BODY_HANDLER);
615
BodySubscriber<T> subscriber = bodyHandler.apply(rinfo);
616
return new ThrowingBodySubscriber(throwing, subscriber);
617
}
618
}
619
620
static final class ThrowingBodySubscriber<T> implements BodySubscriber<T> {
621
private final BodySubscriber<T> subscriber;
622
volatile boolean onSubscribeCalled;
623
final Consumer<Where> throwing;
624
ThrowingBodySubscriber(Consumer<Where> throwing, BodySubscriber<T> subscriber) {
625
this.throwing = throwing;
626
this.subscriber = subscriber;
627
}
628
629
@Override
630
public void onSubscribe(Flow.Subscription subscription) {
631
//out.println("onSubscribe ");
632
onSubscribeCalled = true;
633
throwing.accept(Where.ON_SUBSCRIBE);
634
subscriber.onSubscribe(subscription);
635
}
636
637
@Override
638
public void onNext(List<ByteBuffer> item) {
639
// out.println("onNext " + item);
640
assertTrue(onSubscribeCalled);
641
throwing.accept(Where.ON_NEXT);
642
subscriber.onNext(item);
643
}
644
645
@Override
646
public void onError(Throwable throwable) {
647
//out.println("onError");
648
assertTrue(onSubscribeCalled);
649
throwing.accept(Where.ON_ERROR);
650
subscriber.onError(throwable);
651
}
652
653
@Override
654
public void onComplete() {
655
//out.println("onComplete");
656
assertTrue(onSubscribeCalled, "onComplete called before onSubscribe");
657
throwing.accept(Where.ON_COMPLETE);
658
subscriber.onComplete();
659
}
660
661
@Override
662
public CompletionStage<T> getBody() {
663
throwing.accept(Where.GET_BODY);
664
try {
665
throwing.accept(Where.BODY_CF);
666
} catch (Throwable t) {
667
return CompletableFuture.failedFuture(t);
668
}
669
return subscriber.getBody();
670
}
671
}
672
673
674
@BeforeTest
675
public void setup() throws Exception {
676
sslContext = new SimpleSSLContext().get();
677
if (sslContext == null)
678
throw new AssertionError("Unexpected null sslContext");
679
680
// HTTP/2
681
HttpTestHandler h2_fixedLengthHandler = new HTTP_FixedLengthHandler();
682
HttpTestHandler h2_chunkedHandler = new HTTP_ChunkedHandler();
683
684
http2TestServer = HttpTestServer.of(new Http2TestServer("localhost", false, 0));
685
http2TestServer.addHandler(h2_fixedLengthHandler, "/http2/fixed");
686
http2TestServer.addHandler(h2_chunkedHandler, "/http2/chunk");
687
http2URI_fixed = "http://" + http2TestServer.serverAuthority() + "/http2/fixed/x";
688
http2URI_chunk = "http://" + http2TestServer.serverAuthority() + "/http2/chunk/x";
689
690
https2TestServer = HttpTestServer.of(new Http2TestServer("localhost", true, sslContext));
691
https2TestServer.addHandler(h2_fixedLengthHandler, "/https2/fixed");
692
https2TestServer.addHandler(h2_chunkedHandler, "/https2/chunk");
693
https2URI_fixed = "https://" + https2TestServer.serverAuthority() + "/https2/fixed/x";
694
https2URI_chunk = "https://" + https2TestServer.serverAuthority() + "/https2/chunk/x";
695
696
serverCount.addAndGet(2);
697
http2TestServer.start();
698
https2TestServer.start();
699
}
700
701
@AfterTest
702
public void teardown() throws Exception {
703
String sharedClientName =
704
sharedClient == null ? null : sharedClient.toString();
705
sharedClient = null;
706
Thread.sleep(100);
707
AssertionError fail = TRACKER.check(500);
708
try {
709
http2TestServer.stop();
710
https2TestServer.stop();
711
} finally {
712
if (fail != null) {
713
if (sharedClientName != null) {
714
System.err.println("Shared client name is: " + sharedClientName);
715
}
716
throw fail;
717
}
718
}
719
}
720
721
static final BiPredicate<String,String> ACCEPT_ALL = (x, y) -> true;
722
723
private static void pushPromiseFor(HttpTestExchange t,
724
URI requestURI,
725
String pushPath,
726
boolean fixed)
727
throws IOException
728
{
729
try {
730
URI promise = new URI(requestURI.getScheme(),
731
requestURI.getAuthority(),
732
pushPath, null, null);
733
byte[] promiseBytes = promise.toASCIIString().getBytes(UTF_8);
734
out.printf("TestServer: %s Pushing promise: %s%n", now(), promise);
735
err.printf("TestServer: %s Pushing promise: %s%n", now(), promise);
736
HttpHeaders headers;
737
if (fixed) {
738
String length = String.valueOf(promiseBytes.length);
739
headers = HttpHeaders.of(Map.of("Content-Length", List.of(length)),
740
ACCEPT_ALL);
741
} else {
742
headers = HttpHeaders.of(Map.of(), ACCEPT_ALL); // empty
743
}
744
t.serverPush(promise, headers, promiseBytes);
745
} catch (URISyntaxException x) {
746
throw new IOException(x.getMessage(), x);
747
}
748
}
749
750
static class HTTP_FixedLengthHandler implements HttpTestHandler {
751
@Override
752
public void handle(HttpTestExchange t) throws IOException {
753
out.println("HTTP_FixedLengthHandler received request to " + t.getRequestURI());
754
try (InputStream is = t.getRequestBody()) {
755
is.readAllBytes();
756
}
757
URI requestURI = t.getRequestURI();
758
for (int i = 1; i<2; i++) {
759
String path = requestURI.getPath() + "/before/promise-" + i;
760
pushPromiseFor(t, requestURI, path, true);
761
}
762
byte[] resp = t.getRequestURI().toString().getBytes(StandardCharsets.UTF_8);
763
t.sendResponseHeaders(200, resp.length); //fixed content length
764
try (OutputStream os = t.getResponseBody()) {
765
int bytes = resp.length/3;
766
for (int i = 0; i<2; i++) {
767
String path = requestURI.getPath() + "/after/promise-" + (i + 2);
768
os.write(resp, i * bytes, bytes);
769
os.flush();
770
pushPromiseFor(t, requestURI, path, true);
771
}
772
os.write(resp, 2*bytes, resp.length - 2*bytes);
773
}
774
}
775
776
}
777
778
static class HTTP_ChunkedHandler implements HttpTestHandler {
779
@Override
780
public void handle(HttpTestExchange t) throws IOException {
781
out.println("HTTP_ChunkedHandler received request to " + t.getRequestURI());
782
byte[] resp = t.getRequestURI().toString().getBytes(StandardCharsets.UTF_8);
783
try (InputStream is = t.getRequestBody()) {
784
is.readAllBytes();
785
}
786
URI requestURI = t.getRequestURI();
787
for (int i = 1; i<2; i++) {
788
String path = requestURI.getPath() + "/before/promise-" + i;
789
pushPromiseFor(t, requestURI, path, false);
790
}
791
t.sendResponseHeaders(200, -1); // chunked/variable
792
try (OutputStream os = t.getResponseBody()) {
793
int bytes = resp.length/3;
794
for (int i = 0; i<2; i++) {
795
String path = requestURI.getPath() + "/after/promise-" + (i + 2);
796
os.write(resp, i * bytes, bytes);
797
os.flush();
798
pushPromiseFor(t, requestURI, path, false);
799
}
800
os.write(resp, 2*bytes, resp.length - 2*bytes);
801
}
802
}
803
}
804
805
}
806
807