KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jahia > tools > files > FileWatcher


1 //
2
// ____.
3
// __/\ ______| |__/\. _______
4
// __ .____| | \ | +----+ \
5
// _______| /--| | | - \ _ | : - \_________
6
// \\______: :---| : : | : | \________>
7
// |__\---\_____________:______: :____|____:_____\
8
// /_____|
9
//
10
// . . . i n j a h i a w e t r u s t . . .
11
//
12
//
13
//
14
// FileWatcher
15
//
16
// NK 12.01.2001
17
//
18
//
19

20
21 package org.jahia.tools.files;
22
23 import java.io.File JavaDoc;
24 import java.io.IOException JavaDoc;
25 import java.util.Observable JavaDoc;
26 import org.quartz.JobDetail;
27 import org.quartz.Trigger;
28 import org.jahia.registries.ServicesRegistry;
29 import org.quartz.SimpleTrigger;
30 import org.quartz.Scheduler;
31 import org.jahia.exceptions.JahiaException;
32 import org.quartz.JobDataMap;
33 import java.io.Serializable JavaDoc;
34
35 /**
36  * An Observer/Observable Implementation of a Deamon Thread
37  * that looks at any new File created in a gived Folder.
38  * New files are checked by their last modif date.
39  *
40  * Build a list of files and pass it to any Registered Observer.<br>
41  *
42  * <pre>
43  * Works in two modes : mode = ALL -> returns all files in the folder.
44  * mode = CHECK_DATE -> returns only new files.
45  * </pre>
46  *
47  * @author Khue ng
48  * @version 1.0
49  */

