Java Code Examples for java.nio.file.StandardWatchEventKinds

The following examples show how to use java.nio.file.StandardWatchEventKinds. These examples are extracted from open source projects. 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 Project: packagedrone   Source File: Watcher.java    License: Eclipse Public License 1.0 6 votes vote down vote up
@SuppressWarnings ( "unchecked" )
private void handleEvent ( final WatchEvent<?> event )
{
    final Kind<?> kind = event.kind ();

    if ( kind == StandardWatchEventKinds.OVERFLOW )
    {
        // FIXME: full rescan
        return;
    }

    final Path path = this.path.resolve ( ( (WatchEvent<Path>)event ).context () );

    if ( kind == StandardWatchEventKinds.ENTRY_CREATE )
    {
        this.listener.event ( path, Event.ADDED );
    }
    else if ( kind == StandardWatchEventKinds.ENTRY_DELETE )
    {
        this.listener.event ( path, Event.REMOVED );
    }
    else if ( kind == StandardWatchEventKinds.ENTRY_MODIFY )
    {
        this.listener.event ( path, Event.MODIFIED );
    }
}
 
Example 2
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
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 4
Source Project: training   Source File: FileWatchService.java    License: MIT License 6 votes vote down vote up
public static void main(String[] args) throws IOException, InterruptedException {
	Path tmpDir = Paths.get("tmp");
	WatchService watchService = FileSystems.getDefault().newWatchService();
	Path monitoredFolder = tmpDir;
	monitoredFolder.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE);
	
	tmpDir.toFile().mkdirs();
	new FileChanger(tmpDir).start();
	while (true) {
		System.out.println("Waiting for event");
		WatchKey watchKey = watchService.take();
		for (WatchEvent<?> event : watchKey.pollEvents()) {
			System.out.println("Detected event " + event.kind().name() + " on file " + event.context().toString());
		}
		watchKey.reset();
	}
}
 
Example 5
Source Project: rxjava-file   Source File: FileObservable.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns true if and only if the path corresponding to a WatchEvent
 * represents the given file. This will be the case for Create, Modify,
 * Delete events.
 * 
 * @param file
 *            the file to restrict events to
 * @return predicate
 */
private final static Func1<WatchEvent<?>, Boolean> onlyRelatedTo(final File file) {
    return new Func1<WatchEvent<?>, Boolean>() {

        @Override
        public Boolean call(WatchEvent<?> event) {

            final boolean ok;
            if (file.isDirectory())
                ok = true;
            else if (StandardWatchEventKinds.OVERFLOW.equals(event.kind()))
                ok = true;
            else {
                Object context = event.context();
                if (context != null && context instanceof Path) {
                    Path p = (Path) context;
                    Path basePath = getBasePath(file);
                    File pFile = new File(basePath.toFile(), p.toString());
                    ok = pFile.getAbsolutePath().equals(file.getAbsolutePath());
                } else
                    ok = false;
            }
            return ok;
        }
    };
}
 
Example 6
Source Project: ShootOFF   Source File: PluginEngine.java    License: GNU General Public License v3.0 6 votes vote down vote up
public PluginEngine(final PluginListener pluginListener) throws IOException {
	if (pluginListener == null) {
		throw new IllegalArgumentException("pluginListener cannot be null");
	}

	pluginDir = Paths.get(System.getProperty("shootoff.plugins"));
	this.pluginListener = pluginListener;

	if (!Files.exists(pluginDir) && !pluginDir.toFile().mkdirs()) {
		logger.error("The path specified by shootoff.plugins doesn't exist and we couldn't create it.");
		return;
	}

	if (!Files.isDirectory(pluginDir)) {
		logger.error("Can't enumerate existing plugins or watch for new plugins because the "
				+ "shootoff.plugins property is not set to a directory");
	}

	registerDefaultStandardTrainingExercises();
	enumerateExistingPlugins();
	registerDefaultProjectorExercises();

	pluginDir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE);
}
 
