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(); } }
@SuppressWarnings ( "unchecked" ) private void handleEvent ( final WatchEvent<?> event ) { final Kind<?> kind = event.kind (); if ( kind == StandardWatchEventKinds.OVERFLOW ) { // FIXME: full rescan return; } final Path path = this.path.resolve ( ( (WatchEvent<Path>)event ).context () ); if ( kind == StandardWatchEventKinds.ENTRY_CREATE ) { this.listener.event ( path, Event.ADDED ); } else if ( kind == StandardWatchEventKinds.ENTRY_DELETE ) { this.listener.event ( path, Event.REMOVED ); } else if ( kind == StandardWatchEventKinds.ENTRY_MODIFY ) { this.listener.event ( path, Event.MODIFIED ); } }
@Override public void run() { while (true) { try { WatchKey key = watchService.take(); if (key == trustedKey) { for (WatchEvent<?> watchEvent : key.pollEvents()) { WatchEvent.Kind<?> kind = watchEvent.kind(); if (kind != StandardWatchEventKinds.OVERFLOW) { synchronizeTrustedCertificates(); } } } if (!key.reset()) { break; } } catch (InterruptedException e) { logger.error("Watcher interrupted.", e); } } }
public StorageWatcher ( final StorageManager storageManager, final BaseWatcher baseWatcher, final Path path, final WatchService watcher ) throws IOException { this.storageManager = storageManager; this.baseWatcher = baseWatcher; this.watcher = watcher; this.path = path; this.key = path.register ( watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY ); baseWatcher.addWatcherMap ( path, this ); final File nativeDir = new File ( path.toFile (), "native" ); baseWatcher.addWatcherMap ( nativeDir.toPath (), this ); logger.debug ( "Checking native dir: {}", nativeDir ); if ( nativeDir.exists () && nativeDir.isDirectory () ) { this.nativeKey = nativeDir.toPath ().register ( this.watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE ); check (); } }
public BaseWatcher ( final StorageManager storageManager, final File base ) throws IOException { this.storageManager = storageManager; this.base = base.toPath (); this.watcher = FileSystems.getDefault ().newWatchService (); this.baseKey = base.toPath ().register ( this.watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE ); logger.debug ( "Checking for initial storages" ); for ( final File child : this.base.toFile ().listFiles () ) { logger.debug ( "Found initial storage dir - {}", child ); checkAddStorage ( child.toPath () ); } startWatcher (); }
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) {} } }
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; }
/** * Creates a new CORS filter configuration watcher. * * @param filterConfig The filter configuration. Must not be * {@code null}. */ public CORSConfigurationFileWatcher(final FilterConfig filterConfig) { if (filterConfig == null) { throw new IllegalArgumentException("The servlet filter configuration must not be null"); } this.filterConfig = filterConfig; try { watcher = FileSystems.getDefault().newWatchService(); Path dir = determineConfigDir(); dir.register(watcher, StandardWatchEventKinds.ENTRY_MODIFY); LOG.fine("CORS Filter: Started watching for configuration file changes within " + dir); } catch (IOException e) { LOG.severe("CORS Filter: Failed to initialize file system watcher: " + e.getMessage()); } }
private FileWatcher(Map<Path, Consumer<Path>> registeredPaths) { this.registeredPaths = ImmutableMap.copyOf(registeredPaths); try { watchService = FileSystems.getDefault().newWatchService(); ImmutableMap.Builder<WatchKey, Path> watchedDirsBuilder = ImmutableMap.builder(); for (Map.Entry<Path, Consumer<Path>> entry : registeredPaths.entrySet()) { Path dir = entry.getKey().getParent(); WatchKey key = dir.register( watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY); watchedDirsBuilder.put(key, dir); } this.watchedDirs = watchedDirsBuilder.build(); } catch (IOException e) { throw new UncheckedIOException("Could not create WatchService.", e); } executor = Executors.newSingleThreadScheduledExecutor(); }
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 } }
/** * Create a WatchService to watch for changes in the given directory * and then attempt to close the WatchService and change a registration * at the same time. */ static void test(Path dir, ExecutorService pool) throws Exception { WatchService watcher = FileSystems.getDefault().newWatchService(); // initial registration dir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE); // submit tasks to close the WatchService and update the registration Future<Void> closeResult; Future<Boolean> registerResult; if (RAND.nextBoolean()) { closeResult = pool.submit(newCloserTask(watcher)); registerResult = pool.submit(newRegisterTask(watcher, dir)); } else { registerResult = pool.submit(newRegisterTask(watcher, dir)); closeResult = pool.submit(newCloserTask(watcher)); } closeResult.get(); registerResult.get(); }
/** * 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); } } } }
/** 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(); } }
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 subscribe(String id, Path path, Consumer<String> consumer) { if (this.watchService == null) { return; } // Register with a delay to ignore changes made at startup this.plugin.getScheduler().asyncLater(() -> { try { // doesn't need to be atomic if (this.keyMap.containsKey(id)) { throw new IllegalArgumentException("id already registered"); } WatchKey key = path.register(this.watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY); this.keyMap.put(id, new WatchedLocation(path, key, consumer)); } catch (IOException e) { e.printStackTrace(); } }, 40L); }
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 void createWatchService() { try { this.watchService = trustedDir.toPath().getFileSystem().newWatchService(); WatchKey trustedKey = trustedDir.toPath().register( watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY ); this.thread = new Thread(new Watcher(watchService, trustedKey)); this.thread.setName("ua-certificate-directory-watcher"); this.thread.setDaemon(true); this.thread.start(); } catch (IOException e) { logger.error("Error creating WatchService.", e); } }
/** * Instantiates a new file system watcher. * * @param parent the parent * @param path the path */ public void addWatch(FileWatcherUpdateInterface parent, Path path) { if (path != null) { // The directory that has to be watched needs to be registered. Any // object that implements the Watchable interface can be registered. // Register three events. i.e. whenever a file is created, deleted or // modified the watcher gets informed try { WatchKey key = path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY); watcherMap.put(key, parent); } catch (IOException e) { // Ignore } } }
/** * Register watchers recursively. Applicable for unix type operation systems. * * @param path to directory * @throws IOException during watchers registration */ private void registerWatchersRecursively(final Path path) throws IOException { Files.walkFileTree(path, new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) throws IOException { LOG.trace("Registering in watcher server: {}", () -> dir); final WatchKey watchKey = dir .register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY); // , SensitivityWatchEventModifier.HIGH); if (watchKeyConsumer != null) { watchKeyConsumer.accept(watchKey); } return FileVisitResult.CONTINUE; } }); }
public void addCollectionFileChangeListener(CollectionFileChangeListener listener) { if (null == listeners) { listeners = new ArrayList<CollectionFileChangeListener>(); listeners.add(listener); collectionFilesWatcherExecutor = Executors.newSingleThreadExecutor( new ThreadFactoryBuilder().setNameFormat("jsondb-files-watcher-thread-%d").build()); try { watcher = dbConfig.getDbFilesPath().getFileSystem().newWatchService(); dbConfig.getDbFilesPath().register(watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY); } catch (IOException e) { logger.error("Failed to create the WatchService for the dbFiles location", e); throw new JsonDBException("Failed to create the WatchService for the dbFiles location", e); } collectionFilesWatcherExecutor.execute(new CollectionFilesWatcherRunnable()); } else { listeners.add(listener); } }
public DirEvent(final JsonObject json) { m_base = Paths.get(json.getString(FIELD_BASE)); m_file = Paths.get(json.getString(FIELD_FILE)); m_hash = json.getInteger(FIELD_HASH); m_modtm = FileTime.fromMillis(json.getLong(FIELD_MODTM)); switch (json.getString(FIELD_KIND)) { case "ENTRY_CREATE": m_kind = StandardWatchEventKinds.ENTRY_CREATE; break; case "ENTRY_MODIFY": m_kind = StandardWatchEventKinds.ENTRY_MODIFY; break; case "ENTRY_DELETE": m_kind = StandardWatchEventKinds.ENTRY_DELETE; break; default: m_kind = null; break; } }
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(); } }
public static void main(String[] args) throws Exception { WatchService watchService=FileSystems.getDefault().newWatchService(); Paths.get("C:/").register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY); while(true) { WatchKey key=watchService.take(); for(WatchEvent<?> event:key.pollEvents()) { System.out.println(event.context()+"发生了"+event.kind()+"事件"); } if(!key.reset()) { break; } } }
public PluginEngine(final PluginListener pluginListener) throws IOException { if (pluginListener == null) { throw new IllegalArgumentException("pluginListener cannot be null"); } pluginDir = Paths.get(System.getProperty("shootoff.plugins")); this.pluginListener = pluginListener; if (!Files.exists(pluginDir) && !pluginDir.toFile().mkdirs()) { logger.error("The path specified by shootoff.plugins doesn't exist and we couldn't create it."); return; } if (!Files.isDirectory(pluginDir)) { logger.error("Can't enumerate existing plugins or watch for new plugins because the " + "shootoff.plugins property is not set to a directory"); } registerDefaultStandardTrainingExercises(); enumerateExistingPlugins(); registerDefaultProjectorExercises(); pluginDir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE); }
public MacOSXWatchKey(Path path, AbstractWatchService macOSXWatchService, WatchEvent.Kind<?>[] events) { super(macOSXWatchService); this.path = path; 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 static void watch() throws Exception { WatchService watchService=FileSystems.getDefault().newWatchService(); Paths.get("C:/").register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY,StandardWatchEventKinds.OVERFLOW); while(true) { WatchKey key=watchService.take(); //watchService.poll(10000, TimeUnit.valueOf("2014-8-26")); for(WatchEvent<?> event:key.pollEvents()) { System.out.println(event.context()+"发生了"+event.kind()+"事件"+event.count()); } if(!key.reset()) { break; } } }
public FileAndDirectoryWatcher() throws IOException, URISyntaxException { // set the send list path this.excelListDir = Paths.get( FileTransferClient.class.getResource("./FileList/").getFile()); // set the send file path this.fileSendDir = Paths.get( FileTransferClient.class.getResource("./FileTransferDirectory/").getFile()); // create the watcher watcher = FileSystems.getDefault().newWatchService(); // register the events excelListDir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE); fileSendDir.register(watcher, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE); }
private void processSendListEvt(WatchEvent.Kind<?> kind) throws IOException { if ((kind == StandardWatchEventKinds.ENTRY_CREATE) || (kind == StandardWatchEventKinds.ENTRY_MODIFY)) { if (!isExcelLocked && allowUpdate) { // update (new UpdateTable()).execute(); allowUpdate = false; retry = false; // update table log.append("list update."+Constants.NEWLINE); } else { // set retry retry = true; log.append("excel file is locked. wait..." + Constants.NEWLINE); } } else { // the DELETE evt System.out.println("The sync excel has been deleted"); } }
@Override public void run() { try { WatchService watchService = FileSystems.getDefault().newWatchService(); propsFileFolder.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY); while (true) { WatchKey wk = watchService.take(); for (WatchEvent<?> event : wk.pollEvents()) { Path changed = (Path) event.context(); Path changedFile = propsFileFolder.resolve(changed.toString()); if (changed.getFileName().toString().endsWith(fileName) && Files.exists(changedFile)) { log.info("File '{}' changed. Updating values.", changedFile); limits.tokenBody = FileLoaderUtil.readFileAsString(fileName); } } // reset the key boolean valid = wk.reset(); if (!valid) { log.info("Key has been not unregistered."); } } } catch (IOException | InterruptedException e) { log.warn("Error monitoring '{}' file. Reloadable properties are not enabled.", SERVER_PROPERTIES_FILENAME, e); } }
public void remove(EphemeralFsPath name) { if(!isDir()) { throw new IllegalStateException(); } assertOnlyFileName(name); DirectoryEntry entry = children.remove(name.toFileName()); if(entry == null) { throw new IllegalStateException("removing but nothing exists, name:" + name); } if(!entry.isSymbolicLink() && !entry.getDestination().parents.remove(this)) { throw new IllegalStateException("failed to remove parent? this:" + this + " entry:" + entry); } if(entry.getDestination() != null) { entry.getDestination().removeLink(); } EphemeralFsWatchEvent event = new EphemeralFsWatchEvent(name, StandardWatchEventKinds.ENTRY_DELETE); fs.getWatchRegistry().hearChange(this, event); contents.setDirty(true); }
public void notifyChange(EphemeralFsPath path) throws NoSuchFileException { ResolvedPath resolvedPath; try { resolvedPath = ResolvedPath.resolve(path.getParent(), false); } catch (FileSystemException e) { //we can't resolve the path //ignore and skip notifying return; } if(!resolvedPath.hasTarget()) { return; } if(resolvedPath.getTarget().isDir() && resolvedPath.getTarget().getName(this) != null) { EphemeralFsWatchEvent event = new EphemeralFsWatchEvent( path, StandardWatchEventKinds.ENTRY_MODIFY); fs.getWatchRegistry().hearChange(resolvedPath.getTarget(), event); } }