001    /*
002      GRANITE DATA SERVICES
003      Copyright (C) 2011 GRANITE DATA SERVICES S.A.S.
004    
005      This file is part of Granite Data Services.
006    
007      Granite Data Services is free software; you can redistribute it and/or modify
008      it under the terms of the GNU Library General Public License as published by
009      the Free Software Foundation; either version 2 of the License, or (at your
010      option) any later version.
011    
012      Granite Data Services is distributed in the hope that it will be useful, but
013      WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
014      FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License
015      for more details.
016    
017      You should have received a copy of the GNU Library General Public License
018      along with this library; if not, see <http://www.gnu.org/licenses/>.
019    */
020    
021    package org.granite.tide.cdi;
022    
023    import javax.enterprise.event.Observes;
024    import javax.enterprise.event.TransactionPhase;
025    import javax.enterprise.inject.Instance;
026    import javax.transaction.Status;
027    import javax.transaction.SystemException;
028    import javax.transaction.UserTransaction;
029    
030    import org.granite.logging.Logger;
031    import org.granite.tide.data.DataContext;
032    import org.granite.tide.data.DataEnabled.PublishMode;
033    
034    
035    /**
036     * CDI event listener to handle publishing of data changes instead of relying on the default behaviour
037     * This can be used outside of a HTTP Granite context and inside the security/transaction context
038     * @author William DRAI
039     *
040     */
041    public class TideDataPublishingOnSuccessHandler {
042            
043            private static final Logger log = Logger.getLogger(TideDataPublishingOnSuccessHandler.class);
044            
045        public void doPublish(@Observes(during=TransactionPhase.BEFORE_COMPLETION) TideDataPublishingEvent event, Instance<UserTransaction> uts) {
046            if (uts.isUnsatisfied() || uts.isAmbiguous()) {
047                // No JTA UserTransaction, probably a servlet container
048                // Anyway we should not be here
049                return;
050            }
051    
052            UserTransaction ut = uts.get();        
053            try {
054                            if (!(ut.getStatus() == Status.STATUS_MARKED_ROLLBACK || ut.getStatus() == Status.STATUS_ROLLING_BACK || ut.getStatus() == Status.STATUS_ROLLING_BACK))
055                                    DataContext.publish(PublishMode.ON_COMMIT);
056                    } 
057            catch (SystemException e) {
058                    log.warn(e, "Could not get the current status of the transaction ???");
059                    }
060            if (event.getInitContext())
061                    DataContext.remove();
062        }
063    }