org.apache.commons.dbcp2.PoolableConnection Java Examples

The following examples show how to use org.apache.commons.dbcp2.PoolableConnection. 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
Source File: ScipioErrorDbConnectionFactory.java    From scipio-erp with Apache License 2.0 7 votes vote down vote up
private ScipioErrorDbConnectionFactory() {
    Properties properties = new Properties();
    properties.setProperty("user", DB_USERNAME);
    properties.setProperty("password", DB_PASSWORD);
    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(DB_URL, properties);
    PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, null);
    GenericObjectPool<PoolableConnection> connectionPool = new GenericObjectPool<>(poolableConnectionFactory);
    poolableConnectionFactory.setPool(connectionPool); // TODO: REVIEW: circular?
    poolableConnectionFactory.setValidationQuery("SELECT 1");
    poolableConnectionFactory.setValidationQueryTimeout(3);
    poolableConnectionFactory.setDefaultReadOnly(false);
    poolableConnectionFactory.setDefaultAutoCommit(false);
    poolableConnectionFactory.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
    // Original (log4j manual, dbcp lib):
    //PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(
    //        connectionFactory, connectionPool, null, "SELECT 1", 3, false, false, Connection.TRANSACTION_READ_COMMITTED
    //);
    this.dataSource = new PoolingDataSource<>(connectionPool);
}
 
Example #2
Source File: LinstorConfigTool.java    From linstor-server with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Object call() throws Exception
{
    try (PoolingDataSource<PoolableConnection> dataSource =
             initConnectionProviderFromCfg(linstorTomlFile);
         Connection con = dataSource.getConnection())
    {
        con.setSchema(DATABASE_SCHEMA_NAME);
        final String stmt = "UPDATE PROPS_CONTAINERS SET PROP_VALUE='%d' " +
            "WHERE PROPS_INSTANCE='/CTRLCFG' AND PROP_KEY='netcom/PlainConnector/port'";
        SQLUtils.executeStatement(con, String.format(stmt, controllerPort));
        con.commit();
        System.out.println("Controller plain port set to " + controllerPort);
    }
    return null;
}
 
Example #3
Source File: TransactionLegacy.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a data source
 */
private static DataSource createDataSource(String uri, String username, String password,
                                           Integer maxActive, Integer maxIdle, Long maxWait,
                                           Long timeBtwnEvictionRuns, Long minEvictableIdleTime,
                                           Boolean testWhileIdle, Boolean testOnBorrow,
                                           String validationQuery, Integer isolationLevel) {
    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(uri, username, password);
    PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, null);
    GenericObjectPoolConfig config = createPoolConfig(maxActive, maxIdle, maxWait, timeBtwnEvictionRuns, minEvictableIdleTime, testWhileIdle, testOnBorrow);
    ObjectPool<PoolableConnection> connectionPool = new GenericObjectPool<>(poolableConnectionFactory, config);
    poolableConnectionFactory.setPool(connectionPool);
    if (validationQuery != null) {
        poolableConnectionFactory.setValidationQuery(validationQuery);
    }
    if (isolationLevel != null) {
        poolableConnectionFactory.setDefaultTransactionIsolation(isolationLevel);
    }
    return new PoolingDataSource<>(connectionPool);
}
 
Example #4
Source File: EmbeddedConnectionProvider.java    From Openfire with Apache License 2.0 6 votes vote down vote up
@Override
public void start() {
    File databaseDir = new File(JiveGlobals.getHomeDirectory(), File.separator + "embedded-db");
    // If the database doesn't exist, create it.
    if (!databaseDir.exists()) {
        databaseDir.mkdirs();
    }

    try {
        serverURL = "jdbc:hsqldb:" + databaseDir.getCanonicalPath() + File.separator + "openfire";
    }
    catch (IOException ioe) {
        Log.error("EmbeddedConnectionProvider: Error starting connection pool: ", ioe);
    }
    final ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(serverURL, "sa", "");
    final PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, null);
    poolableConnectionFactory.setMaxConnLifetimeMillis((long) (0.5 * JiveConstants.DAY));

    final GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
    poolConfig.setMinIdle(3);
    poolConfig.setMaxTotal(25);
    final GenericObjectPool<PoolableConnection> connectionPool = new GenericObjectPool<>(poolableConnectionFactory, poolConfig);
    poolableConnectionFactory.setPool(connectionPool);
    dataSource = new PoolingDataSource<>(connectionPool);
}
 
