Search in sources :

Example 41 with WatchEvent

use of java.nio.file.WatchEvent in project SpongeCommon by SpongePowered.

the class SpongeUserManager method pollFilesystemWatcher.

private void pollFilesystemWatcher() {
    if (this.watchKey == null || !this.watchKey.isValid()) {
        // Reboot this if it's somehow failed.
        this.refreshFilesystemProfiles();
        this.setupWatchers();
        return;
    }
    // watcher has found any more (or removed any).
    synchronized (this.watcherUpdateMap) {
        this.watcherUpdateMap.clear();
        for (final WatchEvent<?> event : this.watchKey.pollEvents()) {
            @SuppressWarnings("unchecked") final WatchEvent<Path> ev = (WatchEvent<Path>) event;
            @Nullable final Path file = ev.context();
            // It is possible that the context is null, in which case, ignore it.
            if (file != null) {
                final String filename = file.getFileName().toString();
                // We don't determine the UUIDs yet, we'll only do that if we need to.
                this.watcherUpdateMap.computeIfAbsent(filename, f -> new SpongeUserMutableWatchEvent()).set(ev.kind());
            }
        }
        // Now we know what the final result is, we can act upon it.
        for (final Map.Entry<String, SpongeUserMutableWatchEvent> entry : this.watcherUpdateMap.entrySet()) {
            final WatchEvent.Kind<?> kind = entry.getValue().get();
            if (kind != null) {
                final String name = entry.getKey();
                final UUID uuid;
                if (name.endsWith(".dat")) {
                    try {
                        uuid = UUID.fromString(name.substring(0, name.length() - 4));
                        // It will only be create or delete here.
                        if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
                            this.knownUUIDs.add(uuid);
                        } else {
                            this.knownUUIDs.remove(uuid);
                        // We don't do this, in case we were caught at a bad time.
                        // Everything else should handle it for us, however.
                        // this.userCache.invalidate(uuid);
                        }
                    } catch (final IllegalArgumentException ex) {
                    // ignored, file isn't of use to us.
                    }
                }
            }
        }
    }
}
Also used : Path(java.nio.file.Path) ThreadFactoryBuilder(com.google.common.util.concurrent.ThreadFactoryBuilder) NonNull(org.checkerframework.checker.nullness.qual.NonNull) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) Cache(com.github.benmanes.caffeine.cache.Cache) GameProfileCache(org.spongepowered.api.profile.GameProfileCache) SpongeGameProfile(org.spongepowered.common.profile.SpongeGameProfile) WatchKey(java.nio.file.WatchKey) HashSet(java.util.HashSet) MinecraftServer(net.minecraft.server.MinecraftServer) PlayerDataStorage(net.minecraft.world.level.storage.PlayerDataStorage) StandardWatchEventKinds(java.nio.file.StandardWatchEventKinds) PlayerListAccessor(org.spongepowered.common.accessor.server.players.PlayerListAccessor) Locale(java.util.Locale) Map(java.util.Map) Server(org.spongepowered.api.Server) GameProfile(org.spongepowered.api.profile.GameProfile) Path(java.nio.file.Path) Nullable(org.checkerframework.checker.nullness.qual.Nullable) ExecutorService(java.util.concurrent.ExecutorService) Caffeine(com.github.benmanes.caffeine.cache.Caffeine) User(org.spongepowered.api.entity.living.player.User) Files(java.nio.file.Files) WatchEvent(java.nio.file.WatchEvent) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Sponge(org.spongepowered.api.Sponge) Set(java.util.Set) IOException(java.io.IOException) CompletionException(java.util.concurrent.CompletionException) SpongeCommon(org.spongepowered.common.SpongeCommon) UUID(java.util.UUID) Executors(java.util.concurrent.Executors) PlayerDataStorageAccessor(org.spongepowered.common.accessor.world.level.storage.PlayerDataStorageAccessor) Objects(java.util.Objects) TimeUnit(java.util.concurrent.TimeUnit) WatchService(java.nio.file.WatchService) Stream(java.util.stream.Stream) SpongeUserData(org.spongepowered.common.entity.player.SpongeUserData) SpongeUserView(org.spongepowered.common.entity.player.SpongeUserView) Optional(java.util.Optional) DefaultQualifier(org.checkerframework.framework.qual.DefaultQualifier) FileSystems(java.nio.file.FileSystems) UserManager(org.spongepowered.api.user.UserManager) WatchEvent(java.nio.file.WatchEvent) UUID(java.util.UUID) HashMap(java.util.HashMap) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Nullable(org.checkerframework.checker.nullness.qual.Nullable)

Example 42 with WatchEvent

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

the class WatchMonitorTest method main.

