Search in sources :

Example 46 with WatchService

use of java.nio.file.WatchService in project tutorials by eugenp.

the class DirectoryWatcherExample method main.

public static void main(String[] args) throws IOException, InterruptedException {
    WatchService watchService = FileSystems.getDefault().newWatchService();
    Path path = Paths.get(System.getProperty("user.home"));
    path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);
    WatchKey key;
    while ((key = watchService.take()) != null) {
        for (WatchEvent<?> event : key.pollEvents()) {
            System.out.println("Event kind:" + event.kind() + ". File affected: " + event.context() + ".");
        }
        key.reset();
    }
    watchService.close();
}
Also used : Path(java.nio.file.Path) WatchKey(java.nio.file.WatchKey) WatchService(java.nio.file.WatchService)

Example 47 with WatchService

use of java.nio.file.WatchService in project webpieces by deanhiller.

the class YourCompanyAbstractDevServer method watchForDangerousJarChangesImpl.

private void watchForDangerousJarChangesImpl(URL res) throws IOException {
    // It's always a jar in your code but sometimes we run Dev Server in webpieces where the code is not a jar
    // ie(you can delete the if statement if you like)
    log.info("res=" + res.getFile() + " res=" + res + " res1" + res.getPath());
    // register jar file listener so on changes, we shutdown the server on the developer and make them reboot
    String filePath = res.getFile();
    String absPath = filePath.substring("file:".length());
    String fullJarPath = absPath.split("!")[0];
    File f = new File(fullJarPath);
    Path directoryPath = f.getParentFile().toPath();
    WatchService watcher = FileSystems.getDefault().newWatchService();
    directoryPath.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
    fileWatchThread.execute(new MyFileWatchRunnable(watcher));
}
Also used : Path(java.nio.file.Path) File(java.io.File) VirtualFile(org.webpieces.util.file.VirtualFile) WatchService(java.nio.file.WatchService)

Example 48 with WatchService

use of java.nio.file.WatchService in project streamsx.topology by IBMStreams.

the class DirectoryWatcher method process.

@SuppressWarnings("unchecked")
@Override
protected void process() throws Exception {
    Path dir = dirFile.toPath();
    WatchService watcher = FileSystems.getDefault().newWatchService();
    dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE);
    sortAndSubmit(Arrays.asList(dirFile.listFiles(this)));
    for (; !Thread.interrupted(); ) {
        WatchKey key;
        try {
            key = watcher.take();
        } catch (InterruptedException e) {
            // shutdown has been requested
            return;
        }
        List<File> newFiles = new ArrayList<>();
        boolean needFullScan = false;
        for (WatchEvent<?> watchEvent : key.pollEvents()) {
            if (ENTRY_CREATE == watchEvent.kind()) {
                Path newPath = ((WatchEvent<Path>) watchEvent).context();
                File newFile = toFile(newPath);
                if (accept(newFile))
                    newFiles.add(newFile);
            } else if (ENTRY_DELETE == watchEvent.kind()) {
                Path deletedPath = ((WatchEvent<Path>) watchEvent).context();
                File deletedFile = toFile(deletedPath);
                seenFiles.remove(deletedFile.getName());
            } else if (OVERFLOW == watchEvent.kind()) {
                needFullScan = true;
            }
        }
        key.reset();
        if (needFullScan) {
            Collections.addAll(newFiles, dirFile.listFiles(this));
        }
        sortAndSubmit(newFiles);
    }
}
Also used : Path(java.nio.file.Path) WatchKey(java.nio.file.WatchKey) ArrayList(java.util.ArrayList) WatchEvent(java.nio.file.WatchEvent) WatchService(java.nio.file.WatchService) File(java.io.File)

Example 49 with WatchService

use of java.nio.file.WatchService in project crate by crate.

the class PutHeadChunkRunnable method run.

