Example usage for org.apache.commons.dbcp2.managed PoolableManagedConnectionFactory PoolableManagedConnectionFactory

List of usage examples for org.apache.commons.dbcp2.managed PoolableManagedConnectionFactory PoolableManagedConnectionFactory

Introduction

In this page you can find the example usage for org.apache.commons.dbcp2.managed PoolableManagedConnectionFactory PoolableManagedConnectionFactory.

Prototype

public PoolableManagedConnectionFactory(XAConnectionFactory connFactory, ObjectName dataSourceJmxName) 

Source Link

Document

Create a PoolableManagedConnectionFactory and attach it to a connection pool.

Usage

From source file:org.apache.ofbiz.entity.connection.DBCPConnectionFactory.java

public Connection getConnection(GenericHelperInfo helperInfo, JdbcElement abstractJdbc)
        throws SQLException, GenericEntityException {
    String cacheKey = helperInfo.getHelperFullName();
    DebugManagedDataSource mds = dsCache.get(cacheKey);
    if (mds != null) {
        return TransactionUtil.getCursorConnection(helperInfo, mds.getConnection());
    }// w  w  w  .j a v  a  2  s .co  m
    if (!(abstractJdbc instanceof InlineJdbc)) {
        throw new GenericEntityConfException(
                "DBCP requires an <inline-jdbc> child element in the <datasource> element");
    }
    InlineJdbc jdbcElement = (InlineJdbc) abstractJdbc;
    // connection properties
    TransactionManager txMgr = TransactionFactoryLoader.getInstance().getTransactionManager();
    String driverName = jdbcElement.getJdbcDriver();

    String jdbcUri = helperInfo.getOverrideJdbcUri(jdbcElement.getJdbcUri());
    String jdbcUsername = helperInfo.getOverrideUsername(jdbcElement.getJdbcUsername());
    String jdbcPassword = helperInfo.getOverridePassword(EntityConfig.getJdbcPassword(jdbcElement));

    // pool settings
    int maxSize = jdbcElement.getPoolMaxsize();
    int minSize = jdbcElement.getPoolMinsize();
    int maxIdle = jdbcElement.getIdleMaxsize();
    // maxIdle must be greater than pool-minsize
    maxIdle = maxIdle > minSize ? maxIdle : minSize;
    // load the driver
    Driver jdbcDriver;
    synchronized (DBCPConnectionFactory.class) {
        // Sync needed for MS SQL JDBC driver. See OFBIZ-5216.
        try {
            jdbcDriver = (Driver) Class
                    .forName(driverName, true, Thread.currentThread().getContextClassLoader()).newInstance();
        } catch (Exception e) {
            Debug.logError(e, module);
            throw new GenericEntityException(e.getMessage(), e);
        }
    }

    // connection factory properties
    Properties cfProps = new Properties();
    cfProps.put("user", jdbcUsername);
    cfProps.put("password", jdbcPassword);

    // create the connection factory
    org.apache.commons.dbcp2.ConnectionFactory cf = new DriverConnectionFactory(jdbcDriver, jdbcUri, cfProps);

    // wrap it with a LocalXAConnectionFactory
    XAConnectionFactory xacf = new LocalXAConnectionFactory(txMgr, cf);

    // create the pool object factory
    PoolableConnectionFactory factory = new PoolableManagedConnectionFactory(xacf, null);
    factory.setValidationQuery(jdbcElement.getPoolJdbcTestStmt());
    factory.setDefaultReadOnly(false);
    factory.setRollbackOnReturn(false);
    factory.setEnableAutoCommitOnReturn(false);
    String transIso = jdbcElement.getIsolationLevel();
    if (!transIso.isEmpty()) {
        if ("Serializable".equals(transIso)) {
            factory.setDefaultTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
        } else if ("RepeatableRead".equals(transIso)) {
            factory.setDefaultTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
        } else if ("ReadUncommitted".equals(transIso)) {
            factory.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
        } else if ("ReadCommitted".equals(transIso)) {
            factory.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        } else if ("None".equals(transIso)) {
            factory.setDefaultTransactionIsolation(Connection.TRANSACTION_NONE);
        }
    }

    // configure the pool settings
    GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
    poolConfig.setMaxTotal(maxSize);
    // settings for idle connections
    poolConfig.setMaxIdle(maxIdle);
    poolConfig.setMinIdle(minSize);
    poolConfig.setTimeBetweenEvictionRunsMillis(jdbcElement.getTimeBetweenEvictionRunsMillis());
    poolConfig.setMinEvictableIdleTimeMillis(-1); // disabled in favour of setSoftMinEvictableIdleTimeMillis(...)
    poolConfig.setSoftMinEvictableIdleTimeMillis(jdbcElement.getSoftMinEvictableIdleTimeMillis());
    poolConfig.setNumTestsPerEvictionRun(maxSize); // test all the idle connections
    // settings for when the pool is exhausted
    poolConfig.setBlockWhenExhausted(true); // the thread requesting the connection waits if no connection is available
    poolConfig.setMaxWaitMillis(jdbcElement.getPoolSleeptime()); // throw an exception if, after getPoolSleeptime() ms, no connection is available for the requesting thread
    // settings for the execution of the validation query
    poolConfig.setTestOnCreate(jdbcElement.getTestOnCreate());
    poolConfig.setTestOnBorrow(jdbcElement.getTestOnBorrow());
    poolConfig.setTestOnReturn(jdbcElement.getTestOnReturn());
    poolConfig.setTestWhileIdle(jdbcElement.getTestWhileIdle());

    GenericObjectPool<PoolableConnection> pool = new GenericObjectPool<PoolableConnection>(factory, poolConfig);
    factory.setPool(pool);

    mds = new DebugManagedDataSource(pool, xacf.getTransactionRegistry());
    mds.setAccessToUnderlyingConnectionAllowed(true);

    // cache the pool
    dsCache.putIfAbsent(cacheKey, mds);
    mds = dsCache.get(cacheKey);

    return TransactionUtil.getCursorConnection(helperInfo, mds.getConnection());
}

