All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.takari.watcher.OsxDirectoryWatcher Maven / Gradle / Ivy

package io.takari.watcher;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;

import io.takari.watchservice.MacOSXListeningWatchService;
import io.takari.watchservice.WatchablePath;

import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;
import static java.nio.file.StandardWatchEventKinds.OVERFLOW;

public class OsxDirectoryWatcher extends DirectoryWatcher {

  private final WatchService watchService;
  private final DirectoryChangeListener listener;

  public OsxDirectoryWatcher(Path dir, DirectoryChangeListener listener) throws IOException {
    this.watchService = new MacOSXListeningWatchService();
    this.listener = listener;
    WatchablePath directoryToMonitor = new WatchablePath(dir);
    directoryToMonitor.register(watchService, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
  }

  @Override
  public void processEvents() throws IOException {
    for (;;) {
      // wait for key to be signaled
      WatchKey key;
      try {
        key = watchService.take();
      } catch (InterruptedException x) {
        return;
      }
      for (WatchEvent event : key.pollEvents()) {
        WatchEvent.Kind kind = event.kind();
        if (kind == OVERFLOW) {
          continue;
        }
        //
        // The filename is the context of the event.
        //
        @SuppressWarnings({"unchecked"})
        WatchEvent ev = (WatchEvent) event;
        Path file = ev.context();
        if (file.toFile().isDirectory()) {
          continue;
        }
        if (kind == ENTRY_DELETE) {
          listener.onDelete(file);
        }
        if (kind == ENTRY_MODIFY) {
          listener.onModify(file);
        }
        if (kind == ENTRY_CREATE) {
          listener.onCreate(file);
        }
      }
      // Reset the key -- this step is critical to receive further watch events.
      boolean valid = key.reset();
      if (!valid) {
        break;
      }
    }
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy