Java Code Examples for java.nio.file.WatchService#poll()

The following examples show how to use java.nio.file.WatchService#poll() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PubSubEmulator.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
/**
 * Wait until a PubSub emulator configuration file is updated.
 * Fail if the file does not update after 1 second.
 * @param watchService the watch-service to poll
 * @throws InterruptedException which should interrupt the peaceful slumber and bubble up
 * to fail the test.
 */
private void updateConfig(WatchService watchService) throws InterruptedException {
	int attempts = 10;
	while (--attempts >= 0) {
		WatchKey key = watchService.poll(100, TimeUnit.MILLISECONDS);

		if (key != null) {
			Optional<Path> configFilePath = key.pollEvents().stream()
					.map((event) -> (Path) event.context())
					.filter((path) -> ENV_FILE_NAME.equals(path.toString()))
					.findAny();
			if (configFilePath.isPresent()) {
				return;
			}
		}
	}

	fail("Configuration file update could not be detected");
}
 
Example 2
Source File: AbstractFileTransformationService.java    From openhab-core with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Ensures that a modified or deleted cached files does not stay in the cache
 */
private void processFolderEvents(final WatchService watchService) {
    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();
    }
}
 
Example 3
Source File: AbstractFileTransformationService.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Ensures that a modified or deleted cached files does not stay in the cache
 */
private void processFolderEvents(final WatchService watchService) {
    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();
    }
}
 
Example 4
Source File: SVMJVMImpl.java    From visualvm with GNU General Public License v2.0 5 votes vote down vote up
public File takeHeapDump() throws IOException {
    if (!isTakeHeapDumpSupported()) {
        throw new UnsupportedOperationException();
    }
    String cwd = monitoredVm.findByName(USER_DIR_COUNTER_NAME);
    Path applicationCwd = Paths.get(cwd);
    WatchService watchService = FileSystems.getDefault().newWatchService();
    WatchKey key = applicationCwd.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);
    Runtime.getRuntime().exec(new String[] {"kill", "-USR1", String.valueOf(application.getPid())});
    try {
        Path name = findHeapDumpFile(key);
        if (name == null) {
            key = watchService.poll(20, TimeUnit.SECONDS);
            name = findHeapDumpFile(key);
        }
        watchService.close();
        if (name == null) {
            return null;
        }
        File dumpFile = applicationCwd.resolve(name).toFile();
        waitDumpDone(dumpFile);
        return dumpFile;
    } catch (InterruptedException ex) {
        watchService.close();
        return null;
    }
}
 
Example 5
Source File: TestWatchService.java    From jsr203-hadoop with Apache License 2.0 5 votes vote down vote up
@Test(expected=ClosedWatchServiceException.class)
@Ignore
public void testSimpleEx() throws IOException {
  Path rootPath = Paths.get(clusterUri);
  
  WatchService watcher = rootPath.getFileSystem().newWatchService();
  rootPath.register(watcher, 
        new WatchEvent.Kind<?>[] { ENTRY_MODIFY });
  watcher.close();
  // Should throw ClosedWatchServiceException
  watcher.poll();
}
 
Example 6
Source File: CamelSinkFileITCase.java    From camel-kafka-connector with Apache License 2.0 4 votes vote down vote up
private void waitForFile(File sinkFile, File doneFile) throws IOException, InterruptedException {
    WatchService watchService = FileSystems.getDefault().newWatchService();
    Path path = sinkFile.getParentFile().toPath();

    if (doneFile.exists()) {
        return;
    }

    // We watch for both the file creation and truncation
    path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY);

    int retries = 30;
    do {
        WatchKey watchKey = watchService.poll(1, TimeUnit.SECONDS);

        if (watchKey == null) {
            continue;
        }

        for (WatchEvent<?> event : watchKey.pollEvents()) {

            /*
              It should return a Path object for ENTRY_CREATE and ENTRY_MODIFY events
             */
            Object context = event.context();
            if (!(context instanceof Path)) {
                LOG.warn("Received an unexpected event of kind {} for context {}", event.kind(), event.context());
                continue;
            }

            Path contextPath = (Path) context;

            if (contextPath.toString().equals(doneFile.getName())) {
                LOG.info("Sink file at the build path {} had a matching event of type: {}", sinkFile.getPath(),
                        event.kind());

                return;
            } else {
                LOG.debug("Ignoring a watch event at build path {} of type {} for file: {}", sinkFile.getPath(),
                        event.kind(), contextPath.getFileName());
            }
        }
        watchKey.reset();
        retries--;
    } while (!doneFile.exists() && retries > 0);
}
 
