java.nio.file.WatchKey Java Examples
The following examples show how to use
java.nio.file.WatchKey.
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: LotsOfCancels.java From hottub with GNU General Public License v2.0 | 6 votes |
/** * Polls the given WatchService in a tight loop. This keeps the event * queue drained, it also hogs a CPU core which seems necessary to * tickle the original bug. */ static void poll(WatchService watcher) { try { for (;;) { WatchKey key = watcher.take(); if (key != null) { key.pollEvents(); key.reset(); } } } catch (ClosedWatchServiceException expected) { // nothing to do } catch (Exception e) { e.printStackTrace(); failed = true; } }
Example #2
Source File: WatchServiceHelper.java From Singularity with Apache License 2.0 | 6 votes |
public void watch() throws IOException, InterruptedException { LOG.info("Watching directory {} for event(s) {}", watchDirectory, watchEvents); WatchKey watchKey = watchDirectory.register( watchService, watchEvents.toArray(new WatchEvent.Kind[watchEvents.size()]) ); while (!stopped) { if (watchKey != null) { processWatchKey(watchKey); if (!watchKey.reset()) { LOG.warn("WatchKey for {} no longer valid", watchDirectory); break; } } watchKey = watchService.poll(pollWaitCheckShutdownMillis, TimeUnit.MILLISECONDS); } }
Example #3
Source File: DirWatcher.java From LiveDirsFX with BSD 2-Clause "Simplified" License | 6 votes |
private WatchKey take() throws InterruptedException { synchronized(this) { if(interrupted) { interrupted = false; throw new InterruptedException(); } else { mayInterrupt = true; } } try { return watcher.take(); } finally { synchronized(this) { mayInterrupt = false; } } }
Example #4
Source File: GrpcServer.java From glowroot with Apache License 2.0 | 6 votes |
public void runInternal() throws Exception { WatchKey watchKey = watcher.take(); watchKey.reset(); if (!certificateModified(watchKey)) { return; } // wait for system to settle (in case copying over cert/key pair one by one) while (true) { SECONDS.sleep(5); watchKey = watcher.poll(); if (watchKey == null) { break; } watchKey.reset(); if (!certificateModified(watchKey)) { break; } } delegatingSslContext.reloadCertificate(); }
Example #5
Source File: LotsOfCancels.java From TencentKona-8 with GNU General Public License v2.0 | 6 votes |
/** * Stress the given WatchService, specifically the cancel method, in * the given directory. Closes the WatchService when done. */ static void handle(Path dir, WatchService watcher) { try { try { Path file = dir.resolve("anyfile"); for (int i=0; i<2000; i++) { WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE); Files.createFile(file); Files.delete(file); key.cancel(); } } finally { watcher.close(); } } catch (Exception e) { e.printStackTrace(); failed = true; } }
Example #6
Source File: LotsOfCancels.java From openjdk-jdk8u with GNU General Public License v2.0 | 6 votes |
/** * Polls the given WatchService in a tight loop. This keeps the event * queue drained, it also hogs a CPU core which seems necessary to * tickle the original bug. */ static void poll(WatchService watcher) { try { for (;;) { WatchKey key = watcher.take(); if (key != null) { key.pollEvents(); key.reset(); } } } catch (ClosedWatchServiceException expected) { // nothing to do } catch (Exception e) { e.printStackTrace(); failed = true; } }
Example #7
Source File: TreeWatcherNIO.java From HotswapAgent with GNU General Public License v2.0 | 6 votes |
/** * Register the given directory with the WatchService. * * @param dir the directory to register watch on * @throws IOException Signals that an I/O exception has occurred. */ private void register(Path dir) throws IOException { for(Path p: keys.values()) { // This may NOT be correct for all cases (ensure resolve will work!) if(dir.startsWith(p)) { LOGGER.debug("Path {} watched via {}", dir, p); return; } } if (FILE_TREE == null) { LOGGER.debug("WATCHING:ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY - high} {}", dir); } else { LOGGER.debug("WATCHING: ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY - fileTree,high {}", dir); } final WatchKey key = dir.register(watcher, KINDS, MODIFIERS); keys.put(key, dir); }
Example #8
Source File: PubSubEmulator.java From spring-cloud-gcp with Apache License 2.0 | 6 votes |
/** * Wait until a PubSub emulator configuration file is updated. * Fail if the file does not update after 1 second. * @param watchService the watch-service to poll * @throws InterruptedException which should interrupt the peaceful slumber and bubble up * to fail the test. */ private void updateConfig(WatchService watchService) throws InterruptedException { int attempts = 10; while (--attempts >= 0) { WatchKey key = watchService.poll(100, TimeUnit.MILLISECONDS); if (key != null) { Optional<Path> configFilePath = key.pollEvents().stream() .map((event) -> (Path) event.context()) .filter((path) -> ENV_FILE_NAME.equals(path.toString())) .findAny(); if (configFilePath.isPresent()) { return; } } } fail("Configuration file update could not be detected"); }
Example #9
Source File: FolderReader.java From baleen with Apache License 2.0 | 6 votes |
private void removeFileFromQueue(WatchKey key, WatchEvent<Path> pathEvent) { getMonitor() .debug( "ENTRY_DELETE event received - file '{}' will be removed from queue", pathEvent.context()); try { Path dir = watchKeys.get(key); if (dir != null) { Path resolved = dir.resolve(pathEvent.context()); queue.remove(resolved); } else { getMonitor() .warn( "WatchKey not found - file '{}' will not be removed from the queue", pathEvent.context()); } } catch (Exception ioe) { getMonitor() .warn( "An error occurred - file '{}' will not be removed from the queue", pathEvent.context(), ioe); } queue.remove(pathEvent.context()); }
Example #10
Source File: LotsOfCancels.java From dragonwell8_jdk with GNU General Public License v2.0 | 6 votes |
/** * Stress the given WatchService, specifically the cancel method, in * the given directory. Closes the WatchService when done. */ static void handle(Path dir, WatchService watcher) { try { try { Path file = dir.resolve("anyfile"); for (int i=0; i<2000; i++) { WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE); Files.createFile(file); Files.delete(file); key.cancel(); } } finally { watcher.close(); } } catch (Exception e) { e.printStackTrace(); failed = true; } }
Example #11
Source File: LotsOfCancels.java From jdk8u_jdk with GNU General Public License v2.0 | 6 votes |
/** * Polls the given WatchService in a tight loop. This keeps the event * queue drained, it also hogs a CPU core which seems necessary to * tickle the original bug. */ static void poll(WatchService watcher) { try { for (;;) { WatchKey key = watcher.take(); if (key != null) { key.pollEvents(); key.reset(); } } } catch (ClosedWatchServiceException expected) { // nothing to do } catch (Exception e) { e.printStackTrace(); failed = true; } }
Example #12
Source File: DirWatcher.java From Jupiter with GNU General Public License v3.0 | 6 votes |
/** * Register all keys. * * @param directory directory to register */ private void registerAll(Path directory) { File file = directory.toFile(); // only for unhidden directories if (file.isDirectory() && !file.isHidden()) { try { // create a new watch key for the directory WatchKey key = directory.register( watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY ); keys.put(key, directory); File[] files = file.listFiles(); if (files != null) { // walk directory tree for (File f : files) { registerAll(f.toPath()); } } } catch (IOException e) { // skip directory and subtree :] } } }
Example #13
Source File: HomeDirectoryTreeWalker.java From artifactory_ssh_proxy with Apache License 2.0 | 6 votes |
public HomeDirectoryTreeWalker(final WatchService watchService, final Map<WatchKey, Path> watchKeys, final Path homeDirectoryBasePath, final List<Path> excludedPaths, final MultiUserAuthorizedKeysMap authorizedKeysMap) { this.excludedPaths = new ArrayList<>(excludedPaths.size()); // make sure all paths are absolute for (Path excluded : excludedPaths) { this.excludedPaths.add(excluded.toAbsolutePath()); } this.watchService = watchService; this.watchKeys = watchKeys; this.authorizedKeysMap = authorizedKeysMap; this.homeDirectoryBasePath = homeDirectoryBasePath.toAbsolutePath(); this.homeDirNameCount = this.homeDirectoryBasePath.getNameCount(); }
Example #14
Source File: NioNotifier.java From netbeans with Apache License 2.0 | 6 votes |
@Override protected String nextEvent() throws IOException, InterruptedException { WatchKey key; try { key = watcher.take(); } catch (ClosedWatchServiceException cwse) { // #238261 @SuppressWarnings({"ThrowableInstanceNotThrown"}) InterruptedException ie = new InterruptedException(); throw (InterruptedException) ie.initCause(cwse); } Path dir = (Path)key.watchable(); String res = dir.toAbsolutePath().toString(); for (WatchEvent<?> event: key.pollEvents()) { if (event.kind() == OVERFLOW) { // full rescan res = null; } } key.reset(); return res; }
Example #15
Source File: SVMJVMImpl.java From visualvm with GNU General Public License v2.0 | 5 votes |
public File takeHeapDump() throws IOException { if (!isTakeHeapDumpSupported()) { throw new UnsupportedOperationException(); } String cwd = monitoredVm.findByName(USER_DIR_COUNTER_NAME); Path applicationCwd = Paths.get(cwd); WatchService watchService = FileSystems.getDefault().newWatchService(); WatchKey key = applicationCwd.register(watchService, StandardWatchEventKinds.ENTRY_CREATE); Runtime.getRuntime().exec(new String[] {"kill", "-USR1", String.valueOf(application.getPid())}); try { Path name = findHeapDumpFile(key); if (name == null) { key = watchService.poll(20, TimeUnit.SECONDS); name = findHeapDumpFile(key); } watchService.close(); if (name == null) { return null; } File dumpFile = applicationCwd.resolve(name).toFile(); waitDumpDone(dumpFile); return dumpFile; } catch (InterruptedException ex) { watchService.close(); return null; } }
Example #16
Source File: AbstractWatchService.java From cyberduck with GNU General Public License v3.0 | 5 votes |
@Override public final WatchKey poll() { checkOpen(); WatchKey key = pendingKeys.poll(); checkKey(key); return key; }
Example #17
Source File: CsvFolderReader.java From baleen with Apache License 2.0 | 5 votes |
/** * Every time doHasNext() is called, check the WatchService for new events and add all new events * to the queue. Then return true if there are files on the queue, or false otherwise. * * <p>If the event indicates that a file has been deleted, ensure it is removed from the queue. */ @Override public boolean doHasNext() throws IOException, CollectionException { WatchKey key; while ((key = watcher.poll()) != null) { for (WatchEvent<?> event : key.pollEvents()) { processEvent(key, event); getMonitor().meter("events").mark(); } key.reset(); } return !currLines.isEmpty() || !queue.isEmpty(); }
Example #18
Source File: FileSystemWatchingService.java From ariADDna with Apache License 2.0 | 5 votes |
/** * replacement path associated key when you rename a folder * * @param from old path * @param to new path */ public void replaceKey(Path from, Path to) { Map.Entry<WatchKey, Path> result = removeKey(from); if (result != null) { keys.put(result.getKey(), to); } }
Example #19
Source File: WatchablePath.java From directory-watcher with Apache License 2.0 | 5 votes |
@Override public final WatchKey register(WatchService watcher, WatchEvent.Kind<?>... events) throws IOException { if (!file.toFile().exists()) { throw new RuntimeException("Directory to watch doesn't exist: " + file); } return register(watcher, events, NO_MODIFIERS); }
Example #20
Source File: AuthHeaderStrategyMount.java From spring-cloud-huawei with Apache License 2.0 | 5 votes |
public void run() { while (true) { try { WatchKey watchKey = service.take(); // 清理掉已发生的事件,否则会导致事件遗留,进入死循环 watchKey.pollEvents(); synchronized (this) { createAuthHeaders(); } watchKey.reset(); } catch (InterruptedException e) { LOGGER.error("error occured. detail : {}", e.getMessage()); } } }
Example #21
Source File: AbstractConfigService.java From java-trader with Apache License 2.0 | 5 votes |
private void watchThreadFunc() { logger.info("Config watch thread is started"); while(state!=ServiceState.Stopped) { WatchKey watchKey = null; try{ watchKey = watcher.poll(100, TimeUnit.MILLISECONDS); }catch(Throwable t) {} if ( watchKey==null ) { Thread.yield(); continue; } ConfigProviderEntry providerEntry = getEntryByFile(watchKey); if ( providerEntry!=null ) { for(WatchEvent<?> event:watchKey.pollEvents()) { WatchEvent<Path> ev = (WatchEvent<Path>) event; WatchEvent.Kind<?> kind = event.kind(); Path filename = ev.context(); if (kind == java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY && filename.toString().equals(providerEntry.file.getName())) { doReload(providerEntry); } } } watchKey.reset(); } logger.info("Config watch thread is stopped"); }
Example #22
Source File: ConfDirWatcher.java From OpenFalcon-SuitAgent with Apache License 2.0 | 5 votes |
@Override public void run() { WatchService watchService = WatchServiceUtil.watchModify(confDir); 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(); if("authorization.properties".equals(fileName)){ log.info("检测到授权文件authorization.properties有改动,正在重新配置相关插件配置"); Set<Plugin> plugins = PluginLibraryHelper.getPluginsAboutAuthorization(); for (Plugin plugin : plugins) { plugin.init(PluginLibraryHelper.getPluginConfig(plugin)); log.info("已完成插件{}的配置重新加载",plugin.pluginName()); } } } } key.reset(); } catch (Exception e) { log.error("插件配置文件监听异常",e); break; } } }
Example #23
Source File: JimfsPath.java From jimfs with Apache License 2.0 | 5 votes |
@Override public WatchKey register(WatchService watcher, WatchEvent.Kind<?>... events) throws IOException { checkNotNull(watcher); checkNotNull(events); if (!(watcher instanceof AbstractWatchService)) { throw new IllegalArgumentException( "watcher (" + watcher + ") is not associated with this file system"); } AbstractWatchService service = (AbstractWatchService) watcher; return service.register(this, Arrays.asList(events)); }
Example #24
Source File: Watcher.java From mangooio with Apache License 2.0 | 5 votes |
@SuppressWarnings("all") private void register(Path path) throws IOException { WatchKey watchKey = path.register( watchService, new WatchEvent.Kind[]{ StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE }); watchKeys.put(watchKey, path); }
Example #25
Source File: WatchServiceFileWatcher.java From mirror with Apache License 2.0 | 5 votes |
private void watchDirectory(Path directory) throws IOException { WatchKey key = directory.register(watchService, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY); if (log.isTraceEnabled()) { log.trace("Putting " + key + " = " + directory); } keyToPath.put(key, directory); pathToKey.put(directory, key); }
Example #26
Source File: NioNotifier.java From netbeans with Apache License 2.0 | 5 votes |
@Override protected WatchKey addWatch(String pathStr) throws IOException { Path path = Paths.get(pathStr); try { WatchKey key = path.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY); return key; } catch (ClosedWatchServiceException ex) { throw new IOException(ex); } }
Example #27
Source File: WindowsWatchService.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
@Override WatchKey register(Path path, WatchEvent.Kind<?>[] events, WatchEvent.Modifier... modifiers) throws IOException { // delegate to poller return poller.register(path, events, modifiers); }
Example #28
Source File: FileBasedOneShotLatch.java From flink with Apache License 2.0 | 5 votes |
private void awaitLatchFile(final WatchService watchService) throws InterruptedException { while (true) { WatchKey watchKey = watchService.take(); if (isReleasedOrReleasable()) { break; } watchKey.reset(); } }
Example #29
Source File: WatchServiceFileWatcher.java From mirror with Apache License 2.0 | 5 votes |
private void unwatchDirectory(WatchKey key, Path directory) { if (log.isTraceEnabled()) { log.trace("Removing " + key + " = " + directory); } pathToKey.remove(directory); keyToPath.remove(key); key.cancel(); }
Example #30
Source File: CostFedSummaryProvider.java From CostFed with GNU Affero General Public License v3.0 | 5 votes |
@Override public void run() { for (;;) { WatchKey key; try { key = watcher.take(); } catch (InterruptedException x) { return; } for (WatchEvent<?> event: key.pollEvents()) { WatchEvent.Kind<?> kind = event.kind(); if (kind == java.nio.file.StandardWatchEventKinds.OVERFLOW) { continue; } if (kind == java.nio.file.StandardWatchEventKinds.ENTRY_CREATE || kind == java.nio.file.StandardWatchEventKinds.ENTRY_DELETE || kind == java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY) { rebuildSummary(); } } boolean valid = key.reset(); if (!valid) { break; } } }