From source file:org.noerp.entity.connection.DBCPConnectionFactory.java

public Connection getConnection(GenericHelperInfo helperInfo, JdbcElement abstractJdbc)
        throws SQLException, GenericEntityException {
    String cacheKey = helperInfo.getHelperFullName();
    ManagedDataSource mds = dsCache.get(cacheKey);
    if (mds != null) {
        return TransactionUtil.getCursorConnection(helperInfo, mds.getConnection());
    }/*ww w  . j  av  a2 s . com*/
    if (!(abstractJdbc instanceof InlineJdbc)) {
        throw new GenericEntityConfException(
                "DBCP requires an <inline-jdbc> child element in the <datasource> element");
    }
    InlineJdbc jdbcElement = (InlineJdbc) abstractJdbc;
    // connection properties
    TransactionManager txMgr = TransactionFactoryLoader.getInstance().getTransactionManager();
    String driverName = jdbcElement.getJdbcDriver();

    String jdbcUri = helperInfo.getOverrideJdbcUri(jdbcElement.getJdbcUri());
    String jdbcUsername = helperInfo.getOverrideUsername(jdbcElement.getJdbcUsername());
    String jdbcPassword = helperInfo.getOverridePassword(EntityConfig.getJdbcPassword(jdbcElement));

    // pool settings
    int maxSize = jdbcElement.getPoolMaxsize();
    int minSize = jdbcElement.getPoolMinsize();
    int maxIdle = jdbcElement.getIdleMaxsize();
    // maxIdle must be greater than pool-minsize
    maxIdle = maxIdle > minSize ? maxIdle : minSize;
    // load the driver
    Driver jdbcDriver;
    synchronized (DBCPConnectionFactory.class) {
        // Sync needed for MS SQL JDBC driver. See OFBIZ-5216.
        try {
            jdbcDriver = (Driver) Class
                    .forName(driverName, true, Thread.currentThread().getContextClassLoader()).newInstance();
        } catch (Exception e) {
            Debug.logError(e, module);
            throw new GenericEntityException(e.getMessage(), e);
        }
    }

    // connection factory properties
    Properties cfProps = new Properties();
    cfProps.put("user", jdbcUsername);
    cfProps.put("password", jdbcPassword);

    // create the connection factory
    org.apache.commons.dbcp2.ConnectionFactory cf = new DriverConnectionFactory(jdbcDriver, jdbcUri, cfProps);

    // wrap it with a LocalXAConnectionFactory
    XAConnectionFactory xacf = new LocalXAConnectionFactory(txMgr, cf);

    // create the pool object factory
    PoolableConnectionFactory factory = new PoolableManagedConnectionFactory(xacf, null);
    factory.setValidationQuery(jdbcElement.getPoolJdbcTestStmt());
    factory.setDefaultReadOnly(false);
    String transIso = jdbcElement.getIsolationLevel();
    if (!transIso.isEmpty()) {
        if ("Serializable".equals(transIso)) {
            factory.setDefaultTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
        } else if ("RepeatableRead".equals(transIso)) {
            factory.setDefaultTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
        } else if ("ReadUncommitted".equals(transIso)) {
            factory.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
        } else if ("ReadCommitted".equals(transIso)) {
            factory.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        } else if ("None".equals(transIso)) {
            factory.setDefaultTransactionIsolation(Connection.TRANSACTION_NONE);
        }
    }

    // configure the pool settings
    GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
    poolConfig.setMaxTotal(maxSize);
    // settings for idle connections
    poolConfig.setMaxIdle(maxIdle);
    poolConfig.setMinIdle(minSize);
    poolConfig.setTimeBetweenEvictionRunsMillis(jdbcElement.getTimeBetweenEvictionRunsMillis());
    poolConfig.setMinEvictableIdleTimeMillis(-1); // disabled in favour of setSoftMinEvictableIdleTimeMillis(...)
    poolConfig.setSoftMinEvictableIdleTimeMillis(jdbcElement.getSoftMinEvictableIdleTimeMillis());
    poolConfig.setNumTestsPerEvictionRun(maxSize); // test all the idle connections
    // settings for when the pool is exhausted
    poolConfig.setBlockWhenExhausted(true); // the thread requesting the connection waits if no connection is available
    poolConfig.setMaxWaitMillis(jdbcElement.getPoolSleeptime()); // throw an exception if, after getPoolSleeptime() ms, no connection is available for the requesting thread
    // settings for the execution of the validation query
    poolConfig.setTestOnCreate(jdbcElement.getTestOnCreate());
    poolConfig.setTestOnBorrow(jdbcElement.getTestOnBorrow());
    poolConfig.setTestOnReturn(jdbcElement.getTestOnReturn());
    poolConfig.setTestWhileIdle(jdbcElement.getTestWhileIdle());

    GenericObjectPool pool = new GenericObjectPool(factory, poolConfig);
    factory.setPool(pool);

    mds = new ManagedDataSource(pool, xacf.getTransactionRegistry());
    //mds = new DebugManagedDataSource(pool, xacf.getTransactionRegistry()); // Useful to debug the usage of connections in the pool
    mds.setAccessToUnderlyingConnectionAllowed(true);

    // cache the pool
    dsCache.putIfAbsent(cacheKey, mds);
    mds = dsCache.get(cacheKey);

    return TransactionUtil.getCursorConnection(helperInfo, mds.getConnection());
}

