Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: a539ab5afb4a815e2b2b0a4d19760771c2831460 (plain) (blame)
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
//
//  ========================================================================
//  Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
//  ------------------------------------------------------------------------
//  All rights reserved. This program and the accompanying materials
//  are made available under the terms of the Eclipse Public License v1.0
//  and Apache License v2.0 which accompanies this distribution.
//
//      The Eclipse Public License is available at
//      http://www.eclipse.org/legal/epl-v10.html
//
//      The Apache License v2.0 is available at
//      http://www.opensource.org/licenses/apache2.0.php
//
//  You may elect to redistribute this code under either of these licenses.
//  ========================================================================
//

package org.eclipse.jetty.io;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.WritePendingException;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

import org.eclipse.jetty.util.BlockingCallback;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.Callback;
import org.eclipse.jetty.util.FutureCallback;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.runners.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class WriteFlusherTest
{
    private final AtomicBoolean _flushIncomplete = new AtomicBoolean(false);
    private final ExecutorService executor = Executors.newFixedThreadPool(16);
    @Mock
    private EndPoint _endPointMock;
    private WriteFlusher _flusher;
    private ByteArrayEndPoint _endp;

    @Before
    public void before()
    {
        _endp = new ByteArrayEndPoint(new byte[]{}, 10);
        _flushIncomplete.set(false);
        _flusher = new WriteFlusher(_endp)
        {
            @Override
            protected void onIncompleteFlush()
            {
                _flushIncomplete.set(true);
            }
        };
    }

    @Test
    public void testIgnorePreviousFailures() throws Exception
    {
        _endp.setGrowOutput(true);

        FutureCallback callback = new FutureCallback();
        _flusher.onFail(new IOException("Ignored because no operation in progress"));
        _flusher.write(callback, BufferUtil.toBuffer("How "), BufferUtil.toBuffer("now "), BufferUtil.toBuffer("brown "), BufferUtil.toBuffer("cow!"));
        assertCallbackIsDone(callback);
        assertFlushIsComplete();
        assertThat("context and callback.get() are equal",callback.get() , equalTo(null));
        assertThat("string in endpoint matches expected string", "How now brown cow!",
                equalTo(_endp.takeOutputString()));
        assertTrue(_flusher.isIdle());
    }

    @Test
    public void testCompleteNoBlocking() throws Exception
    {
        _endp.setGrowOutput(true);

        FutureCallback callback = new FutureCallback();
        _flusher.write(callback, BufferUtil.toBuffer("How "), BufferUtil.toBuffer("now "), BufferUtil.toBuffer("brown "), BufferUtil.toBuffer("cow!"));
        assertCallbackIsDone(callback);
        assertFlushIsComplete();
        assertThat("context and callback.get() are equal", callback.get(), equalTo(null));
        assertThat("string in endpoint matches expected string", "How now brown cow!",
                equalTo(_endp.takeOutputString()));
        assertTrue(_flusher.isIdle());
    }

    private void assertFlushIsComplete()
    {
        assertThat("flush is complete", _flushIncomplete.get(), is(false));
    }

    private void assertCallbackIsDone(FutureCallback callback)
    {
        assertThat("callback is done", callback.isDone(), is(true));
    }

    @Test
    public void testClosedNoBlocking() throws Exception
    {
        _endp.close();

        FutureCallback callback = new FutureCallback();
        _flusher.write(callback, BufferUtil.toBuffer("How "), BufferUtil.toBuffer("now "), BufferUtil.toBuffer("brown "), BufferUtil.toBuffer("cow!"));
        assertCallbackIsDone(callback);
        assertFlushIsComplete();
        try
        {
            assertEquals(callback.get(),null);
            Assert.fail();
        }
        catch (ExecutionException e)
        {
            Throwable cause = e.getCause();
            Assert.assertTrue(cause instanceof IOException);
            Assert.assertThat(cause.getMessage(), Matchers.containsString("CLOSED"));
        }
        assertEquals("", _endp.takeOutputString());
        assertTrue(_flusher.isIdle());
    }


    @Test
    public void testCompleteBlocking() throws Exception
    {
        FutureCallback callback = new FutureCallback();
        _flusher.write(callback, BufferUtil.toBuffer("How "), BufferUtil.toBuffer("now "), BufferUtil.toBuffer("brown "), BufferUtil.toBuffer("cow!"));
        assertFalse(callback.isDone());
        assertFalse(callback.isCancelled());

        assertTrue(_flushIncomplete.get());
        try
        {
            assertEquals(callback.get(10, TimeUnit.MILLISECONDS),null);
            Assert.fail();
        }
        catch (TimeoutException to)
        {
            _flushIncomplete.set(false);
        }

        assertEquals("How now br", _endp.takeOutputString());
        _flusher.completeWrite();
        assertCallbackIsDone(callback);
        assertEquals(callback.get(),null);
        assertEquals("own cow!", _endp.takeOutputString());
        assertFlushIsComplete();
        assertTrue(_flusher.isIdle());
    }

    @Test
    public void testCloseWhileBlocking() throws Exception
    {
        FutureCallback callback = new FutureCallback();
        _flusher.write(callback, BufferUtil.toBuffer("How "), BufferUtil.toBuffer("now "), BufferUtil.toBuffer("brown "), BufferUtil.toBuffer("cow!"));

        assertFalse(callback.isDone());
        assertFalse(callback.isCancelled());

        assertTrue(_flushIncomplete.get());
        try
        {
            assertEquals(callback.get(10, TimeUnit.MILLISECONDS),null);
            Assert.fail();
        }
        catch (TimeoutException to)
        {
            _flushIncomplete.set(false);
        }

        assertEquals("How now br", _endp.takeOutputString());
        _endp.close();
        _flusher.completeWrite();
        assertCallbackIsDone(callback);
        assertFlushIsComplete();
        try
        {
            assertEquals(callback.get(),null);
            Assert.fail();
        }
        catch (ExecutionException e)
        {
            Throwable cause = e.getCause();
            Assert.assertTrue(cause instanceof IOException);
            Assert.assertThat(cause.getMessage(), Matchers.containsString("CLOSED"));
        }
        assertEquals("", _endp.takeOutputString());
        assertTrue(_flusher.isIdle());
    }

    @Test
    public void testFailWhileBlocking() throws Exception
    {
        FutureCallback callback = new FutureCallback();
        _flusher.write(callback, BufferUtil.toBuffer("How "), BufferUtil.toBuffer("now "), BufferUtil.toBuffer("brown "), BufferUtil.toBuffer("cow!"));

        assertFalse(callback.isDone());
        assertFalse(callback.isCancelled());

        assertTrue(_flushIncomplete.get());
        try
        {
            assertEquals(callback.get(10, TimeUnit.MILLISECONDS),null);
            Assert.fail();
        }
        catch (TimeoutException to)
        {
            _flushIncomplete.set(false);
        }

        assertEquals("How now br", _endp.takeOutputString());
        _flusher.onFail(new IOException("Failure"));
        _flusher.completeWrite();
        assertCallbackIsDone(callback);
        assertFlushIsComplete();
        try
        {
            assertEquals(callback.get(),null);
            Assert.fail();
        }
        catch (ExecutionException e)
        {
            Throwable cause = e.getCause();
            Assert.assertTrue(cause instanceof IOException);
            Assert.assertThat(cause.getMessage(), Matchers.containsString("Failure"));
        }
        assertEquals("", _endp.takeOutputString());

        assertTrue(_flusher.isIdle());
    }

    private static class ConcurrentFlusher extends WriteFlusher implements Runnable
    {
        final ByteArrayEndPoint _endp;
        final SecureRandom _random;
        final ScheduledThreadPoolExecutor _scheduler;
        final StringBuilder _content = new StringBuilder();

        ConcurrentFlusher(ByteArrayEndPoint endp, SecureRandom random, ScheduledThreadPoolExecutor scheduler)
        {
            super(endp);
            _endp = endp;
            _random = random;
            _scheduler = scheduler;
        }

        @Override
        protected void onIncompleteFlush()
        {
            _scheduler.schedule(this, 1 + _random.nextInt(9), TimeUnit.MILLISECONDS);
        }

        @Override
        public synchronized void run()
        {
            _content.append(_endp.takeOutputString());
            completeWrite();
        }

        @Override
        public synchronized String toString()
        {
            _content.append(_endp.takeOutputString());
            return _content.toString();
        }
    }

    @Test
    public void testConcurrent() throws Exception
    {
        final SecureRandom random = new SecureRandom();
        final ScheduledThreadPoolExecutor scheduler = new ScheduledThreadPoolExecutor(100);


        ConcurrentFlusher[] flushers = new ConcurrentFlusher[50000];
        FutureCallback[] futures = new FutureCallback[flushers.length];
        for (int i = 0; i < flushers.length; i++)
        {
            int size = 5 + random.nextInt(15);
            ByteArrayEndPoint endp = new ByteArrayEndPoint(new byte[]{}, size);

            final ConcurrentFlusher flusher = new ConcurrentFlusher(endp, random, scheduler);
            flushers[i] = flusher;
            final FutureCallback callback = new FutureCallback();
            futures[i] = callback;
            scheduler.schedule(new Runnable()
            {
                @Override
                public void run()
                {
                    flusher.onFail(new Throwable("THE CAUSE"));
                }
            }
                    , random.nextInt(75) + 1, TimeUnit.MILLISECONDS);
            flusher.write(callback, BufferUtil.toBuffer("How Now Brown Cow."), BufferUtil.toBuffer(" The quick brown fox jumped over the lazy dog!"));
        }

        int completed = 0;
        int failed = 0;

        for (int i = 0; i < flushers.length; i++)
        {
            try
            {
                futures[i].get();
                assertEquals("How Now Brown Cow. The quick brown fox jumped over the lazy dog!", flushers[i].toString());
                completed++;
            }
            catch (Exception e)
            {
                assertThat(e.getMessage(), Matchers.containsString("THE CAUSE"));
                failed++;
            }
        }

        assertThat(completed, Matchers.greaterThan(0));
        assertThat(failed, Matchers.greaterThan(0));

        scheduler.shutdown();
    }

    @Test
    public void testConcurrentAccessToWriteAndOnFail() throws Exception
    {
        // TODO review this test - It was changed for the boolean flush return, but not really well inspected

        final CountDownLatch failedCalledLatch = new CountDownLatch(1);
        final CountDownLatch writeCalledLatch = new CountDownLatch(1);
        final CountDownLatch writeCompleteLatch = new CountDownLatch(1);

        final WriteFlusher writeFlusher = new WriteFlusher(_endPointMock)
        {
            @Override
            public void write(Callback callback, ByteBuffer... buffers)
            {
                super.write(callback, buffers);
                writeCompleteLatch.countDown();
            }

            @Override
            protected void onIncompleteFlush()
            {
            }
        };

        endPointFlushExpectation(writeCalledLatch, failedCalledLatch);

        ExposingStateCallback callback = new ExposingStateCallback();
        executor.submit(new Writer(writeFlusher, callback));
        assertThat("Write has been called.", writeCalledLatch.await(5, TimeUnit.SECONDS), is(true));
        executor.submit(new FailedCaller(writeFlusher, failedCalledLatch)).get();


        // callback failed is NOT called because in WRITING state failed() doesn't know about the callback. However
        // either the write succeeds or we get an IOException which will call callback.failed()
        assertThat("write complete", writeCompleteLatch.await(5, TimeUnit.SECONDS), is(true));


        // in this testcase we more or less emulate that the write has successfully finished and we return from
        // EndPoint.flush() back to WriteFlusher.write(). Then someone calls failed. So the callback should have been
        // completed.
        try
        {
            callback.get(5,TimeUnit.SECONDS);
            assertThat("callback completed", callback.isCompleted(), is(true));
            assertThat("callback failed", callback.isFailed(), is(false));
        }
        catch(ExecutionException e)
        {
            // ignored because failure is expected
            assertThat("callback failed", callback.isFailed(), is(true));
        }
        assertThat("callback completed", callback.isDone(), is(true));
    }

    @Test
    public void testPendingWriteDoesNotStoreConsumedBuffers() throws Exception
    {
        int toWrite = _endp.getOutput().capacity();
        byte[] chunk1 = new byte[toWrite / 2];
        Arrays.fill(chunk1, (byte)1);
        ByteBuffer buffer1 = ByteBuffer.wrap(chunk1);
        byte[] chunk2 = new byte[toWrite];
        Arrays.fill(chunk1, (byte)2);
        ByteBuffer buffer2 = ByteBuffer.wrap(chunk2);

        _flusher.write(Callback.NOOP, buffer1, buffer2);
        assertTrue(_flushIncomplete.get());
        assertFalse(buffer1.hasRemaining());

        // Reuse buffer1
        buffer1.clear();
        Arrays.fill(chunk1, (byte)3);
        int remaining1 = buffer1.remaining();

        // Complete the write
        _endp.takeOutput();
        _flusher.completeWrite();

        // Make sure buffer1 is unchanged
        assertEquals(remaining1, buffer1.remaining());
    }

    private class ExposingStateCallback extends FutureCallback
    {
        private boolean failed = false;
        private boolean completed = false;

        @Override
        public void succeeded()
        {
            completed = true;
            super.succeeded();
        }

        @Override
        public void failed(Throwable cause)
        {
            failed = true;
            super.failed(cause);
        }

        public boolean isFailed()
        {
            return failed;
        }

        public boolean isCompleted()
        {
            return completed;
        }
    }

    @Test(expected = WritePendingException.class)
    public void testConcurrentAccessToWrite() throws Throwable
    {
        final CountDownLatch flushCalledLatch = new CountDownLatch(1);

        final WriteFlusher writeFlusher = new WriteFlusher(_endPointMock)
        {
            @Override
            protected void onIncompleteFlush()
            {
            }
        };

        // in this test we just want to make sure that we called write twice at the same time
        when(_endPointMock.flush(any(ByteBuffer[].class))).thenAnswer(new Answer<Object>()
        {
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable
            {
                flushCalledLatch.countDown();
                // make sure we stay here, so write is called twice at the same time
                Thread.sleep(5000);
                return Boolean.TRUE;
            }
        });

        executor.submit(new Writer(writeFlusher, new FutureCallback()));
        // make sure that we call .get() on the write that executed second by waiting on this latch
        assertThat("Flush has been called once", flushCalledLatch.await(5, TimeUnit.SECONDS), is(true));
        try
        {
            executor.submit(new Writer(writeFlusher, new FutureCallback())).get();
        }
        catch (ExecutionException e)
        {
            throw e.getCause();
        }
    }

    private void endPointFlushExpectation(final CountDownLatch writeCalledLatch,
                                          final CountDownLatch failedCalledLatch) throws IOException
    {
        when(_endPointMock.flush(any(ByteBuffer[].class))).thenAnswer(new Answer<Object>()
        {
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable
            {
                Object[] arguments = invocation.getArguments();
                ByteBuffer byteBuffer = (ByteBuffer)arguments[0];
                BufferUtil.flipToFill(byteBuffer); // pretend everything has been written
                writeCalledLatch.countDown();
                failedCalledLatch.await(5, TimeUnit.SECONDS);
                return Boolean.TRUE;
            }
        });
    }

    @Test
    public void testConcurrentAccessToIncompleteWriteAndOnFail() throws Exception
    {
        final CountDownLatch failedCalledLatch = new CountDownLatch(1);
        final CountDownLatch onIncompleteFlushedCalledLatch = new CountDownLatch(1);
        final CountDownLatch writeCalledLatch = new CountDownLatch(1);
        final CountDownLatch completeWrite = new CountDownLatch(1);

        final WriteFlusher writeFlusher = new WriteFlusher(new EndPointConcurrentAccessToIncompleteWriteAndOnFailMock(writeCalledLatch, failedCalledLatch))
        {
            @Override
            protected void onIncompleteFlush()
            {
                onIncompleteFlushedCalledLatch.countDown();
                try
                {
                    failedCalledLatch.await(5, TimeUnit.SECONDS);
                }
                catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
                completeWrite();
                completeWrite.countDown();
            }
        };

        ExposingStateCallback callback = new ExposingStateCallback();
        executor.submit(new Writer(writeFlusher, callback));
        assertThat("Write has been called.", writeCalledLatch.await(5, TimeUnit.SECONDS), is(true));
        // make sure we're in pending state when calling onFail
        assertThat("onIncompleteFlushed has been called.", onIncompleteFlushedCalledLatch.await(5,
                TimeUnit.SECONDS), is(true));
        executor.submit(new FailedCaller(writeFlusher, failedCalledLatch));
        assertThat("Failed has been called.", failedCalledLatch.await(5, TimeUnit.SECONDS), is(true));
        assertThat("completeWrite done", completeWrite.await(5, TimeUnit.SECONDS), is(true));
        // when we fail in PENDING state, we should have called callback.failed()
        assertThat("callback failed has been called", callback.isFailed(), is(true));
        assertThat("callback complete has not been called", callback.isCompleted(), is(false));
    }

    private static class EndPointConcurrentAccessToIncompleteWriteAndOnFailMock extends ByteArrayEndPoint
    {
        private final CountDownLatch writeCalledLatch;
        private final CountDownLatch failedCalledLatch;
        private final AtomicBoolean stalled=new AtomicBoolean(false);

        public EndPointConcurrentAccessToIncompleteWriteAndOnFailMock(CountDownLatch writeCalledLatch, CountDownLatch failedCalledLatch)
        {
            this.writeCalledLatch = writeCalledLatch;
            this.failedCalledLatch = failedCalledLatch;
        }

        @Override
        public boolean flush(ByteBuffer... buffers) throws IOException
        {
            writeCalledLatch.countDown();
            ByteBuffer byteBuffer = buffers[0];
            int oldPos = byteBuffer.position();
            if (byteBuffer.remaining() == 2)
            {
                // make sure we stall at least once
                if (!stalled.get())
                {
                    stalled.set(true);
                    return false;
                }

                // make sure failed is called before we go on
                try
                {
                    failedCalledLatch.await(5, TimeUnit.SECONDS);
                }
                catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
                BufferUtil.flipToFill(byteBuffer);
            }
            else if (byteBuffer.remaining() == 3)
            {
                byteBuffer.position(1); // pretend writing one byte
            }
            else
            {
                byteBuffer.position(byteBuffer.limit());
            }

            for (ByteBuffer b: buffers)
                if (BufferUtil.hasContent(b))
                    return false;
            return true;
        }
    }

    @Test
    public void testIterationOnNonBlockedStall() throws Exception
    {
        final Exchanger<Integer> exchange = new Exchanger<>();
        final AtomicInteger window = new AtomicInteger(10);
        EndPointIterationOnNonBlockedStallMock endp=new EndPointIterationOnNonBlockedStallMock(window);
        final WriteFlusher writeFlusher = new WriteFlusher(endp)
        {
            @Override
            protected void onIncompleteFlush()
            {
                executor.submit(new Runnable()
                {
                    public void run()
                    {
                        try
                        {
                            while(window.get()==0)
                                window.addAndGet(exchange.exchange(0));
                            completeWrite();
                        }
                        catch(Throwable th)
                        {
                            th.printStackTrace();
                        }
                    }
                });

            }
        };

        BlockingCallback callback = new BlockingCallback();
        writeFlusher.write(callback,BufferUtil.toBuffer("How "),BufferUtil.toBuffer("now "),BufferUtil.toBuffer("brown "),BufferUtil.toBuffer("cow."));
        exchange.exchange(0);

        Assert.assertThat(endp.takeOutputString(StandardCharsets.US_ASCII),Matchers.equalTo("How now br"));

        exchange.exchange(1);
        exchange.exchange(0);

        Assert.assertThat(endp.takeOutputString(StandardCharsets.US_ASCII),Matchers.equalTo("o"));

        exchange.exchange(8);
        callback.block();

        Assert.assertThat(endp.takeOutputString(StandardCharsets.US_ASCII),Matchers.equalTo("wn cow."));

    }

    private static class EndPointIterationOnNonBlockedStallMock extends ByteArrayEndPoint
    {
        final AtomicInteger _window;

        public EndPointIterationOnNonBlockedStallMock(AtomicInteger window)
        {
            _window=window;
        }

        @Override
        public boolean flush(ByteBuffer... buffers) throws IOException
        {
            ByteBuffer byteBuffer = buffers[0];

            if (_window.get()>0 && byteBuffer.hasRemaining())
            {
                // consume 1 byte
                byte one = byteBuffer.get(byteBuffer.position());
                if (super.flush(ByteBuffer.wrap(new byte[]{one})))
                {
                    _window.decrementAndGet();
                    byteBuffer.position(byteBuffer.position()+1);
                }
            }
            for (ByteBuffer b: buffers)
                if (BufferUtil.hasContent(b))
                    return false;
            return true;
        }
    }


    private static class FailedCaller implements Callable<FutureCallback>
    {
        private final WriteFlusher writeFlusher;
        private CountDownLatch failedCalledLatch;

        public FailedCaller(WriteFlusher writeFlusher, CountDownLatch failedCalledLatch)
        {
            this.writeFlusher = writeFlusher;
            this.failedCalledLatch = failedCalledLatch;
        }

        @Override
        public FutureCallback call()
        {
            writeFlusher.onFail(new IllegalStateException());
            failedCalledLatch.countDown();
            return null;
        }
    }

    private class Writer implements Callable<FutureCallback>
    {
        private final WriteFlusher writeFlusher;
        private FutureCallback callback;

        public Writer(WriteFlusher writeFlusher, FutureCallback callback)
        {
            this.writeFlusher = writeFlusher;
            this.callback = callback;
        }

        @Override
        public FutureCallback call()
        {
            writeFlusher.write(callback, BufferUtil.toBuffer("foo"));
            return callback;
        }
    }
}

Back to the top