1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.log4j.helpers;
21
22 import java.io.File;
23 import org.apache.log4j.helpers.LogLog;
24
25 /***
26 Check every now and then that a certain file has not changed. If it
27 has, then call the {@link #doOnChange} method.
28
29
30 @author Ceki Gülcü
31 @since version 0.9.1 */
32 public abstract class FileWatchdog extends Thread {
33
34 /***
35 The default delay between every file modification check, set to 60
36 seconds. */
37 static final public long DEFAULT_DELAY = 60000;
38 /***
39 The name of the file to observe for changes.
40 */
41 protected String filename;
42
43 /***
44 The delay to observe between every check. By default set {@link
45 #DEFAULT_DELAY}. */
46 protected long delay = DEFAULT_DELAY;
47
48 File file;
49 long lastModif = 0;
50 boolean warnedAlready = false;
51 boolean interrupted = false;
52
53 protected
54 FileWatchdog(String filename) {
55 this.filename = filename;
56 file = new File(filename);
57 setDaemon(true);
58 checkAndConfigure();
59 }
60
61 /***
62 Set the delay to observe between each check of the file changes.
63 */
64 public
65 void setDelay(long delay) {
66 this.delay = delay;
67 }
68
69 abstract
70 protected
71 void doOnChange();
72
73 protected
74 void checkAndConfigure() {
75 boolean fileExists;
76 try {
77 fileExists = file.exists();
78 } catch(SecurityException e) {
79 LogLog.warn("Was not allowed to read check file existance, file:["+
80 filename+"].");
81 interrupted = true;
82 return;
83 }
84
85 if(fileExists) {
86 long l = file.lastModified();
87 if(l > lastModif) {
88 lastModif = l;
89 doOnChange();
90 warnedAlready = false;
91 }
92 } else {
93 if(!warnedAlready) {
94 LogLog.debug("["+filename+"] does not exist.");
95 warnedAlready = true;
96 }
97 }
98 }
99
100 public
101 void run() {
102 while(!interrupted) {
103 try {
104 Thread.sleep(delay);
105 } catch(InterruptedException e) {
106
107 }
108 checkAndConfigure();
109 }
110 }
111 }