Example 7
Source File: DirectoryWatcherTest.java    From openjdk-systemtest with Apache License 2.0 4 votes vote down vote up
public void testEntryCreate() throws IOException, InterruptedException, StfException {
	Path tempDirectory = getTemporaryDirectory();
	WatchService watchService = FileSystems.getDefault().newWatchService();
	try {
		tempDirectory.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);
		Path newFilename = Paths.get("ENTRY_CREATE.txt");
		Path newFile = tempDirectory.resolve(newFilename);
		Files.createFile(newFile);
		assertTrue("File was not created", Files.exists(newFile));

		WatchKey key = null;

		// We will give it POLL_TIMEOUT_SECONDS seconds, if it hasn't got something by
		// then we assume failure
		key = watchService.poll(POLL_TIMEOUT_SECONDS, TimeUnit.SECONDS);

		assertNotNull("Polling WatchService object returned null", key);

		boolean eventFound = false;

		// Check for exactly one event
		for (WatchEvent<?> event : key.pollEvents()) {
			if (event.kind().equals(StandardWatchEventKinds.ENTRY_CREATE)) {
				// Assert exactly one event
				assertFalse("Duplicate ENTRY_CREATE events delivered for one file creation", eventFound);
				// Assert filename is correct
				assertEquals(newFilename, (Path) event.context());
				eventFound = true;
			} else {
				fail(event.kind() + " event retured, expected ENTRY_CREATE");
			}
		}

		// Reset the key, to allow for future events
		key.reset();

	} finally {
		watchService.close();
	}
	okForCleanup();
}
 
Example 8
Source File: DirectoryWatcherTest.java    From openjdk-systemtest with Apache License 2.0 4 votes vote down vote up
public void testMultipleEntryCreate() throws IOException, InterruptedException, StfException {
	Path tempDirectory = getTemporaryDirectory();
	WatchService watchService = FileSystems.getDefault().newWatchService();
	try {
		tempDirectory.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);
		WatchKey key = null;
		for (int iteration = 0; iteration < 10; iteration++) {
			HangNotifier.ping();
			Path newFilename = Paths.get("ENTRY_CREATE" + iteration + ".txt");
			Path newFile = tempDirectory.resolve(newFilename);
			Files.createFile(newFile);
			assertTrue("File was not created", Files.exists(newFile));

			key = null;

			// We will give it POLL_TIMEOUT_SECONDS seconds, if it hasn't got something by
			// then we assume failure

			key = watchService.poll(POLL_TIMEOUT_SECONDS, TimeUnit.SECONDS);
			assertNotNull("Polling WatchService object returned null", key);
			
			boolean eventFound = false;

			// Check for exactly one event
			for (WatchEvent<?> event : key.pollEvents()) {
				if (event.kind().equals(StandardWatchEventKinds.ENTRY_CREATE)) {
					// Assert exactly one event
					assertFalse("Duplicate ENTRY_CREATE events delivered for one file creation", eventFound);
					// Assert filename is correct
					assertEquals(newFilename, (Path) event.context());
					eventFound = true;
				} else {
					fail(event.kind() + " event retured, expected ENTRY_CREATE");
				}
			}

			// Reset the key, to allow for future events
			if (key != null) {
				key.reset();
			}
		}
	} finally {
		watchService.close();
	}
	okForCleanup();
}
 
Example 9
Source File: DirectoryWatcherTest.java    From openjdk-systemtest with Apache License 2.0 4 votes vote down vote up
public void testEntryModify() throws IOException, InterruptedException, StfException {
	Path tempDirectory = getTemporaryDirectory();
	WatchService watchService = FileSystems.getDefault().newWatchService();
	try {
		Path newFilename = Paths.get("ENTRY_MODIFY.txt");
		Path newFile = tempDirectory.resolve(newFilename);
		Files.createFile(newFile);
		assertTrue("File was not created", Files.exists(newFile));

		// We need to pause so that the implementation on AIX and zOS
		// notices the modification time
		// has changed, which only work to the second apparently.
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {

		}

		tempDirectory.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);

		// Modify file
		OutputStream out = Files.newOutputStream(newFile, StandardOpenOption.WRITE);
		out.write("A".getBytes());
		out.close();

		WatchKey key = null;

		// We will give it POLL_TIMEOUT_SECONDS seconds, if it hasn't got
		// something by
		// then we assume failure

		key = watchService.poll(POLL_TIMEOUT_SECONDS, TimeUnit.SECONDS);

		assertNotNull("Polling WatchService object returned null", key);

		boolean eventFound = false;

		// Check for exactly one event
		for (WatchEvent<?> event : key.pollEvents()) {
			if (event.kind().equals(StandardWatchEventKinds.ENTRY_MODIFY)) {
				// Assert exactly one event
				assertFalse("Duplicate ENTRY_MODIFY events delivered for one file modification", eventFound);
				// Assert filename is correct
				assertEquals(newFilename, (Path) event.context());
				eventFound = true;
			} else {
				fail(event.kind() + " event retured, expected ENTRY_MODIFY");
			}
		}

		// Reset the key, to allow for future events
		key.reset();
	} finally {
		watchService.close();
	}
	okForCleanup();
}
 