Example #5
Source File: DbcpConnectionPoolHealthCheckTest.java    From moneta with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
	org.hsqldb.jdbc.JDBCDriver.class.newInstance();
	Properties connectionProps=new Properties();
	connectionProps.put("user", "SA");
	connectionProps.put("password", "");
	connectionProps.put("create", "true");
	
	ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(
			"jdbc:hsqldb:mem:my-sample",connectionProps);
	
	ObjectName poolName= poolName=new ObjectName("org.moneta", "connectionPool", "TestPool");
	poolableConnectionFactory=
			new PoolableConnectionFactory(connectionFactory,poolName);
	poolableConnectionFactory.setDefaultCatalog("PUBLIC");
	poolableConnectionFactory.setValidationQuery(VALIDATION_SQL);
	
	connectionPool = 
			new GenericObjectPool<PoolableConnection>(poolableConnectionFactory);
	poolableConnectionFactory.setPool(connectionPool);
	connectionPool.setMaxTotal(2);
	connectionPool.setMaxWaitMillis(400);
	
	healthCheck = new DbcpConnectionPoolHealthCheck(connectionPool, "mine");
}
 
Example #6
Source File: DbcpConnectionPoolHealthCheck.java    From moneta with Apache License 2.0 6 votes vote down vote up
@Override
protected Result check() throws Exception {

	GenericObjectPool<PoolableConnection> pool = (GenericObjectPool<PoolableConnection>) connectionPool;
	if (pool.getNumWaiters() > maxWaitingConnections) {
		return Result.unhealthy("Overloaded connection pool.  name="
				+ poolName + " nbrWaiters=" + pool.getNumWaiters());
	}

	PoolableConnectionFactory poolFactory = (PoolableConnectionFactory) pool
			.getFactory();
	PoolableConnection conn = null;
	try {
		conn = pool.borrowObject();
		poolFactory.validateConnection(conn);
	} catch (Exception e) {
		return Result
				.unhealthy("Database connection validation error.  error="
						+ ExceptionUtils.getStackTrace(e));
	} finally {
		DbUtils.closeQuietly(conn);
	}

	return Result.healthy();
}
 
Example #7
Source File: LinstorConfigTool.java    From linstor-server with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Object call() throws Exception
{
    try (PoolingDataSource<PoolableConnection> dataSource =
             initConnectionProviderFromCfg(linstorTomlFile);
         Connection con = dataSource.getConnection())
    {
        con.setSchema(DATABASE_SCHEMA_NAME);
        final String stmt = "UPDATE PROPS_CONTAINERS SET PROP_VALUE='%s' " +
            "WHERE PROPS_INSTANCE='/CTRLCFG' AND PROP_KEY='netcom/PlainConnector/bindaddress'";
        SQLUtils.executeStatement(con, String.format(stmt, listenAddress));
        con.commit();

        System.out.println("Controller plain listen address set to " + listenAddress);
    }

    return null;
}
 
Example #8
Source File: LinstorConfigTool.java    From linstor-server with GNU General Public License v3.0 6 votes vote down vote up
private static PoolingDataSource<PoolableConnection> initConnectionProviderFromCfg(final File tomlFile)
{
    PoolingDataSource<PoolableConnection> dataSource = null;
    try
    {
        CtrlTomlConfig linstorToml = new Toml().read(tomlFile).to(CtrlTomlConfig.class);

        dataSource = initConnectionProvider(
            linstorToml.getDB().getConnectionUrl(),
            linstorToml.getDB().getUser(),
            linstorToml.getDB().getPassword()
        );
    }
    catch (IllegalStateException exc)
    {
        System.err.println(
            String.format("Unable to parse configuration file: '%s': %s", tomlFile, exc.getMessage())
        );
        System.exit(EXIT_CODE_CONFIG_PARSE_ERROR);
    }
    return dataSource;
}
 
