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 File: WatchServiceHolder.java From elexis-3-core with Eclipse Public License 1.0 | 7 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 File: FileWatcher.java From atlas with 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 #3
Source File: FileMonitorJdkImpl.java From util4j with 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 #4
Source File: FileChangedWatcher.java From karate with 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 #5
Source File: LotsOfCancels.java From openjdk-jdk8u 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: FileChangeIngestorTest.java From nifi-minifi with 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 #7
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 #8
Source File: PhotatoFilesManager.java From Photato with 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 #9
Source File: LotsOfCancels.java From hottub 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 #10
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 #11
Source File: AbstractFileTransformationService.java From openhab-core with 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 #12
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 #13
Source File: FileWatchService.java From training with 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 #14
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 #15
Source File: LotsOfCancels.java From jdk8u_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 #16
Source File: DefaultCertificateValidator.java From opc-ua-stack with 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 #17
Source File: AbstractFileTransformationService.java From smarthome with 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 #18
Source File: AbstractDirectoryWatcher.java From debezium-incubator with Apache License 2.0 | 5 votes |
AbstractDirectoryWatcher(WatchService watchService, Path directory, Duration pollInterval, Set<WatchEvent.Kind> kinds) throws IOException { this.watchService = watchService; this.pollInterval = pollInterval; this.directory = directory; this.kinds = kinds; directory.register(watchService, kinds.toArray(new WatchEvent.Kind[kinds.size()])); }
Example #19
Source File: LogSearchConfigLocalUpdater.java From ambari-logsearch with 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 #20
Source File: AbstractFileTransformationService.java From smarthome with 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 #21
Source File: UnixSshFileSystem.java From jsch-nio with MIT License | 5 votes |
@Override public WatchService newWatchService() throws IOException { if ( getBooleanFromEnvironment( "watchservice.inotify" ) ) { return UnixSshFileSystemWatchService.inotifyWatchService(); } else { // TODO make sure these values are set in environment, or get good // defaults return UnixSshFileSystemWatchService.pollingWatchService( getLongFromEnvironment( "watchservice.polling.interval" ), getTimeUnitFromEnvironment( "watchservice.polling.timeunit" ) ); } }
Example #22
Source File: DeleteInterference.java From dragonwell8_jdk with 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 #23
Source File: Watcher.java From packagedrone with 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" ); } } } }
Example #24
Source File: UnixSshPath.java From jsch-nio with 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 #25
Source File: FileMonitorSocket.java From dawnsci with Eclipse Public License 1.0 | 5 votes |
public QueueReader(WatchService watcher, Session session, String path, String dataset, boolean writing) { this.watcher = watcher; this.session = session; this.spath = path; this.sdataset = dataset; this.writing = writing; }
Example #26
Source File: DeleteInterference.java From jdk8u-jdk with 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 #27
Source File: RunnerRun.java From stagen with Apache License 2.0 | 5 votes |
private void register(final WatchService watcher, Path ... dirs) throws IOException { for(Path dir: dirs) { Files.walkFileTree(dir, new SimpleFileVisitor<Path>(){ @Override public FileVisitResult preVisitDirectory(Path d, BasicFileAttributes attrs) throws IOException { d.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY); return FileVisitResult.CONTINUE; } }); } }
Example #28
Source File: JPath.java From baratine with GNU General Public License v2.0 | 5 votes |
@Override public WatchKey register(WatchService watcher, Kind<?>[] events, Modifier... modifiers) throws IOException { if (events.length == 0) { throw new IllegalArgumentException(L.l("no events specified to watch on: {0}", toUri())); } JWatchService jWatcher = (JWatchService) watcher; WatchKey key = jWatcher.register(this, events, modifiers); return key; }
Example #29
Source File: BuckUnixPath.java From buck with Apache License 2.0 | 5 votes |
@Override public WatchKey register( WatchService watcher, WatchEvent.Kind<?>[] events, WatchEvent.Modifier... modifiers) throws IOException { // TODO(buck_team): do not recourse to default Path implementation return asDefault().register(watcher, events, modifiers); }
Example #30
Source File: FileBasedOneShotLatch.java From flink with Apache License 2.0 | 5 votes |
private static void watchForLatchFile(final WatchService watchService, final Path parentDir) { try { parentDir.register( watchService, new WatchEvent.Kind[]{StandardWatchEventKinds.ENTRY_CREATE}, SensitivityWatchEventModifier.HIGH); } catch (IOException e) { throw new RuntimeException(e); } }