Java Code Examples for java.nio.file.WatchService#take()

The following examples show how to use java.nio.file.WatchService#take() . 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: 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 2
Source File: FileWatchService.java    From training with MIT License 6 votes vote down vote up
public static void main(String[] args) throws IOException, InterruptedException {
	Path tmpDir = Paths.get("tmp");
	WatchService watchService = FileSystems.getDefault().newWatchService();
	Path monitoredFolder = tmpDir;
	monitoredFolder.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE);
	
	tmpDir.toFile().mkdirs();
	new FileChanger(tmpDir).start();
	while (true) {
		System.out.println("Waiting for event");
		WatchKey watchKey = watchService.take();
		for (WatchEvent<?> event : watchKey.pollEvents()) {
			System.out.println("Detected event " + event.kind().name() + " on file " + event.context().toString());
		}
		watchKey.reset();
	}
}
 
Example 3
Source File: FileModificationEventWatcher.java    From pravega with Apache License 2.0 6 votes vote down vote up
private WatchKey retrieveWatchKeyFrom(WatchService watchService) throws InterruptedException {
    WatchKey result = watchService.take();
    log.info("Retrieved and removed watch key for watching file at path: {}", this.watchedFilePath);

    // Each file modification/create usually results in the WatcherService reporting the WatchEvent twice,
    // as the file is updated twice: once for the content and once for the file modification time.
    // These events occur in quick succession. We wait for 200 ms., here so that the events get
    // de-duplicated - in other words only single event is processed.
    //
    // See https://stackoverflow.com/questions/16777869/java-7-watchservice-ignoring-multiple-occurrences-
    // of-the-same-event for a discussion on this topic.
    //
    // If the two events are not raised within this duration, the callback will be invoked twice, which we
    // assume is not a problem for applications of this object. In case the applications do care about
    // being notified only once for each modification, they should use the FileModificationPollingMonitor
    // instead.
    Thread.sleep(200);

    return result;
}
 
Example 4
Source File: LotsOfCancels.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Polls the given WatchService in a tight loop. This keeps the event
 * queue drained, it also hogs a CPU core which seems necessary to
 * tickle the original bug.
 */
static void poll(WatchService watcher) {
    try {
        for (;;) {
            WatchKey key = watcher.take();
            if (key != null) {
                key.pollEvents();
                key.reset();
            }
        }
    } catch (ClosedWatchServiceException expected) {
        // nothing to do
    } catch (Exception e) {
        e.printStackTrace();
        failed = true;
    }
}
 
Example 5
Source File: PluginPropertiesWatcher.java    From OpenFalcon-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 6
Source File: LotsOfCancels.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Polls the given WatchService in a tight loop. This keeps the event
 * queue drained, it also hogs a CPU core which seems necessary to
 * tickle the original bug.
 */
static void poll(WatchService watcher) {
    try {
        for (;;) {
            WatchKey key = watcher.take();
            if (key != null) {
                key.pollEvents();
                key.reset();
            }
        }
    } catch (ClosedWatchServiceException expected) {
        // nothing to do
    } catch (Exception e) {
        e.printStackTrace();
        failed = true;
    }
}
 
Example 7
Source File: LotsOfCancels.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Polls the given WatchService in a tight loop. This keeps the event
 * queue drained, it also hogs a CPU core which seems necessary to
 * tickle the original bug.
 */
static void poll(WatchService watcher) {
    try {
        for (;;) {
            WatchKey key = watcher.take();
            if (key != null) {
                key.pollEvents();
                key.reset();
            }
        }
    } catch (ClosedWatchServiceException expected) {
        // nothing to do
    } catch (Exception e) {
        e.printStackTrace();
        failed = true;
    }
}
 
Example 8
Source File: LotsOfCancels.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Polls the given WatchService in a tight loop. This keeps the event
 * queue drained, it also hogs a CPU core which seems necessary to
 * tickle the original bug.
 */
static void poll(int id, WatchService watcher) {
    System.out.printf("begin poll %d%n", id);
    try {
        for (;;) {
            WatchKey key = watcher.take();
            if (key != null) {
                key.pollEvents();
                key.reset();
            }
        }
    } catch (ClosedWatchServiceException expected) {
        // nothing to do but print
        System.out.printf("poll %d expected exception %s%n", id, expected);
    } catch (Exception e) {
        e.printStackTrace();
        failed = true;
    }
    System.out.printf("end poll %d%n", id);
}
 
Example 9
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 10
Source File: Main.java    From java-cheat with GNU General Public License v3.0 6 votes vote down vote up
public static void main(final String[] args) throws InterruptedException, IOException {
    final WatchService watchService = FileSystems.getDefault().newWatchService();
    Paths.get(WATCH_DIR).register(
            watchService,
            StandardWatchEventKinds.ENTRY_CREATE,
            StandardWatchEventKinds.ENTRY_DELETE,
            StandardWatchEventKinds.ENTRY_MODIFY);
    for (;;) {
        final WatchKey key = watchService.take();
        for (final WatchEvent<?> event : key.pollEvents()) {
            final WatchEvent.Kind kind = event.kind();
            // TODO
            if (kind == StandardWatchEventKinds.OVERFLOW) continue;
            System.out.format("%s: %s\n", kind.name(), cast(event).context());
        }
        key.reset();
    }
}
 
