1 2 package org.apache.roller.util.cache; 3 4 import java.io.ByteArrayOutputStream ; 5 import java.io.IOException ; 6 import java.io.OutputStreamWriter ; 7 import java.io.PrintWriter ; 8 import java.io.Serializable ; 9 import java.io.UnsupportedEncodingException ; 10 import org.apache.commons.logging.Log; 11 import org.apache.commons.logging.LogFactory; 12 13 14 17 public class CachedContent implements Serializable { 18 19 private static Log log = LogFactory.getLog(CachedContent.class); 20 21 public static final int DEFAULT_SIZE = 8192; 23 24 private byte[] content = new byte[0]; 26 27 private String contentType = null; 29 30 private transient ByteArrayOutputStream outstream = null; 32 33 private transient PrintWriter cachedWriter = null; 35 36 37 public CachedContent(int size) { 38 39 if(size > 0) { 41 this.outstream = new ByteArrayOutputStream (size); 42 } else { 43 this.outstream = new ByteArrayOutputStream (DEFAULT_SIZE); 44 } 45 46 try { 48 this.cachedWriter = 49 new PrintWriter (new OutputStreamWriter (this.outstream, "UTF-8")); 50 } catch(UnsupportedEncodingException e) { 51 throw new RuntimeException ("Encoding problem", e); 53 } 54 } 55 56 public CachedContent(int size, String contentType) { 57 this(size); 58 this.contentType = contentType; 59 } 60 61 62 69 public byte[] getContent() { 70 return this.content; 71 } 72 73 74 80 public String getContentAsString() { 81 try { 82 return new String (this.content,"UTF-8"); 83 } catch (UnsupportedEncodingException uex) { 84 throw new RuntimeException (uex); 86 } 87 } 88 89 90 public PrintWriter getCachedWriter() { 91 return cachedWriter; 92 } 93 94 95 public String getContentType() { 96 return contentType; 97 } 98 99 100 106 public void flush() { 107 108 if(this.outstream == null) { 109 throw new IllegalStateException ("Cannot flush() after a close()!"); 110 } 111 112 this.cachedWriter.flush(); 113 this.content = this.outstream.toByteArray(); 114 115 log.debug("FLUSHED "+this.content.length); 116 } 117 118 119 122 public void close() throws IOException { 123 124 if(this.cachedWriter != null) { 125 this.cachedWriter.flush(); 126 this.cachedWriter.close(); 127 this.cachedWriter = null; 128 } 129 130 if(this.outstream != null) { 131 this.content = this.outstream.toByteArray(); 132 this.outstream.close(); 133 this.outstream = null; 134 } 135 136 log.debug("CLOSED"); 137 } 138 139 } 140 | Popular Tags |