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

The following examples show how to use java.nio.file.WatchKey#reset() . 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: Main.java    From java-cheat with GNU General Public License v3.0 6 votes vote down vote up
public static void main(final String[] args) throws InterruptedException, IOException {
    final WatchService watchService = FileSystems.getDefault().newWatchService();
    Paths.get(WATCH_DIR).register(
            watchService,
            StandardWatchEventKinds.ENTRY_CREATE,
            StandardWatchEventKinds.ENTRY_DELETE,
            StandardWatchEventKinds.ENTRY_MODIFY);
    for (;;) {
        final WatchKey key = watchService.take();
        for (final WatchEvent<?> event : key.pollEvents()) {
            final WatchEvent.Kind kind = event.kind();
            // TODO
            if (kind == StandardWatchEventKinds.OVERFLOW) continue;
            System.out.format("%s: %s\n", kind.name(), cast(event).context());
        }
        key.reset();
    }
}
 
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: AuthHeaderStrategyMount.java    From spring-cloud-huawei with Apache License 2.0 5 votes vote down vote up
public void run() {
  while (true) {
    try {
      WatchKey watchKey = service.take();
      // 清理掉已发生的事件,否则会导致事件遗留,进入死循环
      watchKey.pollEvents();
      synchronized (this) {
        createAuthHeaders();
      }
      watchKey.reset();
    } catch (InterruptedException e) {
      LOGGER.error("error occured. detail : {}", e.getMessage());
    }
  }
}
 
Example 4
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 5
Source File: AbstractMergeWatcher.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
protected void scanner ()
{
    logger.trace ( "Watching for events" );
    while ( true )
    {
        WatchKey key = null;
        try
        {
            key = this.ws.take ();
            logger.trace ( "Took events: {}", key.watchable () );

            final List<WatchEvent<?>> events = key.pollEvents ();
            for ( final WatchEvent<?> evt : events )
            {
                processEvent ( evt );
            }
        }
        catch ( final InterruptedException | ClosedWatchServiceException e )
        {
            return;
        }
        finally
        {
            if ( key != null )
            {
                key.reset ();
            }
        }
    }
}
 
Example 6
Source File: OSVDataWatcher.java    From osv with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected Void doInBackground() throws Exception {

	System.out.println("Watcher starting");

	while (!(new File("/tmp/osvdatasimulator")).isDirectory()) {
		Thread.sleep(1000);
	}

	System.out.println("Watcher ready");

	WatchService watchService = FileSystems.getDefault().newWatchService();
	Path directory = Paths.get("/tmp/osvdatasimulator");
	directory.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);
	WatchKey key = null;

	while (true) {
		key = watchService.take();
		if (key != null) {
			List<WatchEvent<?>> eventList = key.pollEvents();

			for (int i = 0; i < eventList.size(); i++) {
				publish(eventList.get(i).context().toString());
			}

			key.reset();
		}
	}
}
 
Example 7
Source File: CsvFolderReader.java    From baleen with Apache License 2.0 5 votes vote down vote up
/**
 * Every time doHasNext() is called, check the WatchService for new events and add all new events
 * to the queue. Then return true if there are files on the queue, or false otherwise.
 *
 * <p>If the event indicates that a file has been deleted, ensure it is removed from the queue.
 */
@Override
public boolean doHasNext() throws IOException, CollectionException {
  WatchKey key;
  while ((key = watcher.poll()) != null) {
    for (WatchEvent<?> event : key.pollEvents()) {
      processEvent(key, event);
      getMonitor().meter("events").mark();
    }

    key.reset();
  }

  return !currLines.isEmpty() || !queue.isEmpty();
}
 
Example 8
Source File: DirectoryWatcher.java    From quarks with Apache License 2.0 5 votes vote down vote up
/**
 * Waits for files to become available 
 * and adds them through {@link #sortAndSubmit(List)}
 * to the pendingNames list which the iterator pulls from.
 */
@SuppressWarnings("unchecked")
private void watchForFiles() throws Exception {

    WatchKey key = watcher.take();

    List<File> newFiles = new ArrayList<>();
    boolean needFullScan = false;
    for (WatchEvent<?> watchEvent : key.pollEvents()) {

        if (ENTRY_CREATE == watchEvent.kind()) {
            Path newPath = ((WatchEvent<Path>) watchEvent).context();
            File newFile = toAbsFile(newPath);
            if (accept(newFile))
                newFiles.add(newFile);
        } else if (ENTRY_DELETE == watchEvent.kind()) {
            Path deletedPath = ((WatchEvent<Path>) watchEvent).context();
            File deletedFile = toAbsFile(deletedPath);
            seenFiles.remove(deletedFile.getName());
        } else if (OVERFLOW == watchEvent.kind()) {
            needFullScan = true;
        }
    }
    key.reset();

    if (needFullScan) {
        Collections.addAll(newFiles, dirFile.listFiles(this));
    }
    sortAndSubmit(newFiles);
}
 
