List of usage examples for org.apache.commons.dbcp2 PoolingDataSource PoolingDataSource
public PoolingDataSource(ObjectPool<C> pool)
From source file:ddc.commons.jdbc.PooledDatasourceFactory.java
public DataSource createDataSource(JdbcConnectionFactory conn) throws ClassNotFoundException { conn.loadDriver();// w ww .j a v a 2s .c om // // 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(conn.getUrl(), conn.getUser(), conn.getPassword()); // // 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<PoolableConnection>( 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. // DataSource ds = new PoolingDataSource<PoolableConnection>(connectionPool); return ds; }
From source file:eu.peppol.persistence.jdbc.OxalisDataSourceFactoryDbcpImplTest.java
/** * Verifies that we can create a pooled jdbc data source using the JDBC .jar-file supplied in the global configuration * file.// w w w.jav a2s. c om * * @throws Exception */ @Test public void testLoadJdbcDriverUsingCustomClassLoader() throws Exception { ConnectionFactory driverConnectionFactory = createConnectionFactory(false); ObjectName poolName = new ObjectName("no.difi.oxalis", "connectionPool", "TestPool"); PoolableConnectionFactory factory = new PoolableConnectionFactory(driverConnectionFactory, poolName); GenericObjectPool<PoolableConnection> pool = new GenericObjectPool<>(factory); factory.setPool(pool); pool.setMaxTotal(10); pool.setMaxWaitMillis(100); assertEquals(pool.getFactory(), factory); PoolableConnectionFactory pcf = (PoolableConnectionFactory) ((GenericObjectPool<?>) pool).getFactory(); ObjectPool<PoolableConnection> pool1 = pcf.getPool(); PoolingDataSource<PoolableConnection> poolingDataSource = new PoolingDataSource<>(pool); Connection connection = poolingDataSource.getConnection(); assertNotNull(connection); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery("select current_date()"); assertTrue(resultSet.next()); }
From source file:com.github.brandtg.switchboard.MysqlReplicator.java
@Override public void start() throws Exception { // DBCP2 pool ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(jdbcString, user, password); ObjectName poolName = new ObjectName(JdbcBasedLogIndex.class.getCanonicalName(), URLEncoder.encode(jdbcString, ENCODING), "replicatorConnectionPool"); PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, poolName);/*from w w w . j av a 2 s .com*/ ObjectPool<PoolableConnection> connectionPool = new GenericObjectPool<PoolableConnection>( poolableConnectionFactory); poolableConnectionFactory.setPool(connectionPool); this.dataSource = new PoolingDataSource<PoolableConnection>(connectionPool); LOG.info("Opened connection pool to {} as {}", jdbcString, user); // Replication applier applier = new MysqlReplicationApplier(inputStream, dataSource); super.start(); }
From source file:io.seldon.dbcp.DbcpFactory.java
private void createDbcp(DbcpConfig conf) { if (!dataSources.containsKey(conf.name)) { try {// w ww . j a v a 2s. co m 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."); } }
From source file:com.threecrickets.prudence.cache.SqlCache.java
/** * Constructor.//from ww w . j a v a2 s. c om * * @param dataSource * The data source * @param maxSize * The max entry count * @param poolSize * The number of connections in the pool * @param lockSource * The lock source */ public SqlCache(DataSource dataSource, int maxSize, int poolSize, LockSource lockSource) { this.maxSize = maxSize; this.lockSource = lockSource; GenericObjectPoolConfig config = new GenericObjectPoolConfig(); config.setMaxTotal(poolSize); config.setMaxIdle(poolSize); config.setMinIdle(poolSize); DataSourceConnectionFactory connectionFactory = new DataSourceConnectionFactory(dataSource); PoolableConnectionFactory pooledObjectFactory = new PoolableConnectionFactory(connectionFactory, null); GenericObjectPool<PoolableConnection> pool = new GenericObjectPool<PoolableConnection>(pooledObjectFactory, config); pooledObjectFactory.setPool(pool); this.dataSource = new PoolingDataSource<PoolableConnection>(pool); }
From source file:info.pancancer.arch3.persistence.PostgreSQL.java
public PostgreSQL(HierarchicalINIConfiguration settings) { if (dataSource == null) { try {/* ww w.j a va 2 s . c o m*/ String nullConfigs = ""; String host = settings.getString(Constants.POSTGRES_HOST); if (host == null) { nullConfigs += "postgresHost "; } String user = settings.getString(Constants.POSTGRES_USERNAME); if (user == null) { nullConfigs += "postgresUser "; } String pass = settings.getString(Constants.POSTGRES_PASSWORD); if (pass == null) { nullConfigs += "postgresPass "; } String db = settings.getString(Constants.POSTGRES_DBNAME); if (db == null) { nullConfigs += "postgresDBName "; } String maxConnections = settings.getString(Constants.POSTGRES_MAX_CONNECTIONS, "5"); if (nullConfigs.trim().length() > 0) { throw new NullPointerException("The following configuration values are null: " + nullConfigs + ". Please check your configuration file."); } Class.forName("org.postgresql.Driver"); String url = "jdbc:postgresql://" + host + "/" + db; LOG.debug("PostgreSQL URL is: " + url); Properties props = new Properties(); props.setProperty("user", user); props.setProperty("password", pass); // props.setProperty("ssl","true"); props.setProperty("initialSize", "5"); props.setProperty("maxActive", maxConnections); ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(url, props); PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory( connectionFactory, null); poolableConnectionFactory.setValidationQuery("select count(*) from job;"); ObjectPool<PoolableConnection> connectionPool = new GenericObjectPool<>(poolableConnectionFactory); poolableConnectionFactory.setPool(connectionPool); dataSource = new PoolingDataSource<>(connectionPool); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } }
From source file:edumsg.core.PostgresConnection.java
public static void initSource() { try {//from w w w . ja v a 2s. co m try { Class.forName("org.postgresql.Driver"); } catch (ClassNotFoundException ex) { LOGGER.log(Level.SEVERE, "Error loading Postgres driver: " + ex.getMessage(), ex); } try { readConfFile(); } catch (Exception e) { e.printStackTrace(); } Properties props = new Properties(); // System.out.println(DB_USERNAME); props.setProperty("user", DB_USERNAME); props.setProperty("password", DB_PASSWORD); props.setProperty("initialSize", DB_INIT_CONNECTIONS); props.setProperty("maxActive", DB_MAX_CONNECTIONS); ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(DB_URL, props); PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, null); poolableConnectionFactory.setPoolStatements(true); GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig(); poolConfig.setMaxIdle(Integer.parseInt(DB_INIT_CONNECTIONS)); poolConfig.setMaxTotal(Integer.parseInt(DB_MAX_CONNECTIONS)); ObjectPool<PoolableConnection> connectionPool = new GenericObjectPool<>(poolableConnectionFactory, poolConfig); poolableConnectionFactory.setPool(connectionPool); Class.forName("org.apache.commons.dbcp2.PoolingDriver"); dbDriver = (PoolingDriver) DriverManager.getDriver("jdbc:apache:commons:dbcp:"); dbDriver.registerPool(DB_NAME, connectionPool); dataSource = new PoolingDataSource<>(connectionPool); } catch (Exception ex) { LOGGER.log(Level.SEVERE, "Got error initializing data source: " + ex.getMessage(), ex); } }
From source file:dgw.mt940.db.util.PoolingDataSourceExample.java
public static DataSource setupDataSource(String connectURI) { ////from ww w .j a va 2 s. c o m // 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<PoolableConnection>( 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; }
From source file:PoolingDataSourceExample.java
public static DataSource setupDataSource(String connectURI) { ///*from w w w .j a v a 2 s.com*/ // 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; }
From source file:eu.peppol.persistence.jdbc.OxalisDataSourceFactoryDbcpImpl.java
/** * Creates a DataSource with connection pooling as provided by Apache DBCP * * @return a DataSource//from w w w . jav a 2 s .c o m */ DataSource configureAndCreateDataSource(RepositoryConfiguration configuration) { log.debug("Configuring DataSource wrapped in a Database Connection Pool, using custom loader"); String jdbcDriverClassPath = configuration.getJdbcDriverClassPath(); log.debug("Loading JDBC Driver with custom class path: " + jdbcDriverClassPath); // Creates a new class loader, which will be used for loading our JDBC driver URLClassLoader urlClassLoader = getOxalisClassLoaderForJdbc(jdbcDriverClassPath); String className = configuration.getJdbcDriverClassName(); String connectURI = configuration.getJdbcConnectionUri().toString(); String userName = configuration.getJdbcUsername(); String password = configuration.getJdbcPassword(); log.debug("className=" + className); log.debug("connectURI=" + connectURI); log.debug("userName=" + userName); log.debug("password=" + password); // Loads the JDBC Driver in a separate class loader Driver driver = getJdbcDriver(jdbcDriverClassPath, urlClassLoader, className); Properties properties = new Properties(); properties.put("user", userName); properties.put("password", password); // DBCP factory which will produce JDBC Driver instances ConnectionFactory driverConnectionFactory = new DriverConnectionFactory(driver, connectURI, properties); // DBCP Factory holding the pooled connection, which are created by the driver connection factory and held in the supplied pool ObjectName dataSourceJmxName = null; try { dataSourceJmxName = new ObjectName("no.difi.oxalis", "connectionPool", "OxalisDB"); } catch (MalformedObjectNameException e) { throw new IllegalStateException(e.getMessage(), e); } PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(driverConnectionFactory, dataSourceJmxName); String validationQuery = configuration.getValidationQuery(); if (validationQuery != null) { poolableConnectionFactory.setValidationQuery(validationQuery); } // DBCP object pool holding our driver connections GenericObjectPool<PoolableConnection> genericObjectPool = new GenericObjectPool<PoolableConnection>( poolableConnectionFactory); poolableConnectionFactory.setPool(genericObjectPool); genericObjectPool.setMaxTotal(100); genericObjectPool.setMaxIdle(30); genericObjectPool.setMaxWaitMillis(10000); genericObjectPool.setTestOnBorrow(true); // Test the connection returned from the pool genericObjectPool.setTestWhileIdle(true); // Test idle instances visited by the pool maintenance thread and destroy any that fail validation genericObjectPool.setTimeBetweenEvictionRunsMillis(60 * 60 * 1000); // Test every hour // Creates the actual DataSource instance PoolingDataSource poolingDataSource = new PoolingDataSource(genericObjectPool); return poolingDataSource; }