import
[org.ibex.jinetd.git] / src / org / ibex / jinetd / Watched.java
1 package org.ibex.jinetd;
2 import org.ibex.util.*;
3 import java.io.*;
4 import java.util.*;
5
6 public class Watched extends File {
7
8     // Instance //////////////////////////////////////////////////////////////////////////////
9     
10     private Hashtable cache = new Hashtable();
11     long lastModifiedAtLastScan = -1;
12     public final String path;
13     public final String part;
14
15     public Watcher watcher() { return ((Watched)all.get(getParent())).watcher(); }
16     public Watched slash(String part) { return get(this.path + File.separatorChar + part); }
17     public void scan() throws IOException {
18         if (!exists())                                { return; }
19         if (lastModifiedAtLastScan != lastModified()) { watcher().changed(this); lastModifiedAtLastScan = lastModified(); }
20         if (!isDirectory())                           { return; }
21         Vec removals = new Vec();
22         for(Iterator i = cache.values().iterator(); i.hasNext();) {
23             Watched w = ((Watched)i.next());
24             if (w.exists()) w.scan();
25             else { watcher().changed(w); removals.addElement(w.path.substring(this.path.length() + 1)); }
26         }
27         for(int i=0; i<removals.size(); i++) cache.remove(removals.elementAt(i));
28         String[] kids = list();        
29         if (kids == null) return;
30         for(int i=0; i<kids.length; i++) {
31             if (cache.get(kids[i]) != null) continue;
32             Watched kid = slash(kids[i]);
33             if (kid == null) continue;
34             cache.put(kids[i], kid);
35             watcher().changed(kid);
36         }
37     }
38
39
40     // Pooling //////////////////////////////////////////////////////////////////////////////
41
42     private static WeakHashMap all = new WeakHashMap();
43     protected Watched(String path) {
44         super(path);
45         this.path = path;
46         this.part = path.substring(path.lastIndexOf(File.separatorChar) + 1);
47         all.put(path, this);
48     }
49     private static Watched get(String path) {
50         Watched ret = (Watched)all.get(path);
51         if (ret == null) ret = new Watched(path);
52         return ret;
53     }
54 }