java.nio.file.WatchEvent.Kind Java Examples

The following examples show how to use java.nio.file.WatchEvent.Kind. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: WatchQueueReader.java    From openhab-core with Eclipse Public License 2.0 6 votes vote down vote up
private void registerWithSubDirectories(AbstractWatchService watchService, Path toWatch) throws IOException {
    Files.walkFileTree(toWatch, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE,
            new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult preVisitDirectory(Path subDir, BasicFileAttributes attrs)
                        throws IOException {
                    Kind<?>[] kinds = watchService.getWatchEventKinds(subDir);
                    if (kinds != null) {
                        registerDirectoryInternal(watchService, kinds, subDir);
                    }
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                    if (exc instanceof AccessDeniedException) {
                        logger.warn("Access to folder '{}' was denied, therefore skipping it.",
                                file.toAbsolutePath().toString());
                    }
                    return FileVisitResult.SKIP_SUBTREE;
                }
            });
}
 
Example #2
Source File: AbstractWatchServiceTest.java    From openhab-core with Eclipse Public License 2.0 6 votes vote down vote up
private void fullEventAssertionsByKind(String fileName, Kind<?> kind, boolean osSpecific) throws Exception {
    waitForAssert(() -> assertThat(watchService.allFullEvents.size() >= 1, is(true)), DFL_TIMEOUT * 2,
            DFL_SLEEP_TIME);

    if (osSpecific && ENTRY_DELETE.equals(kind)) {
        // There is possibility that one more modify event is triggered on some OS
        // so sleep a bit extra time
        Thread.sleep(500);
        cleanUpOsSpecificModifyEvent();
    }

    assertEventCount(1);
    FullEvent fullEvent = watchService.allFullEvents.get(0);

    assertThat(fullEvent.eventPath.toString(), is(WATCHED_DIRECTORY + File.separatorChar + fileName));
    assertThat(fullEvent.eventKind, is(kind));
    assertThat(fullEvent.watchEvent.count() >= 1, is(true));
    assertThat(fullEvent.watchEvent.kind(), is(fullEvent.eventKind));
    String fileNameOnly = fileName.contains(File.separatorChar + "")
            ? fileName.substring(fileName.lastIndexOf(File.separatorChar) + 1, fileName.length())
            : fileName;
    assertThat(fullEvent.watchEvent.context().toString(), is(fileNameOnly));

    // Clear all the asserted events
    watchService.allFullEvents.clear();
}
 
Example #3
Source File: ResourceListener.java    From PeonyFramwork with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
	FileListener listener = new FileListener() {
		@Override
		public void onEvent(String rootPath, WatchEvent<Path> event) {
			Kind<Path> kind = event.kind();
			String fileName = event.context().getFileName().toString();
			if (kind == StandardWatchEventKinds.ENTRY_MODIFY) {
				System.err.println(rootPath +"/"+fileName +"   "+ event.kind().name());
			}
		}

		@Override
		public Kind<?>[] events() {
			return new Kind<?>[] { StandardWatchEventKinds.ENTRY_MODIFY };
		}
	};

	ResourceListener.addListener("E:/jPersist2", listener);
	ResourceListener.addListener("E:/MyDownloads/Download", listener);
}
 
Example #4
Source File: LiveDirs.java    From LiveDirsFX with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void processEvent(Path dir, WatchEvent<Path> event) {
    // Context for directory entry event is the file name of entry
    Path relChild = event.context();
    Path child = dir.resolve(relChild);

    Kind<Path> kind = event.kind();

    if(kind == ENTRY_MODIFY) {
        handleModification(child, externalInitiator);
    } else if(kind == ENTRY_CREATE) {
        handleCreation(child, externalInitiator);
    } else if(kind == ENTRY_DELETE) {
        model.delete(child, externalInitiator);
    } else {
        throw new AssertionError("unreachable code");
    }
}
 
Example #5
Source File: FolderWatchService.java    From PeerWasp with MIT License 6 votes vote down vote up
/**
 * Precondition: Event and child must not be null.
 * @param kind type of the event (create, modify, ...)
 * @param source Identifies the related file.
 */
