From: adam Date: Fri, 25 Mar 2005 06:29:57 +0000 (+0000) Subject: added Persistent X-Git-Url: http://git.megacz.com/?p=org.ibex.io.git;a=commitdiff_plain;h=c7ff8a5743d899c1377a40bc5bb090c8f4496157;ds=sidebyside added Persistent darcs-hash:20050325062957-5007d-099427c0dfd5bfe36fd39be02ccceeea2c840b62.gz --- diff --git a/src/org/ibex/io/Persistent.java b/src/org/ibex/io/Persistent.java new file mode 100644 index 0000000..f65d809 --- /dev/null +++ b/src/org/ibex/io/Persistent.java @@ -0,0 +1,58 @@ +// 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); + } + +}