+// Copyright 2000-2005 the Contributors, as shown in the revision logs.
+// Licensed under the Apache Public Source License 2.0 ("the License").
+// You may not use this file except in compliance with the License.
+
+package org.ibex.io;
+import java.util.*;
+import java.io.*;
+import java.nio.*;
+import java.nio.channels.*;
+import org.ibex.util.*;
+import org.ibex.io.*;
+import com.thoughtworks.xstream.*;
+
+public class Persistent {
+
+ private static WeakHashMap cache = new WeakHashMap();
+ private static final XStream xstream = new XStream();
+
+ public transient File file;
+ public transient String path;
+ public transient FileLock lock;
+
+ public Persistent(File file) { this.file = file; this.path = file.getAbsolutePath(); }
+ public Persistent(String path) { this(new File(path)); }
+
+ public static Persistent read(File file) throws Exception {
+
+ // check the cache
+ Persistent ret = (Persistent)cache.get(file.getAbsolutePath());
+ if (ret != null) return ret;
+
+ // open a new file
+ ret = (Persistent)xstream.fromXML(new BufferedReader(new InputStreamReader(new FileInputStream(file))));
+ ret.file = file;
+ ret.path = file.getAbsolutePath();
+
+ // lock it
+ ret.lock = new RandomAccessFile(file, "rw").getChannel().tryLock();
+ if (ret.lock == null) throw new RuntimeException("could not acquire lock on " + ret.path);
+
+ // and save it for later
+ cache.put(ret.path, ret);
+ return ret;
+
+ }
+
+ public synchronized void write() throws Exception {
+ FileOutputStream fos = new FileOutputStream(path + "-");
+ FileDescriptor fd = fos.getFD();
+ BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
+ xstream.toXML(this, bw);
+ bw.flush();
+ fd.sync();
+ bw.close();
+ new File(path + "-").renameTo(file);
+ }
+
+}