Java Code Examples for java.nio.file.WatchEvent#context()
The following examples show how to use
java.nio.file.WatchEvent#context() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AbstractDirectoryWatcher.java From debezium-incubator with Apache License 2.0 | 6 votes |
public void poll() throws InterruptedException, IOException { LOGGER.debug("Polling commitLogFiles from cdc_raw directory..."); WatchKey key = watchService.poll(pollInterval.toMillis(), TimeUnit.MILLISECONDS); if (key != null) { LOGGER.debug("Detected new commitLogFiles in cdc_raw directory."); for (WatchEvent<?> event : key.pollEvents()) { Path relativePath = (Path) event.context(); Path absolutePath = directory.resolve(relativePath); if (kinds.contains(event.kind())) { handleEvent(event, absolutePath); } } key.reset(); } else { LOGGER.debug("No commitLogFile is detected in cdc_raw directory."); } }
Example 2
Source File: FileListener.java From scipio-erp with Apache License 2.0 | 6 votes |
@Override public void run() { try { WatchKey key = scipioWatcher.take(); while(key != null) { for (WatchEvent<?> event : key.pollEvents()) { GenericValue userLogin = EntityQuery.use(delegator).from("UserLogin").where("userLoginId", "system").queryOne(); final Path filename = (Path) event.context(); Path dir = (Path) key.watchable(); Path fullPath = dir.resolve(filename); String fileType = Files.probeContentType(fullPath); if(UtilValidate.isEmpty(fileType))fileType= FilenameUtils.getExtension(fullPath.toString()); dispatcher.runSync("triggerFileEvent", UtilMisc.toMap("fileEvent",""+event.kind(),"fileLocation",""+fullPath,"fileType",fileType,"eventName",eventName,"eventRoot",eventRoot,"userLogin",userLogin)); } key.reset(); key = scipioWatcher.take(); } } catch (Exception e) { Debug.logWarning("Could not fire FileListener Event"+e, module); } }
Example 3
Source File: PluginPropertiesWatcher.java From SuitAgent with Apache License 2.0 | 6 votes |
@Override public void run() { WatchService watchService = WatchServiceUtil.watchModify(pluginDir); WatchKey key; while (watchService != null){ try { key = watchService.take(); for (WatchEvent<?> watchEvent : key.pollEvents()) { if(watchEvent.kind() == ENTRY_MODIFY){ String fileName = watchEvent.context() == null ? "" : watchEvent.context().toString(); Plugin plugin = PluginLibraryHelper.getPluginByConfigFileName(fileName); if(plugin != null){ plugin.init(PluginLibraryHelper.getPluginConfig(plugin)); log.info("已完成插件{}的配置重新加载",plugin.pluginName()); } } } key.reset(); } catch (Exception e) { log.error("插件配置文件监听异常",e); break; } } }
Example 4
Source File: LiveDirs.java From LiveDirsFX with BSD 2-Clause "Simplified" License | 6 votes |
private void processEvent(Path dir, WatchEvent<Path> event) { // Context for directory entry event is the file name of entry Path relChild = event.context(); Path child = dir.resolve(relChild); Kind<Path> kind = event.kind(); if(kind == ENTRY_MODIFY) { handleModification(child, externalInitiator); } else if(kind == ENTRY_CREATE) { handleCreation(child, externalInitiator); } else if(kind == ENTRY_DELETE) { model.delete(child, externalInitiator); } else { throw new AssertionError("unreachable code"); } }
Example 5
Source File: ExternalDatabaseLookupService.java From divolte-collector with Apache License 2.0 | 6 votes |
private void processWatchEvent(final Path parentDirectory, final WatchEvent<?> event) { final WatchEvent.Kind<?> kind = event.kind(); if (kind == StandardWatchEventKinds.OVERFLOW) { // Ignore these for now; we could treat this as a potential change. logger.warn("File notification overflow; may have missed database update."); } else if (kind == StandardWatchEventKinds.ENTRY_MODIFY) { final Path modifiedRelativePath = (Path) event.context(); final Path modifiedAbsolutePath = parentDirectory.resolve(modifiedRelativePath); if (location.equals(modifiedAbsolutePath)) { logger.debug("Database has been updated; attempting reload: {}", modifiedAbsolutePath); reloadDatabase(); } else { logger.debug("Ignoring file modified event: {}", modifiedAbsolutePath); } } else { logger.debug("Ignoring file notification: {}", event); } }
Example 6
Source File: WatchQueueReader.java From smarthome with Eclipse Public License 2.0 | 6 votes |
private Path resolvePath(WatchKey key, WatchEvent<?> event) { WatchEvent<Path> ev = cast(event); // Context for directory entry event is the file name of entry. Path contextPath = ev.context(); Path baseWatchedDir = null; Path registeredPath = null; synchronized (this) { baseWatchedDir = keyToService.get(key).getSourcePath(); registeredPath = registeredKeys.get(key); } if (registeredPath != null) { // If the path has been registered in the watch service it relative path can be resolved // The context path is resolved by its already registered parent path return registeredPath.resolve(contextPath); } logger.warn( "Detected invalid WatchEvent '{}' and key '{}' for entry '{}' in not registered file or directory of '{}'", event, key, contextPath, baseWatchedDir); return null; }
Example 7
Source File: FileChangeEventListener.java From config-toolkit with Apache License 2.0 | 5 votes |
@Override public void run() { while (true) { // wait for key to be signaled WatchKey key; try { key = watcher.take(); } catch (InterruptedException x) { return; } for (WatchEvent<?> event : key.pollEvents()) { WatchEvent.Kind<?> kind = event.kind(); // This key is registered only for ENTRY_MODIFY events, if (kind != StandardWatchEventKinds.ENTRY_MODIFY) { continue; } // The filename is the context of the event. @SuppressWarnings("unchecked") WatchEvent<Path> ev = (WatchEvent<Path>) event; Path filename = ev.context(); LOGGER.debug("File {} changed.", filename); if (isSameFile(filename, watchedFile)) { configGroup.initConfigs(); } } boolean status = key.reset(); if(!status) { break; } } }
Example 8
Source File: GrpcServer.java From glowroot with Apache License 2.0 | 5 votes |
private static boolean certificateModified(WatchKey watchKey) { for (WatchEvent<?> event : watchKey.pollEvents()) { Object context = event.context(); if (context instanceof Path) { String fileName = ((Path) context).toString(); if (fileName.equals("grpc-cert.pem") || fileName.equals("cert.pem") || fileName.equals("grpc-key.pem") || fileName.equals("key.pem")) { return true; } } } return false; }
Example 9
Source File: SVMJVMImpl.java From visualvm with GNU General Public License v2.0 | 5 votes |
private Path findHeapDumpFile(WatchKey key) { for (WatchEvent<?> event : key.pollEvents()) { WatchEvent.Kind<?> kind = event.kind(); if (kind == StandardWatchEventKinds.OVERFLOW) { continue; } WatchEvent<Path> ev = (WatchEvent<Path>)event; Path filename = ev.context(); String name = filename.toString(); if (name.endsWith(SVM_HEAP_DUMP_SUFFIX) && name.startsWith(SVM_HEAP_DUMP_PREFIX)) { return filename; } } return null; }
Example 10
Source File: FileLock.java From scheduling with GNU Affero General Public License v3.0 | 5 votes |
@Override public void run() { while (running) { WatchKey key; try { key = watcher.take(); } catch (InterruptedException ex) { return; } for (WatchEvent<?> event : key.pollEvents()) { WatchEvent.Kind<?> kind = event.kind(); @SuppressWarnings("unchecked") WatchEvent<Path> ev = (WatchEvent<Path>) event; Path fileName = ev.context(); if (kind == StandardWatchEventKinds.OVERFLOW) { continue; } else if (kind == StandardWatchEventKinds.ENTRY_DELETE) { if (fileName.equals(this.lockFile.getFileName())) { running = false; } } } boolean valid = key.reset(); if (!valid) { break; } } try { watcher.close(); } catch (IOException e) { e.printStackTrace(); } }
Example 11
Source File: PutHeadChunkRunnable.java From crate with Apache License 2.0 | 5 votes |
private void waitUntilFileHasGrown(File pendingFile) { try { if (watcher == null) { initWatcher(pendingFile.getParent()); } watchKey = watcher.poll(5, TimeUnit.SECONDS); if (watchKey == null) { return; } for (WatchEvent<?> event : watchKey.pollEvents()) { WatchEvent.Kind<?> kind = event.kind(); if (kind == StandardWatchEventKinds.OVERFLOW) { continue; } @SuppressWarnings("unchecked") WatchEvent<Path> ev = (WatchEvent<Path>) event; Path filename = ev.context(); if (filename.toString().equals(pendingFile.getName())) { break; } } } catch (IOException | InterruptedException ex) { LOGGER.warn(ex.getMessage(), ex); } }
Example 12
Source File: Main.java From thorntail with Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") private static void processEvents(File watchedDir, Path file) { for (;;) { WatchKey key; try { key = watcher.take(); } catch (InterruptedException x) { return; } for (WatchEvent<?> event: key.pollEvents()) { Kind<?> kind = event.kind(); WatchEvent<Path> ev = (WatchEvent<Path>)event; Path name = ev.context(); Path child = watchedDir.toPath().resolve(name); if (kind == ENTRY_DELETE && child.equals(file)) { return; } } boolean valid = key.reset(); if (!valid) { break; } } }
Example 13
Source File: FileMonitorJdkImpl.java From util4j with Apache License 2.0 | 4 votes |
public void watchRNDir(Path path) throws IOException, InterruptedException { try (WatchService watchService = FileSystems.getDefault().newWatchService()) { //给path路径加上文件观察服务 path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE); // start an infinite loop while (true) { // retrieve and remove the next watch key final WatchKey key = watchService.take(); // get list of pending events for the watch key for (WatchEvent<?> watchEvent : key.pollEvents()) { // get the kind of event (create, modify, delete) final Kind<?> kind = watchEvent.kind(); // handle OVERFLOW event if (kind == StandardWatchEventKinds.OVERFLOW) { continue; } //创建事件 if(kind == StandardWatchEventKinds.ENTRY_CREATE){ } //修改事件 if(kind == StandardWatchEventKinds.ENTRY_MODIFY){ } //删除事件 if(kind == StandardWatchEventKinds.ENTRY_DELETE){ } // get the filename for the event @SuppressWarnings("unchecked") final WatchEvent<Path> watchEventPath = (WatchEvent<Path>) watchEvent; final Path filename = watchEventPath.context(); // print it out System.out.println(kind + " -> " + filename); } // reset the keyf boolean valid = key.reset(); // exit loop if the key is not valid (if the directory was // deleted, for if (!valid) { break; } } } }
Example 14
Source File: PrinterTrayWatcher.java From Java-Coding-Problems with MIT License | 4 votes |
public void watchTray(Path path) throws IOException, InterruptedException { try (WatchService watchService = FileSystems.getDefault().newWatchService()) { path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE); System.out.println("Printer watcher ready ..."); //start an infinite loop while (true) { //retrieve and remove the next watch key final WatchKey key = watchService.poll(10, TimeUnit.SECONDS); //get list of events for the watch key if (key != null) { for (WatchEvent<?> watchEvent : key.pollEvents()) { //get the filename for the event final WatchEvent<Path> watchEventPath = (WatchEvent<Path>) watchEvent; final Path filename = watchEventPath.context(); //get the kind of event (create, modify, delete) final Kind<?> kind = watchEvent.kind(); //handle OVERFLOW event if (kind == StandardWatchEventKinds.OVERFLOW) { continue; } if (kind == StandardWatchEventKinds.ENTRY_CREATE) { System.out.println("Sending the document to print -> " + filename); Runnable task = new Printer(path.resolve(filename)); Thread worker = new Thread(task); //we can set the name of the thread worker.setName(path.resolve(filename).toString()); //store the thread and the path threads.put(worker, path.resolve(filename)); //start the thread worker.start(); } if (kind == StandardWatchEventKinds.ENTRY_DELETE) { System.out.println(filename + " was successfully printed!"); } } //reset the key boolean valid = key.reset(); //exit loop if the key is not valid (if the directory was deleted, per example) if (!valid) { threads.clear(); break; } } if (!threads.isEmpty()) { for (Iterator<Map.Entry<Thread, Path>> it = threads.entrySet().iterator(); it.hasNext();) { Map.Entry<Thread, Path> entry = it.next(); if (entry.getKey().getState() == Thread.State.TERMINATED) { Files.deleteIfExists(entry.getValue()); it.remove(); } } } } } }
Example 15
Source File: FileMonitorConfiguration.java From spring-cloud-config with Apache License 2.0 | 4 votes |
private Set<File> filesFromEvents() { Set<File> files = new LinkedHashSet<File>(); if (this.watcher == null) { return files; } 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; }
Example 16
Source File: CamelSinkFileITCase.java From camel-kafka-connector with Apache License 2.0 | 4 votes |
private void waitForFile(File sinkFile, File doneFile) throws IOException, InterruptedException { WatchService watchService = FileSystems.getDefault().newWatchService(); Path path = sinkFile.getParentFile().toPath(); if (doneFile.exists()) { return; } // We watch for both the file creation and truncation path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY); int retries = 30; do { WatchKey watchKey = watchService.poll(1, TimeUnit.SECONDS); if (watchKey == null) { continue; } for (WatchEvent<?> event : watchKey.pollEvents()) { /* It should return a Path object for ENTRY_CREATE and ENTRY_MODIFY events */ Object context = event.context(); if (!(context instanceof Path)) { LOG.warn("Received an unexpected event of kind {} for context {}", event.kind(), event.context()); continue; } Path contextPath = (Path) context; if (contextPath.toString().equals(doneFile.getName())) { LOG.info("Sink file at the build path {} had a matching event of type: {}", sinkFile.getPath(), event.kind()); return; } else { LOG.debug("Ignoring a watch event at build path {} of type {} for file: {}", sinkFile.getPath(), event.kind(), contextPath.getFileName()); } } watchKey.reset(); retries--; } while (!doneFile.exists() && retries > 0); }
Example 17
Source File: Watcher.java From marathonv5 with Apache License 2.0 | 4 votes |
@Override public void run() { for (;;) { // wait for key to be signalled WatchKey key; try { key = watchService.take(); } catch (Exception x) { return; } FolderResource dir = monitored.get(key); if (dir == null) { System.err.println("WatchKey not recognized!!"); continue; } for (WatchEvent<?> event : key.pollEvents()) { Kind<?> kind = event.kind(); // TBD - provide example of how OVERFLOW event is handled if (kind == OVERFLOW) { // TODO: inform overflow handler continue; } @SuppressWarnings("unchecked") WatchEvent<Path> ev = (WatchEvent<Path>) event; Path name = ev.context(); // if directory is created, and watching recursively, then // register it and its sub-directories if (kind == ENTRY_CREATE) { Platform.runLater(() -> dir.create(name)); } if (kind == ENTRY_DELETE) { Platform.runLater(() -> dir.delete(name)); } if (kind == ENTRY_MODIFY) { } } boolean valid = key.reset(); if (!valid) { monitored.remove(key); if (monitored.isEmpty()) { break; } } } }
Example 18
Source File: MultipleFilesWatcher.java From pgptool with GNU General Public License v3.0 | 4 votes |
private Thread buildThreadAndStart() { Thread ret = new Thread("FilesWatcher-" + watcherName) { @Override public void run() { log.debug("FileWatcher thread started " + watcherName); boolean continueWatching = true; while (continueWatching) { WatchKey key; try { idleIfNoKeysRegistered(); key = watcher.take(); // NOTE: Since we're watching only one folder we assume // that there will be only one key for our folder } catch (ClosedWatchServiceException cwe) { log.error("ClosedWatchServiceException fired, stoppign thread.", cwe); return; } catch (InterruptedException x) { log.debug("FileWatcher thread stopped by InterruptedException"); return; } catch (Throwable t) { log.error("Unexpected exception while checking for updates on watched file", t); return; } BaseFolder baseFolder = null; synchronized (watcherName) { baseFolder = keys.get(key); } if (baseFolder == null) { key.cancel(); continue; } for (WatchEvent<?> event : key.pollEvents()) { // Context for directory entry event is the file name of // entry WatchEvent<Path> ev = cast(event); Path name = ev.context(); Path child = baseFolder.path.resolve(name); String relativeFilename = FilenameUtils.getName(child.toString()); if (!baseFolder.interestedFiles.contains(relativeFilename) && !event.kind().equals(ENTRY_CREATE)) { continue; } // print out event log.debug("Watcher event: " + event.kind().name() + ", file " + child); dirWatcherHandler.handleFileChanged(event.kind(), child.toString()); } // reset key and remove from set if directory no longer // accessible boolean valid = key.reset(); if (!valid) { synchronized (watcherName) { keys.remove(key); baseFolders.remove(baseFolder.folder); } } } log.debug("FileWatcher thread stopped " + watcherName); } private void idleIfNoKeysRegistered() throws InterruptedException { while (true) { synchronized (watcherName) { if (!keys.isEmpty()) { break; } } Thread.sleep(500); } }; }; ret.start(); return ret; }
Example 19
Source File: BaseWatcher.java From neoscada with Eclipse Public License 1.0 | 4 votes |
private void checkKey ( final WatchKey key ) throws IOException { if ( this.baseKey == key ) { checkBaseEvents ( key, key.pollEvents () ); if ( !this.baseKey.reset () ) { logger.warn ( "Base key got invalidated" ); this.watcher.close (); } } else { final Path base = (Path)key.watchable (); if ( ! ( key.watchable () instanceof Path ) ) { // don't reset return; } final StorageWatcher w = this.watcherMap.get ( base ); if ( w == null ) { logger.info ( "Event for unknown target: {}", base ); // don't reset return; } try { for ( final WatchEvent<?> event : key.pollEvents () ) { if ( ! ( event.context () instanceof Path ) ) { continue; } w.handleEvent ( (Path)key.watchable (), event ); } } finally { if ( !key.reset () ) { w.dispose (); } } } }
Example 20
Source File: NarAutoLoaderTask.java From nifi with Apache License 2.0 | 4 votes |
@Override public void run() { while (!stopped) { try { WatchKey key; try { LOGGER.debug("Polling for new NARs at {}", new Object[]{autoLoadPath}); key = watchService.poll(pollIntervalMillis, TimeUnit.MILLISECONDS); } catch (InterruptedException x) { LOGGER.info("WatchService interrupted, returning..."); return; } // Key comes back as null when there are no new create events, but we still want to continue processing // so we can consider files added to the candidateNars list in previous iterations if (key != null) { for (WatchEvent<?> event : key.pollEvents()) { final WatchEvent.Kind<?> kind = event.kind(); if (kind == StandardWatchEventKinds.OVERFLOW) { continue; } final WatchEvent<Path> ev = (WatchEvent<Path>) event; final Path filename = ev.context(); final Path autoLoadFile = autoLoadPath.resolve(filename); final String autoLoadFilename = autoLoadFile.toFile().getName().toLowerCase(); if (!autoLoadFilename.endsWith(".nar")) { LOGGER.info("Skipping non-nar file {}", new Object[]{autoLoadFilename}); continue; } if (autoLoadFilename.startsWith(".")) { LOGGER.debug("Skipping partially written file {}", new Object[]{autoLoadFilename}); continue; } LOGGER.info("Found {} in auto-load directory", new Object[]{autoLoadFile}); candidateNars.add(autoLoadFile.toFile()); } final boolean valid = key.reset(); if (!valid) { LOGGER.error("NAR auto-load directory is no longer valid"); stop(); } } // Make sure that the created file is done being written by checking the last modified date of the file and // make sure a certain amount of time has passed indicating it is done being written to final List<File> readyNars = new ArrayList<>(); final Iterator<File> candidateNarIter = candidateNars.iterator(); while (candidateNarIter.hasNext()) { final File candidateNar = candidateNarIter.next(); final long fileAge = System.currentTimeMillis() - candidateNar.lastModified(); if (fileAge >= MIN_FILE_AGE) { readyNars.add(candidateNar); candidateNarIter.remove(); } else { LOGGER.debug("Candidate NAR {} not ready yet, will check again next time", new Object[]{candidateNar.getName()}); } } if (!readyNars.isEmpty()) { narLoader.load(readyNars); } } catch (final Exception e) { LOGGER.error("Error loading NARs due to: " + e.getMessage(), e); } } }