List of usage examples for org.apache.commons.dbcp PoolableConnectionFactory PoolableConnectionFactory
public PoolableConnectionFactory(ConnectionFactory connFactory, ObjectPool pool, KeyedObjectPoolFactory stmtPoolFactory, String validationQuery, boolean defaultReadOnly, boolean defaultAutoCommit)
From source file:com.insprise.common.db.DefaultConnectionPool.java
/** * Sets up the connection pool. Call this at most once only! * * @throws ClassNotFoundException/* ww w . j ava 2 s . c o m*/ */ private void setupPool() throws ClassNotFoundException { if (sourceType != SourceType.DRIVER_MANAGER) { throw new RuntimeException(); } connectionPool = new GenericObjectPool(null); setMaxActive(maxActive); setMaxIdle(maxIdle); setMaxWaittime(maxWaittime); // establish connection factory. ConnectionFactory connectionFactory = null; Class.forName(driverClass); connectionFactory = new DriverManagerConnectionFactory(url, properties); if (validationQuery == null) { log.warn("Validation SQL for database connection pool is null!"); } else { // log.info("Validation SQL for database connection pool is: " + validationQuery); } PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, connectionPool, null, validationQuery, false, true); // force to execute validationQuery before borrowing connection from pool. connectionPool.setTestOnBorrow(true); dataSource = new PoolingDataSource(connectionPool); log.debug("Initialized " + toString()); }
From source file:dev.utils.db.dbcp.ManualPoolingDataSource.java
public DataSource setupDataSource(String connectURI) { ///*from w ww . j a v a 2s. c om*/ // 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. // GenericObjectPool.Config config = new GenericObjectPool.Config(); config.maxActive = maxActive; // ex: 150; config.maxIdle = maxIdle; // ex: 100; config.minIdle = minIdle; //30; config.maxWait = maxWait; //1000; config.testOnBorrow = testOnBorrow; config.testOnReturn = testOnReturn; config.testWhileIdle = testWhileIdle; config.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis; config.numTestsPerEvictionRun = numTestsPerEvictionRun; config.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis; ObjectPool connectionPool = new GenericObjectPool(null, config); // // Next, 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. // Properties connProps = new Properties(); connProps.setProperty("user", username); connProps.setProperty("password", password); //p.setProperty("useUnicode", "true"); //p.setProperty("characterEncoding", "UTF-8"); ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(connectURI, connProps); // // Now 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, connectionPool, null, validationQuery, defaultReadOnly, defaultAutoCommit); // // Finally, we create the PoolingDriver itself, // passing in the object pool we created. // return new PoolingDataSource(connectionPool); }
From source file:net.agmodel.metbroker.driver.impl.JmaMsmJp.java
/** * set up JDBC parameter./*from w w w .ja v a 2 s . c o m*/ * This driver uses postgresql's JDBC driver. * (non-Javadoc) * @see net.agmodel.metbroker.driver.MetDriver#init(net.agmodel.metbroker.driver.DriverConfig) */ public void init(DriverConfig driverConfig) throws DriverException { logger.debug("initialize JMA MSM JP data source"); try { Class.forName("org.postgresql.Driver"); int maxActive = Integer.parseInt(driverConfig.getParam("maxactive")); int maxWait = Integer.parseInt(driverConfig.getParam("maxwait")); int maxIdle = Integer.parseInt(driverConfig.getParam("maxidle")); String user = driverConfig.getParam("user"); String password = driverConfig.getParam("password"); String host = driverConfig.getParam("host"); int port = Integer.parseInt(driverConfig.getParam("port")); String db = driverConfig.getParam("db"); ObjectPool connectionPool = new GenericObjectPool(null, maxActive, GenericObjectPool.WHEN_EXHAUSTED_BLOCK, maxWait, maxIdle, false, false, 60000, 3, 10000, false); Properties p = new Properties(); p.put("user", user); p.put("password", password); ConnectionFactory connectionFactory = new DriverManagerConnectionFactory( "jdbc:postgresql://" + host + ":" + port + "/" + db, p); PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, connectionPool, null, null, false, true); dataSource = new PoolingDataSource(connectionPool); logger.debug("JMA MSM JP DataSource created"); } catch (Exception e) { e.printStackTrace(); throw new DriverException(e.getMessage()); } }
From source file:net.agmodel.metbroker.driver.impl.JmaGsmJp.java
/** * set up JDBC parameter.//from w ww. j a v a2s . c o m * This driver uses postgresql's JDBC driver. * * (non-Javadoc) * @see net.agmodel.metbroker.driver.MetDriver#init(net.agmodel.metbroker.driver.DriverConfig) */ public void init(DriverConfig driverConfig) throws DriverException { logger.debug("initialize JMA GSM JP data source"); try { Class.forName("org.postgresql.Driver"); int maxActive = Integer.parseInt(driverConfig.getParam("maxactive")); int maxWait = Integer.parseInt(driverConfig.getParam("maxwait")); int maxIdle = Integer.parseInt(driverConfig.getParam("maxidle")); String user = driverConfig.getParam("user"); String password = driverConfig.getParam("password"); String host = driverConfig.getParam("host"); int port = Integer.parseInt(driverConfig.getParam("port")); String db = driverConfig.getParam("db"); ObjectPool connectionPool = new GenericObjectPool(null, maxActive, GenericObjectPool.WHEN_EXHAUSTED_BLOCK, maxWait, maxIdle, false, false, 60000, 3, 10000, false); Properties p = new Properties(); p.put("user", user); p.put("password", password); ConnectionFactory connectionFactory = new DriverManagerConnectionFactory( "jdbc:postgresql://" + host + ":" + port + "/" + db, p); PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, connectionPool, null, null, false, true); dataSource = new PoolingDataSource(connectionPool); logger.debug("JMA GSM JP DataSource created"); } catch (Exception e) { e.printStackTrace(); throw new DriverException(e.getMessage()); } }
From source file:net.agmodel.metbroker.driver.impl.JmaGsmGl.java
/** * <PRE>/*w w w.j a va2 s . co m*/ * set up JDBC parameter. * This driver uses postgresql's JDBC driver. * </PRE> * (non-Javadoc) * @see net.agmodel.metbroker.driver.MetDriver#init(net.agmodel.metbroker.driver.DriverConfig) */ public void init(DriverConfig driverConfig) throws DriverException { logger.debug("initialize JMA GSM GLobal data source"); try { Class.forName("org.postgresql.Driver"); int maxActive = Integer.parseInt(driverConfig.getParam("maxactive")); int maxWait = Integer.parseInt(driverConfig.getParam("maxwait")); int maxIdle = Integer.parseInt(driverConfig.getParam("maxidle")); String user = driverConfig.getParam("user"); String password = driverConfig.getParam("password"); String host = driverConfig.getParam("host"); int port = Integer.parseInt(driverConfig.getParam("port")); String db = driverConfig.getParam("db"); ObjectPool connectionPool = new GenericObjectPool(null, maxActive, GenericObjectPool.WHEN_EXHAUSTED_BLOCK, maxWait, maxIdle, false, false, 60000, 3, 10000, false); Properties p = new Properties(); p.put("user", user); p.put("password", password); ConnectionFactory connectionFactory = new DriverManagerConnectionFactory( "jdbc:postgresql://" + host + ":" + port + "/" + db, p); PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, connectionPool, null, null, false, true); dataSource = new PoolingDataSource(connectionPool); logger.debug("JMA GSM Global DataSource created"); } catch (Exception e) { e.printStackTrace(); throw new DriverException(e.getMessage()); } }
From source file:com.glaf.core.jdbc.connection.DBCPConnectionProvider.java
@SuppressWarnings({ "rawtypes", "unchecked" }) public void configure(Properties props) throws RuntimeException { String jdbcDriverClass = props.getProperty(DBConfiguration.JDBC_DRIVER); String jdbcUrl = props.getProperty(DBConfiguration.JDBC_URL); Properties connectionProps = ConnectionProviderFactory.getConnectionProperties(props); log.info("DBCP using driver: " + jdbcDriverClass + " at URL: " + jdbcUrl); log.info("Connection properties: " + PropertiesHelper.maskOut(connectionProps, "password")); autocommit = PropertiesHelper.getBoolean(DBConfiguration.JDBC_AUTOCOMMIT, props); log.info("autocommit mode: " + autocommit); if (jdbcDriverClass == null) { log.warn("No JDBC Driver class was specified by property " + DBConfiguration.JDBC_DRIVER); } else {/*from w w w . ja v a 2s .co m*/ try { Class.forName(jdbcDriverClass); } catch (ClassNotFoundException cnfe) { try { ClassUtils.classForName(jdbcDriverClass); } catch (Exception e) { String msg = "JDBC Driver class not found: " + jdbcDriverClass; log.error(msg, e); throw new RuntimeException(msg, e); } } } String dbUser = props.getProperty(DBConfiguration.JDBC_USER); String dbPassword = props.getProperty(DBConfiguration.JDBC_PASSWORD); if (dbUser == null) { dbUser = ""; // Some RDBMS (e.g Postgresql) don't like null // usernames } if (dbPassword == null) { dbPassword = ""; // Some RDBMS (e.g Postgresql) don't like null // passwords } // Create the actual pool of connections ObjectPool connectionPool = new GenericObjectPool(null); // Apply any properties if (props.getProperty(ConnectionConstants.PROP_MAXIDLE) != null) { int value = PropertiesHelper.getInt(ConnectionConstants.PROP_MAXIDLE, props, 0); if (value > 0) { ((GenericObjectPool) connectionPool).setMaxIdle(value); } } if (props.getProperty(ConnectionConstants.PROP_MINIDLE) != null) { int value = PropertiesHelper.getInt(ConnectionConstants.PROP_MINIDLE, props, 0); if (value > 0) { ((GenericObjectPool) connectionPool).setMinIdle(value); } } if (props.getProperty(ConnectionConstants.PROP_MAXACTIVE) != null) { int value = PropertiesHelper.getInt(ConnectionConstants.PROP_MAXACTIVE, props, 0); if (value > 0) { ((GenericObjectPool) connectionPool).setMaxActive(value); } } if (props.getProperty(ConnectionConstants.PROP_MAXWAIT) != null) { int value = PropertiesHelper.getInt(ConnectionConstants.PROP_MAXWAIT, props, 0); if (value > 0) { ((GenericObjectPool) connectionPool).setMaxWait(value); } } // how often should the evictor run (if ever, default is -1 = off) if (props.getProperty(ConnectionConstants.PROP_TIMEBETWEENEVICTIONRUNSMILLIS) != null) { int value = PropertiesHelper.getInt(ConnectionConstants.PROP_TIMEBETWEENEVICTIONRUNSMILLIS, props, 0); if (value > 0) { ((GenericObjectPool) connectionPool).setTimeBetweenEvictionRunsMillis(value); // in each eviction run, ecict at least a fourth of "maxIdle" // connections int maxIdle = ((GenericObjectPool) connectionPool).getMaxIdle(); int numTestsPerEvictionRun = (int) Math.ceil(((double) maxIdle / 4)); ((GenericObjectPool) connectionPool).setNumTestsPerEvictionRun(numTestsPerEvictionRun); } } // how long may a connection sit idle in the pool before it may be // evicted if (props.getProperty(ConnectionConstants.PROP_MINEVICTABLEIDLETIMEMILLIS) != null) { int value = PropertiesHelper.getInt(ConnectionConstants.PROP_MINEVICTABLEIDLETIMEMILLIS, props, 0); if (value > 0) { ((GenericObjectPool) connectionPool).setMinEvictableIdleTimeMillis(value); } } // Create a factory to be used by the pool to create the connections ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(jdbcUrl, dbUser, dbPassword); // Create a factory for caching the PreparedStatements KeyedObjectPoolFactory kpf = null; if (props.getProperty(ConnectionConstants.PROP_MAXSTATEMENTS) != null) { int value = PropertiesHelper.getInt(ConnectionConstants.PROP_MAXSTATEMENTS, props, 0); if (value > 0) { kpf = new StackKeyedObjectPoolFactory(null, value); } } // Wrap the connections and statements with pooled variants try { String testSQL = null; if (props.getProperty(ConnectionConstants.PROP_VALIDATIONQUERY) != null) { testSQL = PropertiesHelper.getString(ConnectionConstants.PROP_VALIDATIONQUERY, props, null); } new PoolableConnectionFactory(connectionFactory, connectionPool, kpf, testSQL, false, false); if (testSQL != null) { ((GenericObjectPool) connectionPool).setTestOnBorrow(true); } } catch (Exception ex) { ex.printStackTrace(); log.error("could not instantiate DBCP connection pool", ex); throw new ConnectionPoolException("DBCP", jdbcDriverClass, jdbcUrl, ex); } ds = new PoolingDataSource(connectionPool); Connection conn = null; try { conn = ds.getConnection(); if (conn == null) { throw new RuntimeException("DBCP connection pool can't get jdbc connection"); } } catch (SQLException ex) { ex.printStackTrace(); throw new RuntimeException(ex); } finally { JdbcUtils.close(conn); } String i = props.getProperty(DBConfiguration.JDBC_ISOLATION); if (i == null) { isolation = null; } else { isolation = new Integer(i); log.info("JDBC isolation level: " + DBConfiguration.isolationLevelToString(isolation.intValue())); } }
From source file:esg.common.db.DatabaseResource.java
public DatabaseResource setupDataSource(Properties props) { log.trace("Setting up data source... "); if (props == null) { log.error("Property object is [" + props + "]: Cannot setup up data source"); return this; }//from w w w .j a v a 2 s . c o m //Ex: jdbc:postgresql://pcmdi3.llnl.gov:5432/esgcet String protocol = props.getProperty("db.protocol", "jdbc:postgresql:"); String host = props.getProperty("db.host", "localhost"); String port = props.getProperty("db.port", "5432"); String database = props.getProperty("db.database", "esgcet"); String user = props.getProperty("db.user", "dbsuper"); String password = props.getProperty("db.password"); //If the password is not directly available in the properties //object then try to read it via the code provided in the //ESGFProperties type...iff props is actually of the type //ESGFProperties. if (password == null) { try { password = ((esg.common.util.ESGFProperties) props).getDatabasePassword(); } catch (Throwable t) { log.error(" ****** DATABASE PASSWORD IS NOT SET!!! ******"); log.warn( "Check that password is set in the passed in property file or that property object is an ESGFProperties object!!"); t.printStackTrace(); } } String connectURI = protocol + "//" + host + ":" + port + "/" + database; log.info("Connection URI = " + connectURI); connectionPool = new GenericObjectPool(null); ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(connectURI, user, password); PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, connectionPool, null, null, false, true); dataSource = new PoolingDataSource(connectionPool); return this; }
From source file:com.glaf.jbpm.connection.DbcpConnectionProvider.java
@SuppressWarnings({ "rawtypes", "unchecked" }) public void configure(Properties props) throws RuntimeException { String jdbcDriverClass = props.getProperty(Environment.DRIVER); String jdbcUrl = props.getProperty(Environment.URL); Properties connectionProps = ConnectionProviderFactory.getConnectionProperties(props); log.info("DBCP using driver: " + jdbcDriverClass + " at URL: " + jdbcUrl); log.info("Connection properties: " + PropertiesHelper.maskOut(connectionProps, "password")); autocommit = PropertiesHelper.getBoolean(Environment.AUTOCOMMIT, props); log.info("autocommit mode: " + autocommit); if (jdbcDriverClass == null) { log.warn("No JDBC Driver class was specified by property " + Environment.DRIVER); } else {// w ww . j a va2s.c om try { Class.forName(jdbcDriverClass); } catch (ClassNotFoundException cnfe) { try { ClassUtils.classForName(jdbcDriverClass); } catch (Exception e) { String msg = "JDBC Driver class not found: " + jdbcDriverClass; log.error(msg, e); throw new RuntimeException(msg, e); } } } String dbUser = props.getProperty(Environment.USER); String dbPassword = props.getProperty(Environment.PASS); if (dbUser == null) { dbUser = ""; } if (dbPassword == null) { dbPassword = ""; } Properties properties = new Properties(); for (Iterator<Object> ii = props.keySet().iterator(); ii.hasNext();) { String key = (String) ii.next(); if (key.startsWith("hibernate.dbcp.")) { String newKey = key.substring(15); properties.put(newKey, props.get(key)); } } // Create the actual pool of connections ObjectPool connectionPool = new GenericObjectPool(null); if (props.getProperty("hibernate.connection.maxIdle") != null) { int value = PropertiesHelper.getInt("hibernate.connection.maxIdle", props, 0); if (value > 0) { ((GenericObjectPool) connectionPool).setMaxIdle(value); } } if (props.getProperty("hibernate.connection.minIdle") != null) { int value = PropertiesHelper.getInt("hibernate.connection.minIdle", props, 0); if (value > 0) { ((GenericObjectPool) connectionPool).setMinIdle(value); } } if (props.getProperty("hibernate.connection.maxActive") != null) { int value = PropertiesHelper.getInt("hibernate.connection.maxActive", props, 0); if (value > 0) { ((GenericObjectPool) connectionPool).setMaxActive(value); } } if (props.getProperty("hibernate.connection.maxWait") != null) { int value = PropertiesHelper.getInt("hibernate.connection.maxWait", props, 0); if (value > 0) { ((GenericObjectPool) connectionPool).setMaxWait(value); } } // how often should the evictor run (if ever, default is -1 = off) if (props.getProperty("hibernate.connection.timeBetweenEvictionRunsMillis") != null) { int value = PropertiesHelper.getInt("hibernate.connection.timeBetweenEvictionRunsMillis", props, 0); if (value > 0) { ((GenericObjectPool) connectionPool).setTimeBetweenEvictionRunsMillis(value); // in each eviction run, ecict at least a fourth of "maxIdle" // connections int maxIdle = ((GenericObjectPool) connectionPool).getMaxIdle(); int numTestsPerEvictionRun = (int) Math.ceil(((double) maxIdle / 4)); ((GenericObjectPool) connectionPool).setNumTestsPerEvictionRun(numTestsPerEvictionRun); } } // how long may a connection sit idle in the pool before it may be // evicted if (props.getProperty("hibernate.connection.minEvictableIdleTimeMillis") != null) { int value = PropertiesHelper.getInt("hibernate.connection.minEvictableIdleTimeMillis", props, 0); if (value > 0) { ((GenericObjectPool) connectionPool).setMinEvictableIdleTimeMillis(value); } } // Create a factory to be used by the pool to create the connections ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(jdbcUrl, dbUser, dbPassword); // Create a factory for caching the PreparedStatements KeyedObjectPoolFactory kpf = null; if (props.getProperty("hibernate.connection.maxStatements") != null) { int value = PropertiesHelper.getInt("hibernate.connection.maxStatements", props, 0); if (value > 0) { kpf = new StackKeyedObjectPoolFactory(null, value); } } else { kpf = new StackKeyedObjectPoolFactory(null, 200); } // Wrap the connections and statements with pooled variants try { String testSQL = null; if (props.getProperty("hibernate.connection.testSQL") != null) { testSQL = PropertiesHelper.getString("hibernate.connection.testSQL", props, null); } new PoolableConnectionFactory(connectionFactory, connectionPool, kpf, testSQL, false, false); if (testSQL != null) { ((GenericObjectPool) connectionPool).setTestOnBorrow(true); } } catch (Exception e) { throw new ConnectionPoolException("DBCP", jdbcDriverClass, jdbcUrl, e); } ds = new PoolingDataSource(connectionPool); Connection conn = null; try { conn = ds.getConnection(); if (conn == null) { throw new RuntimeException("DBCP connection pool can't get jdbc connection"); } } catch (SQLException ex) { throw new RuntimeException(ex); } finally { JdbcUtils.close(conn); } String i = props.getProperty(Environment.ISOLATION); if (i == null) { isolation = null; } else { isolation = new Integer(i); log.info("JDBC isolation level: " + Environment.isolationLevelToString(isolation.intValue())); } }
From source file:eu.peppol.jdbc.OxalisDataSourceFactoryDbcpImplTest.java
private PoolingDataSource createPoolingDataSource(ConnectionFactory driverConnectionFactory, GenericObjectPool genericObjectPool) { PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(driverConnectionFactory, genericObjectPool, null, null, false, true); poolableConnectionFactory.setValidationQuery("select 1"); return new PoolingDataSource(genericObjectPool); }
From source file:com.l2jserver.service.database.sql.AbstractSQLDatabaseService.java
@Override protected void doStart() throws ServiceStartException { try {/*from w ww .j a va2s .c o m*/ engine = config.getDatabaseEngineClass().newInstance(); } catch (InstantiationException | IllegalAccessException e) { throw new ServiceStartException("DatabaseEngine instance not found", e); } connectionPool = new GenericObjectPool<Connection>(null); connectionPool.setMaxActive(config.getMaxActiveConnections()); connectionPool.setMinIdle(config.getMinIdleConnections()); connectionPool.setMaxIdle(config.getMaxIdleConnections()); // test if connections are active while idle connectionPool.setTestWhileIdle(true); // DriverManager.registerDriver(driver) connectionFactory = new DriverManagerConnectionFactory(config.getJdbcUrl(), config.getUsername(), config.getPassword()); poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, connectionPool, null, "SELECT 1", false, true); dataSource = new PoolingDataSource(connectionPool); if (config.isAutomaticSchemaUpdateEnabled()) { updateSchemas(); } for (final Type<?> type : sqlTypes) { engine.registerType(type); } // cache must be large enough for all world objects, to avoid // duplication... this would endanger non-persistent states objectCache = cacheService.createEternalCache("database-service", IDAllocator.ALLOCABLE_IDS); // start the auto save task autoSaveFuture = threadService.async(60, TimeUnit.SECONDS, 60, new Runnable() { @Override public void run() { try { log.debug("Auto save task started"); int objects = 0; for (final Model<?> object : objectCache) { @SuppressWarnings("unchecked") final DataAccessObject<Model<?>, ?> dao = (DataAccessObject<Model<?>, ?>) daoResolver .getDAO(object.getClass()); if (dao == null) continue; if (dao.save(object) > 0) { objects++; } } log.info("{} objects have been saved by the auto save task", objects); } catch (Exception e) { log.error("Error occured in save thread", e); } } }); }