4 package org.vamsas.client.simpleclient;
10 * Watches a particular file for its creation, deletion, or
11 * modification. The watcher is thread safe and different
12 * instances watching the state of a particular file carry
13 * their own state record for the file.
15 public class FileWatcher {
17 private File subject = null;
19 private long lastStat[];
20 boolean waslocked=false;
21 boolean exists = false;
23 * transient lock on subject - can be passed back to calling class
24 * to preserve new state of file for immediate reading.
26 private Lock subjectLock = null;
28 * clear local locks on subject.
31 private void clearLock() {
32 if (subjectLock!=null)
33 subjectLock.release();
38 * @return true if subject exists and is locked by another process.
40 private boolean checkLock() {
41 if (subject!=null && subject.exists()) {
42 if (subjectLock!=null) {
43 subjectLock.release();
45 subjectLock = new Lock(subject);
46 if (subjectLock.isLocked()) {
55 private long[] getStat(File subject) {
56 return new long[] { subject.lastModified(), subject.length() };
58 private boolean compStat(long[] stat, long[] newstat) {
59 if (stat[0]!=newstat[0] || stat[1]!=newstat[1])
64 * Detect changes in file state and release of any
65 * lock in place during change.
66 * @return true if file state has changed. Leaves lock in subjectLock (ready to be passed to caller)
68 private boolean check() {
69 if (subject != null) {
70 if (!subject.exists()) {
80 // locked - state change registered after lock is released
83 long[] newStat = getStat(subject); // subject.lastModified();
85 // file is free to access, return state change
86 if (!exists || !compStat(lastStat, newStat)) {
103 * updates internal record of file state when caller has intentionally
104 * modified subject. (ignores locked-state of subject)
106 public void setState() {
108 if (exists = subject.exists()) {
109 lastStat = getStat(subject);
116 * Make a watcher for a particular file. If the file doesn't exist, the
117 * watcher will watch for its creation (and indicate a change of state)
118 * For locked files, the removal of a lock constitutes a change of
119 * state if the file was modified.
124 public FileWatcher(File subject) {
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();
152 * safely? getting current state of the watched file
155 public long[] getCurrentState() {
156 return getStat(subject);
159 * safely compare an externally recorded state with the current state
160 * for significant modifications.
165 public boolean diffState(long[] a, long[] b) {
166 return compStat(a,b);