/*
 * 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.cache.interceptors;

import org.jboss.logging.Logger;

import javax.transaction.RollbackException;
import javax.transaction.Synchronization;
import javax.transaction.SystemException;
import javax.transaction.Transaction;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;

/**
 * Maintains a list of Synchronization handlers. Reason is that we have to invoke certain handlers <em>before</em>
 * others. See the description in SyncTxUnitTestCase.testConcurrentPuts(). For example, for synchronous replication,
 * we have to execute the ReplicationInterceptor's afterCompletion() <em>before</em> the TransactionInterceptor's.
 * @author Bela Ban
 * @version $Id: OrderedSynchronizationHandler.java,v 1.2.2.5 2005/12/01 19:48:41 dimitris Exp $
 */
public class OrderedSynchronizationHandler implements Synchronization {
   Transaction       tx=null;
   LinkedList        handlers=new LinkedList();

   /** Map<Transaction,OrderedSynchronizationHandler> */
   static Map instances=new HashMap();

   static Logger log=Logger.getLogger(OrderedSynchronizationHandler.class);


   private OrderedSynchronizationHandler(Transaction tx) {
      this.tx=tx;
   }

   /**
    * Creates a new instance of OrderedSynchronizationHandler, or fetches an existing instance. Key is the local
    * transaction (tx). This instance registers with the TransactionManager automatically
    * @param tx
    * @return
    */
   public static OrderedSynchronizationHandler getInstance(Transaction tx) throws SystemException, RollbackException {
      OrderedSynchronizationHandler retval=(OrderedSynchronizationHandler)instances.get(tx);
      if(retval != null) return retval;
      retval=new OrderedSynchronizationHandler(tx);
      tx.registerSynchronization(retval);
      instances.put(tx, retval);
      return retval;
   }


   public void registerAtHead(Synchronization handler) {
      register(handler, true);
   }

   public void registerAtTail(Synchronization handler) {
      register(handler,  false);
   }

   void register(Synchronization handler, boolean head) {
      if(handler != null && !handlers.contains(handler)) {
         if(head)
            handlers.addFirst(handler);
         else
            handlers.addLast(handler);
      }
   }

   public void beforeCompletion() {
      for(Iterator it=handlers.iterator(); it.hasNext();) {
         Synchronization sync=(Synchronization)it.next();
         sync.beforeCompletion();
      }
   }

   public void afterCompletion(int status) {
      for(Iterator it=handlers.iterator(); it.hasNext();) {
         Synchronization sync=(Synchronization)it.next();
         try {
            sync.afterCompletion(status);
         }
         catch(Throwable t) {
            log.error("failed calling afterCompletion() on " + sync, t);
         }
      }

      // finally unregister us from the hashmap
      instances.remove(tx);
   }

   public String toString() {
      StringBuffer sb=new StringBuffer();
      sb.append("tx=" + tx + ", handlers=" + handlers);
      return sb.toString();
   }
}
