Java Code Examples for java.nio.file.WatchEvent#Kind

The following examples show how to use java.nio.file.WatchEvent#Kind . 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: WindowsWatchService.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
WindowsWatchKey init(long handle,
                     Set<? extends WatchEvent.Kind<?>> events,
                     boolean watchSubtree,
                     NativeBuffer buffer,
                     long countAddress,
                     long overlappedAddress,
                     int completionKey)
{
    this.handle = handle;
    this.events = events;
    this.watchSubtree = watchSubtree;
    this.buffer = buffer;
    this.countAddress = countAddress;
    this.overlappedAddress = overlappedAddress;
    this.completionKey = completionKey;
    return this;
}
 
Example 2
Source File: WindowsWatchService.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
private WatchEvent.Kind<?> translateActionToEvent(int action) {
    switch (action) {
        case FILE_ACTION_MODIFIED :
            return StandardWatchEventKinds.ENTRY_MODIFY;

        case FILE_ACTION_ADDED :
        case FILE_ACTION_RENAMED_NEW_NAME :
            return StandardWatchEventKinds.ENTRY_CREATE;

        case FILE_ACTION_REMOVED :
        case FILE_ACTION_RENAMED_OLD_NAME :
            return StandardWatchEventKinds.ENTRY_DELETE;

        default :
            return null;  // action not recognized
    }
}
 
Example 3
Source File: DefaultCertificateValidator.java    From opc-ua-stack with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    while (true) {
        try {
            WatchKey key = watchService.take();

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

                    if (kind != StandardWatchEventKinds.OVERFLOW) {
                        synchronizeTrustedCertificates();
                    }
                }
            }

            if (!key.reset()) {
                break;
            }
        } catch (InterruptedException e) {
            logger.error("Watcher interrupted.", e);
        }
    }
}
 
Example 4
Source File: WindowsWatchService.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
WindowsWatchKey init(long handle,
                     Set<? extends WatchEvent.Kind<?>> events,
                     boolean watchSubtree,
                     NativeBuffer buffer,
                     long countAddress,
                     long overlappedAddress,
                     int completionKey)
{
    this.handle = handle;
    this.events = events;
    this.watchSubtree = watchSubtree;
    this.buffer = buffer;
    this.countAddress = countAddress;
    this.overlappedAddress = overlappedAddress;
    this.completionKey = completionKey;
    return this;
}
 
Example 5
Source File: ArchivingTest.java    From tomee with Apache License 2.0 5 votes vote down vote up
private static void watch(final WatchKey key) {

        if (watcherThread != null) {
            // tell the old watchter thread to shutdown
            watcherThread.interrupt();
        }

         watcherThread = new Thread("ArchivingTest.watch") {
            @Override
            public void run() {


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

                        if (kind == StandardWatchEventKinds.OVERFLOW) {
                            continue;
                        }

                        if (watcherThread != this || isInterrupted()) {
                            return;
                        }

                        lastEvent.set(event);

                        latch.get().countDown();
                    }

                    final boolean valid = key.reset();
                    if (!valid) {
                        System.out.println("ArchivingTest.watch terminated");
                        break;
                    }
                }
            }
        };

        watcherThread.start();
    }
 
Example 6
Source File: WindowsWatchService.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private void processEvents(WindowsWatchKey key, int size) {
    long address = key.buffer().address();

    int nextOffset;
    do {
        int action = UNSAFE.getInt(address + OFFSETOF_ACTION);

        // map action to event
        WatchEvent.Kind<?> kind = translateActionToEvent(action);
        if (key.events().contains(kind)) {
            // copy the name
            int nameLengthInBytes = UNSAFE.getInt(address + OFFSETOF_FILENAMELENGTH);
            if ((nameLengthInBytes % 2) != 0) {
                throw new AssertionError("FileNameLength is not a multiple of 2");
            }
            char[] nameAsArray = new char[nameLengthInBytes/2];
            UNSAFE.copyMemory(null, address + OFFSETOF_FILENAME, nameAsArray,
                Unsafe.ARRAY_CHAR_BASE_OFFSET, nameLengthInBytes);

            // create FileName and queue event
            WindowsPath name = WindowsPath
                .createFromNormalizedPath(fs, new String(nameAsArray));
            key.signalEvent(kind, name);
        }

        // next event
        nextOffset = UNSAFE.getInt(address + OFFSETOF_NEXTENTRYOFFSET);
        address += (long)nextOffset;
    } while (nextOffset != 0);
}
 