Example 9
Source File: CostFedSummaryProvider.java    From CostFed with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void run() {
    for (;;) {
        WatchKey key;
        try {
            key = watcher.take();
        } catch (InterruptedException x) {
            return;
        }
        
        for (WatchEvent<?> event: key.pollEvents()) {
            WatchEvent.Kind<?> kind = event.kind();
            if (kind == java.nio.file.StandardWatchEventKinds.OVERFLOW) {
                continue;
            }
            
            if (kind == java.nio.file.StandardWatchEventKinds.ENTRY_CREATE || kind == java.nio.file.StandardWatchEventKinds.ENTRY_DELETE || kind == java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY) {
                rebuildSummary();
            }
        }
        
        boolean valid = key.reset();
        if (!valid) {
            break;
        }
    }
}
 
Example 10
Source File: AbstractConfigService.java    From java-trader with Apache License 2.0 5 votes vote down vote up
private void watchThreadFunc() {
    logger.info("Config watch thread is started");
    while(state!=ServiceState.Stopped) {
        WatchKey watchKey = null;
        try{
            watchKey = watcher.poll(100, TimeUnit.MILLISECONDS);
        }catch(Throwable t) {}
        if ( watchKey==null ) {
            Thread.yield();
            continue;
        }
        ConfigProviderEntry providerEntry = getEntryByFile(watchKey);
        if ( providerEntry!=null ) {
            for(WatchEvent<?> event:watchKey.pollEvents()) {
                WatchEvent<Path> ev = (WatchEvent<Path>) event;
                WatchEvent.Kind<?> kind = event.kind();
                Path filename = ev.context();
                if (kind == java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY
                && filename.toString().equals(providerEntry.file.getName())) {
                    doReload(providerEntry);
                }
            }
        }
        watchKey.reset();
    }
    logger.info("Config watch thread is stopped");
}
 
Example 11
Source File: Watcher.java    From packagedrone with Eclipse Public License 1.0 5 votes vote down vote up
private void process () throws IOException
{
    logger.warn ( "Start watching: {}", this.path );

    try ( final WatchService watcher = this.path.getFileSystem ().newWatchService () )
    {
        this.path.register ( watcher, ENTRY_CREATE, ENTRY_MODIFY, ENTRY_DELETE );

        processExisting ( this.path );

        for ( ;; )
        {
            WatchKey key;
            try
            {
                key = watcher.take ();
            }
            catch ( final InterruptedException e )
            {
                return;
            }

            for ( final WatchEvent<?> event : key.pollEvents () )
            {
                logger.debug ( "Handle event: {} - {}", event.kind (), event.context () );
                handleEvent ( event );
            }

            if ( !key.reset () )
            {
                throw new RuntimeException ( "Key got cancelled" );
            }
        }
    }
}
 
Example 12
Source File: TestWatchService.java    From jsr203-hadoop with Apache License 2.0 4 votes vote down vote up
/**
 * Simple test of each of the standard events
 * <p>
 * This is a complete test that checks many feature.
 * TODO split this one in 3 test (create/modify/delete).
 */
