1 40 41 package org.jahia.services.applications; 42 43 import javax.servlet.ServletOutputStream ; 44 import java.io.ByteArrayOutputStream ; 45 import java.io.IOException ; 46 import java.io.OutputStreamWriter ; 47 import java.io.UnsupportedEncodingException ; 48 49 60 public class StringServletOutputStream extends ServletOutputStream { 61 62 private static org.apache.log4j.Logger logger = 63 org.apache.log4j.Logger.getLogger (StringServletOutputStream.class); 64 65 private ByteArrayOutputStream byteArray = new ByteArrayOutputStream (); 66 private OutputStreamWriter streamWriter; 67 private ServletOutputStream existingStream; 68 private OutputStreamWriter existingStreamWriter; 69 private String encoding; 70 71 public StringServletOutputStream (String encoding) throws UnsupportedEncodingException { 72 super (); 73 this.encoding = encoding; 74 streamWriter = new OutputStreamWriter (byteArray, encoding); 75 } 76 77 public StringServletOutputStream (ServletOutputStream existingStream, String encoding) 78 throws UnsupportedEncodingException { 79 super (); 80 this.existingStream = existingStream; 81 this.encoding = encoding; 82 streamWriter = new OutputStreamWriter (byteArray, encoding); 83 existingStreamWriter = new OutputStreamWriter (existingStream, encoding); 84 } 85 86 201 public void write (char[] cbuf) 202 throws IOException { 203 streamWriter.write (cbuf, 0, cbuf.length); 204 if (existingStream != null) { 205 existingStreamWriter.write (cbuf, 0, cbuf.length); 206 } 207 } 208 209 public void write (char[] cbuf, int off, int len) 210 throws IOException { 211 streamWriter.write (cbuf, off, len); 212 if (existingStream != null) { 213 existingStreamWriter.write (cbuf, off, len); 214 } 215 } 216 217 public void write (int c) 218 throws IOException { 219 byteArray.write (c); 220 if (existingStream != null) { 221 existingStream.write (c); 222 } 223 } 224 225 public void write (String s) 226 throws IOException { 227 streamWriter.write (s); 228 if (existingStream != null) { 229 existingStreamWriter.write (s); 230 } 231 } 232 233 public void write (String str, int off, int len) 234 throws IOException { 235 streamWriter.write (str, off, len); 236 if (existingStream != null) { 237 existingStreamWriter.write (str, off, len); 238 } 239 } 240 241 public String getBuffer () throws UnsupportedEncodingException { 242 return byteArray.toString (encoding); 243 } 244 245 public void flush () 246 throws IOException { 247 if (existingStream != null) { 248 logger.debug ("Flushing pass-through stream..."); 249 existingStreamWriter.flush (); 250 existingStream.flush (); 251 } 252 } 253 254 public void close () { 255 } 256 257 } 258 | Popular Tags |