private void handleEvent(Kind<Path> kind, Path source) {
	try {
		if(PathUtils.isFileHidden(source)){
			return;
		}
		if (kind.equals(ENTRY_CREATE)) {
			addNotifyEvent(new NotifyFileCreated(source));
		} else if (kind.equals(ENTRY_MODIFY)) {
			addNotifyEvent(new NotifyFileModified(source));
		} else if (kind.equals(ENTRY_DELETE)) {
			addNotifyEvent(new NotifyFileDeleted(source));
		} else if (kind.equals(OVERFLOW)) {
			// error - overflow... should not happen here (continue if such an event occurs).
			// handled already
			logger.warn("Overflow event from watch service. Too many events?");
		} else {
			logger.warn("Unknown event received");
		}
	} catch (InterruptedException iex) {
		// put into queue failed
		logger.info("Handling event interrupted.", iex);
	}
}
 
Example #6
Source File: TransformationScriptWatcher.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
protected void processWatchEvent(WatchEvent<?> event, Kind<?> kind, Path path) {
    logger.debug("New watch event {} for path {}.", kind, path);

    if (kind == OVERFLOW) {
        return;
    }

    final WatchEvent<Path> ev = (WatchEvent<Path>) event;
    final Path filename = ev.context();

    logger.debug("Reloading javascript file {}.", filename);

    manager.removeFromCache(filename.toString());
}
 
Example #7
Source File: WatchQueueReader.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
private void registerWithSubDirectories(AbstractWatchService watchService, Path toWatch) throws IOException {
    Files.walkFileTree(toWatch, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE,
            new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult preVisitDirectory(Path subDir, BasicFileAttributes attrs)
                        throws IOException {
                    Kind<?>[] kinds = watchService.getWatchEventKinds(subDir);
                    if (kinds != null) {
                        registerDirectoryInternal(watchService, kinds, subDir);
                    }
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                    if (exc instanceof AccessDeniedException) {
                        logger.warn("Access to folder '{}' was denied, therefore skipping it.",
                                file.toAbsolutePath().toString());
                    }
                    return FileVisitResult.SKIP_SUBTREE;
                }
            });
}
 
Example #8
Source File: ConfigDispatcherFileWatcher.java    From openhab-core with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected void processWatchEvent(WatchEvent<?> event, Kind<?> kind, Path path) {
    if (kind == ENTRY_CREATE || kind == ENTRY_MODIFY) {
        File f = path.toFile();
        if (!f.isHidden() && f.getName().endsWith(".cfg")) {
            configDispatcher.processConfigFile(f);
        }
    } else if (kind == ENTRY_DELETE) {
        // Detect if a service specific configuration file was removed. We want to
        // notify the service in this case with an updated empty configuration.
        File configFile = path.toFile();
        if (configFile.isHidden() || configFile.isDirectory() || !configFile.getName().endsWith(".cfg")) {
            return;
        }
        configDispatcher.fileRemoved(configFile.getAbsolutePath());
    }
}
 
Example #9
Source File: ScriptFileWatcher.java    From openhab-core with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected void processWatchEvent(WatchEvent<?> event, Kind<?> kind, Path path) {
    File file = path.toFile();
    if (!file.isHidden()) {
        try {
            URL fileUrl = file.toURI().toURL();
            if (ENTRY_DELETE.equals(kind)) {
                removeFile(fileUrl);
            }

            if (file.canRead() && (ENTRY_CREATE.equals(kind) || ENTRY_MODIFY.equals(kind))) {
                importFile(fileUrl);
            }
        } catch (MalformedURLException e) {
            logger.error("malformed", e);
        }
    }
}
 
Example #10
Source File: ConfigDispatcherFileWatcher.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected void processWatchEvent(WatchEvent<?> event, Kind<?> kind, Path path) {
    if (kind == ENTRY_CREATE || kind == ENTRY_MODIFY) {
        File f = path.toFile();
        if (!f.isHidden() && f.getName().endsWith(".cfg")) {
            configDispatcher.processConfigFile(f);
        }
    } else if (kind == ENTRY_DELETE) {
        // Detect if a service specific configuration file was removed. We want to
        // notify the service in this case with an updated empty configuration.
        File configFile = path.toFile();
        if (configFile.isHidden() || configFile.isDirectory() || !configFile.getName().endsWith(".cfg")) {
            return;
        }
        configDispatcher.fileRemoved(configFile.getAbsolutePath());
    }
}
 
