/*
 * JBoss, Home of Professional Open Source
 * Copyright 2005, JBoss Inc., and individual contributors as indicated
 * by the @authors tag. See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package org.jboss.hibernate.session;

import net.sf.hibernate.Session;
import org.jboss.logging.Logger;

import javax.transaction.Synchronization;

/**
 * Implementation of a transaction Synchronization for managing closure
 * of a hibernate Session on completion of the JTA transaction.
 *
 * @author <a href="mailto:steve@hibernate.org">Steve Ebersole</a>
 * @version $Revision: 1.1.2.5 $
 */
class TransactionSynch implements Synchronization
{
   private static Logger log = Logger.getLogger(TransactionSynch.class);

   private String name;
   private Session session;

   public TransactionSynch(String name, Session session)
   {
      if ( log.isTraceEnabled() )
      {
         log.trace("Preparing synch [name=" + name + ", session=" + session + "]");
      }

      if (session == null)
      {
         throw new IllegalArgumentException("Session to synchronize cannot be null");
      }

      this.name = name;
      this.session = session;
   }

   public void beforeCompletion()
   {
      if ( !session.isOpen() )
      {
         log.warn("Session already closed");
      }
      else
      {
         try
         {
            log.trace("Flushing Session");
            session.flush();
         }
         catch(Throwable t)
         {
            log.warn("Error flushing session");
         }
      }
   }

   public void afterCompletion(int status)
   {
      if ( session.isOpen() )
      {
         try
         {
            log.trace("Closing Session");
            session.close();
         }
         catch(Throwable t)
         {
            log.warn("Unable to close session");
         }
      }

      if ( session != HibernateContext.unbind(name) )
      {
         log.warn("Synch encountered different session in context while performing unbind");
      }
   }

}
