use of java.nio.file.ClosedWatchServiceException in project asterixdb by apache.
the class FileSystemWatcher method take.
// take is blocking
public File take() throws IOException {
File next = poll();
if (next != null) {
return next;
}
if (done || !isFeed) {
return null;
}
// No file was found, wait for the filesystem to push events
WatchKey key;
while (!it.hasNext()) {
try {
key = watcher.take();
} catch (InterruptedException x) {
if (LOGGER.isEnabledFor(Level.WARN)) {
LOGGER.warn("Feed Closed");
}
if (watcher == null) {
return null;
}
continue;
} catch (ClosedWatchServiceException e) {
if (LOGGER.isEnabledFor(Level.WARN)) {
LOGGER.warn("The watcher has exited");
}
if (watcher == null) {
return null;
}
continue;
}
handleEvents(key);
if (endOfEvents(key)) {
return null;
}
}
// files were found, re-create the iterator and move it one step
return it.next();
}
use of java.nio.file.ClosedWatchServiceException in project curiostack by curioswitch.
the class FileWatcher method listenForFileEvents.
private void listenForFileEvents() {
for (; ; ) {
final WatchKey key;
try {
key = watchService.take();
} catch (ClosedWatchServiceException | InterruptedException ex) {
return;
}
key.pollEvents().stream().filter(e -> e.kind() != StandardWatchEventKinds.OVERFLOW).map(e -> {
// Only support Path
@SuppressWarnings("unchecked") WatchEvent<Path> cast = (WatchEvent<Path>) e;
return cast.context();
}).forEach(path -> {
final Path resolved;
try {
resolved = watchedDirs.get(key).resolve(path).toRealPath();
} catch (IOException e) {
logger.warn("Unexpected exception resolving path: {}", path, e);
return;
}
Optional<Consumer<Path>> callback = registeredPaths.entrySet().stream().filter(e -> {
try {
return e.getKey().toRealPath().equals(resolved);
} catch (IOException ex) {
logger.warn("Unexpected exception resolving path: {}", e.getKey(), ex);
return false;
}
}).map(Entry::getValue).findFirst();
if (callback.isPresent()) {
logger.info("Processing update to path: " + resolved);
try {
callback.get().accept(resolved);
} catch (Exception e) {
logger.warn("Unexpected exception processing update to path: {}", resolved, e);
}
} else {
logger.info("Could not find callback for path: {}", resolved);
}
});
boolean valid = key.reset();
if (!valid) {
break;
}
}
}
use of java.nio.file.ClosedWatchServiceException in project Bytecoder by mirkosertic.
the class PollingWatchService method doPrivilegedRegister.
// registers directory returning a new key if not already registered or
// existing key if already registered
private PollingWatchKey doPrivilegedRegister(Path path, Set<? extends WatchEvent.Kind<?>> events, int sensitivityInSeconds) throws IOException {
// check file is a directory and get its file key if possible
BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);
if (!attrs.isDirectory()) {
throw new NotDirectoryException(path.toString());
}
Object fileKey = attrs.fileKey();
if (fileKey == null)
throw new AssertionError("File keys must be supported");
// grab close lock to ensure that watch service cannot be closed
synchronized (closeLock()) {
if (!isOpen())
throw new ClosedWatchServiceException();
PollingWatchKey watchKey;
synchronized (map) {
watchKey = map.get(fileKey);
if (watchKey == null) {
// new registration
watchKey = new PollingWatchKey(path, this, fileKey);
map.put(fileKey, watchKey);
} else {
// update to existing registration
watchKey.disable();
}
}
watchKey.enable(events, sensitivityInSeconds);
return watchKey;
}
}
use of java.nio.file.ClosedWatchServiceException in project fakereplace by fakereplace.
the class WatchServiceFileSystemWatcher method run.
@Override
public void run() {
while (!stopped) {
try {
final WatchKey key = watchService.take();
if (key != null) {
try {
PathData pathData = pathDataByKey.get(key);
if (pathData != null) {
List<WatchEvent<?>> events = new ArrayList<>(key.pollEvents());
final List<FileChangeEvent> results = new ArrayList<>();
List<WatchEvent<?>> latest;
do {
// we need to wait till nothing has changed in 500ms to make sure we have picked up all the changes
Thread.sleep(WAIT_TIME);
latest = key.pollEvents();
events.addAll(latest);
} while (!latest.isEmpty());
final Set<Path> addedFiles = new HashSet<>();
final Set<Path> deletedFiles = new HashSet<>();
for (WatchEvent<?> event : events) {
Path eventPath = (Path) event.context();
Path targetFile = ((Path) key.watchable()).resolve(eventPath);
FileChangeEvent.Type type;
if (event.kind() == ENTRY_CREATE) {
type = FileChangeEvent.Type.ADDED;
addedFiles.add(targetFile);
if (Files.isDirectory(targetFile)) {
try {
addWatchedDirectory(pathData, targetFile);
} catch (IOException e) {
e.printStackTrace();
}
}
} else if (event.kind() == ENTRY_MODIFY) {
type = FileChangeEvent.Type.MODIFIED;
} else if (event.kind() == ENTRY_DELETE) {
type = FileChangeEvent.Type.REMOVED;
deletedFiles.add(targetFile);
} else {
continue;
}
results.add(new FileChangeEvent(targetFile, type));
}
key.pollEvents().clear();
// now we need to prune the results, to remove duplicates
// e.g. if the file is modified after creation we only want to
// show the create event
final List<FileChangeEvent> newEvents = new ArrayList<>();
Iterator<FileChangeEvent> it = results.iterator();
while (it.hasNext()) {
FileChangeEvent event = it.next();
boolean added = addedFiles.contains(event.getFile());
boolean deleted = deletedFiles.contains(event.getFile());
if (event.getType() == FileChangeEvent.Type.MODIFIED) {
if (added || deleted) {
it.remove();
}
} else if (event.getType() == FileChangeEvent.Type.ADDED) {
if (deleted) {
it.remove();
// if it was both deleted and added it was modified
newEvents.add(new FileChangeEvent(event.getFile(), FileChangeEvent.Type.MODIFIED));
}
} else if (event.getType() == FileChangeEvent.Type.REMOVED) {
if (added) {
it.remove();
}
}
}
results.addAll(newEvents);
if (!results.isEmpty()) {
for (FileChangeCallback callback : pathData.callbacks) {
invokeCallback(callback, results);
}
}
}
} finally {
// if the key is no longer valid remove it from the files list
if (!key.reset()) {
files.remove(key.watchable());
}
}
}
} catch (InterruptedException e) {
// ignore
} catch (ClosedWatchServiceException cwse) {
// @see https://developer.jboss.org/message/911519
break;
}
}
}
use of java.nio.file.ClosedWatchServiceException in project divolte-collector by divolte.
the class ExternalDatabaseLookupService method processWatchEvents.
private void processWatchEvents() {
final Thread thisThread = Thread.currentThread();
try {
logger.debug("Starting to wait for watch events");
while (!thisThread.isInterrupted()) {
// Block for the key to be signaled.
logger.debug("Awaiting next file notification...");
final WatchKey key = watcher.take();
try {
final Path parentDirectory = (Path) key.watchable();
for (final WatchEvent<?> event : key.pollEvents()) {
processWatchEvent(parentDirectory, event);
}
} finally {
// Ensure that no matter what happens we will receive subsequent notifications.
key.reset();
}
}
logger.debug("Stopped processing watch events due to interruption.");
} catch (final InterruptedException e) {
logger.debug("Interrupted while waiting for a watch event; stopping.");
// Preserve the interrupt flag.
thisThread.interrupt();
} catch (final ClosedWatchServiceException e) {
logger.debug("Stopped processing watch events; watcher has been closed.");
}
}
Aggregations