File: WebSocketTest.java

package info (click to toggle)
openjdk-21 21.0.8%2B9-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 823,976 kB
  • sloc: java: 5,613,338; xml: 1,643,607; cpp: 1,296,296; ansic: 420,291; asm: 404,850; objc: 20,994; sh: 15,271; javascript: 11,245; python: 6,895; makefile: 2,362; perl: 357; awk: 351; sed: 172; jsp: 24; csh: 3
file content (853 lines) | stat: -rw-r--r-- 36,391 bytes parent folder | download | duplicates (11)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
/*
 * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

/*
 * @test
 * @bug 8217429
 * @build DummyWebSocketServer
 * @run testng/othervm
 *       WebSocketTest
 */

import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import java.io.IOException;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.http.HttpResponse;
import java.net.http.WebSocket;
import java.net.http.WebSocketHandshakeException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.HexFormat;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;

import static java.net.http.HttpClient.Builder.NO_PROXY;
import static java.net.http.HttpClient.newBuilder;
import static java.net.http.WebSocket.NORMAL_CLOSURE;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertThrows;
import static org.testng.Assert.fail;

public class WebSocketTest {

    private static final Class<IllegalArgumentException> IAE = IllegalArgumentException.class;
    private static final Class<IllegalStateException> ISE = IllegalStateException.class;
    private static final Class<IOException> IOE = IOException.class;

    /* shortcut */
    private static void assertFails(Class<? extends Throwable> clazz,
                                    CompletionStage<?> stage) {
        Support.assertCompletesExceptionally(clazz, stage);
    }

    @Test
    public void illegalArgument() throws IOException {
        try (var server = new DummyWebSocketServer()) {
            server.open();
            var webSocket = newBuilder().proxy(NO_PROXY).build()
                    .newWebSocketBuilder()
                    .buildAsync(server.getURI(), new WebSocket.Listener() { })
                    .join();
            try {
                assertFails(IAE, webSocket.sendPing(ByteBuffer.allocate(126)));
                assertFails(IAE, webSocket.sendPing(ByteBuffer.allocate(127)));
                assertFails(IAE, webSocket.sendPing(ByteBuffer.allocate(128)));
                assertFails(IAE, webSocket.sendPing(ByteBuffer.allocate(129)));
                assertFails(IAE, webSocket.sendPing(ByteBuffer.allocate(256)));

                assertFails(IAE, webSocket.sendPong(ByteBuffer.allocate(126)));
                assertFails(IAE, webSocket.sendPong(ByteBuffer.allocate(127)));
                assertFails(IAE, webSocket.sendPong(ByteBuffer.allocate(128)));
                assertFails(IAE, webSocket.sendPong(ByteBuffer.allocate(129)));
                assertFails(IAE, webSocket.sendPong(ByteBuffer.allocate(256)));

                assertFails(IOE, webSocket.sendText(Support.incompleteString(), true));
                assertFails(IOE, webSocket.sendText(Support.incompleteString(), false));
                assertFails(IOE, webSocket.sendText(Support.malformedString(), true));
                assertFails(IOE, webSocket.sendText(Support.malformedString(), false));

                assertFails(IAE, webSocket.sendClose(NORMAL_CLOSURE, Support.stringWithNBytes(124)));
                assertFails(IAE, webSocket.sendClose(NORMAL_CLOSURE, Support.stringWithNBytes(125)));
                assertFails(IAE, webSocket.sendClose(NORMAL_CLOSURE, Support.stringWithNBytes(128)));
                assertFails(IAE, webSocket.sendClose(NORMAL_CLOSURE, Support.stringWithNBytes(256)));
                assertFails(IAE, webSocket.sendClose(NORMAL_CLOSURE, Support.stringWithNBytes(257)));
                assertFails(IAE, webSocket.sendClose(NORMAL_CLOSURE, Support.stringWith2NBytes((123 / 2) + 1)));
                assertFails(IAE, webSocket.sendClose(NORMAL_CLOSURE, Support.malformedString()));
                assertFails(IAE, webSocket.sendClose(NORMAL_CLOSURE, Support.incompleteString()));

                assertFails(IAE, webSocket.sendClose(-2, "a reason"));
                assertFails(IAE, webSocket.sendClose(-1, "a reason"));
                assertFails(IAE, webSocket.sendClose(0, "a reason"));
                assertFails(IAE, webSocket.sendClose(1, "a reason"));
                assertFails(IAE, webSocket.sendClose(500, "a reason"));
                assertFails(IAE, webSocket.sendClose(998, "a reason"));
                assertFails(IAE, webSocket.sendClose(999, "a reason"));
                assertFails(IAE, webSocket.sendClose(1002, "a reason"));
                assertFails(IAE, webSocket.sendClose(1003, "a reason"));
                assertFails(IAE, webSocket.sendClose(1006, "a reason"));
                assertFails(IAE, webSocket.sendClose(1007, "a reason"));
                assertFails(IAE, webSocket.sendClose(1009, "a reason"));
                assertFails(IAE, webSocket.sendClose(1010, "a reason"));
                assertFails(IAE, webSocket.sendClose(1012, "a reason"));
                assertFails(IAE, webSocket.sendClose(1013, "a reason"));
                assertFails(IAE, webSocket.sendClose(1015, "a reason"));
                assertFails(IAE, webSocket.sendClose(5000, "a reason"));
                assertFails(IAE, webSocket.sendClose(32768, "a reason"));
                assertFails(IAE, webSocket.sendClose(65535, "a reason"));
                assertFails(IAE, webSocket.sendClose(65536, "a reason"));
                assertFails(IAE, webSocket.sendClose(Integer.MAX_VALUE, "a reason"));
                assertFails(IAE, webSocket.sendClose(Integer.MIN_VALUE, "a reason"));

                assertThrows(IAE, () -> webSocket.request(Integer.MIN_VALUE));
                assertThrows(IAE, () -> webSocket.request(Long.MIN_VALUE));
                assertThrows(IAE, () -> webSocket.request(-1));
                assertThrows(IAE, () -> webSocket.request(0));

            } finally {
                webSocket.abort();
            }
        }
    }