Example 7
public ExternalDatabaseLookupService(final Path location) throws IOException {
    final Path absoluteLocation = location.toAbsolutePath();
    final Path locationParent = absoluteLocation.getParent();
    if (null == locationParent) {
        throw new IllegalArgumentException("Could not determine parent directory of GeoIP2 database: " + absoluteLocation);
    }
    this.location = absoluteLocation;
    // Do this first, so that if it fails we don't need to clean up resources.
    databaseLookupService = new AtomicReference<>(new DatabaseLookupService(absoluteLocation));

    // Set things up so that we can reload the database if it changes.
    watcher = FileSystems.getDefault().newWatchService();
    logger.debug("Monitoring {} for changes affecting {}.", locationParent, location);
    locationParent.register(watcher, StandardWatchEventKinds.ENTRY_MODIFY);
    // The database will be loaded in the background.
    backgroundWatcher.execute(this::processWatchEvents);
}
 
Example 8
Source Project: ph-commons   Source File: WatchDir.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Register the given directory with the WatchService
 *
 * @param aDir
 *        Directory to be watched. May not be <code>null</code>.
 */
private void _registerDir (@Nonnull final Path aDir) throws IOException
{
  if (LOGGER.isDebugEnabled ())
    LOGGER.debug ("Register directory " +
                  aDir +
                  (m_bRecursive && !m_bRegisterRecursiveManually ? " (recursively)" : ""));

  final WatchEvent.Kind <?> [] aKinds = new WatchEvent.Kind <?> [] { StandardWatchEventKinds.ENTRY_CREATE,
                                                                     StandardWatchEventKinds.ENTRY_DELETE,
                                                                     StandardWatchEventKinds.ENTRY_MODIFY };

  // throws exception when using with modifiers even if null
  final WatchKey aKey = m_aModifiers != null ? aDir.register (m_aWatcher, aKinds, m_aModifiers)
                                             : aDir.register (m_aWatcher, aKinds);
  m_aKeys.put (aKey, aDir);
}
 
Example 9
Source Project: neoscada   Source File: BaseWatcher.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public StorageWatcher ( final StorageManager storageManager, final BaseWatcher baseWatcher, final Path path, final WatchService watcher ) throws IOException
{
    this.storageManager = storageManager;
    this.baseWatcher = baseWatcher;
    this.watcher = watcher;
    this.path = path;

    this.key = path.register ( watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY );
    baseWatcher.addWatcherMap ( path, this );

    final File nativeDir = new File ( path.toFile (), "native" );
    baseWatcher.addWatcherMap ( nativeDir.toPath (), this );

    logger.debug ( "Checking native dir: {}", nativeDir );

    if ( nativeDir.exists () && nativeDir.isDirectory () )
    {
        this.nativeKey = nativeDir.toPath ().register ( this.watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE );
        check ();
    }
}
 
Example 10
Source Project: neoscada   Source File: BaseWatcher.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public BaseWatcher ( final StorageManager storageManager, final File base ) throws IOException
{
    this.storageManager = storageManager;
    this.base = base.toPath ();
    this.watcher = FileSystems.getDefault ().newWatchService ();

    this.baseKey = base.toPath ().register ( this.watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE );

    logger.debug ( "Checking for initial storages" );

    for ( final File child : this.base.toFile ().listFiles () )
    {
        logger.debug ( "Found initial storage dir - {}", child );
        checkAddStorage ( child.toPath () );
    }

    startWatcher ();
}
 
Example 11
Source Project: jsondb-core   Source File: EventListenerList.java    License: MIT License 6 votes vote down vote up
public void addCollectionFileChangeListener(CollectionFileChangeListener listener) {
  if (null == listeners) {
    listeners = new ArrayList<CollectionFileChangeListener>();

    listeners.add(listener);

    collectionFilesWatcherExecutor = Executors.newSingleThreadExecutor(
        new ThreadFactoryBuilder().setNameFormat("jsondb-files-watcher-thread-%d").build());

    try {
      watcher = dbConfig.getDbFilesPath().getFileSystem().newWatchService();
      dbConfig.getDbFilesPath().register(watcher, StandardWatchEventKinds.ENTRY_CREATE,
                                                  StandardWatchEventKinds.ENTRY_DELETE,
                                                  StandardWatchEventKinds.ENTRY_MODIFY);
    } catch (IOException e) {
      logger.error("Failed to create the WatchService for the dbFiles location", e);
      throw new JsonDBException("Failed to create the WatchService for the dbFiles location", e);
    }

    collectionFilesWatcherExecutor.execute(new CollectionFilesWatcherRunnable());
  } else {
    listeners.add(listener);
  }
}
 
