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