01: // Copyright (c) 2001, 2006 Per M.A. Bothner and Brainfood Inc.
02: // This is free software; for terms and warranty disclaimer see ./COPYING.
03:
04: package gnu.kawa.xml;
05:
06: import gnu.mapping.*;
07: import gnu.xml.*;
08: import java.io.*;
09: import gnu.text.Path;
10:
11: /** Write a value to a named file. */
12:
13: public class WriteTo extends Procedure2 // FIXME: implements Inlineable
14: {
15: boolean ifChanged;
16: public static final WriteTo writeTo = new WriteTo();
17: public static final WriteTo writeToIfChanged = new WriteTo();
18: static {
19: writeToIfChanged.ifChanged = true;
20: }
21:
22: public static void writeTo(Object value, Object path)
23: throws Throwable {
24: Path ppath = Path.valueOf(path);
25: OutputStream outs = ppath.openOutputStream();
26: OutPort out = new OutPort(outs, ppath);
27: XMLPrinter consumer = new XMLPrinter(out, false);
28: Values.writeValues(value, consumer);
29: out.close();
30: }
31:
32: public static void writeToIfChanged(Object value, Object path)
33: throws Throwable {
34: Path ppath = Path.valueOf(path);
35: ByteArrayOutputStream bout = new ByteArrayOutputStream();
36: OutPort out = new OutPort(bout, ppath);
37: XMLPrinter consumer = new XMLPrinter(out, false);
38: Values.writeValues(value, consumer);
39: out.close();
40: byte[] bbuf = bout.toByteArray();
41: try {
42: InputStream ins = new BufferedInputStream(ppath
43: .openInputStream());
44: for (int i = 0;;) {
45: int b = ins.read();
46: boolean atend = i == bbuf.length;
47: if (b < 0) {
48: if (!atend)
49: break;
50: ins.close();
51: return;
52: }
53: if (atend || bbuf[i++] != b)
54: break;
55: }
56: ins.close();
57: } catch (Throwable ex) {
58: // fall through
59: }
60: OutputStream fout = new BufferedOutputStream(ppath
61: .openOutputStream());
62: fout.write(bbuf);
63: fout.close();
64: }
65:
66: public Object apply2(Object value, Object fileName)
67: throws Throwable {
68: if (ifChanged)
69: writeToIfChanged(value, fileName.toString());
70: else
71: writeTo(value, fileName.toString());
72: return Values.empty;
73: }
74: }
|