Java Code Examples for java.nio.file.Path#register()

The following examples show how to use java.nio.file.Path#register() . These examples are extracted from open source projects. 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
/**
 * Instantiates a new file system watcher.
 *
 * @param parent the parent
 * @param path the path
 */
public void addWatch(FileWatcherUpdateInterface parent, Path path) {
    if (path != null) {
        // The directory that has to be watched needs to be registered. Any
        // object that implements the Watchable interface can be registered.

        // Register three events. i.e. whenever a file is created, deleted or
        // modified the watcher gets informed
        try {
            WatchKey key =
                    path.register(
                            watchService,
                            StandardWatchEventKinds.ENTRY_CREATE,
                            StandardWatchEventKinds.ENTRY_DELETE,
                            StandardWatchEventKinds.ENTRY_MODIFY);
            watcherMap.put(key, parent);
        } catch (IOException e) {
            // Do nothing
        }
    }
}
 
Example 2
/**
 * Register the given directory with the WatchService
 */
public void register(Path dir) throws IOException {
  if (!enable)
    return;

  WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
  if (trace) {
    Path prev = keys.get(key);
    if (prev == null) {
      System.out.format("CatalogWatcher register: %s%n", dir);
    } else {
      if (!dir.equals(prev)) {
        System.out.format("update: %s -> %s%n", prev, dir);
      }
    }
  }
  keys.put(key, dir);
}
 
Example 3
/**
 * 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 4
public ExternalDatabaseLookupService(final Path location) throws IOException {
    final Path absoluteLocation = location.toAbsolutePath();
    final Path locationParent = absoluteLocation.getParent();
    if (null == locationParent) {
        throw new IllegalArgumentException("Could not determine parent directory of GeoIP2 database: " + absoluteLocation);
    }
    this.location = absoluteLocation;
    // Do this first, so that if it fails we don't need to clean up resources.
    databaseLookupService = new AtomicReference<>(new DatabaseLookupService(absoluteLocation));

    // Set things up so that we can reload the database if it changes.
    watcher = FileSystems.getDefault().newWatchService();
    logger.debug("Monitoring {} for changes affecting {}.", locationParent, location);
    locationParent.register(watcher, StandardWatchEventKinds.ENTRY_MODIFY);
    // The database will be loaded in the background.
    backgroundWatcher.execute(this::processWatchEvents);
}
 
Example 5
public AuthHeaderStrategyMount() {
  try {
    Path p = Paths.get(DEFAULT_SECRET_AUTH_PATH);
    if (!p.toFile().exists()) {
      return;
    }
    WatchService watchService = FileSystems.getDefault().newWatchService();
    p.register(watchService,
        StandardWatchEventKinds.ENTRY_MODIFY,
        StandardWatchEventKinds.ENTRY_CREATE);
    executor.execute(new FileUpdateCheckThread(watchService));
  } catch (Exception e) {
    LOGGER.warn("get watch service failed.", e);
  }
}
 
Example 6
/**
 * Returns a task that updates the registration of a directory with
 * a WatchService.
 */
static Callable<Boolean> newRegisterTask(WatchService watcher, Path dir) {
    return () -> {
        try {
            dir.register(watcher, StandardWatchEventKinds.ENTRY_DELETE);
            return true;
        } catch (ClosedWatchServiceException e) {
            return false;
        } catch (IOException ioe) {
            throw new UncheckedIOException(ioe);
        }
    };
}
 
Example 7
Source Project: Bats   File: Drillbit.java    License: 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 8
Source Project: haxademic   File: WatchDir.java    License: MIT License 5 votes vote down vote up
/**
 * Register the given directory with the WatchService
 */
private void register(Path dir) throws IOException {
	WatchKey key = dir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);
	if (trace) {
		Path prev = keys.get(key);
		if (prev == null) {
			if(DEBUG) System.out.format("register: %s\n", dir);
		} else {
			if (!dir.equals(prev)) {
				if(DEBUG) System.out.format("update: %s -> %s\n", prev, dir);
			}
		}
	}
	keys.put(key, dir);
}
 
Example 9
Source Project: PeerWasp   File: FolderWatchService.java    License: MIT License 5 votes vote down vote up
private synchronized void registerFolder(final Path folder) throws IOException {
	// FIXME: containsValue has bad performance in case of many folders.
	// maybe bidirectional (e.g. BiMap from Guava) map would be an option.
	if (!watchKeyToPath.containsValue(folder)) {
		logger.info("Register folder: {}", folder);
		WatchKey key = folder.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY, OVERFLOW);
		watchKeyToPath.put(key, folder);
	}
}
 
Example 10
Source Project: mangooio   File: Watcher.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("all")
private void register(Path path) throws IOException {
    WatchKey watchKey = path.register(
            watchService,
            new WatchEvent.Kind[]{
                    StandardWatchEventKinds.ENTRY_CREATE,
                    StandardWatchEventKinds.ENTRY_MODIFY,
                    StandardWatchEventKinds.ENTRY_DELETE
            });

    watchKeys.put(watchKey, path);
}
 
