0
votes

I developp an application on a JBoss 7.1 which have to monitor a directory of the fileSystem. For this purpose, I write some code which looks like what I found in this post :EJB 3.1 and NIO2: Monitoring the file system. So I write a session ejb PollingServiceImpl with an asynchronous method watching the path I have to monitor and an @StartUp Ejb which call the session EJB. Here is my code for the 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();
        }
    }

}


}

and here is the code for the startp ejb : @Singleton @Startup public class Initialiser {

        @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;

        }

    }

Everything looks fine and the watcher works well but I have two problems : 1) Some warnings appears on the console like this : [com.arjuna.ats.arjuna] (Transaction Reaper Worker 0) ARJUNA012095: Abort of action id 0:ffff7f000101:-51121f7e:53b7f879:9 invoked while multiple threads active within it. 15:12:14,522 WARN [com.arjuna.ats.arjuna] (Transaction Reaper Worker 0) ARJUNA012108:
CheckedAction::check - atomic action 0:ffff7f000101:-51121f7e:53b7f879:9 aborting with
1 threads active! 15:12:14,522 WARN [com.arjuna.ats.arjuna] (Transaction Reaper Worker 0) ARJUNA012121: TransactionReaper::doCancellations worker Thread[Transaction Reaper Worker 0,5,main] successfully canceled TX 0:ffff7f000101:-51121f7e:53b7f879:9

2) The server refuse to shutdown : apparently the thread launched at start up don't stop. I have read in some posts that i have to stop the method pollForXmlMessage in the @PreDestroy method of the Initializer ejb but I don't know how i can make that or if there is another solution.

Can someone help me please?

2

2 Answers

2
votes

Here is a template of the solution:

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();
    }
}
0
votes

Every EJB method executes in a transaction context. If your method never returns JBoss informs you about a very long transaction that is probably hung.

Instead I would recommend moving this into a resource adapter that invokes a MDB on events like new files. http://robertpanzer.github.io/blog/2014/inboundra-nointfmdbs.html shows an example with a JavaEE7 style MDB but porting this down to JavaEE 6 and therefore JBoss 7 should be trivial.