4 package org.vamsas.client.simpleclient;
10 * @author jim Watches a particular file for its creation, deletion, or
13 public class FileWatcher {
15 private File subject = null;
17 private long lastStat[];
18 boolean waslocked=false;
19 boolean exists = false;
21 * transient lock on subject - can be passed back to calling class
22 * to preserve new state of file for immediate reading.
24 private Lock subjectLock = null;
26 * clear local locks on subject.
29 private void clearLock() {
30 if (subjectLock!=null)
31 subjectLock.release();
36 * @return true if subject exists and is locked by another process.
38 private boolean checkLock() {
39 if (subject!=null && subject.exists()) {
40 if (subjectLock!=null) {
41 subjectLock.release();
43 subjectLock = new Lock(subject);
44 if (subjectLock.isLocked()) {
45 // subjectLock.release();
54 private long[] getStat(File subject) {
55 return new long[] { subject.lastModified(), subject.length() };
57 private boolean compStat(long[] stat, long[] newstat) {
58 if (stat[0]!=newstat[0] || stat[1]!=newstat[1])
63 * Detect changes in file state and release of any
64 * lock in place during change.
65 * @return true if file state has changed. Leaves lock in subjectLock (ready to be passed to caller)
67 private boolean check() {
68 if (subject != null) {
69 if (!subject.exists()) {
79 // locked - state change registered after lock is released
82 long[] newStat = getStat(subject); // subject.lastModified();
84 // file is free to access, return state change
85 if (!exists || !compStat(lastStat, newStat)) {
102 * updates internal record of file state when caller has intentionally
103 * modified subject. (ignores locked-state of subject)
105 public void setState() {
107 if (exists = subject.exists()) {
108 lastStat = getStat(subject);
115 * Make a watcher for a particular file. If the file doesn't exist, the
116 * watcher will watch for its creation (and indicate a change of state)
117 * For locked files, the removal of a lock constitutes a change of
118 * state if the file was modified.
123 public FileWatcher(File subject) {
124 // TODO Auto-generated constructor stub
125 this.subject = subject;
129 * Test for change in file state. Only indicates a change
130 * after any lock on a file has been released.
131 * @return true if file has been modified.
133 public boolean hasChanged() {
134 boolean res = check();
139 * passes lock back to caller if hasChanged returned true.
142 public Lock getChangedState() {
143 boolean res = check();