use of java.nio.file.WatchEvent in project SpongeCommon by SpongePowered.
the class SpongeUserManager method pollFilesystemWatcher.
private void pollFilesystemWatcher() {
if (this.watchKey == null || !this.watchKey.isValid()) {
// Reboot this if it's somehow failed.
this.refreshFilesystemProfiles();
this.setupWatchers();
return;
}
// watcher has found any more (or removed any).
synchronized (this.watcherUpdateMap) {
this.watcherUpdateMap.clear();
for (final WatchEvent<?> event : this.watchKey.pollEvents()) {
@SuppressWarnings("unchecked") final WatchEvent<Path> ev = (WatchEvent<Path>) event;
@Nullable final Path file = ev.context();
// It is possible that the context is null, in which case, ignore it.
if (file != null) {
final String filename = file.getFileName().toString();
// We don't determine the UUIDs yet, we'll only do that if we need to.
this.watcherUpdateMap.computeIfAbsent(filename, f -> new SpongeUserMutableWatchEvent()).set(ev.kind());
}
}
// Now we know what the final result is, we can act upon it.
for (final Map.Entry<String, SpongeUserMutableWatchEvent> entry : this.watcherUpdateMap.entrySet()) {
final WatchEvent.Kind<?> kind = entry.getValue().get();
if (kind != null) {
final String name = entry.getKey();
final UUID uuid;
if (name.endsWith(".dat")) {
try {
uuid = UUID.fromString(name.substring(0, name.length() - 4));
// It will only be create or delete here.
if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
this.knownUUIDs.add(uuid);
} else {
this.knownUUIDs.remove(uuid);
// We don't do this, in case we were caught at a bad time.
// Everything else should handle it for us, however.
// this.userCache.invalidate(uuid);
}
} catch (final IllegalArgumentException ex) {
// ignored, file isn't of use to us.
}
}
}
}
}
}
use of java.nio.file.WatchEvent in project hutool by looly.
the class WatchMonitorTest method main.
public static void main(String[] args) {
Watcher watcher = new SimpleWatcher() {
@Override
public void onCreate(WatchEvent<?> event, Path currentPath) {
Object obj = event.context();
Console.log("创建:{}-> {}", currentPath, obj);
}
@Override
public void onModify(WatchEvent<?> event, Path currentPath) {
Object obj = event.context();
Console.log("修改:{}-> {}", currentPath, obj);
}
@Override
public void onDelete(WatchEvent<?> event, Path currentPath) {
Object obj = event.context();
Console.log("删除:{}-> {}", currentPath, obj);
}
@Override
public void onOverflow(WatchEvent<?> event, Path currentPath) {
Object obj = event.context();
Console.log("Overflow:{}-> {}", currentPath, obj);
}
};
WatchMonitor monitor = WatchMonitor.createAll("d:/test/aaa.txt", new DelayWatcher(watcher, 500));
monitor.setMaxDepth(0);
monitor.start();
}
use of java.nio.file.WatchEvent 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 = watchedDirs.get(key).resolve(path);
Optional<Consumer<Path>> callback = registeredPaths.entrySet().stream().filter(e -> {
try {
// been updated.
return e.getKey().toRealPath().startsWith(resolved);
} catch (IOException ex) {
logger.info("Could not resolve real path.", 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) {
logger.info("Key not valid, breaking.");
break;
}
}
}
use of java.nio.file.WatchEvent in project cas by apereo.
the class ConfigurationDirectoryPathWatchService method watch.
/**
* Watch the directory for changes.
*/
public void watch() {
long lastModified = System.currentTimeMillis();
while (true) {
final WatchKey key;
try {
key = watcher.take();
} catch (final InterruptedException e) {
LOGGER.warn(e.getMessage(), e);
return;
}
for (final WatchEvent<?> event : key.pollEvents()) {
final WatchEvent.Kind<?> kind = event.kind();
if (kind == OVERFLOW) {
LOGGER.warn("An overflow event occurred. File system events may be lost or discarded.");
continue;
}
final WatchEvent<Path> ev = (WatchEvent<Path>) event;
final Path filename = ev.context();
try {
final Path child = this.directory.resolve(filename);
if (System.currentTimeMillis() - lastModified >= MONITOR_INTERVAL) {
LOGGER.debug("Detected configuration change [{}]", kind.name());
if (StringUtils.equalsIgnoreCase(StandardWatchEventKinds.ENTRY_CREATE.name(), kind.name())) {
this.eventPublisher.publishEvent(new CasConfigurationCreatedEvent(this, child));
}
if (StringUtils.equalsIgnoreCase(StandardWatchEventKinds.ENTRY_DELETE.name(), kind.name())) {
this.eventPublisher.publishEvent(new CasConfigurationDeletedEvent(this, child));
}
if (StringUtils.equalsIgnoreCase(StandardWatchEventKinds.ENTRY_MODIFY.name(), kind.name())) {
this.eventPublisher.publishEvent(new CasConfigurationModifiedEvent(this, child));
}
lastModified = System.currentTimeMillis();
}
} catch (final Exception e) {
LOGGER.warn(e.getMessage(), e);
continue;
}
}
final boolean valid = key.reset();
if (!valid) {
break;
}
}
}
use of java.nio.file.WatchEvent in project buck by facebook.
the class WatchedFileHashCache method onFileSystemChange.
/**
* Called when file change events are posted to the file change EventBus to invalidate cached
* build rules if required. {@link Path}s contained within events must all be relative to the
* {@link ProjectFilesystem} root.
*/
@Subscribe
public synchronized void onFileSystemChange(WatchEvent<?> event) {
if (WatchEvents.isPathChangeEvent(event)) {
// Path event, remove the path from the cache as it has been changed, added or deleted.
final Path path = ((Path) event.context()).normalize();
LOG.verbose("Invalidating %s", path);
Iterable<Path> pathsToInvalidate = Maps.filterEntries(loadingCache.asMap(), entry -> {
Preconditions.checkNotNull(entry);
if (entry.getKey().startsWith(path)) {
return true;
}
if (path.startsWith(entry.getKey())) {
return true;
}
return false;
}).keySet();
LOG.verbose("Paths to invalidate: %s", pathsToInvalidate);
for (Path pathToInvalidate : pathsToInvalidate) {
invalidate(pathToInvalidate);
}
} else {
// Non-path change event, likely an overflow due to many change events: invalidate everything.
LOG.debug("Invalidating all");
invalidateAll();
}
}
Aggregations