339700f44a18b7ee79ad53767231f612675d4b1a
[org.ibex.io.git] / src / org / ibex / io / WatchedFile.java
1 // Copyright 2000-2006 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.
4
5 package org.ibex.io;
6
7 import java.io.*;
8 import java.net.*;
9 import java.util.*;
10 import java.util.zip.*;
11 import org.ibex.util.*;
12
13 //
14 // FIXME: this needs to be robust against a getLastModified() call
15 // that hangs forever... what we need is a "watcher watcher" thread
16 // that spawns a new watcher and leaves a note for the old watcher
17 // telling him he's been left behind.
18 //
19
20 /** a "watched" file */
21 public class WatchedFile extends File {
22
23     private static Vec files = new Vec();
24
25     private long lastModified = 0;
26
27     public void deleted() { }
28     public void modified() { }
29
30     public WatchedFile(String s) throws IOException {
31         super(s);
32         if (!this.exists()) throw new IOException("file " + this + " does not exist");
33         lastModified = lastModified();
34         //lastSize     = length();
35         files.add(this);
36     }
37
38     private static Thread watcherThread = new ImmortalThread(2000) {
39             int i=0;
40             public void cycle() throws Exception {
41                 while(i<files.size()) {
42                     final WatchedFile f = (WatchedFile)files.get(i++);
43                     if (!f.exists()) {
44                         files.remove(i);
45                         new ResponseThread() { public void run2() throws Exception { f.deleted(); } }.start();
46                         i--;
47                     } else if (f.lastModified()!=f.lastModified) {
48                         f.lastModified = f.lastModified();
49                         new ResponseThread() { public void run2() throws Exception { f.modified(); } }.start();
50                     }
51                 }
52                 i=0;
53             }
54         };
55     static { watcherThread.start(); }
56
57     // FIXME: throttle these somehow?
58     private abstract static class ResponseThread extends Thread {
59         public abstract void run2() throws Exception;
60         public void run() {
61             try {
62                 run2();
63             } catch (Exception e) { Log.error(this, e); }
64         }
65     }
66
67 }