Skip to content

Instantly share code, notes, and snippets.

@zzzfree
Created March 11, 2013 15:11
Show Gist options
  • Save zzzfree/5134912 to your computer and use it in GitHub Desktop.
Save zzzfree/5134912 to your computer and use it in GitHub Desktop.
Directory Watcher Groovy
package com.wz.service.impl
import com.wz.service.IConfigService
import com.wz.service.IFileService
import com.wz.service.IMonitorService
import com.wz.service.ITagService
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.nio.file.*
import java.nio.file.StandardWatchEventKinds
class MonitorService implements IMonitorService {
IConfigService config
IFileService file
ITagService tag
def handler = []
def watcher
def ts = [:]
def fileSystem
def started = false
def adds = []
def removes = []
def MonitorService(){
fileSystem = FileSystems.getDefault()
watcher = fileSystem.newWatchService();
}
@Override
public Object addDirectory(Object dir) {
println dir
if(ts.get(dir)!=null){
ts.get(dir).cancel()
}
Path myDir = fileSystem.getPath(dir);
def k = myDir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);
ts.put(dir,k)
new File(dir).listFiles().each{
if(it.isDirectory()){
addDirectory(it.getPath())
}
}
return ;
}
@Override
public Object removeDirectory(Object dir) {
if(ts.get(dir)!=null){
ts.get(dir).cancel()
ts.remove(dir)
}
return null;
}
@Override
public Object listDirectory() {
def dirs = []
ts.each{k,v->
dirs<<k
}
return dirs;
}
@Override
public Object start() {
if(started) return
started = true
Thread t = new Thread([run:{
while(started){
sleep(100)
ts.each{k,v->
for (WatchEvent<?> event : v.pollEvents()) {
System.out.print(String.format("An event was found of kind %s.%n", event.kind()));
System.out.print(String.format("The event occurred on file '%s'.%n", event.context()));
println k + File.separator + event.context()
def f = new File( k + File.separator + event.context())
if(f.isDirectory()){
if(StandardWatchEventKinds.ENTRY_CREATE == event.kind()){
adds << f.getPath()
}
else if( StandardWatchEventKinds.ENTRY_DELETE == event.kind()){
removes << f.getPath()
}
}
handler.each{
it.&update(f,event.kind())
}
}
}
def t = []
ts.each{a->
// check sub directories
removes.each{
if(a.indexOf(it)>=0){
t << it
}
}
}
t.each{
remove << t
}
removes.each{
removeDirectory(it)
}
removes = []
adds.each{
addDirectory(it)
}
adds = []
}
}] as Runnable).start()
return null;
}
@Override
public Object stop() {
started = false
return null;
}
@Override
public Object addFileChangeListener(Object handler) {
// TODO Auto-generated method stub
return this.handler << handler;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment