java - EJB 和 WatchService

标签 java jakarta-ee jboss nio ejb-3.1

我在 JBoss 7.1 上开发一个应用程序,它必须监视文件系统的目录。 为此,我编写了一些代码,类似于我在这篇文章中找到的代码:EJB 3.1 and NIO2: Monitoring the file system 。 因此,我编写了一个 session ejb PollingServiceImpl,其中使用异步方法监视我必须监视的路径,并编写了一个调用 session EJB 的 @StartUp Ejb。 这是我的 PollingService 代码:

@Stateless
public class PollingServiceImpl {
private Path       fichiersXmlPath=Paths.get("/media/sf_DossierPartage/IsidoreJaxb/specXML/fichiersXml");

/**
 * Default constructor. 
 */
public PollingServiceImpl() {
    // TODO Auto-generated constructor stub
}


@Asynchronous
public void pollForXmlMessage()  {

     WatchService service=null;
    // Vérification que le path est un répertoire
    try {
        Boolean isFolder = (Boolean) Files.getAttribute(fichiersXmlPath,
                "basic:isDirectory", LinkOption.NOFOLLOW_LINKS);
        if (!isFolder) {
            throw new IllegalArgumentException("le path : " + fichiersXmlPath + " n'est pas un répertoire");
        }
    } catch (IOException ioe) {
        System.out.println("le path : " + fichiersXmlPath + " n'est pas un répertoire");

    }

    System.out.println("Répertoire observé: " + fichiersXmlPath);

    // On obtient le système de fichier du chemin
    FileSystem fs = fichiersXmlPath.getFileSystem ();

    // We create the new WatchService using the new try() block
    try{ service = fs.newWatchService();

        //On enregistre le chemin dans le watcher
        // On surveille les opérations de création
        fichiersXmlPath.register(service, StandardWatchEventKinds.ENTRY_CREATE);

        // Beginning of the infinite loop

        for(;;) {
            WatchKey key = service.take();

            // Sortir les événements de la queue
            Kind<?> kind = null;
            for(WatchEvent<?> watchEvent : key.pollEvents()) {
                // on teste le type de l'événement
                kind = watchEvent.kind();

                // If les événements sont perdus
                if (StandardWatchEventKinds.OVERFLOW == kind) {
                    continue; //loop

                // Si c'est un événement de création
                } else if (StandardWatchEventKinds.ENTRY_CREATE == kind) {
                    // A new Path was created 
                    Path newPath = ((WatchEvent<Path>) watchEvent).context();
                    // Output
                    System.out.println("nouveau chemin : " + newPath +" numKey "+key.toString() );

                    // buisness process
                }
            }

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

        }

    } catch(IOException ioe) {
        ioe.printStackTrace();
    } catch(InterruptedException ie) {
        ie.printStackTrace();
    } finally{
        try {
            service.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}


}

这是 startp ejb 的代码: @辛格尔顿 @启动 公共(public)类初始化器{

        @EJB
        private PollingServiceImpl pollingService;

        public enum States {BEFORESTARTED, STARTED, PAUSED, SHUTTINGDOWN};

        private States state;


        @PostConstruct
        public void initialize() {

        state = States.BEFORESTARTED;

       pollingService.pollForXmlMessage();
         state = States.STARTED;
         System.out.println("ETAT : "+state.toString());
        }


        @PreDestroy
        public void terminate() {

        state = States.SHUTTINGDOWN;

        System.out.println("Shut down in progress");

        }

        public States getState() {

        return state;

        }

        public void setState(States state) {

        this.state = state;

        }

    }

一切看起来都很好,观察者也运行良好,但我有两个问题: 1)控制台上出现一些警告,如下所示: [com.arjuna.ats.arjuna](事务 Reaper Worker 0)ARJUNA012095:操作 id 中止 0:ffff7f000101:-51121f7e:53b7f879:9 在多个线程处于 Activity 状态时调用。 15:12:14,522 警告 [com.arjuna.ats.arjuna](交易 Reaper Worker 0)ARJUNA012108:
CheckedAction::check - 原子操作 0:ffff7f000101:-51121f7e:53b7f879:9 中止
1 个线程活跃! 15:12:14,522 警告 [com.arjuna.ats.arjuna](事务 Reaper Worker 0)ARJUNA012121: TransactionReaper::doCancellations 工作线程[事务收割者工作线程 0,5,main] 成功取消 TX 0:ffff7f000101:-51121f7e:53b7f879:9

2)服务器拒绝关闭:显然启动时启动的线程不会停止。我在一些帖子中读到,我必须停止初始化器 ejb 的 @PreDestroy 方法中的 pollForXmlMessage 方法,但我不知道如何做到这一点,也不知道是否有其他解决方案。

有人可以帮我吗?

最佳答案

这是解决方案的模板:

public class Service{
    private volotile boolean isCancelled = false;

    public void startService()
    {   //infinit loop:
        while(!isCancelled) {}
    }

    public void stopService()
    {
        isCancelled = true;
    }
}
@Singleton
@Startup
public class ServiceStarter{

    Service service;
    @EJB ServiceAsyncWorker asyncWorker;

    @PostConstruct
    private void init()
    {
        service = new Service(...);
        asyncWorker.startService(service);
    }

    @PreDestroy
    private void destroy()
    {
        service.stopService();
    }
}
@Singleton
public class ServiceAsyncWorker{
    @Asynchronous
    @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
    public void startService(Service service){
        service.startService();
    }
}

关于java - EJB 和 WatchService,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24586957/

相关文章:

java - jboss如何使用localhost :8080/projectname without "projectname"?

java - 在 Java 中关闭 ExecutorService 的最佳方法

java - 使用 graphql-java-tools 和 graphql-spring-boot-starter 进行错误处理

java.sql.jdbc.SQLException : No suitable driver on when connect to XAMPP MYSQL 异常

java - Servlet - 强制覆盖下载的文件

java - "Hibernate"类映射到底代表什么?

java - 如何协调部署到 WebLogic 集群中多个服务器的单个 ejb 计时器?

java - 在 EJB 上下文中从 DataSource 调用过程时出现 "Stored procedure ' xxx ' may be run only in unchained transaction mode."错误

java - 如何从 JBoss 中打开的连接池正确保持数据库连接

java - 选择地点或尝试返回时,Android 地点选择器显示空白屏幕