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

The following examples show how to use java.nio.file.WatchKey#pollEvents() . 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: FileChangedWatcher.java    From karate with MIT License 6 votes vote down vote up
public void watch() throws InterruptedException, IOException {
    try {
        final Path directoryPath = file.toPath().getParent();
        final WatchService watchService = FileSystems.getDefault().newWatchService();
        directoryPath.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);
        while (true) {
            final WatchKey wk = watchService.take();
            for (WatchEvent<?> event : wk.pollEvents()) {
                final Path fileChangedPath = (Path) event.context();
                if (fileChangedPath.endsWith(file.getName())) {
                    onModified();
                }
            }
            wk.reset();
        }
    } catch (Exception e) {
        logger.error("exception when handling change of mock file: {}", e.getMessage());
    }
}
 
Example 2
Source File: PluginPropertiesWatcher.java    From SuitAgent with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    WatchService watchService = WatchServiceUtil.watchModify(pluginDir);
    WatchKey key;
    while (watchService != null){
        try {
            key = watchService.take();
            for (WatchEvent<?> watchEvent : key.pollEvents()) {
                if(watchEvent.kind() == ENTRY_MODIFY){
                    String fileName = watchEvent.context() == null ? "" : watchEvent.context().toString();
                    Plugin plugin = PluginLibraryHelper.getPluginByConfigFileName(fileName);
                    if(plugin != null){
                        plugin.init(PluginLibraryHelper.getPluginConfig(plugin));
                        log.info("已完成插件{}的配置重新加载",plugin.pluginName());
                    }
                }
            }
            key.reset();
        } catch (Exception e) {
            log.error("插件配置文件监听异常",e);
            break;
        }
    }
}
 
Example 3
Source File: FileMonitorJdkImpl.java    From util4j with Apache License 2.0 6 votes vote down vote up
public void simpleTest(Path path) throws Exception
{
	WatchService watchService=FileSystems.getDefault().newWatchService();  
	path.register(watchService,   
            StandardWatchEventKinds.ENTRY_CREATE,  
            StandardWatchEventKinds.ENTRY_DELETE,  
            StandardWatchEventKinds.ENTRY_MODIFY);  
    while(true)  
    {  
        WatchKey watchKey=watchService.take();  
           List<WatchEvent<?>> watchEvents = watchKey.pollEvents();  
           for(WatchEvent<?> event : watchEvents){  
               //TODO 根据事件类型采取不同的操作。。。。。。。  
               System.out.println("["+event.context()+"]文件发生了["+event.kind()+"]事件");    
           }  
           watchKey.reset(); 
    } 
}
 
Example 4
Source File: AbstractFileTransformationService.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Ensures that a modified or deleted cached files does not stay in the cache
 */
private void processFolderEvents(final WatchService watchService) {
    WatchKey key = watchService.poll();
    if (key != null) {
        for (WatchEvent<?> e : key.pollEvents()) {
            if (e.kind() == OVERFLOW) {
                continue;
            }

            // Context for directory entry event is the file name of entry
            @SuppressWarnings("unchecked")
            WatchEvent<Path> ev = (WatchEvent<Path>) e;
            Path path = ev.context();

            logger.debug("Refreshing transformation file '{}'", path);

            for (String fileEntry : cachedFiles.keySet()) {
                if (fileEntry.endsWith(path.toString())) {
                    cachedFiles.remove(fileEntry);
                }
            }
        }
        key.reset();
    }
}
 
Example 5
Source File: DefaultCertificateValidator.java    From opc-ua-stack with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    while (true) {
        try {
            WatchKey key = watchService.take();

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

                    if (kind != StandardWatchEventKinds.OVERFLOW) {
                        synchronizeTrustedCertificates();
                    }
                }
            }

            if (!key.reset()) {
                break;
            }
        } catch (InterruptedException e) {
            logger.error("Watcher interrupted.", e);
        }
    }
}
 
Example 6
Source File: FileWatcher.java    From jfilter with Apache License 2.0 6 votes vote down vote up
/**
 * Process all modify events
 *
 * @throws InterruptedException if interrupted while waiting
 */
