Search in sources :

Example 36 with WatchKey

use of java.nio.file.WatchKey in project dwoss by gg-net.

the class DirectoryMonitor method run.

@Override
public void run() {
    try {
        WatchKey key = watchService.take();
        // Need to poll events before reset.
        key.pollEvents();
        key.reset();
        reloadView();
    } catch (InterruptedException ex) {
    }
}
Also used : WatchKey(java.nio.file.WatchKey)

Example 37 with WatchKey

use of java.nio.file.WatchKey in project logging-log4j2 by apache.

the class RollingAppenderTempCompressedFilePatternTest method testAppender.

@Test
public void testAppender() throws Exception {
    final File dirTmp = new File(DIR_TMP);
    dirTmp.mkdirs();
    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);
        assertEquals("Temporarys file created not equals to compressed files " + temporaryFilesCreated + "/" + gzippedFiles, gzippedFiles, temporaryFilesCreated);
    }
}
Also used : Path(java.nio.file.Path) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) WatchKey(java.nio.file.WatchKey) ArrayList(java.util.ArrayList) CompressorStreamFactory(org.apache.commons.compress.compressors.CompressorStreamFactory) ByteArrayOutputStream(java.io.ByteArrayOutputStream) FileInputStream(java.io.FileInputStream) CompressorException(org.apache.commons.compress.compressors.CompressorException) CompressorException(org.apache.commons.compress.compressors.CompressorException) WatchEvent(java.nio.file.WatchEvent) File(java.io.File) WatchService(java.nio.file.WatchService) Test(org.junit.Test)

Example 38 with WatchKey

use of java.nio.file.WatchKey in project logging-log4j2 by apache.

the class RollingAppenderDirectWriteTempCompressedFilePatternTest method testAppender.

@Test
public void testAppender() throws Exception {
    final File dir = new File(DIR);
    dir.mkdirs();
    try (final WatchService watcher = FileSystems.getDefault().newWatchService()) {
        WatchKey key = dir.toPath().register(watcher, StandardWatchEventKinds.ENTRY_CREATE);
        for (int i = 0; i < 100; ++i) {
            logger.debug("This is test message number " + i);
        }
        Thread.sleep(50);
        assertTrue("Directory not created", dir.exists() && dir.listFiles().length > 0);
        final File[] files = dir.listFiles();
        assertNotNull(files);
        assertThat(files, hasItemInArray(that(hasName(that(endsWith(".gz"))))));
        int temporaryFilesCreated = 0;
        int compressedFiles = 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++;
            }
            if (filename.toString().endsWith(".gz")) {
                compressedFiles++;
            }
        }
        assertTrue("No temporary file created during compression", temporaryFilesCreated > 0);
        assertEquals("Temporarys file created not equals to compressed files", compressedFiles, temporaryFilesCreated);
    }
}
Also used : Path(java.nio.file.Path) WatchKey(java.nio.file.WatchKey) WatchEvent(java.nio.file.WatchEvent) File(java.io.File) WatchService(java.nio.file.WatchService) Test(org.junit.Test)

Example 39 with WatchKey

use of java.nio.file.WatchKey in project javaee7-samples by javaee-samples.

the class WatchingThread method run.

public void run() {
    while (true) {
        try {
            WatchKey watchKey = watchService.take();
            if (watchKey != null) {
                dispatchEvents(watchKey.pollEvents(), resourceAdapter.getListener(watchKey));
                watchKey.reset();
            }
        } catch (ClosedWatchServiceException e) {
            return;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
Also used : WatchKey(java.nio.file.WatchKey) ClosedWatchServiceException(java.nio.file.ClosedWatchServiceException)

Example 40 with WatchKey

use of java.nio.file.WatchKey in project javaee7-samples by javaee-samples.

the class FileSystemWatcherResourceAdapter method endpointActivation.

@Override
public void endpointActivation(MessageEndpointFactory endpointFactory, ActivationSpec activationSpec) throws ResourceException {
    out.println(this.getClass().getSimpleName() + " resource adapater endpoint activated for " + endpointFactory.getEndpointClass());
    FileSystemWatcherActivationSpec fsWatcherAS = (FileSystemWatcherActivationSpec) activationSpec;
    try {
        WatchKey watchKey = fileSystem.getPath(fsWatcherAS.getDir()).register(watchService, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
        listeners.put(watchKey, endpointFactory);
        endpointFactoryToBeanClass.put(endpointFactory, endpointFactory.getEndpointClass());
    } catch (IOException e) {
        throw new ResourceException(e);
    }
}
Also used : WatchKey(java.nio.file.WatchKey) ResourceException(javax.resource.ResourceException) IOException(java.io.IOException)

Aggregations

WatchKey (java.nio.file.WatchKey)134 Path (java.nio.file.Path)88 WatchEvent (java.nio.file.WatchEvent)65 IOException (java.io.IOException)49 WatchService (java.nio.file.WatchService)30 File (java.io.File)27 ClosedWatchServiceException (java.nio.file.ClosedWatchServiceException)18 ArrayList (java.util.ArrayList)10 Test (org.junit.Test)10 HashMap (java.util.HashMap)7 Map (java.util.Map)7 FileSystems (java.nio.file.FileSystems)6 FileVisitResult (java.nio.file.FileVisitResult)6 HashSet (java.util.HashSet)6 List (java.util.List)6 StandardWatchEventKinds (java.nio.file.StandardWatchEventKinds)5 InputStream (java.io.InputStream)4 AccessDeniedException (java.nio.file.AccessDeniedException)4 Kind (java.nio.file.WatchEvent.Kind)4 Logger (org.slf4j.Logger)4