View Javadoc

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  import java.util.LinkedList;
26  
27  /***
28   * Helps keep track of the current transaction/JDBC connection.
29   *
30   * @version $Revision: 1.1 $
31   */
32  public class TransactionContext {
33      private static final Log log = LogFactory.getLog(TransactionContext.class);
34      private static ThreadLocal threadLocalTxn = new ThreadLocal();
35  
36      /***
37       * @return the current thread local connection that is associated
38       *  with the JMS transaction or null if there is no 
39       *  transaction in progress.
40       */
41      public static Connection getConnection() {
42          LinkedList list = (LinkedList) threadLocalTxn.get();
43          if (list != null && !list.isEmpty()) {
44              return (Connection) list.getFirst();
45          }
46          throw new IllegalStateException("Attempt to get a connection when no transaction in progress");
47      }
48  
49      /***
50       * Pops off the current Connection from the stack
51       */
52      public static Connection popConnection() {
53          LinkedList list = (LinkedList) threadLocalTxn.get();
54          if (list == null || list.isEmpty()) {
55              log.warn("Attempt to pop connection when no transaction in progress");
56              return null;
57          }
58          else {
59              return (Connection) list.removeFirst();
60          }
61      }
62  
63      /***
64       * Sets the current transaction, possibly including nesting
65       */
66      public static void pushConnection(Connection connection) {
67          LinkedList list = (LinkedList) threadLocalTxn.get();
68          if (list == null) {
69              list = new LinkedList();
70              threadLocalTxn.set(list);
71          }
72          list.addLast(connection);
73      }
74  
75      public static int getTransactionCount() {
76          LinkedList list = (LinkedList) threadLocalTxn.get();
77          if (list != null) {
78              return list.size();
79          }
80          return 0;
81      }
82  
83  }