@Override
public void run() {
    FileInputStream fileInputStream = null;
    try {
        int bufSize = 4096;
        int bytesRead;
        int size;
        int maxFileGrowthWait = 5;
        int fileGrowthWaited = 0;
        byte[] buffer = new byte[bufSize];
        long remainingBytes = bytesToSend;
        File pendingFile;
        try {
            pendingFile = digestBlob.file();
            if (pendingFile == null) {
                pendingFile = digestBlob.getContainerFile();
            }
            fileInputStream = new FileInputStream(pendingFile);
        } catch (FileNotFoundException e) {
            // this happens if the file has already been moved from tmpDirectory to containerDirectory
            pendingFile = digestBlob.getContainerFile();
            fileInputStream = new FileInputStream(pendingFile);
        }
        while (remainingBytes > 0) {
            size = (int) Math.min(bufSize, remainingBytes);
            bytesRead = fileInputStream.read(buffer, 0, size);
            if (bytesRead < size) {
                waitUntilFileHasGrown(pendingFile);
                fileGrowthWaited++;
                if (fileGrowthWaited == maxFileGrowthWait) {
                    throw new HeadChunkFileTooSmallException(pendingFile.getAbsolutePath());
                }
                if (bytesRead < 1) {
                    continue;
                }
            }
            remainingBytes -= bytesRead;
            var listener = new PlainActionFuture<TransportResponse>();
            transportService.sendRequest(recipientNode, BlobHeadRequestHandler.Actions.PUT_BLOB_HEAD_CHUNK, new PutBlobHeadChunkRequest(transferId, new BytesArray(buffer, 0, bytesRead)), TransportRequestOptions.EMPTY, new ActionListenerResponseHandler<>(listener, in -> TransportResponse.Empty.INSTANCE));
            listener.actionGet();
        }
    } catch (IOException ex) {
        LOGGER.error("IOException in PutHeadChunkRunnable", ex);
    } finally {
        blobTransferTarget.putHeadChunkTransferFinished(transferId);
        if (watcher != null) {
            try {
                watcher.close();
            } catch (IOException e) {
                LOGGER.error("Error closing WatchService in {}", e, getClass().getSimpleName());
            }
        }
        if (fileInputStream != null) {
            try {
                fileInputStream.close();
            } catch (IOException e) {
                LOGGER.error("Error closing HeadChunk", e);
            }
        }
    }
}
Also used : WatchEvent(java.nio.file.WatchEvent) PlainActionFuture(org.elasticsearch.action.support.PlainActionFuture) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) UUID(java.util.UUID) FileSystem(java.nio.file.FileSystem) File(java.io.File) FileNotFoundException(java.io.FileNotFoundException) WatchKey(java.nio.file.WatchKey) TimeUnit(java.util.concurrent.TimeUnit) BytesArray(org.elasticsearch.common.bytes.BytesArray) BlobTransferTarget(io.crate.blob.BlobTransferTarget) StandardWatchEventKinds(java.nio.file.StandardWatchEventKinds) WatchService(java.nio.file.WatchService) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) Logger(org.apache.logging.log4j.Logger) ActionListenerResponseHandler(org.elasticsearch.action.ActionListenerResponseHandler) TransportResponse(org.elasticsearch.transport.TransportResponse) TransportRequestOptions(org.elasticsearch.transport.TransportRequestOptions) TransportService(org.elasticsearch.transport.TransportService) DigestBlob(io.crate.blob.DigestBlob) Path(java.nio.file.Path) LogManager(org.apache.logging.log4j.LogManager) FileSystems(java.nio.file.FileSystems) BytesArray(org.elasticsearch.common.bytes.BytesArray) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) PlainActionFuture(org.elasticsearch.action.support.PlainActionFuture) File(java.io.File)

Example 50 with WatchService

use of java.nio.file.WatchService in project spring-cloud-gcp by spring-cloud.

the class PubSubEmulator method updateConfig.

/**
 * 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");
}
Also used : Path(java.nio.file.Path) Files(java.nio.file.Files) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) IOException(java.io.IOException) InputStreamReader(java.io.InputStreamReader) WatchKey(java.nio.file.WatchKey) TimeUnit(java.util.concurrent.TimeUnit) StandardWatchEventKinds(java.nio.file.StandardWatchEventKinds) WatchService(java.nio.file.WatchService) ExternalResource(org.junit.rules.ExternalResource) Paths(java.nio.file.Paths) StringTokenizer(java.util.StringTokenizer) Optional(java.util.Optional) Log(org.apache.commons.logging.Log) Assert.fail(org.junit.Assert.fail) Assume.assumeTrue(org.junit.Assume.assumeTrue) BufferedReader(java.io.BufferedReader) LogFactory(org.apache.commons.logging.LogFactory) Path(java.nio.file.Path) FileSystems(java.nio.file.FileSystems) WatchKey(java.nio.file.WatchKey)

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