WindowsWatchKey init(long handle, Set<? extends WatchEvent.Kind<?>> events, boolean watchSubtree, NativeBuffer buffer, long countAddress, long overlappedAddress, int completionKey) { this.handle = handle; this.events = events; this.watchSubtree = watchSubtree; this.buffer = buffer; this.countAddress = countAddress; this.overlappedAddress = overlappedAddress; this.completionKey = completionKey; return this; }
private void watch() { try { WatchService watchService = directoryPath.getFileSystem().newWatchService(); directoryPath.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE); while (true) { WatchKey watchKey = watchService.take(); for (final WatchEvent<?> event : watchKey.pollEvents()) { takeActionOnChangeEvent(event); } } } catch (InterruptedException interruptedException) { System.out.println("Thread got interrupted:" + interruptedException); } catch (Exception exception) { exception.printStackTrace(); } }
@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; }
@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; } } }
/** * Processes subevents of the key. * @param key That has new events. * @param dir For the key. * @throws IOException If a subdirectory cannot be registered. */ private void processSubevents(final WatchKey key, final Path dir) throws IOException { for (final WatchEvent event : key.pollEvents()) { final WatchEvent.Kind kind = event.kind(); final Path name = (Path) event.context(); final Path child = dir.resolve(name); Logger.debug( this, "%s: %s%n", event.kind().name(), child ); if (kind == ENTRY_CREATE) { try { if (Files.isDirectory(child)) { this.processSubevents(child); } } catch (final IOException ex) { throw new IOException( "Failed to register subdirectories.", ex ); } } } }
private static void setWatcherOnThemeFile() { try { WatchService watchService = FileSystems.getDefault().newWatchService(); WatchKey watchKey = path.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY); while (true) { final WatchKey wk = watchService.take(); for (WatchEvent<?> event : wk.pollEvents()) { //we only register "ENTRY_MODIFY" so the context is always a Path. final Path changed = (Path) event.context(); System.out.println(changed); if (changed.endsWith("Theme.css")) { System.out.println("Theme.css has changed...reloading stylesheet."); scene.getStylesheets().clear(); scene.getStylesheets().add("resources/Theme.css"); } } boolean valid = wk.reset(); if (!valid) System.out.println("Watch Key has been reset..."); } } catch (Exception e) { /*Thrown to void*/ } }
@SuppressWarnings("unchecked") @Override public void run() { while (running) { try { final WatchKey watchKey = watcher.take(); for (final WatchEvent<?> event : watchKey.pollEvents()) { Path changed = (Path) event.context(); if (changed == null || event.kind() == StandardWatchEventKinds.OVERFLOW) { System.out.println("bad file watch event: " + event); continue; } changed = watchedDirectory.resolve(changed); for (final ListenerAndPath x : listeners) { if (Thread.interrupted() && !running) return; if (changed.startsWith(x.startPath)) { x.listener.fileChanged(changed, (Kind<Path>) event.kind()); } } } watchKey.reset(); } catch (final InterruptedException e) {} } }
@Override protected void run() { while(isRunning()) { try { final WatchKey key = watchService.take(); final WatchedDirectory watchedDirectory = dirsByKey.get(key); if(watchedDirectory == null) { logger.warning("Cancelling unknown key " + key); key.cancel(); } else { for(WatchEvent<?> event : key.pollEvents()) { watchedDirectory.dispatch((WatchEvent<Path>) event); } key.reset(); } } catch(InterruptedException e) { // ignore, just check for termination } } }
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(); } }
public MacOSXWatchKey(final Watchable file, final FSEventWatchService service, final WatchEvent.Kind<?>[] events) { super(service); this.file = file; boolean reportCreateEvents = false; boolean reportModifyEvents = false; boolean reportDeleteEvents = false; for(WatchEvent.Kind<?> event : events) { if(event == StandardWatchEventKinds.ENTRY_CREATE) { reportCreateEvents = true; } else if(event == StandardWatchEventKinds.ENTRY_MODIFY) { reportModifyEvents = true; } else if(event == StandardWatchEventKinds.ENTRY_DELETE) { reportDeleteEvents = true; } } this.reportCreateEvents = reportCreateEvents; this.reportDeleteEvents = reportDeleteEvents; this.reportModifyEvents = reportModifyEvents; }
private WatchEvent.Kind<?> translateActionToEvent(int action) { switch (action) { case FILE_ACTION_MODIFIED : return StandardWatchEventKinds.ENTRY_MODIFY; case FILE_ACTION_ADDED : case FILE_ACTION_RENAMED_NEW_NAME : return StandardWatchEventKinds.ENTRY_CREATE; case FILE_ACTION_REMOVED : case FILE_ACTION_RENAMED_OLD_NAME : return StandardWatchEventKinds.ENTRY_DELETE; default : return null; // action not recognized } }
/** * Handles a watchevent, it currently only handles the DELETE and MODIFY - create isn't handled * as when you create a new file you get two events - one of the create and one for the modify, * therefore it can be safely handled in the modify only. * * If the delete corresponds to a adapter loaded - it deregisterWithAdapterManager it with the * adatperManager If the modify is new / modified it passes it to the load method that handles * re-registering existing adapters * * @param event */ public void processWatchEvent(final WatchEvent<?> event) { synchronized (propertiesToAdapter) { if (LOG.isInfoEnabled()) { LOG.info("Logging watch event:" + event.kind() + ": " + event.context()); } // check it is ended with .properties if (isPropertyFile(event)) { String path = ((Path) event.context()).toString(); Adapter adapter = propertiesToAdapter.get(path); // if we have already seen this then deregister it if (adapter != null) { removeAdapter(path, adapter); } if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE || event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) { File file = new File(getPathToWatch().toString(), ((Path) event.context()).toString()); load(file); } } } }
private WatchKey createMockWatchKeyForPath(String configFilePath) { final WatchKey mockWatchKey = Mockito.mock(WatchKey.class); final List<WatchEvent<?>> mockWatchEvents = (List<WatchEvent<?>>) Mockito.mock(List.class); when(mockWatchKey.pollEvents()).thenReturn(mockWatchEvents); when(mockWatchKey.reset()).thenReturn(true); final Iterator mockIterator = Mockito.mock(Iterator.class); when(mockWatchEvents.iterator()).thenReturn(mockIterator); final WatchEvent mockWatchEvent = Mockito.mock(WatchEvent.class); when(mockIterator.hasNext()).thenReturn(true, false); when(mockIterator.next()).thenReturn(mockWatchEvent); // In this case, we receive a trigger event for the directory monitored, and it was the file monitored when(mockWatchEvent.context()).thenReturn(Paths.get(configFilePath)); when(mockWatchEvent.kind()).thenReturn(ENTRY_MODIFY); return mockWatchKey; }
/** * 是否监听事件 * * @return 是否监听 */ private boolean listenEvent() { WatchKey signal; try { Thread.sleep(500L); signal = watchService.take(); } catch (InterruptedException e) { return false; } for (WatchEvent<?> event : signal.pollEvents()) { log.info("event:" + event.kind() + "," + "filename:" + event.context()); pushEvent(event); } return signal.reset(); }
/** Notify file system event. */ void processEvent() { while(true) { WatchKey signal; try { signal = watcher.take(); } catch (InterruptedException e) { return; } for(WatchEvent<?> event : signal.pollEvents()) { Kind<?> kind = event.kind(); if(kind == StandardWatchEventKinds.OVERFLOW) { continue; } Path name = (Path)event.context(); notify(name.toAbsolutePath().toString(), kind); } key.reset(); } }
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); } }
private void processWatchKey(WatchKey watchKey) throws IOException { final long start = System.currentTimeMillis(); final List<WatchEvent<?>> events = watchKey.pollEvents(); int processed = 0; for (WatchEvent<?> event : events) { WatchEvent.Kind<?> kind = event.kind(); if (!watchEvents.contains(kind)) { LOG.trace("Ignoring an {} event to {}", event.context()); continue; } WatchEvent<Path> ev = cast(event); Path filename = ev.context(); if (processEvent(kind, filename)) { processed++; } } LOG.debug("Handled {} out of {} event(s) for {} in {}", processed, events.size(), watchDirectory, JavaUtils.duration(start)); }
public static void main(String[] args) throws Throwable { String tempDirPath = "/tmp"; System.out.println("Starting watcher for " + tempDirPath); Path p = Paths.get(tempDirPath); WatchService watcher = FileSystems.getDefault().newWatchService(); Kind<?>[] watchKinds = { ENTRY_CREATE, ENTRY_MODIFY }; p.register(watcher, watchKinds); mainRunner = Thread.currentThread(); new Thread(new DemoService()).start(); while (!done) { WatchKey key = watcher.take(); for (WatchEvent<?> e : key.pollEvents()) { System.out.println( "Saw event " + e.kind() + " on " + e.context()); if (e.context().toString().equals("MyFileSema.for")) { System.out.println("Semaphore found, shutting down watcher"); done = true; } } if (!key.reset()) { System.err.println("Key failed to reset!"); } } }
private void handleEvent(final WatchKeyHolder watchKeys, final WatchKey key) throws IOException { for (final WatchEvent<?> event : key.pollEvents()) { if (event.kind() == StandardWatchEventKinds.OVERFLOW) { continue; } final WatchEvent<Path> watchEvent = cast(event); Path path = watchKeys.get(key); if (path == null) { continue; } path = path.resolve(watchEvent.context()); if (Files.isDirectory(path, LinkOption.NOFOLLOW_LINKS)) { if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) { watchKeys.register(path); } } else { // Dispatch FileEvent fe = toEvent(watchEvent, path); if (fe != null) { this.eventBus.post(fe); } } } }
public void run() { Logger.info(TAG, "Modified %s STARTED", pin.getCode()); while (!closed) { WatchKey key = null; try { key = service.take(); } catch (InterruptedException e) { } if (this.key.equals(key)) { for (WatchEvent<?> event : key.pollEvents()) { WatchEvent.Kind<?> kind = event.kind(); if (!kind.equals(ENTRY_MODIFY) || !event.context().toString().equals(pin.getPath().getName())) continue; onChange(pin); } } boolean valid = key.reset(); if (!valid) { break; } } }
public MacOSXWatchKey(AbstractWatchService macOSXWatchService, Iterable<? extends WatchEvent.Kind<?>> events) { super(macOSXWatchService, null, events); boolean reportCreateEvents = false; boolean reportModifyEvents = false; boolean reportDeleteEvents = false; for (WatchEvent.Kind<?> event : events) { if (event == StandardWatchEventKinds.ENTRY_CREATE) { reportCreateEvents = true; } else if (event == StandardWatchEventKinds.ENTRY_MODIFY) { reportModifyEvents = true; } else if (event == StandardWatchEventKinds.ENTRY_DELETE) { reportDeleteEvents = true; } } this.reportCreateEvents = reportCreateEvents; this.reportDeleteEvents = reportDeleteEvents; this.reportModifyEvents = reportModifyEvents; }
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); } if(isJarFile(file)) { files.add(file); } else log.warn("[JAR Loader] Ignoring file "+file); } } key.reset(); } return files; }
private static WatchEvent.Modifier[] instantiateWatchModifiers() { if (JavaVersion.current().isJava9Compatible()) { return new WatchEvent.Modifier[]{}; } else { // use reflection to support older JVMs while supporting Java 9 WatchEvent.Modifier highSensitive = instantiateEnum("com.sun.nio.file.SensitivityWatchEventModifier", "HIGH"); if (FILE_TREE_WATCHING_SUPPORTED) { WatchEvent.Modifier fileTree = instantiateEnum("com.sun.nio.file.ExtendedWatchEventModifier", "FILE_TREE"); return new WatchEvent.Modifier[]{fileTree, highSensitive}; } else { return new WatchEvent.Modifier[]{highSensitive}; } } }
private static WatchEvent.Modifier instantiateEnum(String className, String enumName) { try { return (WatchEvent.Modifier) Enum.valueOf((Class<Enum>) Class.forName(className), enumName); } catch (ClassNotFoundException e) { throw UncheckedException.throwAsUncheckedException(e); } }
/** * Instantiates a new Json service registry config watcher. * * @param serviceRegistryDao the registry to callback */ JsonServiceRegistryConfigWatcher(final JsonServiceRegistryDao serviceRegistryDao) { try { this.serviceRegistryDao = serviceRegistryDao; this.watcher = FileSystems.getDefault().newWatchService(); final WatchEvent.Kind[] kinds = (WatchEvent.Kind[]) Arrays.asList(ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY).toArray(); LOGGER.debug("Created service registry watcher for events of type {}", kinds); this.serviceRegistryDao.getServiceRegistryDirectory().register(this.watcher, kinds); LOGGER.debug("Watching service registry directory at {}", this.serviceRegistryDao.getServiceRegistryDirectory()); } catch (final IOException e) { throw new RuntimeException(e); } }
/** * Handle event. * * @param key the key */ private void handleEvent(final WatchKey key) { this.readLock.lock(); try { for (final WatchEvent<?> event : key.pollEvents()) { if (event.count() <= 1) { final WatchEvent.Kind kind = event.kind(); //The filename is the context of the event. final WatchEvent<Path> ev = (WatchEvent<Path>) event; final Path filename = ev.context(); final Path parent = (Path) key.watchable(); final Path fullPath = parent.resolve(filename); final File file = fullPath.toFile(); LOGGER.trace("Detected event [{}] on file [{}]. Loading change...", kind, file); if (kind.name().equals(ENTRY_CREATE.name()) && file.exists()) { handleCreateEvent(file); } else if (kind.name().equals(ENTRY_DELETE.name())) { handleDeleteEvent(); } else if (kind.name().equals(ENTRY_MODIFY.name()) && file.exists()) { handleModifyEvent(file); } } } } finally { this.readLock.unlock(); } }
/** * Instantiates a new Json service registry config watcher. * * @param serviceRegistryDao the registry to callback */ public JsonServiceRegistryConfigWatcher(final JsonServiceRegistryDao serviceRegistryDao) { try { this.serviceRegistryDao = serviceRegistryDao; this.watcher = FileSystems.getDefault().newWatchService(); final WatchEvent.Kind[] kinds = (WatchEvent.Kind[]) Arrays.asList(ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY).toArray(); this.serviceRegistryDao.getServiceRegistryDirectory().register(this.watcher, kinds); } catch (final IOException e) { throw new RuntimeException(e); } }
/** * Instantiates a new Json service registry config watcher. * * @param serviceRegistryDao the registry to callback */ ServiceRegistryConfigWatcher(final ResourceBasedServiceRegistryDao serviceRegistryDao, final ApplicationEventPublisher eventPublisher) { try { this.serviceRegistryDao = serviceRegistryDao; this.watcher = FileSystems.getDefault().newWatchService(); final WatchEvent.Kind[] kinds = new WatchEvent.Kind[]{ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY}; LOGGER.debug("Created service registry watcher for events of type [{}]", (Object[]) kinds); this.serviceRegistryDao.getWatchableResource().register(this.watcher, kinds); this.applicationEventPublisher = eventPublisher; } catch (final IOException e) { throw Throwables.propagate(e); } }
/** * Handle event. * * @param key the key */ private void handleEvent(final WatchKey key) { this.readLock.lock(); try { //The filename is the context of the event. key.pollEvents().stream().filter(event -> event.count() <= 1).forEach(event -> { final WatchEvent.Kind kind = event.kind(); //The filename is the context of the event. final WatchEvent<Path> ev = (WatchEvent<Path>) event; final Path filename = ev.context(); final Path parent = (Path) key.watchable(); final Path fullPath = parent.resolve(filename); final File file = fullPath.toFile(); LOGGER.trace("Detected event [{}] on file [{}]. Loading change...", kind, file); if (kind.name().equals(ENTRY_CREATE.name()) && file.exists()) { handleCreateEvent(file); } else if (kind.name().equals(ENTRY_DELETE.name())) { handleDeleteEvent(); } else if (kind.name().equals(ENTRY_MODIFY.name()) && file.exists()) { handleModifyEvent(file); } }); } finally { this.readLock.unlock(); } }
public void dispatchEvent(WatchEvent.Kind<Path> event, Path path) { if (event == ENTRY_CREATE) { listener.pathCreated(path); } if (event == ENTRY_DELETE) { listener.pathRemoved(path); } if (event == ENTRY_MODIFY) { listener.pathModified(path); } }
public void observePathSet(PathSet pathSet, Listener listener) throws IOException { Preconditions.checkNotNull(listener); Preconditions.checkNotNull(pathSet); final Path rootPath = pathSet.getRootPath(); log.debug("Watching directory {} for changes matching: {}", rootPath, pathSet); final WatchKey key = rootPath.register(watcher, new WatchEvent.Kind[]{ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY}, SensitivityWatchEventModifier.HIGH); // Synchronize on keys to make the two operations atomic. synchronized (keys) { keys.putIfAbsent(key, Sets.newConcurrentHashSet()); keys.get(key).add(new WatchPath(pathSet, listener)); } }