Java Code Examples for org.apache.commons.dbcp.PoolingDataSource

The following examples show how to use org.apache.commons.dbcp.PoolingDataSource. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@Test
public void testCreatePool() throws Exception {
  DatabaseConnection con = ConnectionUtil.createConnection();
  con.getAttributes().put( DatabaseConnection.ATTRIBUTE_CUSTOM_DRIVER_CLASS, ConnectionUtil.DRIVER_CLASS );
  con.getAttributes().put( DatabaseConnection.ATTRIBUTE_CUSTOM_URL, ConnectionUtil.CON_URL );

  PoolingDataSource poolingDataSource = PooledDatasourceHelper.setupPooledDataSource( con );

  assertThat( poolingDataSource, is( notNullValue() ) );
  Connection connection = poolingDataSource.getConnection();
  assertThat( connection, is( notNullValue() ) );
  connection.close();

  DataSourceCacheManager cacheManager =
      ClassicEngineBoot.getInstance().getObjectFactory().get( DataSourceCacheManager.class );
  DataSource ds = cacheManager.getDataSourceCache().get( con.getName() );
  assertThat( ds, is( instanceOf( PoolingDataSource.class ) ) );
  assertThat( (PoolingDataSource) ds, is( equalTo( poolingDataSource ) ) );
}
 
Example 2
@Test
public void testCreatePoolWithAttrs() throws Exception {
  DatabaseConnection con = ConnectionUtil.createConnectionWithAttrs();

  PoolingDataSource poolingDataSource = PooledDatasourceHelper.setupPooledDataSource( con );

  assertThat( poolingDataSource, is( notNullValue() ) );
  Connection connection = poolingDataSource.getConnection();
  assertThat( connection, is( notNullValue() ) );
  connection.close();

  DataSourceCacheManager cacheManager =
      ClassicEngineBoot.getInstance().getObjectFactory().get( DataSourceCacheManager.class );
  DataSource ds = cacheManager.getDataSourceCache().get( con.getName() );
  assertThat( ds, is( instanceOf( PoolingDataSource.class ) ) );
  assertThat( (PoolingDataSource) ds, is( equalTo( poolingDataSource ) ) );
}
 
Example 3
Source Project: openemm   Source File: DBase.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public DataSource newDataSource (String driver, String connect, String login, String password) {
	ObjectPool <Object>		connectionPool = new GenericObjectPool<>(null, dsPoolsize, (dsPoolgrow ? GenericObjectPool.WHEN_EXHAUSTED_GROW : GenericObjectPool.WHEN_EXHAUSTED_BLOCK), 0);
	ConnectionFactory		connectionFactory = new DriverManagerConnectionFactory (connect, login, password);

	// THIS IS REQUIRED DUE TO INTERNAL SIDE EFFECTS, DO NOT REMOVE THIS (AGAIN)!
	@SuppressWarnings("unused")
	PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory (connectionFactory, connectionPool, null, null, false, true);
	log.out (Log.INFO, "nds", "New data source for " + driver + " using " + connect + " with " + login + " created (poolsize " + dsPoolsize + ", grow is " + dsPoolgrow + ")");
	return new PoolingDataSource (connectionPool);
}
 
Example 4
Source Project: snowflake-jdbc   Source File: ConnectionPoolingIT.java    License: Apache License 2.0 5 votes vote down vote up
private PoolingDataSource setUpPoolingDataSource() throws Exception
{
  Class.forName(BaseJDBCTest.DRIVER_CLASS);
  connectionPool = new GenericObjectPool();
  connectionPool.setMaxActive(20);
  return new PoolingDataSource(connectionPool);
}
 
Example 5
Source Project: snowflake-jdbc   Source File: ConnectionPoolingIT.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testPoolingDataSource() throws Exception, SQLException
{
  PoolingDataSource pds = setUpPoolingDataSource();
  for (int i = 0; i < 10; i++)
  {
    Thread t = new Thread(new queryUsingPool(pds));
    t.join();
  }
}
 
