1 // Copyright 2000-2005 the Contributors, as shown in the revision logs.
2 // Licensed under the Apache Public Source License 2.0 ("the License").
3 // You may not use this file except in compliance with the License.
9 import java.nio.channels.*;
10 import org.ibex.util.*;
13 public class Persistent {
15 private static WeakHashMap cache = new WeakHashMap();
16 private static final XStream xstream = new XStream();
18 public transient File file;
19 public transient String path;
20 public transient FileLock lock;
22 public Persistent(File file) { this.file = file; this.path = file.getAbsolutePath(); }
23 public Persistent(String path) { this(new File(path)); }
25 public static Persistent read(File file) throws Exception {
28 Persistent ret = (Persistent)cache.get(file.getAbsolutePath());
29 if (ret != null) return ret;
32 ret = (Persistent)xstream.fromXML(new BufferedReader(new InputStreamReader(new FileInputStream(file))));
34 ret.path = file.getAbsolutePath();
37 ret.lock = new RandomAccessFile(file, "rw").getChannel().tryLock();
38 if (ret.lock == null) throw new RuntimeException("could not acquire lock on " + ret.path);
40 // and save it for later
41 cache.put(ret.path, ret);
46 public synchronized void write() throws Exception {
47 FileOutputStream fos = new FileOutputStream(path + "-");
48 FileDescriptor fd = fos.getFD();
49 BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
50 xstream.toXML(this, bw);
54 new File(path + "-").renameTo(file);