@SuppressWarnings("unchecked")
private void processModifiedFiles() throws InterruptedException {
    WatchKey key = watcher.take();
    for (WatchEvent<?> event : key.pollEvents()) {
        WatchEvent.Kind<?> kind = event.kind();


        if (kind == StandardWatchEventKinds.OVERFLOW) {
            overflowed = true;
            continue;
        }

        if (watchKeys.containsKey(key)) {
            WatchEvent<Path> ev = (WatchEvent<Path>) event;

            String filename = String.format("%s%s%s", watchKeys.get(key).toString(),
                    File.separator, ev.context().toString());
            File file = new File(filename);

            if (fileIsModified(file))
                fileRecords.get(file).onEvent();
        }
    }
    key.reset();
}
 
Example 7
Source File: GrpcServer.java    From glowroot with Apache License 2.0 5 votes vote down vote up
private static boolean certificateModified(WatchKey watchKey) {
    for (WatchEvent<?> event : watchKey.pollEvents()) {
        Object context = event.context();
        if (context instanceof Path) {
            String fileName = ((Path) context).toString();
            if (fileName.equals("grpc-cert.pem") || fileName.equals("cert.pem")
                    || fileName.equals("grpc-key.pem") || fileName.equals("key.pem")) {
                return true;
            }
        }
    }
    return false;
}
 
Example 8
Source File: CostFedSummaryProvider.java    From CostFed with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void run() {
    for (;;) {
        WatchKey key;
        try {
            key = watcher.take();
        } catch (InterruptedException x) {
            return;
        }
        
        for (WatchEvent<?> event: key.pollEvents()) {
            WatchEvent.Kind<?> kind = event.kind();
            if (kind == java.nio.file.StandardWatchEventKinds.OVERFLOW) {
                continue;
            }
            
            if (kind == java.nio.file.StandardWatchEventKinds.ENTRY_CREATE || kind == java.nio.file.StandardWatchEventKinds.ENTRY_DELETE || kind == java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY) {
                rebuildSummary();
            }
        }
        
        boolean valid = key.reset();
        if (!valid) {
            break;
        }
    }
}
 
Example 9
Source File: PollingWatchServiceTest.java    From jimfs with Apache License 2.0 5 votes vote down vote up
private void assertWatcherHasEvents(List<WatchEvent<?>> expected, List<WatchEvent<?>> alternate)
    throws InterruptedException {
  ensureTimeToPoll(); // otherwise we could read 1 event but not all the events we're expecting
  WatchKey key = watcher.take();
  List<WatchEvent<?>> keyEvents = key.pollEvents();

  if (keyEvents.size() == expected.size() || alternate.isEmpty()) {
    assertThat(keyEvents).containsExactlyElementsIn(expected);
  } else {
    assertThat(keyEvents).containsExactlyElementsIn(alternate);
  }
  key.reset();
}
 
Example 10
Source File: ErrorWatcher.java    From weMessage with GNU Affero General Public License v3.0 5 votes vote down vote up
public void run(){
    isRunning.set(true);

    clearErroredFiles();

    try (final WatchService watchService = FileSystems.getDefault().newWatchService()) {
        final WatchKey watchKey = FileSystems.getDefault().getPath(serverConfiguration.getParentDirectoryPath()).register(watchService, new WatchEvent.Kind[]{StandardWatchEventKinds.ENTRY_CREATE}, SensitivityWatchEventModifier.HIGH);

        while (isRunning.get()) {
            final WatchKey wk = watchService.take();

            for (WatchEvent<?> event : wk.pollEvents()) {
                final Path changed = (Path) event.context();

                if (changed.toFile().getName().startsWith(SCRIPT_ERROR_FILE_PREFIX)) {
                    processError(ErrorFileType.SCRIPT, changed.toFile());
                }
            }
            boolean valid = wk.reset();
            if (!valid) {
                ServerLogger.log(ServerLogger.Level.INFO, TAG, "The watcher key has been unregistered");
            }
        }
    }catch(Exception ex){
        if (isRunning.get()) {
            ServerLogger.error(TAG, "An error occurred while watching for errors. Shutting down!", ex);
            messageServer.shutdown(-1, false);
        }
    }
}
 
Example 11
Source File: AbstractNIO2Watcher.java    From HotswapAgent with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Process all events for keys queued to the watcher
 *
 * @return true if should continue
 * @throws InterruptedException
 */
