Search in sources :

Example 41 with WatchService

use of java.nio.file.WatchService in project jimfs by google.

the class WatchServiceConfigurationTest method testPollingConfig.

@Test
public void testPollingConfig() {
    WatchServiceConfiguration polling = WatchServiceConfiguration.polling(50, MILLISECONDS);
    WatchService watchService = polling.newWatchService(fs.getDefaultView(), fs.getPathService());
    assertThat(watchService).isInstanceOf(PollingWatchService.class);
    PollingWatchService pollingWatchService = (PollingWatchService) watchService;
    assertThat(pollingWatchService.interval).isEqualTo(50);
    assertThat(pollingWatchService.timeUnit).isEqualTo(MILLISECONDS);
}
Also used : WatchService(java.nio.file.WatchService) Test(org.junit.Test)

Example 42 with WatchService

use of java.nio.file.WatchService in project j2objc by google.

the class MacOSXPathTest method test_register$WatchService$WatchEvent_Kind$WatchEvent_Modifier.

@Test
public void test_register$WatchService$WatchEvent_Kind$WatchEvent_Modifier() throws IOException {
    WatchService watchService = FileSystems.getDefault().newWatchService();
    WatchEvent.Kind<?>[] events = { ENTRY_CREATE };
    Path dirRoot = Paths.get(filesSetup.getTestDir(), "dir");
    Files.createDirectories(dirRoot);
    try {
        WatchKey key = dirRoot.register(watchService, events, ExtendedWatchEventModifier.FILE_TREE);
        fail();
    } catch (UnsupportedOperationException expected) {
        assertTrue(expected.getMessage().contains("Modifier not supported"));
    }
}
Also used : Path(java.nio.file.Path) Kind(java.nio.file.WatchEvent.Kind) WatchKey(java.nio.file.WatchKey) WatchService(java.nio.file.WatchService) Test(org.junit.Test)

Example 43 with WatchService

use of java.nio.file.WatchService in project j2objc by google.

the class MacOSXPathTest method test_register$WatchService$WatchEvent_Kind_NPE.

/* j2objc: polling key events fails on MacOS, causing this test to hang.
    @Test
    public void test_register$WatchService$WatchEvent_Kind() throws IOException,
            InterruptedException {
        WatchService watchService = FileSystems.getDefault().newWatchService();
        WatchEvent.Kind<?>[] events = {ENTRY_CREATE, ENTRY_DELETE};
        Path file = Paths.get(filesSetup.getTestDir(), "directory/file");
        assertFalse(Files.exists(file));
        Path directory = Paths.get(filesSetup.getTestDir(), "directory");
        Files.createDirectories(directory);
        WatchKey key = directory.register(watchService, events);

        // Creating, modifying and deleting the file.
        Files.createFile(file);
        assertTrue(Files.exists(file));
        // EVENT_MODIFY should not be logged.
        Files.newOutputStream(file).write("hello".getBytes());
        Files.delete(file);
        assertFalse(Files.exists(file));

        assertTrue(key.isValid());
        assertEquals(directory, key.watchable());
        List<WatchEvent<?>> eventList = new ArrayList<>();

        // Wait for the events to be recorded by WatchService.
        while(true) {
            eventList.addAll(key.pollEvents());
            if (eventList.size() == 2) break;
            Thread.sleep(1000);
        }
        // Wait for the events to be recorded by watchService.
        assertEquals(2, eventList.size());
        assertEquals(ENTRY_CREATE, eventList.get(0).kind());
        assertEquals(ENTRY_DELETE, eventList.get(1).kind());
    }
     */
