Java Code Examples for java.nio.file.StandardWatchEventKinds#ENTRY_CREATE

The following examples show how to use java.nio.file.StandardWatchEventKinds#ENTRY_CREATE . 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 dragonwell8_jdk 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 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: WindowsWatchService.java    From openjdk-jdk8u 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 4
Source File: MacOSXWatchKey.java    From RxJavaFileUtils with 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 5
Source File: WindowsWatchService.java    From jdk8u-jdk 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 6
Source File: WindowsWatchService.java    From openjdk-jdk8u-backup 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 7
Source File: DirectoryWatcher.java    From word with 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 8
Source File: WatchDir.java    From ph-commons with 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 File: MacOSXWatchKey.java    From directory-watcher with 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 10
Source File: WindowsWatchService.java    From openjdk-jdk9 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 11
Source File: ConfigUpdater.java    From cellery-security with Apache License 2.0 5 votes vote down vote up
public void run() {

        log.info("Running configuration updater..");
        String configFilePath = CellStsUtils.getConfigFilePath();
        Path directoryPath = Paths.get(configFilePath.substring(0, configFilePath.lastIndexOf("/")));
        try {
            while (true) {
                WatchService watcher = directoryPath.getFileSystem().newWatchService();
                directoryPath.register(watcher, StandardWatchEventKinds.ENTRY_CREATE,
                        StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);

                log.debug("Waiting for config file change");
                WatchKey watckKey = watcher.take();

                List<WatchEvent<?>> events = watckKey.pollEvents();
                log.debug("Received events: ....");
                for (WatchEvent event : events) {
                    if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {
                        log.info("Updating file on {} event", StandardWatchEventKinds.ENTRY_CREATE);
                        CellStsUtils.buildCellStsConfiguration();
                        CellStsUtils.readUnsecuredContexts();
                    }
                    if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) {
                        log.info("Updating file on {} event", StandardWatchEventKinds.ENTRY_MODIFY);
                        CellStsUtils.buildCellStsConfiguration();
                        CellStsUtils.readUnsecuredContexts();
                    }
                }

            }
        } catch (IOException | InterruptedException | CelleryCellSTSException e) {
            log.error("Error while updating configurations on file change ", e);
        }
    }
 
Example 12
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 13
Source File: Watcher.java    From scelight with Apache License 2.0 4 votes vote down vote up
@Override
public void customRun() {
	while ( mayContinue() ) {
		final WatchKey key = watcher.poll();
		
		if ( key != null ) {
			for ( final WatchEvent< ? > event : key.pollEvents() ) {
				final Kind< ? > kind = event.kind();
				
				if ( kind == StandardWatchEventKinds.OVERFLOW ) {
					Env.LOGGER.debug( "Overflow WatchEvent detected." );
					continue; // Ignore these
				}
				
				if ( kind == StandardWatchEventKinds.ENTRY_CREATE ) {
					final FolderInfo info;
					synchronized ( keyInfoMap ) {
						info = keyInfoMap.get( key );
					}
					
					final Path file = info.path.resolve( (Path) event.context() ); // Event context is the path
					synchronized ( ignoredPathMap ) {
						final IgnoredPathInfo ignoredInfo = ignoredPathMap.get( file );
						if ( ignoredInfo != null ) {
							removeIgnoredPath( file );
							// Only take path really ignored (valid),
							// if it was added to be ignored no more than 1 minute ago
							if ( ignoredInfo.firstDate + Utils.MS_IN_MIN > System.currentTimeMillis() )
								continue;
						}
					}
					if ( Env.LOGGER.testTrace() )
						Env.LOGGER.trace( "[Watcher] Detected new entry: " + file );
					
					// If the new entry is a folder and parent is watched recursively, add the new entry too (recursively)
					if ( Files.isDirectory( file, LinkOption.NOFOLLOW_LINKS ) ) {
						if ( info.recursive )
							watchFolder( file, info.recursive );
					} else {
						// Potential new replay
						if ( RepUtils.hasRepExt( file ) )
							new NewReplayHandlerJob( file, info ).start();
					}
				}
			}
			
			// Reset the key - required to receive further watch events!
			if ( !key.reset() ) { // reset() returns whether the key is still valid
				// Key became invalid (e.g. folder deleted), remove it
				synchronized ( keyInfoMap ) {
					keyInfoMap.remove( key );
				}
			}
			
		} else
			checkedSleep( 20 );
	}
}
 
Example 14
Source File: BeatmapWatchService.java    From opsu-dance with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Process all events for keys queued to the watcher
 */
