Java Code Examples for java.nio.file.WatchKey#cancel()

The following examples show how to use java.nio.file.WatchKey#cancel() . 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: LotsOfCancels.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Stress the given WatchService, specifically the cancel method, in
 * the given directory. Closes the WatchService when done.
 */
static void handle(Path dir, WatchService watcher) {
    try {
        try {
            Path file = dir.resolve("anyfile");
            for (int i=0; i<2000; i++) {
                WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE);
                Files.createFile(file);
                Files.delete(file);
                key.cancel();
            }
        } finally {
            watcher.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
        failed = true;
    }
}
 
Example 2
Source File: LotsOfCancels.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Stress the given WatchService, specifically the cancel method, in
 * the given directory. Closes the WatchService when done.
 */
static void handle(Path dir, WatchService watcher) {
    try {
        try {
            Path file = dir.resolve("anyfile");
            for (int i=0; i<2000; i++) {
                WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE);
                Files.createFile(file);
                Files.delete(file);
                key.cancel();
            }
        } finally {
            watcher.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
        failed = true;
    }
}
 
Example 3
Source File: JWatchService.java    From baratine with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void close() throws IOException
{
  ArrayList<JWatchKey> watchList = new ArrayList<>();

  if (_isClosed.getAndSet(true)) {
    return;
  }

  watchList.addAll(_watchList);
  _watchList.clear();

  for (WatchKey key : watchList) {
    key.cancel();
  }
}
 
Example 4
Source File: WorkspaceFolderData.java    From vscode-as3mxml with Apache License 2.0 6 votes vote down vote up
public void cleanup()
{
	if(project != null)
	{
		project.delete();
		project = null;
	}
	
       for(WatchKey watchKey : sourceOrLibraryPathWatchKeys.keySet())
       {
           watchKey.cancel();
       }
	sourceOrLibraryPathWatchKeys.clear();
	
	configurator = null;
}
 
Example 5
Source File: LibraryWatcher.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
public void watchDirs(Set<Path> dirs) {
    if (mWatcher == null) {
        return;
    }
    Map<Path, WatchKey> keep = new HashMap<>();
    for (Path p : dirs) {
        WatchKey key = mPathKeyMap.get(p);
        if (key == null) {
            try {
                keep.put(p, p.register(mWatcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE));
            } catch (IOException exception) {
                Log.error(exception);
            }
        } else {
            keep.put(p, key);
            mPathKeyMap.remove(p);
        }
    }
    for (WatchKey watchKey : mPathKeyMap.values()) {
        watchKey.cancel();
    }
    mPathKeyMap = keep;
}
 
Example 6
Source File: LotsOfCancels.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Stress the given WatchService, specifically the cancel method, in
 * the given directory. Closes the WatchService when done.
 */
static void handle(Path dir, WatchService watcher) {
    try {
        try {
            Path file = dir.resolve("anyfile");
            for (int i=0; i<2000; i++) {
                WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE);
                Files.createFile(file);
                Files.delete(file);
                key.cancel();
            }
        } finally {
            watcher.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
        failed = true;
    }
}
 
Example 7
Source File: LotsOfCancels.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Stress the given WatchService, specifically the cancel method, in
 * the given directory. Closes the WatchService when done.
 */
static void handle(int id, Path dir, WatchService watcher) {
    System.out.printf("begin handle %d%n", id);
    try {
        try {
            Path file = dir.resolve("anyfile");
            for (int i=0; i<2000; i++) {
                WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE);
                Files.createFile(file);
                Files.delete(file);
                key.cancel();
            }
        } finally {
            System.out.printf("WatchService %d closing ...%n", id);
            watcher.close();
            System.out.printf("WatchService %d closed %n", id);
        }
    } catch (Exception e) {
        e.printStackTrace();
        failed = true;
    }
    System.out.printf("end handle %d%n", id);
}
 