Example #11
Source File: MonitoringDecryptedFilesServiceImpl.java    From pgptool with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void handleFileChanged(Kind<?> operation, String fileAbsolutePathname) {
	if (StandardWatchEventKinds.ENTRY_CREATE.equals(operation)) {
		DecryptedFile recentlyRemovedEntry = recentlyRemoved.getIfPresent(fileAbsolutePathname);
		if (recentlyRemovedEntry != null) {
			addOrUpdate(recentlyRemovedEntry);
		}
		return;
	}

	if (StandardWatchEventKinds.ENTRY_DELETE.equals(operation)) {
		remove(fileAbsolutePathname);
		return;
	}

	// Other cases not supported -- not needed
}
 
Example #12
Source File: AbstractWatchServiceTest.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
private void fullEventAssertionsByKind(String fileName, Kind<?> kind, boolean osSpecific) throws Exception {
    waitForAssert(() -> assertThat(watchService.allFullEvents.size() >= 1, is(true)), DFL_TIMEOUT * 2,
            DFL_SLEEP_TIME);

    if (osSpecific && kind.equals(ENTRY_DELETE)) {
        // There is possibility that one more modify event is triggered on some OS
        // so sleep a bit extra time
        Thread.sleep(500);
        cleanUpOsSpecificModifyEvent();
    }

    assertEventCount(1);
    FullEvent fullEvent = watchService.allFullEvents.get(0);

    assertThat(fullEvent.eventPath.toString(), is(WATCHED_DIRECTORY + File.separatorChar + fileName));
    assertThat(fullEvent.eventKind, is(kind));
    assertThat(fullEvent.watchEvent.count() >= 1, is(true));
    assertThat(fullEvent.watchEvent.kind(), is(fullEvent.eventKind));
    String fileNameOnly = fileName.contains(File.separatorChar + "")
            ? fileName.substring(fileName.lastIndexOf(File.separatorChar) + 1, fileName.length())
            : fileName;
    assertThat(fullEvent.watchEvent.context().toString(), is(fileNameOnly));

    // Clear all the asserted events
    watchService.allFullEvents.clear();
}
 
Example #13
Source File: DirWatcher.java    From Launcher with GNU General Public License v3.0 5 votes vote down vote up
private void processKey(WatchKey key) throws IOException {
    Path watchDir = (Path) key.watchable();
    for (WatchEvent<?> event : key.pollEvents()) {
        Kind<?> kind = event.kind();
        if (kind.equals(StandardWatchEventKinds.OVERFLOW)) {
            if (PROP_IGN_OVERFLOW)
                continue; // Sometimes it's better to ignore than interrupt fair playing
            throw new IOException("Overflow");
        }

        // Resolve paths and verify is not exclusion
        Path path = watchDir.resolve((Path) event.context());
        Deque<String> stringPath = toPath(dir.relativize(path));
        if (matcher != null && !matcher.shouldVerify(stringPath))
            continue; // Exclusion; should not be verified
        // Verify is REALLY modified (not just attributes)
        if (kind.equals(StandardWatchEventKinds.ENTRY_MODIFY)) {
            HashedEntry entry = hdir.resolve(stringPath);
            if (entry != null && (entry.getType() != HashedEntry.Type.FILE || ((HashedFile) entry).isSame(path, digest)))
                continue; // Modified attributes, not need to worry :D
        }

        // Forbidden modification!
        throw new SecurityException(String.format("Forbidden modification (%s, %d times): '%s'", kind, event.count(), path));
    }
    key.reset();
}
 
Example #14
Source File: FolderObserver.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected void processWatchEvent(WatchEvent<?> event, Kind<?> kind, Path path) {
    File toCheck = getFileByFileExtMap(folderFileExtMap, path.getFileName().toString());
    if (toCheck != null && !toCheck.isHidden()) {
        checkFile(modelRepo, toCheck, kind);
    }
}
 
Example #15
Source File: FolderObserver.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected void processWatchEvent(WatchEvent<?> event, Kind<?> kind, Path path) {
    File toCheck = getFileByFileExtMap(folderFileExtMap, path.getFileName().toString());
    if (toCheck != null && !toCheck.isHidden()) {
        checkFile(modelRepository, toCheck, kind);
    }
}
 
Example #16
Source File: FolderObserver.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected Kind<?>[] getWatchEventKinds(Path directory) {
    if (directory != null && isNotEmpty(folderFileExtMap)) {
        String folderName = directory.getFileName().toString();
        if (folderFileExtMap.containsKey(folderName)) {
            return new Kind<?>[] { ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY };
        }
    }
    return null;
}
 
Example #17
Source File: AbstractWatchKey.java    From directory-watcher with Apache License 2.0 5 votes vote down vote up
public AbstractWatchKey(
    AbstractWatchService watcher,
    Watchable watchable,
    Iterable<? extends WatchEvent.Kind<?>> subscribedTypes,
    int queueSize) {
  this.watcher = requireNonNull(watcher);
  this.watchable = watchable; // nullable for Watcher poison
  this.events = new ArrayBlockingQueue<>(queueSize);

  Set<Kind<?>> types = new HashSet<Kind<?>>();
  subscribedTypes.forEach(types::add);
  this.subscribedTypes = Collections.unmodifiableSet(types);
}
 
Example #18
Source File: JWatchKey.java    From baratine with GNU General Public License v2.0 5 votes vote down vote up
public JWatchKey(JWatchService watchService,
                 JPath path,
                 Kind<?>[] events,
                 Modifier ... modifiers)
{
  Objects.requireNonNull(events);

  _watchService = watchService;
  _path = path;
  _events = events;
  _modifiers = modifiers;

  _watchHandle = path.getBfsFile().watch(pathString -> onWatch(pathString));
}
 
Example #19
Source File: UnixSshPathWatchKey.java    From jsch-nio with MIT License 5 votes vote down vote up
public UnixSshPathWatchKey( UnixSshFileSystemWatchService watchService, UnixSshPath dir, Kind<?>[] kinds, long pollingInterval, TimeUnit pollingIntervalTimeUnit ) {
    this.watchService = watchService;
    this.dir = dir;
    this.kindsToWatch = new HashSet<>();
    this.kindsToWatch.addAll( Arrays.asList( kinds ) );
    this.pollingInterval = pollingInterval;
    this.pollingIntervalTimeUnit = pollingIntervalTimeUnit;
    this.cancelled = false;
    this.initialized = false;
    this.addMap = new HashMap<>();
    this.deleteMap = new HashMap<>();
    this.modifyMap = new HashMap<>();
    this.state = State.READY;
}
 
Example #20
Source File: JWatchService.java    From baratine with GNU General Public License v2.0 5 votes vote down vote up
protected JWatchKey register(JPath path, Kind<?>[] events, Modifier ... modifiers)
{
  JWatchKey key = new JWatchKey(this, path, events, modifiers);

  synchronized (this) {
    _watchList.add(key);
  }

  return key;
}
 
Example #21
Source File: JPath.java    From baratine with GNU General Public License v2.0 5 votes vote down vote up
@Override
public WatchKey register(WatchService watcher, Kind<?>[] events,
                         Modifier... modifiers) throws IOException
{
  if (events.length == 0) {
    throw new IllegalArgumentException(L.l("no events specified to watch on: {0}", toUri()));
  }

  JWatchService jWatcher = (JWatchService) watcher;

  WatchKey key = jWatcher.register(this, events, modifiers);

  return key;
}
 
Example #22
Source File: AutomationWatchService.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected void processWatchEvent(WatchEvent<?> event, Kind<?> kind, Path path) {
    File file = path.toFile();
    if (!file.isHidden()) {
        if (kind.equals(ENTRY_DELETE)) {
            provider.removeResources(file);
        } else if (file.canRead()) {
            provider.importResources(file);
        }
    }
}
 