private void processEvents() {
	while (true) {
		// wait for key to be signaled
		WatchKey key;
		try {
			key = watcher.take();
		} catch (InterruptedException | ClosedWatchServiceException e) {
			return;
		}

		Path dir = keys.get(key);
		if (dir == null)
			continue;

		boolean isPaused = paused;
		for (WatchEvent<?> event : key.pollEvents()) {
			WatchEvent.Kind<?> kind = event.kind();
			if (kind == StandardWatchEventKinds.OVERFLOW)
				continue;

			// context for directory entry event is the file name of entry
			WatchEvent<Path> ev = cast(event);
			Path name = ev.context();
			Path child = dir.resolve(name);
			//System.out.printf("%s: %s\n", kind.name(), child);

			// fire listeners
			if (!isPaused) {
				for (BeatmapWatchServiceListener listener : listeners)
					listener.eventReceived(kind, child);
			}

			// if directory is created, then register it and its sub-directories
			if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
				if (Files.isDirectory(child, LinkOption.NOFOLLOW_LINKS))
					registerAll(child);
			}
		}

		// reset key and remove from set if directory no longer accessible
		if (!key.reset()) {
			keys.remove(key);
			if (keys.isEmpty())
				break;  // all directories are inaccessible
		}
	}
}
 
Example 15
Source File: PollingWatchService.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Register the given file with this watch service
 */
@Override
WatchKey register(final Path path,
                  WatchEvent.Kind<?>[] events,
                  WatchEvent.Modifier... modifiers)
     throws IOException
{
    // check events - CCE will be thrown if there are invalid elements
    final Set<WatchEvent.Kind<?>> eventSet = new HashSet<>(events.length);
    for (WatchEvent.Kind<?> event: events) {
        // standard events
        if (event == StandardWatchEventKinds.ENTRY_CREATE ||
            event == StandardWatchEventKinds.ENTRY_MODIFY ||
            event == StandardWatchEventKinds.ENTRY_DELETE)
        {
            eventSet.add(event);
            continue;
        }

        // OVERFLOW is ignored
        if (event == StandardWatchEventKinds.OVERFLOW) {
            continue;
        }

        // null/unsupported
        if (event == null)
            throw new NullPointerException("An element in event set is 'null'");
        throw new UnsupportedOperationException(event.name());
    }
    if (eventSet.isEmpty())
        throw new IllegalArgumentException("No events to register");

    // Extended modifiers may be used to specify the sensitivity level
    int sensitivity = 10;
    if (modifiers.length > 0) {
        for (WatchEvent.Modifier modifier: modifiers) {
            if (modifier == null)
                throw new NullPointerException();

            if (ExtendedOptions.SENSITIVITY_HIGH.matches(modifier)) {
                sensitivity = ExtendedOptions.SENSITIVITY_HIGH.parameter();
            } else if (ExtendedOptions.SENSITIVITY_MEDIUM.matches(modifier)) {
                sensitivity = ExtendedOptions.SENSITIVITY_MEDIUM.parameter();
            } else if (ExtendedOptions.SENSITIVITY_LOW.matches(modifier)) {
                sensitivity = ExtendedOptions.SENSITIVITY_LOW.parameter();
            } else {
                throw new UnsupportedOperationException("Modifier not supported");
            }
        }
    }

    // check if watch service is closed
    if (!isOpen())
        throw new ClosedWatchServiceException();

    // registration is done in privileged block as it requires the
    // attributes of the entries in the directory.
    try {
        int value = sensitivity;
        return AccessController.doPrivileged(
            new PrivilegedExceptionAction<PollingWatchKey>() {
                @Override
                public PollingWatchKey run() throws IOException {
                    return doPrivilegedRegister(path, eventSet, value);
                }
            });
    } catch (PrivilegedActionException pae) {
        Throwable cause = pae.getCause();
        if (cause != null && cause instanceof IOException)
            throw (IOException)cause;
        throw new AssertionError(pae);
    }
}
 
