List of usage examples for java.nio.file WatchKey watchable
Watchable watchable();
From source file:Test.java
public static void main(String[] args) throws Exception { FileSystem fileSystem = FileSystems.getDefault(); WatchService watchService = fileSystem.newWatchService(); Path directory = Paths.get("/home/docs"); WatchEvent.Kind<?>[] events = { StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY }; directory.register(watchService, events); while (true) { System.out.println("Waiting for a watch event"); WatchKey watchKey = watchService.take(); System.out.println("Path being watched: " + watchKey.watchable()); if (watchKey.isValid() == false) { return; }//from w w w .j av a2 s . c om for (WatchEvent<?> event : watchKey.pollEvents()) { System.out.println("Kind: " + event.kind()); System.out.println("Context: " + event.context()); System.out.println("Count: " + event.count()); System.out.println(); } boolean valid = watchKey.reset(); System.out.println(valid); } }
From source file:Main.java
public static void main(String[] args) throws Exception { FileSystem fileSystem = FileSystems.getDefault(); WatchService watchService = fileSystem.newWatchService(); Path directory = Paths.get("c:/"); WatchEvent.Kind<?>[] events = { StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY }; directory.register(watchService, events); while (true) { System.out.println("Waiting for a watch event"); WatchKey watchKey = watchService.take(); System.out.println("Path being watched: " + watchKey.watchable()); System.out.println();//from w w w .j ava2 s . com if (watchKey.isValid()) { for (WatchEvent<?> event : watchKey.pollEvents()) { System.out.println("Kind: " + event.kind()); System.out.println("Context: " + event.context()); System.out.println("Count: " + event.count()); System.out.println(); } boolean valid = watchKey.reset(); if (!valid) { // The watchKey is not longer registered } } } }
From source file:Main.java
public static void main(String[] args) throws Exception { FileSystem fileSystem = FileSystems.getDefault(); WatchService watchService = fileSystem.newWatchService(); Path directory = Paths.get("c:/"); WatchEvent.Kind<?>[] events = { StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY }; directory.register(watchService, events); while (true) { System.out.println("Waiting for a watch event"); WatchKey watchKey = watchService.take(); System.out.println("Path being watched: " + watchKey.watchable()); System.out.println();/*from w ww .j a v a 2s. c o m*/ if (watchKey.isValid()) { for (WatchEvent<?> event : watchKey.pollEvents()) { System.out.println("Kind: " + event.kind()); System.out.println("Context: " + event.context()); System.out.println("Count: " + event.count()); System.out.println(); } boolean valid = watchKey.reset(); if (!valid) { // The watchKey is not longer registered } } } }
From source file:com.reactive.hzdfs.dll.JarModuleLoader.java
private Set<File> filesFromEvents() throws InterruptedException { WatchKey key = watcher.take(); Set<File> files = new LinkedHashSet<File>(); if (key != null && key.isValid()) { for (WatchEvent<?> event : key.pollEvents()) { if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE || event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) { Path item = (Path) event.context(); File file = new File( ((Path) key.watchable()).toAbsolutePath() + File.separator + item.getFileName()); if (log.isDebugEnabled()) { log.debug("Watch Event: " + event.kind() + ": " + file); }// w ww. j av a2 s.c o m if (isJarFile(file)) { files.add(file); } else log.warn("[JAR Loader] Ignoring file:- " + file); } } key.reset(); } return files; }
From source file:com.reactivetechnologies.platform.rest.dll.JarModuleLoader.java
private Set<File> filesFromEvents() throws InterruptedException { WatchKey key = watcher.take(); Set<File> files = new LinkedHashSet<File>(); if (key != null && key.isValid()) { for (WatchEvent<?> event : key.pollEvents()) { if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE || event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) { Path item = (Path) event.context(); File file = new File( ((Path) key.watchable()).toAbsolutePath() + File.separator + item.getFileName()); if (log.isDebugEnabled()) { log.debug("Watch Event: " + event.kind() + ": " + file); }/*w ww . j a v a 2s . c o m*/ if (isJarFile(file)) { files.add(file); } else log.warn("[JAR Loader] Ignoring file " + file); } } key.reset(); } return files; }
From source file:com.lukakama.serviio.watchservice.watcher.WatcherRunnable.java
@Override public void run() { try {//from w ww . ja va 2 s . c o m log.info("Watcher started."); initialize(); while (true) { checkInterrupted(); WatchKey watchKey = watcher.poll(CHECK_TIMEOUT, TimeUnit.MILLISECONDS); if (watchKey != null) { try { log.debug("Received watchKey: {} - {}", watchKey, watchKey.watchable()); Path parentPath = (Path) watchKey.watchable(); for (WatchEvent<?> event : watchKey.pollEvents()) { checkInterrupted(); log.debug("Received event: {} - {}", event.kind(), event.context()); if (event.kind() == StandardWatchEventKinds.OVERFLOW) { log.warn("Performing a full scan due loss of native FileSystem tracking data."); // Canceling the old watcher. IOUtils.closeQuietly(watcher); // Clean any pending unaccessible path. unaccessiblePaths.clear(); creatingPaths.clear(); modifyingPaths.clear(); // Re-initialize the monitoring. initialize(); } else { Path eventPath = parentPath.resolve((Path) event.context()); if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) { checkNewPath(eventPath); } else if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) { if (!unaccessiblePaths.contains(eventPath)) { if (isPathFullyAccessible(eventPath)) { handlePathChanged(eventPath); } else { unaccessiblePaths.add(eventPath); modifyingPaths.add(eventPath); log.debug( "File unacessible upon modification. Starting monitoring for '{}'.", eventPath); } } } else if (event.kind() == StandardWatchEventKinds.ENTRY_DELETE) { if (unaccessiblePaths.contains(eventPath)) { unaccessiblePaths.remove(eventPath); log.debug("Monitored file removed. Canceling monitoring for '{}'.", eventPath); if (modifyingPaths.contains(eventPath)) { modifyingPaths.remove(eventPath); handlePathRemoved(eventPath); } else { creatingPaths.remove(eventPath); } } else { handlePathRemoved(eventPath); } } } } } finally { watchKey.reset(); } } if (!unaccessiblePaths.isEmpty()) { checkAccessiblePaths(); } else if ((updateNotificationTimestamp != -1) && ((System.currentTimeMillis() - updateNotificationTimestamp) > CHECK_TIMEOUT)) { // Nothing happened since last update. Resetting the updateTimestamp and requesting a library update on // Serviio. updateNotificationTimestamp = -1; updateServiioReposotories(); } else if (updateNotificationTimestamp == -1) { // No pending path to checks and no pending updates to notify. Check external configuration changes. Object newFlagValue = getFieldValue(LibraryManager.getInstance(), "libraryAdditionsCheckerThread"); if ((configChangeFlag != null) && (newFlagValue != configChangeFlag)) { log.info("Detected configuration change. Restart monitoring."); configChangeFlag = newFlagValue; // Canceling the old watcher. IOUtils.closeQuietly(watcher); // Clean any pending unaccessible path. unaccessiblePaths.clear(); creatingPaths.clear(); modifyingPaths.clear(); // Re-initialize the monitoring. initialize(); } } } } catch (InterruptedException e) { // This thread has been interrupted. Just exit. return; } finally { // Release any bounded resource. unaccessiblePaths.clear(); creatingPaths.clear(); modifyingPaths.clear(); IOUtils.closeQuietly(watcher); log.info("Watcher stopped."); } }
From source file:io.stallion.fileSystem.FileSystemWatcherRunner.java
private void doRun() { while (shouldRun) { Log.fine("Running the file system watcher."); WatchKey key; try {//from w w w .j ava 2s . c o m key = watcher.take(); } catch (InterruptedException x) { Log.warn("Interuppted the watcher!!!"); try { Thread.sleep(1000); } catch (InterruptedException e) { Log.info("Exit watcher run method."); return; } continue; } Log.fine("Watch event key taken. Runner instance is {0}", this.hashCode()); for (WatchEvent<?> event : key.pollEvents()) { WatchEvent.Kind<?> kind = event.kind(); Log.fine("Event is " + kind); // This key is registered only // for ENTRY_CREATE events, // but an OVERFLOW event can // occur regardless if events // are lost or discarded. if (kind == OVERFLOW) { continue; } // The filename is the // context of the event. WatchEvent<Path> ev = (WatchEvent<Path>) event; Path filename = ev.context(); // Ignore emacs autosave files if (filename.toString().contains(".#")) { continue; } Log.finer("Changed file is {0}", filename); Path directory = (Path) key.watchable(); Log.finer("Changed directory is {0}", directory); Path fullPath = directory.resolve(filename); Log.fine("Changed path is {0}", fullPath); Boolean handlerFound = false; for (IWatchEventHandler handler : watchedByPath.values()) { Log.finer("Checking matching handler {0} {1}", handler.getInternalHandlerLabel(), handler.getWatchedFolder()); // Ignore private files if (filename.getFileName().startsWith(".")) { continue; } if ((handler.getWatchedFolder().equals(directory.toAbsolutePath().toString()) || (handler.getWatchTree() && directory.startsWith(handler.getWatchedFolder()))) && (StringUtils.isEmpty(handler.getExtension()) || fullPath.toString().endsWith(handler.getExtension()))) { String relativePath = filename.getFileName().toString(); Log.info("Handling {0} with watcher {1} for folder {2}", filename, handler.getClass().getName(), handler.getWatchedFolder()); try { handler.handle(relativePath, fullPath.toString(), kind, event); handlerFound = true; } catch (Exception e) { Log.exception(e, "Exception processing path={0} handler={1}", relativePath, handler.getClass().getName()); } } } if (!handlerFound) { Log.info("No handler found for {0}", fullPath); } } // Reset the key -- this step is critical if you want to // receive further watch events. If the key is no longer valid, // the directory is inaccessible so exit the loop. boolean valid = key.reset(); if (!valid) { Log.warn("Key invalid! Exit watch."); break; } } }
From source file:org.springframework.cloud.config.monitor.FileMonitorConfiguration.java
private Set<File> filesFromEvents() { Set<File> files = new LinkedHashSet<File>(); if (this.watcher == null) { return files; }/* ww w. j av a 2s .c om*/ WatchKey key = this.watcher.poll(); while (key != null) { for (WatchEvent<?> event : key.pollEvents()) { if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE || event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) { Path item = (Path) event.context(); File file = new File( ((Path) key.watchable()).toAbsolutePath() + File.separator + item.getFileName()); if (file.isDirectory()) { files.addAll(walkDirectory(file.toPath())); } else { if (!file.getPath().contains(".git") && !PatternMatchUtils.simpleMatch(this.excludes, file.getName())) { if (log.isDebugEnabled()) { log.debug("Watch Event: " + event.kind() + ": " + file); } files.add(file); } } } else if (event.kind() == StandardWatchEventKinds.OVERFLOW) { if (log.isDebugEnabled()) { log.debug("Watch Event: " + event.kind() + ": context: " + event.context()); } if (event.context() != null && event.context() instanceof Path) { files.addAll(walkDirectory((Path) event.context())); } else { for (Path path : this.directory) { files.addAll(walkDirectory(path)); } } } else { if (log.isDebugEnabled()) { log.debug("Watch Event: " + event.kind() + ": context: " + event.context()); } } } key.reset(); key = this.watcher.poll(); } return files; }
From source file:org.springframework.integration.file.WatchServiceDirectoryScanner.java
private Set<File> filesFromEvents() { WatchKey key = watcher.poll(); Set<File> files = new LinkedHashSet<File>(); while (key != null) { for (WatchEvent<?> event : key.pollEvents()) { if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) { Path item = (Path) event.context(); File file = new File( ((Path) key.watchable()).toAbsolutePath() + File.separator + item.getFileName()); if (logger.isDebugEnabled()) { logger.debug("Watch Event: " + event.kind() + ": " + file); }//from w w w. j a va 2 s . co m if (file.isDirectory()) { files.addAll(walkDirectory(file.toPath())); } else { files.add(file); } } else if (event.kind() == StandardWatchEventKinds.OVERFLOW) { if (logger.isDebugEnabled()) { logger.debug("Watch Event: " + event.kind() + ": context: " + event.context()); } if (event.context() != null && event.context() instanceof Path) { files.addAll(walkDirectory((Path) event.context())); } else { files.addAll(walkDirectory(this.directory)); } } else { if (logger.isDebugEnabled()) { logger.debug("Watch Event: " + event.kind() + ": context: " + event.context()); } } } key.reset(); key = watcher.poll(); } return files; }
From source file:org.wso2.carbon.uuf.renderablecreator.hbs.internal.io.HbsRenderableUpdater.java
private void run() { while (!isWatchServiceStopped) { WatchKey watchKey; try {//from w ww. j a va2 s . c o m watchKey = watcher.take(); } catch (ClosedWatchServiceException e) { log.debug("File watch service is closed."); return; } catch (InterruptedException e) { log.debug("File watch service interrupted."); return; } for (WatchEvent<?> event : watchKey.pollEvents()) { if (event.kind() != StandardWatchEventKinds.ENTRY_MODIFY) { continue; // We only watch file modify events. } Path updatedDirectory = (Path) watchKey.watchable(); @SuppressWarnings("unchecked") Path updatedFileName = ((WatchEvent<Path>) event).context(); Path updatedFileAbsolutePath = updatedDirectory.resolve(updatedFileName); try (DirectoryStream<Path> stream = Files.newDirectoryStream(updatedFileAbsolutePath.getParent())) { for (Path entry : stream) { if (Files.isDirectory(entry)) { continue; } MutableHbsRenderable mutableRenderable = watchingRenderables.get(entry); if (mutableRenderable != null) { // Updated file is a MutableHbsRenderable try { mutableRenderable.reload(new StringTemplateSource( mutableRenderable.getComponentPath(), readFileContent(entry))); log.info("Handlebars template '" + entry + "' reloaded successfully."); } catch (IOException e) { log.error("An error occurred while reloading Handlebars template '" + entry + "'.", e); } continue; } MutableExecutable mutableExecutable = watchingExecutables.get(entry); if (mutableExecutable != null) { // Updated file is a MutableExecutable try { mutableExecutable.reload(readFileContent(entry)); log.info("JavaScript file '" + entry + "' reloaded successfully."); } catch (IOException e) { log.error("An error occurred while reloading JavaScript file '" + entry + "'.", e); } } } } catch (IOException e) { log.error("An error occurred while reloading modified files '" + updatedFileAbsolutePath + "'.", e); } } boolean valid = watchKey.reset(); if (!valid) { // Watch key cannot not be reset because watch service is already closed. break; } } }