50 public class FileWatcher extends Observable JavaDoc implements Serializable JavaDoc {
51
52     private static org.apache.log4j.Logger logger =
53         org.apache.log4j.Logger.getLogger(FileWatcher.class);
54
55     /** The Full Real Path to the Folder to Watch **/
56     private String JavaDoc m_FolderPath = "";
57
58     /** The Abstract File object of the Folder to watch **/
59     private File JavaDoc m_Folder;
60
61     /** Define at what interval the folder must be checked, in millis **/
62     private long m_Interval;
63
64     /** The internal Thread Timer **/
65     private JobDetail jobDetail;
66     private Trigger trigger;
67
68     /** Both file and directory or only file **/
69     private boolean m_FileOnly = true;
70
71     /** Define if the Thread is User or Deamon Thread **/
72     private boolean m_IsDeamon = true;
73
74     /** Check files by their last modif date status or not **/
75     public boolean mCheckDate = false;
76
77     /** the Last Time the Folder was checked **/
78     private long m_LastCheckTime;
79
80     /**
81      * Constructor
82      *
83      * @param (String) fullDirPath , the real Path to the folder to watch
84      * @param (boolean) checkDate, check by last modif date or not
85      *
86      * @param (long) interval , the interval to do the repeat Task
87      * @exception IOException
88      */

89     public FileWatcher (String JavaDoc fullFolderPath,
90                         boolean checkDate,
91                         long interval,
92                         boolean fileOnly
93                         )
94         throws IOException JavaDoc {
95
96         setFolderPath(fullFolderPath);
97         setCheckDate(checkDate);
98         setInterval(interval);
99         setFileOnly(fileOnly);
100     }
101
102     /**
103      * Constructor
104      * Precise if the Thread to Create is a Deamon or not
105      *
106      * @param (String) fullFolderPath , the real Path to the folder to watch
107      * @param (boolean) checkDate, check new files by date changes ?,
108      *
109      * @param (long) interval , the interval to do the repeat Task
110      * @param (boolean) isDeamon , create a User or Deamon Thread
111      * @exception IOException
112      */

113     public FileWatcher (String JavaDoc fullFolderPath,
114                         boolean checkDate,
115                         long interval,
116                         boolean fileOnly,
117                         boolean isDeamon
118                         )
119         throws IOException JavaDoc {
120
121         setFolderPath(fullFolderPath);
122         setCheckDate(checkDate);
123         setInterval(interval);
124         setFileOnly(fileOnly);
125         setDeamon(isDeamon);
126
127     }
128
129     /**
130      * Creates the Timer Thread and starts it
131      *
132      * @Exception IOException
133      */

134     public void start ()
135         throws IOException JavaDoc {
136
137         initialize();
138
139         logger.debug("Time created, Check Interval=" + getInterval() +
140                      " (millis) ");
141
142         jobDetail = new JobDetail(m_FolderPath + "_Job", Scheduler.DEFAULT_GROUP,
143                                   FileWatcherJob.class);
144         JobDataMap jobDataMap = new JobDataMap();
145         jobDataMap.put("fileWatcher", this);
146         jobDetail.setJobDataMap(jobDataMap);
147
148         trigger = new SimpleTrigger(m_FolderPath + "_Trigger",
149                                     Scheduler.DEFAULT_GROUP,
150                                     SimpleTrigger.REPEAT_INDEFINITELY,
151                                     m_Interval);
152
153
154         try {
155             ServicesRegistry.getInstance().getSchedulerService().unscheduleJob(trigger.getName(), Scheduler.DEFAULT_GROUP);
156             ServicesRegistry.getInstance().getSchedulerService().scheduleJob(
157                 jobDetail, trigger);
158         } catch (JahiaException je) {
159             logger.error("Error while scheduling file watch for " + m_FolderPath, je);
160         }
161
162     }
163
164     public void stop () {
165         try {
166             ServicesRegistry.getInstance().getSchedulerService().unscheduleJob(
167                 m_FolderPath + "_Trigger", Scheduler.DEFAULT_GROUP);
168         } catch (JahiaException je) {
169             logger.error("Error while scheduling file watch for " + m_FolderPath, je);
170         }
171     }
172
173     /**
174      * Returns The Interval Values
175      *
176      * @return (long) the interval
177      */

178     public long getInterval () {
179         return m_Interval;
180     }
181
182     /**
183      * Set The Interval Values
184      *
185      * @param (long) interval , the interval used to do repeatitive task in millis
186      */

187     protected void setInterval (long interval) {
188         m_Interval = interval;
189     }
190
191     /**
192      * Small trick to export the setChanged method that has a protected. This
193      * is necessary for compilation with Ant...
194      */

195     public void externalSetChanged () {
196         setChanged();
197     }
198
199     /**
200      * Returns The Path of the Folder to watch
201      *
202      * @return (String) the path to the folder to watch
203      */

204     public String JavaDoc getFolderPath () {
205         return m_FolderPath;
206     }
207
208     /**
209      * Set The FolderPath
210      *
211      * @param (String) fullFolderPath, the path to the folder to watch
212      */

213     protected void setFolderPath (String JavaDoc fullFolderPath) {
214         m_FolderPath = fullFolderPath;
215     }
216
217     /**
218      * set file only mode
219      *
220      * @param (boolean) file only or not
221      */

222     public void setFileOnly (boolean fileOnly) {
223         m_FileOnly = fileOnly;
224     }
225
226     public boolean getFileOnly() {
227         return m_FileOnly;
228     }
229
230     /**
231      * Returns The Check File Mode
232      *
233      * @return (boolean) if check new file by controling the last modif date
234      */

235     public boolean getCheckDate () {
236         return mCheckDate;
237     }
238
239     /**
240      * Set The Check File Mode ( by last modif date or returns all files found
241      *
242      * @param (boolean) checkDate, check by last modif date or not
243      */

244     public void setCheckDate (boolean checkDate) {
245         mCheckDate = checkDate;
246     }
247
248     /**
249      * Thread is a Deamon or not
250      *
251      * @return (boolean) true if is Deamon Thread
252      */

253     public boolean isDeamon () {
254         return m_IsDeamon;
255     }
256
257     /**
258      * Create a Deamon or User Thread
259      *
260      * @param (boolean) isDeamon
261      */

262     protected void setDeamon (boolean isDeamon) {
263         m_IsDeamon = isDeamon;
264     }
265
266     public File JavaDoc getFolder() {
267         return m_Folder;
268     }
269
270     public long getLastCheckTime() {
271         return m_LastCheckTime;
272     }
273
274     /**
275      * Verify if the Folder to watch exists.
276      * Create the Archive Folder if not exist.
277      *
278      * @exception IOException
279      */

280     protected void initialize ()
281         throws IOException JavaDoc {
282
283         logger.debug("Initializing file watcher");
284
285         /*
286            For Test Purpose
287            ToChange : restore the last check time from ext. file !
288          */

289         m_LastCheckTime = System.currentTimeMillis();
290         logger.debug("Watching directory=" + getFolderPath());
291         File JavaDoc tmpFile = new File JavaDoc(getFolderPath());
292         if (tmpFile != null && tmpFile.isDirectory() && !tmpFile.canWrite()) {
293             logger.debug("No write access to directory " + getFolderPath() +
294                          " tmpFile=" + tmpFile.toString());
295         } else if (!tmpFile.exists()) {
296             logger.debug("Directory " + tmpFile.toString() +
297                          " does not exist, creating...");
298             tmpFile.mkdirs();
299             logger.debug("Directory " + tmpFile.toString() +
300                          " created successfully.");
301             if (tmpFile == null) {
302                 throw new IOException JavaDoc(
303                     "FileWatcher::initialize(), cannot create directory " +
304                     tmpFile.toString());
305             }
306         }
307         m_Folder = tmpFile;
308     }
309
310
311 } // end Class FileWatcher
312
Popular Tags