Source code: org/activemq/store/jdbc/TransactionContext.java
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.activemq.store.jdbc;
20
21 import java.sql.Connection;
22
23 import org.apache.commons.logging.Log;
24 import org.apache.commons.logging.LogFactory;
25
26 /**
27 * Helps keep track of the current transaction/JDBC connection.
28 *
29 * @version $Revision: 1.1 $
30 */
31 public class TransactionContext {
32 private static final Log log = LogFactory.getLog(TransactionContext.class);
33 private static ThreadLocal threadLocalTxn = new ThreadLocal();
34
35 /**
36 * Pops off the current Connection from the stack
37 */
38 public static Connection popConnection() {
39 Connection[] tx = (Connection[]) threadLocalTxn.get();
40 if (tx == null || tx[0]==null) {
41 log.warn("Attempt to pop connection when no transaction in progress");
42 return null;
43 }
44 else {
45 Connection answer = tx[0];
46 tx[0]=null;
47 return answer;
48 }
49 }
50
51 /**
52 * Sets the current transaction, possibly including nesting
53 */
54 public static void pushConnection(Connection connection) {
55 Connection[] tx = (Connection[]) threadLocalTxn.get();
56 if (tx == null) {
57 tx = new Connection[]{null};
58 threadLocalTxn.set(tx);
59 }
60 if (tx[0] != null) {
61 throw new IllegalStateException("A transaction is allready in progress");
62 }
63 tx[0] = connection;
64 }
65
66 /**
67 * @return the current thread local connection that is associated
68 * with the JMS transaction or null if there is no
69 * transaction in progress.
70 */
71 public static Connection peekConnection() {
72 Connection tx[] = (Connection[]) threadLocalTxn.get();
73 if (tx != null && tx[0]!=null ) {
74 return tx[0];
75 }
76 return null;
77 }
78
79 }