From source file:org.ops4j.pax.jdbc.pool.dbcp2.impl.DbcpXAPooledDataSourceFactory.java

@Override
public DataSource create(DataSourceFactory dsf, Properties props) throws SQLException {
    try {//from  ww w . j  a  v  a 2  s. c  o  m
        XADataSource ds = dsf.createXADataSource(getNonPoolProps(props));
        DataSourceXAConnectionFactory connFactory = new DataSourceXAConnectionFactory(tm, (XADataSource) ds);
        PoolableManagedConnectionFactory pcf = new PoolableManagedConnectionFactory(connFactory, null);
        GenericObjectPoolConfig conf = new GenericObjectPoolConfig();
        BeanConfig.configure(conf, getPoolProps(props));
        BeanConfig.configure(pcf, getPrefixed(props, FACTORY_PREFIX));
        GenericObjectPool<PoolableConnection> pool = new GenericObjectPool<PoolableConnection>(pcf, conf);
        pcf.setPool(pool);
        TransactionRegistry transactionRegistry = connFactory.getTransactionRegistry();
        return new ManagedDataSource<PoolableConnection>(pool, transactionRegistry);
    } catch (Throwable e) {
        LOG.error("Error creating pooled datasource" + e.getMessage(), e);
        if (e instanceof SQLException) {
            throw (SQLException) e;
        } else if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        } else {
            throw new RuntimeException(e.getMessage(), e);
        }
    }
}

From source file:org.ops4j.pax.jdbc.pool.dbcp2.impl.ds.DbcpXAPooledDataSourceFactory.java

@Override
public DataSource createDataSource(Properties props) throws SQLException {
    try {/* w  ww.j a  v a2 s  . c  o  m*/
        XADataSource ds = dsFactory.createXADataSource(getNonPoolProps(props));
        DataSourceXAConnectionFactory connFactory = new DataSourceXAConnectionFactory(tm, (XADataSource) ds);
        PoolableManagedConnectionFactory pcf = new PoolableManagedConnectionFactory(connFactory, null);
        GenericObjectPoolConfig conf = new GenericObjectPoolConfig();
        BeanConfig.configure(conf, getPoolProps(props));
        BeanConfig.configure(pcf, getPrefixed(props, FACTORY_PREFIX));
        GenericObjectPool<PoolableConnection> pool = new GenericObjectPool<PoolableConnection>(pcf, conf);
        pcf.setPool(pool);
        TransactionRegistry transactionRegistry = connFactory.getTransactionRegistry();
        return new ManagedDataSource<PoolableConnection>(pool, transactionRegistry);
    } catch (Throwable e) {
        LOG.error("Error creating pooled datasource" + e.getMessage(), e);
        if (e instanceof SQLException) {
            throw (SQLException) e;
        } else if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        } else {
            throw new RuntimeException(e.getMessage(), e);
        }
    }
}