Example 12
Source Project: opc-ua-stack   Source File: DefaultCertificateValidator.java    License: 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 13
Source Project: karate   Source File: FileChangedWatcher.java    License: MIT License 6 votes vote down vote up
public void watch() throws InterruptedException, IOException {
    try {
        final Path directoryPath = file.toPath().getParent();
        final WatchService watchService = FileSystems.getDefault().newWatchService();
        directoryPath.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);
        while (true) {
            final WatchKey wk = watchService.take();
            for (WatchEvent<?> event : wk.pollEvents()) {
                final Path fileChangedPath = (Path) event.context();
                if (fileChangedPath.endsWith(file.getName())) {
                    onModified();
                }
            }
            wk.reset();
        }
    } catch (Exception e) {
        logger.error("exception when handling change of mock file: {}", e.getMessage());
    }
}
 
Example 14
Source Project: opc-ua-stack   Source File: DefaultCertificateValidator.java    License: Apache License 2.0 6 votes vote down vote up
private void createWatchService() {
    try {
        WatchService watchService = FileSystems.getDefault().newWatchService();

        WatchKey trustedKey = trustedDir.toPath().register(
                watchService,
                StandardWatchEventKinds.ENTRY_CREATE,
                StandardWatchEventKinds.ENTRY_DELETE,
                StandardWatchEventKinds.ENTRY_MODIFY
        );

        Thread thread = new Thread(new Watcher(watchService, trustedKey));
        thread.setName("ua-certificate-directory-watcher");
        thread.setDaemon(true);
        thread.start();
    } catch (IOException e) {
        logger.error("Error creating WatchService.", e);
    }
}
 
Example 15
Source Project: RxJavaFileUtils   Source File: MacOSXWatchKey.java    License: Apache License 2.0 6 votes vote down vote up
public MacOSXWatchKey(Path path, AbstractWatchService macOSXWatchService, WatchEvent.Kind<?>[] events) {
    super(macOSXWatchService);
    this.path = path;
    boolean reportCreateEvents = false;
    boolean reportModifyEvents = false;
    boolean reportDeleteEvents = false;

    for (WatchEvent.Kind<?> event : events) {
        if (event == StandardWatchEventKinds.ENTRY_CREATE) {
            reportCreateEvents = true;
        } else if (event == StandardWatchEventKinds.ENTRY_MODIFY) {
            reportModifyEvents = true;
        } else if (event == StandardWatchEventKinds.ENTRY_DELETE) {
            reportDeleteEvents = true;
        }
    }
    this.reportCreateEvents = reportCreateEvents;
    this.reportDeleteEvents = reportDeleteEvents;
    this.reportModifyEvents = reportModifyEvents;
}
 
Example 16
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 17
public MacOSXWatchKey(final Watchable file, final FSEventWatchService service, final WatchEvent.Kind<?>[] events) {
    super(service);
    this.file = file;

    boolean reportCreateEvents = false;
    boolean reportModifyEvents = false;
    boolean reportDeleteEvents = false;

    for(WatchEvent.Kind<?> event : events) {
        if(event == StandardWatchEventKinds.ENTRY_CREATE) {
            reportCreateEvents = true;
        }
        else if(event == StandardWatchEventKinds.ENTRY_MODIFY) {
            reportModifyEvents = true;
        }
        else if(event == StandardWatchEventKinds.ENTRY_DELETE) {
            reportDeleteEvents = true;
        }
    }
    this.reportCreateEvents = reportCreateEvents;
    this.reportDeleteEvents = reportDeleteEvents;
    this.reportModifyEvents = reportModifyEvents;
}
 
Example 18
Source Project: word   Source File: DirectoryWatcher.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    DirectoryWatcher dictionaryWatcher = new DirectoryWatcher(new WatcherCallback(){
        private long lastExecute = System.currentTimeMillis();
        @Override
        public void execute(WatchEvent.Kind<?> kind, String path) {
            if(System.currentTimeMillis() - lastExecute > 1000){                  
                lastExecute = System.currentTimeMillis();
                //刷新词典
                System.out.println("事件:"+kind.name()+" ,路径:"+path);
            }
        }
    }, StandardWatchEventKinds.ENTRY_CREATE,
                StandardWatchEventKinds.ENTRY_MODIFY,
                StandardWatchEventKinds.ENTRY_DELETE);
    //监控DIC目录及其所有子目录的子目录...递归
    dictionaryWatcher.watchDirectoryTree("d:/DIC");
    //只监控DIC2目录
    dictionaryWatcher.watchDirectory("d:/DIC2");
}
 
