84a5e0a38a05a2607fb8075e5553a7a7e83ff2ec
[vamsas.git] / src / org / vamsas / client / simpleclient / FileWatcher.java
1 /**
2  * 
3  */
4 package org.vamsas.client.simpleclient;
5
6 import java.io.File;
7
8 import org.vamsas.client.SimpleClient;
9
10 /**
11  * @author jim Watches a particular file for its creation, deletion, or
12  *         modification.
13  */
14 public class FileWatcher {
15
16   private File subject = null;
17
18   private long lastStat[];
19
20   boolean exists = false;
21
22   /**
23    * Make a watcher for a particular file. If the file doesn't exist, the
24    * watcher will watch for its creation (and indicate a change of state) 
25    * For locked files, the removal of a lock constitutes a change of 
26    * state if the file was modified.
27    * 
28    * @param subject
29    */
30   private boolean checkLock() {
31     if (subject!=null && subject.exists()) {
32       Lock tl = new Lock(subject);
33       if (tl.isLocked()) {
34         tl.release();
35         return false;
36       } else {
37         return true;
38       }
39     }
40     return false;
41   }
42   private long[] getStat(File subject) {
43     return new long[] { subject.lastModified(), subject.length() };
44   }
45   private boolean compStat(long[] stat, long[] newstat) {
46     if (stat[0]!=newstat[0] || stat[1]!=newstat[1])
47       return false;
48     return true;
49   }
50   private boolean check() {
51     if (subject != null) {
52       if (!subject.exists()) {
53         if (exists) {
54           exists = false;
55           return true;
56         }
57         return false;
58       } else {
59         
60         long[] newStat = getStat(subject); // subject.lastModified();
61         if (exists && ((compStat(lastStat, newStat) || checkLock()))) {
62           return false;
63         }
64         lastStat = newStat;
65         exists = true;
66         return true;
67       }
68     }
69     return false;
70   }
71
72   public FileWatcher(File subject) {
73     // TODO Auto-generated constructor stub
74     this.subject = subject;
75     check();
76   }
77
78   public boolean hasChanged() {
79     return check();
80   }
81 }