Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/jdk17u
Path: blob/master/test/jdk/java/net/httpclient/AbstractThrowingPublishers.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
import com.sun.net.httpserver.HttpServer;
25
import com.sun.net.httpserver.HttpsConfigurator;
26
import com.sun.net.httpserver.HttpsServer;
27
import jdk.test.lib.net.SimpleSSLContext;
28
import org.testng.ITestContext;
29
import org.testng.ITestResult;
30
import org.testng.SkipException;
31
import org.testng.annotations.AfterClass;
32
import org.testng.annotations.AfterTest;
33
import org.testng.annotations.BeforeMethod;
34
import org.testng.annotations.BeforeTest;
35
import org.testng.annotations.DataProvider;
36
import org.testng.annotations.Test;
37
38
import javax.net.ssl.SSLContext;
39
import java.io.IOException;
40
import java.io.InputStream;
41
import java.io.OutputStream;
42
import java.io.UncheckedIOException;
43
import java.net.InetAddress;
44
import java.net.InetSocketAddress;
45
import java.net.URI;
46
import java.net.http.HttpClient;
47
import java.net.http.HttpRequest;
48
import java.net.http.HttpRequest.BodyPublisher;
49
import java.net.http.HttpRequest.BodyPublishers;
50
import java.net.http.HttpResponse;
51
import java.net.http.HttpResponse.BodyHandler;
52
import java.net.http.HttpResponse.BodyHandlers;
53
import java.nio.ByteBuffer;
54
import java.nio.charset.StandardCharsets;
55
import java.util.Arrays;
56
import java.util.EnumSet;
57
import java.util.List;
58
import java.util.Set;
59
import java.util.concurrent.CompletableFuture;
60
import java.util.concurrent.CompletionException;
61
import java.util.concurrent.ConcurrentHashMap;
62
import java.util.concurrent.ConcurrentMap;
63
import java.util.concurrent.ExecutionException;
64
import java.util.concurrent.Executor;
65
import java.util.concurrent.Executors;
66
import java.util.concurrent.Flow;
67
import java.util.concurrent.SubmissionPublisher;
68
import java.util.concurrent.atomic.AtomicLong;
69
import java.util.concurrent.atomic.AtomicReference;
70
import java.util.function.BiPredicate;
71
import java.util.function.Consumer;
72
import java.util.function.Supplier;
73
import java.util.stream.Collectors;
74
import java.util.stream.Stream;
75
76
import static java.lang.String.format;
77
import static java.lang.System.out;
78
import static java.nio.charset.StandardCharsets.UTF_8;
79
import static org.testng.Assert.assertEquals;
80
import static org.testng.Assert.assertTrue;
81
82
public abstract class AbstractThrowingPublishers implements HttpServerAdapters {
83
84
SSLContext sslContext;
85
HttpTestServer httpTestServer; // HTTP/1.1 [ 4 servers ]
86
HttpTestServer httpsTestServer; // HTTPS/1.1
87
HttpTestServer http2TestServer; // HTTP/2 ( h2c )
88
HttpTestServer https2TestServer; // HTTP/2 ( h2 )
89
String httpURI_fixed;
90
String httpURI_chunk;
91
String httpsURI_fixed;
92
String httpsURI_chunk;
93
String http2URI_fixed;
94
String http2URI_chunk;
95
String https2URI_fixed;
96
String https2URI_chunk;
97
98
static final int ITERATION_COUNT = 1;
99
// a shared executor helps reduce the amount of threads created by the test
100
static final Executor executor = new TestExecutor(Executors.newCachedThreadPool());
101
static final ConcurrentMap<String, Throwable> FAILURES = new ConcurrentHashMap<>();
102
static volatile boolean tasksFailed;
103
static final AtomicLong serverCount = new AtomicLong();
104
static final AtomicLong clientCount = new AtomicLong();
105
static final long start = System.nanoTime();
106
public static String now() {
107
long now = System.nanoTime() - start;
108
long secs = now / 1000_000_000;
109
long mill = (now % 1000_000_000) / 1000_000;
110
long nan = now % 1000_000;
111
return String.format("[%d s, %d ms, %d ns] ", secs, mill, nan);
112
}
113
114
final ReferenceTracker TRACKER = ReferenceTracker.INSTANCE;
115
private volatile HttpClient sharedClient;
116
117
static class TestExecutor implements Executor {
118
final AtomicLong tasks = new AtomicLong();
119
Executor executor;
120
TestExecutor(Executor executor) {
121
this.executor = executor;
122
}
123
124
@Override
125
public void execute(Runnable command) {
126
long id = tasks.incrementAndGet();
127
executor.execute(() -> {
128
try {
129
command.run();
130
} catch (Throwable t) {
131
tasksFailed = true;
132
System.out.printf(now() + "Task %s failed: %s%n", id, t);
133
System.err.printf(now() + "Task %s failed: %s%n", id, t);
134
FAILURES.putIfAbsent("Task " + id, t);
135
throw t;
136
}
137
});
138
}
139
}
140
141
protected boolean stopAfterFirstFailure() {
142
return Boolean.getBoolean("jdk.internal.httpclient.debug");
143
}
144
145
final AtomicReference<SkipException> skiptests = new AtomicReference<>();
146
void checkSkip() {
147
var skip = skiptests.get();
148
if (skip != null) throw skip;
149
}
150
static String name(ITestResult result) {
151
var params = result.getParameters();
152
return result.getName()
153
+ (params == null ? "()" : Arrays.toString(result.getParameters()));
154
}
155
156
@BeforeMethod
157
void beforeMethod(ITestContext context) {
158
if (stopAfterFirstFailure() && context.getFailedTests().size() > 0) {
159
if (skiptests.get() == null) {
160
SkipException skip = new SkipException("some tests failed");
161
skip.setStackTrace(new StackTraceElement[0]);
162
skiptests.compareAndSet(null, skip);
163
}
164
}
165
}
166
167
@AfterClass
168
static final void printFailedTests(ITestContext context) {
169
out.println("\n=========================");
170
try {
171
// Exceptions should already have been added to FAILURES
172
// var failed = context.getFailedTests().getAllResults().stream()
173
// .collect(Collectors.toMap(r -> name(r), ITestResult::getThrowable));
174
// FAILURES.putAll(failed);
175
176
out.printf("%n%sCreated %d servers and %d clients%n",
177
now(), serverCount.get(), clientCount.get());
178
if (FAILURES.isEmpty()) return;
179
out.println("Failed tests: ");
180
FAILURES.entrySet().forEach((e) -> {
181
out.printf("\t%s: %s%n", e.getKey(), e.getValue());
182
e.getValue().printStackTrace(out);
183
});
184
if (tasksFailed) {
185
System.out.println("WARNING: Some tasks failed");
186
}
187
} finally {
188
out.println("\n=========================\n");
189
}
190
}
191
192
private String[] uris() {
193
return new String[] {
194
httpURI_fixed,
195
httpURI_chunk,
196
httpsURI_fixed,
197
httpsURI_chunk,
198
http2URI_fixed,
199
http2URI_chunk,
200
https2URI_fixed,
201
https2URI_chunk,
202
};
203
}
204
205
@DataProvider(name = "sanity")
206
public Object[][] sanity() {
207
String[] uris = uris();
208
Object[][] result = new Object[uris.length * 2][];
209
//Object[][] result = new Object[uris.length][];
210
int i = 0;
211
for (boolean sameClient : List.of(false, true)) {
212
//if (!sameClient) continue;
213
for (String uri: uris()) {
214
result[i++] = new Object[] {uri + "/sanity", sameClient};
215
}
216
}
217
assert i == uris.length * 2;
218
// assert i == uris.length ;
219
return result;
220
}
221
222
enum Where {
223
BEFORE_SUBSCRIBE, BEFORE_REQUEST, BEFORE_NEXT_REQUEST, BEFORE_CANCEL,
224
AFTER_SUBSCRIBE, AFTER_REQUEST, AFTER_NEXT_REQUEST, AFTER_CANCEL;
225
public Consumer<Where> select(Consumer<Where> consumer) {
226
return new Consumer<Where>() {
227
@Override
228
public void accept(Where where) {
229
if (Where.this == where) {
230
consumer.accept(where);
231
}
232
}
233
};
234
}
235
}
236
237
private Object[][] variants(List<Thrower> throwers, Set<Where> whereValues) {
238
String[] uris = uris();
239
Object[][] result = new Object[uris.length * 2 * throwers.size()][];
240
//Object[][] result = new Object[(uris.length/2) * 2 * 2][];
241
int i = 0;
242
for (Thrower thrower : throwers) {
243
for (boolean sameClient : List.of(false, true)) {
244
for (String uri : uris()) {
245
// if (uri.contains("http2") || uri.contains("https2")) continue;
246
// if (!sameClient) continue;
247
result[i++] = new Object[]{uri, sameClient, thrower, whereValues};
248
}
249
}
250
}
251
assert i == uris.length * 2 * throwers.size();
252
//assert Stream.of(result).filter(o -> o != null).count() == result.length;
253
return result;
254
}
255
256
@DataProvider(name = "subscribeProvider")
257
public Object[][] subscribeProvider(ITestContext context) {
258
if (stopAfterFirstFailure() && context.getFailedTests().size() > 0) {
259
return new Object[0][];
260
}
261
return variants(List.of(
262
new UncheckedCustomExceptionThrower(),
263
new UncheckedIOExceptionThrower()),
264
EnumSet.of(Where.BEFORE_SUBSCRIBE, Where.AFTER_SUBSCRIBE));
265
}
266
267
@DataProvider(name = "requestProvider")
268
public Object[][] requestProvider(ITestContext context) {
269
if (stopAfterFirstFailure() && context.getFailedTests().size() > 0) {
270
return new Object[0][];
271
}
272
return variants(List.of(
273
new UncheckedCustomExceptionThrower(),
274
new UncheckedIOExceptionThrower()),
275
EnumSet.of(Where.BEFORE_REQUEST, Where.AFTER_REQUEST));
276
}
277
278
@DataProvider(name = "nextRequestProvider")
279
public Object[][] nextRequestProvider(ITestContext context) {
280
if (stopAfterFirstFailure() && context.getFailedTests().size() > 0) {
281
return new Object[0][];
282
}
283
return variants(List.of(
284
new UncheckedCustomExceptionThrower(),
285
new UncheckedIOExceptionThrower()),
286
EnumSet.of(Where.BEFORE_NEXT_REQUEST, Where.AFTER_NEXT_REQUEST));
287
}
288
289
@DataProvider(name = "beforeCancelProviderIO")
290
public Object[][] beforeCancelProviderIO(ITestContext context) {
291
if (stopAfterFirstFailure() && context.getFailedTests().size() > 0) {
292
return new Object[0][];
293
}
294
return variants(List.of(
295
new UncheckedIOExceptionThrower()),
296
EnumSet.of(Where.BEFORE_CANCEL));
297
}
298
299
@DataProvider(name = "afterCancelProviderIO")
300
public Object[][] afterCancelProviderIO(ITestContext context) {
301
if (stopAfterFirstFailure() && context.getFailedTests().size() > 0) {
302
return new Object[0][];
303
}
304
return variants(List.of(
305
new UncheckedIOExceptionThrower()),
306
EnumSet.of(Where.AFTER_CANCEL));
307
}
308
309
@DataProvider(name = "beforeCancelProviderCustom")
310
public Object[][] beforeCancelProviderCustom(ITestContext context) {
311
if (stopAfterFirstFailure() && context.getFailedTests().size() > 0) {
312
return new Object[0][];
313
}
314
return variants(List.of(
315
new UncheckedCustomExceptionThrower()),
316
EnumSet.of(Where.BEFORE_CANCEL));
317
}
318
319
@DataProvider(name = "afterCancelProviderCustom")
320
public Object[][] afterCancelProvider(ITestContext context) {
321
if (stopAfterFirstFailure() && context.getFailedTests().size() > 0) {
322
return new Object[0][];
323
}
324
return variants(List.of(
325
new UncheckedCustomExceptionThrower()),
326
EnumSet.of(Where.AFTER_CANCEL));
327
}
328
329
private HttpClient makeNewClient() {
330
clientCount.incrementAndGet();
331
return TRACKER.track(HttpClient.newBuilder()
332
.proxy(HttpClient.Builder.NO_PROXY)
333
.executor(executor)
334
.sslContext(sslContext)
335
.build());
336
}
337
338
HttpClient newHttpClient(boolean share) {
339
if (!share) return makeNewClient();
340
HttpClient shared = sharedClient;
341
if (shared != null) return shared;
342
synchronized (this) {
343
shared = sharedClient;
344
if (shared == null) {
345
shared = sharedClient = makeNewClient();
346
}
347
return shared;
348
}
349
}
350
351
final String BODY = "Some string | that ? can | be split ? several | ways.";
352
353
//@Test(dataProvider = "sanity")
354
protected void testSanityImpl(String uri, boolean sameClient)
355
throws Exception {
356
HttpClient client = null;
357
out.printf("%n%s testSanity(%s, %b)%n", now(), uri, sameClient);
358
for (int i=0; i< ITERATION_COUNT; i++) {
359
if (!sameClient || client == null)
360
client = newHttpClient(sameClient);
361
362
SubmissionPublisher<ByteBuffer> publisher
363
= new SubmissionPublisher<>(executor,10);
364
ThrowingBodyPublisher bodyPublisher = new ThrowingBodyPublisher((w) -> {},
365
BodyPublishers.fromPublisher(publisher));
366
CompletableFuture<Void> subscribedCF = bodyPublisher.subscribedCF();
367
subscribedCF.whenComplete((r,t) -> System.out.println(now() + " subscribe completed " + t))
368
.thenAcceptAsync((v) -> {
369
Stream.of(BODY.split("\\|"))
370
.forEachOrdered(s -> {
371
System.out.println("submitting \"" + s +"\"");
372
publisher.submit(ByteBuffer.wrap(s.getBytes(StandardCharsets.UTF_8)));
373
});
374
System.out.println("publishing done");
375
publisher.close();
376
},
377
executor);
378
379
HttpRequest req = HttpRequest.newBuilder(URI.create(uri))
380
.POST(bodyPublisher)
381
.build();
382
BodyHandler<String> handler = BodyHandlers.ofString();
383
CompletableFuture<HttpResponse<String>> response = client.sendAsync(req, handler);
384
385
String body = response.join().body();
386
assertEquals(body, Stream.of(BODY.split("\\|")).collect(Collectors.joining()));
387
}
388
}
389
390
// @Test(dataProvider = "variants")
391
protected void testThrowingAsStringImpl(String uri,
392
boolean sameClient,
393
Thrower thrower,
394
Set<Where> whereValues)
395
throws Exception
396
{
397
String test = format("testThrowingAsString(%s, %b, %s, %s)",
398
uri, sameClient, thrower, whereValues);
399
List<byte[]> bytes = Stream.of(BODY.split("|"))
400
.map(s -> s.getBytes(UTF_8))
401
.collect(Collectors.toList());
402
testThrowing(test, uri, sameClient, () -> BodyPublishers.ofByteArrays(bytes),
403
this::shouldNotThrowInCancel, thrower,false, whereValues);
404
}
405
406
private <T,U> void testThrowing(String name, String uri, boolean sameClient,
407
Supplier<BodyPublisher> publishers,
408
Finisher finisher, Thrower thrower,
409
boolean async, Set<Where> whereValues)
410
throws Exception
411
{
412
checkSkip();
413
out.printf("%n%s%s%n", now(), name);
414
try {
415
testThrowing(uri, sameClient, publishers, finisher, thrower, async, whereValues);
416
} catch (Error | Exception x) {
417
FAILURES.putIfAbsent(name, x);
418
throw x;
419
}
420
}
421
422
private void testThrowing(String uri, boolean sameClient,
423
Supplier<BodyPublisher> publishers,
424
Finisher finisher, Thrower thrower,
425
boolean async, Set<Where> whereValues)
426
throws Exception
427
{
428
HttpClient client = null;
429
for (Where where : whereValues) {
430
//if (where == Where.ON_SUBSCRIBE) continue;
431
//if (where == Where.ON_ERROR) continue;
432
if (!sameClient || client == null)
433
client = newHttpClient(sameClient);
434
435
ThrowingBodyPublisher bodyPublisher =
436
new ThrowingBodyPublisher(where.select(thrower), publishers.get());
437
HttpRequest req = HttpRequest.
438
newBuilder(URI.create(uri))
439
.header("X-expect-exception", "true")
440
.POST(bodyPublisher)
441
.build();
442
BodyHandler<String> handler = BodyHandlers.ofString();
443
System.out.println("try throwing in " + where);
444
HttpResponse<String> response = null;
445
if (async) {
446
try {
447
response = client.sendAsync(req, handler).join();
448
} catch (Error | Exception x) {
449
Throwable cause = findCause(where, x, thrower);
450
if (cause == null) throw causeNotFound(where, x);
451
System.out.println(now() + "Got expected exception: " + cause);
452
}
453
} else {
454
try {
455
response = client.send(req, handler);
456
} catch (Error | Exception t) {
457
// synchronous send will rethrow exceptions
458
Throwable throwable = t.getCause();
459
assert throwable != null;
460
461
if (thrower.test(where, throwable)) {
462
System.out.println(now() + "Got expected exception: " + throwable);
463
} else throw causeNotFound(where, t);
464
}
465
}
466
if (response != null) {
467
finisher.finish(where, response, thrower);
468
}
469
}
470
}
471
472
// can be used to reduce the surface of the test when diagnosing
473
// some failure
474
Set<Where> whereValues() {
475
//return EnumSet.of(Where.BEFORE_CANCEL, Where.AFTER_CANCEL);
476
return EnumSet.allOf(Where.class);
477
}
478
479
interface Thrower extends Consumer<Where>, BiPredicate<Where,Throwable> {
480
481
}
482
483
interface Finisher<T,U> {
484
U finish(Where w, HttpResponse<T> resp, Thrower thrower) throws IOException;
485
}
486
487
final <T,U> U shouldNotThrowInCancel(Where w, HttpResponse<T> resp, Thrower thrower) {
488
switch (w) {
489
case BEFORE_CANCEL: return null;
490
case AFTER_CANCEL: return null;
491
default: break;
492
}
493
return shouldHaveThrown(w, resp, thrower);
494
}
495
496
497
final <T,U> U shouldHaveThrown(Where w, HttpResponse<T> resp, Thrower thrower) {
498
String msg = "Expected exception not thrown in " + w
499
+ "\n\tReceived: " + resp
500
+ "\n\tWith body: " + resp.body();
501
System.out.println(msg);
502
throw new RuntimeException(msg);
503
}
504
505
506
private static Throwable findCause(Where w,
507
Throwable x,
508
BiPredicate<Where, Throwable> filter) {
509
while (x != null && !filter.test(w,x)) x = x.getCause();
510
return x;
511
}
512
513
static AssertionError causeNotFound(Where w, Throwable t) {
514
return new AssertionError("Expected exception not found in " + w, t);
515
}
516
517
static boolean isConnectionClosedLocally(Throwable t) {
518
if (t instanceof CompletionException) t = t.getCause();
519
if (t instanceof ExecutionException) t = t.getCause();
520
if (t instanceof IOException) {
521
String msg = t.getMessage();
522
return msg == null ? false
523
: msg.contains("connection closed locally");
524
}
525
return false;
526
}
527
528
static final class UncheckedCustomExceptionThrower implements Thrower {
529
@Override
530
public void accept(Where where) {
531
out.println(now() + "Throwing in " + where);
532
throw new UncheckedCustomException(where.name());
533
}
534
535
@Override
536
public boolean test(Where w, Throwable throwable) {
537
switch (w) {
538
case AFTER_REQUEST:
539
case BEFORE_NEXT_REQUEST:
540
case AFTER_NEXT_REQUEST:
541
if (isConnectionClosedLocally(throwable)) return true;
542
break;
543
default:
544
break;
545
}
546
return UncheckedCustomException.class.isInstance(throwable);
547
}
548
549
@Override
550
public String toString() {
551
return "UncheckedCustomExceptionThrower";
552
}
553
}
554
555
static final class UncheckedIOExceptionThrower implements Thrower {
556
@Override
557
public void accept(Where where) {
558
out.println(now() + "Throwing in " + where);
559
throw new UncheckedIOException(new CustomIOException(where.name()));
560
}
561
562
@Override
563
public boolean test(Where w, Throwable throwable) {
564
switch (w) {
565
case AFTER_REQUEST:
566
case BEFORE_NEXT_REQUEST:
567
case AFTER_NEXT_REQUEST:
568
if (isConnectionClosedLocally(throwable)) return true;
569
break;
570
default:
571
break;
572
}
573
return UncheckedIOException.class.isInstance(throwable)
574
&& CustomIOException.class.isInstance(throwable.getCause());
575
}
576
577
@Override
578
public String toString() {
579
return "UncheckedIOExceptionThrower";
580
}
581
}
582
583
static final class UncheckedCustomException extends RuntimeException {
584
UncheckedCustomException(String message) {
585
super(message);
586
}
587
UncheckedCustomException(String message, Throwable cause) {
588
super(message, cause);
589
}
590
}
591
592
static final class CustomIOException extends IOException {
593
CustomIOException(String message) {
594
super(message);
595
}
596
CustomIOException(String message, Throwable cause) {
597
super(message, cause);
598
}
599
}
600
601
602
static final class ThrowingBodyPublisher implements BodyPublisher {
603
private final BodyPublisher publisher;
604
private final CompletableFuture<Void> subscribedCF = new CompletableFuture<>();
605
final Consumer<Where> throwing;
606
ThrowingBodyPublisher(Consumer<Where> throwing, BodyPublisher publisher) {
607
this.throwing = throwing;
608
this.publisher = publisher;
609
}
610
611
@Override
612
public long contentLength() {
613
return publisher.contentLength();
614
}
615
616
@Override
617
public void subscribe(Flow.Subscriber<? super ByteBuffer> subscriber) {
618
try {
619
throwing.accept(Where.BEFORE_SUBSCRIBE);
620
publisher.subscribe(new SubscriberWrapper(subscriber));
621
subscribedCF.complete(null);
622
throwing.accept(Where.AFTER_SUBSCRIBE);
623
} catch (Throwable t) {
624
subscribedCF.completeExceptionally(t);
625
throw t;
626
}
627
}
628
629
CompletableFuture<Void> subscribedCF() {
630
return subscribedCF;
631
}
632
633
class SubscriptionWrapper implements Flow.Subscription {
634
final Flow.Subscription subscription;
635
final AtomicLong requestCount = new AtomicLong();
636
SubscriptionWrapper(Flow.Subscription subscription) {
637
this.subscription = subscription;
638
}
639
@Override
640
public void request(long n) {
641
long count = requestCount.incrementAndGet();
642
System.out.printf("%s request-%d(%d)%n", now(), count, n);
643
if (count > 1) throwing.accept(Where.BEFORE_NEXT_REQUEST);
644
throwing.accept(Where.BEFORE_REQUEST);
645
subscription.request(n);
646
throwing.accept(Where.AFTER_REQUEST);
647
if (count > 1) throwing.accept(Where.AFTER_NEXT_REQUEST);
648
}
649
650
@Override
651
public void cancel() {
652
throwing.accept(Where.BEFORE_CANCEL);
653
subscription.cancel();
654
throwing.accept(Where.AFTER_CANCEL);
655
}
656
}
657
658
class SubscriberWrapper implements Flow.Subscriber<ByteBuffer> {
659
final Flow.Subscriber<? super ByteBuffer> subscriber;
660
SubscriberWrapper(Flow.Subscriber<? super ByteBuffer> subscriber) {
661
this.subscriber = subscriber;
662
}
663
@Override
664
public void onSubscribe(Flow.Subscription subscription) {
665
subscriber.onSubscribe(new SubscriptionWrapper(subscription));
666
}
667
@Override
668
public void onNext(ByteBuffer item) {
669
subscriber.onNext(item);
670
}
671
@Override
672
public void onComplete() {
673
subscriber.onComplete();
674
}
675
676
@Override
677
public void onError(Throwable throwable) {
678
subscriber.onError(throwable);
679
}
680
}
681
}
682
683
684
@BeforeTest
685
public void setup() throws Exception {
686
sslContext = new SimpleSSLContext().get();
687
if (sslContext == null)
688
throw new AssertionError("Unexpected null sslContext");
689
690
// HTTP/1.1
691
HttpTestHandler h1_fixedLengthHandler = new HTTP_FixedLengthHandler();
692
HttpTestHandler h1_chunkHandler = new HTTP_ChunkedHandler();
693
InetSocketAddress sa = new InetSocketAddress(InetAddress.getLoopbackAddress(), 0);
694
httpTestServer = HttpTestServer.of(HttpServer.create(sa, 0));
695
httpTestServer.addHandler(h1_fixedLengthHandler, "/http1/fixed");
696
httpTestServer.addHandler(h1_chunkHandler, "/http1/chunk");
697
httpURI_fixed = "http://" + httpTestServer.serverAuthority() + "/http1/fixed/x";
698
httpURI_chunk = "http://" + httpTestServer.serverAuthority() + "/http1/chunk/x";
699
700
HttpsServer httpsServer = HttpsServer.create(sa, 0);
701
httpsServer.setHttpsConfigurator(new HttpsConfigurator(sslContext));
702
httpsTestServer = HttpTestServer.of(httpsServer);
703
httpsTestServer.addHandler(h1_fixedLengthHandler, "/https1/fixed");
704
httpsTestServer.addHandler(h1_chunkHandler, "/https1/chunk");
705
httpsURI_fixed = "https://" + httpsTestServer.serverAuthority() + "/https1/fixed/x";
706
httpsURI_chunk = "https://" + httpsTestServer.serverAuthority() + "/https1/chunk/x";
707
708
// HTTP/2
709
HttpTestHandler h2_fixedLengthHandler = new HTTP_FixedLengthHandler();
710
HttpTestHandler h2_chunkedHandler = new HTTP_ChunkedHandler();
711
712
http2TestServer = HttpTestServer.of(new Http2TestServer("localhost", false, 0));
713
http2TestServer.addHandler(h2_fixedLengthHandler, "/http2/fixed");
714
http2TestServer.addHandler(h2_chunkedHandler, "/http2/chunk");
715
http2URI_fixed = "http://" + http2TestServer.serverAuthority() + "/http2/fixed/x";
716
http2URI_chunk = "http://" + http2TestServer.serverAuthority() + "/http2/chunk/x";
717
718
https2TestServer = HttpTestServer.of(new Http2TestServer("localhost", true, sslContext));
719
https2TestServer.addHandler(h2_fixedLengthHandler, "/https2/fixed");
720
https2TestServer.addHandler(h2_chunkedHandler, "/https2/chunk");
721
https2URI_fixed = "https://" + https2TestServer.serverAuthority() + "/https2/fixed/x";
722
https2URI_chunk = "https://" + https2TestServer.serverAuthority() + "/https2/chunk/x";
723
724
serverCount.addAndGet(4);
725
httpTestServer.start();
726
httpsTestServer.start();
727
http2TestServer.start();
728
https2TestServer.start();
729
}
730
731
@AfterTest
732
public void teardown() throws Exception {
733
String sharedClientName =
734
sharedClient == null ? null : sharedClient.toString();
735
sharedClient = null;
736
Thread.sleep(100);
737
AssertionError fail = TRACKER.check(500);
738
try {
739
httpTestServer.stop();
740
httpsTestServer.stop();
741
http2TestServer.stop();
742
https2TestServer.stop();
743
} finally {
744
if (fail != null) {
745
if (sharedClientName != null) {
746
System.err.println("Shared client name is: " + sharedClientName);
747
}
748
throw fail;
749
}
750
}
751
}
752
753
static class HTTP_FixedLengthHandler implements HttpTestHandler {
754
@Override
755
public void handle(HttpTestExchange t) throws IOException {
756
out.println("HTTP_FixedLengthHandler received request to " + t.getRequestURI());
757
byte[] resp;
758
try (InputStream is = t.getRequestBody()) {
759
resp = is.readAllBytes();
760
}
761
t.sendResponseHeaders(200, resp.length); //fixed content length
762
try (OutputStream os = t.getResponseBody()) {
763
os.write(resp);
764
}
765
}
766
}
767
768
static class HTTP_ChunkedHandler implements HttpTestHandler {
769
@Override
770
public void handle(HttpTestExchange t) throws IOException {
771
out.println("HTTP_ChunkedHandler received request to " + t.getRequestURI());
772
byte[] resp;
773
try (InputStream is = t.getRequestBody()) {
774
resp = is.readAllBytes();
775
}
776
t.sendResponseHeaders(200, -1); // chunked/variable
777
try (OutputStream os = t.getResponseBody()) {
778
os.write(resp);
779
}
780
}
781
}
782
783
}
784
785