use of java.nio.file.WatchService in project jdk8u_jdk by JetBrains.
the class LotsOfCancels method main.
public static void main(String[] args) throws Exception {
// create a bunch of directories. Create two tasks for each directory,
// one to bash on cancel, the other to poll the events
ExecutorService pool = Executors.newCachedThreadPool();
try {
Path top = Files.createTempDirectory("work");
top.toFile().deleteOnExit();
for (int i = 1; i <= 16; i++) {
Path dir = Files.createDirectory(top.resolve("dir-" + i));
WatchService watcher = FileSystems.getDefault().newWatchService();
pool.submit(() -> handle(dir, watcher));
pool.submit(() -> poll(watcher));
}
} finally {
pool.shutdown();
}
// give thread pool lots of time to terminate
if (!pool.awaitTermination(5L, TimeUnit.MINUTES))
throw new RuntimeException("Thread pool did not terminate");
if (failed)
throw new RuntimeException("Test failed, see log for details");
}
use of java.nio.file.WatchService in project gradle by gradle.
the class Jdk7FileWatcherFactory method watch.
@Override
public FileWatcher watch(Action<? super Throwable> onError, FileWatcherListener listener) {
try {
WatchService watchService = FileSystems.getDefault().newWatchService();
WatchServiceFileWatcherBacking backing = new WatchServiceFileWatcherBacking(onError, listener, watchService, fileSystem);
return backing.start(executor);
} catch (IOException e) {
throw UncheckedException.throwAsUncheckedException(e);
}
}
use of java.nio.file.WatchService in project felix by apache.
the class Posix method tail.
protected void tail(CommandSession session, Process process, String[] argv) throws Exception {
String[] usage = { "tail - displays last lines of file", "Usage: tail [-f] [-q] [-c # | -n #] [file ...]", " -? --help Show help", " -q --quiet Suppress headers when printing multiple sources", " -f --follow Do not stop at end of file", " -F --FOLLOW Follow and check for file renaming or rotation", " -n --lines=LINES Number of lines to print", " -c --bytes=BYTES Number of bytes to print" };
Options opt = parseOptions(session, usage, argv);
if (opt.isSet("lines") && opt.isSet("bytes")) {
throw new IllegalArgumentException("usage: tail [-f] [-q] [-c # | -n #] [file ...]");
}
int lines;
int bytes;
if (opt.isSet("lines")) {
lines = opt.getNumber("lines");
bytes = Integer.MAX_VALUE;
} else if (opt.isSet("bytes")) {
lines = Integer.MAX_VALUE;
bytes = opt.getNumber("bytes");
} else {
lines = 10;
bytes = Integer.MAX_VALUE;
}
boolean follow = opt.isSet("follow") || opt.isSet("FOLLOW");
AtomicReference<Object> lastPrinted = new AtomicReference<>();
WatchService watchService = follow ? session.currentDir().getFileSystem().newWatchService() : null;
Set<Path> watched = new HashSet<>();
class Input implements Closeable {
String name;
Path path;
Reader reader;
StringBuilder buffer;
long ino;
long size;
public Input(String name) {
this.name = name;
this.buffer = new StringBuilder();
}
public void open() {
if (reader == null) {
try {
InputStream is;
if ("-".equals(name)) {
is = new StdInSource(process).read();
} else {
path = session.currentDir().resolve(name);
is = Files.newInputStream(path);
if (opt.isSet("FOLLOW")) {
try {
ino = (Long) Files.getAttribute(path, "unix:ino");
} catch (Exception e) {
// Ignore
}
}
size = Files.size(path);
}
reader = new InputStreamReader(is);
} catch (IOException e) {
// Ignore
}
}
}
@Override
public void close() throws IOException {
if (reader != null) {
try {
reader.close();
} finally {
reader = null;
}
}
}
public boolean tail() throws IOException {
open();
if (reader != null) {
if (buffer != null) {
char[] buf = new char[1024];
int nb;
while ((nb = reader.read(buf)) > 0) {
buffer.append(buf, 0, nb);
if (bytes > 0 && buffer.length() > bytes) {
buffer.delete(0, buffer.length() - bytes);
} else {
int l = 0;
int i = -1;
while ((i = buffer.indexOf("\n", i + 1)) >= 0) {
l++;
}
if (l > lines) {
i = -1;
l = l - lines;
while (--l >= 0) {
i = buffer.indexOf("\n", i + 1);
}
buffer.delete(0, i + 1);
}
}
}
String toPrint = buffer.toString();
print(toPrint);
buffer = null;
if (follow && path != null) {
Path parent = path.getParent();
if (!watched.contains(parent)) {
parent.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);
watched.add(parent);
}
}
return follow;
} else if (follow && path != null) {
while (true) {
long newSize = Files.size(path);
if (size != newSize) {
char[] buf = new char[1024];
int nb;
while ((nb = reader.read(buf)) > 0) {
print(new String(buf, 0, nb));
}
size = newSize;
}
if (opt.isSet("FOLLOW")) {
long newIno = 0;
try {
newIno = (Long) Files.getAttribute(path, "unix:ino");
} catch (Exception e) {
// Ignore
}
if (ino != newIno) {
close();
open();
ino = newIno;
size = -1;
continue;
}
}
break;
}
return true;
} else {
return false;
}
} else {
Path parent = path.getParent();
if (!watched.contains(parent)) {
parent.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);
watched.add(parent);
}
return true;
}
}
private void print(String toPrint) {
if (lastPrinted.get() != this && opt.args().size() > 1 && !opt.isSet("quiet")) {
process.out().println();
process.out().println("==> " + name + " <==");
}
process.out().print(toPrint);
lastPrinted.set(this);
}
}
if (opt.args().isEmpty()) {
opt.args().add("-");
}
List<Input> inputs = new ArrayList<>();
for (String name : opt.args()) {
Input input = new Input(name);
inputs.add(input);
}
try {
boolean cont = true;
while (cont) {
cont = false;
for (Input input : inputs) {
cont |= input.tail();
}
if (cont) {
WatchKey key = watchService.take();
key.pollEvents();
key.reset();
}
}
} catch (InterruptedException e) {
// Ignore, this is the only way to quit
} finally {
for (Input input : inputs) {
input.close();
}
}
}
use of java.nio.file.WatchService in project felix by apache.
the class PathDependencyImpl method run.
// ---------- other methods -----------
/**
* Our start method fires a thread and this is our run method, which is watching for a given directory path
*/
public void run() {
Path myDir = Paths.get(m_path);
try {
WatchService watcher = myDir.getFileSystem().newWatchService();
myDir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE);
while (!Thread.currentThread().isInterrupted()) {
WatchKey watckKey = watcher.take();
List<WatchEvent<?>> events = watckKey.pollEvents();
for (@SuppressWarnings("rawtypes") WatchEvent event : events) {
final Kind<?> kind = event.kind();
if (StandardWatchEventKinds.OVERFLOW == kind) {
continue;
}
if (StandardWatchEventKinds.ENTRY_CREATE == kind) {
// Notify the component implementation context that a file has been created.
// Later, the component will call our invokeAdd method in order to inject the file
// in the component instance
m_component.handleEvent(this, EventType.ADDED, new Event(event.context().toString()));
} else if (StandardWatchEventKinds.ENTRY_DELETE == kind) {
// Notify the component implementation context that a file has been removed.
// Later, the component will call our invokeRemove method in order to call our component "remove" callback
m_component.handleEvent(this, EventType.REMOVED, new Event(event.context().toString()));
}
}
watckKey.reset();
}
} catch (Throwable e) {
m_component.getLogger().err("path dependency exception", e);
}
}
use of java.nio.file.WatchService in project knime-core by knime.
the class SleepNodeModel method execute.
/**
* {@inheritDoc}
*/
@Override
protected PortObject[] execute(final PortObject[] inData, final ExecutionContext exec) throws Exception {
if (m_selection == 0) {
// wait for
exec.setMessage("Waiting for " + (m_waittime / 1000) + " seconds");
waitFor(m_waittime);
} else if (m_selection == 1) {
// wait to
Calendar c = Calendar.getInstance();
c.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DATE), m_toHours, m_toMin, m_toSec);
if (c.getTimeInMillis() - System.currentTimeMillis() <= 0) {
c.add(Calendar.DAY_OF_YEAR, 1);
}
exec.setMessage("Waiting until " + c.getTime());
final long sleepTime = c.getTimeInMillis() - System.currentTimeMillis();
waitFor(sleepTime);
} else if (m_selection == 2) {
WatchService w = FileSystems.getDefault().newWatchService();
Path p = FileUtil.resolveToPath(FileUtil.toURL(m_filePath));
if (p == null) {
throw new IllegalArgumentException("File location '" + m_filePath + "' is not a local file.");
}
exec.setMessage("Waiting for file '" + p + "'");
Path fileName = p.subpath(p.getNameCount() - 1, p.getNameCount());
Path parent = p.getParent();
Kind<Path> e = null;
if (m_fileStatus.equals("Creation")) {
e = StandardWatchEventKinds.ENTRY_CREATE;
} else if (m_fileStatus.equals("Modification")) {
e = StandardWatchEventKinds.ENTRY_MODIFY;
} else if (m_fileStatus.equals("Deletion")) {
e = StandardWatchEventKinds.ENTRY_DELETE;
} else {
throw new RuntimeException("Selected watchservice event is not available. Selected watchservice : " + m_fileStatus);
}
parent.register(w, e);
boolean keepLooking = true;
while (keepLooking) {
// watch file until the event appears
WatchKey key;
// wait for a key to be available
key = w.take();
for (WatchEvent<?> event : key.pollEvents()) {
if (fileName.equals(event.context())) {
keepLooking = false;
}
}
// reset key
boolean valid = key.reset();
if (!valid) {
break;
}
}
}
if (inData[0] == null) {
return new PortObject[] { FlowVariablePortObject.INSTANCE };
} else {
return inData;
}
}
Aggregations