    @Test
    public void partialBinaryThenText() throws IOException {
        try (var server = new DummyWebSocketServer()) {
            server.open();
            var webSocket = newBuilder().proxy(NO_PROXY).build().newWebSocketBuilder()
                    .buildAsync(server.getURI(), new WebSocket.Listener() { })
                    .join();
            try {
                webSocket.sendBinary(ByteBuffer.allocate(16), false).join();
                assertFails(ISE, webSocket.sendText("text", false));
                assertFails(ISE, webSocket.sendText("text", true));
                // Pings & Pongs are fine
                webSocket.sendPing(ByteBuffer.allocate(125)).join();
                webSocket.sendPong(ByteBuffer.allocate(125)).join();
            } finally {
                webSocket.abort();
            }
        }
    }

    @Test
    public void partialTextThenBinary() throws IOException {
        try (var server = new DummyWebSocketServer()) {
            server.open();
            var webSocket = newBuilder().proxy(NO_PROXY).build().newWebSocketBuilder()
                    .buildAsync(server.getURI(), new WebSocket.Listener() { })
                    .join();
            try {
                webSocket.sendText("text", false).join();
                assertFails(ISE, webSocket.sendBinary(ByteBuffer.allocate(16), false));
                assertFails(ISE, webSocket.sendBinary(ByteBuffer.allocate(16), true));
                // Pings & Pongs are fine
                webSocket.sendPing(ByteBuffer.allocate(125)).join();
                webSocket.sendPong(ByteBuffer.allocate(125)).join();
            } finally {
                webSocket.abort();
            }
        }
    }