Example 11
Source File: LotsOfCancels.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Polls the given WatchService in a tight loop. This keeps the event
 * queue drained, it also hogs a CPU core which seems necessary to
 * tickle the original bug.
 */
static void poll(WatchService watcher) {
    try {
        for (;;) {
            WatchKey key = watcher.take();
            if (key != null) {
                key.pollEvents();
                key.reset();
            }
        }
    } catch (ClosedWatchServiceException expected) {
        // nothing to do
    } catch (Exception e) {
        e.printStackTrace();
        failed = true;
    }
}
 
Example 12
Source File: LotsOfCancels.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Polls the given WatchService in a tight loop. This keeps the event
 * queue drained, it also hogs a CPU core which seems necessary to
 * tickle the original bug.
 */
static void poll(WatchService watcher) {
    try {
        for (;;) {
            WatchKey key = watcher.take();
            if (key != null) {
                key.pollEvents();
                key.reset();
            }
        }
    } catch (ClosedWatchServiceException expected) {
        // nothing to do
    } catch (Exception e) {
        e.printStackTrace();
        failed = true;
    }
}
 
Example 13
Source File: LotsOfCancels.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Polls the given WatchService in a tight loop. This keeps the event
 * queue drained, it also hogs a CPU core which seems necessary to
 * tickle the original bug.
 */
static void poll(WatchService watcher) {
    try {
        for (;;) {
            WatchKey key = watcher.take();
            if (key != null) {
                key.pollEvents();
                key.reset();
            }
        }
    } catch (ClosedWatchServiceException expected) {
        // nothing to do
    } catch (Exception e) {
        e.printStackTrace();
        failed = true;
    }
}
 
Example 14
Source File: TestWatchService.java    From jsr203-hadoop with Apache License 2.0 5 votes vote down vote up
static void takeExpectedKey(WatchService watcher, WatchKey expected) {
    System.out.println("take events...");
    WatchKey key;
    try {
        key = watcher.take();
        System.out.println("key taken: " + key);
    } catch (InterruptedException x) {
        // not expected
        throw new RuntimeException(x);
    }
    System.out.println("expected key: " + expected);
    if (key != expected) {
        throw new RuntimeException("removed unexpected key");
    }
}
 
Example 15
Source File: ConfigUpdater.java    From cellery-security with Apache License 2.0 5 votes vote down vote up
public void run() {

        log.info("Running configuration updater..");
        String configFilePath = CellStsUtils.getConfigFilePath();
        Path directoryPath = Paths.get(configFilePath.substring(0, configFilePath.lastIndexOf("/")));
        try {
            while (true) {
                WatchService watcher = directoryPath.getFileSystem().newWatchService();
                directoryPath.register(watcher, StandardWatchEventKinds.ENTRY_CREATE,
                        StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);

                log.debug("Waiting for config file change");
                WatchKey watckKey = watcher.take();

                List<WatchEvent<?>> events = watckKey.pollEvents();
                log.debug("Received events: ....");
                for (WatchEvent event : events) {
                    if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {
                        log.info("Updating file on {} event", StandardWatchEventKinds.ENTRY_CREATE);
                        CellStsUtils.buildCellStsConfiguration();
                        CellStsUtils.readUnsecuredContexts();
                    }
                    if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) {
                        log.info("Updating file on {} event", StandardWatchEventKinds.ENTRY_MODIFY);
                        CellStsUtils.buildCellStsConfiguration();
                        CellStsUtils.readUnsecuredContexts();
                    }
                }

            }
        } catch (IOException | InterruptedException | CelleryCellSTSException e) {
            log.error("Error while updating configurations on file change ", e);
        }
    }
 
Example 16
Source File: ConfDirWatcher.java    From OpenFalcon-SuitAgent with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    WatchService watchService = WatchServiceUtil.watchModify(confDir);
    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();
                    if("authorization.properties".equals(fileName)){
                        log.info("检测到授权文件authorization.properties有改动,正在重新配置相关插件配置");
                        Set<Plugin> plugins = PluginLibraryHelper.getPluginsAboutAuthorization();
                        for (Plugin plugin : plugins) {
                            plugin.init(PluginLibraryHelper.getPluginConfig(plugin));
                            log.info("已完成插件{}的配置重新加载",plugin.pluginName());
                        }
                    }
                }
            }
            key.reset();
        } catch (Exception e) {
            log.error("插件配置文件监听异常",e);
            break;
        }
    }
}
 
Example 17
Source File: FileBasedOneShotLatch.java    From flink with Apache License 2.0 5 votes vote down vote up
private void awaitLatchFile(final WatchService watchService) throws InterruptedException {
	while (true) {
		WatchKey watchKey = watchService.take();
		if (isReleasedOrReleasable()) {
			break;
		}
		watchKey.reset();
	}
}
 
