List of usage examples for java.nio.file WatchKey pollEvents
List<WatchEvent<?>> pollEvents();
From source file:org.fcrepo.http.api.ExternalContentPathValidator.java
/** * Starts up monitoring of the allowed list configuration for changes. *//*from w ww . j a va 2 s .co m*/ private void monitorForChanges() { if (monitorRunning) { return; } final Path path = Paths.get(configPath); if (!path.toFile().exists()) { LOGGER.debug("Allow list configuration {} does not exist, disabling monitoring", configPath); return; } final Path directoryPath = path.getParent(); try { final WatchService watchService = FileSystems.getDefault().newWatchService(); directoryPath.register(watchService, ENTRY_MODIFY); monitorThread = new Thread(new Runnable() { @Override public void run() { try { for (;;) { WatchKey key; try { key = watchService.take(); } catch (final InterruptedException e) { LOGGER.debug("Interrupted the configuration monitor thread."); break; } for (final WatchEvent<?> event : key.pollEvents()) { final WatchEvent.Kind<?> kind = event.kind(); if (kind == OVERFLOW) { continue; } // If the configuration file triggered this event, reload it final Path changed = (Path) event.context(); if (changed.equals(path.getFileName())) { LOGGER.info("External binary configuration {} has been updated, reloading.", path); try { loadAllowedPaths(); } catch (final IOException e) { LOGGER.error("Failed to reload external locations configuration", e); } } // reset the key final boolean valid = key.reset(); if (!valid) { LOGGER.debug("Monitor of {} is no longer valid", path); break; } } } } finally { try { watchService.close(); } catch (final IOException e) { LOGGER.error("Failed to stop configuration monitor", e); } } monitorRunning = false; } }); } catch (final IOException e) { LOGGER.error("Failed to start configuration monitor", e); } monitorThread.start(); monitorRunning = true; }
From source file:MonitorSaurausRex.MainMenu.java
public boolean MonitorDirectory() { Path directory = Paths.get("C:/Users/" + user + "/Documents/"); try {//ww w. j a v a 2s . co m WatchService fileSystemWatchService = FileSystems.getDefault().newWatchService(); WatchKey watchKey = directory.register(fileSystemWatchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE); testTimer = new TimerTask() { @Override public void run() { checkPause = true; test = changeCheck(); if (test) { testTimer.cancel(); System.out.println("Quaritnen sucsessfully activates"); } } }; Timer timer = new Timer(); timer.schedule(testTimer, 0, 1000); while (true) { WatchKey watchKeyActual = fileSystemWatchService.take(); for (WatchEvent<?> event : watchKeyActual.pollEvents()) { WatchEvent.Kind<?> eventKind = event.kind(); if (eventKind == StandardWatchEventKinds.OVERFLOW) { continue; } WatchEvent<Path> eventPath = (WatchEvent<Path>) event; Path fileName = eventPath.context(); //timerCheck(); ????? //http://stackoverflow.com/questions/4044726/how-to-set-a-timer-in-java // boolean test = false; if (checkPause == false) { checkPause = true; } else { ChangeCounter++; System.out.println("Event " + eventKind + " occurred on " + fileName); } if (test) break; } boolean isReset = watchKeyActual.reset(); if (!isReset || test) { break; } } } catch (IOException | InterruptedException ioe) { } return true; /// EXIT METHOD }
From source file:org.apache.logging.log4j.core.appender.rolling.RollingAppenderDirectWriteTempCompressedFilePatternTest.java
@Test public void testAppender() throws Exception { final File dir = new File(DIR); dir.mkdirs();/*from w ww . j a v a 2 s . c om*/ try (final WatchService watcher = FileSystems.getDefault().newWatchService()) { WatchKey key = dir.toPath().register(watcher, StandardWatchEventKinds.ENTRY_CREATE); for (int i = 0; i < 100; ++i) { logger.debug("This is test message number " + i); } Thread.sleep(50); assertTrue("Directory not created", dir.exists() && dir.listFiles().length > 0); final File[] files = dir.listFiles(); assertNotNull(files); assertThat(files, hasItemInArray(that(hasName(that(endsWith(".gz")))))); int temporaryFilesCreated = 0; int compressedFiles = 0; key = watcher.take(); for (final WatchEvent<?> event : key.pollEvents()) { final WatchEvent<Path> ev = (WatchEvent<Path>) event; final Path filename = ev.context(); if (filename.toString().endsWith(".tmp")) { temporaryFilesCreated++; } if (filename.toString().endsWith(".gz")) { compressedFiles++; } } assertTrue("No temporary file created during compression", temporaryFilesCreated > 0); assertTrue("Temporarys file created not equals to compressed files", compressedFiles == temporaryFilesCreated); } }
From source file:acromusashi.stream.ml.common.spout.WatchTextBatchSpout.java
/** * ???????????????????/*from ww w . j ava2 s. com*/ * * @param collector Collector * @throws IOException * @throws InterruptedException ? */ @SuppressWarnings({ "rawtypes" }) protected void checkDataFile(TridentCollector collector) throws IOException, InterruptedException { // ????????????????? if (this.isInitialReaded == false) { List<String> fileContents = FileUtils.readLines(this.targetFile); emitTuples(fileContents, collector); this.isInitialReaded = true; // Path dirPath = new File(this.dataFileDir).toPath(); FileSystem fileSystem = dirPath.getFileSystem(); this.watcherService = fileSystem.newWatchService(); this.watchKey = dirPath.register(this.watcherService, new Kind[] { StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY }); return; } // ???????? WatchKey detectedKey = this.watcherService.poll(1, TimeUnit.SECONDS); // ??????????????????????? if (detectedKey == null || detectedKey.equals(this.watchKey) == false) { return; } try { // ??????????????? for (WatchEvent event : detectedKey.pollEvents()) { Path filePath = (Path) event.context(); // ????????????? if (filePath == null || this.targetFile.toPath().getFileName().equals(filePath.getFileName()) == false) { continue; } List<String> fileContents = FileUtils.readLines(this.targetFile); emitTuples(fileContents, collector); } } finally { detectedKey.reset(); } }
From source file:io.stallion.fileSystem.FileSystemWatcherRunner.java
private void doRun() { while (shouldRun) { Log.fine("Running the file system watcher."); WatchKey key; try {/*from w w w . ja va 2s . c om*/ key = watcher.take(); } catch (InterruptedException x) { Log.warn("Interuppted the watcher!!!"); try { Thread.sleep(1000); } catch (InterruptedException e) { Log.info("Exit watcher run method."); return; } continue; } Log.fine("Watch event key taken. Runner instance is {0}", this.hashCode()); for (WatchEvent<?> event : key.pollEvents()) { WatchEvent.Kind<?> kind = event.kind(); Log.fine("Event is " + kind); // This key is registered only // for ENTRY_CREATE events, // but an OVERFLOW event can // occur regardless if events // are lost or discarded. if (kind == OVERFLOW) { continue; } // The filename is the // context of the event. WatchEvent<Path> ev = (WatchEvent<Path>) event; Path filename = ev.context(); // Ignore emacs autosave files if (filename.toString().contains(".#")) { continue; } Log.finer("Changed file is {0}", filename); Path directory = (Path) key.watchable(); Log.finer("Changed directory is {0}", directory); Path fullPath = directory.resolve(filename); Log.fine("Changed path is {0}", fullPath); Boolean handlerFound = false; for (IWatchEventHandler handler : watchedByPath.values()) { Log.finer("Checking matching handler {0} {1}", handler.getInternalHandlerLabel(), handler.getWatchedFolder()); // Ignore private files if (filename.getFileName().startsWith(".")) { continue; } if ((handler.getWatchedFolder().equals(directory.toAbsolutePath().toString()) || (handler.getWatchTree() && directory.startsWith(handler.getWatchedFolder()))) && (StringUtils.isEmpty(handler.getExtension()) || fullPath.toString().endsWith(handler.getExtension()))) { String relativePath = filename.getFileName().toString(); Log.info("Handling {0} with watcher {1} for folder {2}", filename, handler.getClass().getName(), handler.getWatchedFolder()); try { handler.handle(relativePath, fullPath.toString(), kind, event); handlerFound = true; } catch (Exception e) { Log.exception(e, "Exception processing path={0} handler={1}", relativePath, handler.getClass().getName()); } } } if (!handlerFound) { Log.info("No handler found for {0}", fullPath); } } // Reset the key -- this step is critical if you want to // receive further watch events. If the key is no longer valid, // the directory is inaccessible so exit the loop. boolean valid = key.reset(); if (!valid) { Log.warn("Key invalid! Exit watch."); break; } } }
From source file:com.lukakama.serviio.watchservice.watcher.WatcherRunnable.java
@Override public void run() { try {//from w ww . j a v a2 s.c o m log.info("Watcher started."); initialize(); while (true) { checkInterrupted(); WatchKey watchKey = watcher.poll(CHECK_TIMEOUT, TimeUnit.MILLISECONDS); if (watchKey != null) { try { log.debug("Received watchKey: {} - {}", watchKey, watchKey.watchable()); Path parentPath = (Path) watchKey.watchable(); for (WatchEvent<?> event : watchKey.pollEvents()) { checkInterrupted(); log.debug("Received event: {} - {}", event.kind(), event.context()); if (event.kind() == StandardWatchEventKinds.OVERFLOW) { log.warn("Performing a full scan due loss of native FileSystem tracking data."); // Canceling the old watcher. IOUtils.closeQuietly(watcher); // Clean any pending unaccessible path. unaccessiblePaths.clear(); creatingPaths.clear(); modifyingPaths.clear(); // Re-initialize the monitoring. initialize(); } else { Path eventPath = parentPath.resolve((Path) event.context()); if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) { checkNewPath(eventPath); } else if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) { if (!unaccessiblePaths.contains(eventPath)) { if (isPathFullyAccessible(eventPath)) { handlePathChanged(eventPath); } else { unaccessiblePaths.add(eventPath); modifyingPaths.add(eventPath); log.debug( "File unacessible upon modification. Starting monitoring for '{}'.", eventPath); } } } else if (event.kind() == StandardWatchEventKinds.ENTRY_DELETE) { if (unaccessiblePaths.contains(eventPath)) { unaccessiblePaths.remove(eventPath); log.debug("Monitored file removed. Canceling monitoring for '{}'.", eventPath); if (modifyingPaths.contains(eventPath)) { modifyingPaths.remove(eventPath); handlePathRemoved(eventPath); } else { creatingPaths.remove(eventPath); } } else { handlePathRemoved(eventPath); } } } } } finally { watchKey.reset(); } } if (!unaccessiblePaths.isEmpty()) { checkAccessiblePaths(); } else if ((updateNotificationTimestamp != -1) && ((System.currentTimeMillis() - updateNotificationTimestamp) > CHECK_TIMEOUT)) { // Nothing happened since last update. Resetting the updateTimestamp and requesting a library update on // Serviio. updateNotificationTimestamp = -1; updateServiioReposotories(); } else if (updateNotificationTimestamp == -1) { // No pending path to checks and no pending updates to notify. Check external configuration changes. Object newFlagValue = getFieldValue(LibraryManager.getInstance(), "libraryAdditionsCheckerThread"); if ((configChangeFlag != null) && (newFlagValue != configChangeFlag)) { log.info("Detected configuration change. Restart monitoring."); configChangeFlag = newFlagValue; // Canceling the old watcher. IOUtils.closeQuietly(watcher); // Clean any pending unaccessible path. unaccessiblePaths.clear(); creatingPaths.clear(); modifyingPaths.clear(); // Re-initialize the monitoring. initialize(); } } } } catch (InterruptedException e) { // This thread has been interrupted. Just exit. return; } finally { // Release any bounded resource. unaccessiblePaths.clear(); creatingPaths.clear(); modifyingPaths.clear(); IOUtils.closeQuietly(watcher); log.info("Watcher stopped."); } }
From source file:org.flowerplatform.web.git.GitUtils.java
public void listenForChanges(File file) throws IOException { Path path = file.toPath();/* ww w. j a v a 2s.c o m*/ if (file.isDirectory()) { WatchService ws = path.getFileSystem().newWatchService(); path.register(ws, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY); WatchKey watch = null; while (true) { System.out.println("Watching directory: " + file.getPath()); try { watch = ws.take(); } catch (InterruptedException ex) { System.err.println("Interrupted"); } List<WatchEvent<?>> events = watch.pollEvents(); if (!watch.reset()) { break; } for (WatchEvent<?> event : events) { Kind<Path> kind = (Kind<Path>) event.kind(); Path context = (Path) event.context(); if (kind.equals(StandardWatchEventKinds.OVERFLOW)) { System.out.println("OVERFLOW"); } else if (kind.equals(StandardWatchEventKinds.ENTRY_CREATE)) { System.out.println("Created: " + context.getFileName()); } else if (kind.equals(StandardWatchEventKinds.ENTRY_DELETE)) { System.out.println("Deleted: " + context.getFileName()); } else if (kind.equals(StandardWatchEventKinds.ENTRY_MODIFY)) { System.out.println("Modified: " + context.getFileName()); } } } } else { System.err.println("Not a directory. Will exit."); } }
From source file:com.mycompany.trafficimportfileconverter2.Main2Controller.java
private void watchForConsumption() throws IOException { WatchService watcher = FileSystems.getDefault().newWatchService(); try {/*from w w w.j a v a2 s .c om*/ Path dir = getOutputDir().toPath(); WatchKey key = dir.register(watcher, ENTRY_DELETE); for (;;) { if (Thread.interrupted()) { key.cancel(); return; } try { key = watcher.take(); } catch (InterruptedException x) { return; } for (WatchEvent<?> event : key.pollEvents()) { WatchEvent.Kind<?> kind = event.kind(); // This key is registered only // for ENTRY_CREATE events, // but an OVERFLOW event can // occur regardless if events // are lost or discarded. if (kind == OVERFLOW) { continue; } // // The filename is the // // context of the event. WatchEvent<Path> ev = (WatchEvent<Path>) event; Path filepath = ev.context(); String filename = filepath.toString(); System.out.println("the filename was: " + filename); System.out.println(kind); Optional<String> res = findFile(filename); if (res.isPresent()) { System.out.println("BEFORE REMOVAL: " + myfiles.toString()); System.out.println("removing: " + res.get()); removeFromFiles(res.get()); System.out.println("Removed. Now: " + myfiles.toString()); int dpi = findThisDP(res.get()); if (-1 != dpi) { UI(() -> { datePickers[dpi].setStyle("-fx-background-color: lightgreen"); dayLabels[dpi].setStyle("-fx-background-color: lightgreen"); }); } log("Wide Orbit CONSUMED: " + filename); } else { System.out.println("is present was false for: " + filename); System.out.println(myfiles.toString()); } // Reset the key -- this step is critical if you want to // receive further watch events. If the key is no longer valid, // the directory is inaccessible so exit the loop. boolean valid = key.reset(); if (!valid) { return; } if (myfiles.isEmpty()) { key.cancel(); log("ALL WRITTEN FILES CONSUMED."); System.out.println("\n\n\n"); return; } } //end of events } //end of infinite loop } catch (IOException x) { System.err.println(x); } finally { Thread.currentThread().interrupt(); } }
From source file:erigo.filewatch.FileWatch.java
/** * Process new file events from the Java WatchService; stop when we see a file called "end.txt". * * This method uses Java WatchService, i.e. this is an event-driven method to get file updates. *//* w ww .java 2 s . c om*/ void processEvents_watchservice() throws IOException { for (;;) { // wait for key to be signaled WatchKey key; try { // The ".take()" method is a blocking read; can also use one of // the ".poll()" non-blocking methods if desired. key = watcher.take(); } catch (InterruptedException x) { System.err.println("processEvents(): got InterruptedException: " + x); return; } // process all events // base time for all files currently in the queue double eventTime = (double) (System.currentTimeMillis()); Boolean bDone = false; for (WatchEvent<?> event : key.pollEvents()) { Kind<?> kind = event.kind(); if (kind == OVERFLOW) { // Note: even though we've only registered for ENTRY_CREATE // events, we get OVERFLOW events automatically. System.err.println("OVERFLOW detected"); continue; } // Extract the filename from the event WatchEvent<Path> ev = cast(event); Path name = ev.context(); String filenameStr = name.toString(); bDone = processNewFile(filenameStr, eventTime); if (bDone) { break; } } boolean valid = key.reset(); if (!valid || bDone) { // Directory must have gone away or we have received the "end.txt" file // we're done break; } } }
From source file:org.pgptool.gui.tools.fileswatcher.MultipleFilesWatcher.java
private Thread buildThreadAndStart() { Thread ret = new Thread("FilesWatcher-" + watcherName) { @Override/*from w ww . j a va 2s .co m*/ public void run() { log.debug("FileWatcher thread started " + watcherName); boolean continueWatching = true; while (continueWatching) { WatchKey key; try { idleIfNoKeysRegistered(); key = watcher.take(); // NOTE: Since we're watching only one folder we assume // that there will be only one key for our folder } catch (ClosedWatchServiceException cwe) { log.error("ClosedWatchServiceException fired, stoppign thread.", cwe); return; } catch (InterruptedException x) { log.debug("FileWatcher thread stopped by InterruptedException", x); return; } catch (Throwable t) { log.error("Unexpected exception while checking for updates on watched file", t); return; } BaseFolder baseFolder = null; synchronized (watcherName) { baseFolder = keys.get(key); } if (baseFolder == null) { key.cancel(); continue; } for (WatchEvent<?> event : key.pollEvents()) { // Context for directory entry event is the file name of // entry WatchEvent<Path> ev = cast(event); Path name = ev.context(); Path child = baseFolder.path.resolve(name); String relativeFilename = FilenameUtils.getName(child.toString()); if (!baseFolder.interestedFiles.contains(relativeFilename) && !event.kind().equals(ENTRY_CREATE)) { continue; } // print out event log.debug("Watcher event: " + event.kind().name() + ", file " + child); dirWatcherHandler.handleFileChanged(event.kind(), child.toString()); } // reset key and remove from set if directory no longer // accessible boolean valid = key.reset(); if (!valid) { synchronized (watcherName) { keys.remove(key); baseFolders.remove(baseFolder.folder); } } } log.debug("FileWatcher thread stopped " + watcherName); } private void idleIfNoKeysRegistered() throws InterruptedException { while (true) { synchronized (watcherName) { if (!keys.isEmpty()) { break; } } Thread.sleep(500); } }; }; ret.start(); return ret; }