Example #9
Source File: LinstorConfigTool.java    From linstor-server with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Object call() throws Exception
{
    Reader input = sqlFile != null ? new FileReader(sqlFile) : new InputStreamReader(System.in);

    try (PoolingDataSource<PoolableConnection> dataSource =
             initConnectionProviderFromCfg(linstorTomlFile);
         Connection con = dataSource.getConnection())
    {
        con.setAutoCommit(false);
        try
        {
            SQLUtils.runSql(con, new BufferedReader(input));
            con.commit();
        }
        catch (IOException ioExc)
        {
            System.err.println(String.format("Error reading sql script '%s'", sqlFile.toString()));
            System.exit(EXIT_CODE_CMDLINE_ERROR);
        }
        catch (SQLException sqlExc)
        {
            System.err.println(sqlExc.getMessage());
            System.exit(EXIT_CODE_CMDLINE_ERROR);
        }
    }

    return null;
}
 
Example #10
Source File: BasicManagedDataSource.java    From commons-dbcp with Apache License 2.0 5 votes vote down vote up
@Override
protected DataSource createDataSourceInstance() throws SQLException {
    final PoolingDataSource<PoolableConnection> pds = new ManagedDataSource<>(getConnectionPool(),
            transactionRegistry);
    pds.setAccessToUnderlyingConnectionAllowed(isAccessToUnderlyingConnectionAllowed());
    return pds;
}
 
Example #11
Source File: PoolableManagedConnectionFactory.java    From commons-dbcp with Apache License 2.0 5 votes vote down vote up
/**
 * Uses the configured XAConnectionFactory to create a {@link PoolableManagedConnection}. Throws
 * <code>IllegalStateException</code> if the connection factory returns null. Also initializes the connection using
 * configured initialization SQL (if provided) and sets up a prepared statement pool associated with the
 * PoolableManagedConnection if statement pooling is enabled.
 */
@Override
public synchronized PooledObject<PoolableConnection> makeObject() throws Exception {
    Connection conn = getConnectionFactory().createConnection();
    if (conn == null) {
        throw new IllegalStateException("Connection factory returned null from createConnection");
    }
    initializeConnection(conn);
    if (getPoolStatements()) {
        conn = new PoolingConnection(conn);
        final GenericKeyedObjectPoolConfig<DelegatingPreparedStatement> config = new GenericKeyedObjectPoolConfig<>();
        config.setMaxTotalPerKey(-1);
        config.setBlockWhenExhausted(false);
        config.setMaxWaitMillis(0);
        config.setMaxIdlePerKey(1);
        config.setMaxTotal(getMaxOpenPreparedStatements());
        final ObjectName dataSourceJmxName = getDataSourceJmxName();
        final long connIndex = getConnectionIndex().getAndIncrement();
        if (dataSourceJmxName != null) {
            final StringBuilder base = new StringBuilder(dataSourceJmxName.toString());
            base.append(Constants.JMX_CONNECTION_BASE_EXT);
            base.append(Long.toString(connIndex));
            config.setJmxNameBase(base.toString());
            config.setJmxNamePrefix(Constants.JMX_STATEMENT_POOL_PREFIX);
        } else {
            config.setJmxEnabled(false);
        }
        final KeyedObjectPool<PStmtKey, DelegatingPreparedStatement> stmtPool = new GenericKeyedObjectPool<>(
                (PoolingConnection) conn, config);
        ((PoolingConnection) conn).setStatementPool(stmtPool);
        ((PoolingConnection) conn).setCacheState(getCacheState());
    }
    final PoolableManagedConnection pmc = new PoolableManagedConnection(transactionRegistry, conn, getPool(),
            getDisconnectionSqlCodes(), isFastFailValidation());
    pmc.setCacheState(getCacheState());
    return new DefaultPooledObject<>(pmc);
}
 