Example 19
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 20
Source Project: vscode-as3mxml   Source File: ActionScriptServices.java    License: Apache License 2.0 6 votes vote down vote up
private void watchNewSourceOrLibraryPath(Path sourceOrLibraryPath, WorkspaceFolderData folderData)
{
    try
    {
        java.nio.file.Files.walkFileTree(sourceOrLibraryPath, new SimpleFileVisitor<Path>()
        {
            @Override
            public FileVisitResult preVisitDirectory(Path subPath, BasicFileAttributes attrs) throws IOException
            {
                WatchKey watchKey = subPath.register(sourcePathWatcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);
                folderData.sourceOrLibraryPathWatchKeys.put(watchKey, subPath);
                return FileVisitResult.CONTINUE;
            }
        });
    }
    catch (IOException e)
    {
        System.err.println("Failed to watch source or library path: " + sourceOrLibraryPath.toString());
        e.printStackTrace(System.err);
    }
}
 
Example 21
Source Project: openjdk-jdk9   Source File: LotsOfCloses.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Create a WatchService to watch for changes in the given directory
 * and then attempt to close the WatchService and change a registration
 * at the same time.
 */
static void test(Path dir, ExecutorService pool) throws Exception {
    WatchService watcher = FileSystems.getDefault().newWatchService();

    // initial registration
    dir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE);

    // submit tasks to close the WatchService and update the registration
    Future<Void> closeResult;
    Future<Boolean> registerResult;

    if (RAND.nextBoolean()) {
        closeResult = pool.submit(newCloserTask(watcher));
        registerResult = pool.submit(newRegisterTask(watcher, dir));
    } else {
        registerResult = pool.submit(newRegisterTask(watcher, dir));
        closeResult = pool.submit(newCloserTask(watcher));
    }

    closeResult.get();
    registerResult.get();

}
 
Example 22
Source Project: directory-watcher   Source File: MacOSXWatchKey.java    License: Apache License 2.0 6 votes vote down vote up
public MacOSXWatchKey(
    AbstractWatchService macOSXWatchService,
    Iterable<? extends WatchEvent.Kind<?>> events,
    int queueSize) {
  super(macOSXWatchService, null, events, queueSize);
  boolean reportCreateEvents = false;
  boolean reportModifyEvents = false;
  boolean reportDeleteEvents = false;

  for (WatchEvent.Kind<?> event : events) {
    if (event == StandardWatchEventKinds.ENTRY_CREATE) {
      reportCreateEvents = true;
    } else if (event == StandardWatchEventKinds.ENTRY_MODIFY) {
      reportModifyEvents = true;
    } else if (event == StandardWatchEventKinds.ENTRY_DELETE) {
      reportDeleteEvents = true;
    }
  }
  this.reportCreateEvents = reportCreateEvents;
  this.reportDeleteEvents = reportDeleteEvents;
  this.reportModifyEvents = reportModifyEvents;
}
 
Example 23
Source Project: curiostack   Source File: FileWatcher.java    License: MIT License 6 votes vote down vote up
private FileWatcher(Map<Path, Consumer<Path>> registeredPaths) {
  this.registeredPaths = ImmutableMap.copyOf(registeredPaths);
  try {
    watchService = FileSystems.getDefault().newWatchService();
    ImmutableMap.Builder<WatchKey, Path> watchedDirsBuilder = ImmutableMap.builder();
    for (Map.Entry<Path, Consumer<Path>> entry : registeredPaths.entrySet()) {
      Path dir = entry.getKey().getParent();
      WatchKey key =
          dir.register(
              watchService,
              StandardWatchEventKinds.ENTRY_CREATE,
              StandardWatchEventKinds.ENTRY_DELETE,
              StandardWatchEventKinds.ENTRY_MODIFY);
      watchedDirsBuilder.put(key, dir);
    }
    this.watchedDirs = watchedDirsBuilder.build();
  } catch (IOException e) {
    throw new UncheckedIOException("Could not create WatchService.", e);
  }
  executor = Executors.newSingleThreadScheduledExecutor();
}
 
