01: package biz.hammurapi.web.mda;
02:
03: import java.io.IOException;
04: import java.io.StringWriter;
05: import java.io.Writer;
06: import java.util.ArrayList;
07: import java.util.Collections;
08: import java.util.Comparator;
09: import java.util.Iterator;
10: import java.util.List;
11:
12: /**
13: * Channel which uses StringWriter.
14: * @author Pavel
15: *
16: */
17: public class MemorySubChannel extends MemoryChannelBase implements
18: SubChannel {
19:
20: private StringWriter header;
21: private StringWriter footer;
22:
23: private Comparator partsComparator;
24:
25: public synchronized void flush(Writer writer) throws IOException {
26: if (header != null) {
27: header.close();
28: writer.write(header.toString());
29: header = null;
30: }
31:
32: List partNames = new ArrayList(getParts().keySet());
33: if (partsComparator != null) {
34: Collections.sort(partNames, partsComparator);
35: }
36:
37: Iterator it = partNames.iterator();
38: while (it.hasNext()) {
39: Object part = getParts().get(it.next());
40: if (part instanceof SubChannel) {
41: ((SubChannel) part).flush(writer);
42: } else if (part instanceof StringWriter) {
43: ((StringWriter) part).close();
44: writer.write(part.toString());
45: }
46: }
47:
48: if (footer != null) {
49: footer.close();
50: writer.write(footer.toString());
51: footer = null;
52: }
53: }
54:
55: public synchronized Writer getFooter() {
56: if (footer == null) {
57: footer = new StringWriter();
58: }
59: return footer;
60: }
61:
62: public synchronized Writer getHeader() {
63: if (header == null) {
64: header = new StringWriter();
65: }
66: return header;
67: }
68:
69: public void setPartsComparator(Comparator partsComparator) {
70: this.partsComparator = partsComparator;
71: }
72:
73: }
|