Example 18
Source File: FileSystemEventReader.java    From singer with Apache License 2.0 5 votes vote down vote up
public static void readEvents(String pathStr, long pollIntervalMs) throws IOException, InterruptedException {
  WatchService watchService = FileSystems.getDefault().newWatchService();
  Path path = Paths.get(pathStr);
  SingerUtils.registerWatchKey(watchService, path);

  while (true) {
    WatchKey watchKey = watchService.take();
    int numHiddenFileEvents = 0;
    int numNormalFileEvents = 0;
    for (final WatchEvent<?> event : watchKey.pollEvents()) {
      WatchEvent.Kind<?> kind = event.kind();
      Path filePath = (Path) event.context();
      if (filePath.toString().startsWith(".")) {
        numHiddenFileEvents++;
        continue;
      } else {
        numNormalFileEvents++;
        System.out.println("kind = " + kind + ": " + event.context());
      }
    }
    System.out.println("Events in one batch      : " + (numHiddenFileEvents + numNormalFileEvents));
    System.out.println("Events from normal files : " + numNormalFileEvents);
    System.out.println("Events from hidden files : " + numHiddenFileEvents);
    watchKey.reset();
    Thread.sleep(pollIntervalMs);
  }
}
 
Example 19
Source File: MainPanel.java    From java-swing-tips with MIT License 4 votes vote down vote up
public void processEvents(Path dir, WatchService watcher) {
  for (;;) {
    // wait for key to be signaled
    WatchKey key;
    try {
      key = watcher.take();
    } catch (InterruptedException ex) {
      EventQueue.invokeLater(() -> append("Interrupted"));
      Thread.currentThread().interrupt();
      return;
    }

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

      // This key is registered only for ENTRY_CREATE events,
      // but an OVERFLOW event can occur regardless if events
      // are lost or discarded.
      if (kind == StandardWatchEventKinds.OVERFLOW) {
        continue;
      }

      // The filename is the context of the event.
      @SuppressWarnings("unchecked")
      WatchEvent<Path> ev = (WatchEvent<Path>) event;
      Path filename = ev.context();

      Path child = dir.resolve(filename);
      EventQueue.invokeLater(() -> {
        append(String.format("%s: %s", kind, child));
        updateTable(kind, child);
      });
    }

    // Reset the key -- this step is critical if you want to
    // receive further watch events.  If the key is no longer valid,
    // the directory is inaccessible so exit the loop.
    boolean valid = key.reset();
    if (!valid) {
      break;
    }
  }
}
 
Example 20
Source File: Watchdir.java    From verigreen with Apache License 2.0 4 votes vote down vote up
@Override
public void run() {
	FileReader reader = null;
	Properties properties = new Properties();
	
	for(;;){
		 try
           {
			    WatchService watcher = myDir.getFileSystem().newWatchService();
				myDir.register(watcher, StandardWatchEventKinds.ENTRY_MODIFY);
				WatchKey watckKey = watcher.take();
				List<WatchEvent<?>> events = watckKey.pollEvents();
				for (WatchEvent<?> event : events) {
					if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) {
						VerigreenLogger.get().log(
			                       getClass().getName(),
			                       RuntimeUtils.getCurrentMethodName(),
			                       "Modify: " + event.context().toString());
						reader = new FileReader(path + "/config.properties");
						properties.load(reader);
					
						String protectedBranches=properties.getProperty("git.protectedBranches");
						String permittedUsers=properties.getProperty("git.permittedUsers");
						String jobName=properties.getProperty("jenkins.jobName");
						String fullPush=properties.getProperty("full.push");
						
						//If the value is null then add it from the prop file to the hash map. This is important in case reading the value when a first push happened after changing the job name 
						if((VerigreenNeededLogic.VerigreenMap.get("_jobName") == null) || (!VerigreenNeededLogic.VerigreenMap.get("_jobName").equals(jobName))){
							VerigreenNeededLogic.VerigreenMap.put("_jobName", jobName);
							JenkinsVerifier.job2Verify = JenkinsVerifier.getJobToVerify();
						}
						
						if(!VerigreenNeededLogic.VerigreenMap.get("_protectedBranches").equals(protectedBranches)){
							VerigreenNeededLogic.VerigreenMap.put("_protectedBranches", protectedBranches);
						}
						
						if(!VerigreenNeededLogic.VerigreenMap.get("_permittedUsers").equals(permittedUsers)){
							VerigreenNeededLogic.VerigreenMap.put("_permittedUsers", permittedUsers);
						}
						
						if(!VerigreenNeededLogic.VerigreenMap.get("_fullPush").equals(fullPush)){
							VerigreenNeededLogic.VerigreenMap.put("_fullPush", fullPush);
						}
					}
				}					
           }
           catch( Exception e)
           {
               e.printStackTrace ( );
           } 
	}
	
}