01: /*
02: * Created on Apr 25, 2004
03: */
04: package uk.org.ponder.streamutil.write;
05:
06: import java.io.PrintStream;
07: import java.io.Writer;
08: import java.util.ArrayList;
09:
10: import uk.org.ponder.stringutil.StringList;
11: import uk.org.ponder.util.UniversalRuntimeException;
12:
13: /**
14: * Multicasts PrintOutputStream data to a collection of targets.
15: * TODO: guard exceptions properly.
16: * @author Bosmon
17: */
18: public class POSMulticaster implements PrintOutputStream {
19: private ArrayList targets = new ArrayList();
20:
21: public POSMulticaster() {
22: }
23:
24: public POSMulticaster(Object target) {
25: addTarget(target);
26: }
27:
28: public boolean isEmpty() {
29: return targets.isEmpty();
30: }
31:
32: private PrintOutputStream POSAt(int i) {
33: return (PrintOutputStream) targets.get(i);
34: }
35:
36: public void addTarget(Object target) {
37: if (target instanceof Writer) {
38: targets.add(new WriterPOS((Writer) target));
39: } else if (target instanceof PrintStream) {
40: targets.add(new PrintStreamPOS((PrintStream) target));
41: } else if (target instanceof PrintOutputStream) {
42: targets.add(target);
43: } else if (target instanceof StringList) {
44: targets.add(new StringListPOS((StringList) target));
45: } else {
46: throw new UniversalRuntimeException(
47: "Unrecognised PrintOutputStream target of "
48: + target.getClass());
49: }
50: }
51:
52: public void addTarget(Writer target) {
53: targets.add(target);
54: }
55:
56: public void println(String toprint) {
57: for (int i = 0; i < targets.size(); ++i) {
58: POSAt(i).println(toprint);
59: }
60: }
61:
62: public void flush() {
63: for (int i = 0; i < targets.size(); ++i) {
64: POSAt(i).flush();
65: }
66: }
67:
68: public void close() {
69: for (int i = 0; i < targets.size(); ++i) {
70: POSAt(i).close();
71: }
72: }
73:
74: public PrintOutputStream print(String string) {
75: for (int i = 0; i < targets.size(); ++i) {
76: POSAt(i).print(string);
77: }
78: return this ;
79: }
80:
81: public void println() {
82: println("");
83: }
84:
85: public void println(Object obj) {
86: println("" + obj);
87: }
88:
89: public void write(char[] storage, int offset, int size) {
90: for (int i = 0; i < targets.size(); ++i) {
91: POSAt(i).write(storage, offset, size);
92: }
93: }
94: }
|