List of usage examples for java.nio.file WatchEvent context
T context();
From source file:net.mindengine.dashserver.compiler.GlobalAssetsFileWatcher.java
@Override public void run() { copyAllAssets();/*from ww w . j a v a 2 s .c o m*/ Path path = Paths.get(this.assetsFolderPath); FileSystem fileSystem = path.getFileSystem(); try (WatchService service = fileSystem.newWatchService()) { path.register(service, ENTRY_MODIFY, ENTRY_CREATE); while (true) { WatchKey watchKey = service.take(); for (WatchEvent<?> watchEvent : watchKey.pollEvents()) { Path watchEventPath = (Path) watchEvent.context(); String fileName = watchEventPath.toString(); copyFileAsset(fileName); } if (!watchKey.reset()) { break; } } } catch (Exception e) { e.printStackTrace(); } }
From source file:cz.muni.fi.pb138.cvmanager.service.PDFgenerator.java
/** * By external calling pdflatex function of laTex generates pdf curriculum vitae document from .tex file * @param username name of user whose is the CV * @return language to export (sk/en)/*from w ww .j av a2s . c o m*/ * @throws IOException * @throws InterruptedException * @throws NullPointerException */ public InputStream latexToPdf(String username) throws IOException, InterruptedException, NullPointerException { ProcessBuilder pb = new ProcessBuilder("pdflatex", username + "_cv.tex", "--output-directory="); File file = new File("cvxml/"); pb.directory(file); Process p = pb.start(); WatchService watcher = FileSystems.getDefault().newWatchService(); Path dir = Paths.get("cvxml/"); dir.register(watcher, ENTRY_CREATE, ENTRY_MODIFY); while (true) { // wait for a key to be available for 10 seconds WatchKey key = watcher.poll(10000L, TimeUnit.MILLISECONDS); if (key == null) { break; } for (WatchEvent<?> event : key.pollEvents()) { // get event type WatchEvent.Kind<?> kind = event.kind(); // get file name @SuppressWarnings("unchecked") WatchEvent<Path> ev = (WatchEvent<Path>) event; Path fileName = ev.context(); System.out.println(kind.name() + ": " + fileName); } boolean valid = key.reset(); if (!valid) { break; } } System.out.println("end of cycle"); File pdf = new File("cvxml/" + username + "_cv.pdf"); return new FileInputStream(pdf); }
From source file:org.brekka.stillingar.spring.snapshot.WatchedResourceMonitor.java
@Override public boolean hasChanged() { if (!watchKey.isValid()) { return false; }/*from w w w . j a v a 2 s.c om*/ 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:com.xiaomi.linden.common.util.FileChangeWatcher.java
@Override public void run() { try {// ww w . jav a2 s . c o m watcher = FileSystems.getDefault().newWatchService(); Path path = new File(absolutePath).toPath().getParent(); String fileWatched = FilenameUtils.getName(absolutePath); path.register(watcher, new WatchEvent.Kind[] { StandardWatchEventKinds.ENTRY_MODIFY }, SensitivityWatchEventModifier.HIGH); LOGGER.info("File watcher start to watch {}", absolutePath); while (isAlive()) { try { Thread.sleep(interval); WatchKey key = watcher.poll(1000l, TimeUnit.MILLISECONDS); if (key == null) { continue; } List<WatchEvent<?>> events = key.pollEvents(); for (WatchEvent<?> event : events) { if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) { String file = event.context().toString(); if (fileWatched.equals(file)) { doOnChange(); } } } if (!key.reset()) { LOGGER.info("File watcher key not valid."); } } catch (InterruptedException e) { LOGGER.error("File watcher thread exit!"); break; } } } catch (Throwable e) { LOGGER.error("File watcher error {}", Throwables.getStackTraceAsString(e)); } }
From source file:org.dia.kafka.isatools.producer.DirWatcher.java
/** * Process all events for keys queued to the watcher * @param isatProd/*from w w w. j a va 2s . com*/ */ void processEvents(ISAToolsKafkaProducer isatProd) { for (;;) { // wait for key to be signalled WatchKey key; try { key = watcher.take(); } catch (InterruptedException x) { return; } Path dir = keys.get(key); if (dir == null) { System.err.println("WatchKey not recognized!!"); continue; } List<JSONObject> jsonParsedResults = new ArrayList<JSONObject>(); for (WatchEvent<?> event : key.pollEvents()) { WatchEvent.Kind kind = event.kind(); // TBD - provide example of how OVERFLOW event is handled if (kind == OVERFLOW) { continue; } // Context for directory entry event is the file name of entry WatchEvent<Path> ev = cast(event); Path name = ev.context(); Path child = dir.resolve(name); // If an inner file has been modify then, recreate the entry if (kind == ENTRY_MODIFY || kind == ENTRY_CREATE) { File fileCheck = child.getParent().toFile(); if (child.toFile().isDirectory()) { fileCheck = child.toFile(); } System.out.format("[%s] %s : %s\n", this.getClass().getSimpleName(), kind.toString(), fileCheck.getAbsolutePath()); List<String> folderFiles = ISAToolsKafkaProducer.getFolderFiles(fileCheck); List<JSONObject> jsonObjects = ISAToolsKafkaProducer.doTikaRequest(folderFiles); if (!jsonObjects.isEmpty()) { // jsonParsedResults.addAll(jsonObjects); isatProd.sendISAToolsUpdates(jsonObjects); } } // TODO this event has still to be specified for documents if (kind == ENTRY_DELETE) { System.err.println(String.format("Delete event not supported %s", child.toAbsolutePath())); } // if directory is created, and watching recursively, then // register it and its sub-directories if (kind == ENTRY_CREATE) { try { if (Files.isDirectory(child, NOFOLLOW_LINKS)) { registerAll(child); } } catch (IOException x) { // ignore to keep sample readbale System.err.format("IOException when creating %s \n", child.toAbsolutePath()); } } } // reset key and remove from set if directory no longer accessible boolean valid = key.reset(); if (!valid) { keys.remove(key); // all directories are inaccessible if (keys.isEmpty()) { break; } } } }
From source file:jsonbrowse.JsonBrowse.java
@Override public void run() { try {/*from w ww . j a v a 2s . c o m*/ WatchKey key = watcher.take(); while (key != null) { if (watching) { for (WatchEvent event : key.pollEvents()) { if (event.context() instanceof Path) { Path path = (Path) (event.context()); if (path.getFileName().equals(jsonFilePath.getFileName())) { if (path.toFile().length() > 0) updateModel(); } } } } key.reset(); key = watcher.take(); } } catch (InterruptedException | IOException ex) { Logger.getLogger(JsonBrowse.class.getName()).log(Level.SEVERE, null, ex); } System.out.println("Stopping thread."); }
From source file:org.apache.logging.log4j.core.appender.rolling.RollingAppenderTempCompressedFilePatternTest.java
@Test public void testAppender() throws Exception { final File dirTmp = new File(DIR_TMP); dirTmp.mkdirs();//from ww w . j a v a2s . c o m try (final WatchService watcher = FileSystems.getDefault().newWatchService()) { WatchKey key = dirTmp.toPath().register(watcher, StandardWatchEventKinds.ENTRY_CREATE); final List<String> messages = new ArrayList<>(); for (int i = 0; i < 500; ++i) { final String message = "This is test message number " + i; messages.add(message); logger.debug(message); if (i % 100 == 0) { Thread.sleep(500); } } if (!loggerContextRule.getLoggerContext().stop(30, TimeUnit.SECONDS)) { System.err.println("Could not stop cleanly " + loggerContextRule + " for " + this); } final File dir = new File(DIR); assertTrue("Directory not created", dir.exists()); final File[] files = dir.listFiles(); assertNotNull(files); int gzippedFiles = 0; for (final File file : files) { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); InputStream in = null; final FileExtension ext = FileExtension.lookupForFile(file.getName()); try { try (FileInputStream fis = new FileInputStream(file)) { if (ext != null) { gzippedFiles++; try { in = new CompressorStreamFactory() .createCompressorInputStream(ext.name().toLowerCase(), fis); } catch (final CompressorException ce) { ce.printStackTrace(); fail("Error creating intput stream from " + file.toString() + ": " + ce.getMessage()); } } else { in = new FileInputStream(file); } assertNotNull("No input stream for " + file.getName(), in); try { IOUtils.copy(in, baos); } catch (final Exception ex) { ex.printStackTrace(); fail("Unable to decompress " + file.getAbsolutePath()); } } } finally { Closer.close(in); } final String text = new String(baos.toByteArray(), Charset.defaultCharset()); final String[] lines = text.split("[\\r\\n]+"); for (final String line : lines) { messages.remove(line); } } assertTrue("Log messages lost : " + messages.size(), messages.isEmpty()); assertTrue("Files not rolled : " + files.length, files.length > 2); assertTrue("Files gzipped not rolled : " + gzippedFiles, gzippedFiles > 0); int temporaryFilesCreated = 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++; } } assertTrue("No temporary file created during compression", temporaryFilesCreated > 0); assertTrue("Temporarys file created not equals to compressed files " + temporaryFilesCreated + "/" + gzippedFiles, gzippedFiles == temporaryFilesCreated); } }
From source file:bjerne.gallery.service.impl.GalleryRootDirConfigJob.java
private void watchForChanges() { Path dir = configFile.getParentFile().toPath(); try {//from w w w .j av a 2s . co 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:desktopsearch.WatchDir.java
/** * Process all events for keys queued to the watcher *//* w w w.ja v a 2 s . c o m*/ void processEvents() { for (;;) { // wait for key to be signalled WatchKey key; try { key = watcher.take(); } catch (InterruptedException x) { return; } Path dir = keys.get(key); if (dir == null) { System.err.println("WatchKey not recognized!!"); continue; } for (WatchEvent<?> event : key.pollEvents()) { WatchEvent.Kind kind = event.kind(); // TBD - provide example of how OVERFLOW event is handled if (kind == OVERFLOW) { continue; } // Context for directory entry event is the file name of entry WatchEvent<Path> ev = cast(event); Path name = ev.context(); Path child = dir.resolve(name); // if directory is created, and watching recursively, then // register it and its sub-directories if (recursive && (kind == ENTRY_CREATE)) { try { if (Files.isDirectory(child, NOFOLLOW_LINKS)) { registerAll(child); } } catch (Exception x) { // ignore to keep sample readbale } } // print out event //System.out.format("%s: %s\n", event.kind().name(), child); try { UpdateDB(event.kind().name(), child); } catch (Exception e) { e.printStackTrace(); } } // reset key and remove from set if directory no longer accessible boolean valid = key.reset(); if (!valid) { keys.remove(key); // all directories are inaccessible if (keys.isEmpty()) { break; } } } }
From source file:com.garyclayburg.filesystem.WatchDir.java
@Override public void run() { try {// ww w . ja v a2 s. c o m init(watchDir, recursive); for (;;) { log.debug("Listening for File Events..."); // wait for key to be signalled WatchKey key; try { key = watcher.take(); } catch (InterruptedException x) { return; } Path dir = keys.get(key); if (dir == null) { log.warn("WatchKey not recognized!! " + key); continue; } for (WatchEvent<?> event : key.pollEvents()) { WatchEvent.Kind kind = event.kind(); // TBD - provide example of how OVERFLOW event is handled if (kind == OVERFLOW) { continue; } // Context for directory entry event is the file name of entry WatchEvent<Path> ev = cast(event); Path name = ev.context(); Path child = dir.resolve(name); // print out event log.info("{}: {}", event.kind().name(), child); if (kind == ENTRY_CREATE || kind == ENTRY_MODIFY) { attributeService.reloadGroovyClass(child); } else if (kind == ENTRY_DELETE) { attributeService.removeGroovyClass(child); } // if directory is created, and watching recursively, then // register it and its sub-directories if (recursive && (kind == ENTRY_CREATE)) { try { if (Files.isDirectory(child, NOFOLLOW_LINKS)) { registerAll(child); } } catch (IOException x) { log.warn("Cannot register possible new directory for groovy changes: {}", child); } } } // reset key and remove from set if directory no longer accessible boolean valid = key.reset(); if (!valid) { keys.remove(key); // all directories are inaccessible if (keys.isEmpty()) { break; } } } log.info("Stopped listening for file events"); } catch (IOException e) { log.warn("Could not start File Watch service", e); } }