Example #12
Source File: DbcpNPEXAConnectionTest.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Test
public void check() throws SQLException {
    final Connection con = ejb.newConn();
    con.close(); // no NPE
    Assert.assertTrue("Connection was not closed", con.isClosed());
    final GenericObjectPool<PoolableConnection> pool =  GenericObjectPool.class.cast(Reflections.get(ds, "connectionPool"));
    assertEquals(0, pool.getNumActive());
}
 
Example #13
Source File: BasicManagedDataSource.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
protected DataSource createDataSourceInstance() throws SQLException {
    final TransactionRegistry transactionRegistry = getTransactionRegistry();
    if (transactionRegistry == null) {
        throw new IllegalStateException("TransactionRegistry has not been set");
    }
    if (getConnectionPool() == null) {
        throw new IllegalStateException("Pool has not been set");
    }
    final PoolingDataSource<PoolableConnection> pds = new ManagedDataSource<PoolableConnection>(getConnectionPool(), transactionRegistry) {
        @Override
        public Connection getConnection() throws SQLException {
            return new ManagedConnection<PoolableConnection>(getPool(), transactionRegistry, isAccessToUnderlyingConnectionAllowed()) {
                @Override
                public void close() throws SQLException {
                    if (!isClosedInternal()) {
                        try {
                            if (null != getDelegateInternal()) {
                                super.close();
                            }
                        } finally {
                            setClosedInternal(true);
                        }
                    }
                }

                @Override
                public boolean isClosed() throws SQLException {
                    return isClosedInternal() || null != getDelegateInternal() && getDelegateInternal().isClosed();
                }
            };
        }
    };
    pds.setAccessToUnderlyingConnectionAllowed(isAccessToUnderlyingConnectionAllowed());
    return pds;
}
 
Example #14
Source File: DbConnectionPool.java    From linstor-server with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void start() throws SystemServiceStartException
{
    if (!atomicStarted.getAndSet(true))
    {
        Properties props = new Properties();
        if (linstorConfig.getDbUser() != null)
        {
            props.setProperty("user", linstorConfig.getDbUser());
        }
        if (linstorConfig.getDbPassword() != null)
        {
            props.setProperty("password", linstorConfig.getDbPassword());
        }
        ConnectionFactory connFactory = new DriverManagerConnectionFactory(dbConnectionUrl, props);
        PoolableConnectionFactory poolConnFactory = new PoolableConnectionFactory(connFactory, null);

        GenericObjectPoolConfig<PoolableConnection> poolConfig = new GenericObjectPoolConfig<>();
        poolConfig.setMinIdle(DEFAULT_MIN_IDLE_CONNECTIONS);
        poolConfig.setMaxIdle(DEFAULT_MAX_IDLE_CONNECTIONS);
        poolConfig.setBlockWhenExhausted(true);
        poolConfig.setFairness(true);
        GenericObjectPool<PoolableConnection> connPool = new GenericObjectPool<>(poolConnFactory, poolConfig);

        poolConnFactory.setPool(connPool);
        poolConnFactory.setValidationQueryTimeout(dbTimeout);
        poolConnFactory.setMaxOpenPreparedStatements(dbMaxOpen);
        poolConnFactory.setMaxConnLifetimeMillis(DEFAULT_IDLE_TIMEOUT);
        poolConnFactory.setDefaultTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);

        dataSource = new PoolingDataSource<>(connPool);
    }
}
 
Example #15
Source File: ConnectionPoolFactoryTest.java    From moneta with Apache License 2.0 5 votes vote down vote up
@Test
public void testBasicHappyPath() throws Exception {
	ObjectPool<PoolableConnection> pool = ConnectionPoolFactory.createConnectionPool(dataSource);
	Assert.assertTrue(pool != null);
	
	Connection conn = pool.borrowObject();
	Assert.assertTrue(conn != null);
	Assert.assertTrue(!conn.isClosed() );
}
 