@Test
public void test_register$WatchService$WatchEvent_Kind_NPE() throws IOException, InterruptedException {
    WatchService watchService = FileSystems.getDefault().newWatchService();
    WatchEvent.Kind<?>[] events = { ENTRY_CREATE, ENTRY_DELETE };
    Path directory = Paths.get(filesSetup.getTestDir(), "directory");
    Files.createDirectories(directory);
    try {
        directory.register(null, events);
        fail();
    } catch (NullPointerException expected) {
    }
    try {
        directory.register(watchService, (WatchEvent.Kind<?>) null);
        fail();
    } catch (NullPointerException expected) {
    }
}
Also used : Path(java.nio.file.Path) Kind(java.nio.file.WatchEvent.Kind) WatchEvent(java.nio.file.WatchEvent) WatchService(java.nio.file.WatchService) Test(org.junit.Test)

Example 44 with WatchService

use of java.nio.file.WatchService in project knime-core by knime.

the class DataContainerTest method testWriteRead.

/**
 * In this test, we write a table, check that no unnecessary temp files have been generated and left undeleted, read
 * the file, and compare the read table to the written table.
 *
 * @throws IOException an exception that is thrown when something goes wrong while creating a temporary buffer file,
 *             writing to it, or reading from it
 * @throws CanceledExecutionException an exception that is thrown when writing data to a zip file is cancelled
 * @throws InterruptedException an exception that is thrown if the test thread is interrupted while waiting for
 *             asynchronous disk write threads
 */
@Test(timeout = 5000)
public void testWriteRead() throws IOException, CanceledExecutionException, InterruptedException {
    // (1) create table
    final ContainerTable writeTable = generateMediumSizedTable();
    // (2) create file to write to / read from and start monitoring file creation and deletion in temp dir
    final File file = FileUtil.createTempFile("testWriteStream", ".zip");
    file.deleteOnExit();
    // wait for all asynchronous disk write threads to terminate such that they do not interfere with our
    // monitoring of file creation / deletion.
    BufferTest.waitForBufferToBeFlushed(((BufferedContainerTable) writeTable).getBuffer());
    try (WatchService watcher = FileSystems.getDefault().newWatchService()) {
        Path dir = FileUtil.getWorkflowTempDir().toPath();
        WatchKey key = dir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE);
        // (3) write to file
        final ExecutionMonitor exec = new ExecutionMonitor(new DefaultNodeProgressMonitor());
        DataContainer.writeToZip(writeTable, file, exec);
        // (4) make sure that no undeleted temp files have been created in the process (see AP-9727)
        Set<String> undeletedFilenames = new HashSet<>();
        for (WatchEvent<?> event : key.pollEvents()) {
            WatchEvent.Kind<?> kind = event.kind();
            String filename = ((Path) event.context()).toString();
            if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
                undeletedFilenames.add(filename);
            } else if (kind == StandardWatchEventKinds.ENTRY_DELETE) {
                undeletedFilenames.remove(filename);
            }
        }
        org.junit.Assert.assertTrue("Unnecessary (and undeleted) temp files created: " + String.join(", ", undeletedFilenames), undeletedFilenames.isEmpty());
        // (5) read the file file and compare its content to the original table
        final ContainerTable readTable = DataContainer.readFromZip(file);
        try (final CloseableRowIterator writeIt = writeTable.iterator();
            final CloseableRowIterator readIt = readTable.iterator()) {
            int i = 0;
            while (writeIt.hasNext() && readIt.hasNext()) {
                i++;
                final DataRow refRow = writeIt.next();
                final DataRow dataRow = readIt.next();
                org.junit.Assert.assertEquals("Row key in row " + i, dataRow.getKey(), refRow.getKey());
                for (int j = 0; j < refRow.getNumCells(); j++) {
                    final DataCell refCell = refRow.getCell(j);
                    final DataCell dataCell = dataRow.getCell(j);
                    if (refCell.isMissing()) {
                        org.junit.Assert.assertTrue("Cell " + j + " in Row " + i + " is missing", dataCell.isMissing());
                        org.junit.Assert.assertEquals("Error message of missing cell " + j + " in Row " + i, ((MissingValue) refCell).getError(), ((MissingValue) dataCell).getError());
                    } else {
                        org.junit.Assert.assertEquals("Cell " + j + " in Row " + i, refCell, dataCell);
                    }
                }
            }
            org.junit.Assert.assertFalse("Read table has " + writeTable.size() + " rows", writeIt.hasNext() || readIt.hasNext());
        }
    }
}
Also used : Path(java.nio.file.Path) WatchKey(java.nio.file.WatchKey) DataRow(org.knime.core.data.DataRow) DefaultNodeProgressMonitor(org.knime.core.node.DefaultNodeProgressMonitor) DataCell(org.knime.core.data.DataCell) WatchEvent(java.nio.file.WatchEvent) ExecutionMonitor(org.knime.core.node.ExecutionMonitor) File(java.io.File) WatchService(java.nio.file.WatchService) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 45 with WatchService