Example 11
Source Project: nifi   File: NarAutoLoader.java    License: Apache License 2.0 5 votes vote down vote up
public synchronized void start() throws IOException {
    if (started) {
        return;
    }

    FileUtils.ensureDirectoryExistAndCanReadAndWrite(autoLoadDir);

    final WatchService watcher = FileSystems.getDefault().newWatchService();

    final Path autoLoadPath = autoLoadDir.toPath();
    autoLoadPath.register(watcher, StandardWatchEventKinds.ENTRY_CREATE);

    narAutoLoaderTask = new NarAutoLoaderTask.Builder()
            .autoLoadPath(autoLoadPath)
            .watchService(watcher)
            .pollIntervalMillis(POLL_INTERVAL_MS)
            .narLoader(narLoader)
            .build();

    LOGGER.info("Starting NAR Auto-Loader for directory {} ...", new Object[]{autoLoadPath});

    final Thread thread = new Thread(narAutoLoaderTask);
    thread.setName("NAR Auto-Loader");
    thread.setDaemon(true);
    thread.start();

    LOGGER.info("NAR Auto-Loader started");
    started = true;
}
 
Example 12
Source Project: baleen   File: CsvFolderReader.java    License: Apache License 2.0 5 votes vote down vote up
private void registerDirectory(Path path) throws IOException {
  WatchKey key;
  if (reprocessOnModify) {
    key = path.register(watcher, ENTRY_CREATE, ENTRY_MODIFY, ENTRY_DELETE);
  } else {
    key = path.register(watcher, ENTRY_CREATE, ENTRY_DELETE);
  }

  watchKeys.put(key, path);

  getMonitor().counter("directories").inc();
}
 
Example 13
private void manageDirectoryCreation(Path filename) throws IOException {
    PhotatoFolder newFolder = new PhotatoFolder(rootFolder.fsPath, filename);
    PhotatoFolder parentFolder = getCurrentFolder(filename.getParent());

    parentFolder.subFolders.put(filename.getFileName().toString(), newFolder);

    WatchKey key = filename.register(watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE);
    watchedDirectoriesKeys.put(filename, key);
    watchedDirectoriesPaths.put(key, filename);

    runInitialFolderExploration(watcher, newFolder);
}
 
Example 14
/**
 * 监听指定路径的修改事件
 * @param path
 * @return
 */
public static WatchService watch(String path, WatchEvent.Kind kind){
    WatchService watchService = null;
    try {
        watchService = FileSystems.getDefault().newWatchService();
        Path dir = FileSystems.getDefault().getPath(path);
        dir.register(watchService, kind);
    } catch (IOException e) {
        log.error("{}监听异常",path,e);
    }
    return watchService;
}
 
Example 15
synchronized void registerWatcher() {
    try {
        if (watchKey != null) {
            watchKey.cancel();
            watchKey = null;
        }
        
        Path dir = Paths.get(path);
        watchKey = dir.register(watcher, java.nio.file.StandardWatchEventKinds.ENTRY_CREATE, java.nio.file.StandardWatchEventKinds.ENTRY_DELETE, java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY);

    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}
 
Example 16
public AbstractMergeWatcher ( Path path, final long delay, final TimeUnit timeUnit ) throws IOException
{
    this.path = path;
    this.delay = delay;
    this.timeUnit = timeUnit;

    if ( !Files.exists ( path ) )
    {
        throw new IllegalArgumentException ( String.format ( "Failed to watch: %s. Path does not exists.", path ) );
    }

    this.ws = path.getFileSystem ().newWatchService ();

    if ( Files.isRegularFile ( path ) )
    {
        path = path.getParent ();
        logger.debug ( "Watching parent directory: {}", path );
        path.register ( this.ws, ENTRY_CREATE, ENTRY_MODIFY, ENTRY_DELETE );
        this.watchFile = true;
    }
    else
    {
        logger.debug ( "Watching directory: {}", path );
        path.register ( this.ws, ENTRY_CREATE, ENTRY_MODIFY, ENTRY_DELETE );
        this.watchFile = false;
    }

    this.watchPath = path;

    this.runner = new Thread () {
        @Override
        public void run ()
        {
            try
            {
                logger.info ( "Starting scanner thread" );
                scanner ();
            }
            finally
            {
                logger.info ( "Exiting scanner thread" );
            }
        }
    };
    this.runner.start ();

    this.executor = ScheduledExportedExecutorService.newSingleThreadExportedScheduledExecutor ( "org.eclipse.scada.ca.updater/MergeWatcher" );
}
 
Example 17
public void watchTray(Path path) throws IOException, InterruptedException {
    try (WatchService watchService = FileSystems.getDefault().newWatchService()) {
        path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE,
                StandardWatchEventKinds.ENTRY_DELETE);

        System.out.println("Printer watcher ready ...");
        
        //start an infinite loop
        while (true) {

            //retrieve and remove the next watch key
            final WatchKey key = watchService.poll(10, TimeUnit.SECONDS);

            //get list of events for the watch key
            if (key != null) {
                for (WatchEvent<?> watchEvent : key.pollEvents()) {

                    //get the filename for the event
                    final WatchEvent<Path> watchEventPath = (WatchEvent<Path>) watchEvent;
                    final Path filename = watchEventPath.context();

                    //get the kind of event (create, modify, delete)
                    final Kind<?> kind = watchEvent.kind();

                    //handle OVERFLOW event
                    if (kind == StandardWatchEventKinds.OVERFLOW) {
                        continue;
                    }

                    if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
                        System.out.println("Sending the document to print -> " + filename);

                        Runnable task = new Printer(path.resolve(filename));
                        Thread worker = new Thread(task);

                        //we can set the name of the thread			
                        worker.setName(path.resolve(filename).toString());

                        //store the thread and the path
                        threads.put(worker, path.resolve(filename));

                        //start the thread
                        worker.start();
                    }

                    if (kind == StandardWatchEventKinds.ENTRY_DELETE) {
                        System.out.println(filename + " was successfully printed!");
                    }
                }

                //reset the key
                boolean valid = key.reset();

                //exit loop if the key is not valid (if the directory was deleted, per example)
                if (!valid) {
                    threads.clear();
                    break;
                }
            }

            if (!threads.isEmpty()) {
                for (Iterator<Map.Entry<Thread, Path>> it = 
                        threads.entrySet().iterator(); it.hasNext();) {
                    Map.Entry<Thread, Path> entry = it.next();
                    if (entry.getKey().getState() == Thread.State.TERMINATED) {
                        Files.deleteIfExists(entry.getValue());
                        it.remove();
                    }
                }
            }
        }
    }
}
 