Example 24
@Override
public void handleFileChanged(Kind<?> operation, String fileAbsolutePathname) {
	if (StandardWatchEventKinds.ENTRY_CREATE.equals(operation)) {
		DecryptedFile recentlyRemovedEntry = recentlyRemoved.getIfPresent(fileAbsolutePathname);
		if (recentlyRemovedEntry != null) {
			addOrUpdate(recentlyRemovedEntry);
		}
		return;
	}

	if (StandardWatchEventKinds.ENTRY_DELETE.equals(operation)) {
		remove(fileAbsolutePathname);
		return;
	}

	// Other cases not supported -- not needed
}
 
Example 25
Source Project: gcs   Source File: LibraryWatcher.java    License: Mozilla Public License 2.0 6 votes vote down vote up
public void watchDirs(Set<Path> dirs) {
    if (mWatcher == null) {
        return;
    }
    Map<Path, WatchKey> keep = new HashMap<>();
    for (Path p : dirs) {
        WatchKey key = mPathKeyMap.get(p);
        if (key == null) {
            try {
                keep.put(p, p.register(mWatcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE));
            } catch (IOException exception) {
                Log.error(exception);
            }
        } else {
            keep.put(p, key);
            mPathKeyMap.remove(p);
        }
    }
    for (WatchKey watchKey : mPathKeyMap.values()) {
        watchKey.cancel();
    }
    mPathKeyMap = keep;
}
 
Example 26
Source Project: hottub   Source File: WindowsWatchService.java    License: 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 27
Source Project: cssfx   Source File: PathsWatcher.java    License: Apache License 2.0 6 votes vote down vote up
public void monitor(Path directory, Path sourceFile, Runnable action) {
    if (watchService != null) {
        logger(PathsWatcher.class).info("registering action %d for monitoring %s in %s", System.identityHashCode(action), sourceFile, directory);
        Map<String, List<Runnable>> fileAction = filesActions.computeIfAbsent(
                directory.toString(), (p) -> {
                    try {
                        directory.register(watchService, new WatchEvent.Kind[]{ StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE}, SensitivityWatchEventModifier.HIGH);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return new HashMap<>();
                });

        List<Runnable> actions = fileAction.computeIfAbsent(sourceFile.toString(), k -> new LinkedList<>());
        actions.add(action);
        logger(PathsWatcher.class).debug("%d CSS modification actions registered for file %s", actions.size(), sourceFile);
    } else {
        logger(PathsWatcher.class).warn("no WatchService active, CSS monitoring cannot occur");
    }
}
 
Example 28
Source Project: bazel   Source File: WatchServiceDiffAwareness.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public FileVisitResult preVisitDirectory(Path path, BasicFileAttributes attrs)
    throws IOException {
  // It's important that we register the directory before we visit its children. This way we
  // are guaranteed to see new files/directories either on this #getDiff or the next one.
  // Otherwise, e.g., an intra-build creation of a child directory will be forever missed if it
  // happens before the directory is listed as part of the visitation.
  Preconditions.checkState(path.isAbsolute(), path);
  // On windows we register the root path with ExtendedWatchEventModifier.FILE_TREE
  // Therefore there is no need to register recursive watchers
  if (!isWindows) {
    WatchKey key =
        path.register(
            watchService,
            StandardWatchEventKinds.ENTRY_CREATE,
            StandardWatchEventKinds.ENTRY_MODIFY,
            StandardWatchEventKinds.ENTRY_DELETE);
    watchKeyToDirBiMap.put(key, path);
  }
  visitedAbsolutePaths.add(path);
  return FileVisitResult.CONTINUE;
}
 
Example 29
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 30
Source Project: sldeditor   Source File: FileSystemWatcher.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Instantiates a new file system watcher.
 *
 * @param parent the parent
 * @param path the path
 */
public void addWatch(FileWatcherUpdateInterface parent, Path path) {
    if (path != null) {
        // The directory that has to be watched needs to be registered. Any
        // object that implements the Watchable interface can be registered.

        // Register three events. i.e. whenever a file is created, deleted or
        // modified the watcher gets informed
        try {
            WatchKey key =
                    path.register(
                            watchService,
                            StandardWatchEventKinds.ENTRY_CREATE,
                            StandardWatchEventKinds.ENTRY_DELETE,
                            StandardWatchEventKinds.ENTRY_MODIFY);
            watcherMap.put(key, parent);
        } catch (IOException e) {
            // Do nothing
        }
    }
}