197f7dd0c6e808da6770fffd6266418bab95b1ef
[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             Watched kid = (Watched)cache.get(kids[i]);
32             if (kid == null) {
33                 kid = slash(kids[i]);
34                 if (kid == null) continue;
35                 cache.put(kids[i], kid);
36                 watcher().changed(kid);
37             } else {
38                 kid.scan();
39             }
40         }
41     }
42
43
44     // Pooling //////////////////////////////////////////////////////////////////////////////
45
46     private static WeakHashMap all = new WeakHashMap();
47     protected Watched(String path) {
48         super(path);
49         this.path = path;
50         this.part = path.substring(path.lastIndexOf(File.separatorChar) + 1);
51         all.put(path, this);
52     }
53     private static Watched get(String path) {
54         Watched ret = (Watched)all.get(path);
55         if (ret == null) ret = new Watched(path);
56         return ret;
57     }
58 }