Example #16
Source File: LinstorConfigTool.java    From linstor-server with GNU General Public License v3.0 5 votes vote down vote up
private static PoolingDataSource<PoolableConnection> initConnectionProvider(
    final String connUrl,
    final String user,
    final String password)
{
    Properties dbProps = new Properties();
    if (user != null)
    {
        dbProps.setProperty("user", user);
    }
    if (password != null)
    {
        dbProps.setProperty("password", password);
    }
    ConnectionFactory connFactory = new DriverManagerConnectionFactory(
        connUrl,
        dbProps
    );
    PoolableConnectionFactory poolConnFactory = new PoolableConnectionFactory(connFactory, null);

    GenericObjectPoolConfig<PoolableConnection> poolConfig = new GenericObjectPoolConfig<PoolableConnection>();
    poolConfig.setBlockWhenExhausted(true);
    poolConfig.setFairness(true);

    GenericObjectPool<PoolableConnection> connPool = new GenericObjectPool<>(poolConnFactory, poolConfig);

    poolConnFactory.setPool(connPool);

    return new PoolingDataSource<>(connPool);
}
 
Example #17
Source File: DbcpConnectionPoolHealthCheck.java    From moneta with Apache License 2.0 5 votes vote down vote up
public DbcpConnectionPoolHealthCheck(
		GenericObjectPool<PoolableConnection> pool, String poolName) {
	Validate.notNull(pool, "Null connection pool not allowed.");
	Validate.notEmpty(poolName, "Null or blank poolName not allowed.");
	Validate.isTrue(pool.getFactory() instanceof PoolableConnectionFactory,
			"this check only handles connection pools using PoolableConnectionFactory");
	connectionPool = pool;
	this.poolName = poolName;
	this.setMaxWaitingConnections(3);
}
 
Example #18
Source File: AthenzDataSourceTest.java    From athenz with Apache License 2.0 5 votes vote down vote up
@Test
public void testClearPoolConnectionsException() throws Exception {

    ObjectPool<PoolableConnection> pool = Mockito.mock(ObjectPool.class);
    Mockito.doThrow(new SQLException()).when(pool).clear();
    AthenzDataSource dataSource = new AthenzDataSource(pool);
    dataSource.clearPoolConnections();
}
 
Example #19
Source File: AthenzDataSource.java    From athenz with Apache License 2.0 5 votes vote down vote up
@Override
synchronized public void clearPoolConnections() {
    ObjectPool<PoolableConnection> pool = getPool();
    try {
        LOG.info("Clearing all active/idle ({}/{}) connections from the pool",
                pool.getNumActive(), pool.getNumIdle());
        pool.clear();
    } catch (Exception ex) {
        LOG.error("Unable to clear connections from the pool", ex);
    }
}
 
Example #20
Source File: AthenzDataSource.java    From athenz with Apache License 2.0 5 votes vote down vote up
public AthenzDataSource(ObjectPool<PoolableConnection> pool) {

        super(pool);

        int timeoutThreads = Integer.parseInt(System.getProperty(ATHENZ_PROP_DATASTORE_TIMEOUT_THREADS, "8"));
        if (timeoutThreads <= 0) {
            timeoutThreads = 1;
        }
        networkTimeout = Integer.parseInt(System.getProperty(ATHENZ_PROP_DATASTORE_NETWORK_TIMEOUT, "0"));

        // create our executors pool

        timeoutThreadPool = Executors.newScheduledThreadPool(timeoutThreads);
    }
 