private boolean processEvents() throws InterruptedException {

    // wait for key to be signaled
    WatchKey key = watcher.poll(10, TimeUnit.MILLISECONDS);
    if (key == null) {
        return true;
    }

    Path dir = keys.get(key);

    if (dir == null) {
        LOGGER.warning("WatchKey '{}' not recognized", key);
        return true;
    }

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

        if (kind == OVERFLOW) {
            LOGGER.warning("WatchKey '{}' overflowed", key);
            continue;
        }

        // Context for directory entry event is the file name of entry
        WatchEvent<Path> ev = cast(event);
        Path name = ev.context();
        Path child = dir.resolve(name);

        LOGGER.debug("Watch event '{}' on '{}' --> {}", event.kind().name(), child, name);

        dispatcher.add(ev, child);

        // if directory is created, and watching recursively, then
        // register it and its sub-directories
        if (kind == ENTRY_CREATE) {
            try {
                if (Files.isDirectory(child, NOFOLLOW_LINKS)) {
                    registerAll(child);
                }
            } catch (IOException x) {
                LOGGER.warning("Unable to register events for directory {}", x, child);
            }
        }
    }

    // reset key and remove from set if directory no longer accessible
    boolean valid = key.reset();
    if (!valid) {
        LOGGER.warning("Watcher on {} not valid, removing path=", keys.get(key));
        keys.remove(key);
        // all directories are inaccessible
        if (keys.isEmpty()) {
            return false;
        }
        if (classLoaderListeners.isEmpty()) {
            for (WatchKey k : keys.keySet()) {
                k.cancel();
            }
            return false;
        }
    }
    return true;
}
 
Example 12
Source File: Watcher.java    From marathonv5 with Apache License 2.0 4 votes vote down vote up
@Override
public void run() {

    for (;;) {
        // wait for key to be signalled
        WatchKey key;
        try {
            key = watchService.take();
        } catch (Exception x) {
            return;
        }

        FolderResource dir = monitored.get(key);
        if (dir == null) {
            System.err.println("WatchKey not recognized!!");
            continue;
        }

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

            // TBD - provide example of how OVERFLOW event is handled
            if (kind == OVERFLOW) {
                // TODO: inform overflow handler
                continue;
            }

            @SuppressWarnings("unchecked")
            WatchEvent<Path> ev = (WatchEvent<Path>) event;
            Path name = ev.context();

            // if directory is created, and watching recursively, then
            // register it and its sub-directories
            if (kind == ENTRY_CREATE) {
                Platform.runLater(() -> dir.create(name));
            }
            if (kind == ENTRY_DELETE) {
                Platform.runLater(() -> dir.delete(name));
            }
            if (kind == ENTRY_MODIFY) {
            }
        }

        boolean valid = key.reset();
        if (!valid) {
            monitored.remove(key);

            if (monitored.isEmpty()) {
                break;
            }
        }
    }
}
 
Example 13
Source File: FileMonitorJdkImpl.java    From util4j with Apache License 2.0 4 votes vote down vote up
public void watchRNDir(Path path) throws IOException, InterruptedException {  
    try (WatchService watchService = FileSystems.getDefault().newWatchService()) {  
        //给path路径加上文件观察服务  
        path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE,  
                StandardWatchEventKinds.ENTRY_MODIFY,  
                StandardWatchEventKinds.ENTRY_DELETE);  
        // start an infinite loop  
        while (true) {  
            // retrieve and remove the next watch key  
            final WatchKey key = watchService.take();  
            // get list of pending events for the watch key  
            for (WatchEvent<?> watchEvent : key.pollEvents()) {  
                // 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){  
                      
                }  
                //修改事件  
                if(kind == StandardWatchEventKinds.ENTRY_MODIFY){  
                      
                }  
                //删除事件  
                if(kind == StandardWatchEventKinds.ENTRY_DELETE){  
                      
                }  
                // get the filename for the event  
                @SuppressWarnings("unchecked")
	final WatchEvent<Path> watchEventPath = (WatchEvent<Path>) watchEvent;  
                final Path filename = watchEventPath.context();  
                // print it out  
                System.out.println(kind + " -> " + filename);  
  
            }  
            // reset the keyf  
            boolean valid = key.reset();  
            // exit loop if the key is not valid (if the directory was  
            // deleted, for  
            if (!valid) {  
                break;  
            }  
        }  
    }  
}
 
Example 14
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 15
Source File: BeatmapWatchService.java    From opsu with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Process all events for keys queued to the watcher
 */
private void processEvents() {
	while (true) {
		// wait for key to be signaled
		WatchKey key;
		try {
			key = watcher.take();
		} catch (InterruptedException | ClosedWatchServiceException e) {
			return;
		}

		Path dir = keys.get(key);
		if (dir == null)
			continue;

		boolean isPaused = paused;
		for (WatchEvent<?> event : key.pollEvents()) {
			WatchEvent.Kind<?> kind = event.kind();
			if (kind == StandardWatchEventKinds.OVERFLOW)
				continue;

			// context for directory entry event is the file name of entry
			WatchEvent<Path> ev = cast(event);
			Path name = ev.context();
			Path child = dir.resolve(name);
			//System.out.printf("%s: %s\n", kind.name(), child);

			// fire listeners
			if (!isPaused) {
				for (BeatmapWatchServiceListener listener : listeners)
					listener.eventReceived(kind, child);
			}

			// if directory is created, then register it and its sub-directories
			if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
				if (Files.isDirectory(child, LinkOption.NOFOLLOW_LINKS))
					registerAll(child);
			}
		}

		// reset key and remove from set if directory no longer accessible
		if (!key.reset()) {
			keys.remove(key);
			if (keys.isEmpty())
				break;  // all directories are inaccessible
		}
	}
}
 
Example 16
Source File: BaseWatcher.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
private void checkKey ( final WatchKey key ) throws IOException
{
    if ( this.baseKey == key )
    {
        checkBaseEvents ( key, key.pollEvents () );
        if ( !this.baseKey.reset () )
        {
            logger.warn ( "Base key got invalidated" );
            this.watcher.close ();
        }
    }
    else
    {
        final Path base = (Path)key.watchable ();

        if ( ! ( key.watchable () instanceof Path ) )
        {
            // don't reset
            return;
        }

        final StorageWatcher w = this.watcherMap.get ( base );
        if ( w == null )
        {
            logger.info ( "Event for unknown target: {}", base );
            // don't reset
            return;
        }
        try
        {
            for ( final WatchEvent<?> event : key.pollEvents () )
            {
                if ( ! ( event.context () instanceof Path ) )
                {
                    continue;
                }

                w.handleEvent ( (Path)key.watchable (), event );
            }
        }
        finally
        {
            if ( !key.reset () )
            {
                w.dispose ();
            }
        }
    }
}
 
Example 17
Source File: MainWatch.java    From DiscordSoundboard with Apache License 2.0 4 votes vote down vote up
@Async
@SuppressWarnings("unchecked")
public void watchDirectoryPath(Path path) {
    // Sanity check - Check if path is a folder
    try {
        Boolean isFolder = (Boolean) Files.getAttribute(path,
                "basic:isDirectory", NOFOLLOW_LINKS);
        if (!isFolder) {
            throw new IllegalArgumentException("Path: " + path + " is not a folder");
        }
    } catch (IOException e) {
        // Folder does not exists
        e.printStackTrace();
    }

    System.out.println("Watching path: " + path);

    // We obtain the file system of the Path
    FileSystem fs = path.getFileSystem ();

    // We create the new WatchService using the new try() block
    try(WatchService service = fs.newWatchService()) {

        // We register the path to the service
        // We watch for creation events
        path.register(service, ENTRY_CREATE, ENTRY_MODIFY, ENTRY_DELETE);

        // Start the infinite polling loop
        WatchKey key;
        while(true) {
            key = service.take();

            // Dequeueing events
            Kind<?> kind;
            for(WatchEvent<?> watchEvent : key.pollEvents()) {
                // Get the type of the event
                kind = watchEvent.kind();
                if (kind == ENTRY_CREATE || kind == ENTRY_DELETE || kind == ENTRY_MODIFY) {
                    // A new Path was created 
                    Path newPath = ((WatchEvent<Path>) watchEvent).context();
                    // Output
                    //Mark the observable object as changed.
                    this.setChanged();
                    System.out.println("New path created: " + newPath + " kind of operation: " + kind);
                    
                    notifyObservers(this);
                }
            }

            if(!key.reset()) {
                break; //loop
            }
        }
    } catch(IOException | InterruptedException ioe) {
        ioe.printStackTrace();
    }
}
 