Example 7
Source File: Watcher.java    From mangooio with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("all")
private void handleEvents(WatchKey watchKey, Path path) {
    for (WatchEvent<?> watchEvent : watchKey.pollEvents()) {
        WatchEvent.Kind<?> watchEventKind = watchEvent.kind();
        if (OVERFLOW.equals(watchEventKind)) {
            continue;
        }

        WatchEvent<Path> ev = (WatchEvent<Path>) watchEvent;
        Path name = ev.context();
        Path child = path.resolve(name);

        if (ENTRY_MODIFY.equals(watchEventKind) && !child.toFile().isDirectory()) {
            handleNewOrModifiedFile(child);
        }

        if (ENTRY_CREATE.equals(watchEventKind)) {
            if (!child.toFile().isDirectory()) {
                handleNewOrModifiedFile(child);
            }
            try {
                if (Files.isDirectory(child, NOFOLLOW_LINKS)) {
                    registerAll(child);
                }
            } catch (IOException e) {
                LOG.error("Something fishy happened. Unable to register new dir for watching", e);
            }
        }
    }
}
 
Example 8
Source File: AbstractWatchService.java    From jimfs with Apache License 2.0 5 votes vote down vote up
public Key(
    AbstractWatchService watcher,
    @NullableDecl Watchable watchable,
    Iterable<? extends WatchEvent.Kind<?>> subscribedTypes) {
  this.watcher = checkNotNull(watcher);
  this.watchable = watchable; // nullable for Watcher poison
  this.subscribedTypes = ImmutableSet.copyOf(subscribedTypes);
}
 
Example 9
Source File: PollingWatchService.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
void enable(Set<? extends WatchEvent.Kind<?>> events, long period) {
    synchronized (this) {
        // update the events
        this.events = events;

        // create the periodic task
        Runnable thunk = new Runnable() { public void run() { poll(); }};
        this.poller = scheduledExecutor
            .scheduleAtFixedRate(thunk, period, period, TimeUnit.SECONDS);
    }
}
 
Example 10
Source File: JsonServiceRegistryConfigWatcher.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
/**
 * Handle event.
 *
 * @param key the key
 */
private void handleEvent(final WatchKey key) {
    this.readLock.lock();
    try {
        for (final WatchEvent<?> event : key.pollEvents()) {
            if (event.count() <= 1) {
                final WatchEvent.Kind kind = event.kind();

                //The filename is the context of the event.
                final WatchEvent<Path> ev = (WatchEvent<Path>) event;
                final Path filename = ev.context();

                final Path parent = (Path) key.watchable();
                final Path fullPath = parent.resolve(filename);
                final File file = fullPath.toFile();

                LOGGER.trace("Detected event [{}] on file [{}]. Loading change...", kind, file);
                if (kind.name().equals(ENTRY_CREATE.name()) && file.exists()) {
                    handleCreateEvent(file);
                } else if (kind.name().equals(ENTRY_DELETE.name())) {
                    handleDeleteEvent();
                } else if (kind.name().equals(ENTRY_MODIFY.name()) && file.exists()) {
                    handleModifyEvent(file);
                }
            }

        }
    } finally {
        this.readLock.unlock();
    }
}
 
Example 11
Source File: WindowsWatchService.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
private void processEvents(WindowsWatchKey key, int size) {
    long address = key.buffer().address();

    int nextOffset;
    do {
        int action = UNSAFE.getInt(address + OFFSETOF_ACTION);

        // map action to event
        WatchEvent.Kind<?> kind = translateActionToEvent(action);
        if (key.events().contains(kind)) {
            // copy the name
            int nameLengthInBytes = UNSAFE.getInt(address + OFFSETOF_FILENAMELENGTH);
            if ((nameLengthInBytes % 2) != 0) {
                throw new AssertionError("FileNameLength is not a multiple of 2");
            }
            char[] nameAsArray = new char[nameLengthInBytes/2];
            UNSAFE.copyMemory(null, address + OFFSETOF_FILENAME, nameAsArray,
                Unsafe.ARRAY_CHAR_BASE_OFFSET, nameLengthInBytes);

            // create FileName and queue event
            WindowsPath name = WindowsPath
                .createFromNormalizedPath(fs, new String(nameAsArray));
            key.signalEvent(kind, name);
        }

        // next event
        nextOffset = UNSAFE.getInt(address + OFFSETOF_NEXTENTRYOFFSET);
        address += (long)nextOffset;
    } while (nextOffset != 0);
}
 
Example 12
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 13
Source File: AbstractWatchKey.java    From RxJavaFileUtils with Apache License 2.0 4 votes vote down vote up
@Override
public WatchEvent.Kind<T> kind() {
    return kind;
}
 
