package org.jboss.resource.connectionmanager;
import java.util.ArrayList;
import javax.transaction.RollbackException;
import javax.transaction.Synchronization;
import javax.transaction.SystemException;
import javax.transaction.Transaction;
import javax.transaction.TransactionManager;
import org.jboss.logging.Logger;
import org.jboss.tm.TransactionLocal;
public class TransactionSynchronizer implements Synchronization
{
private static final Logger log = Logger.getLogger(TransactionSynchronizer.class);
protected static TransactionLocal txSynchs;
protected Transaction tx;
protected ArrayList txRemoverSynchs;
protected Synchronization ccmSynch;
public static void setTransactionManager(TransactionManager tm)
{
txSynchs = new TransactionLocal(tm);
}
public static void registerTxRemoverSynchronization(Transaction tx, Synchronization synch) throws RollbackException, SystemException
{
TransactionSynchronizer ts = getRegisteredSynchronizer(tx);
if (ts.txRemoverSynchs == null)
ts.txRemoverSynchs = new ArrayList();
ts.txRemoverSynchs.add(synch);
}
public static Synchronization getCCMSynchronization(Transaction tx)
{
TransactionSynchronizer ts = (TransactionSynchronizer) txSynchs.get(tx);
if (ts != null)
return ts.ccmSynch;
else
return null;
}
public static void registerCCMSynchronization(Transaction tx, Synchronization synch) throws RollbackException, SystemException
{
TransactionSynchronizer ts = getRegisteredSynchronizer(tx);
ts.ccmSynch = synch;
}
private TransactionSynchronizer(Transaction tx)
{
this.tx = tx;
}
public void beforeCompletion()
{
if (txRemoverSynchs != null)
{
for (int i = 0; i < txRemoverSynchs.size(); ++i)
{
Synchronization synch = (Synchronization) txRemoverSynchs.get(i);
invokeBefore(synch);
}
}
if (ccmSynch != null)
invokeBefore(ccmSynch);
}
public void afterCompletion(int status)
{
if (txRemoverSynchs != null)
{
for (int i = 0; i < txRemoverSynchs.size(); ++i)
{
Synchronization synch = (Synchronization) txRemoverSynchs.get(i);
invokeAfter(synch, status);
}
}
if (ccmSynch != null)
invokeAfter(ccmSynch, status);
}
protected void invokeBefore(Synchronization synch)
{
try
{
synch.beforeCompletion();
}
catch (Throwable t)
{
log.warn("Transaction " + tx + " error in before completion " + synch, t);
}
}
protected void invokeAfter(Synchronization synch, int status)
{
try
{
synch.afterCompletion(status);
}
catch (Throwable t)
{
log.warn("Transaction " + tx + " error in after completion " + synch, t);
}
}
protected static TransactionSynchronizer getRegisteredSynchronizer(Transaction tx) throws RollbackException, SystemException
{
TransactionSynchronizer result = (TransactionSynchronizer) txSynchs.get(tx);
if (result == null)
{
result = new TransactionSynchronizer(tx);
tx.registerSynchronization(result);
txSynchs.set(tx, result);
}
return result;
}
}