11package io .avaje .jex .core ;
22
33import java .io .ByteArrayOutputStream ;
4+ import java .io .FilterOutputStream ;
45import java .io .IOException ;
5- import java .io .OutputStream ;
66
7- import com .sun .net .httpserver .HttpExchange ;
8-
9- final class BufferedOutStream extends OutputStream {
7+ final class BufferedOutStream extends FilterOutputStream {
108
119 private final long max ;
1210 private final JdkContext context ;
1311 private ByteArrayOutputStream buffer ;
14- private OutputStream stream ;
12+ private boolean jdkOutput ;
1513 private long count ;
1614
1715 BufferedOutStream (JdkContext context , int initial , long max ) {
16+ super (context .exchange ().getResponseBody ());
1817 this .context = context ;
1918 this .max = max ;
2019
@@ -28,12 +27,12 @@ final class BufferedOutStream extends OutputStream {
2827
2928 @ Override
3029 public void write (int b ) throws IOException {
31- if (stream != null ) {
32- stream .write (b );
30+ if (jdkOutput ) {
31+ out .write (b );
3332 } else {
3433 if (count ++ > max ) {
3534 useJdkOutput ();
36- stream .write (b );
35+ out .write (b );
3736 return ;
3837 }
3938 buffer .write (b );
@@ -42,37 +41,35 @@ public void write(int b) throws IOException {
4241
4342 @ Override
4443 public void write (byte [] b , int off , int len ) throws IOException {
45- if (stream != null ) {
46- stream .write (b , off , len );
44+ if (jdkOutput ) {
45+ out .write (b , off , len );
4746 } else {
4847 count += len ;
4948 if (count > max ) {
5049 useJdkOutput ();
51- stream .write (b , off , len );
50+ out .write (b , off , len );
5251 return ;
5352 }
5453 buffer .write (b , off , len );
5554 }
5655 }
5756
58- /** Use the underlying HttpExchange . Chunking the response if needed */
57+ /** Use the underlying OutputStream . Chunking the response if needed */
5958 private void useJdkOutput () throws IOException {
60- final HttpExchange exchange = context .exchange ();
6159 // if a manual content-length is set, honor that instead of chunking
62- String length = context .responseHeader (Constants .CONTENT_LENGTH );
63- exchange .sendResponseHeaders (context .statusCode (), length == null ? 0 : Long .parseLong (length ));
64- stream = exchange . getResponseBody () ;
60+ var length = context .responseHeader (Constants .CONTENT_LENGTH );
61+ context . exchange () .sendResponseHeaders (context .statusCode (), length == null ? 0 : Long .parseLong (length ));
62+ jdkOutput = true ;
6563 // empty the existing buffer
6664 if (buffer != null ) {
67- buffer .writeTo (stream );
68- buffer = null ;
65+ buffer .writeTo (out );
6966 }
7067 }
7168
7269 @ Override
7370 public void close () throws IOException {
74- if (stream != null ) {
75- stream .close ();
71+ if (jdkOutput ) {
72+ out .close ();
7673 } else {
7774 context .write (buffer .toByteArray ());
7875 }
0 commit comments