Example 14
Source File: WindowsWatchService.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
Set<? extends WatchEvent.Kind<?>> events() {
    return events;
}
 
Example 15
Source File: WindowsWatchService.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
void setEvents(Set<? extends WatchEvent.Kind<?>> events) {
    this.events = events;
}
 
Example 16
Source File: GcsPath.java    From beam with Apache License 2.0 4 votes vote down vote up
@Override
public WatchKey register(
    WatchService watcher, WatchEvent.Kind<?>[] events, WatchEvent.Modifier... modifiers)
    throws IOException {
  throw new UnsupportedOperationException();
}
 
Example 17
Source File: AbstractWatchServiceTest.java    From jimfs with Apache License 2.0 4 votes vote down vote up
@Override
public WatchKey register(WatchService watcher, WatchEvent.Kind<?>... events)
    throws IOException {
  return ((AbstractWatchService) watcher).register(this, Arrays.asList(events));
}
 
Example 18
Source File: Consumer.java    From ariADDna with Apache License 2.0 4 votes vote down vote up
/**
 * find MOVE, CREATE, DELETE events
 * bufferQueue processing
 * wen we delete file the fileSystem generate ENTRY_DELETE and ENTRY_CREATE events but not in a strict order
 * therefore we take a event from bufferQueue and fid a pair, the remove these events from queue
 * if we did not find a pair
 */
private void checkOtherEvents() {

    //collection for prepared events
    List<Pair<Path, WatchEvent<?>>> doneList = new ArrayList<>();
    for (Pair<Path, WatchEvent<?>> p : bufferQueue) {
        if (p != null && !doneList.contains(p)) {
            @SuppressWarnings("unchecked")
            WatchEvent<Path> event = (WatchEvent<Path>) p.getValue();
            Path name = event.context();
            final boolean[] isMoveEvent = { false };

            WatchEvent.Kind<Path> from = event.kind();
            WatchEvent.Kind<Path> to = from.equals(ENTRY_DELETE) ? ENTRY_CREATE : ENTRY_DELETE;

            bufferQueue.forEach(e -> {
                if (!doneList.contains(e)) {
                    WatchEvent<Path> ev = (WatchEvent<Path>) e.getValue();
                    Path newName = ev.context();
                    if (ev.kind().equals(to) && newName.equals(name)) {
                        if (from.equals(ENTRY_DELETE)) {
                            LOGGER.debug("defined MOVE event from {} to {}",
                                    p.getKey().resolve(name), e.getKey().resolve(name));

                            service.runEvents(
                                    new FileSystemWatchEvent(FileSystemWatchEvent.Type.MOVE,
                                            p.getKey().resolve(name),
                                            e.getKey().resolve(name)));
                        } else {
                            LOGGER.debug("defined MOVE event from {} to {}",
                                    e.getKey().resolve(name), p.getKey().resolve(name));

                            service.runEvents(
                                    new FileSystemWatchEvent(FileSystemWatchEvent.Type.MOVE,
                                            e.getKey().resolve(name),
                                            p.getKey().resolve(name)));
                        }

                        bufferQueue.remove(e);
                        doneList.add(e);
                        isMoveEvent[0] = true;

                    }
                }

            });

            if (!isMoveEvent[0]) {
                FileSystemWatchEvent.Type eventType = from.equals(ENTRY_CREATE) ?
                        FileSystemWatchEvent.Type.CREATE :
                        FileSystemWatchEvent.Type.DELETE;

                if (from == ENTRY_CREATE) {
                    LOGGER.debug("defined CREATE event from {}", p.getKey().resolve(name));

                    try {
                        if (Files.isDirectory(p.getKey().resolve(name))) {
                            service.registerDirectories(p.getKey().resolve(name));
                        }
                    } catch (IOException x) {
                        LOGGER.trace("Cant register folder {}", x.getMessage());
                    }
                } else if (from == ENTRY_DELETE) {
                    LOGGER.debug("defined DELETE event from {}", p.getKey().resolve(name));
                }

                service.runEvents(
                        new FileSystemWatchEvent(eventType, p.getKey().resolve(name)));
                isMoveEvent[0] = false;
            }

        }
        bufferQueue.remove(p);
        doneList.add(p);
    }
    //queue.clear();
    bufferQueue.clear();
}
 
Example 19
Source File: DirectoryChangeEvent.java    From directory-watcher with Apache License 2.0 4 votes vote down vote up
EventType(WatchEvent.Kind<?> kind) {
  this.kind = kind;
}
 
Example 20
Source File: DirectoryWatcher.java    From word with Apache License 2.0 votes vote down vote up
public void execute(WatchEvent.Kind<?> kind, String path);