Example 16
Source File: FileMonitorJdkImpl.java    From util4j with Apache License 2.0 4 votes vote down vote up
public void watchRNDir(Path path) throws IOException, InterruptedException {  
    try (WatchService watchService = FileSystems.getDefault().newWatchService()) {  
        //给path路径加上文件观察服务  
        path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE,  
                StandardWatchEventKinds.ENTRY_MODIFY,  
                StandardWatchEventKinds.ENTRY_DELETE);  
        // start an infinite loop  
        while (true) {  
            // retrieve and remove the next watch key  
            final WatchKey key = watchService.take();  
            // get list of pending events for the watch key  
            for (WatchEvent<?> watchEvent : key.pollEvents()) {  
                // get the kind of event (create, modify, delete)  
                final Kind<?> kind = watchEvent.kind();  
                // handle OVERFLOW event  
                if (kind == StandardWatchEventKinds.OVERFLOW) {  
                    continue;  
                }  
                //创建事件  
                if(kind == StandardWatchEventKinds.ENTRY_CREATE){  
                      
                }  
                //修改事件  
                if(kind == StandardWatchEventKinds.ENTRY_MODIFY){  
                      
                }  
                //删除事件  
                if(kind == StandardWatchEventKinds.ENTRY_DELETE){  
                      
                }  
                // get the filename for the event  
                @SuppressWarnings("unchecked")
	final WatchEvent<Path> watchEventPath = (WatchEvent<Path>) watchEvent;  
                final Path filename = watchEventPath.context();  
                // print it out  
                System.out.println(kind + " -> " + filename);  
  
            }  
            // reset the keyf  
            boolean valid = key.reset();  
            // exit loop if the key is not valid (if the directory was  
            // deleted, for  
            if (!valid) {  
                break;  
            }  
        }  
    }  
}
 
Example 17
Source File: DirWatcher.java    From Jupiter with GNU General Public License v3.0 4 votes vote down vote up
/** {@inheritDoc} */
@Override
public Void call() {
  registerAll(FS.toPath(Settings.USER_DIR.get()));
  while(!isCancelled()) {
    // wait for key to be signalled
    WatchKey key;
    try {
      key = watcher.take();
    } catch (InterruptedException e) {
      break;
    }
    // get path
    Path dir = keys.get(key);
    // ignore unregistered keys
    if (dir == null) {
      continue;
    }
    // get events
    for (WatchEvent<?> event : key.pollEvents()) {
      WatchEvent.Kind kind = event.kind();
      // ignore overflow events
      if (kind == StandardWatchEventKinds.OVERFLOW) {
        continue;
      }
      @SuppressWarnings("unchecked")
      File file = dir.resolve(((WatchEvent<Path>) event).context()).toFile();
      // handle event
      if (kind == StandardWatchEventKinds.ENTRY_CREATE && file.isDirectory()) {
        pcs.firePropertyChange("create_dir", "create", file);
        // register new keys
        registerAll(file.toPath());
      } else if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
        pcs.firePropertyChange("create_file", "create", file);
      } else if (kind == StandardWatchEventKinds.ENTRY_DELETE && file.isDirectory()) {
        pcs.firePropertyChange("delete_dir", "delete", file);
      } else if (kind == StandardWatchEventKinds.ENTRY_DELETE) {
        pcs.firePropertyChange("delete_file", "delete", file);
      } else if (kind == StandardWatchEventKinds.ENTRY_MODIFY && file.isDirectory()) {
        pcs.firePropertyChange("modify_dir", "modify", file);
      } else if (kind == StandardWatchEventKinds.ENTRY_MODIFY) {
        pcs.firePropertyChange("modify_file", "modify", file);
      }
    }
    boolean valid = key.reset();
    if (!valid) {
      keys.remove(key);
      if (keys.isEmpty()) {
        break;
      }
    }
  }
  return null;
}
 
Example 18
Source File: PathsWatcher.java    From cssfx with Apache License 2.0 4 votes vote down vote up
public void watch() {
    watcherThread = new Thread(new Runnable() {
        @Override
        public void run() {
            logger(PathsWatcher.class).info("starting to monitor physical files");
            while (true) {
                WatchKey key;
                try {
                    key = watchService.take();
                } catch (InterruptedException ex) {
                    return;
                }
                Path directory = ((Path) key.watchable()).toAbsolutePath().normalize();

                for (WatchEvent<?> event : key.pollEvents()) {
                    WatchEvent.Kind<?> kind = event.kind();
                    logger(PathsWatcher.class).debug("'%s' change detected in directory %s", kind, directory);

                    if (kind == StandardWatchEventKinds.ENTRY_MODIFY || kind == StandardWatchEventKinds.ENTRY_CREATE || kind == StandardWatchEventKinds.ENTRY_DELETE) {
                        // it is a modification
                        @SuppressWarnings("unchecked")
                        WatchEvent<Path> ev = (WatchEvent<Path>) event;
                        Path modifiedFile = directory.resolve(ev.context()).toAbsolutePath().normalize();

                        if (filesActions.containsKey(directory.toString())) {
                            logger(PathsWatcher.class).debug("file: %s was modified", modifiedFile.getFileName());
                            Map<String, List<Runnable>> filesAction = filesActions.get(directory.toString());
                            if (filesAction.containsKey(modifiedFile.toString())) {
                                logger(PathsWatcher.class).debug("file is monitored");
                                List<Runnable> actions = filesAction.get(modifiedFile.toString());
                                logger(PathsWatcher.class).debug("%d CSS modification will be performed ", actions.size());
                                
                                for (Runnable action : actions) {
                                    action.run();
                                }
                            } else {
                                logger(PathsWatcher.class).debug("file is not monitored");
                            }
                        }
                    }
                }

                boolean valid = key.reset();
                if (!valid) {
                    break;
                }
            }
        }
    }, "CSSFX-file-monitor");
    watcherThread.setDaemon(true);
    watcherThread.start();
}
 
