-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
HttpOutput.java
1933 lines (1713 loc) · 59.9 KB
/
HttpOutput.java
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
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// ========================================================================
// Copyright (c) 1995-2021 Mort Bay Consulting Pty Ltd and others.
// ------------------------------------------------------------------------
// 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.server;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritePendingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CoderResult;
import java.nio.charset.CodingErrorAction;
import java.util.ResourceBundle;
import java.util.concurrent.CancellationException;
import java.util.concurrent.TimeUnit;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.WriteListener;
import org.eclipse.jetty.http.HttpContent;
import org.eclipse.jetty.io.ByteBufferPool;
import org.eclipse.jetty.io.EofException;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.Callback;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.IteratingCallback;
import org.eclipse.jetty.util.SharedBlockingCallback;
import org.eclipse.jetty.util.SharedBlockingCallback.Blocker;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
/**
* <p>{@link HttpOutput} implements {@link ServletOutputStream}
* as required by the Servlet specification.</p>
* <p>{@link HttpOutput} buffers content written by the application until a
* further write will overflow the buffer, at which point it triggers a commit
* of the response.</p>
* <p>{@link HttpOutput} can be closed and reopened, to allow requests included
* via {@link RequestDispatcher#include(ServletRequest, ServletResponse)} to
* close the stream, to be reopened after the inclusion ends.</p>
*/
public class HttpOutput extends ServletOutputStream implements Runnable
{
private static final String LSTRING_FILE = "javax.servlet.LocalStrings";
private static ResourceBundle lStrings = ResourceBundle.getBundle(LSTRING_FILE);
/**
* The output state
*/
enum State
{
OPEN, // Open
CLOSE, // Close needed from onWriteComplete
CLOSING, // Close in progress after close API called
CLOSED // Closed
}
/**
* The API State which combines with the output State:
* <pre>
OPEN/BLOCKING---last----------------------------+ CLOSED/BLOCKING
/ | ^ \ ^ ^
/ w | \ / |
/ | owc +--owcL------------------->--owcL-----\---------------------+ |
| v | / / V |
swl OPEN/BLOCKED----last---->CLOSE/BLOCKED----owc----->CLOSING/BLOCKED--owcL------+
|
\
\
V
+-->OPEN/READY------last---------------------------+
/ ^ | \
/ / w \
| / | +--owcL------------------->--owcL----\---------------------------+
| / v / / V |
| irt OPEN/PENDING----last---->CLOSE/PENDING----owc---->CLOSING/PENDING--owcL----+ |
| \ / | | ^ | | |
owc \/ owc irf / irf | |
| /\ | | / | | |
| / \ V | / | V V
| irf OPEN/ASYNC------last----------|----------------+ | CLOSED/ASYNC
| \ | | ^ ^
\ \ | | | |
\ \ | | | |
\ v v v | |
+--OPEN/UNREADY----last---->CLOSE/UNREADY----owc----->CLOSING/UNREADY--owcL---+ |
\ \ |
+--owcL------------------->--owcL--------------------------------+
swl : setWriteListener
w : write
owc : onWriteComplete last == false
owcL : onWriteComplete last == true
irf : isReady() == false
irt : isReady() == true
last : close() or complete(Callback) or write of known last content
</pre>
*/
enum ApiState
{
BLOCKING, // Open in blocking mode
BLOCKED, // Blocked in blocking operation
ASYNC, // Open in async mode
READY, // isReady() has returned true
PENDING, // write operating in progress
UNREADY, // write operating in progress, isReady has returned false
}
/**
* The HttpOutput.Interceptor is a single intercept point for all
* output written to the HttpOutput: via writer; via output stream;
* asynchronously; or blocking.
* <p>
* The Interceptor can be used to implement translations (eg Gzip) or
* additional buffering that acts on all output. Interceptors are
* created in a chain, so that multiple concerns may intercept.
* <p>
* The {@link HttpChannel} is an {@link Interceptor} and is always the
* last link in any Interceptor chain.
* <p>
* Responses are committed by the first call to
* {@link #write(ByteBuffer, boolean, Callback)}
* and closed by a call to {@link #write(ByteBuffer, boolean, Callback)}
* with the last boolean set true. If no content is available to commit
* or close, then a null buffer is passed.
*/
public interface Interceptor
{
/**
* Write content.
* The response is committed by the first call to write and is closed by
* a call with last == true. Empty content buffers may be passed to
* force a commit or close.
*
* @param content The content to be written or an empty buffer.
* @param last True if this is the last call to write
* @param callback The callback to use to indicate {@link Callback#succeeded()}
* or {@link Callback#failed(Throwable)}.
*/
void write(ByteBuffer content, boolean last, Callback callback);
/**
* @return The next Interceptor in the chain or null if this is the
* last Interceptor in the chain.
*/
Interceptor getNextInterceptor();
/**
* @return True if the Interceptor is optimized to receive direct
* {@link ByteBuffer}s in the {@link #write(ByteBuffer, boolean, Callback)}
* method. If false is returned, then passing direct buffers may cause
* inefficiencies.
*/
boolean isOptimizedForDirectBuffers();
/**
* Reset the buffers.
* <p>If the Interceptor contains buffers then reset them.
*
* @throws IllegalStateException Thrown if the response has been
* committed and buffers and/or headers cannot be reset.
*/
default void resetBuffer() throws IllegalStateException
{
Interceptor next = getNextInterceptor();
if (next != null)
next.resetBuffer();
}
}
private static Logger LOG = Log.getLogger(HttpOutput.class);
private static final ThreadLocal<CharsetEncoder> _encoder = new ThreadLocal<>();
private final HttpChannel _channel;
private final HttpChannelState _channelState;
private final SharedBlockingCallback _writeBlocker;
private ApiState _apiState = ApiState.BLOCKING;
private State _state = State.OPEN;
private boolean _softClose = false;
private Interceptor _interceptor;
private long _written;
private long _flushed;
private long _firstByteTimeStamp = -1;
private ByteBuffer _aggregate;
private int _bufferSize;
private int _commitSize;
private WriteListener _writeListener;
private volatile Throwable _onError;
private Callback _closedCallback;
public HttpOutput(HttpChannel channel)
{
_channel = channel;
_channelState = channel.getState();
_interceptor = channel;
_writeBlocker = new WriteBlocker(channel);
HttpConfiguration config = channel.getHttpConfiguration();
_bufferSize = config.getOutputBufferSize();
_commitSize = config.getOutputAggregationSize();
if (_commitSize > _bufferSize)
{
LOG.warn("OutputAggregationSize {} exceeds bufferSize {}", _commitSize, _bufferSize);
_commitSize = _bufferSize;
}
}
public HttpChannel getHttpChannel()
{
return _channel;
}
public Interceptor getInterceptor()
{
return _interceptor;
}
public void setInterceptor(Interceptor interceptor)
{
_interceptor = interceptor;
}
public boolean isWritten()
{
return _written > 0;
}
public long getWritten()
{
return _written;
}
public void reopen()
{
synchronized (_channelState)
{
_softClose = false;
}
}
protected Blocker acquireWriteBlockingCallback() throws IOException
{
return _writeBlocker.acquire();
}
private void channelWrite(ByteBuffer content, boolean complete) throws IOException
{
try (Blocker blocker = _writeBlocker.acquire())
{
channelWrite(content, complete, blocker);
blocker.block();
}
}
private void channelWrite(ByteBuffer content, boolean last, Callback callback)
{
if (_firstByteTimeStamp == -1)
{
long minDataRate = getHttpChannel().getHttpConfiguration().getMinResponseDataRate();
if (minDataRate > 0)
_firstByteTimeStamp = System.nanoTime();
else
_firstByteTimeStamp = Long.MAX_VALUE;
}
_interceptor.write(content, last, callback);
}
private void onWriteComplete(boolean last, Throwable failure)
{
String state = null;
boolean wake = false;
Callback closedCallback = null;
ByteBuffer closeContent = null;
synchronized (_channelState)
{
if (LOG.isDebugEnabled())
state = stateString();
// Transition to CLOSED state if we were the last write or we have failed
if (last || failure != null)
{
_state = State.CLOSED;
closedCallback = _closedCallback;
_closedCallback = null;
releaseBuffer(failure);
wake = updateApiState(failure);
}
else if (_state == State.CLOSE)
{
// Somebody called close or complete while we were writing.
// We can now send a (probably empty) last buffer and then when it completes
// onWriteComplete will be called again to actually execute the _completeCallback
_state = State.CLOSING;
closeContent = BufferUtil.hasContent(_aggregate) ? _aggregate : BufferUtil.EMPTY_BUFFER;
}
else
{
wake = updateApiState(null);
}
}
if (LOG.isDebugEnabled())
LOG.debug("onWriteComplete({},{}) {}->{} c={} cb={} w={}",
last, failure, state, stateString(), BufferUtil.toDetailString(closeContent), closedCallback, wake);
try
{
if (failure != null)
_channel.abort(failure);
if (closedCallback != null)
{
if (failure == null)
closedCallback.succeeded();
else
closedCallback.failed(failure);
}
else if (closeContent != null)
{
channelWrite(closeContent, true, new WriteCompleteCB());
}
}
finally
{
if (wake)
_channel.execute(_channel); // TODO review in jetty-10 if execute is needed
}
}
private boolean updateApiState(Throwable failure)
{
boolean wake = false;
switch (_apiState)
{
case BLOCKED:
_apiState = ApiState.BLOCKING;
break;
case PENDING:
_apiState = ApiState.ASYNC;
if (failure != null)
{
_onError = failure;
wake = _channelState.onWritePossible();
}
break;
case UNREADY:
_apiState = ApiState.READY;
if (failure != null)
_onError = failure;
wake = _channelState.onWritePossible();
break;
default:
if (_state == State.CLOSED)
break;
throw new IllegalStateException(stateString());
}
return wake;
}
private int maximizeAggregateSpace()
{
// If no aggregate, we can allocate one of bufferSize
if (_aggregate == null)
return getBufferSize();
// compact to maximize space
BufferUtil.compact(_aggregate);
return BufferUtil.space(_aggregate);
}
public void softClose()
{
synchronized (_channelState)
{
_softClose = true;
}
}
public void complete(Callback callback)
{
// This method is invoked for the COMPLETE action handling in
// HttpChannel.handle. The callback passed typically will call completed
// to finish the request cycle and so may need to asynchronously wait for:
// a pending/blocked operation to finish and then either an async close or
// wait for an application close to complete.
boolean succeeded = false;
Throwable error = null;
ByteBuffer content = null;
synchronized (_channelState)
{
// First check the API state for any unrecoverable situations
switch (_apiState)
{
case UNREADY: // isReady() has returned false so a call to onWritePossible may happen at any time
error = new CancellationException("Completed whilst write unready");
break;
case PENDING: // an async write is pending and may complete at any time
// If this is not the last write, then we must abort
if (!_channel.getResponse().isContentComplete(_written))
error = new CancellationException("Completed whilst write pending");
break;
case BLOCKED: // another thread is blocked in a write or a close
error = new CancellationException("Completed whilst write blocked");
break;
default:
break;
}
// If we can't complete due to the API state, then abort
if (error != null)
{
_channel.abort(error);
_writeBlocker.fail(error);
_state = State.CLOSED;
}
else
{
// Otherwise check the output state to determine how to complete
switch (_state)
{
case CLOSED:
succeeded = true;
break;
case CLOSE:
case CLOSING:
_closedCallback = Callback.combine(_closedCallback, callback);
break;
case OPEN:
if (_onError != null)
{
error = _onError;
break;
}
_closedCallback = Callback.combine(_closedCallback, callback);
switch (_apiState)
{
case BLOCKING:
// Output is idle blocking state, but we still do an async close
_apiState = ApiState.BLOCKED;
_state = State.CLOSING;
content = BufferUtil.hasContent(_aggregate) ? _aggregate : BufferUtil.EMPTY_BUFFER;
break;
case ASYNC:
case READY:
// Output is idle in async state, so we can do an async close
_apiState = ApiState.PENDING;
_state = State.CLOSING;
content = BufferUtil.hasContent(_aggregate) ? _aggregate : BufferUtil.EMPTY_BUFFER;
break;
case UNREADY:
case PENDING:
// An operation is in progress, so we soft close now
_softClose = true;
// then trigger a close from onWriteComplete
_state = State.CLOSE;
break;
default:
throw new IllegalStateException();
}
break;
}
}
}
if (LOG.isDebugEnabled())
LOG.debug("complete({}) {} s={} e={}, c={}", callback, stateString(), succeeded, error, BufferUtil.toDetailString(content));
if (succeeded)
{
callback.succeeded();
return;
}
if (error != null)
{
callback.failed(error);
return;
}
if (content != null)
channelWrite(content, true, new WriteCompleteCB());
}
/**
* Called to indicate that the request cycle has been completed.
*/
public void completed(Throwable failure)
{
synchronized (_channelState)
{
_state = State.CLOSED;
releaseBuffer(failure);
}
}
@Override
public void close() throws IOException
{
ByteBuffer content = null;
Blocker blocker = null;
synchronized (_channelState)
{
if (_onError != null)
{
if (_onError instanceof IOException)
throw (IOException)_onError;
if (_onError instanceof RuntimeException)
throw (RuntimeException)_onError;
if (_onError instanceof Error)
throw (Error)_onError;
throw new IOException(_onError);
}
switch (_state)
{
case CLOSED:
break;
case CLOSE:
case CLOSING:
switch (_apiState)
{
case BLOCKING:
case BLOCKED:
// block until CLOSED state reached.
blocker = _writeBlocker.acquire();
_closedCallback = Callback.combine(_closedCallback, blocker);
break;
default:
// async close with no callback, so nothing to do
break;
}
break;
case OPEN:
switch (_apiState)
{
case BLOCKING:
// Output is idle blocking state, but we still do an async close
_apiState = ApiState.BLOCKED;
_state = State.CLOSING;
blocker = _writeBlocker.acquire();
content = BufferUtil.hasContent(_aggregate) ? _aggregate : BufferUtil.EMPTY_BUFFER;
break;
case BLOCKED:
// An blocking operation is in progress, so we soft close now
_softClose = true;
// then trigger a close from onWriteComplete
_state = State.CLOSE;
// and block until it is complete
blocker = _writeBlocker.acquire();
_closedCallback = Callback.combine(_closedCallback, blocker);
break;
case ASYNC:
case READY:
// Output is idle in async state, so we can do an async close
_apiState = ApiState.PENDING;
_state = State.CLOSING;
content = BufferUtil.hasContent(_aggregate) ? _aggregate : BufferUtil.EMPTY_BUFFER;
break;
case UNREADY:
case PENDING:
// An async operation is in progress, so we soft close now
_softClose = true;
// then trigger a close from onWriteComplete
_state = State.CLOSE;
break;
}
break;
}
}
if (LOG.isDebugEnabled())
LOG.debug("close() {} c={} b={}", stateString(), BufferUtil.toDetailString(content), blocker);
if (content == null)
{
if (blocker == null)
// nothing to do or block for.
return;
// Just wait for some other close to finish.
try (Blocker b = blocker)
{
b.block();
}
}
else
{
if (blocker == null)
{
// Do an async close
channelWrite(content, true, new WriteCompleteCB());
}
else
{
// Do a blocking close
try (Blocker b = blocker)
{
channelWrite(content, true, blocker);
b.block();
onWriteComplete(true, null);
}
catch (Throwable t)
{
onWriteComplete(true, t);
throw t;
}
}
}
}
public ByteBuffer getBuffer()
{
synchronized (_channelState)
{
return acquireBuffer();
}
}
private ByteBuffer acquireBuffer()
{
if (_aggregate == null)
_aggregate = _channel.getByteBufferPool().acquire(getBufferSize(), _interceptor.isOptimizedForDirectBuffers());
return _aggregate;
}
private void releaseBuffer(Throwable failure)
{
if (_aggregate != null)
{
ByteBufferPool bufferPool = _channel.getConnector().getByteBufferPool();
if (failure == null)
bufferPool.release(_aggregate);
else
bufferPool.remove(_aggregate);
_aggregate = null;
}
}
public boolean isClosed()
{
synchronized (_channelState)
{
return _softClose || (_state != State.OPEN);
}
}
public boolean isAsync()
{
synchronized (_channelState)
{
switch (_apiState)
{
case ASYNC:
case READY:
case PENDING:
case UNREADY:
return true;
default:
return false;
}
}
}
@Override
public void flush() throws IOException
{
ByteBuffer content = null;
synchronized (_channelState)
{
switch (_state)
{
case CLOSED:
case CLOSING:
return;
default:
{
switch (_apiState)
{
case BLOCKING:
_apiState = ApiState.BLOCKED;
content = BufferUtil.hasContent(_aggregate) ? _aggregate : BufferUtil.EMPTY_BUFFER;
break;
case ASYNC:
case PENDING:
throw new IllegalStateException("isReady() not called: " + stateString());
case READY:
_apiState = ApiState.PENDING;
break;
case UNREADY:
throw new WritePendingException();
default:
throw new IllegalStateException(stateString());
}
}
}
}
if (content == null)
new AsyncFlush(false).iterate();
else
{
try
{
channelWrite(content, false);
onWriteComplete(false, null);
}
catch (Throwable t)
{
onWriteComplete(false, t);
throw t;
}
}
}
private void checkWritable() throws EofException
{
if (_softClose)
throw new EofException("Closed");
switch (_state)
{
case CLOSED:
case CLOSING:
throw new EofException("Closed");
default:
break;
}
if (_onError != null)
throw new EofException(_onError);
}
@Override
public void write(byte[] b, int off, int len) throws IOException
{
if (LOG.isDebugEnabled())
LOG.debug("write(array {})", BufferUtil.toDetailString(ByteBuffer.wrap(b, off, len)));
boolean last;
boolean aggregate;
boolean flush;
// Async or Blocking ?
boolean async;
synchronized (_channelState)
{
checkWritable();
long written = _written + len;
int space = maximizeAggregateSpace();
last = _channel.getResponse().isAllContentWritten(written);
// Write will be aggregated if:
// + it is smaller than the commitSize
// + is not the last one, or is last but will fit in an already allocated aggregate buffer.
aggregate = len <= _commitSize && (!last || BufferUtil.hasContent(_aggregate) && len <= space);
flush = last || !aggregate || len >= space;
if (last && _state == State.OPEN)
_state = State.CLOSING;
switch (_apiState)
{
case BLOCKING:
_apiState = flush ? ApiState.BLOCKED : ApiState.BLOCKING;
async = false;
break;
case ASYNC:
throw new IllegalStateException("isReady() not called: " + stateString());
case READY:
async = true;
_apiState = flush ? ApiState.PENDING : ApiState.ASYNC;
break;
case PENDING:
case UNREADY:
throw new WritePendingException();
default:
throw new IllegalStateException(stateString());
}
_written = written;
// Should we aggregate?
if (aggregate)
{
acquireBuffer();
int filled = BufferUtil.fill(_aggregate, b, off, len);
// return if we are not complete, not full and filled all the content
if (!flush)
{
if (LOG.isDebugEnabled())
LOG.debug("write(array) {} aggregated !flush {}",
stateString(), BufferUtil.toDetailString(_aggregate));
return;
}
// adjust offset/length
off += filled;
len -= filled;
}
}
if (LOG.isDebugEnabled())
LOG.debug("write(array) {} last={} agg={} flush=true async={}, len={} {}",
stateString(), last, aggregate, async, len, BufferUtil.toDetailString(_aggregate));
if (async)
{
// Do the asynchronous writing from the callback
new AsyncWrite(b, off, len, last).iterate();
return;
}
// Blocking write
try
{
// flush any content from the aggregate
if (BufferUtil.hasContent(_aggregate))
{
channelWrite(_aggregate, last && len == 0);
// should we fill aggregate again from the buffer?
if (len > 0 && !last && len <= _commitSize && len <= maximizeAggregateSpace())
{
BufferUtil.append(_aggregate, b, off, len);
onWriteComplete(false, null);
return;
}
}
// write any remaining content in the buffer directly
if (len > 0)
{
// write a buffer capacity at a time to avoid JVM pooling large direct buffers
// http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6210541
ByteBuffer view = ByteBuffer.wrap(b, off, len);
while (len > getBufferSize())
{
int p = view.position();
int l = p + getBufferSize();
view.limit(l);
channelWrite(view, false);
view.limit(p + len);
view.position(l);
len -= getBufferSize();
}
channelWrite(view, last);
}
else if (last)
{
channelWrite(BufferUtil.EMPTY_BUFFER, true);
}
onWriteComplete(last, null);
}
catch (Throwable t)
{
onWriteComplete(last, t);
throw t;
}
}
public void write(ByteBuffer buffer) throws IOException
{
// This write always bypasses aggregate buffer
int len = BufferUtil.length(buffer);
boolean flush;
boolean last;
// Async or Blocking ?
boolean async;
synchronized (_channelState)
{
checkWritable();
long written = _written + len;
last = _channel.getResponse().isAllContentWritten(_written);
flush = last || len > 0 || BufferUtil.hasContent(_aggregate);
if (last && _state == State.OPEN)
_state = State.CLOSING;
switch (_apiState)
{
case BLOCKING:
async = false;
_apiState = flush ? ApiState.BLOCKED : ApiState.BLOCKING;
break;
case ASYNC:
throw new IllegalStateException("isReady() not called: " + stateString());
case READY:
async = true;
_apiState = flush ? ApiState.PENDING : ApiState.ASYNC;
break;
case PENDING:
case UNREADY:
throw new WritePendingException();
default:
throw new IllegalStateException(stateString());
}
_written = written;
}
if (!flush)
return;
if (async)
{
new AsyncWrite(buffer, last).iterate();
}
else
{
try
{
// Blocking write
// flush any content from the aggregate
if (BufferUtil.hasContent(_aggregate))
channelWrite(_aggregate, last && len == 0);
// write any remaining content in the buffer directly
if (len > 0)
channelWrite(buffer, last);
else if (last)
channelWrite(BufferUtil.EMPTY_BUFFER, true);
onWriteComplete(last, null);
}
catch (Throwable t)
{
onWriteComplete(last, t);
throw t;
}
}
}
@Override
public void write(int b) throws IOException
{
boolean flush;
boolean last;
// Async or Blocking ?
boolean async = false;
synchronized (_channelState)
{
checkWritable();
long written = _written + 1;