/* * Copyright 2005-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wamblee.test.transactions; import java.util.ArrayList; import java.util.List; import javax.transaction.UserTransaction; import org.wamblee.general.ThreadSpecificProxyFactory; /** * Simple transaction manager provides a simple mechanism to manage transaction * in test code through the {@link UserTransaction} object. * * @author Erik Brakkee * */ public class SimpleTransactionManager { private UserTransactionFactory factory; private ThreadSpecificProxyFactory transaction; private UserTransactionCallback callback; private List resources; /** * Constructs the transaction manager. * * @param aFactory * Factory to create transactions with. */ public SimpleTransactionManager(UserTransactionFactory aFactory) { factory = aFactory; transaction = new ThreadSpecificProxyFactory(UserTransaction.class); callback = new UserTransactionCallback() { @Override public void transactionFinished() { transaction.set(null); } }; resources = new ArrayList(); } /** * Adds a resource to manage. Adding resources is no longer allowed after * the first transaction has started. * * @param aResource * Resource. */ public void addResource(TransactionResource aResource) { resources.add(aResource); } /** * Gets the user transaction. This is a contextual reference, meaning that * it will delegate to the appropriate thread-specific user transaction. * It is also safe to store in a JNDI tree and for caching by applications. * * @return User transaction. */ public UserTransaction getTransaction() { UserTransaction tx = transaction.get(); if (tx == null) { tx = factory.create(callback, resources); transaction.set(tx); } return transaction.getProxy(); } /** * Gets the thread-specific transaction object. * @return Transaction object. */ UserTransaction getThreadSpecificTransaction() { getTransaction(); // create tx if needed return transaction.get(); } }