001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017
018package org.apache.commons.dbcp2;
019
020import java.sql.CallableStatement;
021import java.sql.Connection;
022import java.sql.ResultSet;
023import java.sql.SQLException;
024import java.util.ArrayList;
025import java.util.List;
026
027import org.apache.commons.pool2.KeyedObjectPool;
028
029/**
030 * A {@link DelegatingCallableStatement} that cooperates with {@link PoolingConnection} to implement a pool of
031 * {@link CallableStatement}s.
032 * <p>
033 * The {@link #close} method returns this statement to its containing pool. (See {@link PoolingConnection}.)
034 *
035 * @see PoolingConnection
036 * @since 2.0
037 */
038public class PoolableCallableStatement extends DelegatingCallableStatement {
039
040    /**
041     * The {@link KeyedObjectPool} from which this CallableStatement was obtained.
042     */
043    private final KeyedObjectPool<PStmtKey, DelegatingPreparedStatement> pool;
044
045    /**
046     * Key for this statement in the containing {@link KeyedObjectPool}.
047     */
048    private final PStmtKey key;
049
050    /**
051     * Constructor.
052     *
053     * @param callableStatement
054     *            the underlying {@link CallableStatement}
055     * @param key
056     *            the key for this statement in the {@link KeyedObjectPool}
057     * @param pool
058     *            the {@link KeyedObjectPool} from which this CallableStatement was obtained
059     * @param connection
060     *            the {@link DelegatingConnection} that created this CallableStatement
061     */
062    public PoolableCallableStatement(final CallableStatement callableStatement, final PStmtKey key,
063            final KeyedObjectPool<PStmtKey, DelegatingPreparedStatement> pool,
064            final DelegatingConnection<Connection> connection) {
065        super(connection, callableStatement);
066        this.pool = pool;
067        this.key = key;
068
069        // Remove from trace now because this statement will be
070        // added by the activate method.
071        removeThisTrace(getConnectionInternal());
072    }
073
074    /**
075     * Activates after retrieval from the pool. Adds a trace for this CallableStatement to the Connection that created
076     * it.
077     *
078     * @since 2.4.0 made public, was protected in 2.3.0.
079     */
080    @Override
081    public void activate() throws SQLException {
082        setClosedInternal(false);
083        if (getConnectionInternal() != null) {
084            getConnectionInternal().addTrace(this);
085        }
086        super.activate();
087    }
088
089    /**
090     * Returns the CallableStatement to the pool. If {{@link #isClosed()}, this is a No-op.
091     */
092    @Override
093    public void close() throws SQLException {
094        // calling close twice should have no effect
095        if (!isClosed()) {
096            try {
097                pool.returnObject(key, this);
098            } catch (final SQLException | RuntimeException e) {
099                throw e;
100            } catch (final Exception e) {
101                throw new SQLException("Cannot close CallableStatement (return to pool failed)", e);
102            }
103        }
104    }
105
106    /**
107     * Passivates to prepare for return to the pool. Removes the trace associated with this CallableStatement from the
108     * Connection that created it. Also closes any associated ResultSets.
109     *
110     * @since 2.4.0 made public, was protected in 2.3.0.
111     */
112    @Override
113    public void passivate() throws SQLException {
114        setClosedInternal(true);
115        removeThisTrace(getConnectionInternal());
116
117        // The JDBC spec requires that a statement close any open
118        // ResultSet's when it is closed.
119        // FIXME The PreparedStatement we're wrapping should handle this for us.
120        // See DBCP-10 for what could happen when ResultSets are closed twice.
121        final List<AbandonedTrace> resultSetList = getTrace();
122        if (resultSetList != null) {
123            final List<Exception> thrownList = new ArrayList<>();
124            final ResultSet[] resultSets = resultSetList.toArray(Utils.EMPTY_RESULT_SET_ARRAY);
125            for (final ResultSet resultSet : resultSets) {
126                if (resultSet != null) {
127                    try {
128                        resultSet.close();
129                    } catch (final Exception e) {
130                        thrownList.add(e);
131                    }
132                }
133            }
134            clearTrace();
135            if (!thrownList.isEmpty()) {
136                throw new SQLExceptionList(thrownList);
137            }
138        }
139
140        super.passivate();
141    }
142
143}