EJB 3.1 and NIO2: Monitoring the file system

前端 未结 2 944
萌比男神i
萌比男神i 2021-01-25 08:33

I guess most of us agree, that NIO2 is a fine thing to make use of. Presumed you want to monitor some part of the file system for incoming xml - files it is an easy task now. Bu

相关标签:
2条回答
  • 2021-01-25 09:26

    You could create a singleton that loads at startup and delegates the monitoring to an Asynchronous bean

    @Singleton
    @Startup
    public class Initialiser {
    
        @EJB
        private FileSystemMonitor fileSystemMonitor;
    
        @PostConstruct
        public void init() {
            String fileSystemPath = ....;
            fileSystemMonitor.poll(fileSystemPath);
        }
    
    }
    

    Then the Asynchronous bean looks something like this

    @Stateless
    public class FileSystemMonitor {
    
        @Asynchronous
        public void poll(String fileSystemPath) {
            WatchService watcher = ....;
            for (;;) {
                WatchKey key = null;
                try {
                    key = watcher.take();
                    for (WatchEvent<?> event: key.pollEvents()) {
                        WatchEvent.Kind<?> kind = event.kind();
                        if (kind == StandardWatchEventKinds.OVERFLOW) {
                            continue; // If events are lost or discarded
                        }
                        WatchEvent<Path> watchEvent = (WatchEvent<Path>)event;
    
                        //Process files....
    
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    return;
                } finally {
                    if (key != null) {
                        boolean valid = key.reset();
                        if (!valid) break; // If the key is no longer valid, the directory is inaccessible so exit the loop.
                    }
                }
            }
        }
    
    }
    
    0 讨论(0)
  • 2021-01-25 09:33

    Might help if you specified what server you're using, but have you considered implementing a JMX based service ? It's a bit more "neutral" than EJB, is more appropriate for a background service and has fewer restrictions.

    0 讨论(0)
提交回复
热议问题