1 /*** 2 * 3 * Copyright 2004 Hiram Chirino 4 * Copyright 2004 Protique Ltd 5 * 6 * Licensed under the Apache License, Version 2.0 (the "License"); 7 * you may not use this file except in compliance with the License. 8 * You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, software 13 * distributed under the License is distributed on an "AS IS" BASIS, 14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 * See the License for the specific language governing permissions and 16 * limitations under the License. 17 * 18 **/ 19 package org.codehaus.activemq.store.jdbc; 20 21 import org.apache.commons.logging.Log; 22 import org.apache.commons.logging.LogFactory; 23 24 import java.sql.Connection; 25 26 import javax.sql.DataSource; 27 28 /*** 29 * Helps keep track of the current transaction/JDBC connection. 30 * 31 * @version $Revision: 1.2 $ 32 */ 33 public class TransactionContext { 34 private static final Log log = LogFactory.getLog(TransactionContext.class); 35 private static ThreadLocal threadLocalTxn = new ThreadLocal(); 36 private final DataSource dataSource; 37 38 TransactionContext( DataSource dataSource ) { 39 this.dataSource = dataSource; 40 } 41 42 /*** 43 * Pops off the current Connection from the stack 44 */ 45 public static Connection popConnection() { 46 Connection[] tx = (Connection[]) threadLocalTxn.get(); 47 if (tx == null || tx[0]==null) { 48 log.warn("Attempt to pop connection when no transaction in progress"); 49 return null; 50 } 51 else { 52 Connection answer = tx[0]; 53 tx[0]=null; 54 return answer; 55 } 56 } 57 58 /*** 59 * Sets the current transaction, possibly including nesting 60 */ 61 public static void pushConnection(Connection connection) { 62 Connection[] tx = (Connection[]) threadLocalTxn.get(); 63 if (tx == null) { 64 tx = new Connection[]{null}; 65 threadLocalTxn.set(tx); 66 } 67 if (tx[0] != null) { 68 throw new IllegalStateException("A transaction is allready in progress"); 69 } 70 tx[0] = connection; 71 } 72 73 /*** 74 * @return the current thread local connection that is associated 75 * with the JMS transaction or null if there is no 76 * transaction in progress. 77 */ 78 public static Connection peekConnection() { 79 Connection tx[] = (Connection[]) threadLocalTxn.get(); 80 if (tx != null && tx[0]!=null ) { 81 return tx[0]; 82 } 83 return null; 84 } 85 86 }