View Javadoc
1   /*
2   
3     Licensed to the Apache Software Foundation (ASF) under one or more
4     contributor license agreements.  See the NOTICE file distributed with
5     this work for additional information regarding copyright ownership.
6     The ASF licenses this file to You under the Apache License, Version 2.0
7     (the "License"); you may not use this file except in compliance with
8     the License.  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  package org.apache.commons.dbcp2.managed;
19  
20  import java.sql.Connection;
21  import java.sql.SQLException;
22  import java.util.Map;
23  import java.util.Objects;
24  import java.util.WeakHashMap;
25  
26  import javax.transaction.SystemException;
27  import javax.transaction.Transaction;
28  import javax.transaction.TransactionManager;
29  import javax.transaction.TransactionSynchronizationRegistry;
30  import javax.transaction.xa.XAResource;
31  
32  import org.apache.commons.dbcp2.DelegatingConnection;
33  
34  /**
35   * TransactionRegistry tracks Connections and XAResources in a transacted environment for a single XAConnectionFactory.
36   * <p>
37   * The TransactionRegistry hides the details of transaction processing from the existing DBCP pooling code, and gives
38   * the ManagedConnection a way to enlist connections in a transaction, allowing for the maximal rescue of DBCP.
39   * </p>
40   *
41   * @since 2.0
42   */
43  public class TransactionRegistry {
44      private final TransactionManager transactionManager;
45      private final Map<Transaction, TransactionContext> caches = new WeakHashMap<>();
46      private final Map<Connection, XAResource> xaResources = new WeakHashMap<>();
47      private final TransactionSynchronizationRegistry transactionSynchronizationRegistry;
48  
49      /**
50       * Provided for backwards compatibility
51       * @param transactionManager the transaction manager used to enlist connections
52       */
53      public TransactionRegistry(final TransactionManager transactionManager) {
54          this (transactionManager, null);
55      }
56  
57      /**
58       * Creates a TransactionRegistry for the specified transaction manager.
59       *
60       * @param transactionManager
61       *            the transaction manager used to enlist connections.
62       * @param transactionSynchronizationRegistry
63       *              The optional TSR to register synchronizations with
64       * @since 2.6.0
65       */
66      public TransactionRegistry(final TransactionManager transactionManager, final TransactionSynchronizationRegistry transactionSynchronizationRegistry) {
67          this.transactionManager = transactionManager;
68          this.transactionSynchronizationRegistry = transactionSynchronizationRegistry;
69      }
70  
71      /**
72       * Gets the active TransactionContext or null if not Transaction is active.
73       *
74       * @return The active TransactionContext or null if no Transaction is active.
75       * @throws SQLException
76       *             Thrown when an error occurs while fetching the transaction.
77       */
78      public TransactionContext getActiveTransactionContext() throws SQLException {
79          Transaction transaction = null;
80          try {
81              transaction = transactionManager.getTransaction();
82  
83              // was there a transaction?
84              if (transaction == null) {
85                  return null;
86              }
87  
88              // This is the transaction on the thread so no need to check it's status - we should try to use it and
89              // fail later based on the subsequent status
90          } catch (final SystemException e) {
91              throw new SQLException("Unable to determine current transaction ", e);
92          }
93  
94          // register the context (or create a new one)
95          synchronized (this) {
96              TransactionContext cache = caches.get(transaction);
97              if (cache == null) {
98                  cache = new TransactionContext(this, transaction, transactionSynchronizationRegistry);
99                  caches.put(transaction, cache);
100             }
101             return cache;
102         }
103     }
104 
105     private Connection getConnectionKey(final Connection connection) {
106         final Connection result;
107         if (connection instanceof DelegatingConnection) {
108             result = ((DelegatingConnection<?>) connection).getInnermostDelegateInternal();
109         } else {
110             result = connection;
111         }
112         return result;
113     }
114 
115     /**
116      * Gets the XAResource registered for the connection.
117      *
118      * @param connection
119      *            the connection
120      * @return The XAResource registered for the connection; never null.
121      * @throws SQLException
122      *             Thrown when the connection does not have a registered XAResource.
123      */
124     public synchronized XAResource getXAResource(final Connection connection) throws SQLException {
125         Objects.requireNonNull(connection, "connection is null");
126         final Connection key = getConnectionKey(connection);
127         final XAResource xaResource = xaResources.get(key);
128         if (xaResource == null) {
129             throw new SQLException("Connection does not have a registered XAResource " + connection);
130         }
131         return xaResource;
132     }
133 
134     /**
135      * Registers the association between a Connection and a XAResource. When a connection is enlisted in a transaction,
136      * it is actually the XAResource that is given to the transaction manager.
137      *
138      * @param connection
139      *            The JDBC connection.
140      * @param xaResource
141      *            The XAResource which managed the connection within a transaction.
142      */
143     public synchronized void registerConnection(final Connection connection, final XAResource xaResource) {
144         Objects.requireNonNull(connection, "connection is null");
145         Objects.requireNonNull(xaResource, "xaResource is null");
146         xaResources.put(connection, xaResource);
147     }
148 
149     /**
150      * Unregisters a destroyed connection from {@link TransactionRegistry}.
151      *
152      * @param connection
153      *            A destroyed connection from {@link TransactionRegistry}.
154      */
155     public synchronized void unregisterConnection(final Connection connection) {
156         final Connection key = getConnectionKey(connection);
157         xaResources.remove(key);
158     }
159 }