View Javadoc

1   /*
2    * $Id: JdbcTransaction.java 7976 2007-08-21 14:26:13Z dirk.olmes $
3    * --------------------------------------------------------------------------------------
4    * Copyright (c) MuleSource, Inc.  All rights reserved.  http://www.mulesource.com
5    *
6    * The software in this package is published under the terms of the CPAL v1.0
7    * license, a copy of which has been included with this distribution in the
8    * LICENSE.txt file.
9    */
10  
11  package org.mule.providers.jdbc;
12  
13  import org.mule.config.i18n.CoreMessages;
14  import org.mule.providers.jdbc.i18n.JdbcMessages;
15  import org.mule.transaction.AbstractSingleResourceTransaction;
16  import org.mule.transaction.IllegalTransactionStateException;
17  import org.mule.transaction.TransactionRollbackException;
18  import org.mule.umo.TransactionException;
19  
20  import java.sql.Connection;
21  import java.sql.SQLException;
22  
23  import javax.sql.DataSource;
24  
25  /**
26   * TODO
27   */
28  public class JdbcTransaction extends AbstractSingleResourceTransaction
29  {
30  
31      public JdbcTransaction()
32      {
33          super();
34      }
35  
36      public void bindResource(Object key, Object resource) throws TransactionException
37      {
38          if (!(key instanceof DataSource) || !(resource instanceof Connection))
39          {
40              throw new IllegalTransactionStateException(
41                  CoreMessages.transactionCanOnlyBindToResources("javax.sql.DataSource/java.sql.Connection"));
42          }
43          Connection con = (Connection)resource;
44          try
45          {
46              if (con.getAutoCommit())
47              {
48                  con.setAutoCommit(false);
49              }
50          }
51          catch (SQLException e)
52          {
53              throw new TransactionException(JdbcMessages.transactionSetAutoCommitFailed(), e);
54          }
55          super.bindResource(key, resource);
56      }
57  
58      protected void doBegin() throws TransactionException
59      {
60          // Do nothing
61      }
62  
63      protected void doCommit() throws TransactionException
64      {
65          try
66          {
67              ((Connection)resource).commit();
68              ((Connection)resource).close();
69          }
70          catch (SQLException e)
71          {
72              throw new TransactionException(CoreMessages.transactionCommitFailed(), e);
73          }
74      }
75  
76      protected void doRollback() throws TransactionException
77      {
78          try
79          {
80              ((Connection)resource).rollback();
81              ((Connection)resource).close();
82          }
83          catch (SQLException e)
84          {
85              throw new TransactionRollbackException(CoreMessages.transactionRollbackFailed(), e);
86          }
87      }
88  }