Example 6
Source Project: ralasafe   Source File: DataSourceProviderDbcpImpl.java    License: MIT License 5 votes vote down vote up
public void setup( Properties prop ) {
	this.prop=prop;

       GenericObjectPool.Config conPoolCfg = new GenericObjectPool.Config();
       conPoolCfg.maxActive = Integer.parseInt( prop.getProperty( "connectionPoolMaxSize", "15" ) );
       conPoolCfg.maxIdle = Integer.parseInt( prop.getProperty( "connectionPoolMaxIdle", "8" ) );
       conPoolCfg.maxWait = Integer.parseInt( prop.getProperty( "connectionPoolMaxWait", "60000" ) );
       conPoolCfg.minIdle = Integer.parseInt( prop.getProperty( "connectionPoolMinSize", "2" ) );


       ObjectPool connectionPool = new GenericObjectPool( null, conPoolCfg );
       try {
		Class.forName( prop.getProperty( "jdbcDriver" ) );
	} catch( ClassNotFoundException e ) {
		e.printStackTrace();
		throw new RuntimeException();
	}

       ConnectionFactory connectionFactory = new
           DriverManagerConnectionFactory( prop.getProperty( "jdbcUrl" ),
                                          prop.getProperty( "jdbcUser" ), 
                                          prop.getProperty( "jdbcPassword" ) );


       new PoolableConnectionFactory(connectionFactory, connectionPool, null, null, false, true);

       PoolingDataSource dataSource = new PoolingDataSource(connectionPool);
       
       ds = dataSource;
}
 
Example 7
Source Project: tribaltrouble   Source File: DBUtils.java    License: GNU General Public License v2.0 5 votes vote down vote up
public final static void initConnection(String address, String user, String password) throws ClassNotFoundException {
	Class.forName("com.mysql.jdbc.Driver");
	GenericObjectPool connectionPool = new GenericObjectPool(null);
	ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(address, user, password);
	KeyedObjectPoolFactory keyed_factory = new StackKeyedObjectPoolFactory();
	new PoolableConnectionFactory(connectionFactory, connectionPool, keyed_factory, null, false, true);
	ds = new PoolingDataSource(connectionPool);
}
 
Example 8
Source Project: oodt   Source File: DatabaseConnectionBuilder.java    License: Apache License 2.0 5 votes vote down vote up
public static DataSource buildDataSource(String user, String pass,
        String driver, String url) {

    DataSource ds;

    try {
        Class.forName(driver);
    } catch (ClassNotFoundException ignore) {
    }

    GenericObjectPool connectionPool = new GenericObjectPool(null);
  ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(
                      url, user, pass);
          PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(
                      connectionFactory, connectionPool, null, null, false, true);

  return new PoolingDataSource(connectionPool);
}
 
Example 9
Source Project: oodt   Source File: DataSourceWorkflowRepositoryFactory.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * <p>
 * Default Constructor
 * </p>.
 */
public DataSourceWorkflowRepositoryFactory() throws WorkflowException {
    String jdbcUrl, user, pass, driver;

    jdbcUrl = System
            .getProperty("org.apache.oodt.cas.workflow.repo.datasource.jdbc.url");
    user = System
            .getProperty("org.apache.oodt.cas.workflow.repo.datasource.jdbc.user");
    pass = System
            .getProperty("org.apache.oodt.cas.workflow.repo.datasource.jdbc.pass");
    driver = System
            .getProperty("org.apache.oodt.cas.workflow.repo.datasource.jdbc.driver");

    try {
        Class.forName(driver);
    } catch (ClassNotFoundException e) {
        throw new WorkflowException("Cannot load driver: " + driver);
    }

    GenericObjectPool connectionPool = new GenericObjectPool(null);
    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(
            jdbcUrl, user, pass);
    PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(
            connectionFactory, connectionPool, null, null, false, true);

    dataSource = new PoolingDataSource(connectionPool);
}
 
Example 10
/**
 * <p>
 * Default constructor
 * </p>
 */