public static void main(String[] args) {
    Watcher watcher = new SimpleWatcher() {

        @Override
        public void onCreate(WatchEvent<?> event, Path currentPath) {
            Object obj = event.context();
            Console.log("创建:{}-> {}", currentPath, obj);
        }

        @Override
        public void onModify(WatchEvent<?> event, Path currentPath) {
            Object obj = event.context();
            Console.log("修改:{}-> {}", currentPath, obj);
        }

        @Override
        public void onDelete(WatchEvent<?> event, Path currentPath) {
            Object obj = event.context();
            Console.log("删除:{}-> {}", currentPath, obj);
        }

        @Override
        public void onOverflow(WatchEvent<?> event, Path currentPath) {
            Object obj = event.context();
            Console.log("Overflow:{}-> {}", currentPath, obj);
        }
    };
    WatchMonitor monitor = WatchMonitor.createAll("d:/test/aaa.txt", new DelayWatcher(watcher, 500));
    monitor.setMaxDepth(0);
    monitor.start();
}
Also used : Path(java.nio.file.Path) WatchMonitor(cn.hutool.core.io.watch.WatchMonitor) SimpleWatcher(cn.hutool.core.io.watch.SimpleWatcher) Watcher(cn.hutool.core.io.watch.Watcher) DelayWatcher(cn.hutool.core.io.watch.watchers.DelayWatcher) WatchEvent(java.nio.file.WatchEvent) SimpleWatcher(cn.hutool.core.io.watch.SimpleWatcher) DelayWatcher(cn.hutool.core.io.watch.watchers.DelayWatcher)

Example 43 with WatchEvent

use of java.nio.file.WatchEvent in project curiostack by curioswitch.

the class FileWatcher method listenForFileEvents.

private void listenForFileEvents() {
    for (; ; ) {
        final WatchKey key;
        try {
            key = watchService.take();
        } catch (ClosedWatchServiceException | InterruptedException ex) {
            return;
        }
        key.pollEvents().stream().filter(e -> e.kind() != StandardWatchEventKinds.OVERFLOW).map(e -> {
            // Only support Path
            @SuppressWarnings("unchecked") WatchEvent<Path> cast = (WatchEvent<Path>) e;
            return cast.context();
        }).forEach(path -> {
            final Path resolved = watchedDirs.get(key).resolve(path);
            Optional<Consumer<Path>> callback = registeredPaths.entrySet().stream().filter(e -> {
                try {
                    // been updated.
                    return e.getKey().toRealPath().startsWith(resolved);
                } catch (IOException ex) {
                    logger.info("Could not resolve real path.", ex);
                    return false;
                }
            }).map(Entry::getValue).findFirst();
            if (callback.isPresent()) {
                logger.info("Processing update to path: " + resolved);
                try {
                    callback.get().accept(resolved);
                } catch (Exception e) {
                    logger.warn("Unexpected exception processing update to path: {}", resolved, e);
                }
            } else {
                logger.info("Could not find callback for path: {}", resolved);
            }
        });
        boolean valid = key.reset();
        if (!valid) {
            logger.info("Key not valid, breaking.");
            break;
        }
    }
}
Also used : ImmutableMap(com.google.common.collect.ImmutableMap) WatchEvent(java.nio.file.WatchEvent) IOException(java.io.IOException) HashMap(java.util.HashMap) Singleton(javax.inject.Singleton) Executors(java.util.concurrent.Executors) UncheckedIOException(java.io.UncheckedIOException) WatchKey(java.nio.file.WatchKey) Consumer(java.util.function.Consumer) Inject(javax.inject.Inject) StandardWatchEventKinds(java.nio.file.StandardWatchEventKinds) WatchService(java.nio.file.WatchService) ClosedWatchServiceException(java.nio.file.ClosedWatchServiceException) Logger(org.apache.logging.log4j.Logger) Map(java.util.Map) Entry(java.util.Map.Entry) Optional(java.util.Optional) Path(java.nio.file.Path) LogManager(org.apache.logging.log4j.LogManager) FileSystems(java.nio.file.FileSystems) ExecutorService(java.util.concurrent.ExecutorService) Path(java.nio.file.Path) Consumer(java.util.function.Consumer) WatchKey(java.nio.file.WatchKey) ClosedWatchServiceException(java.nio.file.ClosedWatchServiceException) WatchEvent(java.nio.file.WatchEvent) IOException(java.io.IOException) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException) UncheckedIOException(java.io.UncheckedIOException) ClosedWatchServiceException(java.nio.file.ClosedWatchServiceException)

Example 44 with WatchEvent

use of java.nio.file.WatchEvent in project cas by apereo.

the class ConfigurationDirectoryPathWatchService method watch.

/**
     * Watch the directory for changes.
     */
