1 16 package org.apache.myfaces.component.html.util; 17 18 import java.io.ByteArrayInputStream ; 19 import java.io.ByteArrayOutputStream ; 20 import java.io.IOException ; 21 import java.io.OutputStreamWriter ; 22 import java.io.PrintWriter ; 23 import java.io.UnsupportedEncodingException ; 24 import java.nio.charset.Charset ; 25 26 import javax.servlet.ServletOutputStream ; 27 import javax.servlet.http.HttpServletResponse ; 28 import javax.servlet.http.HttpServletResponseWrapper ; 29 30 import org.xml.sax.InputSource ; 31 32 56 public class ExtensionsResponseWrapper extends HttpServletResponseWrapper { 57 private ByteArrayOutputStream stream = null; 58 private PrintWriter printWriter = null; 59 60 public ExtensionsResponseWrapper(HttpServletResponse response){ 61 super( response ); 62 stream = new ByteArrayOutputStream (); 63 } 64 65 66 public byte[] getBytes() { 67 return stream.toByteArray(); 68 } 69 70 public String toString(){ 71 try{ 72 return stream.toString(getCharacterEncoding()); 73 }catch(UnsupportedEncodingException e){ 74 throw new RuntimeException ("Response accepted invalid character encoding " + getCharacterEncoding()); 76 } 77 } 78 79 81 public PrintWriter getWriter(){ 82 if( printWriter == null ){ 83 OutputStreamWriter streamWriter = new OutputStreamWriter (stream, Charset.forName(getCharacterEncoding())); 84 printWriter = new PrintWriter (streamWriter, true); 85 } 87 return printWriter; 88 } 89 90 92 public ServletOutputStream getOutputStream(){ 93 return new MyServletOutputStream( stream ); 94 } 95 96 public InputSource getInputSource(){ 97 ByteArrayInputStream bais = new ByteArrayInputStream ( stream.toByteArray() ); 98 return new InputSource ( bais ); 99 } 100 101 104 public void setContentLength(int contentLength) { 105 } 107 108 public void flushBuffer() throws IOException { 109 stream.flush(); 110 } 111 112 public void finishResponse() { 113 try { 114 if (printWriter != null) { 115 printWriter.close(); 116 } else { 117 if (stream != null) { 118 stream.close(); 119 } 120 } 121 } catch (IOException e) { 122 e.printStackTrace(); 123 } 124 } 125 126 128 private class MyServletOutputStream extends ServletOutputStream { 129 private ByteArrayOutputStream outputStream; 130 131 public MyServletOutputStream(ByteArrayOutputStream outputStream){ 132 this.outputStream = outputStream; 133 } 134 135 public void write(int b){ 136 outputStream.write( b ); 137 } 138 139 public void write(byte[] bytes) throws IOException { 140 outputStream.write( bytes ); 141 } 142 143 public void write(byte[] bytes, int off, int len){ 144 outputStream.write(bytes, off, len); 145 } 146 } 147 } | Popular Tags |