PropertiesFile and WatchedFile
[org.ibex.io.git] / src / org / ibex / io / WatchedFile.java
diff --git a/src/org/ibex/io/WatchedFile.java b/src/org/ibex/io/WatchedFile.java
new file mode 100644 (file)
index 0000000..339700f
--- /dev/null
@@ -0,0 +1,67 @@
+// Copyright 2000-2006 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.io.*;
+import java.net.*;
+import java.util.*;
+import java.util.zip.*;
+import org.ibex.util.*;
+
+//
+// FIXME: this needs to be robust against a getLastModified() call
+// that hangs forever... what we need is a "watcher watcher" thread
+// that spawns a new watcher and leaves a note for the old watcher
+// telling him he's been left behind.
+//
+
+/** a "watched" file */
+public class WatchedFile extends File {
+
+    private static Vec files = new Vec();
+
+    private long lastModified = 0;
+
+    public void deleted() { }
+    public void modified() { }
+
+    public WatchedFile(String s) throws IOException {
+        super(s);
+        if (!this.exists()) throw new IOException("file " + this + " does not exist");
+        lastModified = lastModified();
+        //lastSize     = length();
+        files.add(this);
+    }
+
+    private static Thread watcherThread = new ImmortalThread(2000) {
+            int i=0;
+            public void cycle() throws Exception {
+                while(i<files.size()) {
+                    final WatchedFile f = (WatchedFile)files.get(i++);
+                    if (!f.exists()) {
+                        files.remove(i);
+                        new ResponseThread() { public void run2() throws Exception { f.deleted(); } }.start();
+                        i--;
+                    } else if (f.lastModified()!=f.lastModified) {
+                        f.lastModified = f.lastModified();
+                        new ResponseThread() { public void run2() throws Exception { f.modified(); } }.start();
+                    }
+                }
+                i=0;
+            }
+        };
+    static { watcherThread.start(); }
+
+    // FIXME: throttle these somehow?
+    private abstract static class ResponseThread extends Thread {
+        public abstract void run2() throws Exception;
+        public void run() {
+            try {
+                run2();
+            } catch (Exception e) { Log.error(this, e); }
+        }
+    }
+
+}