List of usage examples for java.nio.file WatchKey reset
boolean reset();
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)); }// ww w. ja v a2 s.c om // 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: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)// w ww . j av a2 s.c om * @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:com.xiaomi.linden.common.util.FileChangeWatcher.java
@Override public void run() { try {//from w w w.j a va 2 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:com.gwac.job.FileTransferServiceImpl.java
public void transFile() { System.out.println("123"); try {/*from w ww . j a v a2s .c o m*/ System.out.println("123"); watcher = FileSystems.getDefault().newWatchService(); Path dir = Paths.get("E:/TestData/gwacTest"); dir.register(watcher, ENTRY_CREATE, ENTRY_MODIFY); System.out.println("Watch Service registered for dir: " + dir.getFileName()); isSuccess = true; } catch (IOException ex) { isSuccess = false; ex.printStackTrace(); } if (isBeiJingServer || !isSuccess) { return; } if (running == true) { log.debug("start job fileTransferJob..."); running = false; } else { log.warn("job fileTransferJob is running, jump this scheduler."); return; } try { WatchKey key = watcher.poll(); if (key != null) { for (WatchEvent<?> event : key.pollEvents()) { WatchEvent.Kind<?> kind = event.kind(); WatchEvent<Path> ev = (WatchEvent<Path>) event; Path fileName = ev.context(); System.out.println(kind.name() + ": " + fileName); if (kind == ENTRY_MODIFY) { System.out.println("My source file has changed!!!"); } } } boolean valid = key.reset(); if (!valid) { return; } } catch (Exception ex) { } if (running == false) { running = true; log.debug("job fileTransferJob is done."); } }
From source file:jsonbrowse.JsonBrowse.java
@Override public void run() { try {/*from www. java2 s . 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:io.mangoo.build.Watcher.java
@Override @SuppressWarnings("all") public void run() { for (;;) {/*from w w w .j a v a 2 s. co m*/ WatchKey watchKey; try { watchKey = watchService.take(); takeCount.incrementAndGet(); } catch (InterruptedException e) { if (!shutdown) { LOG.error("Unexpectedly interrupted while waiting for take()", e); } return; } Path path = watchKeys.get(watchKey); if (path == null) { LOG.error("WatchKey not recognized!!"); continue; } handleEvents(watchKey, path); if (!watchKey.reset()) { watchKeys.remove(watchKey); if (watchKeys.isEmpty()) { break; } } } }
From source file:com.basistech.yca.FlatteningConfigFileManager.java
private void watchLoop() { for (;;) {/*from ww w. j a v a 2 s. c o m*/ // wait for key to be signaled WatchKey key; try { key = watchService.take(); } catch (InterruptedException x) { break; } for (WatchEvent<?> event : key.pollEvents()) { WatchEvent.Kind<?> kind = event.kind(); if (kind == OVERFLOW) { continue; } @SuppressWarnings("unchecked") WatchEvent<Path> ev = (WatchEvent<Path>) event; processEvent(ev); } boolean valid = key.reset(); if (!valid) { break; } } watchKey.cancel(); try { watchService.close(); } catch (IOException e) { LOG.error("Error closing watch service", e); } }
From source file:com.dm.estore.common.config.Cfg.java
private void startWatcher(final String configDirPath) throws IOException { Path path = Paths.get(configDirPath); path.register(watchService, ENTRY_MODIFY); Runtime.getRuntime().addShutdownHook(new Thread() { @Override/*from www .j a v a 2s .c o m*/ public void run() { try { keepWatching = false; watchService.close(); } catch (IOException e) { LOG.error("Unable to stop configuration watch service", e); } } }); FutureTask<Integer> watchTask = new FutureTask<>(new Callable<Integer>() { private int totalEventCount; @Override public Integer call() throws Exception { while (keepWatching) { try { WatchKey watchKey = watchService.poll(5, TimeUnit.SECONDS); if (watchKey != null) { boolean updateConfiguration = false; for (WatchEvent<?> event : watchKey.pollEvents()) { LOG.debug("Configuration changed: " + event.kind()); updateConfiguration = true; totalEventCount++; } if (!watchKey.reset()) { // handle situation no longer valid keepWatching = false; } else { if (updateConfiguration) { new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(1000); getConfig().getString(CommonConstants.Cfg.CFG_UPDATE_TRIGGER); } catch (InterruptedException ex) { // do nothing } } }).start(); } } } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } return totalEventCount; } }); new Thread(watchTask).start(); }
From source file:org.balloon_project.overflight.task.importer.ImporterFileListener.java
@Override public void run() { // TODO initial import start // initial import of existing file logger.info("Scanning for files to import"); File importDir = new File(configuration.getDatabaseImportDirectory()); if (importDir.exists() && importDir.isDirectory()) { for (File file : importDir.listFiles()) { if (file.isFile() && file.getPath().endsWith(IndexingTask.N_TRIPLES_EXTENSION)) { logger.info("File event: Adding " + file.toString() + " to importer queue"); importer.startImporting(file); }/* w ww .j a v a 2 s . c o m*/ } } // starting file watch service for future files try { String path = configuration.getDatabaseImportDirectory(); logger.info("Starting import file listener for path " + path); Path tmpPath = Paths.get(path); WatchService watchService = FileSystems.getDefault().newWatchService(); tmpPath.register(watchService, StandardWatchEventKinds.ENTRY_CREATE); for (;;) { WatchKey key = watchService.take(); for (WatchEvent event : key.pollEvents()) { if (event.kind().name() == "OVERFLOW") { continue; } else { WatchEvent<Path> ev = (WatchEvent<Path>) event; Path filename = ev.context(); logger.info("File event: Adding " + filename.toString() + " to importer queue"); importer.startImporting(tmpPath.resolve(filename).toFile()); } } // 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) { break; } } } catch (IOException | InterruptedException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } finally { logger.debug("Stopping import file listener"); } }
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(//from w w w. ja v 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; } } }