public DataSourceWorkflowInstanceRepositoryFactory() throws WorkflowException {
    String jdbcUrl, user, pass, driver;

    jdbcUrl = PathUtils
            .replaceEnvVariables(System
                    .getProperty("org.apache.oodt.cas.workflow.instanceRep.datasource.jdbc.url"));
    user = PathUtils
            .replaceEnvVariables(System
                    .getProperty("org.apache.oodt.cas.workflow.instanceRep.datasource.jdbc.user"));
    pass = PathUtils
            .replaceEnvVariables(System
                    .getProperty("org.apache.oodt.cas.workflow.instanceRep.datasource.jdbc.pass"));
    driver = PathUtils
            .replaceEnvVariables(System
                    .getProperty("org.apache.oodt.cas.workflow.instanceRep.datasource.jdbc.driver"));

    try {
        Class.forName(driver);
    } catch (ClassNotFoundException e) {
        throw new WorkflowException("Cannot load driver: " + driver);
    }

    GenericObjectPool connectionPool = new GenericObjectPool(null);

    dataSource = new PoolingDataSource(connectionPool);
    quoteFields = Boolean
            .getBoolean("org.apache.oodt.cas.workflow.instanceRep.datasource.quoteFields");
    pageSize = Integer.getInteger(
        "org.apache.oodt.cas.workflow.instanceRep.pageSize", VAL);

}
 
Example 11
Source Project: neoscada   Source File: PoolConnectionAccessor.java    License: Eclipse Public License 1.0 4 votes vote down vote up
public PoolConnectionAccessor ( final DataSourceFactory dataSourceFactory, final Properties paramProperties ) throws SQLException
{
    logger.debug ( "Creating pool connection accessor : {}", paramProperties );

    // first remove all our properties

    this.connectionPool = new GenericObjectPool<Object> ( null );
    this.connectionPool.setMaxActive ( getInteger ( paramProperties, PREFIX + "maxActive", 8 ) );
    this.connectionPool.setMaxIdle ( getInteger ( paramProperties, PREFIX + "maxIdle", 8 ) );
    this.connectionPool.setMinIdle ( getInteger ( paramProperties, PREFIX + "minIdle", 1 ) );
    this.connectionPool.setTestOnBorrow ( getBoolean ( paramProperties, PREFIX + "testOnBorrow", true ) );
    this.connectionPool.setTestOnReturn ( getBoolean ( paramProperties, PREFIX + "testOnReturn", true ) );

    this.connectionPool.setTimeBetweenEvictionRunsMillis ( getLong ( paramProperties, PREFIX + "timeBetweenEvictionRunsMillis", -1 ) );
    this.connectionPool.setMinEvictableIdleTimeMillis ( getLong ( paramProperties, PREFIX + "minEvictableIdleTimeMillis", 30 * 60 * 1000 ) );
    this.connectionPool.setTestWhileIdle ( getBoolean ( paramProperties, PREFIX + "testWhileIdle", false ) );
    this.connectionPool.setSoftMinEvictableIdleTimeMillis ( getLong ( paramProperties, PREFIX + "softMinEvictableIdleTimeMillis", -1 ) );
    this.connectionPool.setNumTestsPerEvictionRun ( getInteger ( paramProperties, PREFIX + "numTestsPerEvictionRun", 3 ) );

    final String connectionInitSql = getString ( paramProperties, PREFIX + "connectionInitSql", null );
    final String validationQuery = getString ( paramProperties, PREFIX + "validationQuery", null );
    final Integer validationQueryTimeout = getInteger ( paramProperties, PREFIX + "validationQueryTimeout", -1 );

    this.driverDataSource = dataSourceFactory.createDataSource ( paramProperties );

    final ConnectionFactory connectionFactory = new DataSourceConnectionFactory ( this.driverDataSource );
    this.poolableConnectionFactory = new PoolableConnectionFactory ( connectionFactory, this.connectionPool, null, null, false, true );

    if ( connectionInitSql != null )
    {
        this.poolableConnectionFactory.setConnectionInitSql ( Arrays.asList ( connectionInitSql ) );
    }
    if ( validationQuery != null )
    {
        this.poolableConnectionFactory.setValidationQuery ( validationQuery );
    }
    if ( validationQueryTimeout != null )
    {
        this.poolableConnectionFactory.setValidationQueryTimeout ( validationQueryTimeout );
    }

    this.dataSource = new PoolingDataSource ( this.connectionPool );
}
 
