List of usage examples for java.nio.file WatchKey reset
boolean reset();
From source file:bjerne.gallery.service.impl.GalleryRootDirConfigJob.java
private void watchForChanges() { Path dir = configFile.getParentFile().toPath(); try {/* w ww . jav a 2s . c o m*/ WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY); for (;;) { try { key = watcher.take(); } catch (InterruptedException | ClosedWatchServiceException e) { LOG.info("Interrupted during watcher.take(). Exiting watch loop."); return; } for (WatchEvent<?> event : key.pollEvents()) { WatchEvent.Kind<?> kind = event.kind(); if (kind == OVERFLOW) { continue; } @SuppressWarnings("unchecked") WatchEvent<Path> ev = (WatchEvent<Path>) event; Path filename = ev.context(); Path child = dir.resolve(filename); if (child.equals(configFile.toPath())) { LOG.debug("File was changed."); updateConfigFromFile(); } } boolean valid = key.reset(); if (!valid) { break; } } } catch (IOException ioe) { LOG.error("Exception in filewatcher loop. Exiting.", ioe); } }
From source file:org.mail.bridge.FolderMonitor.java
@SuppressWarnings("unchecked") @Override/*from w w w . j a v a 2s .c om*/ public void run() { Path outboxPath = outboxFolder.toPath(); WatchService watcher; try { watcher = FileSystems.getDefault().newWatchService(); outboxPath.register(watcher, ENTRY_CREATE); } catch (IOException e) { LOG.error(e.getMessage(), e); throw new IllegalStateException(e); } while (true) { WatchKey key; try { key = watcher.take(); } catch (InterruptedException e) { LOG.error(e.getMessage(), e); throw new IllegalStateException(e); } if (timer != null) { timer.cancel(); timer = null; } LOG.info("Folder '{}' content changed", outboxFolder.getAbsolutePath()); for (WatchEvent<?> event : key.pollEvents()) { if (event.kind() == OVERFLOW) continue; File patch = outboxPath.resolve(((WatchEvent<Path>) event).context()).toFile(); if (fileFilter.accept(patch)) files.add(patch); } if (!files.isEmpty()) { timer = new Timer(); timer.schedule(new ProcessFilesTimerTask(), NEW_FILES_PROCESS_DELAY); LOG.debug("File processing timer is (re-)scheduled"); } boolean valid = key.reset(); if (!valid) { LOG.error("Path '{}' isn't valid anymore", outboxPath); postMessage(new Main.StopMessage( String.format("Please verify validity of folder '%s' and re-run application", outboxPath))); break; } } monitorThread = null; }
From source file:org.brekka.stillingar.spring.snapshot.WatchedResourceMonitor.java
@Override public boolean hasChanged() { if (!watchKey.isValid()) { return false; }/*from www.ja v a 2 s .c o m*/ boolean changed = false; try { WatchKey wKey; if (timeout > 0) { wKey = watchService.poll(timeout, TimeUnit.MILLISECONDS); } else { // Indefinite blocking wKey = watchService.take(); } if (wKey != null) { if (wKey != this.watchKey) { throw new IllegalStateException("WatchKey does not match that registered with the service"); } List<WatchEvent<?>> pollEvents = wKey.pollEvents(); if (log.isDebugEnabled()) { log.debug(String.format("Found %d events", pollEvents.size())); } for (WatchEvent<?> watchEvent : pollEvents) { Path name = (Path) watchEvent.context(); if (resourceFile.getFileName().equals(name)) { changed = true; if (log.isInfoEnabled()) { log.info(String.format("Found change to file '%s'", name)); } break; } } wKey.reset(); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } return changed; }
From source file:acromusashi.stream.ml.common.spout.WatchTextBatchSpout.java
/** * ???????????????????/* w ww .java2 s.co m*/ * * @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:SecurityWatch.java
public void watchVideoCamera(Path path) throws IOException, InterruptedException { watchService = FileSystems.getDefault().newWatchService(); register(path, StandardWatchEventKinds.ENTRY_CREATE); OUTERMOST: while (true) { final WatchKey key = watchService.poll(); if (key == null) { System.out.println("The video camera is jammed - security watch system is canceled!"); break; } else {/*from ww w. j av a2 s . c o m*/ for (WatchEvent<?> watchEvent : key.pollEvents()) { final Kind<?> kind = watchEvent.kind(); if (kind == StandardWatchEventKinds.OVERFLOW) { continue; } if (kind == StandardWatchEventKinds.ENTRY_CREATE) { //get the filename for the event final WatchEvent<Path> watchEventPath = (WatchEvent<Path>) watchEvent; final Path filename = watchEventPath.context(); final Path child = path.resolve(filename); if (Files.probeContentType(child).equals("image/jpeg")) { //print it out the video capture time SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss"); System.out.println("Video capture successfully at: " + dateFormat.format(new Date())); } else { System.out.println("The video camera capture format failed! This could be a virus!"); break OUTERMOST; } } } boolean valid = key.reset(); if (!valid) { break; } } } watchService.close(); }
From source file:SecurityWatch.java
public void watchVideoCamera(Path path) throws IOException, InterruptedException { watchService = FileSystems.getDefault().newWatchService(); register(path, StandardWatchEventKinds.ENTRY_CREATE); OUTERMOST: while (true) { final WatchKey key = watchService.poll(11, TimeUnit.SECONDS); if (key == null) { System.out.println("The video camera is jammed - security watch system is canceled!"); break; } else {/*from w ww . j ava 2 s.com*/ for (WatchEvent<?> watchEvent : key.pollEvents()) { final Kind<?> kind = watchEvent.kind(); if (kind == StandardWatchEventKinds.OVERFLOW) { continue; } if (kind == StandardWatchEventKinds.ENTRY_CREATE) { //get the filename for the event final WatchEvent<Path> watchEventPath = (WatchEvent<Path>) watchEvent; final Path filename = watchEventPath.context(); final Path child = path.resolve(filename); if (Files.probeContentType(child).equals("image/jpeg")) { //print it out the video capture time SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss"); System.out.println("Video capture successfully at: " + dateFormat.format(new Date())); } else { System.out.println("The video camera capture format failed! This could be a virus!"); break OUTERMOST; } } } boolean valid = key.reset(); if (!valid) { break; } } } watchService.close(); }
From source file:org.fcrepo.kernel.api.utils.AutoReloadingConfiguration.java
/** * Starts up monitoring of the configuration for changes. *///from w w w. j a va 2s .c o m private void monitorForChanges() { if (monitorRunning) { return; } final Path path = Paths.get(configPath); if (!path.toFile().exists()) { LOGGER.debug("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("Configuration {} has been updated, reloading.", path); try { loadConfiguration(); } catch (final IOException e) { LOGGER.error("Failed to reload configuration {}", configPath, 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 {/* w ww. j a v a 2 s. c o 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.codice.ddf.configuration.store.ConfigurationFilesPoller.java
@Override public void run() { try {/*from w w w .j a v a 2s.c o m*/ try { LOGGER.debug("Registering path [{}] with Watch Service.", configurationDirectoryPath.toString()); configurationDirectoryPath.register(watchService, ENTRY_CREATE); } catch (IOException e) { LOGGER.error("Unable to register path [{}] with Watch Service", configurationDirectoryPath.toString(), e); return; } WatchKey key; while (!Thread.currentThread().isInterrupted()) { key = watchService.take(); // blocking LOGGER.debug("Key has been signalled. Looping over events."); for (WatchEvent<?> genericEvent : key.pollEvents()) { WatchEvent.Kind<?> kind = genericEvent.kind(); if (kind == OVERFLOW || kind == ENTRY_MODIFY || kind == ENTRY_DELETE) { LOGGER.debug("Skipping event [{}]", kind); continue; } Path filename = (Path) genericEvent.context(); if (!filename.toString().endsWith(fileExtension)) { LOGGER.debug("Skipping event for [{}] due to unsupported file extension of [{}].", filename, fileExtension); continue; // just skip to the next event } if (configurationDirectory != null) { LOGGER.debug("Notifying [{}] of event [{}] for file [{}].", configurationDirectory.getClass().getName(), kind, configurationDirectoryPath.resolve(filename)); configurationDirectory.notify(configurationDirectoryPath.resolve(filename)); } } // Reset key, shutdown watcher if directory not able to be observed // (possibly deleted) if (!key.reset()) { LOGGER.warn("Configurations in [{}] are no longer able to be observed.", configurationDirectoryPath.toString()); break; } } } catch (InterruptedException | RuntimeException e) { LOGGER.error("The [{}] was interrupted.", this.getClass().getName(), e); Thread.currentThread().interrupt(); } }
From source file:org.fcrepo.http.api.ExternalContentPathValidator.java
/** * Starts up monitoring of the allowed list configuration for changes. *//*w w w .jav a2s . c om*/ 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; }