@Test
@Ignore
public void testEvents() throws IOException {
  Path dir = Paths.get(clusterUri);


  Path name = dir.resolve("foo");
  System.out.println("name: " + name);

  try (WatchService watcher = dir.getFileSystem().newWatchService()) {
    // --- ENTRY_CREATE ---

    // register for event
    System.out.format("register %s for ENTRY_CREATE\n", dir);
    WatchKey myKey = dir.register(watcher,
        new WatchEvent.Kind<?>[] { ENTRY_CREATE });
    Assert.assertTrue(myKey.isValid());
    Assert.assertEquals(dir, myKey.watchable());

    // create file
    Path file = dir.resolve("foo");
    System.out.format("create %s\n", file);
    Files.createFile(file);

    // remove key and check that we got the ENTRY_CREATE event
    takeExpectedKey(watcher, myKey);
    checkExpectedEvent(myKey.pollEvents(),
        StandardWatchEventKinds.ENTRY_CREATE, name);

    System.out.println("reset key");
    if (!myKey.reset())
      throw new RuntimeException("key has been cancalled");

    System.out.println("OKAY");

    // --- ENTRY_DELETE ---

    System.out.format("register %s for ENTRY_DELETE\n", dir);
    WatchKey deleteKey = dir.register(watcher,
        new WatchEvent.Kind<?>[] { ENTRY_DELETE });
    //if (deleteKey != myKey)
    //  throw new RuntimeException("register did not return existing key");
    Assert.assertTrue(deleteKey.isValid());
    Assert.assertEquals(dir, deleteKey.watchable());

    System.out.format("delete %s\n", file);
    Files.delete(file);
    takeExpectedKey(watcher, myKey);
    checkExpectedEvent(myKey.pollEvents(),
        StandardWatchEventKinds.ENTRY_DELETE, name);

    System.out.println("reset key");
    if (!myKey.reset())
      throw new RuntimeException("key has been cancalled");

    System.out.println("OKAY");

    // create the file for the next test
    Files.createFile(file);

    // --- ENTRY_MODIFY ---

    System.out.format("register %s for ENTRY_MODIFY\n", dir);
    WatchKey newKey = dir.register(watcher,
        new WatchEvent.Kind<?>[] { ENTRY_MODIFY });
    if (newKey != myKey)
      throw new RuntimeException("register did not return existing key");
    Assert.assertTrue(newKey.isValid());
    Assert.assertEquals(dir, newKey.watchable());

    System.out.format("update: %s\n", file);
    try (OutputStream out = Files.newOutputStream(file,
        StandardOpenOption.APPEND)) {
      out.write("I am a small file".getBytes("UTF-8"));
    }

    // remove key and check that we got the ENTRY_MODIFY event
    takeExpectedKey(watcher, myKey);
    checkExpectedEvent(myKey.pollEvents(),
        StandardWatchEventKinds.ENTRY_MODIFY, name);
    System.out.println("OKAY");

    // done
    Files.delete(file);
  }
}
 
Example 13
Source File: MultipleFilesWatcher.java    From pgptool with GNU General Public License v3.0 4 votes vote down vote up
private Thread buildThreadAndStart() {
	Thread ret = new Thread("FilesWatcher-" + watcherName) {
		@Override
		public void run() {
			log.debug("FileWatcher thread started " + watcherName);
			boolean continueWatching = true;
			while (continueWatching) {
				WatchKey key;
				try {
					idleIfNoKeysRegistered();
					key = watcher.take();
					// NOTE: Since we're watching only one folder we assume
					// that there will be only one key for our folder
				} catch (ClosedWatchServiceException cwe) {
					log.error("ClosedWatchServiceException fired, stoppign thread.", cwe);
					return;
				} catch (InterruptedException x) {
					log.debug("FileWatcher thread stopped by InterruptedException");
					return;
				} catch (Throwable t) {
					log.error("Unexpected exception while checking for updates on watched file", t);
					return;
				}

				BaseFolder baseFolder = null;
				synchronized (watcherName) {
					baseFolder = keys.get(key);
				}
				if (baseFolder == null) {
					key.cancel();
					continue;
				}

				for (WatchEvent<?> event : key.pollEvents()) {
					// Context for directory entry event is the file name of
					// entry
					WatchEvent<Path> ev = cast(event);
					Path name = ev.context();
					Path child = baseFolder.path.resolve(name);
					String relativeFilename = FilenameUtils.getName(child.toString());
					if (!baseFolder.interestedFiles.contains(relativeFilename)
							&& !event.kind().equals(ENTRY_CREATE)) {
						continue;
					}

					// print out event
					log.debug("Watcher event: " + event.kind().name() + ", file " + child);
					dirWatcherHandler.handleFileChanged(event.kind(), child.toString());
				}

				// reset key and remove from set if directory no longer
				// accessible
				boolean valid = key.reset();
				if (!valid) {
					synchronized (watcherName) {
						keys.remove(key);
						baseFolders.remove(baseFolder.folder);
					}
				}
			}
			log.debug("FileWatcher thread stopped " + watcherName);
		}

		private void idleIfNoKeysRegistered() throws InterruptedException {
			while (true) {
				synchronized (watcherName) {
					if (!keys.isEmpty()) {
						break;
					}
				}
				Thread.sleep(500);
			}
		};
	};
	ret.start();
	return ret;
}
 
