Java Code Examples for java.nio.file.WatchKey#watchable()

The following examples show how to use java.nio.file.WatchKey#watchable() . 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: NioNotifier.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
protected String nextEvent() throws IOException, InterruptedException {
    WatchKey key;
    try {
        key = watcher.take();
    } catch (ClosedWatchServiceException cwse) { // #238261
        @SuppressWarnings({"ThrowableInstanceNotThrown"})
        InterruptedException ie = new InterruptedException();
        throw (InterruptedException) ie.initCause(cwse);
    }
    Path dir = (Path)key.watchable();
           
    String res = dir.toAbsolutePath().toString();
    for (WatchEvent<?> event: key.pollEvents()) {
        if (event.kind() == OVERFLOW) {
            // full rescan
            res = null;
        }
    }
    key.reset();
    return res;
}
 
Example 2
Source File: FileListener.java    From scipio-erp with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    try {
        WatchKey key = scipioWatcher.take();
        while(key != null) {
            for (WatchEvent<?> event : key.pollEvents()) {
                GenericValue userLogin = EntityQuery.use(delegator).from("UserLogin").where("userLoginId", "system").queryOne();
                final Path filename = (Path) event.context();
                Path dir = (Path) key.watchable();
                Path fullPath = dir.resolve(filename);
                String fileType = Files.probeContentType(fullPath);
                if(UtilValidate.isEmpty(fileType))fileType= FilenameUtils.getExtension(fullPath.toString());
                dispatcher.runSync("triggerFileEvent", UtilMisc.toMap("fileEvent",""+event.kind(),"fileLocation",""+fullPath,"fileType",fileType,"eventName",eventName,"eventRoot",eventRoot,"userLogin",userLogin));
            }
            key.reset();
            key = scipioWatcher.take();
        }
    } catch (Exception e) {
        Debug.logWarning("Could not fire FileListener Event"+e, module);
    }
}
 
Example 3
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 4
Source File: FileSystemWatcher.java    From sldeditor with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Process watch events.
 *
 * @param key the key
 * @param keys the keys
 */
private void processWatchEvents(WatchKey key, List<WatchEvent<?>> keys) {
    for (WatchEvent<?> watchEvent : keys) {

        Kind<?> watchEventKind = watchEvent.kind();
        // Sometimes events are created faster than they are registered
        // or the implementation may specify a maximum number of events
        // and further events are discarded. In these cases an event of
        // kind overflow is returned. We ignore this case for now
        if (watchEventKind == StandardWatchEventKinds.OVERFLOW) {
            continue;
        }

        Path dir = (Path) key.watchable();
        Path fullPath = dir.resolve((Path) watchEvent.context());

        FileWatcherUpdateInterface parentObj = watcherMap.get(key);
        if (parentObj != null) {
            if (watchEventKind == StandardWatchEventKinds.ENTRY_CREATE) {
                // A new file has been created
                parentObj.fileAdded(fullPath);
            } else if (watchEventKind == StandardWatchEventKinds.ENTRY_MODIFY) {
                ReloadManager.getInstance().fileModified(fullPath);
                // The file has been modified.
                parentObj.fileModified(fullPath);
            } else if (watchEventKind == StandardWatchEventKinds.ENTRY_DELETE) {
                parentObj.fileDeleted(fullPath);
            }
        }
    }
}
 
Example 5
Source File: BaseWatcher.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
private void checkKey ( final WatchKey key ) throws IOException
{
    if ( this.baseKey == key )
    {
        checkBaseEvents ( key, key.pollEvents () );
        if ( !this.baseKey.reset () )
        {
            logger.warn ( "Base key got invalidated" );
            this.watcher.close ();
        }
    }
    else
    {
        final Path base = (Path)key.watchable ();

        if ( ! ( key.watchable () instanceof Path ) )
        {
            // don't reset
            return;
        }

        final StorageWatcher w = this.watcherMap.get ( base );
        if ( w == null )
        {
            logger.info ( "Event for unknown target: {}", base );
            // don't reset
            return;
        }
        try
        {
            for ( final WatchEvent<?> event : key.pollEvents () )
            {
                if ( ! ( event.context () instanceof Path ) )
                {
                    continue;
                }

                w.handleEvent ( (Path)key.watchable (), event );
            }
        }
        finally
        {
            if ( !key.reset () )
            {
                w.dispose ();
            }
        }
    }
}
 
