use of java.nio.file.WatchEvent in project rxjava-file by davidmoten.
the class FileObservableTest method testNoEventsThrownIfFileDoesNotExist.
@Test
public void testNoEventsThrownIfFileDoesNotExist() throws InterruptedException {
File file = new File("target/does-not-exist");
Observable<WatchEvent<?>> events = FileObservable.from(file, ENTRY_MODIFY);
final CountDownLatch latch = new CountDownLatch(1);
Subscription sub = events.subscribeOn(Schedulers.io()).subscribe(new Observer<WatchEvent<?>>() {
@Override
public void onCompleted() {
latch.countDown();
}
@Override
public void onError(Throwable e) {
latch.countDown();
e.printStackTrace();
}
@Override
public void onNext(WatchEvent<?> arg0) {
latch.countDown();
}
});
assertFalse(latch.await(100, TimeUnit.MILLISECONDS));
sub.unsubscribe();
}
use of java.nio.file.WatchEvent in project wicket by apache.
the class Nio2ModificationWatcher method checkCreated.
/**
* Checks for newly created files and folders.
* New folders are registered to be watched.
* New files are removed from the MarkupCache because there could be
* {@link org.apache.wicket.markup.Markup#NO_MARKUP} (Not Found) entries for them already.
* @param log
* a logger that can be used to log the events
*/
protected void checkCreated(Logger log) {
WatchKey watchKey = watchService.poll();
if (watchKey != null) {
List<WatchEvent<?>> events = watchKey.pollEvents();
for (WatchEvent<?> event : events) {
WatchEvent.Kind<?> eventKind = event.kind();
Path eventPath = (Path) event.context();
if (eventKind == ENTRY_CREATE) {
entryCreated(eventPath, log);
} else if (eventKind == ENTRY_DELETE) {
entryDeleted(eventPath, log);
} else if (eventKind == ENTRY_MODIFY) {
entryModified(eventPath, log);
}
}
watchKey.reset();
}
}
use of java.nio.file.WatchEvent in project hutool by looly.
the class Props method autoLoad.
/**
* 在配置文件变更时自动加载
*
* @param autoReload 是否自动加载
*/
public void autoLoad(boolean autoReload) {
if (autoReload) {
if (null != this.watchMonitor) {
this.watchMonitor.close();
try {
watchMonitor = WatchMonitor.create(Paths.get(this.propertiesFileUrl.toURI()));
watchMonitor.setWatcher(new SimpleWatcher() {
@Override
public void onModify(WatchEvent<?> event, Path currentPath) {
load();
}
}).start();
} catch (Exception e) {
throw new SettingRuntimeException(e, "Setting auto load not support url: [{}]", this.propertiesFileUrl);
}
}
} else {
IoUtil.close(this.watchMonitor);
this.watchMonitor = null;
}
}
use of java.nio.file.WatchEvent in project hazelcast by hazelcast.
the class StreamFilesP method drainWatcherEvents.
/**
* @return false, if the watcher should be closed
*/
private boolean drainWatcherEvents() {
final ILogger logger = getLogger();
// poll with blocking only when there is no other work to do
final WatchKey key;
try {
key = (currentFile == null && eventQueue.isEmpty()) ? watcher.poll(1, SECONDS) : watcher.poll();
} catch (InterruptedException e) {
return false;
}
if (key == null) {
if (!Files.exists(watchedDirectory)) {
logger.info("Directory " + watchedDirectory + " does not exist, stopped watching");
return false;
}
return true;
}
for (WatchEvent<?> event : key.pollEvents()) {
final WatchEvent.Kind<?> kind = event.kind();
final Path fileName = ((WatchEvent<Path>) event).context();
final Path filePath = watchedDirectory.resolve(fileName);
if (kind == ENTRY_CREATE || kind == ENTRY_MODIFY) {
if (glob.matches(fileName) && belongsToThisProcessor(fileName) && !Files.isDirectory(filePath)) {
logFine(logger, "Will open file to read new content: %s", filePath);
eventQueue.add(filePath);
}
} else if (kind == ENTRY_DELETE) {
logFinest(logger, "File was deleted: %s", filePath);
fileOffsets.remove(filePath);
} else if (kind == OVERFLOW) {
logger.warning("Detected OVERFLOW in " + watchedDirectory);
} else {
throw new JetException("Unknown kind of WatchEvent: " + kind);
}
}
if (!key.reset()) {
logger.info("Watch key is invalid. Stopping watcher.");
return false;
}
return true;
}
use of java.nio.file.WatchEvent in project pravega by pravega.
the class FileModificationEventWatcher method run.
@Override
@SuppressWarnings("SleepWhileInLoop")
public void run() {
WatchKey watchKey = null;
WatchService watchService = null;
try {
watchService = FileSystems.getDefault().newWatchService();
log.debug("Done creating watch service for watching file at path: {}", this.watchedFilePath);
String fileName = getWatchedFileName();
Path directoryPath = getWatchedDirectory();
log.debug("Directory being watched is {}", directoryPath);
assert directoryPath != null;
directoryPath.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_CREATE);
log.debug("Registered the watch for the file: {}", this.watchedFilePath);
isWatchRegistered = true;
while (!Thread.currentThread().isInterrupted()) {
try {
watchKey = retrieveWatchKeyFrom(watchService);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
logException(e);
// Allow thread to exit.
}
if (watchKey != null) {
Optional<WatchEvent<?>> modificationDetectionEvent = watchKey.pollEvents().stream().filter(event -> event.context().toString().contains(fileName)).findAny();
if (modificationDetectionEvent.isPresent()) {
log.info("Detected that the file [{}] has modified", this.watchedFilePath);
callback.accept(modificationDetectionEvent.get());
}
boolean isKeyValid = watchKey.reset();
log.debug("Done resetting watch key.");
if (!isKeyValid) {
log.info("No longer watching file [{}]", this.watchedFilePath);
break;
}
}
if (!loopContinuously) {
break;
}
}
} catch (IOException e) {
logException(e);
throw new RuntimeException(e);
} finally {
if (watchKey != null) {
watchKey.cancel();
}
if (watchService != null) {
try {
watchService.close();
} catch (IOException e) {
log.warn("Error closing watch service", e);
}
}
}
log.info("Thread [{}], watching for modifications in file [{}] exiting,", getName(), this.watchedFilePath);
}
Aggregations