List of usage examples for java.nio.file WatchEvent context
T context();
From source file:eu.edisonproject.rest.FolderWatcherRunnable.java
@Override public void run() { final Path path = FileSystems.getDefault().getPath(dir); try (final WatchService watchService = FileSystems.getDefault().newWatchService()) { final WatchKey watchKey = path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE); while (true) { final WatchKey wk = watchService.take(); for (WatchEvent<?> event : wk.pollEvents()) { final Path changed = (Path) event.context(); executeClassification(new File(dir + File.separator + changed)); }/*www.j av a2 s. co m*/ // reset the key boolean valid = wk.reset(); if (!valid) { Logger.getLogger(FolderWatcherRunnable.class.getName()).log(Level.WARNING, "Key has been unregisterede"); } } } catch (IOException ex) { Logger.getLogger(FolderWatcherRunnable.class.getName()).log(Level.SEVERE, null, ex); } catch (InterruptedException ex) { Logger.getLogger(FolderWatcherRunnable.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { Logger.getLogger(FolderWatcherRunnable.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:org.dishevelled.thumbnail.examples.ThumbnailDrop.java
/** * Process file system watcher events./* w ww . ja v a 2 s. com*/ */ void processEvents() { for (;;) { WatchKey key = null; try { key = watcher.take(); } catch (InterruptedException e) { return; } for (WatchEvent<?> event : key.pollEvents()) { WatchEvent.Kind kind = event.kind(); if (kind == OVERFLOW) { continue; } WatchEvent<Path> pathEvent = cast(event); Path name = pathEvent.context(); Path path = watchDirectory.resolve(name); if (kind == ENTRY_CREATE) { created(path); } else if (kind == ENTRY_MODIFY) { modified(path); } } if (!key.reset()) { key.cancel(); try { watcher.close(); } catch (IOException e) { // ignore } break; } } }
From source file:org.eclipse.smarthome.core.transform.AbstractFileTransformationService.java
/** * Ensures that a modified or deleted cached files does not stay in the cache *//*w w w .j av a 2s . co m*/ private void processFolderEvents() { WatchKey key = watchService.poll(); if (key != null) { for (WatchEvent<?> e : key.pollEvents()) { if (e.kind() == OVERFLOW) { continue; } // Context for directory entry event is the file name of entry @SuppressWarnings("unchecked") WatchEvent<Path> ev = (WatchEvent<Path>) e; Path path = ev.context(); logger.debug("Refreshing transformation file '{}'", path); for (String fileEntry : cachedFiles.keySet()) { if (fileEntry.endsWith(path.toString())) { cachedFiles.remove(fileEntry); } } } key.reset(); } }
From source file:ddf.camel.component.catalog.content.ContentProducerDataAccessObject.java
public File getFileUsingRefKey(boolean storeRefKey, Message in) throws ContentComponentException { File ingestedFile = null;//from w w w.j a v a 2 s . co m try { if (!storeRefKey) { ingestedFile = ((GenericFile<File>) in.getBody()).getFile(); } else { WatchEvent<Path> pathWatchEvent = (WatchEvent<Path>) ((GenericFileMessage) in).getGenericFile() .getFile(); if (pathWatchEvent != null && pathWatchEvent.context() != null) { ingestedFile = pathWatchEvent.context().toFile(); } } } catch (ClassCastException e) { throw new ContentComponentException( "Unable to cast message body to Camel GenericFile, so unable to process ingested file"); } return ingestedFile; }
From source file:org.springframework.integration.file.WatchServiceDirectoryScanner.java
private Set<File> filesFromEvents() { WatchKey key = watcher.poll(); Set<File> files = new LinkedHashSet<File>(); while (key != null) { for (WatchEvent<?> event : key.pollEvents()) { if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) { Path item = (Path) event.context(); File file = new File( ((Path) key.watchable()).toAbsolutePath() + File.separator + item.getFileName()); if (logger.isDebugEnabled()) { logger.debug("Watch Event: " + event.kind() + ": " + file); }/*from w w w. j a v a2 s .co m*/ if (file.isDirectory()) { files.addAll(walkDirectory(file.toPath())); } else { files.add(file); } } else if (event.kind() == StandardWatchEventKinds.OVERFLOW) { if (logger.isDebugEnabled()) { logger.debug("Watch Event: " + event.kind() + ": context: " + event.context()); } if (event.context() != null && event.context() instanceof Path) { files.addAll(walkDirectory((Path) event.context())); } else { files.addAll(walkDirectory(this.directory)); } } else { if (logger.isDebugEnabled()) { logger.debug("Watch Event: " + event.kind() + ": context: " + event.context()); } } } key.reset(); key = watcher.poll(); } return files; }
From source file:uk.gov.gchq.gaffer.miniaccumulocluster.MiniAccumuloClusterController.java
protected void watchShutdown() { LOGGER.info("Watching Shutdown File " + clusterPath + "/" + SHUTDOWN_FILENAME); try {/* w w w .j a v a 2s.co m*/ WatchService watcher = FileSystems.getDefault().newWatchService(); clusterPath.register(watcher, ENTRY_CREATE); OUTER: while (true) { WatchKey key; try { key = watcher.take(); } catch (final InterruptedException e) { return; } for (final WatchEvent<?> event : key.pollEvents()) { final WatchEvent.Kind<?> kind = event.kind(); if (kind == OVERFLOW) { continue; } final WatchEvent<Path> ev = (WatchEvent<Path>) event; final Path filename = ev.context(); LOGGER.debug("Filename changed " + filename); if (filename.toString().equals(SHUTDOWN_FILENAME)) { MiniAccumuloClusterController.this.stop(); break OUTER; } } boolean valid = key.reset(); if (!valid) { break; } } LOGGER.info("Finished Watching Shutdown"); } catch (final IOException e) { LOGGER.error("Failed to watch shutdown", 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(() -> {//from w ww.ja va 2 s. co m 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.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 w w w . j av 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:de.elomagic.carafile.client.CaraCloud.java
/** * Starts synchronization of the given base path with the registry. * <p/>// w w w.j a v a 2s . co m * This method will block till call method {@link CaraCloud#stop() } * * @throws IOException Thrown when an I/O error occurs * @throws InterruptedException Thrown when method stop was called or application will terminate * @throws GeneralSecurityException */ public void start() throws IOException, InterruptedException, GeneralSecurityException { if (client == null) { throw new IllegalStateException("Attribute \"client\" must be set."); } if (basePath == null) { throw new IllegalStateException("Attribute \"basePath\" must be set."); } if (!Files.exists(basePath)) { throw new IllegalStateException("Path \"" + basePath + "\" must exists."); } if (!Files.isDirectory(basePath)) { throw new IllegalStateException("Path \"" + basePath + "\" must be a directory/folder."); } watcher = FileSystems.getDefault().newWatchService(); registerDefaultWatch(basePath); while (!Thread.interrupted()) { WatchKey key = watcher.take(); for (WatchEvent<?> event : key.pollEvents()) { if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) { Path path = basePath.resolve(event.context().toString()); createFile(path); } else if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) { } else if (event.kind() == StandardWatchEventKinds.ENTRY_DELETE) { Path path = basePath.resolve(event.context().toString()); deleteFile(path); } else { LOG.error("Unsupported kind: " + event.kind() + ", path: " + event.context()); } } key.reset(); } }
From source file:org.apache.tomee.jul.handler.rotating.ArchivingTest.java
@SuppressWarnings("unchecked") @Test//from ww w . j a v a 2 s . c om public void logAndRotateAndPurge() throws Exception { clean("target/ArchivingTestPurge-" + format + "/logs"); final AtomicReference<String> today = new AtomicReference<>(); final Map<String, String> config = new HashMap<>(); // initial config today.set("2015-09-01"); config.put("filenamePattern", "target/ArchivingTestPurge-" + format + "/logs/test.%s.%d.log"); config.put("archiveDirectory", "target/ArchivingTestPurge-" + format + "/logs/archives"); config.put("archiveFormat", format); config.put("archiveOlderThan", "1 s"); config.put("purgeOlderThan", "2 s"); config.put("limit", "10 kilobytes"); config.put("level", "INFO"); config.put("dateCheckInterval", "1 second"); final LocalFileHandler handler = new LocalFileHandler() { @Override protected String currentDate() { return today.get(); } @Override protected String getProperty(final String name, final String defaultValue) { final String s = config.get(name.substring(name.lastIndexOf('.') + 1)); return s != null ? s : defaultValue; } }; final String string10chars = "abcdefghij"; final int iterations = 950; for (int i = 0; i < iterations; i++) { handler.publish(new LogRecord(Level.INFO, string10chars)); } today.set("2015-09-02"); try { Thread.sleep(2000); } catch (final InterruptedException e) { Thread.interrupted(); } final File logArchive = new File( "target/ArchivingTestPurge-" + format + "/logs/archives/test.2015-09-01.0.log." + format); final File parentFile = logArchive.getParentFile(); if (!parentFile.exists() && !parentFile.mkdirs()) { Assert.fail("Unable to create: " + parentFile); } final Path dir = parentFile.toPath(); final WatchService watcher = FileSystems.getDefault().newWatchService(); final WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_MODIFY); latch.set(new CountDownLatch(1)); watch(key); handler.publish(new LogRecord(Level.INFO, string10chars)); // will trigger the archiving assertTrue("Failed to get archived log", latch.get().await(20, TimeUnit.SECONDS)); final WatchEvent<?> watchEvent = lastEvent.get(); assertTrue(StandardWatchEventKinds.ENTRY_CREATE.equals(watchEvent.kind()) || StandardWatchEventKinds.ENTRY_MODIFY.equals(watchEvent.kind())); final WatchEvent<Path> ev = (WatchEvent<Path>) watchEvent; final String io = ev.context().toString(); assertTrue(io.startsWith("test.2015-09-01.") && io.endsWith(format)); today.set("2015-09-03"); try { Thread.sleep(2500); } catch (final InterruptedException e) { Thread.interrupted(); } handler.publish(new LogRecord(Level.INFO, string10chars)); // will trigger the purging handler.close(); withRetry(10, 2, new Runnable() { @Override public void run() { assertFalse(logArchive.getAbsolutePath() + " was purged", logArchive.exists()); } }); }