List of usage examples for java.nio.file WatchService take
WatchKey take() throws InterruptedException;
From source file:org.mail.bridge.FolderMonitor.java
@SuppressWarnings("unchecked") @Override/* www . ja va 2s . co m*/ 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:io.gravitee.gateway.services.localregistry.LocalApiDefinitionRegistry.java
@Override protected void doStart() throws Exception { if (enabled) { super.doStart(); this.init(); executor = Executors.newSingleThreadExecutor(r -> new Thread(r, "registry-monitor")); executor.execute(() -> {//from w w w . ja v a 2s . com Path registry = Paths.get(registryPath); LOGGER.info("Start local registry monitor for directory {}", registry); try { WatchService watcher = registry.getFileSystem().newWatchService(); registry.register(watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY); while (true) { WatchKey key; try { key = watcher.take(); } catch (InterruptedException ex) { return; } for (WatchEvent<?> event : key.pollEvents()) { WatchEvent.Kind<?> kind = event.kind(); @SuppressWarnings("unchecked") WatchEvent<Path> ev = (WatchEvent<Path>) event; Path fileName = registry.resolve(ev.context().getFileName()); LOGGER.info("An event occurs for file {}: {}", fileName, kind.name()); if (kind == StandardWatchEventKinds.ENTRY_MODIFY) { Api loadedDefinition = loadDefinition(fileName.toFile()); Api existingDefinition = definitions.get(fileName); if (existingDefinition != null) { if (apiManager.get(existingDefinition.getId()) != null) { apiManager.update(loadedDefinition); } else { apiManager.undeploy(existingDefinition.getId()); definitions.remove(fileName); apiManager.deploy(loadedDefinition); definitions.put(fileName, loadedDefinition); } } } else if (kind == StandardWatchEventKinds.ENTRY_CREATE) { Api loadedDefinition = loadDefinition(fileName.toFile()); Api existingDefinition = apiManager.get(loadedDefinition.getId()); if (existingDefinition != null) { apiManager.update(loadedDefinition); } else { apiManager.deploy(loadedDefinition); definitions.put(fileName, loadedDefinition); } } else if (kind == StandardWatchEventKinds.ENTRY_DELETE) { Api existingDefinition = definitions.get(fileName); if (existingDefinition != null && apiManager.get(existingDefinition.getId()) != null) { apiManager.undeploy(existingDefinition.getId()); definitions.remove(fileName); } } boolean valid = key.reset(); if (!valid) { break; } } } } catch (IOException ioe) { LOGGER.error("Unexpected error while looking for PI definitions from filesystem", ioe); } }); } }
From source file:org.fcrepo.kernel.api.utils.AutoReloadingConfiguration.java
/** * Starts up monitoring of the configuration for changes. */// ww w . ja va2 s . com 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:org.fcrepo.http.api.ExternalContentPathValidator.java
/** * Starts up monitoring of the allowed list configuration for changes. */// www. 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("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:org.wso2.appserver.integration.tests.logging.accesslogs.HttpAccessLogTestCase.java
@Test(groups = "wso2.as", description = "Send GET and POST requests to generate http access logs and read " + "http access log files", dependsOnMethods = "testWebAppUpload") public void testWebAppResponse() throws Exception { //GET request HttpResponse response = HttpURLConnectionClient.sendGetRequest(getWebAppURL(WebAppTypes.WEBAPPS) + "/" + WEB_APP_NAME + "/services/test_access_log/simpleget?name=abc&domain=wso2.com", null); assertEquals(response.getResponseCode(), HttpStatus.SC_OK, "GET Request was not successful in user mode : " + userMode); //POST Request assertEquals(/* w w w . jav a2 s . co m*/ makePostRequest(getWebAppURL(WebAppTypes.WEBAPPS) + "/" + WEB_APP_NAME + "/services/test_access_log/simplepost").toString(), "hello abc", "POST Request was not successful in user mode : " + userMode); //Register a watch service to wait until log files are created WatchService watcher = FileSystems.getDefault().newWatchService(); Path filePath = Paths.get(logFileLocation); filePath.register(watcher, StandardWatchEventKinds.ENTRY_MODIFY); long time = System.currentTimeMillis() + 30 * 1000; boolean isNewLogFilesAreCreated = false; while (!isNewLogFilesAreCreated && System.currentTimeMillis() < time) { WatchKey key; try { key = watcher.take(); } catch (InterruptedException ex) { return; } for (WatchEvent<?> event : key.pollEvents()) { WatchEvent.Kind<?> kind = event.kind(); if (kind == StandardWatchEventKinds.ENTRY_MODIFY) { if (request_log_file.exists() && response_log_file.exists() && variable_log_file.exists()) { isNewLogFilesAreCreated = true; break; } } } boolean valid = key.reset(); if (!valid) { break; } } }
From source file:org.wso2.carbon.identity.adaptive.auth.deployer.SiddhiAppDeployer.java
private void startWatching() { if (!Files.exists(rootPath)) { return;/*from w w w.j a va2 s .com*/ } Thread serviceWatcherThread = new Thread(() -> { WatchService watcher; try { watcher = FileSystems.getDefault().newWatchService(); rootPath.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY); } catch (IOException e) { log.error("Error registering watcher for path: " + rootPath.toAbsolutePath()); return; } isFileWatcherRunning = true; while (isFileWatcherRunning) { // Wait for key to be signaled WatchKey fileWatcherKey; try { fileWatcherKey = watcher.take(); } catch (InterruptedException e) { if (log.isDebugEnabled()) { log.debug("Watching for siddhi apps deployment folder interrupted.", e); } return; } try { for (WatchEvent<?> event : fileWatcherKey.pollEvents()) { WatchEvent.Kind<?> kind = event.kind(); if (kind == ENTRY_CREATE) { WatchEvent<Path> ev = (WatchEvent<Path>) event; Path appPath = getResolvedPathRelativeToRoot(ev.context()); if (appPath.getFileName().toString().endsWith(SIDDHI_FILE_SUFFIX)) { deploySiddhiApp(appPath); } } else if (kind == ENTRY_DELETE) { WatchEvent<Path> ev = (WatchEvent<Path>) event; Path appPath = getResolvedPathRelativeToRoot(ev.context()); if (appPath.getFileName().toString().endsWith(SIDDHI_FILE_SUFFIX)) { undeploySiddhiApp(appPath); } } else if (kind == ENTRY_MODIFY) { WatchEvent<Path> ev = (WatchEvent<Path>) event; Path appPath = getResolvedPathRelativeToRoot(ev.context()); if (appPath.getFileName().toString().endsWith(SIDDHI_FILE_SUFFIX)) { updateSiddhiApp(appPath); } } } //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 = fileWatcherKey.reset(); if (!valid) { break; } } catch (Exception ex) { log.error("Error while watching deployment folder for siddhiApps.", ex); } } }); serviceWatcherThread.start(); }
From source file:org.flowerplatform.web.git.GitUtils.java
public void listenForChanges(File file) throws IOException { Path path = file.toPath();/*from ww w. j a va 2 s . 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 ww w . j a va2s .co m*/ 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:MonitorSaurausRex.MainMenu.java
public boolean MonitorDirectory() { Path directory = Paths.get("C:/Users/" + user + "/Documents/"); try {/* w w w. j av 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:de.prozesskraft.pkraft.Manager.java
/** * erstellt fuer jeden running step einen watchkey * es soll jedes stepverzeichnis mit dem status 'working' observiert werden bis das file ".exit" erscheint * @param process/*w w w .j a v a 2s . c om*/ * @throws IOException */ private static void createWatchKeysForAllRunningSteps(Process process) throws IOException { // diesen Thread ablegen, damit er vom zyklischen thread gekillt werden kann watcherThread = Thread.currentThread(); // einen neuen map erzeugen fuer die watchKeys keys = new HashMap<WatchKey, Path>(); WatchService watcher = FileSystems.getDefault().newWatchService(); // Anlegen des WatchKeys fuer den Prozess (falls er gestoppt wird, erfolgt die Komunikation mit diesem manager ueber das binaerfile) Path processDir = Paths.get(process.getRootdir()); System.err.println("info: creating a watchkey for the process path " + process.getRootdir()); WatchKey keyProcess = processDir.register(watcher, ENTRY_MODIFY); keys.put(keyProcess, processDir); // Anlegen der WatchKeys fuer jeden laufenden Step for (Step actStep : process.getStep()) { if (actStep.getStatus().equals("working")) { Path stepDir = Paths.get(actStep.getAbsdir()); try { System.err.println("info: step " + actStep.getName() + " is working -> creating a watchkey for its path " + actStep.getAbsdir()); System.err.println("debug: creating..."); WatchKey key = stepDir.register(watcher, ENTRY_CREATE); System.err.println("debug: creating...done. putting to the map"); keys.put(key, stepDir); System.err.println("debug: creating...done. putting to the map...done"); } catch (IOException e) { System.err.println(e); } catch (Exception e) { System.err.println(e); } java.io.File stepDirExitFile = new java.io.File(actStep.getAbsdir() + "/.exit"); java.io.File stepDirStatusFile = new java.io.File(actStep.getAbsdir() + "/.status"); // falls die datei bereits existiert, wird sofort erneut der Prozess weitergeschoben // dies ist dann der fall, wenn ein step gestartet wurde, und danach der manager neu gestartet wurde if (stepDirExitFile.exists()) { System.err.println("info: .exit file already exists -> shortcutting to pushing the process"); // alle keys loeschen keys = null; // den prozess weiter pushen pushProcessAsFarAsPossible(process.getRootdir() + "/process.pmb", false); } // falls der step ein process ist, bibts dort kein .exit file sondern ein .status file else if (stepDirStatusFile.exists()) { System.err.println("info: .status file already exists."); try { java.util.List<String> statusInhalt = Files.readAllLines(stepDirStatusFile.toPath(), Charset.defaultCharset()); if (statusInhalt.size() > 0) { String firstLine = statusInhalt.get(0); System.err.println("info: status changed to: " + firstLine); System.err.println("info: .status file contains status " + firstLine); // wenn ein finaler status, dann soll manager aufgeweckt werden if (firstLine.equals("error") || firstLine.equals("finished")) { System.err.println("info: --> shortcutting to pushing process"); // alle keys loeschen keys = null; // den prozess weiter pushen pushProcessAsFarAsPossible(process.getRootdir() + "/process.pmb", false); } } } catch (IOException e) { // TODO Auto-generated catch block System.err.println( "IOException: trying to read file: " + stepDirStatusFile.getAbsolutePath()); e.printStackTrace(); } catch (ExceptionInInitializerError e) { System.err.println("ExceptionInInitializerError: trying to read file: " + stepDirStatusFile.getAbsolutePath()); e.printStackTrace(); } } } } process.log("info", "now into the watchloop"); // warten auf ein Signal von einem WatchKey for (;;) { WatchKey key; try { key = watcher.take(); } catch (InterruptedException e) { System.err.println(new Timestamp(System.currentTimeMillis()) + ": ---- watcher thread: interrupted! returning to alternativer Thread"); return; } Path dir = keys.get(key); if (dir == null) { System.err.println("WatchKey not recognized!!"); continue; } for (WatchEvent<?> event : key.pollEvents()) { // System.err.println("debug: poll event " + event); WatchEvent.Kind kind = event.kind(); WatchEvent<Path> ev = (WatchEvent<Path>) event; Path name = ev.context(); // dieses logging fuehrt zur aenderung von stderr.txt und .log, was wiederum ein ENTRY_MODIFY ausloest etc. endlosschleife bis platte volllaeuft // System.err.println("debug: poll context " + name); Path child = dir.resolve(name); // System.err.println("debug: poll child " + child); if (kind == ENTRY_CREATE) { if (child.endsWith(".exit")) { System.err.println("info: waking up, because file created: " + child.toString()); // alle keys loeschen keys = null; // den prozess weiter pushen pushProcessAsFarAsPossible(process.getRootdir() + "/process.pmb", false); } } if ((kind == ENTRY_MODIFY) && (child.endsWith("process.pmb"))) { // System.err.println("info: waking up, because process binary file has been modified: " + child.toString()); // alle keys loeschen keys = null; // den prozess weiter pushen pushProcessAsFarAsPossible(process.getRootdir() + "/process.pmb", false); } if (kind == ENTRY_CREATE || kind == ENTRY_MODIFY) { if (child.endsWith(".status")) { try { java.util.List<String> statusInhalt = Files.readAllLines(child, Charset.defaultCharset()); if (statusInhalt.size() > 0) { String firstLine = statusInhalt.get(0); System.err.println("info: status changed to: " + firstLine); // wenn ein finaler status, dann soll manager aufgeweckt werden if (firstLine.equals("error") || firstLine.equals("finished")) { System.err.println("info: waking up, because status changed to: " + firstLine); // alle keys loeschen keys = null; // den prozess weiter pushen pushProcessAsFarAsPossible(process.getRootdir() + "/process.pmb", false); } } } catch (IOException e) { // TODO Auto-generated catch block System.err.println("IOException: trying to read file: " + child.toString()); e.printStackTrace(); } catch (ExceptionInInitializerError e) { System.err.println( "ExceptionInInitializerError: trying to read file: " + child.toString()); e.printStackTrace(); } } } // reset the triggered key key.reset(); } } }