/
FileWatcher.java
212 lines (197 loc) · 8.79 KB
/
FileWatcher.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
package org.chii2.medialibrary.file.watcher;
import name.pachler.nio.file.*;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.chii2.medialibrary.api.file.FileService;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventAdmin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.*;
/**
* FileWatcher based on JPathWatch, File/Directory watch service
*/
public class FileWatcher implements Runnable {
// Flag
public volatile boolean shouldStop = false;
// Directory to be watched
private List<String> directories;
// File Filter
private FileFilter filter;
// Create Event Topic
private String createTopic;
// Modify Event Topic
private String modifyTopic;
// Delete Event Topic
private String deleteTopic;
// EventAdmin
private EventAdmin eventAdmin;
// Logger
private Logger logger = LoggerFactory.getLogger("org.chii2.medialibrary.file.watcher");
/**
* Constructor
*
* @param directories Directory to be watched
* @param filter File Name Filter
* @param createTopic Create Event Topic
* @param modifyTopic Modify Event Topic
* @param deleteTopic Delete Event Topic
* @param eventAdmin EventAdmin
*/
public FileWatcher(List<String> directories, FileFilter filter, String createTopic, String modifyTopic, String deleteTopic, EventAdmin eventAdmin) {
this.directories = directories;
this.filter = filter;
this.createTopic = createTopic;
this.modifyTopic = modifyTopic;
this.deleteTopic = deleteTopic;
this.eventAdmin = eventAdmin;
}
@Override
public void run() {
// New Watch Service
WatchService watchService = FileSystems.getDefault().newWatchService();
// Mapping Cache
Map<WatchKey, Path> mapping = new HashMap<WatchKey, Path>();
// Add directories to watch
for (String directory : this.directories) {
// Path
Path path = Paths.get(directory);
// Key
WatchKey key = null;
try {
key = path.register(watchService, StandardWatchEventKind.ENTRY_CREATE, StandardWatchEventKind.ENTRY_MODIFY, StandardWatchEventKind.ENTRY_DELETE);
} catch (UnsupportedOperationException e) {
logger.error("Error when register watcher key: {}", ExceptionUtils.getMessage(e));
} catch (IOException e) {
logger.error("Error when register watcher key: {}", ExceptionUtils.getMessage(e));
}
// Add to mapping
if (key != null) {
mapping.put(key, path);
}
}
// Loop event handling
while (!this.shouldStop) {
// take() will block until a file has been created/deleted
WatchKey signalledKey = null;
try {
signalledKey = watchService.take();
} catch (InterruptedException e) {
logger.warn("Watcher thread has been interrupted: {}", ExceptionUtils.getMessage(e));
} catch (ClosedWatchServiceException e) {
// other thread closed watch service
logger.warn("Watcher thread has been closed by other thread: {}", ExceptionUtils.getMessage(e));
break;
}
if (signalledKey != null) {
// Get Path
Path directory = mapping.get(signalledKey);
// get list of events from key
List<WatchEvent<?>> events = signalledKey.pollEvents();
// VERY IMPORTANT! call reset() AFTER pollEvents() to allow the
// key to be reported again by the watch service
signalledKey.reset();
// Loop Event Type
for (WatchEvent event : events) {
if (event.kind() == StandardWatchEventKind.ENTRY_CREATE) {
Path context = (Path) event.context();
logger.debug("Receive a Entry Create watch event for: {}", context.toString());
// File
File file = new File(directory.toString(), context.toString());
if (file.exists()) {
// Directory
if (file.isDirectory()) {
// Path
Path path = Paths.get(file.getAbsolutePath());
// Key
WatchKey key = null;
try {
key = path.register(watchService, StandardWatchEventKind.ENTRY_CREATE, StandardWatchEventKind.ENTRY_MODIFY, StandardWatchEventKind.ENTRY_DELETE);
} catch (UnsupportedOperationException e) {
logger.error("Error when register watcher key: {}", ExceptionUtils.getMessage(e));
} catch (IOException e) {
logger.error("Error when register watcher key: {}", ExceptionUtils.getMessage(e));
}
// Add to mapping
if (key != null) {
mapping.put(key, path);
}
}
// Filer
else if (file.isFile()) {
// Name Filter
if (this.filter.accept(file)) {
// Post Event
this.postEvent(file, this.createTopic);
}
}
}
} else if (event.kind() == StandardWatchEventKind.ENTRY_MODIFY) {
Path context = (Path) event.context();
logger.debug("Receive a Entry Modify watch event for: {}", context.toString());
// File
File file = new File(directory.toString(), context.toString());
if (file.exists() && file.isFile()) {
this.postEvent(file, this.modifyTopic);
}
} else if (event.kind() == StandardWatchEventKind.ENTRY_DELETE) {
Path context = (Path) event.context();
logger.debug("Receive a Entry Delete watch event for: {}", context.toString());
// File
File file = new File(directory.toString(), context.toString());
// Path
Path path = Paths.get(file.getAbsolutePath());
// Mapping Cache contains path, it's a directory
if (mapping.containsValue(path)) {
WatchKey cacheKey = this.getKeyByPath(mapping, path);
// Canceled
cacheKey.cancel();
// Remove from mapping cache
mapping.remove(cacheKey);
}
// it's a file
else {
// Name Filter
if (this.filter.accept(file)) {
// Post Event
this.postEvent(file, this.deleteTopic);
}
}
} else if (event.kind() == StandardWatchEventKind.OVERFLOW) {
logger.warn("OVERFLOW: more changes happened than we could retrieve");
}
}
}
}
}
/**
* Get WatchKey by Path from Key-Path Mapping Cache
*
* @param mapping Key-Path Mapping Cache
* @param path Path Value
* @return WatchKey
*/
private WatchKey getKeyByPath(Map<WatchKey, Path> mapping, Path path) {
for (Map.Entry<WatchKey, Path> entry : mapping.entrySet()) {
if (entry.getValue().equals(path)) {
return entry.getKey();
}
}
return null;
}
/**
* Send a scanAll event asynchronously
*
* @param file File discovered
* @param topic Event topic
*/
private void postEvent(File file, String topic) {
Dictionary<String, Object> properties = new Hashtable<String, Object>();
properties.put(FileService.FILE_PROPERTY, file);
Event event = new Event(topic, properties);
logger.debug("Send a file {} watch event to topic {}.", file.getAbsolutePath(), topic);
this.eventAdmin.postEvent(event);
}
}