Example #21
Source File: DataSourceFactory.java    From athenz with Apache License 2.0 5 votes vote down vote up
static PoolableDataSource create(ConnectionFactory connectionFactory) {

        // setup our pool config object
        
        GenericObjectPoolConfig config = setupPoolConfig();
        
        PoolableConnectionFactory poolableConnectionFactory =
            new PoolableConnectionFactory(connectionFactory, null);
         
        // Set max lifetime of a connection in milli-secs, after which it will
        // always fail activation, passivation, and validation.
        // Value of -1 means infinite life time. The default value
        // defined in this class is 10 minutes.
        long connTtlMillis = retrieveConfigSetting(ATHENZ_PROP_DBPOOL_MAX_TTL, MAX_TTL_CONN_MS);
        poolableConnectionFactory.setMaxConnLifetimeMillis(connTtlMillis);
        if (LOG.isInfoEnabled()) {
            LOG.info("Setting Time-To-Live interval for live connections ({}) msecs", connTtlMillis);
        }

        // set the validation query for our jdbc connector
        final String validationQuery = System.getProperty(ATHENZ_PROP_DBPOOL_VALIDATION_QUERY, MYSQL_VALIDATION_QUERY);
        poolableConnectionFactory.setValidationQuery(validationQuery);

        ObjectPool<PoolableConnection> connectionPool =
                new GenericObjectPool<>(poolableConnectionFactory, config);
        poolableConnectionFactory.setPool(connectionPool);

        return new AthenzDataSource(connectionPool);
    }
 
Example #22
Source File: PoolingDataSourceExample.java    From commons-dbcp with Apache License 2.0 4 votes vote down vote up
public static DataSource setupDataSource(String connectURI) {
    //
    // First, 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,null);

    //
    // Next we'll create the PoolableConnectionFactory, which wraps
    // the "real" Connections created by the ConnectionFactory with
    // the classes that implement the pooling functionality.
    //
    PoolableConnectionFactory poolableConnectionFactory =
        new PoolableConnectionFactory(connectionFactory, null);

    //
    // Now 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.
    //
    ObjectPool<PoolableConnection> connectionPool =
            new GenericObjectPool<>(poolableConnectionFactory);
    
    // Set the factory's pool property to the owning pool
    poolableConnectionFactory.setPool(connectionPool);

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

    return dataSource;
}
 
Example #23
Source File: DbcpFactory.java    From seldon-server with Apache License 2.0 4 votes vote down vote up
private void createDbcp(DbcpConfig conf)
{
	if (!dataSources.containsKey(conf.name))
	{
		try
	    {
			
			Class.forName(conf.driverClassName);
		    
		    DriverManagerConnectionFactory cf =  new DriverManagerConnectionFactory(conf.jdbc,conf.user,conf.password);
		    
		    PoolableConnectionFactory pcf  =  new PoolableConnectionFactory(cf,null);
		    pcf.setValidationQuery(conf.validationQuery);
		    //, pool, null, conf.validationQuery, false, true,abandondedConfig);
			
		    logger.info("Creating pool "+conf.toString());
		    // create a generic pool
		    GenericObjectPool<PoolableConnection> pool = new GenericObjectPool<PoolableConnection>(pcf);
		    pool.setMaxTotal(conf.maxTotal);
		    pool.setMaxIdle(conf.maxIdle);
		    pool.setMinIdle(conf.minIdle);
		    pool.setMaxWaitMillis(conf.maxWait);
		    pool.setTimeBetweenEvictionRunsMillis(conf.timeBetweenEvictionRunsMillis);
		    pool.setMinEvictableIdleTimeMillis(conf.minEvictableIdleTimeMillis);
		    pool.setTestWhileIdle(conf.testWhileIdle);
		    pool.setTestOnBorrow(conf.testOnBorrow);
	    
		    AbandonedConfig abandonedConfig = new AbandonedConfig();
		    abandonedConfig.setRemoveAbandonedOnMaintenance(conf.removeAbanadoned);
		    abandonedConfig.setRemoveAbandonedTimeout(conf.removeAbandonedTimeout);
		    abandonedConfig.setLogAbandoned(conf.logAbandonded);
	    
		    pool.setAbandonedConfig(abandonedConfig);
	    
		    pcf.setPool(pool);
		    DataSource ds = new PoolingDataSource(pool);
		    dataSources.put(conf.name, ds);

	    } catch (ClassNotFoundException e) {
			logger.error("Failed to create datasource for "+conf.name+ " with class "+conf.driverClassName);
		}
	   
	}
	else
	{
		logger.error("Pool "+conf.name+" already exists. Can't change existing datasource at present.");
	}
}
 