Example 14
Source File: DirectoryWatcher.java    From streamsx.topology with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
protected void process() throws Exception {

    Path dir = dirFile.toPath();

    WatchService watcher = FileSystems.getDefault().newWatchService();
    dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE);

    sortAndSubmit(Arrays.asList(dirFile.listFiles(this)));

    for (;!Thread.interrupted();) {
        WatchKey key;
        try {
            key = watcher.take();
        } catch (InterruptedException e) {
            // shutdown has been requested
            return;
        }

        List<File> newFiles = new ArrayList<>();
        boolean needFullScan = false;
        for (WatchEvent<?> watchEvent : key.pollEvents()) {

            if (ENTRY_CREATE == watchEvent.kind()) {
                Path newPath = ((WatchEvent<Path>) watchEvent).context();
                File newFile = toFile(newPath);
                if (accept(newFile))
                    newFiles.add(newFile);
            } else if (ENTRY_DELETE == watchEvent.kind()) {
                Path deletedPath = ((WatchEvent<Path>) watchEvent)
                        .context();
                File deletedFile = toFile(deletedPath);
                seenFiles.remove(deletedFile.getName());
            } else if (OVERFLOW == watchEvent.kind()) {
                needFullScan = true;
            }
        }
        key.reset();

        if (needFullScan) {
            Collections.addAll(newFiles, dirFile.listFiles(this));
        }
        sortAndSubmit(newFiles);
    }
}
 
Example 15
Source File: ArtifactSourceFileWatcherThread.java    From rug-cli with GNU General Public License v3.0 4 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public void run() {

    final Map<WatchKey, Path> keys = new HashMap<>();

    Consumer<Path> register = register(keys);

    register.accept(Paths.get(artifact.uri()));

    while (!interrupted) {
        final WatchKey key;
        try {
            key = watcher.take(); // wait for a key to be available
        }
        catch (InterruptedException ex) {
            return;
        }

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

        key.pollEvents().stream().filter(e -> (e.kind() != OVERFLOW)).forEach(e -> {
            Path p = ((WatchEvent<Path>) e).context();
            Path absPath = dir.resolve(p);
            File f = absPath.toFile();

            if (f.isDirectory()) {
                register.accept(absPath);
            }

            String path = f.getAbsolutePath();
            if (!path.contains(".atomist/target") && !path.contains(".git")) {

                // There was a modification to the filesystem, trigger reload of ArtifactSource
                CommandContext.delete(ArtifactSource.class);
                CommandContext.delete(Rugs.class);

                // Special case for changes to manifest.yml
                if (f.getName().equals("manifest.yml") && f.getParentFile() != null
                        && f.getParentFile().getName().equals(".atomist")) {
                    Constants.setReload(true);
                }
                // Special case for changes to package.json
                if (f.getName().equals("package.json") && f.getParentFile() != null
                        && f.getParentFile().getName().equals(".atomist")) {
                    Constants.setReload(true);
                }
            }
        });

        boolean valid = key.reset(); // IMPORTANT: The key must be reset after processed
        if (!valid) {
            keys.remove(key);
        }
    }
}
 
Example 16
Source File: WatchServiceHolder.java    From elexis-3-core with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public void run(){
	logger.debug("Start polling");
	WatchKey key = null;
	for (;;) {
		try {
			// on os x it can take up to 10 seconds until changes are picked up
			// https://www.reddit.com/r/java/comments/3vtv8i/beware_javaniofilewatchservice_is_subtly_broken/
			key = watchService.poll(250, TimeUnit.MILLISECONDS);
			if (key == null) {
				continue;
			}
			ITaskDescriptor taskDescriptor = incurredTasks.get(key);
			List<WatchEvent<?>> pollEvents = key.pollEvents();
			for (WatchEvent<?> watchEvent : pollEvents) {
				if (taskDescriptor != null) {
					// the watchkey does not know its base path
					String watcherPath = taskDescriptor.getTriggerParameters().get(
							IIdentifiedRunnable.RunContextParameter.STRING_URL);
					
					Path name = (Path) watchEvent.context();
					String fullPath = Paths.get(watcherPath, name.toString()).toString();
					logger.debug("{} -> {}", watchEvent.kind(), fullPath);
					
					Map<String, String> runContext = new HashMap<>();
					
					runContext.put(IIdentifiedRunnable.RunContextParameter.STRING_URL,
						fullPath);
					
					trigger(taskDescriptor, runContext);
				} else {
					logger.error(
						"No taskDescriptor registered for the provided watchKey [{}], removing key",
						key);
					incurredTasks.remove(key);
				}
			}
			key.reset();
		} catch (InterruptedException e) {
			logger.error("Interrupted", e);
		}
	}
}
 