Example 19
Source File: PrinterTrayWatcher.java    From Java-Coding-Problems with MIT License 4 votes vote down vote up
public void watchTray(Path path) throws IOException, InterruptedException {
    try (WatchService watchService = FileSystems.getDefault().newWatchService()) {
        path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE,
                StandardWatchEventKinds.ENTRY_DELETE);

        System.out.println("Printer watcher ready ...");
        
        //start an infinite loop
        while (true) {

            //retrieve and remove the next watch key
            final WatchKey key = watchService.poll(10, TimeUnit.SECONDS);

            //get list of events for the watch key
            if (key != null) {
                for (WatchEvent<?> watchEvent : key.pollEvents()) {

                    //get the filename for the event
                    final WatchEvent<Path> watchEventPath = (WatchEvent<Path>) watchEvent;
                    final Path filename = watchEventPath.context();

                    //get the kind of event (create, modify, delete)
                    final Kind<?> kind = watchEvent.kind();

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

                    if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
                        System.out.println("Sending the document to print -> " + filename);

                        Runnable task = new Printer(path.resolve(filename));
                        Thread worker = new Thread(task);

                        //we can set the name of the thread			
                        worker.setName(path.resolve(filename).toString());

                        //store the thread and the path
                        threads.put(worker, path.resolve(filename));

                        //start the thread
                        worker.start();
                    }

                    if (kind == StandardWatchEventKinds.ENTRY_DELETE) {
                        System.out.println(filename + " was successfully printed!");
                    }
                }

                //reset the key
                boolean valid = key.reset();

                //exit loop if the key is not valid (if the directory was deleted, per example)
                if (!valid) {
                    threads.clear();
                    break;
                }
            }

            if (!threads.isEmpty()) {
                for (Iterator<Map.Entry<Thread, Path>> it = 
                        threads.entrySet().iterator(); it.hasNext();) {
                    Map.Entry<Thread, Path> entry = it.next();
                    if (entry.getKey().getState() == Thread.State.TERMINATED) {
                        Files.deleteIfExists(entry.getValue());
                        it.remove();
                    }
                }
            }
        }
    }
}
 
Example 20
Source File: VideoCaptureWatcher.java    From Java-Coding-Problems with MIT License 4 votes vote down vote up
public void watchVideoCaptureSystem(Path path) throws IOException, InterruptedException {

        try (WatchService watchService = FileSystems.getDefault().newWatchService()) {
            path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);

            System.out.println("Watching captures ...");
            
            //start an infinite loop           
            while (true) {

                //retrieve and remove the next watch key
                final WatchKey key = watchService.poll(11, TimeUnit.SECONDS);

                if (key == null) {
                    throw new IllegalStateException("The video capture system is jammed. Missed capture!");                    
                }

                //get list of events for the watch key
                for (WatchEvent<?> watchEvent : key.pollEvents()) {

                    //get the kind of event (create, modify, delete)
                    final Kind<?> kind = watchEvent.kind();

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

                    if (kind == StandardWatchEventKinds.ENTRY_CREATE) {

                        //get the filename for the event
                        final WatchEvent<Path> watchEventPath = (WatchEvent<Path>) watchEvent;
                        final Path filename = watchEventPath.context();
                        final Path child = path.resolve(filename);

                        if (Files.probeContentType(child).equals("image/jpeg")) {

                            //print it out the video capture time
                            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
                            System.out.println("Video capture successfully at: " + dateFormat.format(new Date()));
                        } else {
                            Files.deleteIfExists(child);
                            throw new IllegalStateException("Unauthorized file type has been added!");  
                        }
                    }

                    //reset the key
                    boolean valid = key.reset();

                    //exit loop if the key is not valid (if the directory was deleted, per example)
                    if (!valid) {
                        break;
                    }
                }
            }
        }
    }