use of java.nio.file.WatchService 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);
}
use of java.nio.file.WatchService in project quasar by puniverse.
the class ActorLoader method monitorFilesystem.
private static void monitorFilesystem(ActorLoader instance, Path moduleDir) {
try (WatchService watcher = FileSystems.getDefault().newWatchService()) {
moduleDir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
LOG.info("Filesystem monitor: Watching module directory " + moduleDir + " for changes.");
for (; ; ) {
final WatchKey key = watcher.take();
for (WatchEvent<?> event : key.pollEvents()) {
final WatchEvent.Kind<?> kind = event.kind();
if (kind == OVERFLOW) {
// An OVERFLOW event can occur regardless of registration if events are lost or discarded.
LOG.warn("Filesystem monitor: filesystem events may have been missed");
continue;
}
final WatchEvent<Path> ev = (WatchEvent<Path>) event;
// The filename is the context of the event.
final Path filename = ev.context();
// Resolve the filename against the directory.
final Path child = moduleDir.resolve(filename);
if (isValidFile(child, kind == ENTRY_DELETE)) {
try {
final URL jarUrl = child.toUri().toURL();
LOG.info("Filesystem monitor: detected module file {} {}", child, kind == ENTRY_CREATE ? "created" : kind == ENTRY_MODIFY ? "modified" : kind == ENTRY_DELETE ? "deleted" : null);
if (kind == ENTRY_CREATE || kind == ENTRY_MODIFY)
instance.reloadModule(jarUrl);
else if (kind == ENTRY_DELETE)
instance.unloadModule(jarUrl);
} catch (Exception e) {
LOG.error("Filesystem monitor: exception while processing " + child, e);
}
} else {
if (kind == ENTRY_CREATE || kind == ENTRY_MODIFY)
LOG.warn("Filesystem monitor: A non-jar item " + child.getFileName() + " has been placed in the modules directory " + moduleDir);
}
}
if (!key.reset())
throw new IOException("Directory " + moduleDir + " is no longer accessible");
}
} catch (Exception e) {
LOG.error("Filesystem monitor thread terminated with an exception", e);
throw Exceptions.rethrow(e);
}
}
use of java.nio.file.WatchService in project tomee by apache.
the class FileWatcher method watch.
public Closeable watch(final String folder) {
final File file = new File(folder);
if (!file.isDirectory()) {
throw new IllegalArgumentException(folder + " is not a directory");
}
try {
final AtomicBoolean again = new AtomicBoolean(true);
final Path path = file.getAbsoluteFile().toPath();
final WatchService watchService = path.getFileSystem().newWatchService();
path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);
final Thread watcherThread = new Thread(new Runnable() {
@Override
public void run() {
while (again.get()) {
try {
// don't use take to not block forever
final WatchKey key = watchService.poll(1, TimeUnit.SECONDS);
if (key == null) {
continue;
}
for (final WatchEvent<?> event : key.pollEvents()) {
final WatchEvent.Kind<?> kind = event.kind();
if (kind != StandardWatchEventKinds.ENTRY_CREATE && kind != StandardWatchEventKinds.ENTRY_DELETE && kind != StandardWatchEventKinds.ENTRY_MODIFY) {
continue;
}
final Path updatedPath = Path.class.cast(event.context());
if (kind == StandardWatchEventKinds.ENTRY_DELETE || updatedPath.toFile().isFile()) {
final String path = updatedPath.toString();
if (path.endsWith("___jb_tmp___") || path.endsWith("___jb_old___")) {
continue;
} else if (path.endsWith("~")) {
onChange(path.replace(File.pathSeparatorChar, '/').substring(0, path.length() - 1));
} else {
onChange(path.replace(File.pathSeparatorChar, '/'));
}
}
}
key.reset();
} catch (final InterruptedException e) {
Thread.interrupted();
again.set(false);
} catch (final ClosedWatchServiceException cwse) {
// ok, we finished there
}
}
}
});
watcherThread.setName("livereload-tomee-watcher(" + folder + ")");
watcherThread.start();
return new Closeable() {
@Override
public void close() throws IOException {
synchronized (this) {
for (final Session s : sessions) {
removeSession(s);
try {
s.close(new CloseReason(CloseReason.CloseCodes.GOING_AWAY, "container shutdowned"));
} catch (final Exception e) {
// ok: not important there
}
}
}
again.compareAndSet(true, false);
try {
watchService.close();
} catch (final IOException ioe) {
logger.warning("Error closing the watch service for " + folder + "(" + ioe.getMessage() + ")");
}
try {
watcherThread.join(TimeUnit.MINUTES.toMillis(1));
} catch (final InterruptedException e) {
Thread.interrupted();
}
}
};
} catch (final IOException e) {
throw new IllegalArgumentException(e);
}
}
use of java.nio.file.WatchService in project tomee by apache.
the class ArchivingTest method logAndRotateAndPurge.
@SuppressWarnings("unchecked")
@Test
public void logAndRotateAndPurge() throws Exception {
clean("target/ArchivingTestPurge-" + format + "/logs");
final AtomicReference<String> today = new AtomicReference<>();
final Map<String, String> config = new HashMap<>();
// initial config
today.set("2015-09-01");
config.put("filenamePattern", "target/ArchivingTestPurge-" + format + "/logs/test.%s.%d.log");
config.put("archiveDirectory", "target/ArchivingTestPurge-" + format + "/logs/archives");
config.put("archiveFormat", format);
config.put("archiveOlderThan", "1 s");
config.put("purgeOlderThan", "2 s");
config.put("limit", "10 kilobytes");
config.put("level", "INFO");
config.put("dateCheckInterval", "1 second");
final LocalFileHandler handler = new LocalFileHandler() {
@Override
protected String currentDate() {
return today.get();
}
@Override
protected String getProperty(final String name, final String defaultValue) {
final String s = config.get(name.substring(name.lastIndexOf('.') + 1));
return s != null ? s : defaultValue;
}
};
final String string10chars = "abcdefghij";
final int iterations = 950;
for (int i = 0; i < iterations; i++) {
handler.publish(new LogRecord(Level.INFO, string10chars));
}
today.set("2015-09-02");
try {
Thread.sleep(2000);
} catch (final InterruptedException e) {
Thread.interrupted();
}
final File logArchive = new File("target/ArchivingTestPurge-" + format + "/logs/archives/test.2015-09-01.0.log." + format);
final File parentFile = logArchive.getParentFile();
if (!parentFile.exists() && !parentFile.mkdirs()) {
Assert.fail("Unable to create: " + parentFile);
}
final Path dir = parentFile.toPath();
final WatchService watcher = FileSystems.getDefault().newWatchService();
final WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_MODIFY);
latch.set(new CountDownLatch(1));
watch(key);
// will trigger the archiving
handler.publish(new LogRecord(Level.INFO, string10chars));
assertTrue("Failed to get archived log", latch.get().await(20, TimeUnit.SECONDS));
final WatchEvent<?> watchEvent = lastEvent.get();
assertTrue(StandardWatchEventKinds.ENTRY_CREATE.equals(watchEvent.kind()) || StandardWatchEventKinds.ENTRY_MODIFY.equals(watchEvent.kind()));
final WatchEvent<Path> ev = (WatchEvent<Path>) watchEvent;
final String io = ev.context().toString();
assertTrue(io.startsWith("test.2015-09-01.") && io.endsWith(format));
today.set("2015-09-03");
try {
Thread.sleep(2500);
} catch (final InterruptedException e) {
Thread.interrupted();
}
// will trigger the purging
handler.publish(new LogRecord(Level.INFO, string10chars));
handler.close();
withRetry(10, 2, new Runnable() {
@Override
public void run() {
assertFalse(logArchive.getAbsolutePath() + " was purged", logArchive.exists());
}
});
}
use of java.nio.file.WatchService in project yyl_example by Relucent.
the class WatchServiceTest method main.
public static void main(String[] args) throws IOException, InterruptedException {
String directory = "D:/temp-" + System.currentTimeMillis();
File folder = new File(directory);
folder.mkdirs();
new Thread(() -> {
for (int i = 0; i < 100; i++) {
try {
File file = new File(directory + "/" + i);
file.createNewFile();
file.deleteOnExit();
} catch (IOException e) {
e.printStackTrace();
}
folder.delete();
}
}).start();
Thread watch = new Thread(() -> {
try {
WatchService watcher = FileSystems.getDefault().newWatchService();
FileSystems.getDefault().getPath(directory).register(watcher, StandardWatchEventKinds.ENTRY_DELETE);
while (true) {
WatchKey key = watcher.take();
for (WatchEvent<?> event : key.pollEvents()) {
Object name = event.context();
System.out.println(name);
}
key.reset();
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
watch.setDaemon(true);
watch.start();
}
Aggregations