Search in sources :

Example 76 with WatchEvent

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

the class PollingWatchServiceTest method assertWatcherHasEvents.

private void assertWatcherHasEvents(List<WatchEvent<?>> expected, List<WatchEvent<?>> alternate) throws InterruptedException {
    // otherwise we could read 1 event but not all the events we're expecting
    ensureTimeToPoll();
    WatchKey key = watcher.take();
    List<WatchEvent<?>> keyEvents = key.pollEvents();
    if (keyEvents.size() == expected.size() || alternate.isEmpty()) {
        assertThat(keyEvents).containsExactlyElementsIn(expected);
    } else {
        assertThat(keyEvents).containsExactlyElementsIn(alternate);
    }
    key.reset();
}
Also used : WatchKey(java.nio.file.WatchKey) WatchEvent(java.nio.file.WatchEvent)

Example 77 with WatchEvent

use of java.nio.file.WatchEvent 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 78 with WatchEvent

use of java.nio.file.WatchEvent in project meecrowave by apache.

the class ReloadOnChangeController method run.

@Override
public void run() {
    if (watchService == null) {
        return;
    }
    final CountDownLatch latch = new CountDownLatch(1);
    bouncer = new Thread(() -> {
        // simple bouncing impl
        long last = redeployMarker;
        latch.countDown();
        boolean needsRedeploy = false;
        long antepenultiem = -1;
        while (running) {
            if (redeployMarker > last) {
                antepenultiem = last;
                last = redeployMarker;
                needsRedeploy = true;
            } else if (needsRedeploy) {
                antepenultiem = last;
            }
            try {
                Thread.sleep(bouncing);
            } catch (final InterruptedException e) {
                Thread.interrupted();
                break;
            }
            if (needsRedeploy && last == antepenultiem) {
                new LogFacade(ReloadOnChangeController.class.getName()).info("Redeploying " + context.getName());
                redeploy();
            }
        }
    });
    bouncer.setName("meecrowave-watcher-redeployer");
    bouncer.start();
    try {
        latch.await(1, TimeUnit.MINUTES);
    } catch (final InterruptedException e) {
        Thread.interrupted();
        return;
    }
    paths.forEach(p -> {
        try {
            Files.walkFileTree(p, new SimpleFileVisitor<Path>() {

                @Override
                public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) throws IOException {
                    dir.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);
                    return FileVisitResult.CONTINUE;
                }
            });
        } catch (final IOException e) {
            new LogFacade(ReloadOnChangeController.class.getName()).warn(e.getMessage());
        }
    });
    try {
        while (running) {
            final WatchKey watchKey = watchService.poll(bouncing, TimeUnit.MILLISECONDS);
            if (watchKey == null) {
                Thread.sleep(bouncing);
                continue;
            }
            boolean foundNew = false;
            for (final WatchEvent<?> event : watchKey.pollEvents()) {
                final Path path = Path.class.cast(event.context());
                final WatchEvent.Kind<?> kind = event.kind();
                if (!isIgnored(kind, path)) {
                    foundNew = true;
                    final File file = path.toAbsolutePath().toFile();
                    if (file.isDirectory()) {
                        if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
                            try {
                                path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE);
                            } catch (final IOException e) {
                                new LogFacade(ReloadOnChangeController.class.getName()).warn(e.getMessage());
                            }
                        }
                    }
                    break;
                }
            }
            if (foundNew) {
                new LogFacade(ReloadOnChangeController.class.getName()).info("Marking to redeploy " + context.getName());
                redeployMarker = System.nanoTime();
            }
            if (!watchKey.reset()) {
                // deletion
                watchKey.cancel();
            }
        }
    } catch (final InterruptedException ie) {
        Thread.interrupted();
    }
}
Also used : Path(java.nio.file.Path) WatchKey(java.nio.file.WatchKey) FileVisitResult(java.nio.file.FileVisitResult) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) LogFacade(org.apache.meecrowave.logging.tomcat.LogFacade) WatchEvent(java.nio.file.WatchEvent) File(java.io.File) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes)

Example 79 with WatchEvent

use of java.nio.file.WatchEvent 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 80 with WatchEvent

use of java.nio.file.WatchEvent in project chatty by chatty.

the class FileWatcher method run.

@Override
public void run() {
    for (; ; ) {
        WatchKey key;
        /**
         * Wait for a modification to occur.
         */
        try {
            key = watcher.take();
        } catch (InterruptedException ex) {
            return;
        }
        /**
         * Wait a bit for events to accumulate. This prevents several
         * consecutive modifications (e.g. several writes or change of file
         * modification date) from all triggering the listener.
         */
        try {
            Thread.sleep(4000);
        } catch (InterruptedException ex) {
            return;
        }
        for (WatchEvent<?> event : key.pollEvents()) {
            WatchEvent.Kind<?> kind = event.kind();
            if (kind == OVERFLOW) {
                continue;
            }
            WatchEvent<Path> ev = (WatchEvent<Path>) event;
            Path fileName = ev.context();
            Path changedFile = directory.resolve(fileName);
            if (changedFile.equals(file)) {
                listener.fileChanged();
            }
        }
        boolean valid = key.reset();
        if (!valid) {
            break;
        }
    }
}
Also used : Path(java.nio.file.Path) WatchKey(java.nio.file.WatchKey) WatchEvent(java.nio.file.WatchEvent)

Aggregations

WatchEvent (java.nio.file.WatchEvent)92 Path (java.nio.file.Path)68 WatchKey (java.nio.file.WatchKey)58 IOException (java.io.IOException)33 File (java.io.File)27 Test (org.junit.Test)24 WatchService (java.nio.file.WatchService)20 BuckEventBus (com.facebook.buck.event.BuckEventBus)13 FakeClock (com.facebook.buck.timing.FakeClock)13 EventBus (com.google.common.eventbus.EventBus)12 ClosedWatchServiceException (java.nio.file.ClosedWatchServiceException)10 EasyMock.anyObject (org.easymock.EasyMock.anyObject)10 ArrayList (java.util.ArrayList)9 HashMap (java.util.HashMap)6 Subscribe (com.google.common.eventbus.Subscribe)5 FakeWatchmanClient (com.facebook.buck.io.FakeWatchmanClient)4 FileSystems (java.nio.file.FileSystems)4 StandardWatchEventKinds (java.nio.file.StandardWatchEventKinds)4 HashSet (java.util.HashSet)4 List (java.util.List)4