01: package biz.hammurapi.web.mda;
02:
03: import java.io.File;
04: import java.io.FileWriter;
05: import java.io.IOException;
06: import java.io.StringWriter;
07: import java.util.Iterator;
08: import java.util.Map;
09:
10: /**
11: * Outputs channels to files.
12: * @author Pavel
13: */
14: public class FileRootChannel extends MemoryChannelBase implements
15: RootChannel {
16:
17: private File outputDir;
18:
19: public FileRootChannel(File outputDir) {
20: this .outputDir = outputDir;
21: }
22:
23: /**
24: * Converts channel name to file name. By default returns channel name.
25: * @param channelName
26: * @return
27: */
28: protected String fileName(String channelName) {
29: return channelName;
30: }
31:
32: public void flush() throws IOException {
33: Iterator it = getParts().entrySet().iterator();
34: while (it.hasNext()) {
35: Map.Entry entry = (Map.Entry) it.next();
36: File outputFile = new File(outputDir, fileName(String
37: .valueOf(entry.getKey())));
38: File parentDir = outputFile.getParentFile();
39: if (parentDir != null) {
40: if (!parentDir.exists()) {
41: if (!parentDir.mkdirs()) {
42: throw new IOException(
43: "Could not create directory "
44: + parentDir.getAbsolutePath());
45: }
46: }
47: }
48:
49: FileWriter fw = new FileWriter(outputFile);
50: try {
51: if (entry.getValue() instanceof SubChannel) {
52: ((SubChannel) entry.getValue()).flush(fw);
53: } else if (entry.getValue() instanceof StringWriter) {
54: ((StringWriter) entry.getValue()).close();
55: fw.write(entry.getValue().toString());
56: }
57: } finally {
58: fw.close();
59: }
60: }
61: }
62: }
|