    @Test
    public void sendMethodsThrowIOE1() throws IOException {
        try (var server = new DummyWebSocketServer()) {
            server.open();
            var webSocket = newBuilder().proxy(NO_PROXY).build()
                    .newWebSocketBuilder()
                    .buildAsync(server.getURI(), new WebSocket.Listener() { })
                    .join();
            try {
                webSocket.sendClose(NORMAL_CLOSURE, "ok").join();

                assertFails(IOE, webSocket.sendClose(WebSocket.NORMAL_CLOSURE, "ok"));

                assertFails(IOE, webSocket.sendText("", true));
                assertFails(IOE, webSocket.sendText("", false));
                assertFails(IOE, webSocket.sendText("abc", true));
                assertFails(IOE, webSocket.sendText("abc", false));
                assertFails(IOE, webSocket.sendBinary(ByteBuffer.allocate(0), true));
                assertFails(IOE, webSocket.sendBinary(ByteBuffer.allocate(0), false));
                assertFails(IOE, webSocket.sendBinary(ByteBuffer.allocate(1), true));
                assertFails(IOE, webSocket.sendBinary(ByteBuffer.allocate(1), false));

                assertFails(IOE, webSocket.sendPing(ByteBuffer.allocate(125)));
                assertFails(IOE, webSocket.sendPing(ByteBuffer.allocate(124)));
                assertFails(IOE, webSocket.sendPing(ByteBuffer.allocate(1)));
                assertFails(IOE, webSocket.sendPing(ByteBuffer.allocate(0)));

                assertFails(IOE, webSocket.sendPong(ByteBuffer.allocate(125)));
                assertFails(IOE, webSocket.sendPong(ByteBuffer.allocate(124)));
                assertFails(IOE, webSocket.sendPong(ByteBuffer.allocate(1)));
                assertFails(IOE, webSocket.sendPong(ByteBuffer.allocate(0)));
            } finally {
                webSocket.abort();
            }
        }
    }

    @DataProvider(name = "sequence")
    public Object[][] data1() {
        int[] CLOSE = {
                0x81, 0x00, // ""
                0x82, 0x00, // []
                0x89, 0x00, // <PING>
                0x8a, 0x00, // <PONG>
                0x88, 0x00, // <CLOSE>
        };
        int[] ERROR = {
                0x81, 0x00, // ""
                0x82, 0x00, // []
                0x89, 0x00, // <PING>
                0x8a, 0x00, // <PONG>
                0x8b, 0x00, // 0xB control frame (causes an error)
        };
        return new Object[][]{
                {CLOSE, 1},
                {CLOSE, 3},
                {CLOSE, 4},
                {CLOSE, Long.MAX_VALUE},
                {ERROR, 1},
                {ERROR, 3},
                {ERROR, 4},
                {ERROR, Long.MAX_VALUE},
        };
    }

    @Test(dataProvider = "sequence")
    public void listenerSequentialOrder(int[] binary, long requestSize)
            throws IOException
    {
        try (var server = Support.serverWithCannedData(binary)) {
            server.open();

            CompletableFuture<Void> violation = new CompletableFuture<>();

            MockListener listener = new MockListener(requestSize) {

                final AtomicBoolean guard = new AtomicBoolean();

                private <T> T checkRunExclusively(Supplier<T> action) {
                    if (guard.getAndSet(true)) {
                        violation.completeExceptionally(new RuntimeException());
                    }
                    try {
                        return action.get();
                    } finally {
                        if (!guard.getAndSet(false)) {
                            violation.completeExceptionally(new RuntimeException());
                        }
                    }
                }

                @Override
                public void onOpen(WebSocket webSocket) {
                    checkRunExclusively(() -> {
                        super.onOpen(webSocket);
                        return null;
                    });
                }

                @Override
                public CompletionStage<?> onText(WebSocket webSocket,
                                                 CharSequence data,
                                                 boolean last) {
                    return checkRunExclusively(
                            () -> super.onText(webSocket, data, last));
                }

                @Override
                public CompletionStage<?> onBinary(WebSocket webSocket,
                                                   ByteBuffer data,
                                                   boolean last) {
                    return checkRunExclusively(
                            () -> super.onBinary(webSocket, data, last));
                }

                @Override
                public CompletionStage<?> onPing(WebSocket webSocket,
                                                 ByteBuffer message) {
                    return checkRunExclusively(
                            () -> super.onPing(webSocket, message));
                }

                @Override
                public CompletionStage<?> onPong(WebSocket webSocket,
                                                 ByteBuffer message) {
                    return checkRunExclusively(
                            () -> super.onPong(webSocket, message));
                }

                @Override
                public CompletionStage<?> onClose(WebSocket webSocket,
                                                  int statusCode,
                                                  String reason) {
                    return checkRunExclusively(
                            () -> super.onClose(webSocket, statusCode, reason));
                }

                @Override
                public void onError(WebSocket webSocket, Throwable error) {
                    checkRunExclusively(() -> {
                        super.onError(webSocket, error);
                        return null;
                    });
                }
            };

            var webSocket = newBuilder().proxy(NO_PROXY).build().newWebSocketBuilder()
                    .buildAsync(server.getURI(), listener)
                    .join();
            try {
                listener.invocations();
                violation.complete(null); // won't affect if completed exceptionally
                violation.join();
            } finally {
                webSocket.abort();
            }
        }
    }