Example 6
Source File: UnixSocketFile.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args)
    throws InterruptedException, IOException {

    // Use 'which' to verify that 'nc' is available and skip the test
    // if it is not.
    Process proc = Runtime.getRuntime().exec("which nc");
    InputStream stdout = proc.getInputStream();
    int b = stdout.read();
    proc.destroy();
    if (b == -1) {
        System.err.println("Netcat command unavailable; skipping test.");
        return;
    }

    // Create a new sub-directory of the nominal test directory in which
    // 'nc' will create the socket file.
    String testSubDir = System.getProperty("test.dir", ".")
        + File.separator + TEST_SUB_DIR;
    Path socketTestDir = Paths.get(testSubDir);
    Files.createDirectory(socketTestDir);

    // Set the path of the socket file.
    String socketFilePath = testSubDir + File.separator
        + SOCKET_FILE_NAME;

    // Create a process which executes the nc (netcat) utility to create
    // a socket file at the indicated location.
    FileSystem fs = FileSystems.getDefault();
    try (WatchService ws = fs.newWatchService()) {
        // Watch the test sub-directory to receive notification when an
        // entry, i.e., the socket file, is added to the sub-directory.
        WatchKey wk = socketTestDir.register(ws,
                StandardWatchEventKinds.ENTRY_CREATE);

        // Execute the 'nc' command.
        proc = Runtime.getRuntime().exec(CMD_BASE + " " + socketFilePath);

        // Wait until the socket file is created.
        WatchKey key = ws.take();
        if (key != wk) {
            throw new RuntimeException("Unknown entry created - expected: "
                + wk.watchable() + ", actual: " + key.watchable());
        }
        wk.cancel();
    }

    // Verify that the socket file in fact exists.
    Path socketPath = fs.getPath(socketFilePath);
    if (!Files.exists(socketPath)) {
        throw new RuntimeException("Socket file " + socketFilePath
            + " was not created by \"nc\" command.");
    }

    // Retrieve the most recent access and modification times of the
    // socket file; print the values.
    BasicFileAttributeView attributeView = Files.getFileAttributeView(
            socketPath, BasicFileAttributeView.class);
    BasicFileAttributes oldAttributes = attributeView.readAttributes();
    FileTime oldAccessTime = oldAttributes.lastAccessTime();
    FileTime oldModifiedTime = oldAttributes.lastModifiedTime();
    System.out.println("Old times: " + oldAccessTime
        + " " + oldModifiedTime);

    // Calculate the time to which the access and modification times of the
    // socket file will be changed.
    FileTime newFileTime =
        FileTime.fromMillis(oldAccessTime.toMillis() + 1066);

    try {
        // Set the access and modification times of the socket file.
        attributeView.setTimes(newFileTime, newFileTime, null);

        // Retrieve the updated access and modification times of the
        // socket file; print the values.
        FileTime newAccessTime = null;
        FileTime newModifiedTime = null;
        BasicFileAttributes newAttributes = attributeView.readAttributes();
        newAccessTime = newAttributes.lastAccessTime();
        newModifiedTime = newAttributes.lastModifiedTime();
        System.out.println("New times: " + newAccessTime + " "
            + newModifiedTime);

        // Verify that the updated times have the expected values.
        if ((newAccessTime != null && !newAccessTime.equals(newFileTime))
            || (newModifiedTime != null
                && !newModifiedTime.equals(newFileTime))) {
            throw new RuntimeException("Failed to set correct times.");
        }
    } finally {
        // Destry the process running netcat and delete the socket file.
        proc.destroy();
        Files.delete(socketPath);
    }
}