Example 12
Source Project: wisp   Source File: DbWrapper.java    License: Apache License 2.0 4 votes vote down vote up
private DataSource setupDataSource(String driver, String connectURI,
                                   String userName, String passwd) throws ClassNotFoundException {

    // driver
    Class.forName(driver);

    //
    // First, we'll need a ObjectPool that serves as the
    // actual pool of connections.
    //
    // We'll use a GenericObjectPool instance, although
    // any ObjectPool implementation will suffice.
    //
    GenericObjectPool connectionPool = new GenericObjectPool(null);
    // 设置在getConnection时验证Connection是否有效
    connectionPool.setTestOnBorrow(true);

    //
    // Next, we'll create a ConnectionFactory that the
    // pool will use to create Connections.
    // We'll use the DriverManagerConnectionFactory,
    // using the connect string passed in the command line
    // arguments.
    //
    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(
            connectURI, userName, passwd);

    // null can be used as parameter because this parameter is set in
    // PoolableConnectionFactory when creating a new PoolableConnection
    KeyedObjectPoolFactory statementPool = new GenericKeyedObjectPoolFactory(
            null);

    //
    // Now we'll create the PoolableConnectionFactory, which wraps
    // the "real" Connections created by the ConnectionFactory with
    // the classes that implement the pooling functionality.
    //
    new PoolableConnectionFactory(connectionFactory, connectionPool,
            statementPool, "select now()", false, true);

    //
    // Finally, we create the PoolingDriver itself,
    // passing in the object pool we created.
    //
    PoolingDataSource dataSource = new PoolingDataSource(connectionPool);

    return dataSource;
}
 
Example 13
Source Project: snowflake-jdbc   Source File: ConnectionPoolingIT.java    License: Apache License 2.0 4 votes vote down vote up
queryUsingPool(PoolingDataSource pds)
{
  this.pds = pds;
}
 
Example 14
Source Project: XPagesExtensionLibrary   Source File: DbcpPoolDataSource.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * 
 */
public DbcpPoolDataSource(final String dataSourceName, 
        final String driverClass, 
        final String url, 
        final String username, 
        final String password,
        final int minIdle,
        final int maxIdle,
        final int maxActive,
        final long maxWait) throws PoolException{
    try {
        ds = AccessController.doPrivileged( new PrivilegedExceptionAction<DataSource>() {
            public DataSource run() throws Exception {
                // create a driver connection factory
                driver = JDBCDriverLoader.loadDriver(driverClass);

                Properties properties = new Properties();
                properties.setProperty("user", username); // $NON-NLS-1$
                properties.setProperty("password", (StringUtil.isEmpty(password) ? "":password)); // $NON-NLS-1$

                ConnectionFactory connectionFactory = new DriverConnectionFactory(driver, url, properties);

                // create the pool
                pool = new GenericObjectPool();
                pool.setMaxActive(maxActive);
                pool.setMaxWait(maxWait);
                pool.setMaxIdle(maxIdle);
                pool.setMinIdle(minIdle);

                // create the pool object factory
                PoolableConnectionFactory factory = new PoolableConnectionFactory(connectionFactory, pool, null, null, false, true);
                pool.setFactory(factory);

                // finally create the datasource
                PoolingDataSource bds = new PoolingDataSource(pool);

                return bds;
            }
        });

    } catch (Exception e) {
        String msg = "Unable to initialize the shared connection pool DataSource"; // $NLX-DbcpPoolDataSource.Unabletoinitializethesharedconnec-1$[["connection pool" is a technical term related to databases]]
        // Note, this resource key is used elsewhere in this plugin
        // "Unable to initialize the shared connection pool DataSource"
        //String msg = com.ibm.xsp.extlib.relational.ResourceHandler.getSpecialAudienceString("DbcpPoolDataSource.Unabletoinitializethesharedconnec");//$NON-NLS-1$
        throw new PoolException( e, msg);
    }
}
 
Example 15
/**
 * Creates a mocked SQL connection, that looks like a apache commons dbcp pooled connection.
 * @param username the username to use
 * @param password the password to use
 * @return the connection
 * @throws SQLException
 */
public static Connection create(String username, String password) throws SQLException {
    ObjectPool pool = new MockedObjectPool(username, password);
    PoolingDataSource ds = new PoolingDataSource(pool);
    return ds.getConnection();
}
 
Example 16
/**
 * Gives access to a {@link java.sql.DataSource} for the given database.
 * @param dbcfg a registered {@link amforeas.config.DatabaseConfiguration}
 * @return a {@link java.sql.DataSource}
 */
public DataSource getDataSource (final DatabaseConfiguration dbcfg) {
    PoolingDataSource dataSource = new PoolingDataSource(this.connectionPool.get(dbcfg.getDatabase()));
    return dataSource;
}