EJB 3.1 and NIO2: Monitoring the file system

大城市里の小女人 提交于 2019-12-02 12:00:20

问题


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. But what if I want to integrate the things into an existing Java EE application so I don't have to start another service (app-server AND the one which monitors the file system)? So I have the heavy weight app-server with all the EJB 3.1 stuff and some kind of service monitoring the file system and take appropriate action once a file shows up. Interestingly the appropriate action is to create a Message and send it by JMS and it might be nice to integrate both into the app server.

I tried @Startup but deployment freezes (and I know that I shouldn't make use of I/O in there, was just a try). Anyhow ... any suggestions?


回答1:


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.
                }
            }
        }
    }

}



回答2:


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.



来源:https://stackoverflow.com/questions/14381274/ejb-3-1-and-nio2-monitoring-the-file-system

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!