Example 8
Source File: PhotatoFilesManager.java    From Photato with GNU Affero General Public License v3.0 6 votes vote down vote up
private void manageDirectoryDeletion(Path filename) throws IOException {
    PhotatoFolder parentFolder = getCurrentFolder(filename.getParent());
    parentFolder.subFolders.remove(filename.getFileName().toString());
    WatchKey removed = watchedDirectoriesKeys.remove(filename);
    if (removed != null) {
        removed.cancel();
        watchedDirectoriesPaths.remove(removed);
    }

    PhotatoFolder currentFolder = getCurrentFolder(filename);
    if (currentFolder.medias != null) {
        for (PhotatoMedia media : currentFolder.medias) {
            try {
                searchManager.removeMedia(media);
                albumsManager.removeMedia(media);
                thumbnailGenerator.deleteThumbnail(media.fsPath, media.lastModificationTimestamp);
                fullScreenImageGetter.deleteImage(media);
            } catch (IOException ex) {
            }
        }
    }
}
 
Example 9
Source File: PathWatcherServiceImpl.java    From ProjectAres with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
protected void run() {
    while(isRunning()) {
        try {
            final WatchKey key = watchService.take();
            final WatchedDirectory watchedDirectory = dirsByKey.get(key);
            if(watchedDirectory == null) {
                logger.warning("Cancelling unknown key " + key);
                key.cancel();
            } else {
                for(WatchEvent<?> event : key.pollEvents()) {
                    watchedDirectory.dispatch((WatchEvent<Path>) event);
                }
                key.reset();
            }
        } catch(InterruptedException e) {
            // ignore, just check for termination
        }
    }
}
 
Example 10
Source File: LotsOfCancels.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Stress the given WatchService, specifically the cancel method, in
 * the given directory. Closes the WatchService when done.
 */
static void handle(Path dir, WatchService watcher) {
    try {
        try {
            Path file = dir.resolve("anyfile");
            for (int i=0; i<2000; i++) {
                WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE);
                Files.createFile(file);
                Files.delete(file);
                key.cancel();
            }
        } finally {
            watcher.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
        failed = true;
    }
}
 
Example 11
Source File: LotsOfCancels.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Stress the given WatchService, specifically the cancel method, in
 * the given directory. Closes the WatchService when done.
 */
static void handle(Path dir, WatchService watcher) {
    try {
        try {
            Path file = dir.resolve("anyfile");
            for (int i=0; i<2000; i++) {
                WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE);
                Files.createFile(file);
                Files.delete(file);
                key.cancel();
            }
        } finally {
            watcher.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
        failed = true;
    }
}
 
Example 12
Source File: DirectoryMonitor.java    From phoebus with Eclipse Public License 1.0 5 votes vote down vote up
/** @param dir Directory that received a change
 *  @param event Change within dir
 */
private void handle(final Path dir, final WatchEvent<?> event)
{
    final WatchEvent.Kind<?> kind = event.kind();

    // Not registered for this, but may happen anyway
    if (kind == OVERFLOW)
        return;

    @SuppressWarnings("unchecked")
    final WatchEvent<Path> ev = (WatchEvent<Path>)event;
    final Path filename = ev.context();
    final File file = dir.resolve(filename).toFile();

    if (kind == ENTRY_CREATE)
        listener.accept(file, Change.ADDED);
    else if (kind == ENTRY_MODIFY)
        listener.accept(file, Change.CHANGED);
    else if (kind == ENTRY_DELETE)
    {
        final WatchKey key = dir_keys.remove(file);
        if (key != null)
        {
            logger.log(Level.FINE, () -> "No longer monitoring removed directory " + file);
            key.cancel();
        }
        listener.accept(file, Change.REMOVED);
    }
    else
        logger.log(Level.WARNING, "Unexpected " + kind + " for " + file);
}
 
Example 13
Source File: InterpreterOutputChangeWatcher.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
public void clear() {
  synchronized (watchKeys) {
    for (WatchKey key : watchKeys.keySet()) {
      key.cancel();

    }
    watchKeys.clear();
    watchFiles.clear();
  }
}
 
Example 14
Source File: NioNotifier.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected void removeWatch(WatchKey key) throws IOException {
    try {
        key.cancel();
    } catch (ClosedWatchServiceException ex) {
        // This happens on shutdown as watcher service can be closed before
        // all watches are removed from it. It is safe to swallow this
        // exception here.
    }
}
 