Example 18
Source File: FileSystemWatchingService.java    From ariADDna with Apache License 2.0 4 votes vote down vote up
/**
 * Process all events for keys queued to the watcher
 */
public void processEvents() {
    while (isAlive) {

        // wait for key to be signalled
        //multiple events packed into key
        WatchKey key;
        try {
            key = watcher.poll(50, TimeUnit.MILLISECONDS);
        } catch (InterruptedException x) {
            LOGGER.trace("processEvent was interrupted and service stopped with message: {}",
                    x.getMessage());
            return;
        }

        //Get the path associated with the key
        Path dir = keys.get(key);
        if (dir == null) {
            continue;
        }

        //get the events list
        List<WatchEvent<?>> events = key.pollEvents();

        //create pair with path and events
        Pair<Path, List<WatchEvent<?>>> eventsSet = new Pair<>(dir, events);

        //add pair to the shared with Consumer queue
        queue.add(eventsSet);

        // reset key and remove from set if directory no longer accessible
        boolean valid = key.reset();
        if (!valid) {
            keys.remove(key);

            // all directories are inaccessible
            if (keys.isEmpty()) {
                break;
            }
        }

    }
}
 
Example 19
Source File: BeatmapWatchService.java    From opsu-dance with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Process all events for keys queued to the watcher
 */
private void processEvents() {
	while (true) {
		// wait for key to be signaled
		WatchKey key;
		try {
			key = watcher.take();
		} catch (InterruptedException | ClosedWatchServiceException e) {
			return;
		}

		Path dir = keys.get(key);
		if (dir == null)
			continue;

		boolean isPaused = paused;
		for (WatchEvent<?> event : key.pollEvents()) {
			WatchEvent.Kind<?> kind = event.kind();
			if (kind == StandardWatchEventKinds.OVERFLOW)
				continue;

			// context for directory entry event is the file name of entry
			WatchEvent<Path> ev = cast(event);
			Path name = ev.context();
			Path child = dir.resolve(name);
			//System.out.printf("%s: %s\n", kind.name(), child);

			// fire listeners
			if (!isPaused) {
				for (BeatmapWatchServiceListener listener : listeners)
					listener.eventReceived(kind, child);
			}

			// if directory is created, then register it and its sub-directories
			if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
				if (Files.isDirectory(child, LinkOption.NOFOLLOW_LINKS))
					registerAll(child);
			}
		}

		// reset key and remove from set if directory no longer accessible
		if (!key.reset()) {
			keys.remove(key);
			if (keys.isEmpty())
				break;  // all directories are inaccessible
		}
	}
}
 
Example 20
Source File: CamelSinkFileITCase.java    From camel-kafka-connector with Apache License 2.0 4 votes vote down vote up
private void waitForFile(File sinkFile, File doneFile) throws IOException, InterruptedException {
    WatchService watchService = FileSystems.getDefault().newWatchService();
    Path path = sinkFile.getParentFile().toPath();

    if (doneFile.exists()) {
        return;
    }

    // We watch for both the file creation and truncation
    path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY);

    int retries = 30;
    do {
        WatchKey watchKey = watchService.poll(1, TimeUnit.SECONDS);

        if (watchKey == null) {
            continue;
        }

        for (WatchEvent<?> event : watchKey.pollEvents()) {

            /*
              It should return a Path object for ENTRY_CREATE and ENTRY_MODIFY events
             */
            Object context = event.context();
            if (!(context instanceof Path)) {
                LOG.warn("Received an unexpected event of kind {} for context {}", event.kind(), event.context());
                continue;
            }

            Path contextPath = (Path) context;

            if (contextPath.toString().equals(doneFile.getName())) {
                LOG.info("Sink file at the build path {} had a matching event of type: {}", sinkFile.getPath(),
                        event.kind());

                return;
            } else {
                LOG.debug("Ignoring a watch event at build path {} of type {} for file: {}", sinkFile.getPath(),
                        event.kind(), contextPath.getFileName());
            }
        }
        watchKey.reset();
        retries--;
    } while (!doneFile.exists() && retries > 0);
}