From source file:org.ops4j.pax.jdbc.pool.dbcp2.impl.ds.XAPooledDataSourceFactory.java

@Override
protected DataSource createDataSourceInternal(Properties props, Map<String, String> poolProps)
        throws SQLException {
    XADataSource ds = dsFactory.createXADataSource(props);
    DataSourceXAConnectionFactory connFactory = new DataSourceXAConnectionFactory(tm, ds);
    PoolableManagedConnectionFactory pcf = new PoolableManagedConnectionFactory(connFactory, null);
    GenericObjectPoolConfig conf = new GenericObjectPoolConfig();
    BeanConfig.configure(conf, poolProps);
    GenericObjectPool<PoolableConnection> pool = new GenericObjectPool<PoolableConnection>(pcf, conf);
    TransactionRegistry transactionRegistry = connFactory.getTransactionRegistry();
    return new CloseableManagedDataSource<PoolableConnection>(pool, transactionRegistry);
}

From source file:org.ops4j.pax.jdbc.pool.narayana.impl.DbcpXAPooledDataSourceFactory.java

@Override
public DataSource create(DataSourceFactory dsf, Properties props) throws SQLException {
    try {// ww  w  . java2 s.c o  m
        final XADataSource ds = dsf.createXADataSource(getNonPoolProps(props));
        DataSourceXAConnectionFactory connFactory = new DataSourceXAConnectionFactory(tm, (XADataSource) ds);
        PoolableManagedConnectionFactory pcf = new PoolableManagedConnectionFactory(connFactory, null);
        GenericObjectPoolConfig conf = new GenericObjectPoolConfig();
        BeanConfig.configure(conf, getPoolProps(props));
        BeanConfig.configure(pcf, getPrefixed(props, FACTORY_PREFIX));
        GenericObjectPool<PoolableConnection> pool = new GenericObjectPool<PoolableConnection>(pcf, conf);
        pcf.setPool(pool);
        TransactionRegistry transactionRegistry = connFactory.getTransactionRegistry();
        final ServiceRegistration<XAResourceRecovery> registration = bundleContext
                .registerService(XAResourceRecovery.class, new XAResourceRecovery() {
                    @Override
                    public XAResource[] getXAResources() {
                        try {
                            return new XAResource[] { new Wrapper(ds.getXAConnection()) };
                        } catch (SQLException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }, null);
        ManagedDataSource<PoolableConnection> mds = new ManagedDataSource<PoolableConnection>(pool,
                transactionRegistry) {
            @Override
            public void close() throws Exception {
                registration.unregister();
                super.close();
            }
        };
        return mds;
    } catch (Throwable e) {
        LOG.error("Error creating pooled datasource" + e.getMessage(), e);
        if (e instanceof SQLException) {
            throw (SQLException) e;
        } else if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        } else {
            throw new RuntimeException(e.getMessage(), e);
        }
    }
}

From source file:org.ops4j.pax.jdbc.pool.narayana.impl.ds.DbcpXAPooledDataSourceFactory.java

@Override
public DataSource createDataSource(Properties props) throws SQLException {
    try {/*from   w  w w .ja va  2s.c om*/
        final XADataSource ds = dsFactory.createXADataSource(getNonPoolProps(props));
        DataSourceXAConnectionFactory connFactory = new DataSourceXAConnectionFactory(tm, (XADataSource) ds);
        PoolableManagedConnectionFactory pcf = new PoolableManagedConnectionFactory(connFactory, null);
        GenericObjectPoolConfig conf = new GenericObjectPoolConfig();
        BeanConfig.configure(conf, getPoolProps(props));
        BeanConfig.configure(pcf, getPrefixed(props, FACTORY_PREFIX));
        GenericObjectPool<PoolableConnection> pool = new GenericObjectPool<PoolableConnection>(pcf, conf);
        pcf.setPool(pool);
        TransactionRegistry transactionRegistry = connFactory.getTransactionRegistry();
        final ServiceRegistration<XAResourceRecovery> registration = bundleContext
                .registerService(XAResourceRecovery.class, new XAResourceRecovery() {
                    @Override
                    public XAResource[] getXAResources() {
                        try {
                            return new XAResource[] { new Wrapper(ds.getXAConnection()) };
                        } catch (SQLException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }, null);
        ManagedDataSource mds = new ManagedDataSource<PoolableConnection>(pool, transactionRegistry) {
            @Override
            public void close() throws Exception {
                registration.unregister();
                super.close();
            }
        };
        return mds;
    } catch (Throwable e) {
        LOG.error("Error creating pooled datasource" + e.getMessage(), e);
        if (e instanceof SQLException) {
            throw (SQLException) e;
        } else if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        } else {
            throw new RuntimeException(e.getMessage(), e);
        }
    }
}