java.nio.file.WatchService Java Examples
The following examples show how to use
java.nio.file.WatchService.
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 Project: elexis-3-core Author: elexis File: WatchServiceHolder.java License: Eclipse Public License 1.0 | 6 votes |
public WatchServiceHolder(TaskServiceImpl taskServiceImpl){ logger = LoggerFactory.getLogger(getClass()); taskService = taskServiceImpl; incurredTasks = Collections.synchronizedMap(new HashMap<WatchKey, ITaskDescriptor>()); WatchService initWatchService; try { initWatchService = FileSystems.getDefault().newWatchService(); } catch (IOException ioe) { initWatchService = null; logger.error( "Error instantiating WatchService, filesystem events will not be picked up.", ioe); } watchService = initWatchService; pollerThread = new WatchServicePoller(); }
Example #2
Source Project: spring-cloud-gcp Author: spring-cloud File: PubSubEmulator.java License: 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 #3
Source Project: openhab-core Author: openhab File: AbstractFileTransformationService.java License: Eclipse Public License 2.0 | 6 votes |
/** * Ensures that a modified or deleted cached files does not stay in the cache */ private void processFolderEvents(final WatchService watchService) { 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(); } }
Example #4
Source Project: dragonwell8_jdk Author: alibaba File: LotsOfCancels.java License: 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 #5
Source Project: TencentKona-8 Author: Tencent File: LotsOfCancels.java License: 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 Project: training Author: victorrentea File: FileWatchService.java License: MIT License | 6 votes |
public static void main(String[] args) throws IOException, InterruptedException { Path tmpDir = Paths.get("tmp"); WatchService watchService = FileSystems.getDefault().newWatchService(); Path monitoredFolder = tmpDir; monitoredFolder.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE); tmpDir.toFile().mkdirs(); new FileChanger(tmpDir).start(); while (true) { System.out.println("Waiting for event"); WatchKey watchKey = watchService.take(); for (WatchEvent<?> event : watchKey.pollEvents()) { System.out.println("Detected event " + event.kind().name() + " on file " + event.context().toString()); } watchKey.reset(); } }
Example #7
Source Project: hottub Author: dsrg-uoft File: LotsOfCancels.java License: 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 #8
Source Project: openjdk-jdk8u Author: AdoptOpenJDK File: LotsOfCancels.java License: 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 #9
Source Project: atlas Author: apache File: FileWatcher.java License: Apache License 2.0 | 6 votes |
public void start() throws IOException { if (existsAndReadyCheck()) { return; } WatchService watcher = FileSystems.getDefault().newWatchService(); Path pathToWatch = FileSystems.getDefault().getPath(fileToWatch.getParent()); register(watcher, pathToWatch); try { LOG.info(String.format("Migration File Watcher: Watching: %s", fileToWatch.toString())); startWatching(watcher); } catch (InterruptedException ex) { LOG.error("Migration File Watcher: Interrupted!"); } finally { watcher.close(); } }
Example #10
Source Project: SuitAgent Author: DevopsJK File: PluginPropertiesWatcher.java License: 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 #11
Source Project: jdk8u_jdk Author: JetBrains File: LotsOfCancels.java License: 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 #12
Source Project: opc-ua-stack Author: kevinherron File: DefaultCertificateValidator.java License: Apache License 2.0 | 6 votes |
private void createWatchService() { try { WatchService watchService = FileSystems.getDefault().newWatchService(); WatchKey trustedKey = trustedDir.toPath().register( watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY ); Thread thread = new Thread(new Watcher(watchService, trustedKey)); thread.setName("ua-certificate-directory-watcher"); thread.setDaemon(true); thread.start(); } catch (IOException e) { logger.error("Error creating WatchService.", e); } }
Example #13
Source Project: smarthome Author: eclipse-archived File: AbstractFileTransformationService.java License: Eclipse Public License 2.0 | 6 votes |
private synchronized WatchService getWatchService() throws TransformationException { WatchService watchService = this.watchService; if (watchService != null) { return watchService; } try { watchService = this.watchService = FileSystems.getDefault().newWatchService(); } catch (IOException e) { logger.error("Unable to start transformation directory monitoring"); throw new TransformationException("Cannot get a new watch service."); } watchSubDirectory("", watchService); return watchService; }
Example #14
Source Project: Photato Author: trebonius0 File: PhotatoFilesManager.java License: GNU Affero General Public License v3.0 | 6 votes |
public PhotatoFilesManager(Path rootFolder, FileSystem fileSystem, IMetadataAggregator metadataGetter, IThumbnailGenerator thumbnailGenerator, IFullScreenImageGetter fullScreenImageGetter, boolean prefixOnlyMode, boolean indexFolderName, boolean useParallelPicturesGeneration) throws IOException { this.fileSystem = fileSystem; this.metadataAggregator = metadataGetter; this.thumbnailGenerator = thumbnailGenerator; this.fullScreenImageGetter = fullScreenImageGetter; this.rootFolder = new PhotatoFolder(rootFolder, rootFolder); this.searchManager = new SearchManager(prefixOnlyMode, indexFolderName); this.albumsManager = new AlbumsManager(); this.prefixOnlyMode = prefixOnlyMode; this.useParallelPicturesGeneration = useParallelPicturesGeneration; WatchService watcher = this.fileSystem.newWatchService(); this.watchedDirectoriesKeys = new HashMap<>(); this.watchedDirectoriesPaths = new HashMap<>(); this.runInitialFolderExploration(watcher, this.rootFolder); this.watchServiceThread = new WatchServiceThread(watcher); this.watchServiceThread.start(); }
Example #15
Source Project: nifi-minifi Author: apache File: FileChangeIngestorTest.java License: Apache License 2.0 | 6 votes |
@Before public void setUp() throws Exception { mockWatchService = Mockito.mock(WatchService.class); notifierSpy = Mockito.spy(new FileChangeIngestor()); mockDifferentiator = Mockito.mock(Differentiator.class); testNotifier = Mockito.mock(ConfigurationChangeNotifier.class); notifierSpy.setConfigFilePath(Paths.get(TEST_CONFIG_PATH)); notifierSpy.setWatchService(mockWatchService); notifierSpy.setDifferentiator(mockDifferentiator); notifierSpy.setConfigurationChangeNotifier(testNotifier); testProperties = new Properties(); testProperties.put(FileChangeIngestor.CONFIG_FILE_PATH_KEY, TEST_CONFIG_PATH); testProperties.put(FileChangeIngestor.POLLING_PERIOD_INTERVAL_KEY, FileChangeIngestor.DEFAULT_POLLING_PERIOD_INTERVAL); }
Example #16
Source Project: karate Author: intuit File: FileChangedWatcher.java License: MIT License | 6 votes |
public void watch() throws InterruptedException, IOException { try { final Path directoryPath = file.toPath().getParent(); final WatchService watchService = FileSystems.getDefault().newWatchService(); directoryPath.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY); while (true) { final WatchKey wk = watchService.take(); for (WatchEvent<?> event : wk.pollEvents()) { final Path fileChangedPath = (Path) event.context(); if (fileChangedPath.endsWith(file.getName())) { onModified(); } } wk.reset(); } } catch (Exception e) { logger.error("exception when handling change of mock file: {}", e.getMessage()); } }
Example #17
Source Project: util4j Author: juebanlin File: FileMonitorJdkImpl.java License: Apache License 2.0 | 6 votes |
public void simpleTest(Path path) throws Exception { WatchService watchService=FileSystems.getDefault().newWatchService(); path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY); while(true) { WatchKey watchKey=watchService.take(); List<WatchEvent<?>> watchEvents = watchKey.pollEvents(); for(WatchEvent<?> event : watchEvents){ //TODO 根据事件类型采取不同的操作。。。。。。。 System.out.println("["+event.context()+"]文件发生了["+event.kind()+"]事件"); } watchKey.reset(); } }
Example #18
Source Project: jsch-nio Author: lucastheisen File: UnixSshPath.java License: MIT License | 5 votes |
/** {@inheritDoc} */ @Override public WatchKey register( WatchService watcher, Kind<?>[] events, Modifier... modifiers ) throws IOException { if ( watcher == null ) { throw new NullPointerException(); } if ( !(watcher instanceof UnixSshFileSystemWatchService) ) { throw new ProviderMismatchException(); } if ( !getFileSystem().provider().readAttributes( this, BasicFileAttributes.class ).isDirectory() ) { throw new NotDirectoryException( this.toString() ); } getFileSystem().provider().checkAccess( this, AccessMode.READ ); return ((UnixSshFileSystemWatchService) watcher).register( this, events, modifiers ); }
Example #19
Source Project: cellery-security Author: wso2 File: ConfigUpdater.java License: Apache License 2.0 | 5 votes |
public void run() { log.info("Running configuration updater.."); String configFilePath = CellStsUtils.getConfigFilePath(); Path directoryPath = Paths.get(configFilePath.substring(0, configFilePath.lastIndexOf("/"))); try { while (true) { WatchService watcher = directoryPath.getFileSystem().newWatchService(); directoryPath.register(watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY); log.debug("Waiting for config file change"); WatchKey watckKey = watcher.take(); List<WatchEvent<?>> events = watckKey.pollEvents(); log.debug("Received events: ...."); for (WatchEvent event : events) { if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) { log.info("Updating file on {} event", StandardWatchEventKinds.ENTRY_CREATE); CellStsUtils.buildCellStsConfiguration(); CellStsUtils.readUnsecuredContexts(); } if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) { log.info("Updating file on {} event", StandardWatchEventKinds.ENTRY_MODIFY); CellStsUtils.buildCellStsConfiguration(); CellStsUtils.readUnsecuredContexts(); } } } } catch (IOException | InterruptedException | CelleryCellSTSException e) { log.error("Error while updating configurations on file change ", e); } }
Example #20
Source Project: nano-framework Author: nano-projects File: TomcatCustomServer.java License: Apache License 2.0 | 5 votes |
protected void watcherPid(final File pidFile) throws IOException { final WatchService watcher = FileSystems.getDefault().newWatchService(); final Path path = Paths.get("."); path.register(watcher, StandardWatchEventKinds.ENTRY_DELETE); Executors.newFixedThreadPool(1, (runnable) -> { final Thread tomcat = new Thread(runnable); tomcat.setName("Tomcat PID Watcher: " + System.currentTimeMillis()); return tomcat; }).execute(() -> { try { for (;;) { final WatchKey watchKey = watcher.take(); final List<WatchEvent<?>> events = watchKey.pollEvents(); for (WatchEvent<?> event : events) { final String fileName = ((Path) event.context()).toFile().getAbsolutePath(); if (pidFile.getAbsolutePath().equals(fileName)) { LOGGER.info("tomcat.pid已被删除,应用进入退出流程"); System.exit(0); } } watchKey.reset(); } } catch (final InterruptedException e) { LOGGER.info("Stoped File Watcher"); } }); }
Example #21
Source Project: jsr203-hadoop Author: damiencarol File: TestFileSystem.java License: Apache License 2.0 | 5 votes |
@Test @Ignore public void newWatchService() throws IOException { Path pathToTest = Paths.get(clusterUri); WatchService ws = pathToTest.getFileSystem().newWatchService(); Assert.assertNotNull(ws); }
Example #22
Source Project: flink Author: flink-tpc-ds File: FileBasedOneShotLatch.java License: 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 #23
Source Project: dragonwell8_jdk Author: alibaba File: DeleteInterference.java License: GNU General Public License v2.0 | 5 votes |
private static void openAndCloseWatcher(Path dir) { FileSystem fs = FileSystems.getDefault(); for (int i = 0; i < ITERATIONS_COUNT; i++) { try (WatchService watcher = fs.newWatchService()) { dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY); } catch (IOException ioe) { // ignore } } }
Example #24
Source Project: smarthome Author: eclipse-archived File: AbstractFileTransformationService.java License: Eclipse Public License 2.0 | 5 votes |
private void watchSubDirectory(String subDirectory, final WatchService watchService) { if (watchedDirectories.indexOf(subDirectory) == -1) { String watchedDirectory = getSourcePath() + subDirectory; Path transformFilePath = Paths.get(watchedDirectory); try { transformFilePath.register(watchService, ENTRY_DELETE, ENTRY_MODIFY); logger.debug("Watching directory {}", transformFilePath); watchedDirectories.add(subDirectory); } catch (IOException e) { logger.warn("Unable to watch transformation directory : {}", watchedDirectory); cachedFiles.clear(); } } }
Example #25
Source Project: jimfs Author: google File: WatchServiceConfigurationTest.java License: Apache License 2.0 | 5 votes |
@Test public void testPollingConfig() { WatchServiceConfiguration polling = WatchServiceConfiguration.polling(50, MILLISECONDS); WatchService watchService = polling.newWatchService(fs.getDefaultView(), fs.getPathService()); assertThat(watchService).isInstanceOf(PollingWatchService.class); PollingWatchService pollingWatchService = (PollingWatchService) watchService; assertThat(pollingWatchService.interval).isEqualTo(50); assertThat(pollingWatchService.timeUnit).isEqualTo(MILLISECONDS); }
Example #26
Source Project: flink Author: apache File: FileBasedOneShotLatch.java License: Apache License 2.0 | 5 votes |
private static WatchService createWatchService(final Path parentDir) { try { return parentDir.getFileSystem().newWatchService(); } catch (IOException e) { throw new RuntimeException(e); } }
Example #27
Source Project: arcusplatform Author: arcus-smart-home File: DriverWatcher.java License: Apache License 2.0 | 5 votes |
public void watch() { final WatchService watcher; if (watchDir == null) { return; } try { watcher = FileSystems.getDefault().newWatchService(); watchDir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY); logger.trace("Watching driver directory [{}]", watchDir); } catch (IOException ex) { logger.error("Could not register watcher for driver directory [{}]", watchDir); return; } executor.submit(new Runnable() { @Override public void run() { while (true) { WatchKey key = null; try { key = watcher.take(); } catch (InterruptedException e) { logger.error("Interrupted Exception encountered [{}]", e); } if (key != null) { if (key.pollEvents().size() > 0) { // Something has changed. That's all we need to know. for (DriverWatcherListener listener : listeners) { listener.onChange(); } } boolean isValid = key.reset(); if (!isValid) { logger.error("Unable to watch driver directory. Watcher key invalid."); } } } } }); }
Example #28
Source Project: TencentKona-8 Author: Tencent File: DeleteInterference.java License: GNU General Public License v2.0 | 5 votes |
private static void openAndCloseWatcher(Path dir) { FileSystem fs = FileSystems.getDefault(); for (int i = 0; i < ITERATIONS_COUNT; i++) { try (WatchService watcher = fs.newWatchService()) { dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY); } catch (IOException ioe) { // ignore } } }
Example #29
Source Project: ambari-logsearch Author: apache File: LogSearchConfigLocalUpdater.java License: Apache License 2.0 | 5 votes |
public LogSearchConfigLocalUpdater(final Path path, final WatchService watchService, final InputConfigMonitor inputConfigMonitor, final Map<String, String> inputFileContentsMap, final JsonParser parser, final JsonArray globalConfigNode, final Pattern serviceNamePattern) { this.path = path; this.watchService = watchService; this.inputConfigMonitor = inputConfigMonitor; this.inputFileContentsMap = inputFileContentsMap; this.parser = parser; this.globalConfigNode = globalConfigNode; this.serviceNamePattern = serviceNamePattern; }
Example #30
Source Project: packagedrone Author: eclipse File: Watcher.java License: Eclipse Public License 1.0 | 5 votes |
private void process () throws IOException { logger.warn ( "Start watching: {}", this.path ); try ( final WatchService watcher = this.path.getFileSystem ().newWatchService () ) { this.path.register ( watcher, ENTRY_CREATE, ENTRY_MODIFY, ENTRY_DELETE ); processExisting ( this.path ); for ( ;; ) { WatchKey key; try { key = watcher.take (); } catch ( final InterruptedException e ) { return; } for ( final WatchEvent<?> event : key.pollEvents () ) { logger.debug ( "Handle event: {} - {}", event.kind (), event.context () ); handleEvent ( event ); } if ( !key.reset () ) { throw new RuntimeException ( "Key got cancelled" ); } } } }