public void watch() {
    long lastModified = System.currentTimeMillis();
    while (true) {
        final WatchKey key;
        try {
            key = watcher.take();
        } catch (final InterruptedException e) {
            LOGGER.warn(e.getMessage(), e);
            return;
        }
        for (final WatchEvent<?> event : key.pollEvents()) {
            final WatchEvent.Kind<?> kind = event.kind();
            if (kind == OVERFLOW) {
                LOGGER.warn("An overflow event occurred. File system events may be lost or discarded.");
                continue;
            }
            final WatchEvent<Path> ev = (WatchEvent<Path>) event;
            final Path filename = ev.context();
            try {
                final Path child = this.directory.resolve(filename);
                if (System.currentTimeMillis() - lastModified >= MONITOR_INTERVAL) {
                    LOGGER.debug("Detected configuration change [{}]", kind.name());
                    if (StringUtils.equalsIgnoreCase(StandardWatchEventKinds.ENTRY_CREATE.name(), kind.name())) {
                        this.eventPublisher.publishEvent(new CasConfigurationCreatedEvent(this, child));
                    }
                    if (StringUtils.equalsIgnoreCase(StandardWatchEventKinds.ENTRY_DELETE.name(), kind.name())) {
                        this.eventPublisher.publishEvent(new CasConfigurationDeletedEvent(this, child));
                    }
                    if (StringUtils.equalsIgnoreCase(StandardWatchEventKinds.ENTRY_MODIFY.name(), kind.name())) {
                        this.eventPublisher.publishEvent(new CasConfigurationModifiedEvent(this, child));
                    }
                    lastModified = System.currentTimeMillis();
                }
            } catch (final Exception e) {
                LOGGER.warn(e.getMessage(), e);
                continue;
            }
        }
        final boolean valid = key.reset();
        if (!valid) {
            break;
        }
    }
}
Also used : Path(java.nio.file.Path) CasConfigurationCreatedEvent(org.apereo.cas.support.events.config.CasConfigurationCreatedEvent) WatchKey(java.nio.file.WatchKey) CasConfigurationModifiedEvent(org.apereo.cas.support.events.config.CasConfigurationModifiedEvent) WatchEvent(java.nio.file.WatchEvent) CasConfigurationDeletedEvent(org.apereo.cas.support.events.config.CasConfigurationDeletedEvent)

Example 45 with WatchEvent

use of java.nio.file.WatchEvent in project buck by facebook.

the class WatchedFileHashCache method onFileSystemChange.

/**
   * Called when file change events are posted to the file change EventBus to invalidate cached
   * build rules if required. {@link Path}s contained within events must all be relative to the
   * {@link ProjectFilesystem} root.
   */
@Subscribe
public synchronized void onFileSystemChange(WatchEvent<?> event) {
    if (WatchEvents.isPathChangeEvent(event)) {
        // Path event, remove the path from the cache as it has been changed, added or deleted.
        final Path path = ((Path) event.context()).normalize();
        LOG.verbose("Invalidating %s", path);
        Iterable<Path> pathsToInvalidate = Maps.filterEntries(loadingCache.asMap(), entry -> {
            Preconditions.checkNotNull(entry);
            if (entry.getKey().startsWith(path)) {
                return true;
            }
            if (path.startsWith(entry.getKey())) {
                return true;
            }
            return false;
        }).keySet();
        LOG.verbose("Paths to invalidate: %s", pathsToInvalidate);
        for (Path pathToInvalidate : pathsToInvalidate) {
            invalidate(pathToInvalidate);
        }
    } else {
        // Non-path change event, likely an overflow due to many change events: invalidate everything.
        LOG.debug("Invalidating all");
        invalidateAll();
    }
}
Also used : Path(java.nio.file.Path) ProjectFilesystem(com.facebook.buck.io.ProjectFilesystem) Logger(com.facebook.buck.log.Logger) WatchEvent(java.nio.file.WatchEvent) WatchEvents(com.facebook.buck.io.WatchEvents) Optional(java.util.Optional) Preconditions(com.google.common.base.Preconditions) Subscribe(com.google.common.eventbus.Subscribe) Maps(com.google.common.collect.Maps) Path(java.nio.file.Path) Subscribe(com.google.common.eventbus.Subscribe)

Aggregations

WatchEvent (java.nio.file.WatchEvent)91 Path (java.nio.file.Path)68 WatchKey (java.nio.file.WatchKey)57 IOException (java.io.IOException)33 File (java.io.File)26 Test (org.junit.Test)24 WatchService (java.nio.file.WatchService)20 BuckEventBus (com.facebook.buck.event.BuckEventBus)13 FakeClock (com.facebook.buck.timing.FakeClock)13 EventBus (com.google.common.eventbus.EventBus)12 ClosedWatchServiceException (java.nio.file.ClosedWatchServiceException)10 EasyMock.anyObject (org.easymock.EasyMock.anyObject)10 ArrayList (java.util.ArrayList)9 HashMap (java.util.HashMap)6 Subscribe (com.google.common.eventbus.Subscribe)5 FakeWatchmanClient (com.facebook.buck.io.FakeWatchmanClient)4 FileSystems (java.nio.file.FileSystems)4 StandardWatchEventKinds (java.nio.file.StandardWatchEventKinds)4 HashSet (java.util.HashSet)4 List (java.util.List)4