01: /* Copyright 2001 The JA-SIG Collaborative. All rights reserved.
02: * See license distributed with this file and
03: * available online at http://www.uportal.org/license.html
04: */
05:
06: package org.jasig.portal.serialize;
07:
08: import java.io.ByteArrayOutputStream;
09: import java.io.IOException;
10: import java.io.OutputStream;
11: import java.io.UnsupportedEncodingException;
12:
13: public class CachingOutputStream extends OutputStream implements
14: CharacterCachingWriter {
15:
16: OutputStream out;
17: ByteArrayOutputStream cache;
18: boolean caching;
19:
20: public CachingOutputStream(OutputStream out) {
21: cache = null;
22: caching = false;
23: this .out = out;
24: }
25:
26: public boolean startCaching() throws IOException {
27: if (caching)
28: return false;
29: flush();
30: caching = true;
31: cache = new ByteArrayOutputStream();
32: return true;
33: }
34:
35: public String getCache(String encoding)
36: throws UnsupportedEncodingException, IOException {
37: flush();
38: return cache.toString(encoding);
39: }
40:
41: public boolean stopCaching() {
42: if (!caching)
43: return false;
44: caching = false;
45: return true;
46: }
47:
48: public void close() throws IOException {
49: out.close();
50: }
51:
52: public void flush() throws IOException {
53: if (out != null)
54: out.flush();
55: if (cache != null)
56: cache.flush();
57: }
58:
59: public void write(byte[] b) throws IOException {
60: out.write(b);
61: if (caching)
62: cache.write(b);
63: }
64:
65: public void write(byte[] b, int off, int len) throws IOException {
66: out.write(b, off, len);
67: if (caching)
68: cache.write(b, off, len);
69: }
70:
71: public void write(int b) throws IOException {
72: out.write(b);
73: if (caching)
74: cache.write(b);
75: }
76: }
|