List of usage examples for org.apache.commons.pool.impl GenericKeyedObjectPoolFactory GenericKeyedObjectPoolFactory
public GenericKeyedObjectPoolFactory(KeyedPoolableObjectFactory factory, int maxActive, byte whenExhaustedAction, long maxWait, int maxIdle, int maxTotal)
From source file:lineage2.commons.dbcp.BasicDataSource.java
/** * Constructor for BasicDataSource./* w w w . j av a2 s. c o m*/ * @param driver String * @param connectURI String * @param uname String * @param passwd String * @param maxActive int * @param maxIdle int * @param idleTimeOut int * @param idleTestPeriod int * @param poolPreparedStatements boolean */ public BasicDataSource(String driver, String connectURI, String uname, String passwd, int maxActive, int maxIdle, int idleTimeOut, int idleTestPeriod, boolean poolPreparedStatements) { GenericObjectPool<?> connectionPool = new GenericObjectPool<>(null); connectionPool.setMaxActive(maxActive); connectionPool.setMaxIdle(maxIdle); connectionPool.setMinIdle(1); connectionPool.setMaxWait(-1L); connectionPool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_GROW); connectionPool.setTestOnBorrow(false); connectionPool.setTestWhileIdle(true); connectionPool.setTimeBetweenEvictionRunsMillis(idleTestPeriod * 1000L); connectionPool.setNumTestsPerEvictionRun(maxActive); connectionPool.setMinEvictableIdleTimeMillis(idleTimeOut * 1000L); GenericKeyedObjectPoolFactory<?, ?> statementPoolFactory = null; if (poolPreparedStatements) { statementPoolFactory = new GenericKeyedObjectPoolFactory<>(null, -1, GenericObjectPool.WHEN_EXHAUSTED_FAIL, 0L, 1, GenericKeyedObjectPool.DEFAULT_MAX_TOTAL); } Properties connectionProperties = new Properties(); connectionProperties.put("user", uname); connectionProperties.put("password", passwd); ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(connectURI, connectionProperties); @SuppressWarnings("unused") PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, connectionPool, statementPoolFactory, "SELECT 1", false, true); PoolingDataSource dataSource = new PoolingDataSource(connectionPool); _connectionPool = connectionPool; _source = dataSource; }
From source file:net.ontopia.persistence.proxy.DBCPConnectionFactory.java
protected void initPool() { // Set up connection pool pool = new GenericObjectPool(null); // Read/Write by default boolean readonly = defaultReadOnly; // Auto-commit disabled by default boolean autocommit = readonly; log.debug("Creating new DBCP connection factory, readonly=" + readonly + ", autocommit=" + autocommit); // Set minimum pool size (default: 20) String _minsize = PropertyUtils.getProperty(properties, "net.ontopia.topicmaps.impl.rdbms.ConnectionPool.MinimumSize", false); int minsize = (_minsize == null ? 20 : Integer.parseInt(_minsize)); log.debug("Setting ConnectionPool.MinimumSize '" + minsize + "'"); pool.setMaxIdle(minsize); // 0 = no limit // Set maximum pool size (default: Integer.MAX_VALUE) String _maxsize = PropertyUtils.getProperty(properties, "net.ontopia.topicmaps.impl.rdbms.ConnectionPool.MaximumSize", false); int maxsize = (_maxsize == null ? 0 : Integer.parseInt(_maxsize)); log.debug("Setting ConnectionPool.MaximumSize '" + maxsize + "'"); pool.setMaxActive(maxsize); // 0 = no limit // Set user timeout (default: never) String _utimeout = PropertyUtils.getProperty(properties, "net.ontopia.topicmaps.impl.rdbms.ConnectionPool.UserTimeout", false); int utimeout = (_utimeout == null ? -1 : Integer.parseInt(_utimeout)); pool.setMaxWait(utimeout); // -1 = never // Set soft maximum - emergency objects (default: true) boolean softmax = PropertyUtils.isTrue(properties, "net.ontopia.topicmaps.impl.rdbms.ConnectionPool.SoftMaximum", true); log.debug("Setting ConnectionPool.SoftMaximum '" + softmax + "'"); if (softmax)/*from ww w .j ava 2 s . c o m*/ pool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_GROW); else pool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_BLOCK); // allow the user to overwrite exhausted options // warning: when set to fail, make sure Maximum and Minimum are set correctly // warning: when set to block, make sure a propper usertimeout is set, or pool will block // forever String _whenExhaustedAction = PropertyUtils.getProperty(properties, "net.ontopia.topicmaps.impl.rdbms.ConnectionPool.WhenExhaustedAction", false); if (EXHAUSED_BLOCK.equals(_whenExhaustedAction)) pool.setWhenExhaustedAction(GenericKeyedObjectPool.WHEN_EXHAUSTED_BLOCK); if (EXHAUSED_GROW.equals(_whenExhaustedAction)) pool.setWhenExhaustedAction(GenericKeyedObjectPool.WHEN_EXHAUSTED_GROW); if (EXHAUSED_FAIL.equals(_whenExhaustedAction)) pool.setWhenExhaustedAction(GenericKeyedObjectPool.WHEN_EXHAUSTED_FAIL); if (pool.getWhenExhaustedAction() == GenericKeyedObjectPool.WHEN_EXHAUSTED_BLOCK) log.debug("Pool is set to block on exhaused"); if (pool.getWhenExhaustedAction() == GenericKeyedObjectPool.WHEN_EXHAUSTED_GROW) log.debug("Pool is set to grow on exhaused"); if (pool.getWhenExhaustedAction() == GenericKeyedObjectPool.WHEN_EXHAUSTED_FAIL) log.debug("Pool is set to fail on exhaused"); // Statement pool GenericKeyedObjectPoolFactory stmpool = null; if (PropertyUtils.isTrue(properties, "net.ontopia.topicmaps.impl.rdbms.ConnectionPool.PoolStatements", true)) { log.debug("Using prepared statement pool: Yes"); stmpool = new GenericKeyedObjectPoolFactory(null, -1, // unlimited maxActive (per key) GenericKeyedObjectPool.WHEN_EXHAUSTED_FAIL, 0, // maxWait 1, // maxIdle (per key) GenericKeyedObjectPool.DEFAULT_MAX_TOTAL); } else { log.debug("Using prepared statement pool: No"); } // Test on borrow pool.setTestOnBorrow(true); // Get validation query String vquery = PropertyUtils.getProperty(properties, "net.ontopia.topicmaps.impl.rdbms.ConnectionPool.ValidationQuery", false); if (vquery == null) vquery = "select seq_count from TM_ADMIN_SEQUENCE where seq_name = '<GLOBAL>'"; try { // Make sure driver is registered ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); Class.forName(getDriver(), true, classLoader); // Create connection factory ConnectionFactory cfactory; if (getUserName() == null || getPassword() == null) { Properties props = new Properties(); props.putAll(properties); cfactory = new DriverManagerConnectionFactory(getConnectionString(), props); } else { cfactory = new DriverManagerConnectionFactory(getConnectionString(), getUserName(), getPassword()); } // Create data source this.pcfactory = new TraceablePoolableConnectionFactory(cfactory, pool, stmpool, vquery, readonly, autocommit); // Set default transaction isolation level pcfactory.setDefaultTransactionIsolation(defaultTransactionIsolation); this.datasource = new PoolingDataSource(pool); } catch (Exception e) { throw new OntopiaRuntimeException("Problems occurred when setting up DBCP connection pool.", e); } }
From source file:org.agnitas.dao.LoggingEnhBasicDataSource.java
/** * <p>Create (if necessary) and return the internal data source we are * using to manage our connections.</p> */*from w w w . jav a 2 s . c om*/ * <p><strong>IMPLEMENTATION NOTE</strong> - It is tempting to use the * "double checked locking" idiom in an attempt to avoid synchronizing * on every single call to this method. However, this idiom fails to * work correctly in the face of some optimizations that are legal for * a JVM to perform.</p> * * @exception SQLException if the object pool cannot be created. */ protected synchronized DataSource createDataSource() throws SQLException { // Return the pool if we have already created it if (dataSource != null) { return (dataSource); } logger.error("-------------------------------------------- Create new datasource"); // Load the JDBC driver class if (driverClassName != null) { try { Class.forName(driverClassName); } catch (Throwable t) { String message = "Cannot load JDBC driver class '" + driverClassName + "'"; logWriter.println(message); t.printStackTrace(logWriter); throw new SQLNestedException(message, t); } } // Create a JDBC driver instance Driver driver = null; try { driver = DriverManager.getDriver(url); } catch (Throwable t) { String message = "Cannot create JDBC driver of class '" + (driverClassName != null ? driverClassName : "") + "' for connect URL '" + url + "'"; logWriter.println(message); t.printStackTrace(logWriter); throw new SQLNestedException(message, t); } // Can't test without a validationQuery if (validationQuery == null) { setTestOnBorrow(false); setTestOnReturn(false); setTestWhileIdle(false); } // Create an object pool to contain our active connections connectionPool = new LoggingObjectPool(); connectionPool.setMaxActive(maxActive); connectionPool.setMaxIdle(maxIdle); connectionPool.setMinIdle(minIdle); connectionPool.setMaxWait(maxWait); connectionPool.setTestOnBorrow(testOnBorrow); connectionPool.setTestOnReturn(testOnReturn); connectionPool.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis); connectionPool.setNumTestsPerEvictionRun(numTestsPerEvictionRun); connectionPool.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis); connectionPool.setTestWhileIdle(testWhileIdle); // Set up statement pool, if desired GenericKeyedObjectPoolFactory statementPoolFactory = null; if (isPoolPreparedStatements()) { statementPoolFactory = new GenericKeyedObjectPoolFactory(null, -1, // unlimited maxActive (per key) GenericKeyedObjectPool.WHEN_EXHAUSTED_FAIL, 0, // maxWait 1, // maxIdle (per key) maxOpenPreparedStatements); } // Set up the driver connection factory we will use if (username != null) { connectionProperties.put("user", username); } else { logger.error("DBCP DataSource configured without a 'username'"); } if (password != null) { connectionProperties.put("password", password); } else { logger.error("DBCP DataSource configured without a 'password'"); } DriverConnectionFactory driverConnectionFactory = new DriverConnectionFactory(driver, url, connectionProperties); // Set up the poolable connection factory we will use PoolableConnectionFactory connectionFactory = null; try { connectionFactory = new PoolableConnectionFactory(driverConnectionFactory, connectionPool, statementPoolFactory, validationQuery, defaultReadOnly, defaultAutoCommit, defaultTransactionIsolation, defaultCatalog, null); if (connectionFactory == null) { throw new SQLException("Cannot create PoolableConnectionFactory"); } validateConnectionFactory(connectionFactory); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new SQLNestedException("Cannot create PoolableConnectionFactory (" + e.getMessage() + ")", e); } // Create and return the pooling data source to manage the connections dataSource = new PoolingDataSource(connectionPool); ((PoolingDataSource) dataSource) .setAccessToUnderlyingConnectionAllowed(isAccessToUnderlyingConnectionAllowed()); dataSource.setLogWriter(logWriter); try { for (int i = 0; i < initialSize; i++) { connectionPool.addObject(); } } catch (Exception e) { throw new SQLNestedException("Error preloading the connection pool", e); } return dataSource; }
From source file:org.apache.ojb.broker.accesslayer.ConnectionFactoryDBCPImpl.java
protected KeyedObjectPoolFactory createStatementPoolFactory(JdbcConnectionDescriptor jcd) { final String platform = jcd.getDbms(); if (platform.startsWith("Oracle9i")) { // mkalen: let the platform set Oracle-specific statement pooling return null; }//from w w w . ja v a2s . c om // Set up statement pool, if desired GenericKeyedObjectPoolFactory statementPoolFactory = null; final Properties properties = jcd.getConnectionPoolDescriptor().getDbcpProperties(); final String poolStmtParam = properties.getProperty(PARAM_NAME_POOL_STATEMENTS); if (poolStmtParam != null && Boolean.valueOf(poolStmtParam).booleanValue()) { int maxOpenPreparedStatements = GenericKeyedObjectPool.DEFAULT_MAX_TOTAL; final String maxOpenPrepStmtString = properties.getProperty(PARAM_NAME_STATEMENT_POOL_MAX_TOTAL); if (maxOpenPrepStmtString != null) { maxOpenPreparedStatements = Integer.parseInt(maxOpenPrepStmtString); } // Use the same values as Commons DBCP BasicDataSource statementPoolFactory = new GenericKeyedObjectPoolFactory(null, -1, // unlimited maxActive (per key) GenericKeyedObjectPool.WHEN_EXHAUSTED_FAIL, 0, // maxWait 1, // maxIdle (per key) maxOpenPreparedStatements); } return statementPoolFactory; }
From source file:org.kuali.rice.core.framework.persistence.jdbc.datasource.RiceXADataSource.java
protected KeyedObjectPoolFactory createStatementPoolFactory() { return new GenericKeyedObjectPoolFactory(null, -1, // unlimited maxActive (per key) GenericKeyedObjectPool.WHEN_EXHAUSTED_GROW, 0, // maxWait 1, // maxIdle (per key) getPreparedStatementCacheSize()); }
From source file:org.onecmdb.core.utils.transform.jdbc.ClassLoaderBasicDataSource.java
/** * <p>Create (if necessary) and return the internal data source we are * using to manage our connections.</p> * * <p><strong>IMPLEMENTATION NOTE</strong> - It is tempting to use the * "double checked locking" idiom in an attempt to avoid synchronizing * on every single call to this method. However, this idiom fails to * work correctly in the face of some optimizations that are legal for * a JVM to perform.</p>/*from w w w. ja va 2 s . co m*/ * * @throws SQLException if the object pool cannot be created. */ protected synchronized DataSource createDataSource() throws SQLException { // Return the pool if we have already created it if (dataSource != null) { return (dataSource); } // Load the JDBC driver class Driver driver = null; if (driverClassName != null) { try { Class driverClass = Class.forName(driverClassName, true, driverLoader); driver = (Driver) driverClass.newInstance(); //Class.forName(driverClassName); } catch (Throwable t) { String message = "Cannot load JDBC driver class '" + driverClassName + "'"; logWriter.println(message); t.printStackTrace(logWriter); throw new SQLNestedException(message, t); } } // Create a JDBC driver instance if (driver == null) { try { driver = DriverManager.getDriver(url); } catch (Throwable t) { String message = "Cannot create JDBC driver of class '" + (driverClassName != null ? driverClassName : "") + "' for connect URL '" + url + "'"; logWriter.println(message); t.printStackTrace(logWriter); throw new SQLNestedException(message, t); } } // Can't test without a validationQuery if (validationQuery == null) { setTestOnBorrow(false); setTestOnReturn(false); setTestWhileIdle(false); } // Create an object pool to contain our active connections if ((abandonedConfig != null) && (abandonedConfig.getRemoveAbandoned())) { connectionPool = new AbandonedObjectPool(null, abandonedConfig); } else { connectionPool = new GenericObjectPool(); } connectionPool.setMaxActive(maxActive); connectionPool.setMaxIdle(maxIdle); connectionPool.setMinIdle(minIdle); connectionPool.setMaxWait(maxWait); connectionPool.setTestOnBorrow(testOnBorrow); connectionPool.setTestOnReturn(testOnReturn); connectionPool.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis); connectionPool.setNumTestsPerEvictionRun(numTestsPerEvictionRun); connectionPool.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis); connectionPool.setTestWhileIdle(testWhileIdle); // Set up statement pool, if desired GenericKeyedObjectPoolFactory statementPoolFactory = null; if (isPoolPreparedStatements()) { statementPoolFactory = new GenericKeyedObjectPoolFactory(null, -1, // unlimited maxActive (per key) GenericKeyedObjectPool.WHEN_EXHAUSTED_FAIL, 0, // maxWait 1, // maxIdle (per key) maxOpenPreparedStatements); } // Set up the driver connection factory we will use if (username != null) { connectionProperties.put("user", username); } else { log("DBCP DataSource configured without a 'username'"); } if (password != null) { connectionProperties.put("password", password); } else { log("DBCP DataSource configured without a 'password'"); } DriverConnectionFactory driverConnectionFactory = new DriverConnectionFactory(driver, url, connectionProperties); // Set up the poolable connection factory we will use PoolableConnectionFactory connectionFactory = null; try { connectionFactory = new PoolableConnectionFactory(driverConnectionFactory, connectionPool, statementPoolFactory, validationQuery, defaultReadOnly, defaultAutoCommit, defaultTransactionIsolation, defaultCatalog, abandonedConfig); if (connectionFactory == null) { throw new SQLException("Cannot create PoolableConnectionFactory"); } validateConnectionFactory(connectionFactory); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new SQLNestedException("Cannot create PoolableConnectionFactory (" + e.getMessage() + ")", e); } // Create and return the pooling data source to manage the connections dataSource = new PoolingDataSource(connectionPool); ((PoolingDataSource) dataSource) .setAccessToUnderlyingConnectionAllowed(isAccessToUnderlyingConnectionAllowed()); dataSource.setLogWriter(logWriter); try { for (int i = 0; i < initialSize; i++) { connectionPool.addObject(); } } catch (Exception e) { throw new SQLNestedException("Error preloading the connection pool", e); } return dataSource; }
From source file:org.openspaces.jdbc.datasource.DbcpBasicDataSource.java
/** * <p>Create (if necessary) and return the internal data source we are * using to manage our connections.</p> * * <p><strong>IMPLEMENTATION NOTE</strong> - It is tempting to use the * "double checked locking" idiom in an attempt to avoid synchronizing * on every single call to this method. However, this idiom fails to * work correctly in the face of some optimizations that are legal for * a JVM to perform.</p>/*w w w . j a va 2 s.com*/ * * @throws SQLException if the object pool cannot be created. */ protected void createDataSource() throws SQLException { // Can't test without a validationQuery if (validationQuery == null) { setTestOnBorrow(false); setTestOnReturn(false); setTestWhileIdle(false); } // Create an object pool to contain our active connections if ((abandonedConfig != null) && (abandonedConfig.getRemoveAbandoned() == true)) { connectionPool = new AbandonedObjectPool(null, abandonedConfig); } else { connectionPool = new GenericObjectPool(); } connectionPool.setMaxActive(maxActive); connectionPool.setMaxIdle(maxIdle); connectionPool.setMinIdle(minIdle); connectionPool.setMaxWait(maxWait); connectionPool.setTestOnBorrow(testOnBorrow); connectionPool.setTestOnReturn(testOnReturn); connectionPool.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis); connectionPool.setNumTestsPerEvictionRun(numTestsPerEvictionRun); connectionPool.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis); connectionPool.setTestWhileIdle(testWhileIdle); // Set up statement pool, if desired GenericKeyedObjectPoolFactory statementPoolFactory = null; if (isPoolPreparedStatements()) { statementPoolFactory = new GenericKeyedObjectPoolFactory(null, -1, // unlimited maxActive (per key) GenericKeyedObjectPool.WHEN_EXHAUSTED_FAIL, 0, // maxWait 1, // maxIdle (per key) maxOpenPreparedStatements); } DataSourceConnectionFactory dataSourceConnectionFactory = new DataSourceConnectionFactory( new SpaceDriverManagerDataSource(space)); // Set up the poolable connection factory we will use try { PoolableConnectionFactory connectionFactory = new PoolableConnectionFactory(dataSourceConnectionFactory, connectionPool, statementPoolFactory, validationQuery, defaultReadOnly, defaultAutoCommit, defaultTransactionIsolation, defaultCatalog, abandonedConfig); validateConnectionFactory(connectionFactory); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new SQLNestedException("Cannot create PoolableConnectionFactory (" + e.getMessage() + ")", e); } // Create and return the pooling data source to manage the connections dataSource = new PoolingDataSource(connectionPool); ((PoolingDataSource) dataSource) .setAccessToUnderlyingConnectionAllowed(isAccessToUnderlyingConnectionAllowed()); dataSource.setLogWriter(logWriter); try { for (int i = 0; i < initialSize; i++) { connectionPool.addObject(); } } catch (Exception e) { throw new SQLNestedException("Error preloading the connection pool", e); } }
From source file:org.pentaho.platform.engine.services.connection.datasource.dbcp.PooledDatasourceHelper.java
public static PoolingDataSource setupPooledDataSource(IDatabaseConnection databaseConnection) throws DBDatasourceServiceException { PoolingDataSource poolingDataSource = null; String driverClass = null;// www . j av a 2 s. c o m String url = null; try { if (databaseConnection.getAccessType().equals(DatabaseAccessType.JNDI)) { throw new DBDatasourceServiceException(Messages.getInstance().getErrorString( "PooledDatasourceHelper.ERROR_0008_UNABLE_TO_POOL_DATASOURCE_IT_IS_JNDI", databaseConnection.getName())); } ICacheManager cacheManager = PentahoSystem.getCacheManager(null); IDatabaseDialectService databaseDialectService = PentahoSystem.get(IDatabaseDialectService.class); if (databaseDialectService == null) { throw new DBDatasourceServiceException(Messages.getInstance().getErrorString( "PooledDatasourceHelper.ERROR_0005_UNABLE_TO_POOL_DATASOURCE_NO_DIALECT_SERVICE", databaseConnection.getName())); } IDatabaseDialect dialect = databaseDialectService.getDialect(databaseConnection); if (dialect == null || dialect.getDatabaseType() == null) { throw new DBDatasourceServiceException(Messages.getInstance().getErrorString( "PooledDatasourceHelper.ERROR_0004_UNABLE_TO_POOL_DATASOURCE_NO_DIALECT", databaseConnection.getName())); } if (databaseConnection.getDatabaseType().getShortName().equals("GENERIC")) { //$NON-NLS-1$ driverClass = databaseConnection.getAttributes() .get(GenericDatabaseDialect.ATTRIBUTE_CUSTOM_DRIVER_CLASS); if (StringUtils.isEmpty(driverClass)) { throw new DBDatasourceServiceException(Messages.getInstance().getErrorString( "PooledDatasourceHelper.ERROR_0006_UNABLE_TO_POOL_DATASOURCE_NO_CLASSNAME", databaseConnection.getName())); } } else { driverClass = dialect.getNativeDriver(); if (StringUtils.isEmpty(driverClass)) { throw new DBDatasourceServiceException(Messages.getInstance().getErrorString( "PooledDatasourceHelper.ERROR_0007_UNABLE_TO_POOL_DATASOURCE_NO_DRIVER", databaseConnection.getName())); } } try { url = dialect.getURLWithExtraOptions(databaseConnection); } catch (DatabaseDialectException e) { url = null; } // Read default connection pooling parameter String maxdleConn = PentahoSystem.getSystemSetting("dbcp-defaults/max-idle-conn", null); //$NON-NLS-1$ String minIdleConn = PentahoSystem.getSystemSetting("dbcp-defaults/min-idle-conn", null); //$NON-NLS-1$ String maxActConn = PentahoSystem.getSystemSetting("dbcp-defaults/max-act-conn", null); //$NON-NLS-1$ String validQuery = null; String whenExhaustedAction = PentahoSystem.getSystemSetting("dbcp-defaults/when-exhausted-action", //$NON-NLS-1$ null); String wait = PentahoSystem.getSystemSetting("dbcp-defaults/wait", null); //$NON-NLS-1$ String testWhileIdleValue = PentahoSystem.getSystemSetting("dbcp-defaults/test-while-idle", null); //$NON-NLS-1$ String testOnBorrowValue = PentahoSystem.getSystemSetting("dbcp-defaults/test-on-borrow", null); //$NON-NLS-1$ String testOnReturnValue = PentahoSystem.getSystemSetting("dbcp-defaults/test-on-return", null); //$NON-NLS-1$ // property initialization boolean testWhileIdle = !StringUtil.isEmpty(testWhileIdleValue) ? Boolean.parseBoolean(testWhileIdleValue) : false; boolean testOnBorrow = !StringUtil.isEmpty(testOnBorrowValue) ? Boolean.parseBoolean(testOnBorrowValue) : false; boolean testOnReturn = !StringUtil.isEmpty(testOnReturnValue) ? Boolean.parseBoolean(testOnReturnValue) : false; int maxActiveConnection = !StringUtil.isEmpty(maxActConn) ? Integer.parseInt(maxActConn) : -1; long waitTime = !StringUtil.isEmpty(wait) ? Integer.parseInt(wait) : -1; byte whenExhaustedActionType = !StringUtil.isEmpty(whenExhaustedAction) ? Byte.parseByte(whenExhaustedAction) : GenericObjectPool.WHEN_EXHAUSTED_BLOCK; int minIdleConnection = !StringUtil.isEmpty(minIdleConn) ? Integer.parseInt(minIdleConn) : -1; int maxIdleConnection = !StringUtil.isEmpty(maxdleConn) ? Integer.parseInt(maxdleConn) : -1; // setting properties according to user specifications Map<String, String> attributes = databaseConnection.getConnectionPoolingProperties(); if (attributes.containsKey(IDBDatasourceService.MAX_ACTIVE_KEY) && NumberUtils.isNumber(attributes.get(IDBDatasourceService.MAX_ACTIVE_KEY))) { maxActiveConnection = Integer.parseInt(attributes.get(IDBDatasourceService.MAX_ACTIVE_KEY)); } if (attributes.containsKey(IDBDatasourceService.MAX_WAIT_KEY) && NumberUtils.isNumber(attributes.get(IDBDatasourceService.MAX_WAIT_KEY))) { waitTime = Integer.parseInt(attributes.get(IDBDatasourceService.MAX_WAIT_KEY)); } if (attributes.containsKey(IDBDatasourceService.MIN_IDLE_KEY) && NumberUtils.isNumber(attributes.get(IDBDatasourceService.MIN_IDLE_KEY))) { minIdleConnection = Integer.parseInt(attributes.get(IDBDatasourceService.MIN_IDLE_KEY)); } if (attributes.containsKey(IDBDatasourceService.MAX_IDLE_KEY) && NumberUtils.isNumber(attributes.get(IDBDatasourceService.MAX_IDLE_KEY))) { maxIdleConnection = Integer.parseInt(attributes.get(IDBDatasourceService.MAX_IDLE_KEY)); } if (attributes.containsKey(IDBDatasourceService.QUERY_KEY)) { validQuery = attributes.get(IDBDatasourceService.QUERY_KEY); } if (attributes.containsKey(IDBDatasourceService.TEST_ON_BORROW)) { testOnBorrow = Boolean.parseBoolean(attributes.get(IDBDatasourceService.TEST_ON_BORROW)); } if (attributes.containsKey(IDBDatasourceService.TEST_ON_RETURN)) { testOnReturn = Boolean.parseBoolean(attributes.get(IDBDatasourceService.TEST_ON_RETURN)); } if (attributes.containsKey(IDBDatasourceService.TEST_WHILE_IDLE)) { testWhileIdle = Boolean.parseBoolean(attributes.get(IDBDatasourceService.TEST_WHILE_IDLE)); } poolingDataSource = new PoolingDataSource(); Class.forName(driverClass); // As the name says, this is a generic pool; it returns basic Object-class objects. GenericObjectPool pool = new GenericObjectPool(null); // if removedAbandoned = true, then an AbandonedObjectPool object will take GenericObjectPool's place if (attributes.containsKey(IDBDatasourceService.REMOVE_ABANDONED) && true == Boolean.parseBoolean(attributes.get(IDBDatasourceService.REMOVE_ABANDONED))) { AbandonedConfig config = new AbandonedConfig(); config.setRemoveAbandoned( Boolean.parseBoolean(attributes.get(IDBDatasourceService.REMOVE_ABANDONED))); if (attributes.containsKey(IDBDatasourceService.LOG_ABANDONED)) { config.setLogAbandoned( Boolean.parseBoolean(attributes.get(IDBDatasourceService.LOG_ABANDONED))); } if (attributes.containsKey(IDBDatasourceService.REMOVE_ABANDONED_TIMEOUT) && NumberUtils.isNumber(attributes.get(IDBDatasourceService.REMOVE_ABANDONED_TIMEOUT))) { config.setRemoveAbandonedTimeout( Integer.parseInt(attributes.get(IDBDatasourceService.REMOVE_ABANDONED_TIMEOUT))); } pool = new AbandonedObjectPool(null, config); } pool.setWhenExhaustedAction(whenExhaustedActionType); // Tuning the connection pool pool.setMaxActive(maxActiveConnection); pool.setMaxIdle(maxIdleConnection); pool.setMaxWait(waitTime); pool.setMinIdle(minIdleConnection); pool.setTestWhileIdle(testWhileIdle); pool.setTestOnReturn(testOnReturn); pool.setTestOnBorrow(testOnBorrow); pool.setTestWhileIdle(testWhileIdle); if (attributes.containsKey(IDBDatasourceService.TIME_BETWEEN_EVICTION_RUNS_MILLIS) && NumberUtils .isNumber(attributes.get(IDBDatasourceService.TIME_BETWEEN_EVICTION_RUNS_MILLIS))) { pool.setTimeBetweenEvictionRunsMillis( Long.parseLong(attributes.get(IDBDatasourceService.TIME_BETWEEN_EVICTION_RUNS_MILLIS))); } /* * ConnectionFactory creates connections on behalf of the pool. Here, we use the DriverManagerConnectionFactory * because that essentially uses DriverManager as the source of connections. */ ConnectionFactory factory = null; if (url.startsWith("jdbc:mysql:")) { Properties props = new Properties(); props.put("user", databaseConnection.getUsername()); props.put("password", databaseConnection.getPassword()); props.put("socketTimeout", "0"); props.put("connectTimeout", "5000"); factory = new DriverManagerConnectionFactory(url, props); } else { factory = new DriverManagerConnectionFactory(url, databaseConnection.getUsername(), databaseConnection.getPassword()); } boolean defaultReadOnly = attributes.containsKey(IDBDatasourceService.DEFAULT_READ_ONLY) ? Boolean.parseBoolean(attributes.get(IDBDatasourceService.TEST_WHILE_IDLE)) : false; // default to false boolean defaultAutoCommit = attributes.containsKey(IDBDatasourceService.DEFAULT_AUTO_COMMIT) ? Boolean.parseBoolean(attributes.get(IDBDatasourceService.DEFAULT_AUTO_COMMIT)) : true; // default to true KeyedObjectPoolFactory kopf = null; if (attributes.containsKey(IDBDatasourceService.POOL_PREPARED_STATEMENTS) && true == Boolean .parseBoolean(attributes.get(IDBDatasourceService.POOL_PREPARED_STATEMENTS))) { int maxOpenPreparedStatements = -1; // unlimited if (attributes.containsKey(IDBDatasourceService.MAX_OPEN_PREPARED_STATEMENTS) && NumberUtils .isNumber(attributes.get(IDBDatasourceService.MAX_OPEN_PREPARED_STATEMENTS))) { maxOpenPreparedStatements = Integer .parseInt(attributes.get(IDBDatasourceService.MAX_OPEN_PREPARED_STATEMENTS)); } kopf = new GenericKeyedObjectPoolFactory(null, pool.getMaxActive(), pool.getWhenExhaustedAction(), pool.getMaxWait(), pool.getMaxIdle(), maxOpenPreparedStatements); } /* * Puts pool-specific wrappers on factory connections. For clarification: "[PoolableConnection]Factory," not * "Poolable[ConnectionFactory]." */ PoolableConnectionFactory pcf = new PoolableConnectionFactory(factory, // ConnectionFactory pool, // ObjectPool kopf, // KeyedObjectPoolFactory validQuery, // String (validation query) defaultReadOnly, // boolean (default to read-only?) defaultAutoCommit // boolean (default to auto-commit statements?) ); if (attributes.containsKey(IDBDatasourceService.DEFAULT_TRANSACTION_ISOLATION) && !IDBDatasourceService.TRANSACTION_ISOLATION_NONE_VALUE .equalsIgnoreCase(attributes.get(IDBDatasourceService.DEFAULT_TRANSACTION_ISOLATION))) { Isolation isolationLevel = Isolation .valueOf(attributes.get(IDBDatasourceService.DEFAULT_TRANSACTION_ISOLATION)); if (isolationLevel != null) { pcf.setDefaultTransactionIsolation(isolationLevel.value()); } } if (attributes.containsKey(IDBDatasourceService.DEFAULT_CATALOG)) { pcf.setDefaultCatalog(attributes.get(IDBDatasourceService.DEFAULT_CATALOG)); } /* * initialize the pool to X connections */ Logger.debug(PooledDatasourceHelper.class, "Pool defaults to " + maxActiveConnection + " max active/" + maxIdleConnection + "max idle" //$NON-NLS-3$ + "with " + waitTime + "wait time"//$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-4$ //$NON-NLS-5$ + " idle connections."); //$NON-NLS-1$ for (int i = 0; i < maxIdleConnection; ++i) { pool.addObject(); } Logger.debug(PooledDatasourceHelper.class, "Pool now has " + pool.getNumActive() + " active/" + pool.getNumIdle() + " idle connections."); //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-3$ /* * All of this is wrapped in a DataSource, which client code should already know how to handle (since it's the * same class of object they'd fetch via the container's JNDI tree */ poolingDataSource.setPool(pool); if (attributes.containsKey(IDBDatasourceService.ACCESS_TO_UNDERLYING_CONNECTION_ALLOWED)) { poolingDataSource.setAccessToUnderlyingConnectionAllowed(Boolean.parseBoolean( attributes.get(IDBDatasourceService.ACCESS_TO_UNDERLYING_CONNECTION_ALLOWED))); } // store the pool, so we can get to it later cacheManager.putInRegionCache(IDBDatasourceService.JDBC_POOL, databaseConnection.getName(), pool); return (poolingDataSource); } catch (Exception e) { throw new DBDatasourceServiceException(e); } }
From source file:org.sakaiproject.kernel.persistence.dbcp.DataSourceServiceImpl.java
/** * Construct a DBCP data source service. * * @param driverClassName//from w ww.j a va 2 s . c o m * @param url * @param username * @param password * @param validationQuery * @param defaultReadOnly * @param defaultAutoCommit * @param poolPreparedStatements * @throws ClassNotFoundException * @throws SQLException */ @Inject @edu.umd.cs.findbugs.annotations.SuppressWarnings(value = { "URF_UNREAD_FIELD" }, justification = "The conection factory must be initialized before use") public DataSourceServiceImpl(@Named(KernelConstants.JDBC_DRIVER_NAME) String driverClassName, @Named(KernelConstants.JDBC_URL) String url, @Named(KernelConstants.JDBC_USERNAME) String username, @Named(KernelConstants.JDBC_PASSWORD) String password, @Named(KernelConstants.JDBC_VALIDATION_QUERY) String validationQuery, @Named(KernelConstants.JDBC_DEFAULT_READ_ONLY) boolean defaultReadOnly, @Named(KernelConstants.JDBC_DEFAULT_AUTO_COMMIT) boolean defaultAutoCommit, @Named(KernelConstants.JDBC_DEFAULT_PREPARED_STATEMENTS) boolean poolPreparedStatements) throws ClassNotFoundException, SQLException { Class.forName(driverClassName); GenericObjectPool connectionPool = new GenericObjectPool(null); ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(url, username, password); // Set up statement pool, if desired GenericKeyedObjectPoolFactory statementPoolFactory = null; if (poolPreparedStatements) { int maxActive = -1; byte whenExhaustedAction = GenericKeyedObjectPool.WHEN_EXHAUSTED_FAIL; long maxWait = 0L; int maxIdlePerKey = 1; int maxOpenPreparedStatements = 0; statementPoolFactory = new GenericKeyedObjectPoolFactory(null, maxActive, whenExhaustedAction, maxWait, maxIdlePerKey, maxOpenPreparedStatements); } poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, connectionPool, statementPoolFactory, validationQuery, defaultReadOnly, defaultAutoCommit); dataSource = new PoolingDataSource(connectionPool); }
From source file:org.sakaiproject.nakamura.persistence.dbcp.DataSourceServiceImpl.java
@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = { "URF_UNREAD_FIELD", "UWF_UNWRITTEN_FIELD" }, justification = "PoolableConnectionFactory injects itself into connectionPool, but we need a reference to it, ConfigurationService is OSgi managed.") protected void activate(ComponentContext componentContext) throws ClassNotFoundException { String driverClassName = confurationService.getProperty(NakamuraConstants.JDBC_DRIVER_NAME); String url = confurationService.getProperty(NakamuraConstants.JDBC_URL); String username = confurationService.getProperty(NakamuraConstants.JDBC_USERNAME); String password = confurationService.getProperty(NakamuraConstants.JDBC_PASSWORD); String validationQuery = confurationService.getProperty(NakamuraConstants.JDBC_VALIDATION_QUERY); boolean defaultReadOnly = Boolean .valueOf(confurationService.getProperty(NakamuraConstants.JDBC_DEFAULT_READ_ONLY)); boolean defaultAutoCommit = Boolean .valueOf(confurationService.getProperty(NakamuraConstants.JDBC_DEFAULT_AUTO_COMMIT)); boolean poolPreparedStatements = Boolean .valueOf(confurationService.getProperty(NakamuraConstants.JDBC_DEFAULT_PREPARED_STATEMENTS)); Class.forName(driverClassName); GenericObjectPool connectionPool = new GenericObjectPool(null); ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(url, username, password); // Set up statement pool, if desired GenericKeyedObjectPoolFactory statementPoolFactory = null; if (poolPreparedStatements) { int maxActive = -1; byte whenExhaustedAction = GenericKeyedObjectPool.WHEN_EXHAUSTED_FAIL; long maxWait = 0L; int maxIdlePerKey = 1; int maxOpenPreparedStatements = 0; statementPoolFactory = new GenericKeyedObjectPoolFactory(null, maxActive, whenExhaustedAction, maxWait, maxIdlePerKey, maxOpenPreparedStatements); }/*from w w w . j a v a 2s . c o m*/ poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, connectionPool, statementPoolFactory, validationQuery, defaultReadOnly, defaultAutoCommit); dataSource = new PoolingDataSource(connectionPool); }