Example 15
Source File: Watcher.java    From scelight with Apache License 2.0 5 votes vote down vote up
/**
 * Clears all previously registered watched folders.
 */
public void clear() {
	synchronized ( keyInfoMap ) {
		for ( final WatchKey key : keyInfoMap.keySet() )
			key.cancel();
		keyInfoMap.clear();
	}
}
 
Example 16
Source File: Drillbit.java    From Bats with Apache License 2.0 5 votes vote down vote up
private void pollShutdown(Drillbit drillbit) throws IOException, InterruptedException {
  final String drillHome = System.getenv("DRILL_HOME");
  final String gracefulFile = System.getenv("GRACEFUL_SIGFILE");
  final Path drillHomePath;
  if (drillHome == null || gracefulFile == null) {
    logger.warn("Cannot access graceful file. Graceful shutdown from command line will not be supported.");
    return;
  }
  try {
    drillHomePath = Paths.get(drillHome);
  } catch (InvalidPathException e) {
    logger.warn("Cannot access graceful file. Graceful shutdown from command line will not be supported.");
    return;
  }
  boolean triggered_shutdown = false;
  WatchKey wk = null;
  try (final WatchService watchService = drillHomePath.getFileSystem().newWatchService()) {
    drillHomePath.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_CREATE);
    while (!triggered_shutdown) {
      wk = watchService.take();
      for (WatchEvent<?> event : wk.pollEvents()) {
        final Path changed = (Path) event.context();
        if (changed != null && changed.endsWith(gracefulFile)) {
          drillbit.interruptPollShutdown = false;
          triggered_shutdown = true;
          drillbit.close();
          break;
        }
      }
    }
  } finally {
    if (wk != null) {
      wk.cancel();
    }
  }
}
 
Example 17
Source File: WatchServiceFileWatcher.java    From mirror with Apache License 2.0 5 votes vote down vote up
private void unwatchDirectory(WatchKey key, Path directory) {
  if (log.isTraceEnabled()) {
    log.trace("Removing " + key + " = " + directory);
  }
  pathToKey.remove(directory);
  keyToPath.remove(key);
  key.cancel();
}
 
Example 18
Source File: UnixSocketFile.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args)
    throws InterruptedException, IOException {

    // Use 'which' to verify that 'nc' is available and skip the test
    // if it is not.
    Process proc = Runtime.getRuntime().exec("which nc");
    InputStream stdout = proc.getInputStream();
    int b = stdout.read();
    proc.destroy();
    if (b == -1) {
        System.err.println("Netcat command unavailable; skipping test.");
        return;
    }

    // Create a new sub-directory of the nominal test directory in which
    // 'nc' will create the socket file.
    String testSubDir = System.getProperty("test.dir", ".")
        + File.separator + TEST_SUB_DIR;
    Path socketTestDir = Paths.get(testSubDir);
    Files.createDirectory(socketTestDir);

    // Set the path of the socket file.
    String socketFilePath = testSubDir + File.separator
        + SOCKET_FILE_NAME;

    // Create a process which executes the nc (netcat) utility to create
    // a socket file at the indicated location.
    FileSystem fs = FileSystems.getDefault();
    try (WatchService ws = fs.newWatchService()) {
        // Watch the test sub-directory to receive notification when an
        // entry, i.e., the socket file, is added to the sub-directory.
        WatchKey wk = socketTestDir.register(ws,
                StandardWatchEventKinds.ENTRY_CREATE);

        // Execute the 'nc' command.
        proc = Runtime.getRuntime().exec(CMD_BASE + " " + socketFilePath);

        // Wait until the socket file is created.
        WatchKey key = ws.take();
        if (key != wk) {
            throw new RuntimeException("Unknown entry created - expected: "
                + wk.watchable() + ", actual: " + key.watchable());
        }
        wk.cancel();
    }

    // Verify that the socket file in fact exists.
    Path socketPath = fs.getPath(socketFilePath);
    if (!Files.exists(socketPath)) {
        throw new RuntimeException("Socket file " + socketFilePath
            + " was not created by \"nc\" command.");
    }

    // Retrieve the most recent access and modification times of the
    // socket file; print the values.
    BasicFileAttributeView attributeView = Files.getFileAttributeView(
            socketPath, BasicFileAttributeView.class);
    BasicFileAttributes oldAttributes = attributeView.readAttributes();
    FileTime oldAccessTime = oldAttributes.lastAccessTime();
    FileTime oldModifiedTime = oldAttributes.lastModifiedTime();
    System.out.println("Old times: " + oldAccessTime
        + " " + oldModifiedTime);

    // Calculate the time to which the access and modification times of the
    // socket file will be changed.
    FileTime newFileTime =
        FileTime.fromMillis(oldAccessTime.toMillis() + 1066);

    try {
        // Set the access and modification times of the socket file.
        attributeView.setTimes(newFileTime, newFileTime, null);

        // Retrieve the updated access and modification times of the
        // socket file; print the values.
        FileTime newAccessTime = null;
        FileTime newModifiedTime = null;
        BasicFileAttributes newAttributes = attributeView.readAttributes();
        newAccessTime = newAttributes.lastAccessTime();
        newModifiedTime = newAttributes.lastModifiedTime();
        System.out.println("New times: " + newAccessTime + " "
            + newModifiedTime);

        // Verify that the updated times have the expected values.
        if ((newAccessTime != null && !newAccessTime.equals(newFileTime))
            || (newModifiedTime != null
                && !newModifiedTime.equals(newFileTime))) {
            throw new RuntimeException("Failed to set correct times.");
        }
    } finally {
        // Destry the process running netcat and delete the socket file.
        proc.destroy();
        Files.delete(socketPath);
    }
}
 
