org.apache.commons.dbcp2.PoolingDataSource Java Examples

The following examples show how to use org.apache.commons.dbcp2.PoolingDataSource. 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: 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 #4
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 #5
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 #6
Source File: JdbcIO.java    From beam with Apache License 2.0 6 votes vote down vote up
@Override
public DataSource apply(Void input) {
  return instances.computeIfAbsent(
      config.config,
      ignored -> {
        DataSource basicSource = config.apply(input);
        DataSourceConnectionFactory connectionFactory =
            new DataSourceConnectionFactory(basicSource);
        PoolableConnectionFactory poolableConnectionFactory =
            new PoolableConnectionFactory(connectionFactory, null);
        GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
        poolConfig.setMaxTotal(1);
        poolConfig.setMinIdle(0);
        poolConfig.setMinEvictableIdleTimeMillis(10000);
        poolConfig.setSoftMinEvictableIdleTimeMillis(30000);
        GenericObjectPool connectionPool =
            new GenericObjectPool(poolableConnectionFactory, poolConfig);
        poolableConnectionFactory.setPool(connectionPool);
        poolableConnectionFactory.setDefaultAutoCommit(false);
        poolableConnectionFactory.setDefaultReadOnly(false);
        return new PoolingDataSource(connectionPool);
      });
}
 
Example #7
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 #8
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 #9
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 #10
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 #11
Source File: TransactionLegacy.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({"unchecked", "rawtypes"})
private static DataSource getDefaultDataSource(final String database) {
    final ConnectionFactory connectionFactory = new DriverManagerConnectionFactory("jdbc:mysql://localhost:3306/" + database, "cloud", "cloud");
    final PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, null);
    final GenericObjectPool connectionPool = new GenericObjectPool(poolableConnectionFactory);
    return new PoolingDataSource(connectionPool);
}
 
Example #12
Source File: CalciteAssert.java    From calcite with Apache License 2.0 5 votes vote down vote up
PoolingConnectionFactory(final ConnectionFactory factory) {
  final PoolableConnectionFactory connectionFactory =
      new PoolableConnectionFactory(factory::createConnection, null);
  connectionFactory.setRollbackOnReturn(false);
  this.dataSource = new PoolingDataSource<>(
      new GenericObjectPool<>(connectionFactory));
}
 
Example #13
Source File: DefaultConnectionProvider.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Override
public void start() {

    try {
        Class.forName(driver);
    } catch (final ClassNotFoundException e) {
        throw new RuntimeException("Unable to find JDBC driver " + driver, e);
    }

    final ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(serverURL, username, password);
    final PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, null);
    poolableConnectionFactory.setValidationQuery(testSQL);
    poolableConnectionFactory.setValidationQueryTimeout(testTimeout);
    poolableConnectionFactory.setMaxConnLifetimeMillis((long) (connectionTimeout * JiveConstants.DAY));

    final GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
    poolConfig.setTestOnBorrow(testBeforeUse);
    poolConfig.setTestOnReturn(testAfterUse);
    poolConfig.setMinIdle(minConnections);
    if( minConnections > GenericObjectPoolConfig.DEFAULT_MAX_IDLE )
    {
        poolConfig.setMaxIdle(minConnections);
    }
    poolConfig.setMaxTotal(maxConnections);
    poolConfig.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRuns);
    poolConfig.setSoftMinEvictableIdleTimeMillis(minIdleTime);
    poolConfig.setMaxWaitMillis(maxWaitTime);
    connectionPool = new GenericObjectPool<>(poolableConnectionFactory, poolConfig);
    poolableConnectionFactory.setPool(connectionPool);
    dataSource = new PoolingDataSource<>(connectionPool);
}
 
Example #14
Source File: MockedDbcp2PoolingConnection.java    From liquibase-percona with Apache License 2.0 5 votes vote down vote up
/**
 * 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<Connection> pool = new MockedObjectPool(username, password);
    PoolingDataSource<Connection> ds = new PoolingDataSource<Connection>(pool);
    try {
        return ds.getConnection();
    } finally {
        try {
            ds.close();
        } catch (Exception ignored) {
            // ignored
        }
    }
}
 
Example #15
Source File: JdbcIOTest.java    From beam with Apache License 2.0 5 votes vote down vote up
@Test
public void testDataSourceConfigurationDataSourceWithPool() {
  assertTrue(
      JdbcIO.PoolableDataSourceProvider.of(JdbcIO.DataSourceConfiguration.create(dataSource))
              .apply(null)
          instanceof PoolingDataSource);
}
 
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: 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 #18
Source File: CalciteAssert.java    From Quicksql with MIT License 5 votes vote down vote up
PoolingConnectionFactory(final ConnectionFactory factory) {
  final PoolableConnectionFactory connectionFactory =
      new PoolableConnectionFactory(factory::createConnection, null);
  connectionFactory.setRollbackOnReturn(false);
  this.dataSource = new PoolingDataSource<>(
      new GenericObjectPool<>(connectionFactory));
}
 
Example #19
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 #20
Source File: DynamicJdbcIO.java    From DataflowTemplates with Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
DataSource buildDatasource() {
  BasicDataSource basicDataSource = new BasicDataSource();
  if (getDriverClassName() != null) {
    if (getDriverClassName().get() == null) {
      throw new RuntimeException("Driver class name is required.");
    }
    basicDataSource.setDriverClassName(getDriverClassName().get());
  }
  if (getUrl() != null) {
    if (getUrl().get() == null) {
      throw new RuntimeException("Connection url is required.");
    }
    basicDataSource.setUrl(getUrl().get());
  }
  if (getUsername() != null) {
    basicDataSource.setUsername(getUsername().get());
  }
  if (getPassword() != null) {
    basicDataSource.setPassword(getPassword().get());
  }
  if (getConnectionProperties() != null && getConnectionProperties().get() != null) {
    basicDataSource.setConnectionProperties(getConnectionProperties().get());
  }

  /**
   * Since the jdbc connection connection class might have dependencies that are not available
   * to the template, we will localize the user provided dependencies from GCS and create a new
   * {@link URLClassLoader} that is added to the {@link
   * BasicDataSource#setDriverClassLoader(ClassLoader)}
   */
  if (getDriverJars() != null) {
    ClassLoader urlClassLoader = getNewClassLoader(getDriverJars());
    basicDataSource.setDriverClassLoader(urlClassLoader);
  }

  // wrapping the datasource as a pooling datasource
  DataSourceConnectionFactory connectionFactory =
      new DataSourceConnectionFactory(basicDataSource);
  PoolableConnectionFactory poolableConnectionFactory =
      new PoolableConnectionFactory(connectionFactory, null);
  GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
  poolConfig.setMaxTotal(1);
  poolConfig.setMinIdle(0);
  poolConfig.setMinEvictableIdleTimeMillis(10000);
  poolConfig.setSoftMinEvictableIdleTimeMillis(30000);
  GenericObjectPool connectionPool =
      new GenericObjectPool(poolableConnectionFactory, poolConfig);
  poolableConnectionFactory.setPool(connectionPool);
  poolableConnectionFactory.setDefaultAutoCommit(false);
  poolableConnectionFactory.setDefaultReadOnly(false);
  PoolingDataSource poolingDataSource = new PoolingDataSource(connectionPool);
  return poolingDataSource;
}
 
Example #21
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;
}