/
HttpOutput.java
1586 lines (1405 loc) · 47.1 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-2019 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.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.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.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.IteratingNestedCallback;
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);
/* TODO UPDATE!!!
ACTION OPEN ASYNC READY PENDING UNREADY CLOSING CLOSED
--------------------------------------------------------------------------------------------------
setWriteListener() READY->owp ise ise ise ise ise ise
write() OPEN ise PENDING wpe wpe eof eof
flush() OPEN ise PENDING wpe wpe eof eof
close() CLOSING CLOSING CLOSING CLOSED CLOSED CLOSING CLOSED
isReady() OPEN:true READY:true READY:true UNREADY:false UNREADY:false CLOSED:true CLOSED:true
write completed - - - ASYNC READY->owp CLOSED -
*/
enum State
{
OPEN, // Open in blocking mode
ASYNC, // Open in async mode
READY, // isReady() has returned true
PENDING, // write operating in progress
UNREADY, // write operating in progress, isReady has returned false
ERROR, // An error has occured
CLOSING, // Asynchronous close in progress
CLOSED // Closed
}
/**
* 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 State _state = State.OPEN;
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 _closeCallback;
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)
{
_state = State.OPEN;
}
}
private boolean isLastContentToWrite(int len)
{
_written += len;
return _channel.getResponse().isAllContentWritten(_written);
}
public boolean isAllContentWritten()
{
return _channel.getResponse().isAllContentWritten(_written);
}
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();
if (complete)
closed();
}
catch (Throwable failure)
{
if (LOG.isDebugEnabled())
LOG.debug(failure);
abort(failure);
throw failure;
}
}
protected void channelWrite(ByteBuffer content, boolean complete, Callback callback)
{
if (_firstByteTimeStamp == -1)
{
long minDataRate = getHttpChannel().getHttpConfiguration().getMinResponseDataRate();
if (minDataRate > 0)
_firstByteTimeStamp = System.nanoTime();
else
_firstByteTimeStamp = Long.MAX_VALUE;
}
_interceptor.write(content, complete, callback);
}
private void abort(Throwable failure)
{
closed();
_channel.abort(failure);
}
public void closedBySendError()
{
synchronized (_channelState)
{
switch (_state)
{
case OPEN:
case READY:
case ASYNC:
_state = State.CLOSED;
return;
default:
throw new IllegalStateException(_state.toString());
}
}
}
public void close(Callback callback)
{
synchronized (_channelState)
{
switch (_state)
{
case CLOSED:
callback.succeeded();
return;
case ERROR:
// TODO is this right?
Callback cb = Callback.combine(_closeCallback, callback);
_closeCallback = null;
cb.failed(_onError);
_state = State.CLOSED;
return;
case CLOSING: // Close already initiated, so just add callback
case PENDING: // Add the callback and close when write is complete.
case UNREADY: // Add the callback and close when write is complete.
// Let's just add the callback so it get's noticed once write is possible.
_closeCallback = Callback.combine(_closeCallback, callback);
return;
default:
_state = State.CLOSING;
_closeCallback = Callback.combine(_closeCallback, callback);
}
}
ByteBuffer content = BufferUtil.hasContent(_aggregate) ? _aggregate : BufferUtil.EMPTY_BUFFER;
channelWrite(content, !_channel.getResponse().isIncluding(), new Callback()
{
@Override
public void succeeded()
{
callback().succeeded();
}
@Override
public void failed(Throwable x)
{
callback().failed(x);
}
public Callback callback()
{
Callback closeCallback;
synchronized (_channelState)
{
_state = State.CLOSED;
closeCallback = _closeCallback;
_closeCallback = null;
}
return closeCallback == null ? Callback.NOOP : closeCallback;
}
});
}
@Override
public void close() throws IOException
{
try (Blocker blocker = _writeBlocker.acquire())
{
close(blocker);
blocker.block();
}
catch (Throwable failure)
{
if (LOG.isDebugEnabled())
LOG.debug(failure);
abort(failure);
throw failure;
}
}
/**
* Called to indicate that the last write has been performed.
* It updates the state and performs cleanup operations.
*/
public void closed()
{
synchronized (_channelState)
{
switch (_state)
{
case CLOSED:
{
break;
}
case UNREADY:
{
_state = State.ERROR;
if (_onError == null)
_onError = new EofException("Async closed");
releaseBuffer();
break;
}
default:
{
_state = State.CLOSED;
releaseBuffer();
}
}
}
}
public ByteBuffer getBuffer()
{
return _aggregate;
}
public ByteBuffer acquireBuffer()
{
if (_aggregate == null)
_aggregate = _channel.getByteBufferPool().acquire(getBufferSize(), _interceptor.isOptimizedForDirectBuffers());
return _aggregate;
}
private void releaseBuffer()
{
if (_aggregate != null)
{
_channel.getConnector().getByteBufferPool().release(_aggregate);
_aggregate = null;
}
}
public boolean isClosed()
{
synchronized (_channelState)
{
switch (_state)
{
case CLOSING:
case CLOSED:
return true;
default:
return false;
}
}
}
public boolean isAsync()
{
synchronized (_channelState)
{
switch (_state)
{
case ASYNC:
case READY:
case PENDING:
case UNREADY:
return true;
default:
return false;
}
}
}
@Override
public void flush() throws IOException
{
synchronized (_channelState)
{
switch (_state)
{
case OPEN:
channelWrite(BufferUtil.hasContent(_aggregate) ? _aggregate : BufferUtil.EMPTY_BUFFER, false);
return;
case ASYNC:
throw new IllegalStateException("isReady() not called");
case READY:
_state = State.PENDING;
new AsyncFlush().iterate();
return;
case UNREADY:
throw new WritePendingException();
case ERROR:
throw new EofException(_onError);
case PENDING:
case CLOSING:
case CLOSED:
return;
default:
throw new IllegalStateException(_state.toString());
}
}
}
@Override
public void write(byte[] b, int off, int len) throws IOException
{
boolean last;
boolean aggregate;
boolean flush;
// Async or Blocking ?
boolean async = false;
synchronized (_channelState)
{
long written = _written + len;
int space = _aggregate == null ? getBufferSize() : BufferUtil.space(_aggregate);
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;
switch (_state)
{
case OPEN:
// process blocking write below
break;
case ASYNC:
throw new IllegalStateException("isReady() not called");
case READY:
async = true;
_state = flush ? State.PENDING : State.ASYNC;
break;
case PENDING:
case UNREADY:
throw new WritePendingException();
case ERROR:
throw new EofException(_onError);
case CLOSING:
case CLOSED:
throw new EofException("Closed");
default:
throw new IllegalStateException(_state.toString());
}
_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)
return;
// adjust offset/length
off += filled;
len -= filled;
}
if (async)
{
// Do the asynchronous writing from the callback
new AsyncWrite(b, off, len, last).iterate();
return;
}
// 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 <= BufferUtil.space(_aggregate))
{
BufferUtil.append(_aggregate, b, off, len);
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);
}
}
public void write(ByteBuffer buffer) throws IOException
{
// This write always bypasses aggregate buffer
int len = BufferUtil.length(buffer);
boolean last;
// Async or Blocking ?
boolean async = false;
synchronized (_channelState)
{
long written = _written + len;
last = _channel.getResponse().isAllContentWritten(_written);
switch (_state)
{
case OPEN:
break;
case ASYNC:
throw new IllegalStateException("isReady() not called");
case READY:
async = true;
_state = State.PENDING;
break;
case PENDING:
case UNREADY:
throw new WritePendingException();
case ERROR:
throw new EofException(_onError);
case CLOSING:
case CLOSED:
throw new EofException("Closed");
default:
throw new IllegalStateException(_state.toString());
}
_written = written;
}
if (async)
{
new AsyncWrite(buffer, last).iterate();
}
else
{
// 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);
}
}
@Override
public void write(int b) throws IOException
{
boolean flush;
boolean last;
// Async or Blocking ?
boolean async = false;
synchronized (_channelState)
{
long written = _written + 1;
int space = _aggregate == null ? getBufferSize() : BufferUtil.space(_aggregate);
last = _channel.getResponse().isAllContentWritten(written);
flush = last || space == 1;
switch (_state)
{
case OPEN:
break;
case ASYNC:
throw new IllegalStateException("isReady() not called");
case READY:
async = true;
_state = flush ? State.PENDING : State.ASYNC;
break;
case PENDING:
case UNREADY:
throw new WritePendingException();
case ERROR:
throw new EofException(_onError);
case CLOSING:
case CLOSED:
throw new EofException("Closed");
default:
throw new IllegalStateException();
}
_written = written;
}
acquireBuffer();
BufferUtil.append(_aggregate, (byte)b);
// Check if all written or full
if (!flush)
return;
if (async)
// Do the asynchronous writing from the callback
new AsyncFlush().iterate();
else
channelWrite(_aggregate, last);
}
@Override
public void print(String s) throws IOException
{
print(s, false);
}
@Override
public void println(String s) throws IOException
{
print(s, true);
}
private void print(String s, boolean eoln) throws IOException
{
if (isClosed())
throw new IOException("Closed");
String charset = _channel.getResponse().getCharacterEncoding();
CharsetEncoder encoder = _encoder.get();
if (encoder == null || !encoder.charset().name().equalsIgnoreCase(charset))
{
encoder = Charset.forName(charset).newEncoder();
encoder.onMalformedInput(CodingErrorAction.REPLACE);
encoder.onUnmappableCharacter(CodingErrorAction.REPLACE);
_encoder.set(encoder);
}
else
{
encoder.reset();
}
CharBuffer in = CharBuffer.wrap(s);
CharBuffer crlf = eoln ? CharBuffer.wrap("\r\n") : null;
ByteBuffer out = getHttpChannel().getByteBufferPool().acquire((int)(1 + (s.length() + 2) * encoder.averageBytesPerChar()), false);
BufferUtil.flipToFill(out);
for (; ; )
{
CoderResult result;
if (in.hasRemaining())
{
result = encoder.encode(in, out, crlf == null);
if (result.isUnderflow())
if (crlf == null)
break;
else
continue;
}
else if (crlf != null && crlf.hasRemaining())
{
result = encoder.encode(crlf, out, true);
if (result.isUnderflow())
{
if (!encoder.flush(out).isUnderflow())
result.throwException();
break;
}
}
else
break;
if (result.isOverflow())
{
BufferUtil.flipToFlush(out, 0);
ByteBuffer bigger = BufferUtil.ensureCapacity(out, out.capacity() + s.length() + 2);
getHttpChannel().getByteBufferPool().release(out);
BufferUtil.flipToFill(bigger);
out = bigger;
continue;
}
result.throwException();
}
BufferUtil.flipToFlush(out, 0);
write(out.array(), out.arrayOffset(), out.remaining());
getHttpChannel().getByteBufferPool().release(out);
}
@Override
public void println(boolean b) throws IOException
{
println(lStrings.getString(b ? "value.true" : "value.false"));
}
@Override
public void println(char c) throws IOException
{
println(String.valueOf(c));
}
@Override
public void println(int i) throws IOException
{
println(String.valueOf(i));
}
@Override
public void println(long l) throws IOException
{
println(String.valueOf(l));
}
@Override
public void println(float f) throws IOException
{
println(String.valueOf(f));
}
@Override
public void println(double d) throws IOException
{
println(String.valueOf(d));
}
/**
* Blocking send of whole content.
*
* @param content The whole content to send
* @throws IOException if the send fails
*/
public void sendContent(ByteBuffer content) throws IOException
{
if (LOG.isDebugEnabled())
LOG.debug("sendContent({})", BufferUtil.toDetailString(content));
_written += content.remaining();
channelWrite(content, true);
}
/**
* Blocking send of stream content.
*
* @param in The stream content to send
* @throws IOException if the send fails
*/
public void sendContent(InputStream in) throws IOException
{
try (Blocker blocker = _writeBlocker.acquire())
{
new InputStreamWritingCB(in, blocker).iterate();
blocker.block();
}
catch (Throwable failure)
{
if (LOG.isDebugEnabled())
LOG.debug(failure);
abort(failure);
throw failure;
}
}
/**
* Blocking send of channel content.
*
* @param in The channel content to send
* @throws IOException if the send fails
*/
public void sendContent(ReadableByteChannel in) throws IOException
{
try (Blocker blocker = _writeBlocker.acquire())
{
new ReadableByteChannelWritingCB(in, blocker).iterate();
blocker.block();
}
catch (Throwable failure)
{
if (LOG.isDebugEnabled())
LOG.debug(failure);
abort(failure);
throw failure;
}
}
/**
* Blocking send of HTTP content.
*
* @param content The HTTP content to send
* @throws IOException if the send fails
*/
public void sendContent(HttpContent content) throws IOException
{
try (Blocker blocker = _writeBlocker.acquire())
{
sendContent(content, blocker);
blocker.block();
}
catch (Throwable failure)
{
if (LOG.isDebugEnabled())
LOG.debug(failure);
abort(failure);
throw failure;
}
}
/**
* Asynchronous send of whole content.
*
* @param content The whole content to send
* @param callback The callback to use to notify success or failure
*/
public void sendContent(ByteBuffer content, final Callback callback)
{
if (LOG.isDebugEnabled())
LOG.debug("sendContent(buffer={},{})", BufferUtil.toDetailString(content), callback);
if (!prepareSendContent(content.remaining(), callback))
return;
channelWrite(content, true, new Callback.Nested(callback)
{
@Override
public void succeeded()
{
closed();
super.succeeded();
}
@Override
public void failed(Throwable x)
{
abort(x);
super.failed(x);
}
});
}
/**
* Asynchronous send of stream content.
* The stream will be closed after reading all content.
*
* @param in The stream content to send
* @param callback The callback to use to notify success or failure
*/
public void sendContent(InputStream in, Callback callback)
{
if (LOG.isDebugEnabled())
LOG.debug("sendContent(stream={},{})", in, callback);
if (!prepareSendContent(0, callback))
return;
new InputStreamWritingCB(in, callback).iterate();
}
/**
* Asynchronous send of channel content.
* The channel will be closed after reading all content.
*
* @param in The channel content to send
* @param callback The callback to use to notify success or failure
*/
public void sendContent(ReadableByteChannel in, Callback callback)
{
if (LOG.isDebugEnabled())
LOG.debug("sendContent(channel={},{})", in, callback);
if (!prepareSendContent(0, callback))
return;
new ReadableByteChannelWritingCB(in, callback).iterate();
}
private boolean prepareSendContent(int len, Callback callback)
{
synchronized (_channelState)
{
if (BufferUtil.hasContent(_aggregate))
{
callback.failed(new IOException("cannot sendContent() after write()"));
return false;
}
if (_channel.isCommitted())
{
callback.failed(new IOException("cannot sendContent(), output already committed"));
return false;
}
switch (_state)
{
case OPEN:
_state = State.PENDING;
if (len > 0)
_written += len;
return true;