List of usage examples for org.apache.commons.pool.impl GenericKeyedObjectPoolFactory GenericKeyedObjectPoolFactory
public GenericKeyedObjectPoolFactory(KeyedPoolableObjectFactory factory, int maxActive)
From source file:ConnectionPoolBasics.java
public static void main(String args[]) throws Exception { GenericObjectPool gPool = new GenericObjectPool(); /*Class.forName("com.mysql.jdbc.Driver"); //ww w . j av a 2s.co m DriverManagerConnectionFactory cf = new DriverManagerConnectionFactory( "jdbc:mysql://localhost/commons", "root", "");*/ Properties props = new Properties(); props.setProperty("Username", "root"); props.setProperty("Password", ""); ConnectionFactory cf = new DriverConnectionFactory(new com.mysql.jdbc.Driver(), "jdbc:mysql://localhost/commons", props); KeyedObjectPoolFactory kopf = new GenericKeyedObjectPoolFactory(null, 8); PoolableConnectionFactory pcf = new PoolableConnectionFactory(cf, gPool, kopf, null, false, true); for (int i = 0; i < 5; i++) { gPool.addObject(); } // PoolingDataSource pds = new PoolingDataSource(gPool); PoolingDriver pd = new PoolingDriver(); pd.registerPool("example", gPool); for (int i = 0; i < 5; i++) { gPool.addObject(); } Connection conn = java.sql.DriverManager.getConnection("jdbc:apache:commons:dbcp:example"); System.err.println("Connection: " + conn); //": Delegate: " + ((org.apache.commons.dbcp.PoolingConnection)conn).getDelegate()); // do some work with the connection PreparedStatement ps = conn.prepareStatement("Select * from customer where id = ?"); System.err.println("Active: " + gPool.getNumActive() + ", Idle: " + gPool.getNumIdle()); conn.close(); System.err.println("Active: " + gPool.getNumActive() + ", Idle: " + gPool.getNumIdle()); }
From source file:eu.openanalytics.rsb.rservi.RmiRServiInstanceProvider.java
private void initializeRServiClientPool(final Config config) { final KeyedPoolableObjectFactory<RServiPoolKey, PooledRServiWrapper> factory = new BaseKeyedPoolableObjectFactory<RServiPoolKey, PooledRServiWrapper>() { @Override//from w w w . j av a 2 s. c om public PooledRServiWrapper makeObject(final RServiPoolKey key) throws Exception { final RServi rServi = RServiUtil.getRServi(key.getAddress(), key.getClientId()); return new PooledRServiWrapper(rServiPool, key, rServi); } @Override public void destroyObject(final RServiPoolKey key, final PooledRServiWrapper rServi) throws Exception { rServi.destroy(); } @Override public boolean validateObject(final RServiPoolKey key, final PooledRServiWrapper rServi) { if (rServi.isClosed()) { return false; } if (rServi.hasError() || configuration .getRServiClientPoolValidationStrategy() == RServiClientPoolValidationStrategy.FULL) { final boolean responding = Util.isRResponding(rServi); if (rServi.hasError() && LOGGER.isInfoEnabled()) { LOGGER.info(String.format("RServi @ %s has been found %svalid after error", key.getAddress(), responding ? "" : "in")); } if (responding) { rServi.resetError(); } return responding; } else { return true; } } }; rServiPool = new GenericKeyedObjectPoolFactory<RServiPoolKey, PooledRServiWrapper>(factory, config) .createPool(); LOGGER.info("RServi pool instantiated and configured with: " + ToStringBuilder.reflectionToString(config)); }
From source file:ojw28.orm.utils.DbConnectionPool.java
private void createPool() throws Exception { mPool = new GenericObjectPool(); Properties props = new Properties(); props.setProperty("user", "orm"); props.setProperty("password", "openroommap"); ConnectionFactory cf = new DriverConnectionFactory(new org.postgresql.Driver(), "jdbc:postgresql://localhost:5432/openroommap", props); KeyedObjectPoolFactory kopf = new GenericKeyedObjectPoolFactory(null, 10); new PoolableConnectionFactory(cf, mPool, kopf, null, false, false); for (int i = 0; i < 5; i++) { mPool.addObject();/* w w w . j a va2s . com*/ } // PoolingDataSource pds = new PoolingDataSource(gPool); PoolingDriver pd = new PoolingDriver(); pd.registerPool("openroommap", mPool); for (int i = 0; i < 5; i++) { mPool.addObject(); } mLogger.info("Created connection pool"); mLogger.info("Active\t" + mPool.getNumActive() + "\tIdle\t" + mPool.getNumIdle()); }
From source file:org.dspace.storage.rdbms.DataSourceInit.java
public static DataSource getDatasource() throws SQLException { if (dataSource != null) { return dataSource; }// www.jav a 2 s . c o m try { // Register basic JDBC driver Class driverClass = Class.forName(ConfigurationManager.getProperty("db.driver")); Driver basicDriver = (Driver) driverClass.newInstance(); DriverManager.registerDriver(basicDriver); // Read pool configuration parameter or use defaults // Note we check to see if property is null; getIntProperty returns // '0' if the property is not set OR if it is actually set to zero. // But 0 is a valid option... int maxConnections = ConfigurationManager.getIntProperty("db.maxconnections"); if (ConfigurationManager.getProperty("db.maxconnections") == null) { maxConnections = 30; } int maxWait = ConfigurationManager.getIntProperty("db.maxwait"); if (ConfigurationManager.getProperty("db.maxwait") == null) { maxWait = 5000; } int maxIdle = ConfigurationManager.getIntProperty("db.maxidle"); if (ConfigurationManager.getProperty("db.maxidle") == null) { maxIdle = -1; } boolean useStatementPool = ConfigurationManager.getBooleanProperty("db.statementpool", true); // Create object pool ObjectPool connectionPool = new GenericObjectPool(null, // PoolableObjectFactory // - set below maxConnections, // max connections GenericObjectPool.WHEN_EXHAUSTED_BLOCK, maxWait, // don't // block // more than 5 // seconds maxIdle, // max idle connections (unlimited) true, // validate when we borrow connections from pool false // don't bother validation returned connections ); // ConnectionFactory the pool will use to create connections. ConnectionFactory connectionFactory = new DriverManagerConnectionFactory( ConfigurationManager.getProperty("db.url"), ConfigurationManager.getProperty("db.username"), ConfigurationManager.getProperty("db.password")); // // Now we'll create the PoolableConnectionFactory, which wraps // the "real" Connections created by the ConnectionFactory with // the classes that implement the pooling functionality. // String validationQuery = "SELECT 1"; // Oracle has a slightly different validation query if ("oracle".equals(ConfigurationManager.getProperty("db.name"))) { validationQuery = "SELECT 1 FROM DUAL"; } GenericKeyedObjectPoolFactory statementFactory = null; if (useStatementPool) { // The statement Pool is used to pool prepared statements. GenericKeyedObjectPool.Config statementFactoryConfig = new GenericKeyedObjectPool.Config(); // Just grow the pool size when needed. // // This means we will never block when attempting to // create a query. The problem is unclosed statements, // they can never be reused. So if we place a maximum // cap on them, then we might reach a condition where // a page can only be viewed X number of times. The // downside of GROW_WHEN_EXHAUSTED is that this may // allow a memory leak to exist. Both options are bad, // but I'd prefer a memory leak over a failure. // // FIXME: Perhaps this decision should be derived from config parameters? statementFactoryConfig.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_GROW; statementFactory = new GenericKeyedObjectPoolFactory(null, statementFactoryConfig); } PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, connectionPool, statementFactory, validationQuery, // validation query false, // read only is not default for now false); // Autocommit defaults to none // // Finally, we create the PoolingDataSource itself... // PoolingDataSource poolingDataSource = new PoolingDataSource(); // // ...and register our pool with it. // poolingDataSource.setPool(connectionPool); dataSource = poolingDataSource; return poolingDataSource; } catch (Exception e) { // Need to be able to catch other exceptions. Pretend they are // SQLExceptions, but do log log.warn("Exception initializing DB pool", e); throw new SQLException(e.toString(), e); } }
From source file:org.dspace.storage.rdbms.MockDatabaseManager.java
/** * Initialize the DatabaseManager.//from w w w . j a v a 2 s .c o m */ @Mock private static synchronized void initialize() throws SQLException { if (initialized) { return; } try { // Register basic JDBC driver Class.forName(ConfigurationManager.getProperty("db.driver")); // Register the DBCP driver Class.forName("org.apache.commons.dbcp.PoolingDriver"); // Read pool configuration parameter or use defaults // Note we check to see if property is null; getIntProperty returns // '0' if the property is not set OR if it is actually set to zero. // But 0 is a valid option... int maxConnections = ConfigurationManager.getIntProperty("db.maxconnections"); if (ConfigurationManager.getProperty("db.maxconnections") == null) { maxConnections = 30; } int maxWait = ConfigurationManager.getIntProperty("db.maxwait"); if (ConfigurationManager.getProperty("db.maxwait") == null) { maxWait = 5000; } int maxIdle = ConfigurationManager.getIntProperty("db.maxidle"); if (ConfigurationManager.getProperty("db.maxidle") == null) { maxIdle = -1; } boolean useStatementPool = ConfigurationManager.getBooleanProperty("db.statementpool", true); // Create object pool connectionPool = new GenericObjectPool(null, // PoolableObjectFactory // - set below maxConnections, // max connections GenericObjectPool.WHEN_EXHAUSTED_BLOCK, maxWait, // don't // block // more than 5 // seconds maxIdle, // max idle connections (unlimited) true, // validate when we borrow connections from pool false // don't bother validation returned connections ); // ConnectionFactory the pool will use to create connections. ConnectionFactory connectionFactory = new DriverManagerConnectionFactory( ConfigurationManager.getProperty("db.url"), ConfigurationManager.getProperty("db.username"), ConfigurationManager.getProperty("db.password")); // // Now we'll create the PoolableConnectionFactory, which wraps // the "real" Connections created by the ConnectionFactory with // the classes that implement the pooling functionality. // String validationQuery = "SELECT 1"; // Oracle has a slightly different validation query if ("oracle".equals(ConfigurationManager.getProperty("db.name"))) { validationQuery = "SELECT 1 FROM DUAL"; } GenericKeyedObjectPoolFactory statementFactory = null; if (useStatementPool) { // The statement Pool is used to pool prepared statements. GenericKeyedObjectPool.Config statementFactoryConfig = new GenericKeyedObjectPool.Config(); // Just grow the pool size when needed. // // This means we will never block when attempting to // create a query. The problem is unclosed statements, // they can never be reused. So if we place a maximum // cap on them, then we might reach a condition where // a page can only be viewed X number of times. The // downside of GROW_WHEN_EXHAUSTED is that this may // allow a memory leak to exist. Both options are bad, // but I'd prefer a memory leak over a failure. // // Perhaps this decision should be derived from config parameters? statementFactoryConfig.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_GROW; statementFactory = new GenericKeyedObjectPoolFactory(null, statementFactoryConfig); } PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, connectionPool, statementFactory, validationQuery, // validation query false, // read only is not default for now false); // Autocommit defaults to none // Obtain a poolName from the config, default is "dspacepool" if (ConfigurationManager.getProperty("db.poolname") != null) { poolName = ConfigurationManager.getProperty("db.poolname"); } // // Finally, we get the PoolingDriver itself... // PoolingDriver driver = (PoolingDriver) DriverManager.getDriver("jdbc:apache:commons:dbcp:"); // // ...and register our pool with it. // if (driver != null) driver.registerPool(poolName, connectionPool); //preload the contents of the database String s = new String(); StringBuilder sb = new StringBuilder(); String schemaPath = System.getProperty("db.schema.path"); if (null == schemaPath) throw new IllegalArgumentException("System property db.schema.path must be defined"); FileReader fr = new FileReader(new File(schemaPath)); BufferedReader br = new BufferedReader(fr); while ((s = br.readLine()) != null) { //we skip white lines and comments if (!"".equals(s.trim()) && !s.trim().startsWith("--")) { sb.append(s); } } br.close(); //we use ";" as a delimiter for each request. This assumes no triggers //nor other calls besides CREATE TABLE, CREATE SEQUENCE and INSERT //exist in the file String[] stmts = sb.toString().split(";"); //stablish the connection using the pool Connection con = DriverManager.getConnection("jdbc:apache:commons:dbcp:" + poolName); Statement st = con.createStatement(); for (int i = 0; i < stmts.length; i++) { // we ensure that there is no spaces before or after the request string // in order to not execute empty statements if (!stmts[i].trim().equals("")) { st.executeUpdate(stmts[i]); log.debug("Loading into database: " + stmts[i]); } } //commit changes con.commit(); con.close(); // Old SimplePool init //DriverManager.registerDriver(new SimplePool()); initialized = true; } catch (SQLException se) { // Simply throw up SQLExceptions throw se; } catch (Exception e) { // Need to be able to catch other exceptions. Pretend they are // SQLExceptions, but do log log.warn("Exception initializing DB pool", e); throw new SQLException(e.toString()); } }
From source file:org.eclipse.osee.jdbc.internal.PooledDataSourceFetcher.java
@SuppressWarnings({ "rawtypes", "unchecked" }) private ObjectPool<Connection> createConnectionPool() throws Exception { MetaData metadata = manager.getMetaData(dbInfo); JdbcConnectionFactory proxiedFactory = manager.getFactory(dbInfo.getDriver()); ConnectionFactory connectionFactory = new ConnectionFactoryProxy(proxiedFactory, dbInfo, metadata.isTxIsolationLevelSupported()); AbandonedObjectPool connectionPool = new AbandonedObjectPool(null, getAbandonedConnectionConfig(poolConfig)); connectionPool.setConfig(getPoolConfig(poolConfig)); GenericKeyedObjectPoolFactory statementPool = null; if (poolConfig.isPoolPreparedStatementsAllowed()) { statementPool = new GenericKeyedObjectPoolFactory(null, getStatementPoolConfig(poolConfig)); }//from w ww .ja va 2 s . c o m AbandonedConfig abandoned = new AbandonedConfig(); abandoned.setLogAbandoned(true); abandoned.setLogWriter(new PrintWriter(System.out)); String validationQuery = metadata.getValidationQuery(); int validationQueryTimeoutSecs = poolConfig.getPoolValidationQueryTimeoutSecs(); boolean defaultReadOnly = false; boolean defaultAutoCommit = true; new PoolableConnectionFactory(connectionFactory, connectionPool, statementPool, validationQuery, validationQueryTimeoutSecs, defaultReadOnly, defaultAutoCommit); return connectionPool; }
From source file:org.opensubsystems.core.persist.jdbc.connectionpool.dbcp.DBCPDatabaseConnectionFactoryImpl.java
/** * {@inheritDoc}/* w w w. j a v a 2 s . c o m*/ */ @Override protected Object createConnectionPool(String strConnectionPoolName, Database database, String strDriverName, String strUrl, String strUser, String strPassword, int iTransactionIsolation) throws OSSException { // I am using here the PoolingDriver instead of PoolingDataSource because // in DBCP version 1.1 the PoolingDriver has clear way how to shutdown // the pool and PoolingDataSource doesn't. // This code was inspired by method setupDriver from // ManualPoolingDriverExample.java in commons-dbcp package v 1.6 ObjectPool connectionPool; ConnectionFactory connectionFactory; PoolableConnectionFactory poolableConnectionFactory; PooledDatabaseConnectionFactorySetupReader setupReader = new PooledDatabaseConnectionFactorySetupReader( strConnectionPoolName, database.getDatabaseTypeIdentifier()); int iInitialPoolSize = setupReader .getIntegerParameterValue(PooledDatabaseConnectionFactorySetupReader.DBPOOL_INITIAL_SIZE) .intValue(); int iMinimalPoolSize = setupReader .getIntegerParameterValue(PooledDatabaseConnectionFactorySetupReader.DBPOOL_MIN_SIZE).intValue(); int iMaximalPoolSize = setupReader .getIntegerParameterValue(PooledDatabaseConnectionFactorySetupReader.DBPOOL_MAX_SIZE).intValue(); boolean bCanGrow = setupReader .getBooleanParameterValue(PooledDatabaseConnectionFactorySetupReader.DBPOOL_CAN_GROW) .booleanValue(); long lMaxWaitTimeForConnection = setupReader .getLongParameterValue(PooledDatabaseConnectionFactorySetupReader.DBPOOL_WAIT_PERIOD).longValue(); boolean bValidateOnBorrow = setupReader .getBooleanParameterValue(PooledDatabaseConnectionFactorySetupReader.DBPOOL_VALIDATE_BORROW) .booleanValue(); boolean bValidateOnReturn = setupReader .getBooleanParameterValue(PooledDatabaseConnectionFactorySetupReader.DBPOOL_VALIDATE_RETURN) .booleanValue(); boolean bValidateOnIdle = setupReader .getBooleanParameterValue(PooledDatabaseConnectionFactorySetupReader.DBPOOL_VALIDATE_IDLE) .booleanValue(); long lTimeBetweenEvictionRunsMillis = setupReader .getLongParameterValue(PooledDatabaseConnectionFactorySetupReader.DBPOOL_IDLE_CHECK_PERIOD) .longValue(); int iNumTestsPerEvictionRun = setupReader .getIntegerParameterValue(PooledDatabaseConnectionFactorySetupReader.DBPOOL_IDLE_CHECK_SIZE) .intValue(); long lMinEvictableIdleTimeMillis = setupReader .getLongParameterValue(PooledDatabaseConnectionFactorySetupReader.DBPOOL_IDLE_PERIOD).longValue(); int iPreparedStatementCacheSize = setupReader.getIntegerParameterValue( PooledDatabaseConnectionFactorySetupReader.DBPOOL_PREPSTATEMENT_CACHE_SIZE).intValue(); // 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. connectionPool = new GenericObjectPool(null, // factory will be specified below iMaximalPoolSize, bCanGrow ? GenericObjectPool.WHEN_EXHAUSTED_GROW : GenericObjectPool.WHEN_EXHAUSTED_BLOCK, lMaxWaitTimeForConnection, iMaximalPoolSize, // max idle - if no connections are used // the pool should not fall under this size iMinimalPoolSize, // min idle - if connection count falls // under this limit (e.g. closed connections) // new connections will be created bValidateOnBorrow, bValidateOnReturn, lTimeBetweenEvictionRunsMillis, iNumTestsPerEvictionRun, lMinEvictableIdleTimeMillis, bValidateOnIdle); // Next, we'll create a ConnectionFactory that the pool will use to // create Connections. I am using DriverManagerConnectionFactory instead // of DriverConnectionFactory because it allows me to specify user name // and password directly connectionFactory = new DriverManagerConnectionFactory(strUrl, strUser, strPassword); // This configuration of prepared statement caching is inspired by // Commons-DBCP Wiki available at http://wiki.apache.org/jakarta-commons/DBCP // null can be used as parameter because this parameter is set in // PoolableConnectionFactory when creating a new PoolableConnection // 0 according to documentation should mean no limit KeyedObjectPoolFactory statementPool = null; if (iPreparedStatementCacheSize >= 0) { statementPool = new GenericKeyedObjectPoolFactory(null, iPreparedStatementCacheSize); } // Now we'll create the PoolableConnectionFactory, which wraps // the "real" Connections created by the ConnectionFactory with // the classes that implement the pooling functionality. poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, connectionPool, statementPool, DatabaseImpl.getInstance().getConnectionTestStatement(), false, // not read-only connection false, // Default auto commit is false iTransactionIsolation); // PoolableConnectionFactory doesn't support the initialSize attribute of // DBCP so I have replicated the code from BasicDataSource v1.37 here try { for (int iIndex = 0; iIndex < iInitialPoolSize; iIndex++) { connectionPool.addObject(); } } catch (Exception e) { throw new OSSDatabaseAccessException("Error preloading the connection pool", e); } if (GlobalConstants.ERROR_CHECKING) { // Put this check here to trick checkstyle assert poolableConnectionFactory != null : "Poolable connection factory cannot be null."; } return connectionPool; }
From source file:org.s23m.cell.repository.RelationalDatabaseRepository.java
private static void initializeConnectionPool() { final Properties props = new Properties(); props.setProperty("user", ConfigValues.getValue("Repository.REPOSITORY_ACCOUNT")); props.setProperty("password", ConfigValues.getValue("Repository.REPOSITORY_PW")); props.setProperty("rewriteBatchedStatements", "true"); final ConnectionFactory cf = new DriverManagerConnectionFactory( ConfigValues.getValue("Repository.REPOSITORY_CONNECTION_STRING"), props); final KeyedObjectPoolFactory keyedObjecPoolFacto = new GenericKeyedObjectPoolFactory(null, MAX_ACTIVE_CONNECTION); new PoolableConnectionFactory(cf, RepositoryHolder.CONNECTION_POOL, keyedObjecPoolFacto, null, false, true); for (int i = 0; i < INITIAL_CONNECTION_POOL_SIZE; i++) { try {/*from w w w .ja v a2 s. com*/ RepositoryHolder.CONNECTION_POOL.addObject(); } catch (final Exception e) { } } new PoolingDriver().registerPool(REPOSITORY_CONNECTION_POOL_ID, RepositoryHolder.CONNECTION_POOL); RepositoryHolder.setConnectionPoolInitialized(true); }