Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/jdk17u
Path: blob/master/test/jdk/java/net/httpclient/CancelRequestTest.java
66644 views
1
/*
2
* Copyright (c) 2020, 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
* @test
26
* @bug 8245462 8229822
27
* @summary Tests cancelling the request.
28
* @library /test/lib http2/server
29
* @key randomness
30
* @build jdk.test.lib.net.SimpleSSLContext HttpServerAdapters
31
* ReferenceTracker CancelRequestTest
32
* @modules java.base/sun.net.www.http
33
* java.net.http/jdk.internal.net.http.common
34
* java.net.http/jdk.internal.net.http.frame
35
* java.net.http/jdk.internal.net.http.hpack
36
* @run testng/othervm -Djdk.internal.httpclient.debug=true
37
* -Djdk.httpclient.enableAllMethodRetry=true
38
* CancelRequestTest
39
*/
40
// * -Dseed=3582896013206826205L
41
// * -Dseed=5784221742235559231L
42
import com.sun.net.httpserver.HttpServer;
43
import com.sun.net.httpserver.HttpsConfigurator;
44
import com.sun.net.httpserver.HttpsServer;
45
import jdk.test.lib.RandomFactory;
46
import jdk.test.lib.net.SimpleSSLContext;
47
import org.testng.ITestContext;
48
import org.testng.ITestResult;
49
import org.testng.SkipException;
50
import org.testng.annotations.AfterClass;
51
import org.testng.annotations.AfterTest;
52
import org.testng.annotations.BeforeMethod;
53
import org.testng.annotations.BeforeTest;
54
import org.testng.annotations.DataProvider;
55
import org.testng.annotations.Test;
56
57
import javax.net.ssl.SSLContext;
58
import java.io.IOException;
59
import java.io.InputStream;
60
import java.io.OutputStream;
61
import java.net.InetAddress;
62
import java.net.InetSocketAddress;
63
import java.net.URI;
64
import java.net.http.HttpClient;
65
import java.net.http.HttpConnectTimeoutException;
66
import java.net.http.HttpRequest;
67
import java.net.http.HttpResponse;
68
import java.net.http.HttpResponse.BodyHandler;
69
import java.net.http.HttpResponse.BodyHandlers;
70
import java.util.Arrays;
71
import java.util.Iterator;
72
import java.util.List;
73
import java.util.Random;
74
import java.util.concurrent.CancellationException;
75
import java.util.concurrent.CompletableFuture;
76
import java.util.concurrent.ConcurrentHashMap;
77
import java.util.concurrent.ConcurrentMap;
78
import java.util.concurrent.CountDownLatch;
79
import java.util.concurrent.ExecutionException;
80
import java.util.concurrent.Executor;
81
import java.util.concurrent.Executors;
82
import java.util.concurrent.atomic.AtomicLong;
83
import java.util.concurrent.atomic.AtomicReference;
84
import java.util.stream.Collectors;
85
import java.util.stream.Stream;
86
87
import static java.lang.System.arraycopy;
88
import static java.lang.System.out;
89
import static java.nio.charset.StandardCharsets.UTF_8;
90
import static org.testng.Assert.assertEquals;
91
import static org.testng.Assert.assertTrue;
92
93
public class CancelRequestTest implements HttpServerAdapters {
94
95
private static final Random random = RandomFactory.getRandom();
96
97
SSLContext sslContext;
98
HttpTestServer httpTestServer; // HTTP/1.1 [ 4 servers ]
99
HttpTestServer httpsTestServer; // HTTPS/1.1
100
HttpTestServer http2TestServer; // HTTP/2 ( h2c )
101
HttpTestServer https2TestServer; // HTTP/2 ( h2 )
102
String httpURI;
103
String httpsURI;
104
String http2URI;
105
String https2URI;
106
107
static final long SERVER_LATENCY = 75;
108
static final int MAX_CLIENT_DELAY = 75;
109
static final int ITERATION_COUNT = 3;
110
// a shared executor helps reduce the amount of threads created by the test
111
static final Executor executor = new TestExecutor(Executors.newCachedThreadPool());
112
static final ConcurrentMap<String, Throwable> FAILURES = new ConcurrentHashMap<>();
113
static volatile boolean tasksFailed;
114
static final AtomicLong serverCount = new AtomicLong();
115
static final AtomicLong clientCount = new AtomicLong();
116
static final long start = System.nanoTime();
117
public static String now() {
118
long now = System.nanoTime() - start;
119
long secs = now / 1000_000_000;
120
long mill = (now % 1000_000_000) / 1000_000;
121
long nan = now % 1000_000;
122
return String.format("[%d s, %d ms, %d ns] ", secs, mill, nan);
123
}
124
125
final ReferenceTracker TRACKER = ReferenceTracker.INSTANCE;
126
private volatile HttpClient sharedClient;
127
128
static class TestExecutor implements Executor {
129
final AtomicLong tasks = new AtomicLong();
130
Executor executor;
131
TestExecutor(Executor executor) {
132
this.executor = executor;
133
}
134
135
@Override
136
public void execute(Runnable command) {
137
long id = tasks.incrementAndGet();
138
executor.execute(() -> {
139
try {
140
command.run();
141
} catch (Throwable t) {
142
tasksFailed = true;
143
System.out.printf(now() + "Task %s failed: %s%n", id, t);
144
System.err.printf(now() + "Task %s failed: %s%n", id, t);
145
FAILURES.putIfAbsent("Task " + id, t);
146
throw t;
147
}
148
});
149
}
150
}
151
152
protected boolean stopAfterFirstFailure() {
153
return Boolean.getBoolean("jdk.internal.httpclient.debug");
154
}
155
156
final AtomicReference<SkipException> skiptests = new AtomicReference<>();
157
void checkSkip() {
158
var skip = skiptests.get();
159
if (skip != null) throw skip;
160
}
161
static String name(ITestResult result) {
162
var params = result.getParameters();
163
return result.getName()
164
+ (params == null ? "()" : Arrays.toString(result.getParameters()));
165
}
166
167
@BeforeMethod
168
void beforeMethod(ITestContext context) {
169
if (stopAfterFirstFailure() && context.getFailedTests().size() > 0) {
170
if (skiptests.get() == null) {
171
SkipException skip = new SkipException("some tests failed");
172
skip.setStackTrace(new StackTraceElement[0]);
173
skiptests.compareAndSet(null, skip);
174
}
175
}
176
}
177
178
@AfterClass
179
static final void printFailedTests(ITestContext context) {
180
out.println("\n=========================");
181
var failed = context.getFailedTests().getAllResults().stream()
182
.collect(Collectors.toMap(r -> name(r), ITestResult::getThrowable));
183
FAILURES.putAll(failed);
184
try {
185
out.printf("%n%sCreated %d servers and %d clients%n",
186
now(), serverCount.get(), clientCount.get());
187
if (FAILURES.isEmpty()) return;
188
out.println("Failed tests: ");
189
FAILURES.entrySet().forEach((e) -> {
190
out.printf("\t%s: %s%n", e.getKey(), e.getValue());
191
e.getValue().printStackTrace(out);
192
});
193
if (tasksFailed) {
194
System.out.println("WARNING: Some tasks failed");
195
}
196
} finally {
197
out.println("\n=========================\n");
198
}
199
}
200
201
private String[] uris() {
202
return new String[] {
203
httpURI,
204
httpsURI,
205
http2URI,
206
https2URI,
207
};
208
}
209
210
@DataProvider(name = "asyncurls")
211
public Object[][] asyncurls() {
212
String[] uris = uris();
213
Object[][] result = new Object[uris.length * 2 * 3][];
214
//Object[][] result = new Object[uris.length][];
215
int i = 0;
216
for (boolean mayInterrupt : List.of(true, false, true)) {
217
for (boolean sameClient : List.of(false, true)) {
218
//if (!sameClient) continue;
219
for (String uri : uris()) {
220
String path = sameClient ? "same" : "new";
221
path = path + (mayInterrupt ? "/interrupt" : "/nointerrupt");
222
result[i++] = new Object[]{uri + path, sameClient, mayInterrupt};
223
}
224
}
225
}
226
assert i == uris.length * 2 * 3;
227
// assert i == uris.length ;
228
return result;
229
}
230
231
@DataProvider(name = "urls")
232
public Object[][] alltests() {
233
String[] uris = uris();
234
Object[][] result = new Object[uris.length * 2][];
235
//Object[][] result = new Object[uris.length][];
236
int i = 0;
237
for (boolean sameClient : List.of(false, true)) {
238
//if (!sameClient) continue;
239
for (String uri : uris()) {
240
String path = sameClient ? "same" : "new";
241
path = path + "/interruptThread";
242
result[i++] = new Object[]{uri + path, sameClient};
243
}
244
}
245
assert i == uris.length * 2;
246
// assert i == uris.length ;
247
return result;
248
}
249
250
private HttpClient makeNewClient() {
251
clientCount.incrementAndGet();
252
return TRACKER.track(HttpClient.newBuilder()
253
.proxy(HttpClient.Builder.NO_PROXY)
254
.executor(executor)
255
.sslContext(sslContext)
256
.build());
257
}
258
259
HttpClient newHttpClient(boolean share) {
260
if (!share) return makeNewClient();
261
HttpClient shared = sharedClient;
262
if (shared != null) return shared;
263
synchronized (this) {
264
shared = sharedClient;
265
if (shared == null) {
266
shared = sharedClient = makeNewClient();
267
}
268
return shared;
269
}
270
}
271
272
final static String BODY = "Some string | that ? can | be split ? several | ways.";
273
274
// should accept SSLHandshakeException because of the connectionAborter
275
// with http/2 and should accept Stream 5 cancelled.
276
// => also examine in what measure we should always
277
// rewrap in "Request Cancelled" when the multi exchange was aborted...
278
private static boolean isCancelled(Throwable t) {
279
while (t instanceof ExecutionException) t = t.getCause();
280
if (t instanceof CancellationException) return true;
281
if (t instanceof IOException) return String.valueOf(t).contains("Request cancelled");
282
out.println("Not a cancellation exception: " + t);
283
t.printStackTrace(out);
284
return false;
285
}
286
287
private static void delay() {
288
int delay = random.nextInt(MAX_CLIENT_DELAY);
289
try {
290
System.out.println("client delay: " + delay);
291
Thread.sleep(delay);
292
} catch (InterruptedException x) {
293
out.println("Unexpected exception: " + x);
294
}
295
}
296
297
@Test(dataProvider = "asyncurls")
298
public void testGetSendAsync(String uri, boolean sameClient, boolean mayInterruptIfRunning)
299
throws Exception {
300
checkSkip();
301
HttpClient client = null;
302
uri = uri + "/get";
303
out.printf("%n%s testGetSendAsync(%s, %b, %b)%n", now(), uri, sameClient, mayInterruptIfRunning);
304
for (int i=0; i< ITERATION_COUNT; i++) {
305
if (!sameClient || client == null)
306
client = newHttpClient(sameClient);
307
308
HttpRequest req = HttpRequest.newBuilder(URI.create(uri))
309
.GET()
310
.build();
311
BodyHandler<String> handler = BodyHandlers.ofString();
312
CountDownLatch latch = new CountDownLatch(1);
313
CompletableFuture<HttpResponse<String>> response = client.sendAsync(req, handler);
314
var cf1 = response.whenComplete((r,t) -> System.out.println(t));
315
CompletableFuture<HttpResponse<String>> cf2 = cf1.whenComplete((r,t) -> latch.countDown());
316
out.println("response: " + response);
317
out.println("cf1: " + cf1);
318
out.println("cf2: " + cf2);
319
delay();
320
cf1.cancel(mayInterruptIfRunning);
321
out.println("response after cancel: " + response);
322
out.println("cf1 after cancel: " + cf1);
323
out.println("cf2 after cancel: " + cf2);
324
try {
325
String body = cf2.get().body();
326
assertEquals(body, Stream.of(BODY.split("\\|")).collect(Collectors.joining()));
327
throw new AssertionError("Expected CancellationException not received");
328
} catch (ExecutionException x) {
329
out.println("Got expected exception: " + x);
330
assertTrue(isCancelled(x));
331
}
332
333
// Cancelling the request may cause an IOException instead...
334
boolean hasCancellationException = false;
335
try {
336
cf1.get();
337
} catch (CancellationException | ExecutionException x) {
338
out.println("Got expected exception: " + x);
339
assertTrue(isCancelled(x));
340
hasCancellationException = x instanceof CancellationException;
341
}
342
343
// because it's cf1 that was cancelled then response might not have
344
// completed yet - so wait for it here...
345
try {
346
String body = response.get().body();
347
assertEquals(body, Stream.of(BODY.split("\\|")).collect(Collectors.joining()));
348
if (mayInterruptIfRunning) {
349
// well actually - this could happen... In which case we'll need to
350
// increase the latency in the server handler...
351
throw new AssertionError("Expected Exception not received");
352
}
353
} catch (ExecutionException x) {
354
assertEquals(response.isDone(), true);
355
Throwable wrapped = x.getCause();
356
assertTrue(CancellationException.class.isAssignableFrom(wrapped.getClass()));
357
Throwable cause = wrapped.getCause();
358
out.println("CancellationException cause: " + x);
359
assertTrue(IOException.class.isAssignableFrom(cause.getClass()));
360
if (cause instanceof HttpConnectTimeoutException) {
361
cause.printStackTrace(out);
362
throw new RuntimeException("Unexpected timeout exception", cause);
363
}
364
if (mayInterruptIfRunning) {
365
out.println("Got expected exception: " + wrapped);
366
out.println("\tcause: " + cause);
367
} else {
368
out.println("Unexpected exception: " + wrapped);
369
wrapped.printStackTrace(out);
370
throw x;
371
}
372
}
373
374
assertEquals(response.isDone(), true);
375
assertEquals(response.isCancelled(), false);
376
assertEquals(cf1.isCancelled(), hasCancellationException);
377
assertEquals(cf2.isDone(), true);
378
assertEquals(cf2.isCancelled(), false);
379
assertEquals(latch.getCount(), 0);
380
}
381
}
382
383
@Test(dataProvider = "asyncurls")
384
public void testPostSendAsync(String uri, boolean sameClient, boolean mayInterruptIfRunning)
385
throws Exception {
386
checkSkip();
387
uri = uri + "/post";
388
HttpClient client = null;
389
out.printf("%n%s testPostSendAsync(%s, %b, %b)%n", now(), uri, sameClient, mayInterruptIfRunning);
390
for (int i=0; i< ITERATION_COUNT; i++) {
391
if (!sameClient || client == null)
392
client = newHttpClient(sameClient);
393
394
CompletableFuture<CompletableFuture<?>> cancelFuture = new CompletableFuture<>();
395
396
Iterable<byte[]> iterable = new Iterable<byte[]>() {
397
@Override
398
public Iterator<byte[]> iterator() {
399
// this is dangerous
400
out.println("waiting for completion on: " + cancelFuture);
401
boolean async = random.nextBoolean();
402
Runnable cancel = () -> {
403
out.println("Cancelling from " + Thread.currentThread());
404
var cf1 = cancelFuture.join();
405
cf1.cancel(mayInterruptIfRunning);
406
out.println("cancelled " + cf1);
407
};
408
if (async) executor.execute(cancel);
409
else cancel.run();
410
return List.of(BODY.getBytes(UTF_8)).iterator();
411
}
412
};
413
414
HttpRequest req = HttpRequest.newBuilder(URI.create(uri))
415
.POST(HttpRequest.BodyPublishers.ofByteArrays(iterable))
416
.build();
417
BodyHandler<String> handler = BodyHandlers.ofString();
418
CountDownLatch latch = new CountDownLatch(1);
419
CompletableFuture<HttpResponse<String>> response = client.sendAsync(req, handler);
420
var cf1 = response.whenComplete((r,t) -> System.out.println(t));
421
CompletableFuture<HttpResponse<String>> cf2 = cf1.whenComplete((r,t) -> latch.countDown());
422
out.println("response: " + response);
423
out.println("cf1: " + cf1);
424
out.println("cf2: " + cf2);
425
cancelFuture.complete(cf1);
426
out.println("response after cancel: " + response);
427
out.println("cf1 after cancel: " + cf1);
428
out.println("cf2 after cancel: " + cf2);
429
try {
430
String body = cf2.get().body();
431
assertEquals(body, Stream.of(BODY.split("\\|")).collect(Collectors.joining()));
432
throw new AssertionError("Expected CancellationException not received");
433
} catch (ExecutionException x) {
434
out.println("Got expected exception: " + x);
435
assertTrue(isCancelled(x));
436
}
437
438
// Cancelling the request may cause an IOException instead...
439
boolean hasCancellationException = false;
440
try {
441
cf1.get();
442
} catch (CancellationException | ExecutionException x) {
443
out.println("Got expected exception: " + x);
444
assertTrue(isCancelled(x));
445
hasCancellationException = x instanceof CancellationException;
446
}
447
448
// because it's cf1 that was cancelled then response might not have
449
// completed yet - so wait for it here...
450
try {
451
String body = response.get().body();
452
assertEquals(body, Stream.of(BODY.split("\\|")).collect(Collectors.joining()));
453
if (mayInterruptIfRunning) {
454
// well actually - this could happen... In which case we'll need to
455
// increase the latency in the server handler...
456
throw new AssertionError("Expected Exception not received");
457
}
458
} catch (ExecutionException x) {
459
assertEquals(response.isDone(), true);
460
Throwable wrapped = x.getCause();
461
assertTrue(CancellationException.class.isAssignableFrom(wrapped.getClass()));
462
Throwable cause = wrapped.getCause();
463
assertTrue(IOException.class.isAssignableFrom(cause.getClass()));
464
if (cause instanceof HttpConnectTimeoutException) {
465
cause.printStackTrace(out);
466
throw new RuntimeException("Unexpected timeout exception", cause);
467
}
468
if (mayInterruptIfRunning) {
469
out.println("Got expected exception: " + wrapped);
470
out.println("\tcause: " + cause);
471
} else {
472
out.println("Unexpected exception: " + wrapped);
473
wrapped.printStackTrace(out);
474
throw x;
475
}
476
}
477
478
assertEquals(response.isDone(), true);
479
assertEquals(response.isCancelled(), false);
480
assertEquals(cf1.isCancelled(), hasCancellationException);
481
assertEquals(cf2.isDone(), true);
482
assertEquals(cf2.isCancelled(), false);
483
assertEquals(latch.getCount(), 0);
484
}
485
}
486
487
@Test(dataProvider = "urls")
488
public void testPostInterrupt(String uri, boolean sameClient)
489
throws Exception {
490
checkSkip();
491
HttpClient client = null;
492
out.printf("%n%s testPostInterrupt(%s, %b)%n", now(), uri, sameClient);
493
for (int i=0; i< ITERATION_COUNT; i++) {
494
if (!sameClient || client == null)
495
client = newHttpClient(sameClient);
496
Thread main = Thread.currentThread();
497
CompletableFuture<Thread> interruptingThread = new CompletableFuture<>();
498
Runnable interrupt = () -> {
499
Thread current = Thread.currentThread();
500
out.printf("%s Interrupting main from: %s (%s)", now(), current, uri);
501
interruptingThread.complete(current);
502
main.interrupt();
503
};
504
Iterable<byte[]> iterable = () -> {
505
var async = random.nextBoolean();
506
if (async) executor.execute(interrupt);
507
else interrupt.run();
508
return List.of(BODY.getBytes(UTF_8)).iterator();
509
};
510
511
HttpRequest req = HttpRequest.newBuilder(URI.create(uri))
512
.POST(HttpRequest.BodyPublishers.ofByteArrays(iterable))
513
.build();
514
String body = null;
515
Exception failed = null;
516
try {
517
body = client.send(req, BodyHandlers.ofString()).body();
518
} catch (Exception x) {
519
failed = x;
520
}
521
522
if (failed instanceof InterruptedException) {
523
out.println("Got expected exception: " + failed);
524
} else if (failed instanceof IOException) {
525
// that could be OK if the main thread was interrupted
526
// from the main thread: the interrupt status could have
527
// been caught by writing to the socket from the main
528
// thread.
529
if (interruptingThread.get() == main) {
530
out.println("Accepting IOException: " + failed);
531
failed.printStackTrace(out);
532
} else {
533
throw failed;
534
}
535
} else if (failed != null) {
536
assertEquals(body, Stream.of(BODY.split("\\|")).collect(Collectors.joining()));
537
throw failed;
538
}
539
}
540
}
541
542
543
544
@BeforeTest
545
public void setup() throws Exception {
546
sslContext = new SimpleSSLContext().get();
547
if (sslContext == null)
548
throw new AssertionError("Unexpected null sslContext");
549
550
// HTTP/1.1
551
HttpTestHandler h1_chunkHandler = new HTTPSlowHandler();
552
InetSocketAddress sa = new InetSocketAddress(InetAddress.getLoopbackAddress(), 0);
553
httpTestServer = HttpTestServer.of(HttpServer.create(sa, 0));
554
httpTestServer.addHandler(h1_chunkHandler, "/http1/x/");
555
httpURI = "http://" + httpTestServer.serverAuthority() + "/http1/x/";
556
557
HttpsServer httpsServer = HttpsServer.create(sa, 0);
558
httpsServer.setHttpsConfigurator(new HttpsConfigurator(sslContext));
559
httpsTestServer = HttpTestServer.of(httpsServer);
560
httpsTestServer.addHandler(h1_chunkHandler, "/https1/x/");
561
httpsURI = "https://" + httpsTestServer.serverAuthority() + "/https1/x/";
562
563
// HTTP/2
564
HttpTestHandler h2_chunkedHandler = new HTTPSlowHandler();
565
566
http2TestServer = HttpTestServer.of(new Http2TestServer("localhost", false, 0));
567
http2TestServer.addHandler(h2_chunkedHandler, "/http2/x/");
568
http2URI = "http://" + http2TestServer.serverAuthority() + "/http2/x/";
569
570
https2TestServer = HttpTestServer.of(new Http2TestServer("localhost", true, sslContext));
571
https2TestServer.addHandler(h2_chunkedHandler, "/https2/x/");
572
https2URI = "https://" + https2TestServer.serverAuthority() + "/https2/x/";
573
574
serverCount.addAndGet(4);
575
httpTestServer.start();
576
httpsTestServer.start();
577
http2TestServer.start();
578
https2TestServer.start();
579
}
580
581
@AfterTest
582
public void teardown() throws Exception {
583
String sharedClientName =
584
sharedClient == null ? null : sharedClient.toString();
585
sharedClient = null;
586
Thread.sleep(100);
587
AssertionError fail = TRACKER.check(500);
588
try {
589
httpTestServer.stop();
590
httpsTestServer.stop();
591
http2TestServer.stop();
592
https2TestServer.stop();
593
} finally {
594
if (fail != null) {
595
if (sharedClientName != null) {
596
System.err.println("Shared client name is: " + sharedClientName);
597
}
598
throw fail;
599
}
600
}
601
}
602
603
private static boolean isThreadInterrupt(HttpTestExchange t) {
604
return t.getRequestURI().getPath().contains("/interruptThread");
605
}
606
607
/**
608
* A handler that slowly sends back a body to give time for the
609
* the request to get cancelled before the body is fully received.
610
*/
611
static class HTTPSlowHandler implements HttpTestHandler {
612
@Override
613
public void handle(HttpTestExchange t) throws IOException {
614
try {
615
out.println("HTTPSlowHandler received request to " + t.getRequestURI());
616
System.err.println("HTTPSlowHandler received request to " + t.getRequestURI());
617
618
boolean isThreadInterrupt = isThreadInterrupt(t);
619
byte[] req;
620
try (InputStream is = t.getRequestBody()) {
621
req = is.readAllBytes();
622
}
623
t.sendResponseHeaders(200, -1); // chunked/variable
624
try (OutputStream os = t.getResponseBody()) {
625
// lets split the response in several chunks...
626
String msg = (req != null && req.length != 0)
627
? new String(req, UTF_8)
628
: BODY;
629
String[] str = msg.split("\\|");
630
for (var s : str) {
631
req = s.getBytes(UTF_8);
632
os.write(req);
633
os.flush();
634
try {
635
Thread.sleep(SERVER_LATENCY);
636
} catch (InterruptedException x) {
637
// OK
638
}
639
out.printf("Server wrote %d bytes%n", req.length);
640
}
641
}
642
} catch (Throwable e) {
643
out.println("HTTPSlowHandler: unexpected exception: " + e);
644
e.printStackTrace();
645
throw e;
646
} finally {
647
out.printf("HTTPSlowHandler reply sent: %s%n", t.getRequestURI());
648
System.err.printf("HTTPSlowHandler reply sent: %s%n", t.getRequestURI());
649
}
650
}
651
}
652
653
}
654
655