01: // Copyright (C) 2003,2004,2005 by Object Mentor, Inc. All rights reserved.
02: // Released under the terms of the GNU General Public License version 2 or later.
03: package fitnesse.components;
04:
05: import java.io.*;
06: import fitnesse.util.FileUtil;
07:
08: public class ContentBuffer {
09: File tempFile;
10:
11: private OutputStream outputStream;
12:
13: private boolean opened;
14:
15: private int size = 0;
16:
17: public ContentBuffer() throws Exception {
18: this (".tmp");
19: }
20:
21: public ContentBuffer(String ext) throws Exception {
22: tempFile = File.createTempFile("FitNesse-", ext);
23: }
24:
25: private void open() throws FileNotFoundException {
26: if (!opened) {
27: outputStream = new FileOutputStream(tempFile, true);
28: opened = true;
29: }
30: }
31:
32: public ContentBuffer append(String value) throws Exception {
33: byte[] bytes = value.getBytes("UTF-8");
34: return append(bytes);
35: }
36:
37: public ContentBuffer append(byte[] bytes) throws IOException {
38: open();
39: size += bytes.length;
40: outputStream.write(bytes);
41: return this ;
42: }
43:
44: private void close() throws Exception {
45: if (opened) {
46: outputStream.close();
47: opened = false;
48: }
49: }
50:
51: public String getContent() throws Exception {
52: close();
53: return FileUtil.getFileContent(tempFile);
54: }
55:
56: public int getSize() throws Exception {
57: close();
58: return size;
59: }
60:
61: public InputStream getInputStream() throws Exception {
62: close();
63: return new FileInputStream(tempFile) {
64: public void close() throws IOException {
65: super .close();
66: tempFile.delete();
67: }
68: };
69: }
70:
71: public InputStream getNonDeleteingInputStream() throws Exception {
72: close();
73: return new FileInputStream(tempFile);
74: }
75:
76: public OutputStream getOutputStream() throws Exception {
77: return outputStream;
78: }
79:
80: protected File getFile() {
81: return tempFile;
82: }
83:
84: public void delete() {
85: tempFile.delete();
86: }
87:
88: protected void finalize() throws Throwable {
89: delete();
90: super.finalize();
91: }
92: }
|