Example #24
Source File: PoolingDriverExample.java    From commons-dbcp with Apache License 2.0 4 votes vote down vote up
public static void setupDriver(String connectURI) throws Exception {
    //
    // First, 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,null);

    //
    // Next, we'll create the PoolableConnectionFactory, which wraps
    // the "real" Connections created by the ConnectionFactory with
    // the classes that implement the pooling functionality.
    //
    PoolableConnectionFactory poolableConnectionFactory =
        new PoolableConnectionFactory(connectionFactory, null);

    //
    // Now 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.
    //
    ObjectPool<PoolableConnection> connectionPool =
        new GenericObjectPool<>(poolableConnectionFactory);
    
    // Set the factory's pool property to the owning pool
    poolableConnectionFactory.setPool(connectionPool);

    //
    // Finally, we create the PoolingDriver itself...
    //
    Class.forName("org.apache.commons.dbcp2.PoolingDriver");
    PoolingDriver driver = (PoolingDriver) DriverManager.getDriver("jdbc:apache:commons:dbcp:");

    //
    // ...and register our pool with it.
    //
    driver.registerPool("example",connectionPool);

    //
    // Now we can just use the connect string "jdbc:apache:commons:dbcp:example"
    // to access our pool of Connections.
    //
}
 
Example #25
Source File: PoolableManagedConnection.java    From commons-dbcp with Apache License 2.0 3 votes vote down vote up
/**
 * Create a PoolableManagedConnection.
 *
 * @param transactionRegistry
 *            transaction registry
 * @param conn
 *            underlying connection
 * @param pool
 *            connection pool
 * @param disconnectSqlCodes
 *            SQL_STATE codes considered fatal disconnection errors
 * @param fastFailValidation
 *            true means fatal disconnection errors cause subsequent validations to fail immediately (no attempt to
 *            run query or isValid)
 */
public PoolableManagedConnection(final TransactionRegistry transactionRegistry, final Connection conn,
        final ObjectPool<PoolableConnection> pool, final Collection<String> disconnectSqlCodes,
        final boolean fastFailValidation) {
    super(conn, pool, null, disconnectSqlCodes, fastFailValidation);
    this.transactionRegistry = transactionRegistry;
}
 
Example #26
Source File: ConnectionUtils.java    From FROST-Server with GNU Lesser General Public License v3.0 3 votes vote down vote up
/**
 * Set up a connection pool. The driver used in the connection URI should
 * already be loaded using
 * Class.forName("org.apache.commons.dbcp2.PoolingDriver"); After calling
 * this you can use "jdbc:apache:commons:dbcp:FROST-Pool" to connect.
 *
 * @param name The name of the pool to create.
 * @param connectURI The URL of the database to connect to.
 * @param username The username to use when connecting to the database.
 * @param password The password to use when connecting to the database.
 * @throws ClassNotFoundException If the PoolingDriver is not on the
 * classpath.
 * @throws SQLException If the dbcp driver could not be loaded.
 */
public static void setupPoolingDriver(String name, String connectURI, String username, String password) throws ClassNotFoundException, SQLException {
    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(connectURI, username, password);
    PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, null);
    ObjectPool<PoolableConnection> connectionPool = new GenericObjectPool<>(poolableConnectionFactory);
    poolableConnectionFactory.setPool(connectionPool);
    Class.forName("org.apache.commons.dbcp2.PoolingDriver");
    PoolingDriver driver = (PoolingDriver) DriverManager.getDriver("jdbc:apache:commons:dbcp:");
    driver.registerPool(name, connectionPool);
}
 
Example #27
Source File: PoolableManagedConnection.java    From commons-dbcp with Apache License 2.0 2 votes vote down vote up
/**
 * Create a PoolableManagedConnection.
 *
 * @param transactionRegistry
 *            transaction registry
 * @param conn
 *            underlying connection
 * @param pool
 *            connection pool
 */
public PoolableManagedConnection(final TransactionRegistry transactionRegistry, final Connection conn,
        final ObjectPool<PoolableConnection> pool) {
    this(transactionRegistry, conn, pool, null, true);
}