1 package com.quadcap.http.server22; 2 3 40 41 import java.io.ByteArrayOutputStream ; 42 import java.io.BufferedOutputStream ; 43 import java.io.IOException ; 44 import java.io.OutputStream ; 45 46 import javax.servlet.ServletOutputStream ; 47 48 import com.quadcap.net.server.WorkerOutputStream; 49 50 import com.quadcap.util.Debug; 51 52 68 public class HttpOutputStream extends ServletOutputStream { 69 WorkerOutputStream os; 70 HttpResponse res; 71 ByteArrayOutputStream bos = new ByteArrayOutputStream (); 72 boolean committed = false; 73 boolean autoFlush = true; 74 75 int bufferSize = 32 * 1024; 76 77 83 public void reset(WorkerOutputStream os) { 84 this.os = os; 85 this.bos.reset(); 86 this.committed = false; 87 } 88 89 94 public void write(int b) throws IOException { 95 if (committed) { 96 os.write(b); 97 } else if (bos.size() >= bufferSize) { 98 res.writeHeaders(); 99 bos.writeTo(os); 100 committed = true; 101 os.write(b); 102 } else { 103 bos.write(b); 104 } 105 } 106 107 116 public void write(byte[] buf, int off, int len) throws IOException { 117 if (committed) { 118 os.write(buf, off, len); 119 } else if (bos.size() + len >= bufferSize) { 120 res.writeHeaders(); 121 bos.writeTo(os); 122 committed = true; 123 os.write(buf, off, len); 124 } else { 125 bos.write(buf, off, len); 126 } 127 } 128 129 132 public final void flushBuffered() throws IOException { 133 if (!committed) { 134 int len = bos.size(); 135 if (len > 0) { 136 res.maybeSetContentLength(len); 137 } 138 res.writeHeaders(); 139 bos.writeTo(os); 140 committed = true; 141 } 142 os.flush(); 143 } 144 145 148 public final void flush() throws IOException { 149 flushBuffered(); 150 } 151 152 156 public final void close() throws IOException { 157 flushBuffered(); 158 } 159 160 public final void reallyClose() throws IOException { 161 os.close(); 162 } 163 164 168 public boolean discard() { 169 if (!committed) { 170 bos.reset(); 171 return true; 172 } 173 return false; 174 } 175 176 183 void setResponse(HttpResponse res) { 184 this.res = res; 185 } 186 187 190 WorkerOutputStream getOutputStream() { return os; } 191 192 final void setBufferSize(int size) throws IllegalStateException { 193 if (committed) { 194 throw new IllegalStateException ("Response already committed"); 195 } 196 this.bufferSize = size; 197 } 198 199 final int getBufferSize() { 200 return bufferSize; 201 } 202 203 final boolean isCommitted() { 204 return committed; 205 } 206 207 final void reset() throws IllegalStateException { 208 if (committed) { 209 throw new IllegalStateException ("Response already committed"); 210 } 211 bos.reset(); 212 } 213 214 final boolean getAutoFlush() { 215 return autoFlush; 216 } 217 218 final void setAutoFlush(boolean autoFlush) { 219 this.autoFlush = autoFlush; 220 } 221 222 public int getRemaining() { 223 return bufferSize - bos.size(); 224 } 225 } 226 | Popular Tags |