Example 17
Source File: DirectoryWatcherTest.java    From openjdk-systemtest with Apache License 2.0 4 votes vote down vote up
public void testDirectoryWatcher() throws IOException, StfException {
	Path tempDirectory = getTemporaryDirectory();
	WatchService watchService = null;

	// Obtain watch service for the default file system and register
	// an interest in knowing when files are created
	watchService = FileSystems.getDefault().newWatchService();
	try {
		tempDirectory.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);
		// Hard-coded values of how many files to touch
		int numberOfIterationsRemaining = 10;
		int numberOfFiles = 5;
		int totalFiles = numberOfFiles * numberOfIterationsRemaining;
		long startTime = System.currentTimeMillis();

		// Our variables containing information as to whether we are going
		// to pass
		// or fail
		int filesFound = 0;
		boolean discardedEvents = false;

		LOOP: while (true) {
			WatchKey key;
			
			// Spread out the creating of files, interspersing them with polls.
			if (numberOfIterationsRemaining > 0) {
				createFiles(tempDirectory, numberOfFiles);
				numberOfIterationsRemaining--;
			}

			// Try taking a key off the service, if available (null if not)
			key = watchService.poll();
			if (key != null) {
				// Retrieve each event
				for (WatchEvent<?> event : key.pollEvents()) {
					if (event.kind().equals(StandardWatchEventKinds.ENTRY_CREATE)) {
						// New file found
						filesFound++;
					} else if (event.kind().equals(StandardWatchEventKinds.OVERFLOW)) {
						// Overflow occurred.
						// This is sort of a warning, but expected if we
						// (the JVM?) can't process
						// the events fast enough
						discardedEvents = true;
					}
				}

				// Important to reset the key
				key.reset();
			}

			long duration = System.currentTimeMillis() - startTime;

			// Check if we have received everything we intended to
			// if so, we can break the loop
			if (numberOfIterationsRemaining == 0) {
				if (filesFound == totalFiles) {
					break LOOP;
				}
				if (discardedEvents == true) {
					break LOOP;
				}
			}

			// Check to see if we have been doing this for too long
			// if so, then break the loop
			if (duration > TIMEOUT) {
				fail("Timeout exceeded: " + filesFound + " files found in " + duration + "ms");
				break LOOP;
			}
		}

		System.out.println("Summary: totalfile - " + totalFiles + " , files found " + filesFound);

		if (discardedEvents == false && (totalFiles != filesFound)) {
			fail("No events were knowingly discarded, but the total number of files found does not equal the number created");
		}

		if (discardedEvents == true) {
			System.out.println("Warning, events were discarded.");
		}
	} finally {
		watchService.close();
	}
	okForCleanup();
}
 
Example 18
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 19
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;
                    }
                }
            }
        }
    }
 
Example 20
Source File: DirectoryWatcherTest.java    From openjdk-systemtest with Apache License 2.0 4 votes vote down vote up
public void testEntryModify() throws IOException, InterruptedException, StfException {
	Path tempDirectory = getTemporaryDirectory();
	WatchService watchService = FileSystems.getDefault().newWatchService();
	try {
		Path newFilename = Paths.get("ENTRY_MODIFY.txt");
		Path newFile = tempDirectory.resolve(newFilename);
		Files.createFile(newFile);
		assertTrue("File was not created", Files.exists(newFile));

		// We need to pause so that the implementation on AIX and zOS
		// notices the modification time
		// has changed, which only work to the second apparently.
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {

		}

		tempDirectory.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);

		// Modify file
		OutputStream out = Files.newOutputStream(newFile, StandardOpenOption.WRITE);
		out.write("A".getBytes());
		out.close();

		WatchKey key = null;

		// We will give it POLL_TIMEOUT_SECONDS seconds, if it hasn't got
		// something by
		// then we assume failure

		key = watchService.poll(POLL_TIMEOUT_SECONDS, TimeUnit.SECONDS);

		assertNotNull("Polling WatchService object returned null", key);

		boolean eventFound = false;

		// Check for exactly one event
		for (WatchEvent<?> event : key.pollEvents()) {
			if (event.kind().equals(StandardWatchEventKinds.ENTRY_MODIFY)) {
				// Assert exactly one event
				assertFalse("Duplicate ENTRY_MODIFY events delivered for one file modification", eventFound);
				// Assert filename is correct
				assertEquals(newFilename, (Path) event.context());
				eventFound = true;
			} else {
				fail(event.kind() + " event retured, expected ENTRY_MODIFY");
			}
		}

		// Reset the key, to allow for future events
		key.reset();
	} finally {
		watchService.close();
	}
	okForCleanup();
}