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 private void clearLock() {
27 if (subjectLock!=null)
28 subjectLock.release();
32 private boolean checkLock() {
33 if (subject!=null && subject.exists()) {
34 if (subjectLock!=null) {
35 subjectLock.release();
37 subjectLock = new Lock(subject);
38 if (subjectLock.isLocked()) {
39 // subjectLock.release();
48 private long[] getStat(File subject) {
49 return new long[] { subject.lastModified(), subject.length() };
51 private boolean compStat(long[] stat, long[] newstat) {
52 if (stat[0]!=newstat[0] || stat[1]!=newstat[1])
57 * Detect changes in file state and release of any
58 * lock in place during change.
59 * @return true if file state has changed. Leaves lock in subjectLock (ready to be passed to caller)
61 private boolean check() {
62 if (subject != null) {
63 if (!subject.exists()) {
73 // locked - state change registered after lock is released
76 long[] newStat = getStat(subject); // subject.lastModified();
78 // file is free to access, return state change
79 if (!exists || !compStat(lastStat, newStat)) {
96 * updates internal record of file state when caller has intentionally
97 * modified subject. (ignores locked-state of subject)
99 public void setState() {
101 if (exists = subject.exists()) {
102 lastStat = getStat(subject);
109 * Make a watcher for a particular file. If the file doesn't exist, the
110 * watcher will watch for its creation (and indicate a change of state)
111 * For locked files, the removal of a lock constitutes a change of
112 * state if the file was modified.
117 public FileWatcher(File subject) {
118 // TODO Auto-generated constructor stub
119 this.subject = subject;
123 * Test for change in file state. Only indicates a change
124 * after any lock on a file has been released.
125 * @return true if file has been modified.
127 public boolean hasChanged() {
128 boolean res = check();
133 * passes lock back to caller if hasChanged returned true.
136 public Lock getChangedState() {
137 boolean res = check();