1 16 package org.apache.cocoon.bean.helpers; 17 18 import java.io.ByteArrayOutputStream ; 19 import java.io.FileNotFoundException ; 20 import java.io.IOException ; 21 import java.io.OutputStream ; 22 23 30 public class DelayedOutputStream extends OutputStream { 31 35 private ByteArrayOutputStream baos; 36 40 private OutputStream fos; 41 42 43 47 public DelayedOutputStream() { 48 baos = new ByteArrayOutputStream (); 49 fos = null; 50 } 51 52 58 public void setFileOutputStream(OutputStream outputStream) throws FileNotFoundException { 59 if (fos == null) { 60 fos = outputStream; 61 } 62 } 63 64 72 public void write(int b) throws IOException { 73 OutputStream os = getTargetOutputStream(); 74 os.write(b); 75 } 76 77 78 86 public void write(byte b[]) throws IOException { 87 OutputStream os = getTargetOutputStream(); 88 os.write(b); 89 } 90 91 92 102 public void write(byte b[], int off, int len) throws IOException { 103 OutputStream os = getTargetOutputStream(); 104 os.write(b, off, len); 105 } 106 107 108 115 public void close() throws IOException { 116 IOException ioexception = null; 117 118 getTargetOutputStream(); 119 120 try { 122 if (baos != null) { 123 baos.close(); 124 } 125 } catch (IOException ioe) { 126 ioexception = ioe; 127 } finally { 128 baos = null; 129 } 130 131 try { 133 if (fos != null) { 134 fos.close(); 135 } 136 } catch (IOException ioe) { 137 if (ioexception == null) { 138 ioexception = ioe; 139 } 140 } finally { 141 fos = null; 142 } 143 144 if (ioexception != null) { 145 throw ioexception; 146 } 147 } 148 149 150 157 public void flush() throws IOException { 158 IOException ioexception = null; 159 160 getTargetOutputStream(); 162 163 try { 165 if (baos != null) { 166 baos.flush(); 167 } 168 } catch (IOException ioe) { 169 ioexception = ioe; 170 } 171 172 try { 174 if (fos != null) { 175 fos.flush(); 176 } 177 } catch (IOException ioe) { 178 if (ioexception == null) { 179 ioexception = ioe; 180 } 181 } 182 if (ioexception != null) { 183 throw ioexception; 184 } 185 } 186 187 188 194 private OutputStream getTargetOutputStream() throws IOException { 195 if (baos != null && fos == null) { 196 197 return baos; 199 } else if (baos != null && fos != null) { 200 try { 202 baos.flush(); 203 baos.writeTo(fos); 204 baos.close(); 205 } finally { 206 baos = null; 207 } 208 209 return fos; 210 } else if (baos == null && fos != null) { 211 return fos; 213 } else { 214 throw new IOException ("No outputstream available!"); 216 } 217 } 218 219 222 public int size() { 223 if (baos != null) { 224 return baos.size(); 225 } 226 return 0; 227 } 228 229 232 public byte[] getContent() { 233 if (baos != null) { 234 return baos.toByteArray(); 235 } else { 236 return null; 237 } 238 } 239 } 240 | Popular Tags |