Search in sources :

Example 6 with WatchKey

use of java.nio.file.WatchKey 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();
        }
    }
}
Also used : Options(org.jline.builtins.Options) AttributedStringBuilder(org.jline.utils.AttributedStringBuilder) Closeable(java.io.Closeable) ArrayList(java.util.ArrayList) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) AttributedString(org.jline.utils.AttributedString) HashSet(java.util.HashSet) Path(java.nio.file.Path) InputStreamReader(java.io.InputStreamReader) ByteArrayInputStream(java.io.ByteArrayInputStream) FilterInputStream(java.io.FilterInputStream) InputStream(java.io.InputStream) WatchKey(java.nio.file.WatchKey) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) IOException(java.io.IOException) WatchService(java.nio.file.WatchService)

Example 7 with WatchKey

use of java.nio.file.WatchKey in project hutool by looly.

the class WatchMonitor method watch.

/**
 * 开始监听事件,阻塞当前进程
 * @param watcher 监听
 * @throws WatchException 监听异常,如果监听关闭抛出此异常
 */
public void watch(Watcher watcher) throws WatchException {
    if (isClosed) {
        throw new WatchException("Watch Monitor is closed !");
    }
    registerPath();
    while (false == isClosed) {
        WatchKey wk;
        try {
            wk = watchService.take();
        } catch (InterruptedException e) {
            // log.warn(e);
            return;
        }
        final Path currentPath = watchKeyPathMap.get(wk);
        WatchEvent.Kind<?> kind;
        for (WatchEvent<?> event : wk.pollEvents()) {
            kind = event.kind();
            if (null != this.filePath && false == this.filePath.endsWith(event.context().toString())) {
                // log.debug("[{}] is not fit for [{}], pass it.", event.context(), this.filePath.getFileName());
                continue;
            }
            if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
                watcher.onCreate(event, currentPath);
            } else if (kind == StandardWatchEventKinds.ENTRY_MODIFY) {
                watcher.onModify(event, currentPath);
            } else if (kind == StandardWatchEventKinds.ENTRY_DELETE) {
                watcher.onDelete(event, currentPath);
            } else if (kind == StandardWatchEventKinds.OVERFLOW) {
                watcher.onOverflow(event, currentPath);
            }
        }
        wk.reset();
    }
}
Also used : Path(java.nio.file.Path) WatchKey(java.nio.file.WatchKey) WatchEvent(java.nio.file.WatchEvent)

Example 8 with WatchKey

use of java.nio.file.WatchKey in project felix by apache.

the class Watcher method watch.

private void watch(final Path path) throws IOException {
    if (watcher != null) {
        WatchKey key = path.register(watcher, ENTRY_CREATE, ENTRY_MODIFY, ENTRY_DELETE);
        keys.put(key, path);
        debug("Watched path " + path + " key " + key);
    } else {
        warn("No watcher yet for path " + path);
    }
}
Also used : WatchKey(java.nio.file.WatchKey)

Example 9 with WatchKey

use of java.nio.file.WatchKey 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);
    }
}
Also used : Path(java.nio.file.Path) WatchKey(java.nio.file.WatchKey) Event(org.apache.felix.dm.context.Event) WatchEvent(java.nio.file.WatchEvent) WatchEvent(java.nio.file.WatchEvent) WatchService(java.nio.file.WatchService)

Example 10 with WatchKey

use of java.nio.file.WatchKey in project Orchid by JavaEden.

the class FileWatcher method register.

private void register(Path dir) throws IOException {
    WatchKey key = dir.register(watcher, new WatchEvent.Kind[] { ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY }, SensitivityWatchEventModifier.HIGH);
    keys.put(key, dir);
}
Also used : WatchKey(java.nio.file.WatchKey) WatchEvent(java.nio.file.WatchEvent)

Aggregations

WatchKey (java.nio.file.WatchKey)134 Path (java.nio.file.Path)88 WatchEvent (java.nio.file.WatchEvent)65 IOException (java.io.IOException)49 WatchService (java.nio.file.WatchService)30 File (java.io.File)27 ClosedWatchServiceException (java.nio.file.ClosedWatchServiceException)18 ArrayList (java.util.ArrayList)10 Test (org.junit.Test)10 HashMap (java.util.HashMap)7 Map (java.util.Map)7 FileSystems (java.nio.file.FileSystems)6 FileVisitResult (java.nio.file.FileVisitResult)6 HashSet (java.util.HashSet)6 List (java.util.List)6 StandardWatchEventKinds (java.nio.file.StandardWatchEventKinds)5 InputStream (java.io.InputStream)4 AccessDeniedException (java.nio.file.AccessDeniedException)4 Kind (java.nio.file.WatchEvent.Kind)4 Logger (org.slf4j.Logger)4