Example #23
Source File: AutomationWatchService.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected void processWatchEvent(WatchEvent<?> event, Kind<?> kind, Path path) {
    File file = path.toFile();
    if (!file.isHidden()) {
        if (ENTRY_DELETE.equals(kind)) {
            provider.removeResources(file);
        } else if (file.canRead()) {
            provider.importResources(file);
        }
    }
}
 
Example #24
Source File: BuckUnixPath.java    From buck with Apache License 2.0 5 votes vote down vote up
@Override
public WatchKey register(
    WatchService watcher, WatchEvent.Kind<?>[] events, WatchEvent.Modifier... modifiers)
    throws IOException {
  // TODO(buck_team): do not recourse to default Path implementation
  return asDefault().register(watcher, events, modifiers);
}
 
Example #25
Source File: FileSystemWatcher.java    From sldeditor with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Process watch events.
 *
 * @param key the key
 * @param keys the keys
 */
private void processWatchEvents(WatchKey key, List<WatchEvent<?>> keys) {
    for (WatchEvent<?> watchEvent : keys) {

        Kind<?> watchEventKind = watchEvent.kind();
        // Sometimes events are created faster than they are registered
        // or the implementation may specify a maximum number of events
        // and further events are discarded. In these cases an event of
        // kind overflow is returned. We ignore this case for now
        if (watchEventKind == StandardWatchEventKinds.OVERFLOW) {
            continue;
        }

        Path dir = (Path) key.watchable();
        Path fullPath = dir.resolve((Path) watchEvent.context());

        FileWatcherUpdateInterface parentObj = watcherMap.get(key);
        if (parentObj != null) {
            if (watchEventKind == StandardWatchEventKinds.ENTRY_CREATE) {
                // A new file has been created
                parentObj.fileAdded(fullPath);
            } else if (watchEventKind == StandardWatchEventKinds.ENTRY_MODIFY) {
                ReloadManager.getInstance().fileModified(fullPath);
                // The file has been modified.
                parentObj.fileModified(fullPath);
            } else if (watchEventKind == StandardWatchEventKinds.ENTRY_DELETE) {
                parentObj.fileDeleted(fullPath);
            }
        }
    }
}
 
Example #26
Source File: Main.java    From thorntail with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private static void processEvents(File watchedDir, Path file) {
    for (;;) {

        WatchKey key;
        try {
            key = watcher.take();
        } catch (InterruptedException x) {
            return;
        }

        for (WatchEvent<?> event: key.pollEvents()) {
            Kind<?> kind = event.kind();

            WatchEvent<Path> ev = (WatchEvent<Path>)event;
            Path name = ev.context();
            Path child = watchedDir.toPath().resolve(name);

            if (kind == ENTRY_DELETE && child.equals(file)) {
                return;
            }
        }

        boolean valid = key.reset();
        if (!valid) {
           break;
        }
    }
}
 
Example #27
Source File: HadoopPath.java    From jsr203-hadoop with Apache License 2.0 5 votes vote down vote up
@Override
public WatchKey register(WatchService watcher, Kind<?>[] events,
    Modifier... modifiers) throws IOException {
  if (watcher == null || events == null || modifiers == null) {
    throw new NullPointerException();
  }

  // Not implemented now
  // The Hadoop API for notification is not stable
  throw new IOException("Not implemented");
}
 
Example #28
Source File: AbstractWatchServiceTest.java    From openhab-core with Eclipse Public License 2.0 4 votes vote down vote up
public FullEvent(WatchEvent<?> event, Kind<?> kind, Path path) {
    watchEvent = event;
    eventKind = kind;
    eventPath = path;
}
 
Example #29
Source File: MTGPath.java    From MtgDesktopCompanion with GNU General Public License v3.0 4 votes vote down vote up
@Override
public WatchKey register(WatchService watcher, Kind<?>[] events, Modifier... modifiers) throws IOException {
	return null;
}
 
Example #30
Source File: ScriptFileWatcher.java    From openhab-core with Eclipse Public License 2.0 4 votes vote down vote up
@Override
protected Kind<?>[] getWatchEventKinds(Path subDir) {
    return new Kind<?>[] { ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY };
}