1. /*
  2. * Copyright 1999-2004 The Apache Software Foundation.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package org.apache.commons.dbcp;
  17. import java.sql.Connection;
  18. import java.sql.SQLException;
  19. import org.apache.commons.pool.ObjectPool;
  20. /**
  21. * A delegating connection that, rather than closing the underlying
  22. * connection, returns itself to an {@link ObjectPool} when
  23. * closed.
  24. *
  25. * @author Rodney Waldhoff
  26. * @author Glenn L. Nielsen
  27. * @author James House
  28. * @version $Revision: 1.14 $ $Date: 2004/05/01 12:50:12 $
  29. */
  30. public class PoolableConnection extends DelegatingConnection {
  31. /** The pool to which I should return. */
  32. protected ObjectPool _pool = null;
  33. /**
  34. *
  35. * @param conn my underlying connection
  36. * @param pool the pool to which I should return when closed
  37. */
  38. public PoolableConnection(Connection conn, ObjectPool pool) {
  39. super(conn);
  40. _pool = pool;
  41. }
  42. /**
  43. *
  44. * @param conn my underlying connection
  45. * @param pool the pool to which I should return when closed
  46. * @param config the abandoned configuration settings
  47. * @deprecated AbandonedConfig is now deprecated.
  48. */
  49. public PoolableConnection(Connection conn, ObjectPool pool,
  50. AbandonedConfig config) {
  51. super(conn, config);
  52. _pool = pool;
  53. }
  54. /**
  55. * Returns me to my pool.
  56. */
  57. public synchronized void close() throws SQLException {
  58. boolean isClosed = false;
  59. try {
  60. isClosed = isClosed();
  61. } catch (SQLException e) {
  62. try {
  63. _pool.invalidateObject(this);
  64. } catch (Exception ie) {
  65. // DO NOTHING the original exception will be rethrown
  66. }
  67. throw new SQLNestedException("Cannot close connection (isClosed check failed)", e);
  68. }
  69. if (isClosed) {
  70. throw new SQLException("Already closed.");
  71. } else {
  72. try {
  73. _pool.returnObject(this);
  74. } catch(SQLException e) {
  75. throw e;
  76. } catch(RuntimeException e) {
  77. throw e;
  78. } catch(Exception e) {
  79. throw new SQLNestedException("Cannot close connection (return to pool failed)", e);
  80. }
  81. }
  82. }
  83. /**
  84. * Actually close my underlying {@link Connection}.
  85. */
  86. public void reallyClose() throws SQLException {
  87. super.close();
  88. }
  89. }