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.managed;
019import java.sql.Connection;
020
021import javax.management.ObjectName;
022
023import org.apache.commons.dbcp2.Constants;
024import org.apache.commons.dbcp2.DelegatingPreparedStatement;
025import org.apache.commons.dbcp2.PStmtKey;
026import org.apache.commons.dbcp2.PoolableConnection;
027import org.apache.commons.dbcp2.PoolableConnectionFactory;
028import org.apache.commons.dbcp2.PoolingConnection;
029import org.apache.commons.pool2.KeyedObjectPool;
030import org.apache.commons.pool2.PooledObject;
031import org.apache.commons.pool2.impl.GenericKeyedObjectPool;
032import org.apache.commons.pool2.impl.GenericKeyedObjectPoolConfig;
033import org.apache.commons.pool2.impl.DefaultPooledObject;
034
035/**
036 * A {@link PoolableConnectionFactory} that creates {@link PoolableManagedConnection}s.
037 *
038 * @version $Id: PoolableManagedConnectionFactory.java 1659452 2015-02-13 04:00:39Z psteitz $
039 * @since 2.0
040 */
041public class PoolableManagedConnectionFactory extends PoolableConnectionFactory {
042
043    /** Transaction registry associated with connections created by this factory */
044    private final TransactionRegistry transactionRegistry;
045
046    /**
047     * Create a PoolableManagedConnectionFactory and attach it to a connection pool.
048     *
049     * @param connFactory XAConnectionFactory
050     */
051    public PoolableManagedConnectionFactory(XAConnectionFactory connFactory,
052            ObjectName dataSourceJmxName) {
053        super(connFactory, dataSourceJmxName);
054        this.transactionRegistry = connFactory.getTransactionRegistry();
055    }
056
057    /**
058     * Uses the configured XAConnectionFactory to create a {@link PoolableManagedConnection}.
059     * Throws <code>IllegalStateException</code> if the connection factory returns null.
060     * Also initializes the connection using configured initialization sql (if provided)
061     * and sets up a prepared statement pool associated with the PoolableManagedConnection
062     * if statement pooling is enabled.
063     */
064    @Override
065    synchronized public PooledObject<PoolableConnection> makeObject() throws Exception {
066        Connection conn = getConnectionFactory().createConnection();
067        if (conn == null) {
068            throw new IllegalStateException("Connection factory returned null from createConnection");
069        }
070        initializeConnection(conn);
071        if (getPoolStatements()) {
072            conn = new PoolingConnection(conn);
073            GenericKeyedObjectPoolConfig config = new GenericKeyedObjectPoolConfig();
074            config.setMaxTotalPerKey(-1);
075            config.setBlockWhenExhausted(false);
076            config.setMaxWaitMillis(0);
077            config.setMaxIdlePerKey(1);
078            config.setMaxTotal(getMaxOpenPreparedStatements());
079            ObjectName dataSourceJmxName = getDataSourceJmxName();
080            long connIndex = getConnectionIndex().getAndIncrement();
081            if (dataSourceJmxName != null) {
082                StringBuilder base = new StringBuilder(dataSourceJmxName.toString());
083                base.append(Constants.JMX_CONNECTION_BASE_EXT);
084                base.append(Long.toString(connIndex));
085                config.setJmxNameBase(base.toString());
086                config.setJmxNamePrefix(Constants.JMX_STATEMENT_POOL_PREFIX);
087            } else {
088                config.setJmxEnabled(false);
089            }
090            KeyedObjectPool<PStmtKey,DelegatingPreparedStatement> stmtPool =
091                new GenericKeyedObjectPool<>((PoolingConnection)conn, config);
092            ((PoolingConnection)conn).setStatementPool(stmtPool);
093            ((PoolingConnection) conn).setCacheState(getCacheState());
094        }
095        return new DefaultPooledObject<PoolableConnection>(
096                new PoolableManagedConnection(transactionRegistry, conn, getPool()));
097    }
098}