Example 18
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
/** Add a watch for the directory, then add the files found inside of it */
private void addDirectory(Path path, List<File> filesFound) throws IOException {

	if (watchedPaths.containsKey(path)) {
		return;
	}

	String normalizedPath = PathUtils.normalizePath(path.toFile().getPath());

	String relativePath = PathUtils
			.convertAbsolutePathWithUnixSeparatorsToProjectRelativePath(normalizedPath, pathInNormalizedForm)
			.orElse(null);

	if (relativePath != null) {
		if (pathFilter.isFilteredOutByFilename(relativePath)) {
			log.logDebug("Filtering out " + path + " due to filename");
			return;
		} else if (pathFilter.isFilteredOutByPath(relativePath)) {
			log.logDebug("Filtering out " + path + " due to path.");
			return;
		}
	}

	watchedPaths.put(path, true);

	WatchKey key = path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE,
			StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE);

	keys.put(key, path);

	// Any files found in the directory should also be reported as created.
	File[] farr = path.toFile().listFiles();
	if (farr == null) {
		log.logDebug("Added directory: " + path + " files found: " + farr + " " + path.toFile().exists());
		return;
	}

	for (File f : farr) {
		filesFound.add(f);
		if (f.isDirectory()) {
			addDirectory(f.toPath(), filesFound);
		}
	}

	log.logDebug("Added directory: " + path + " files found: " + farr.length);

}
 
Example 20
public void testMultipleEntryCreate() throws IOException, InterruptedException, StfException {
	Path tempDirectory = getTemporaryDirectory();
	WatchService watchService = FileSystems.getDefault().newWatchService();
	try {
		tempDirectory.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);
		WatchKey key = null;
		for (int iteration = 0; iteration < 10; iteration++) {
			HangNotifier.ping();
			Path newFilename = Paths.get("ENTRY_CREATE" + iteration + ".txt");
			Path newFile = tempDirectory.resolve(newFilename);
			Files.createFile(newFile);
			assertTrue("File was not created", Files.exists(newFile));

			key = null;

			// We will give it POLL_TIMEOUT_SECONDS seconds, if it hasn't got something by
			// then we assume failure

			key = watchService.poll(POLL_TIMEOUT_SECONDS, TimeUnit.SECONDS);
			assertNotNull("Polling WatchService object returned null", key);
			
			boolean eventFound = false;

			// Check for exactly one event
			for (WatchEvent<?> event : key.pollEvents()) {
				if (event.kind().equals(StandardWatchEventKinds.ENTRY_CREATE)) {
					// Assert exactly one event
					assertFalse("Duplicate ENTRY_CREATE events delivered for one file creation", eventFound);
					// Assert filename is correct
					assertEquals(newFilename, (Path) event.context());
					eventFound = true;
				} else {
					fail(event.kind() + " event retured, expected ENTRY_CREATE");
				}
			}

			// Reset the key, to allow for future events
			if (key != null) {
				key.reset();
			}
		}
	} finally {
		watchService.close();
	}
	okForCleanup();
}