use of java.nio.file.WatchService in project jgnash by ccavanaugh.

the class FileUtils method waitForFileRemoval.

/**
 * Blocks for a specified period of time for removal of a file
 *
 * @param fileName file to monitor
 * @param timeout  timeout in milliseconds
 * @return true if the file existed and was removed
 */
public static boolean waitForFileRemoval(final String fileName, final long timeout) {
    boolean result = false;
    final LocalDateTime start = LocalDateTime.now();
    if (fileName != null && Files.exists(Paths.get(fileName))) {
        final Path filePath = Paths.get(fileName);
        try (final WatchService watchService = FileSystems.getDefault().newWatchService()) {
            filePath.getParent().register(watchService, StandardWatchEventKinds.ENTRY_DELETE);
            while (Duration.between(start, LocalDateTime.now()).toMillis() < timeout) {
                final WatchKey watchKey = watchService.poll(timeout, TimeUnit.MILLISECONDS);
                if (watchKey != null) {
                    for (final WatchEvent<?> ignored : watchKey.pollEvents()) {
                        if (!Files.exists(filePath)) {
                            Logger.getLogger(FileUtils.class.getName()).info(fileName + " was removed");
                            result = true;
                            break;
                        }
                    }
                }
            }
        } catch (final IOException e) {
            logSevere(FileUtils.class, e);
        } catch (final InterruptedException e) {
            logSevere(FileUtils.class, e);
            Thread.currentThread().interrupt();
        }
    } else {
        // lock file was already gone
        result = true;
    }
    // Last check for file existence.  File removal could have occurred before watch service started
    if (!result && Files.exists(Paths.get(fileName))) {
        Logger.getLogger(FileUtils.class.getName()).info("Timed out waiting for removal of: " + fileName);
    }
    return result;
}
Also used : LocalDateTime(java.time.LocalDateTime) Path(java.nio.file.Path) WatchKey(java.nio.file.WatchKey) IOException(java.io.IOException) WatchService(java.nio.file.WatchService)

Aggregations

WatchService (java.nio.file.WatchService)56 Path (java.nio.file.Path)40 WatchKey (java.nio.file.WatchKey)32 WatchEvent (java.nio.file.WatchEvent)23 IOException (java.io.IOException)21 Test (org.junit.Test)18 File (java.io.File)16 FileSystem (java.nio.file.FileSystem)6 ClosedWatchServiceException (java.nio.file.ClosedWatchServiceException)5 Kind (java.nio.file.WatchEvent.Kind)5 FileSystems (java.nio.file.FileSystems)4 StandardWatchEventKinds (java.nio.file.StandardWatchEventKinds)4 SensitivityWatchEventModifier (com.sun.nio.file.SensitivityWatchEventModifier)3 SuppressFBWarnings (edu.umd.cs.findbugs.annotations.SuppressFBWarnings)3 InputStream (java.io.InputStream)3 ArrayList (java.util.ArrayList)3 HashMap (java.util.HashMap)3 TimeUnit (java.util.concurrent.TimeUnit)3 BufferedReader (java.io.BufferedReader)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2