1 package info.magnolia.cms.cache; 2 3 import java.io.ByteArrayOutputStream ; 4 import java.io.IOException ; 5 import java.io.OutputStreamWriter ; 6 import java.io.PrintWriter ; 7 8 import javax.servlet.ServletOutputStream ; 9 import javax.servlet.http.HttpServletResponse ; 10 import javax.servlet.http.HttpServletResponseWrapper ; 11 12 13 17 public class CacheResponseWrapper extends HttpServletResponseWrapper { 18 19 private ByteArrayOutputStream cachingStream; 20 21 private PrintWriter cachingWriter = null; 22 23 private CacheableEntry cacheableEntry; 24 25 private int status = SC_OK; 26 27 public CacheResponseWrapper(HttpServletResponse response) { 28 super(response); 29 } 30 31 public CacheableEntry getCacheableEntry() { 32 if (cachingStream == null) { 33 return null; 34 } 35 cacheableEntry = new CacheableEntry(cachingStream.toByteArray()); 36 cacheableEntry.setContentType(getContentType()); 37 cacheableEntry.setCharacterEncoding(getCharacterEncoding()); 38 return cacheableEntry; 39 } 40 41 44 public ServletOutputStream getOutputStream() throws IOException { 45 cachingStream = new ByteArrayOutputStream (); 46 return new MultiplexServletOutputStream(super.getOutputStream(), cachingStream); 47 } 48 49 public PrintWriter getWriter() throws IOException { 50 if (cachingWriter == null) { 51 String encoding = getCharacterEncoding(); 52 cachingWriter = encoding != null 53 ? new PrintWriter (new OutputStreamWriter (getOutputStream(), encoding)) 54 : new PrintWriter (new OutputStreamWriter (getOutputStream())); 55 } 56 57 return cachingWriter; 58 } 59 60 public void flushBuffer() throws IOException { 61 super.flushBuffer(); 62 63 if (cachingStream != null) { 64 cachingStream.flush(); 65 } 66 67 if (cachingWriter != null) { 68 cachingWriter.flush(); 69 } 70 } 71 72 public int getStatus() { 73 return status; 74 } 75 76 public void setStatus(int status) { 77 super.setStatus(status); 78 this.status = status; 79 } 80 81 public void setStatus(int status, String string) { 82 super.setStatus(status, string); 83 this.status = status; 84 } 85 86 public void sendRedirect(String location) throws IOException { 87 this.status = SC_MOVED_TEMPORARILY; 88 super.sendRedirect(location); 89 } 90 91 public void sendError(int status, String string) throws IOException { 92 super.sendError(status, string); 93 this.status = status; 94 } 95 96 public void sendError(int status) throws IOException { 97 super.sendError(status); 98 this.status = status; 99 } 100 101 public void reset() { 102 super.reset(); 103 if (cachingStream != null) { 104 cachingStream.reset(); 105 } 106 cachingWriter = null; 107 status = SC_OK; 108 } 109 110 public void resetBuffer() { 111 super.reset(); 112 if (cachingStream != null) { 113 cachingStream.reset(); 114 } 115 cachingWriter = null; 116 status = SC_OK; 117 } 118 119 } 120 | Popular Tags |