Example 10
Source File: DirectoryWatcherTest.java    From openjdk-systemtest with Apache License 2.0 4 votes vote down vote up
public void testEntryDelete() throws IOException, InterruptedException, StfException {
	Path tempDirectory = getTemporaryDirectory();
	WatchService watchService = FileSystems.getDefault().newWatchService();
	try {
		// Create the file before registering the WatchService, so that
		// we don't need to pause before deleting the file
		Path newFilename = Paths.get("ENTRY_DELETE.txt");
		Path newFile = tempDirectory.resolve(newFilename);
		Files.createFile(newFile);
		assertTrue("File was not created", Files.exists(newFile));

		tempDirectory.register(watchService, StandardWatchEventKinds.ENTRY_DELETE);

		Files.delete(newFile);

		WatchKey key = null;
		// We will give it POLL_TIMEOUT_SECONDS seconds, if it hasn't got
		// something by
		// then we assume failure

		key = watchService.poll(POLL_TIMEOUT_SECONDS, TimeUnit.SECONDS);

		assertNotNull("Polling WatchService object returned null", key);

		boolean eventFound = false;

		// Check for exactly one event
		for (WatchEvent<?> event : key.pollEvents()) {
			if (event.kind().equals(StandardWatchEventKinds.ENTRY_DELETE)) {
				// Assert exactly one event
				assertFalse("Duplicate ENTRY_DELETE events delivered for one file deletion", eventFound);
				// Assert filename is correct
				assertEquals(newFilename, (Path) event.context());
				eventFound = true;
			} else {
				fail(event.kind() + " event retured, expected ENTRY_DELETE");
			}
		}
		// Reset the key, to allow for future events
		key.reset();
	} finally {
		watchService.close();
	}
	okForCleanup();
}
 
Example 11
Source File: DirectoryWatcherTest.java    From openjdk-systemtest with Apache License 2.0 4 votes vote down vote up
public void testDirectoryWatcher() throws IOException, StfException {
	Path tempDirectory = getTemporaryDirectory();
	WatchService watchService = null;

	// Obtain watch service for the default file system and register
	// an interest in knowing when files are created
	watchService = FileSystems.getDefault().newWatchService();
	try {
		tempDirectory.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);
		// Hard-coded values of how many files to touch
		int numberOfIterationsRemaining = 10;
		int numberOfFiles = 5;
		int totalFiles = numberOfFiles * numberOfIterationsRemaining;
		long startTime = System.currentTimeMillis();

		// Our variables containing information as to whether we are going
		// to pass
		// or fail
		int filesFound = 0;
		boolean discardedEvents = false;

		LOOP: while (true) {
			WatchKey key;
			
			// Spread out the creating of files, interspersing them with polls.
			if (numberOfIterationsRemaining > 0) {
				createFiles(tempDirectory, numberOfFiles);
				numberOfIterationsRemaining--;
			}

			// Try taking a key off the service, if available (null if not)
			key = watchService.poll();
			if (key != null) {
				// Retrieve each event
				for (WatchEvent<?> event : key.pollEvents()) {
					if (event.kind().equals(StandardWatchEventKinds.ENTRY_CREATE)) {
						// New file found
						filesFound++;
					} else if (event.kind().equals(StandardWatchEventKinds.OVERFLOW)) {
						// Overflow occurred.
						// This is sort of a warning, but expected if we
						// (the JVM?) can't process
						// the events fast enough
						discardedEvents = true;
					}
				}

				// Important to reset the key
				key.reset();
			}

			long duration = System.currentTimeMillis() - startTime;

			// Check if we have received everything we intended to
			// if so, we can break the loop
			if (numberOfIterationsRemaining == 0) {
				if (filesFound == totalFiles) {
					break LOOP;
				}
				if (discardedEvents == true) {
					break LOOP;
				}
			}

			// Check to see if we have been doing this for too long
			// if so, then break the loop
			if (duration > TIMEOUT) {
				fail("Timeout exceeded: " + filesFound + " files found in " + duration + "ms");
				break LOOP;
			}
		}

		System.out.println("Summary: totalfile - " + totalFiles + " , files found " + filesFound);

		if (discardedEvents == false && (totalFiles != filesFound)) {
			fail("No events were knowingly discarded, but the total number of files found does not equal the number created");
		}

		if (discardedEvents == true) {
			System.out.println("Warning, events were discarded.");
		}
	} finally {
		watchService.close();
	}
	okForCleanup();
}