List of usage examples for java.nio.file StandardWatchEventKinds ENTRY_MODIFY
WatchEvent.Kind ENTRY_MODIFY
To view the source code for java.nio.file StandardWatchEventKinds ENTRY_MODIFY.
Click Source Link
From source file:org.wso2.carbon.uuf.renderablecreator.html.internal.io.HtmlRenderableUpdater.java
private void run() { while (!isWatchServiceStopped) { WatchKey watchKey;//from w ww. ja va 2s . c o m try { watchKey = watchService.take(); } catch (ClosedWatchServiceException e) { log.debug("File watch service is closed."); return; } catch (InterruptedException e) { log.debug("File watch service interrupted."); return; } for (WatchEvent<?> watchEvent : watchKey.pollEvents()) { if (watchEvent.kind() != StandardWatchEventKinds.ENTRY_MODIFY) { continue; } Path updatedDirectory = (Path) watchKey.watchable(); @SuppressWarnings("unchecked") Path updatedFileName = ((WatchEvent<Path>) watchEvent).context(); // Updating the changed html file Path updatedFileAbsolutePath = updatedDirectory.resolve(updatedFileName); try (DirectoryStream<Path> stream = Files.newDirectoryStream(updatedFileAbsolutePath.getParent())) { for (Path entry : stream) { if (Files.isDirectory(entry)) { continue; } MutableHtmlRenderable mutableHtmlRenderable = watchingRenderables.get(entry); if (mutableHtmlRenderable != null) { try { String content = new String(Files.readAllBytes(entry), StandardCharsets.UTF_8); mutableHtmlRenderable.setHtml(content); log.info("HTML template '" + entry + "' reloaded successfully."); } catch (IOException e) { log.error("An error occurred while reloading HTML template '" + entry + "'.", e); } } } } catch (IOException e) { log.error("An error occurred while reloading HTML template '" + updatedFileAbsolutePath + "'.", e); } } boolean valid = watchKey.reset(); if (!valid) { // Watch key cannot not be reset because watch service is already closed. break; } } }
From source file:com.temenos.interaction.loader.detector.DirectoryChangeActionNotifier.java
protected void initWatchers(Collection<? extends File> resources) { if (scheduledTask != null) { scheduledTask.cancel(true);//w ww. j av a2s . c o m } if (resources == null || resources.isEmpty() || getListeners() == null || getListeners().isEmpty()) { return; } try { WatchService ws = FileSystems.getDefault().newWatchService(); for (File file : resources) { Path filePath = Paths.get(file.toURI()); filePath.register(ws, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE); } watchService = ws; scheduledTask = executorService.scheduleWithFixedDelay( new ListenerNotificationTask(watchService, getListeners(), getIntervalSeconds() * 1000), 5, getIntervalSeconds(), TimeUnit.SECONDS); } catch (IOException ex) { throw new RuntimeException("Error configuring directory change listener - unexpected IOException", ex); } }
From source file:org.siphon.d2js.jshttp.ServerUnitManager.java
public void onFileChanged(WatchEvent<Path> ev, Path file) { Kind<Path> kind = ev.kind(); String filename = file.toString(); try {//from w w w. j a v a 2s .c om if (kind == StandardWatchEventKinds.ENTRY_DELETE) { if (allD2js.containsKey(filename)) { if (logger.isDebugEnabled()) { logger.debug(filename + " dropped"); } ScriptObjectMirror d2js = allD2js.get(filename); if (d2js.containsKey("releaseD2js")) { d2js.callMember("releaseD2js"); } allD2js.remove(filename); //TODO call releaseD2js? } } else if (kind == StandardWatchEventKinds.ENTRY_MODIFY) { if (allD2js.containsKey(filename)) { if (logger.isDebugEnabled()) { logger.debug(filename + " changed"); } ScriptObjectMirror d2js = allD2js.get(filename); if (d2js.containsKey("releaseD2js")) { d2js.callMember("releaseD2js"); } allD2js.remove(filename); } } } catch (Exception e) { logger.error("file synchronize failed on " + filename + " changed ", e); } }
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(() -> {/*w ww . ja v a 2s. c om*/ 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:com.aspc.cms.module.SyncResourceApp.java
private void registerDir(final WatchService watchService, final File dir) throws Exception { // Folder we are going to watch Path p = dir.toPath();/* w w w . j a va 2 s. co m*/ p.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE); for (File f : dir.listFiles()) { if (f.isDirectory()) { registerDir(watchService, f); } } }
From source file:com.lukakama.serviio.watchservice.watcher.WatcherRunnable.java
@Override public void run() { try {//from w w w . jav 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.wso2.carbon.uuf.renderablecreator.hbs.internal.io.RenderableUpdater.java
private void run() { while (!isWatchServiceStopped) { WatchKey watchKey;//from ww w . j a va 2 s. c o m try { watchKey = watcher.take(); } catch (ClosedWatchServiceException e) { log.debug("File watch service is closed."); return; } catch (InterruptedException e) { log.debug("File watch service interrupted."); return; } for (WatchEvent<?> event : watchKey.pollEvents()) { if (event.kind() != StandardWatchEventKinds.ENTRY_MODIFY) { continue; // We only watch file modify events. } Path updatedDirectory = (Path) watchKey.watchable(); @SuppressWarnings("unchecked") Path updatedFileName = ((WatchEvent<Path>) event).context(); MutableHbsRenderable mutableRenderable = watchingRenderables.get(updatedFileName); if (mutableRenderable != null) { // Updated file is a MutableHbsRenderable Path updatedFileAbsolutePath = updatedDirectory.resolve(updatedFileName); try { String content = readFileContent(updatedFileAbsolutePath); mutableRenderable.reload(new StringTemplateSource(mutableRenderable.getPath(), content)); log.info("Handlebars template '" + updatedFileAbsolutePath + "' reloaded successfully."); } catch (UUFException e) { log.error("An error occurred while reloading Handlebars template '" + updatedFileAbsolutePath + "'.", e); } } else { MutableExecutable mutableExecutable = watchingExecutables.get(updatedFileName); if (mutableExecutable != null) { // Updated file is a MutableExecutable Path updatedFileAbsolutePath = updatedDirectory.resolve(updatedFileName); try { mutableExecutable.reload(readFileContent(updatedFileAbsolutePath)); log.info("JavaScript file '" + updatedFileAbsolutePath + "' reloaded successfully."); } catch (UUFException e) { log.error("An error occurred while reloading JavaScript file '" + updatedFileAbsolutePath + "'.", e); } } } } boolean valid = watchKey.reset(); if (!valid) { // Watch key cannot not be reset because watch service is already closed. break; } } }
From source file:org.wso2.carbon.uuf.renderablecreator.hbs.internal.io.HbsRenderableUpdater.java
private void run() { while (!isWatchServiceStopped) { WatchKey watchKey;//from w w w .j av a2 s .com try { watchKey = watcher.take(); } catch (ClosedWatchServiceException e) { log.debug("File watch service is closed."); return; } catch (InterruptedException e) { log.debug("File watch service interrupted."); return; } for (WatchEvent<?> event : watchKey.pollEvents()) { if (event.kind() != StandardWatchEventKinds.ENTRY_MODIFY) { continue; // We only watch file modify events. } Path updatedDirectory = (Path) watchKey.watchable(); @SuppressWarnings("unchecked") Path updatedFileName = ((WatchEvent<Path>) event).context(); Path updatedFileAbsolutePath = updatedDirectory.resolve(updatedFileName); try (DirectoryStream<Path> stream = Files.newDirectoryStream(updatedFileAbsolutePath.getParent())) { for (Path entry : stream) { if (Files.isDirectory(entry)) { continue; } MutableHbsRenderable mutableRenderable = watchingRenderables.get(entry); if (mutableRenderable != null) { // Updated file is a MutableHbsRenderable try { mutableRenderable.reload(new StringTemplateSource( mutableRenderable.getComponentPath(), readFileContent(entry))); log.info("Handlebars template '" + entry + "' reloaded successfully."); } catch (IOException e) { log.error("An error occurred while reloading Handlebars template '" + entry + "'.", e); } continue; } MutableExecutable mutableExecutable = watchingExecutables.get(entry); if (mutableExecutable != null) { // Updated file is a MutableExecutable try { mutableExecutable.reload(readFileContent(entry)); log.info("JavaScript file '" + entry + "' reloaded successfully."); } catch (IOException e) { log.error("An error occurred while reloading JavaScript file '" + entry + "'.", e); } } } } catch (IOException e) { log.error("An error occurred while reloading modified files '" + updatedFileAbsolutePath + "'.", e); } } boolean valid = watchKey.reset(); if (!valid) { // Watch key cannot not be reset because watch service is already closed. break; } } }
From source file:com.reactive.hzdfs.dll.JarModuleLoader.java
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); }/*from www. j a v a 2 s .c o m*/ if (isJarFile(file)) { files.add(file); } else log.warn("[JAR Loader] Ignoring file:- " + file); } } key.reset(); } return files; }
From source file:request.processing.ServletLoader.java
/** * Watch dir monitors the current directory for any new files and calls * loadJar on them./*from w ww . java 2 s . c o m*/ */ public static void watchDir() { WatchService watcher = null; try { watcher = FileSystems.getDefault().newWatchService(); WatchKey key = servletDir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE); servletDir.register(watcher, StandardWatchEventKinds.ENTRY_MODIFY); } catch (IOException x) { System.err.println(x); } while (true) { WatchKey key = null; try { key = watcher.take(); } catch (InterruptedException x) { System.err.println("Interrupted Exception"); x.printStackTrace(); } for (WatchEvent<?> event : key.pollEvents()) { WatchEvent.Kind<?> kind = event.kind(); if (kind == StandardWatchEventKinds.OVERFLOW) { continue; } try { System.out.println("Directory Changed!"); Thread.sleep(1000); loadServletsAndConfig(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } boolean valid = key.reset(); if (!valid) { break; } } } }