    @Test
    public void sendMethodsThrowIOE2() throws Exception {
        try (var server = Support.serverWithCannedData(0x88, 0x00)) {
            server.open();

            CompletableFuture<Void> onCloseCalled = new CompletableFuture<>();
            CompletableFuture<Void> canClose = new CompletableFuture<>();

            WebSocket.Listener listener = new WebSocket.Listener() {
                @Override
                public CompletionStage<?> onClose(WebSocket webSocket,
                                                  int statusCode,
                                                  String reason) {
                    System.out.printf("onClose(%s, '%s')%n", statusCode, reason);
                    onCloseCalled.complete(null);
                    return canClose;
                }

                @Override
                public void onError(WebSocket webSocket, Throwable error) {
                    System.out.println("onError(" + error + ")");
                    onCloseCalled.completeExceptionally(error);
                }
            };

            var webSocket = newBuilder().proxy(NO_PROXY).build().newWebSocketBuilder()
                    .buildAsync(server.getURI(), listener)
                    .join();
            try {
                onCloseCalled.join();      // Wait for onClose to be called
                canClose.complete(null);   // Signal to the WebSocket it can close the output
                TimeUnit.SECONDS.sleep(5); // Give canClose some time to reach the WebSocket

                assertFails(IOE, webSocket.sendClose(WebSocket.NORMAL_CLOSURE, "ok"));

                assertFails(IOE, webSocket.sendText("", true));
                assertFails(IOE, webSocket.sendText("", false));
                assertFails(IOE, webSocket.sendText("abc", true));
                assertFails(IOE, webSocket.sendText("abc", false));
                assertFails(IOE, webSocket.sendBinary(ByteBuffer.allocate(0), true));
                assertFails(IOE, webSocket.sendBinary(ByteBuffer.allocate(0), false));
                assertFails(IOE, webSocket.sendBinary(ByteBuffer.allocate(1), true));
                assertFails(IOE, webSocket.sendBinary(ByteBuffer.allocate(1), false));

                assertFails(IOE, webSocket.sendPing(ByteBuffer.allocate(125)));
                assertFails(IOE, webSocket.sendPing(ByteBuffer.allocate(124)));
                assertFails(IOE, webSocket.sendPing(ByteBuffer.allocate(1)));
                assertFails(IOE, webSocket.sendPing(ByteBuffer.allocate(0)));

                assertFails(IOE, webSocket.sendPong(ByteBuffer.allocate(125)));
                assertFails(IOE, webSocket.sendPong(ByteBuffer.allocate(124)));
                assertFails(IOE, webSocket.sendPong(ByteBuffer.allocate(1)));
                assertFails(IOE, webSocket.sendPong(ByteBuffer.allocate(0)));
            } finally {
                webSocket.abort();
            }
        }
    }

    // Used to verify a server requiring Authentication
    private static final String USERNAME = "chegar";
    private static final String PASSWORD = "a1b2c3";

