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