List of usage examples for java.nio.file WatchEvent kind
Kind<T> kind();
From source file:org.codice.ddf.configuration.store.ConfigurationFilesPoller.java
@Override public void run() { try {//from w ww.j a va 2s. c o m try { LOGGER.debug("Registering path [{}] with Watch Service.", configurationDirectoryPath.toString()); configurationDirectoryPath.register(watchService, ENTRY_CREATE); } catch (IOException e) { LOGGER.error("Unable to register path [{}] with Watch Service", configurationDirectoryPath.toString(), e); return; } WatchKey key; while (!Thread.currentThread().isInterrupted()) { key = watchService.take(); // blocking LOGGER.debug("Key has been signalled. Looping over events."); for (WatchEvent<?> genericEvent : key.pollEvents()) { WatchEvent.Kind<?> kind = genericEvent.kind(); if (kind == OVERFLOW || kind == ENTRY_MODIFY || kind == ENTRY_DELETE) { LOGGER.debug("Skipping event [{}]", kind); continue; } Path filename = (Path) genericEvent.context(); if (!filename.toString().endsWith(fileExtension)) { LOGGER.debug("Skipping event for [{}] due to unsupported file extension of [{}].", filename, fileExtension); continue; // just skip to the next event } if (configurationDirectory != null) { LOGGER.debug("Notifying [{}] of event [{}] for file [{}].", configurationDirectory.getClass().getName(), kind, configurationDirectoryPath.resolve(filename)); configurationDirectory.notify(configurationDirectoryPath.resolve(filename)); } } // Reset key, shutdown watcher if directory not able to be observed // (possibly deleted) if (!key.reset()) { LOGGER.warn("Configurations in [{}] are no longer able to be observed.", configurationDirectoryPath.toString()); break; } } } catch (InterruptedException | RuntimeException e) { LOGGER.error("The [{}] was interrupted.", this.getClass().getName(), e); Thread.currentThread().interrupt(); } }
From source file:org.wso2.carbon.uuf.renderablecreator.hbs.internal.io.RenderableUpdater.java
private void run() { while (!isWatchServiceStopped) { WatchKey watchKey;//from w ww .ja va 2 s.c o m try { 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(); MutableHbsRenderable mutableRenderable = watchingRenderables.get(updatedFileName); if (mutableRenderable != null) { // Updated file is a MutableHbsRenderable Path updatedFileAbsolutePath = updatedDirectory.resolve(updatedFileName); try { String content = readFileContent(updatedFileAbsolutePath); mutableRenderable.reload(new StringTemplateSource(mutableRenderable.getPath(), content)); log.info("Handlebars template '" + updatedFileAbsolutePath + "' reloaded successfully."); } catch (UUFException e) { log.error("An error occurred while reloading Handlebars template '" + updatedFileAbsolutePath + "'.", e); } } else { MutableExecutable mutableExecutable = watchingExecutables.get(updatedFileName); if (mutableExecutable != null) { // Updated file is a MutableExecutable Path updatedFileAbsolutePath = updatedDirectory.resolve(updatedFileName); try { mutableExecutable.reload(readFileContent(updatedFileAbsolutePath)); log.info("JavaScript file '" + updatedFileAbsolutePath + "' reloaded successfully."); } catch (UUFException e) { log.error("An error occurred while reloading JavaScript file '" + updatedFileAbsolutePath + "'.", e); } } } } boolean valid = watchKey.reset(); if (!valid) { // Watch key cannot not be reset because watch service is already closed. break; } } }
From source file:org.codice.ddf.configuration.admin.ConfigurationFilesPoller.java
@Override public void run() { try {//from w ww .ja v a 2 s .co m try { LOGGER.debug("Registering path [{}] with Watch Service.", configurationDirectoryPath.toString()); configurationDirectoryPath.register(watchService, ENTRY_CREATE); } catch (IOException e) { LOGGER.error("Unable to register path [{}] with Watch Service", configurationDirectoryPath.toString(), e); return; } WatchKey key; while (!Thread.currentThread().isInterrupted()) { key = watchService.take(); // blocking LOGGER.debug("Key has been signalled. Looping over events."); for (WatchEvent<?> genericEvent : key.pollEvents()) { WatchEvent.Kind<?> kind = genericEvent.kind(); if (kind == OVERFLOW || kind == ENTRY_MODIFY || kind == ENTRY_DELETE) { LOGGER.debug("Skipping event [{}]", kind); continue; } Path filename = (Path) genericEvent.context(); if (!filename.toString().endsWith(fileExtension)) { LOGGER.debug("Skipping event for [{}] due to unsupported file extension of [{}].", filename, fileExtension); continue; // just skip to the next event } if (changeListener != null) { // Sleeping before notifying the listener to make sure file is // done writing, otherwise the listener may read the file too soon. TimeUnit.SECONDS.sleep(1); LOGGER.debug("Notifying [{}] of event [{}] for file [{}].", changeListener.getClass().getName(), kind, configurationDirectoryPath.resolve(filename)); changeListener.notify(configurationDirectoryPath.resolve(filename)); } } // Reset key, shutdown watcher if directory not able to be observed // (possibly deleted) if (!key.reset()) { LOGGER.warn("Configurations in [{}] are no longer able to be observed.", configurationDirectoryPath.toString()); break; } } } catch (InterruptedException | RuntimeException e) { LOGGER.error("The [{}] was interrupted.", this.getClass().getName(), e); Thread.currentThread().interrupt(); } }
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 av a 2 s .c om*/ if (isJarFile(file)) { files.add(file); } else log.warn("[JAR Loader] Ignoring file " + file); } } key.reset(); } return files; }
From source file:org.wso2.carbon.uuf.renderablecreator.hbs.internal.io.HbsRenderableUpdater.java
private void run() { while (!isWatchServiceStopped) { WatchKey watchKey;//from w ww . ja va 2 s.co m try { 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; } } }
From source file:ch.cyberduck.core.local.FileWatcher.java
public CountDownLatch register(final Local file, final FileWatcherListener listener) throws IOException { // Make sure to canonicalize the watched folder final Path folder = new File(file.getParent().getAbsolute()).getCanonicalFile().toPath(); if (log.isDebugEnabled()) { log.debug(String.format("Register folder %s watching for file %s", folder, file)); }//from ww w. jav a 2 s . com final WatchKey key = monitor.register(folder, new WatchEvent.Kind[] { ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY }); if (!key.isValid()) { throw new IOException(String.format("Failure registering for events in %s", file)); } final CountDownLatch lock = new CountDownLatch(1); pool.execute(new Callable<Boolean>() { @Override public Boolean call() throws IOException { while (true) { // wait for key to be signaled final WatchKey key; try { lock.countDown(); if (log.isDebugEnabled()) { log.debug(String.format("Wait for key from watch service %s", monitor)); } key = monitor.take(); } catch (ClosedWatchServiceException e) { // If this watch service is closed return true; } catch (InterruptedException e) { return false; } if (log.isDebugEnabled()) { log.debug(String.format("Retrieved key %s from watch service %s", key, monitor)); } for (WatchEvent<?> event : key.pollEvents()) { final WatchEvent.Kind<?> kind = event.kind(); if (log.isInfoEnabled()) { log.info(String.format("Detected file system event %s", kind.name())); } if (kind == OVERFLOW) { log.error(String.format("Overflow event for %s", folder)); break; } // The filename is the context of the event. May be absolute or relative path name. if (matches(normalize(LocalFactory.get(folder.toString()), event.context().toString()), LocalFactory.get(folder.toString(), file.getName()))) { callback(LocalFactory.get(folder.toString()), event, listener); } else { log.warn(String.format("Ignored file system event for unknown file %s", event.context())); } } // Reset the key -- this step is critical to receive further watch events. boolean valid = key.reset(); if (!valid) { // The key is no longer valid and the loop can exit. return true; } } } }); return lock; }
From source file:org.dia.kafka.isatools.producer.DirWatcher.java
/** * Process all events for keys queued to the watcher * @param isatProd/*w ww. ja va 2s . c o m*/ */ void processEvents(ISAToolsKafkaProducer isatProd) { for (;;) { // wait for key to be signalled WatchKey key; try { key = watcher.take(); } catch (InterruptedException x) { return; } Path dir = keys.get(key); if (dir == null) { System.err.println("WatchKey not recognized!!"); continue; } List<JSONObject> jsonParsedResults = new ArrayList<JSONObject>(); for (WatchEvent<?> event : key.pollEvents()) { WatchEvent.Kind kind = event.kind(); // TBD - provide example of how OVERFLOW event is handled if (kind == OVERFLOW) { continue; } // Context for directory entry event is the file name of entry WatchEvent<Path> ev = cast(event); Path name = ev.context(); Path child = dir.resolve(name); // If an inner file has been modify then, recreate the entry if (kind == ENTRY_MODIFY || kind == ENTRY_CREATE) { File fileCheck = child.getParent().toFile(); if (child.toFile().isDirectory()) { fileCheck = child.toFile(); } System.out.format("[%s] %s : %s\n", this.getClass().getSimpleName(), kind.toString(), fileCheck.getAbsolutePath()); List<String> folderFiles = ISAToolsKafkaProducer.getFolderFiles(fileCheck); List<JSONObject> jsonObjects = ISAToolsKafkaProducer.doTikaRequest(folderFiles); if (!jsonObjects.isEmpty()) { // jsonParsedResults.addAll(jsonObjects); isatProd.sendISAToolsUpdates(jsonObjects); } } // TODO this event has still to be specified for documents if (kind == ENTRY_DELETE) { System.err.println(String.format("Delete event not supported %s", child.toAbsolutePath())); } // if directory is created, and watching recursively, then // register it and its sub-directories if (kind == ENTRY_CREATE) { try { if (Files.isDirectory(child, NOFOLLOW_LINKS)) { registerAll(child); } } catch (IOException x) { // ignore to keep sample readbale System.err.format("IOException when creating %s \n", child.toAbsolutePath()); } } } // reset key and remove from set if directory no longer accessible boolean valid = key.reset(); if (!valid) { keys.remove(key); // all directories are inaccessible if (keys.isEmpty()) { break; } } } }
From source file:org.mail.bridge.FolderMonitor.java
@SuppressWarnings("unchecked") @Override/*w w w.ja v a 2s. c o m*/ public void run() { Path outboxPath = outboxFolder.toPath(); WatchService watcher; try { watcher = FileSystems.getDefault().newWatchService(); outboxPath.register(watcher, ENTRY_CREATE); } catch (IOException e) { LOG.error(e.getMessage(), e); throw new IllegalStateException(e); } while (true) { WatchKey key; try { key = watcher.take(); } catch (InterruptedException e) { LOG.error(e.getMessage(), e); throw new IllegalStateException(e); } if (timer != null) { timer.cancel(); timer = null; } LOG.info("Folder '{}' content changed", outboxFolder.getAbsolutePath()); for (WatchEvent<?> event : key.pollEvents()) { if (event.kind() == OVERFLOW) continue; File patch = outboxPath.resolve(((WatchEvent<Path>) event).context()).toFile(); if (fileFilter.accept(patch)) files.add(patch); } if (!files.isEmpty()) { timer = new Timer(); timer.schedule(new ProcessFilesTimerTask(), NEW_FILES_PROCESS_DELAY); LOG.debug("File processing timer is (re-)scheduled"); } boolean valid = key.reset(); if (!valid) { LOG.error("Path '{}' isn't valid anymore", outboxPath); postMessage(new Main.StopMessage( String.format("Please verify validity of folder '%s' and re-run application", outboxPath))); break; } } monitorThread = null; }
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); }// w w w . j a va 2s.c om 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.eclipse.smarthome.core.transform.AbstractFileTransformationService.java
/** * Ensures that a modified or deleted cached files does not stay in the cache *//*from ww w .j a va 2 s. co m*/ private void processFolderEvents() { WatchKey key = watchService.poll(); if (key != null) { for (WatchEvent<?> e : key.pollEvents()) { if (e.kind() == OVERFLOW) { continue; } // Context for directory entry event is the file name of entry @SuppressWarnings("unchecked") WatchEvent<Path> ev = (WatchEvent<Path>) e; Path path = ev.context(); logger.debug("Refreshing transformation file '{}'", path); for (String fileEntry : cachedFiles.keySet()) { if (fileEntry.endsWith(path.toString())) { cachedFiles.remove(fileEntry); } } } key.reset(); } }