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