PoolingDataSource.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.apache.commons.dbcp2;

  18. import java.io.PrintWriter;
  19. import java.sql.Connection;
  20. import java.sql.SQLException;
  21. import java.sql.SQLFeatureNotSupportedException;
  22. import java.util.NoSuchElementException;
  23. import java.util.Objects;
  24. import java.util.logging.Logger;

  25. import javax.sql.DataSource;

  26. import org.apache.commons.logging.Log;
  27. import org.apache.commons.logging.LogFactory;
  28. import org.apache.commons.pool2.ObjectPool;
  29. import org.apache.commons.pool2.impl.GenericObjectPool;

  30. /**
  31.  * A simple {@link DataSource} implementation that obtains {@link Connection}s from the specified {@link ObjectPool}.
  32.  *
  33.  * @param <C>
  34.  *            The connection type
  35.  *
  36.  * @since 2.0
  37.  */
  38. public class PoolingDataSource<C extends Connection> implements DataSource, AutoCloseable {

  39.     /**
  40.      * PoolGuardConnectionWrapper is a Connection wrapper that makes sure a closed connection cannot be used anymore.
  41.      *
  42.      * @since 2.0
  43.      */
  44.     private final class PoolGuardConnectionWrapper<D extends Connection> extends DelegatingConnection<D> {

  45.         PoolGuardConnectionWrapper(final D delegate) {
  46.             super(delegate);
  47.         }

  48.         @Override
  49.         public void close() throws SQLException {
  50.             if (getDelegateInternal() != null) {
  51.                 super.close();
  52.                 super.setDelegate(null);
  53.             }
  54.         }

  55.         /**
  56.          * @see org.apache.commons.dbcp2.DelegatingConnection#getDelegate()
  57.          */
  58.         @Override
  59.         public D getDelegate() {
  60.             return isAccessToUnderlyingConnectionAllowed() ? super.getDelegate() : null;
  61.         }

  62.         /**
  63.          * @see org.apache.commons.dbcp2.DelegatingConnection#getInnermostDelegate()
  64.          */
  65.         @Override
  66.         public Connection getInnermostDelegate() {
  67.             return isAccessToUnderlyingConnectionAllowed() ? super.getInnermostDelegate() : null;
  68.         }

  69.         @Override
  70.         public boolean isClosed() throws SQLException {
  71.             return getDelegateInternal() == null || super.isClosed();
  72.         }
  73.     }

  74.     private static final Log log = LogFactory.getLog(PoolingDataSource.class);

  75.     /** Controls access to the underlying connection */
  76.     private boolean accessToUnderlyingConnectionAllowed;

  77.     /** My log writer. */
  78.     private PrintWriter logWriter;

  79.     private final ObjectPool<C> pool;

  80.     /**
  81.      * Constructs a new instance backed by the given connection pool.
  82.      *
  83.      * @param pool
  84.      *            the given connection pool.
  85.      */
  86.     public PoolingDataSource(final ObjectPool<C> pool) {
  87.         Objects.requireNonNull(pool, "pool");
  88.         this.pool = pool;
  89.         // Verify that pool's factory refers back to it. If not, log a warning and try to fix.
  90.         if (this.pool instanceof GenericObjectPool<?>) {
  91.             final PoolableConnectionFactory pcf = (PoolableConnectionFactory) ((GenericObjectPool<?>) this.pool).getFactory();
  92.             Objects.requireNonNull(pcf, "this.pool.getFactory()");
  93.             if (pcf.getPool() != this.pool) {
  94.                 log.warn(Utils.getMessage("poolingDataSource.factoryConfig"));
  95.                 @SuppressWarnings("unchecked") // PCF must have a pool of PCs
  96.                 final ObjectPool<PoolableConnection> p = (ObjectPool<PoolableConnection>) this.pool;
  97.                 pcf.setPool(p);
  98.             }
  99.         }
  100.     }

  101.     /**
  102.      * Closes and free all {@link Connection}s from the pool.
  103.      *
  104.      * @since 2.1
  105.      */
  106.     @Override
  107.     public void close() throws SQLException {
  108.         try {
  109.             pool.close();
  110.         } catch (final Exception e) {
  111.             throw new SQLException(Utils.getMessage("pool.close.fail"), e);
  112.         }
  113.     }

  114.     /**
  115.      * Returns a {@link java.sql.Connection} from my pool, according to the contract specified by
  116.      * {@link ObjectPool#borrowObject}.
  117.      */
  118.     @Override
  119.     public Connection getConnection() throws SQLException {
  120.         try {
  121.             final C conn = pool.borrowObject();
  122.             if (conn == null) {
  123.                 return null;
  124.             }
  125.             return new PoolGuardConnectionWrapper<>(conn);
  126.         } catch (final NoSuchElementException e) {
  127.             throw new SQLException("Cannot get a connection, pool error " + e.getMessage(), e);
  128.         } catch (final SQLException | RuntimeException e) {
  129.             throw e;
  130.         } catch (final InterruptedException e) {
  131.             // Reset the interrupt status so it is visible to callers
  132.             Thread.currentThread().interrupt();
  133.             throw new SQLException("Cannot get a connection, general error", e);
  134.         } catch (final Exception e) {
  135.             throw new SQLException("Cannot get a connection, general error", e);
  136.         }
  137.     }

  138.     /**
  139.      * Throws {@link UnsupportedOperationException}
  140.      *
  141.      * @throws UnsupportedOperationException
  142.      *             always thrown
  143.      */
  144.     @Override
  145.     public Connection getConnection(final String userName, final String password) throws SQLException {
  146.         throw new UnsupportedOperationException();
  147.     }


  148.     /**
  149.      * Throws {@link UnsupportedOperationException}.
  150.      *
  151.      * @throws UnsupportedOperationException
  152.      *             As this implementation does not support this feature.
  153.      */
  154.     @Override
  155.     public int getLoginTimeout() {
  156.         throw new UnsupportedOperationException("Login timeout is not supported.");
  157.     }

  158.     /**
  159.      * Returns my log writer.
  160.      *
  161.      * @return my log writer
  162.      * @see DataSource#getLogWriter
  163.      */
  164.     @Override
  165.     public PrintWriter getLogWriter() {
  166.         return logWriter;
  167.     }

  168.     @Override
  169.     public Logger getParentLogger() throws SQLFeatureNotSupportedException {
  170.         throw new SQLFeatureNotSupportedException();
  171.     }

  172.     /**
  173.      * Gets the backing object pool.
  174.      *
  175.      * @return the backing object pool.
  176.      */
  177.     protected ObjectPool<C> getPool() {
  178.         return pool;
  179.     }

  180.     /**
  181.      * Returns the value of the accessToUnderlyingConnectionAllowed property.
  182.      *
  183.      * @return true if access to the underlying {@link Connection} is allowed, false otherwise.
  184.      */
  185.     public boolean isAccessToUnderlyingConnectionAllowed() {
  186.         return this.accessToUnderlyingConnectionAllowed;
  187.     }

  188.     @Override
  189.     public boolean isWrapperFor(final Class<?> iface) throws SQLException {
  190.         return iface != null && iface.isInstance(this);
  191.     }

  192.     /**
  193.      * Sets the value of the accessToUnderlyingConnectionAllowed property. It controls if the PoolGuard allows access to
  194.      * the underlying connection. (Default: false)
  195.      *
  196.      * @param allow
  197.      *            Access to the underlying connection is granted when true.
  198.      */
  199.     public void setAccessToUnderlyingConnectionAllowed(final boolean allow) {
  200.         this.accessToUnderlyingConnectionAllowed = allow;
  201.     }

  202.     /**
  203.      * Throws {@link UnsupportedOperationException}.
  204.      *
  205.      * @throws UnsupportedOperationException
  206.      *             As this implementation does not support this feature.
  207.      */
  208.     @Override
  209.     public void setLoginTimeout(final int seconds) {
  210.         throw new UnsupportedOperationException("Login timeout is not supported.");
  211.     }

  212.     /**
  213.      * Sets my log writer.
  214.      *
  215.      * @see DataSource#setLogWriter
  216.      */
  217.     @Override
  218.     public void setLogWriter(final PrintWriter out) {
  219.         logWriter = out;
  220.     }

  221.     @Override
  222.     public <T> T unwrap(final Class<T> iface) throws SQLException {
  223.         if (isWrapperFor(iface)) {
  224.             return iface.cast(this);
  225.         }
  226.         throw new SQLException(this + " is not a wrapper for " + iface);
  227.     }
  228. }