Java Code Examples for java.nio.file.WatchEvent.Kind#equals()

The following examples show how to use java.nio.file.WatchEvent.Kind#equals() . 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: ScriptFileWatcher.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) {
    File file = path.toFile();
    if (!file.isHidden()) {
        try {
            URL fileUrl = file.toURI().toURL();
            if (kind.equals(ENTRY_DELETE)) {
                this.removeFile(fileUrl);
            }

            if (file.canRead() && (kind.equals(ENTRY_CREATE) || kind.equals(ENTRY_MODIFY))) {
                this.importFile(fileUrl);
            }
        } catch (MalformedURLException e) {
            logger.error("malformed", e);
        }
    }
}
 
Example 2
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 3
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 4
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 5
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 6
Source File: SingularityS3UploaderDriver.java    From Singularity with Apache License 2.0 4 votes vote down vote up
@Override
protected boolean processEvent(Kind<?> kind, final Path filename) throws IOException {
  metrics.getFilesystemEventsMeter().mark();

  if (!isS3MetadataFile(filename)) {
    return false;
  }

  runLock.lock();

  try {
    if (isStopped()) {
      LOG.warn("Driver is stopped, ignoring file watch event for {}", filename);
      return false;
    }

    final Path fullPath = Paths
      .get(baseConfiguration.getS3UploaderMetadataDirectory())
      .resolve(filename);

    if (kind.equals(StandardWatchEventKinds.ENTRY_DELETE)) {
      Optional<SingularityUploader> foundRegular = metadataToUploader
        .values()
        .stream()
        .filter(input -> input != null && input.getMetadataPath().equals(fullPath))
        .findFirst();
      Optional<SingularityUploader> found = foundRegular.isPresent()
        ? foundRegular
        : metadataToImmediateUploader
          .values()
          .stream()
          .filter(input -> input != null && input.getMetadataPath().equals(fullPath))
          .findFirst();

      LOG.trace("Found {} to match deleted path {}", found, filename);

      if (found.isPresent()) {
        expiring.add(found.get());
      }
    } else {
      return handleNewOrModifiedS3Metadata(fullPath);
    }

    return false;
  } finally {
    runLock.unlock();
  }
}