2 * Copyright 2005-2010 the original author or authors.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 package org.wamblee.test.transactions;
18 import java.util.ArrayList;
19 import java.util.List;
21 import javax.transaction.UserTransaction;
23 import org.wamblee.general.ThreadSpecificProxyFactory;
26 * Simple transaction manager provides a simple mechanism to manage transaction
27 * in test code through the {@link UserTransaction} object.
29 * @author Erik Brakkee
32 public class SimpleTransactionManager {
34 private UserTransactionFactory factory;
35 private ThreadSpecificProxyFactory<UserTransaction> transaction;
36 private UserTransactionCallback callback;
37 private List<TransactionResource> resources;
40 * Constructs the transaction manager.
43 * Factory to create transactions with.
45 public SimpleTransactionManager(UserTransactionFactory aFactory) {
47 transaction = new ThreadSpecificProxyFactory<UserTransaction>(UserTransaction.class);
48 callback = new UserTransactionCallback() {
51 public void transactionFinished() {
52 transaction.set(null);
55 resources = new ArrayList<TransactionResource>();
59 * Adds a resource to manage. Adding resources is no longer allowed after
60 * the first transaction has started.
65 public void addResource(TransactionResource aResource) {
66 resources.add(aResource);
70 * Gets the user transaction. This is a contextual reference, meaning that
71 * it will delegate to the appropriate thread-specific user transaction.
72 * It is also safe to store in a JNDI tree and for caching by applications.
74 * @return User transaction.
76 public UserTransaction getTransaction() {
77 UserTransaction tx = transaction.get();
79 tx = factory.create(callback, resources);
82 return transaction.getProxy();
86 * Gets the thread-specific transaction object.
87 * @return Transaction object.
89 UserTransaction getThreadSpecificTransaction() {
90 getTransaction(); // create tx if needed
91 return transaction.get();