    static class WSAuthenticator extends Authenticator {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(USERNAME, PASSWORD.toCharArray());
        }
    }

    static final Function<int[],DummyWebSocketServer> SERVER_WITH_CANNED_DATA =
        new Function<>() {
            @Override public DummyWebSocketServer apply(int[] data) {
                return Support.serverWithCannedData(data); }
            @Override public String toString() { return "SERVER_WITH_CANNED_DATA"; }
        };

    static final Function<int[],DummyWebSocketServer> AUTH_SERVER_WITH_CANNED_DATA =
        new Function<>() {
            @Override public DummyWebSocketServer apply(int[] data) {
                return Support.serverWithCannedDataAndAuthentication(USERNAME, PASSWORD, data); }
            @Override public String toString() { return "AUTH_SERVER_WITH_CANNED_DATA"; }
        };

    @DataProvider(name = "servers")
    public Object[][] servers() {
        return new Object[][] {
            { SERVER_WITH_CANNED_DATA },
            { AUTH_SERVER_WITH_CANNED_DATA },
        };
    }

    record bytes(byte[] bytes) {
        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o instanceof bytes other) {
                return Arrays.equals(bytes(), other.bytes());
            }
            return false;
        }
        @Override
        public int hashCode() { return Arrays.hashCode(bytes()); }
        public String toString() {
            return "0x" + HexFormat.of()
                    .withUpperCase()
                    .formatHex(bytes());
        }
    }

    static List<bytes> ofBytes(List<byte[]> bytes) {
        return bytes.stream().map(bytes::new).toList();
    }

    static String diagnose(List<byte[]> a, List<byte[]> b) {
        var actual = ofBytes(a);
        var expected = ofBytes(b);
        var message = actual.equals(expected) ? "match" : "differ";
        return "%s and %s %s".formatted(actual, expected, message);
    }

    @Test(dataProvider = "servers")
    public void simpleAggregatingBinaryMessages
            (Function<int[],DummyWebSocketServer> serverSupplier)
        throws IOException
    {
        List<byte[]> expected = List.of("alpha", "beta", "gamma", "delta")
                .stream()
                .map(s -> s.getBytes(StandardCharsets.US_ASCII))
                .collect(Collectors.toList());
        int[] binary = new int[]{
                0x82, 0x05, 0x61, 0x6c, 0x70, 0x68, 0x61, // [alpha]
                0x02, 0x02, 0x62, 0x65,                   // [be
                0x80, 0x02, 0x74, 0x61,                   // ta]
                0x02, 0x01, 0x67,                         // [g
                0x00, 0x01, 0x61,                         // a
                0x00, 0x00,                               //
                0x00, 0x00,                               //
                0x00, 0x01, 0x6d,                         // m
                0x00, 0x01, 0x6d,                         // m
                0x80, 0x01, 0x61,                         // a]
                0x8a, 0x00,                               // <PONG>
                0x02, 0x04, 0x64, 0x65, 0x6c, 0x74,       // [delt
                0x00, 0x01, 0x61,                         // a
                0x80, 0x00,                               // ]
                0x88, 0x00                                // <CLOSE>
        };
        CompletableFuture<List<byte[]>> actual = new CompletableFuture<>();

        try (var server = serverSupplier.apply(binary)) {
            server.open();

            WebSocket.Listener listener = new WebSocket.Listener() {

                List<byte[]> collectedBytes = new ArrayList<>();
                ByteBuffer buffer = ByteBuffer.allocate(1024);

                @Override
                public CompletionStage<?> onBinary(WebSocket webSocket,
                                                   ByteBuffer message,
                                                   boolean last) {
                    System.out.printf("onBinary(%s, %s)%n", message, last);
                    webSocket.request(1);

                    append(message);
                    if (last) {
                        buffer.flip();
                        byte[] bytes = new byte[buffer.remaining()];
                        buffer.get(bytes);
                        buffer.clear();
                        processWholeBinary(bytes);
                    }
                    return null;
                }

                private void append(ByteBuffer message) {
                    if (buffer.remaining() < message.remaining()) {
                        assert message.remaining() > 0;
                        int cap = (buffer.capacity() + message.remaining()) * 2;
                        ByteBuffer b = ByteBuffer.allocate(cap);
                        b.put(buffer.flip());
                        buffer = b;
                    }
                    buffer.put(message);
                }

                private void processWholeBinary(byte[] bytes) {
                    String stringBytes = new String(bytes, UTF_8);
                    System.out.println("processWholeBinary: " + stringBytes);
                    collectedBytes.add(bytes);
                }

                @Override
                public CompletionStage<?> onClose(WebSocket webSocket,
                                                  int statusCode,
                                                  String reason) {
                    actual.complete(collectedBytes);
                    return null;
                }

                @Override
                public void onError(WebSocket webSocket, Throwable error) {
                    actual.completeExceptionally(error);
                }
            };

            var webSocket = newBuilder()
                    .proxy(NO_PROXY)
                    .authenticator(new WSAuthenticator())
                    .build().newWebSocketBuilder()
                    .buildAsync(server.getURI(), listener)
                    .join();
            try {
                List<byte[]> a = actual.join();
                assertEquals(ofBytes(a), ofBytes(expected), diagnose(a, expected));
            } finally {
                webSocket.abort();
            }
        }
    }

    @Test(dataProvider = "servers")
    public void simpleAggregatingTextMessages
            (Function<int[],DummyWebSocketServer> serverSupplier)
        throws IOException
    {
        List<String> expected = List.of("alpha", "beta", "gamma", "delta");

        int[] binary = new int[]{
                0x81, 0x05, 0x61, 0x6c, 0x70, 0x68, 0x61, // "alpha"
                0x01, 0x02, 0x62, 0x65,                   // "be
                0x80, 0x02, 0x74, 0x61,                   // ta"
                0x01, 0x01, 0x67,                         // "g
                0x00, 0x01, 0x61,                         // a
                0x00, 0x00,                               //
                0x00, 0x00,                               //
                0x00, 0x01, 0x6d,                         // m
                0x00, 0x01, 0x6d,                         // m
                0x80, 0x01, 0x61,                         // a"
                0x8a, 0x00,                               // <PONG>
                0x01, 0x04, 0x64, 0x65, 0x6c, 0x74,       // "delt
                0x00, 0x01, 0x61,                         // a
                0x80, 0x00,                               // "
                0x88, 0x00                                // <CLOSE>
        };
        CompletableFuture<List<String>> actual = new CompletableFuture<>();

        try (var server = serverSupplier.apply(binary)) {
            server.open();

            WebSocket.Listener listener = new WebSocket.Listener() {

                List<String> collectedStrings = new ArrayList<>();
                StringBuilder text = new StringBuilder();

                @Override
                public CompletionStage<?> onText(WebSocket webSocket,
                                                 CharSequence message,
                                                 boolean last) {
                    System.out.printf("onText(%s, %s)%n", message, last);
                    webSocket.request(1);
                    text.append(message);
                    if (last) {
                        String str = text.toString();
                        text.setLength(0);
                        processWholeText(str);
                    }
                    return null;
                }

                private void processWholeText(String string) {
                    System.out.println(string);
                    collectedStrings.add(string);
                }

                @Override
                public CompletionStage<?> onClose(WebSocket webSocket,
                                                  int statusCode,
                                                  String reason) {
                    actual.complete(collectedStrings);
                    return null;
                }

                @Override
                public void onError(WebSocket webSocket, Throwable error) {
                    actual.completeExceptionally(error);
                }
            };

            var webSocket = newBuilder()
                    .proxy(NO_PROXY)
                    .authenticator(new WSAuthenticator())
                    .build().newWebSocketBuilder()
                    .buildAsync(server.getURI(), listener)
                    .join();
            try {
                List<String> a = actual.join();
                assertEquals(a, expected);
            } finally {
                webSocket.abort();
            }
        }
    }

    /*
     * Exercises the scenario where requests for more messages are made prior to
     * completing the returned CompletionStage instances.
     */
    @Test(dataProvider = "servers")
    public void aggregatingTextMessages
        (Function<int[],DummyWebSocketServer> serverSupplier)
        throws IOException
    {
        List<String> expected = List.of("alpha", "beta", "gamma", "delta");

        int[] binary = new int[]{
                0x81, 0x05, 0x61, 0x6c, 0x70, 0x68, 0x61, // "alpha"
                0x01, 0x02, 0x62, 0x65,                   // "be
                0x80, 0x02, 0x74, 0x61,                   // ta"
                0x01, 0x01, 0x67,                         // "g
                0x00, 0x01, 0x61,                         // a
                0x00, 0x00,                               //
                0x00, 0x00,                               //
                0x00, 0x01, 0x6d,                         // m
                0x00, 0x01, 0x6d,                         // m
                0x80, 0x01, 0x61,                         // a"
                0x8a, 0x00,                               // <PONG>
                0x01, 0x04, 0x64, 0x65, 0x6c, 0x74,       // "delt
                0x00, 0x01, 0x61,                         // a
                0x80, 0x00,                               // "
                0x88, 0x00                                // <CLOSE>
        };
        CompletableFuture<List<String>> actual = new CompletableFuture<>();

        try (var server = serverSupplier.apply(binary)) {
            server.open();

            WebSocket.Listener listener = new WebSocket.Listener() {

                List<CharSequence> parts = new ArrayList<>();
                /*
                 * A CompletableFuture which will complete once the current
                 * message has been fully assembled. Until then the listener
                 * returns this instance for every call.
                 */
                CompletableFuture<?> currentCf = new CompletableFuture<>();
                List<String> collected = new ArrayList<>();

                @Override
                public CompletionStage<?> onText(WebSocket webSocket,
                                                 CharSequence message,
                                                 boolean last) {
                    parts.add(message);
                    if (!last) {
                        webSocket.request(1);
                    } else {
                        this.currentCf.thenRun(() -> webSocket.request(1));
                        CompletableFuture<?> refCf = this.currentCf;
                        processWholeMessage(new ArrayList<>(parts), refCf);
                        currentCf = new CompletableFuture<>();
                        parts.clear();
                        return refCf;
                    }
                    return currentCf;
                }

                @Override
                public CompletionStage<?> onClose(WebSocket webSocket,
                                                  int statusCode,
                                                  String reason) {
                    actual.complete(collected);
                    return null;
                }

                @Override
                public void onError(WebSocket webSocket, Throwable error) {
                    actual.completeExceptionally(error);
                }

                public void processWholeMessage(List<CharSequence> data,
                                                CompletableFuture<?> cf) {
                    StringBuilder b = new StringBuilder();
                    data.forEach(b::append);
                    String s = b.toString();
                    System.out.println(s);
                    cf.complete(null);
                    collected.add(s);
                }
            };

            var webSocket = newBuilder()
                    .proxy(NO_PROXY)
                    .authenticator(new WSAuthenticator())
                    .build().newWebSocketBuilder()
                    .buildAsync(server.getURI(), listener)
                    .join();
            try {
                List<String> a = actual.join();
                assertEquals(a, expected);
            } finally {
                webSocket.abort();
            }
        }
    }

    // -- authentication specific tests

    /*
     * Ensures authentication succeeds when an Authenticator set on client builder.
     */
    @Test
    public void clientAuthenticate() throws IOException  {
        try (var server = new DummyWebSocketServer(USERNAME, PASSWORD)){
            server.open();

            var webSocket = newBuilder()
                    .proxy(NO_PROXY)
                    .authenticator(new WSAuthenticator())
                    .build()
                    .newWebSocketBuilder()
                    .buildAsync(server.getURI(), new WebSocket.Listener() { })
                    .join();
            webSocket.abort();
        }
    }

    /*
     * Ensures authentication succeeds when an `Authorization` header is explicitly set.
     */
    @Test
    public void explicitAuthenticate() throws IOException  {
        try (var server = new DummyWebSocketServer(USERNAME, PASSWORD)) {
            server.open();

            String hv = "Basic " + Base64.getEncoder().encodeToString(
                    (USERNAME + ":" + PASSWORD).getBytes(UTF_8));

            var webSocket = newBuilder()
                    .proxy(NO_PROXY).build()
                    .newWebSocketBuilder()
                    .header("Authorization", hv)
                    .buildAsync(server.getURI(), new WebSocket.Listener() { })
                    .join();
            webSocket.abort();
        }
    }

    /*
     * Ensures authentication does not succeed when no authenticator is present.
     */
    @Test
    public void failNoAuthenticator() throws IOException  {
        try (var server = new DummyWebSocketServer(USERNAME, PASSWORD)) {
            server.open();

            CompletableFuture<WebSocket> cf = newBuilder()
                    .proxy(NO_PROXY).build()
                    .newWebSocketBuilder()
                    .buildAsync(server.getURI(), new WebSocket.Listener() { });

            try {
                var webSocket = cf.join();
                silentAbort(webSocket);
                fail("Expected exception not thrown");
            } catch (CompletionException expected) {
                WebSocketHandshakeException e = (WebSocketHandshakeException)expected.getCause();
                HttpResponse<?> response = e.getResponse();
                assertEquals(response.statusCode(), 401);
            }
        }
    }

    /*
     * Ensures authentication does not succeed when the authenticator presents
     * unauthorized credentials.
     */
    @Test
    public void failBadCredentials() throws IOException  {
        try (var server = new DummyWebSocketServer(USERNAME, PASSWORD)) {
            server.open();

            Authenticator authenticator = new Authenticator() {
                @Override protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("BAD" + USERNAME, "".toCharArray());
                }
            };

            CompletableFuture<WebSocket> cf = newBuilder()
                    .proxy(NO_PROXY)
                    .authenticator(authenticator)
                    .build()
                    .newWebSocketBuilder()
                    .buildAsync(server.getURI(), new WebSocket.Listener() { });

            try {
                var webSocket = cf.join();
                silentAbort(webSocket);
                fail("Expected exception not thrown");
            } catch (CompletionException expected) {
                System.out.println("caught expected exception:" + expected);
            }
        }
    }
    private static void silentAbort(WebSocket ws) {
        try {
            ws.abort();
        } catch (Throwable t) { }
    }
}