Example 19
Source File: MultipleFilesWatcher.java    From pgptool with GNU General Public License v3.0 4 votes vote down vote up
private Thread buildThreadAndStart() {
	Thread ret = new Thread("FilesWatcher-" + watcherName) {
		@Override
		public void run() {
			log.debug("FileWatcher thread started " + watcherName);
			boolean continueWatching = true;
			while (continueWatching) {
				WatchKey key;
				try {
					idleIfNoKeysRegistered();
					key = watcher.take();
					// NOTE: Since we're watching only one folder we assume
					// that there will be only one key for our folder
				} catch (ClosedWatchServiceException cwe) {
					log.error("ClosedWatchServiceException fired, stoppign thread.", cwe);
					return;
				} catch (InterruptedException x) {
					log.debug("FileWatcher thread stopped by InterruptedException");
					return;
				} catch (Throwable t) {
					log.error("Unexpected exception while checking for updates on watched file", t);
					return;
				}

				BaseFolder baseFolder = null;
				synchronized (watcherName) {
					baseFolder = keys.get(key);
				}
				if (baseFolder == null) {
					key.cancel();
					continue;
				}

				for (WatchEvent<?> event : key.pollEvents()) {
					// Context for directory entry event is the file name of
					// entry
					WatchEvent<Path> ev = cast(event);
					Path name = ev.context();
					Path child = baseFolder.path.resolve(name);
					String relativeFilename = FilenameUtils.getName(child.toString());
					if (!baseFolder.interestedFiles.contains(relativeFilename)
							&& !event.kind().equals(ENTRY_CREATE)) {
						continue;
					}

					// print out event
					log.debug("Watcher event: " + event.kind().name() + ", file " + child);
					dirWatcherHandler.handleFileChanged(event.kind(), child.toString());
				}

				// reset key and remove from set if directory no longer
				// accessible
				boolean valid = key.reset();
				if (!valid) {
					synchronized (watcherName) {
						keys.remove(key);
						baseFolders.remove(baseFolder.folder);
					}
				}
			}
			log.debug("FileWatcher thread stopped " + watcherName);
		}

		private void idleIfNoKeysRegistered() throws InterruptedException {
			while (true) {
				synchronized (watcherName) {
					if (!keys.isEmpty()) {
						break;
					}
				}
				Thread.sleep(500);
			}
		};
	};
	ret.start();
	return ret;
}
 
Example 20
Source File: FolderWatchService.java    From PeerWasp with MIT License 4 votes vote down vote up
private synchronized void unregisterFolder(WatchKey folderKey) {
	folderKey.cancel();
	Path folder = watchKeyToPath.remove(folderKey);
	logger.info("Unregister folder: {}", folder);
}