Created
October 16, 2013 22:02
-
-
Save h3xstream/7015701 to your computer and use it in GitHub Desktop.
Simple script that monitor a directory and search for a specific keyword. (Java NIO simple test..)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.nio.file.FileSystems | |
import java.nio.file.Path | |
import java.nio.file.Paths | |
import java.nio.file.StandardWatchEventKinds; | |
import java.nio.file.WatchEvent; | |
import java.nio.file.WatchKey | |
import java.nio.file.WatchService; | |
class FileEvent { | |
String kind | |
String path | |
String toString() { "${kind} ${path}" } | |
} | |
eventIds = [] as Set<String> | |
events = [] as Queue<FileEvent> | |
def analyzeFile(File f, int level = 0) { | |
//println "Visiting "+f.getCanonicalPath() | |
//Recursive scan | |
if (f.isDirectory()) { | |
f.listFiles().each { File subFiles -> analyzeFile(subFiles, level++); } | |
} else { | |
line = 0 | |
f.eachLine { | |
line++ | |
if (it.contains("flag")) | |
println "($f.canonicalPath:$line) " + it | |
} | |
} | |
} | |
def watchDir(String dir) { | |
WatchService service = FileSystems.getDefault().newWatchService(); | |
Paths.get(dir).register(service, // | |
StandardWatchEventKinds.ENTRY_CREATE, // Watch all the things! | |
StandardWatchEventKinds.ENTRY_MODIFY // | |
//StandardWatchEventKinds.ENTRY_DELETE | |
); | |
//Producer loop | |
while (true) { | |
WatchKey key = service.take(); //Get changes notification | |
for (WatchEvent event in key.pollEvents()) { | |
kind = event.kind().toString(); | |
ctx = event.context().toString(); | |
FileEvent ev = new FileEvent(kind: kind, path: dir + ctx) | |
if (eventIds.add(ev.path)) { | |
println " $kind => $ctx" | |
events.add(ev) | |
} | |
} | |
boolean valid = key.reset(); | |
if (!valid) { | |
break; // Exit if directory is deleted | |
} | |
} | |
} | |
//Consumer loop | |
Thread.start { | |
while (true) { | |
FileEvent ev = events.poll() | |
if (ev) { | |
eventIds.remove(ev.path) | |
println "Analyzing $ev ..." | |
analyzeFile(new File(ev.path)) | |
} | |
//println "Status queue{" + events.size() + "} {"+eventIds.size() + "}" | |
sleep 5000 | |
} | |
} | |
watchDir("C:\\") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment