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.google.acre.keystore.MySQLKeyStore.java
@SuppressWarnings("unused") private void setupDriver(String connectURI, String username, String password) throws SQLException, ClassNotFoundException { GenericObjectPool connectionPool = new GenericObjectPool(null); connectionPool.setTimeBetweenEvictionRunsMillis(5 * 60 * 1000 - 13); // check if jdbc connections are still alive every 5 min - 13 msec ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(connectURI, username, password); new PoolableConnectionFactory(connectionFactory, connectionPool, null, TEST_QUERY, false, true); Class.forName("org.apache.commons.dbcp.PoolingDriver"); PoolingDriver driver = (PoolingDriver) DriverManager.getDriver(DRIVER_PREFIX); driver.registerPool(DATASOURCE_NAME, connectionPool); active = true;/*from www. j av a2s .com*/ // Now we can just use the connect string "jdbc:apache:commons:dbcp:keystore" // to access our pool of Connections. }
From source file:backtype.storm.scheduler.adaptive.DataManager.java
private DataManager() { logger = Logger.getLogger(DataManager.class); logger.info("Starting DataManager (working directory: " + System.getProperty("user.dir") + ")"); try {//from ww w . j av a 2 s . co m // load configuration from file logger.debug("Loading configuration from file"); Properties properties = new Properties(); properties.load(new FileInputStream("db.ini")); logger.debug("Configuration loaded"); // load JDBC driver logger.debug("Loading JDBC driver"); String jdbc_driver = properties.getProperty("jdbc.driver").trim(); Class.forName(jdbc_driver); logger.debug("Driver loaded"); // set up data source logger.debug("Setting up pooling data source"); String connection_uri = properties.getProperty("data.connection.uri"); String validation_query = properties.getProperty("validation.query"); ObjectPool connectionPool = new GenericObjectPool(null); ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(connection_uri, null); PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, connectionPool, null, validation_query, false, true); poolableConnectionFactory.hashCode(); dataSource = new PoolingDataSource(connectionPool); logger.debug("Data source set up"); nodeName = properties.getProperty("node-name"); if (properties.getProperty("capacity") != null) { capacity = Integer.parseInt(properties.getProperty("capacity")); if (capacity < 1 || capacity > 100) throw new RuntimeException("Wrong capacity: " + capacity + ", expected in the range [1, 100]"); } logger.info("DataManager started"); } catch (Exception e) { logger.error("Error starting DataManager", e); } }
From source file:lineage2.commons.dbcp.BasicDataSource.java
/** * Constructor for BasicDataSource.//from w w w .j av a 2s . 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:com.jaspersoft.jasperserver.api.engine.jasperreports.service.impl.TibcoDriverManagerImpl.java
public Connection unlockConnection(DataSource dataSource) throws SQLException { Connection originalConnection = getOriginalConnection(dataSource); if (unlockDSConnection(originalConnection)) return originalConnection; GenericObjectPool connectionPool = new GenericObjectPool(null); DataSourceConnectionFactory connectionFactory = new DataSourceConnectionFactory(dataSource); PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, connectionPool, null, null, false, true); PoolingDataSource ds = new PoolingDataSource(connectionPool); if (ds != null) { Connection connection = getOriginalConnection(ds); ds.setAccessToUnderlyingConnectionAllowed(true); if (unlockDSConnection(connection)) return connection; }//from w w w . j av a 2s . c o m return originalConnection; }
From source file:eu.peppol.jdbc.OxalisDataSourceFactoryDbcpImpl.java
/** * Creates a DataSource with connection pooling as provided by Apache DBCP * * @return a DataSource/*from w ww .j a va2 s .co m*/ */ public static DataSource configureAndCreateDataSource() { log.debug("Configuring DataSource wrapped in a Database Connection Pool, using custom loader"); GlobalConfiguration globalConfiguration = GlobalConfigurationImpl.getInstance(); String jdbcDriverClassPath = globalConfiguration.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 = globalConfiguration.getJdbcDriverClassName(); String connectURI = globalConfiguration.getJdbcConnectionURI(); String userName = globalConfiguration.getJdbcUsername(); String password = globalConfiguration.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 object pool holding our driver connections GenericObjectPool genericObjectPool = new GenericObjectPool(null); genericObjectPool.setMaxActive(100); genericObjectPool.setMaxIdle(30); genericObjectPool.setMaxWait(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 // DBCP Factory holding the pooled connection, which are created by the driver connection factory and held in the supplied pool PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(driverConnectionFactory, genericObjectPool, null, null, false, true); String validationQuery = globalConfiguration.getValidationQuery(); poolableConnectionFactory.setValidationQuery(validationQuery); // Creates the actual DataSource instance PoolingDataSource poolingDataSource = new PoolingDataSource(genericObjectPool); return poolingDataSource; }
From source file:gov.lanl.util.DBCPUtils.java
/** * Set-up a DBCP DataSource from core connection properties. * @param connectURI jdbc connection uri * @param jdbcDriverName qualified classpath to jdbc driver for database * @param username database user account * @param password database password// w w w . j a va 2s . c o m * @param maxActive max simultaneous db connections (default: 50) * @param maxIdle max idle db connections (default: 10) */ public static DataSource setupDataSource(String connectURI, String jdbcDriverName, String username, String password, int maxActive, int maxIdle) throws Exception { try { java.lang.Class.forName(jdbcDriverName).newInstance(); } catch (Exception e) { log.error( "Error when attempting to obtain DB Driver: " + jdbcDriverName + " on " + new Date().toString(), e); throw new ResolverException(e); } if (maxActive <= 0) maxActive = 50; if (maxIdle <= 0) maxIdle = 10; GenericObjectPool connectionPool = new GenericObjectPool(null, // PoolableObjectFactory, can be null maxActive, // max active GenericObjectPool.WHEN_EXHAUSTED_BLOCK, // action when exhausted 3000, // max wait (milli seconds) maxIdle, // max idle false, // test on borrow false, // test on return 60000, // time between eviction runs (millis) 5, // number to test on eviction run 30000, // min evictable idle time (millis) true // test while idle ); ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(connectURI, username, password); PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, connectionPool, null, null, false, true); PoolingDataSource dataSource = new PoolingDataSource(connectionPool); return dataSource; }
From source file:it.greenvulcano.gvesb.j2ee.db.connections.impl.DriverPoolConnectionBuilder.java
public void init(Node node) throws GVDBException { try {/*www .j a v a 2 s .c o m*/ name = XMLConfig.get(node, "@name"); user = XMLConfig.get(node, "@user", null); password = XMLConfig.getDecrypted(node, "@password", null); url = XMLConfig.get(node, "@url"); try { debugJDBCConn = Boolean.getBoolean( "it.greenvulcano.gvesb.j2ee.db.connections.impl.ConnectionBuilder.debugJDBCConn"); } catch (Exception exc) { debugJDBCConn = false; } Node poolNode = XMLConfig.getNode(node, "PoolParameters"); connectionPool = new GenericObjectPool(null); connectionPool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_BLOCK); connectionPool.setMaxWait(XMLConfig.getLong(poolNode, "@maxWait", 30) * 1000); connectionPool.setMinIdle(XMLConfig.getInteger(poolNode, "@minIdle", 5)); connectionPool.setMaxIdle(XMLConfig.getInteger(poolNode, "@maxIdle", 10)); connectionPool.setMaxActive(XMLConfig.getInteger(poolNode, "@maxActive", 15)); connectionPool.setTimeBetweenEvictionRunsMillis( XMLConfig.getLong(poolNode, "@timeBetweenEvictionRuns", 300) * 1000); connectionPool.setMinEvictableIdleTimeMillis( XMLConfig.getLong(poolNode, "@minEvictableIdleTime", 300) * 1000); connectionPool.setNumTestsPerEvictionRun(XMLConfig.getInteger(poolNode, "@numTestsPerEvictionRun", 3)); if (XMLConfig.exists(poolNode, "validationQuery")) { validationQuery = XMLConfig.get(poolNode, "validationQuery"); } } catch (Exception exc) { throw new GVDBException("DriverPoolConnectionBuilder - Initialization error", exc); } ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(url, user, password); new PoolableConnectionFactory(connectionFactory, connectionPool, null, validationQuery, false, true); dataSource = new PoolingDataSource(connectionPool); logger.debug("Crated DriverPoolConnectionBuilder(" + name + "). - user: " + user + " - password: ********* - url: " + url + " - Pool: [" + connectionPool.getMinIdle() + "/" + connectionPool.getMaxIdle() + "/" + connectionPool.getMaxActive() + "]"); }
From source file:jp.co.acroquest.endosnipe.data.db.PostgresDataSourceCreator.java
/** * {@inheritDoc}//from w w w .ja v a 2 s . c om */ public DataSource createPoolingDataSource(String dbname, boolean connectOnlyExists) throws SQLException { try { String driverClass = DBManager.getDriverClass(); Class.forName(driverClass); String uri = createDatabaseURI(DBManager.getHostName(), DBManager.getPort(), dbname); String userName = DBManager.getUserName(); String password = DBManager.getPassword(); ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(uri, userName, password); // ????????connectOnlyExists?false??? // ???????? if (!connectOnlyExists) { if (!(this.existsDatabase(dbname))) { // ??????? DBInitializer.createDatabase(dbname); } } // ????? StackObjectPool ?? // ???????? ConnectionManager manager = ConnectionManager.getInstance(); ObjectPool connectionPool = manager.getConnectionPool(uri); if (connectionPool == null) { connectionPool = manager.createNewConnectionPool(uri); } new PoolableConnectionFactory(connectionFactory, connectionPool, null, null, false, true); return new PoolingDataSource(connectionPool); } catch (Throwable ex) { LOGGER.log(EXCEPTION_OCCURED, ex, ex.getMessage()); throw new SQLException(ex.getMessage()); } }
From source file:de.othsoft.codeGen.requirements.jdbc.ConnectionFactory.java
private void initPool() throws DaoException { if (_connectionPool != null) { return;//w ww . j a v a2s. com } if (conStr == null) { throw new DaoException(log, "connection string is needed"); } if (userStr == null) { throw new DaoException(log, "user name is needed"); } if (pwdStr == null) { throw new DaoException(log, "password is needed"); } if (testStr == null) { throw new DaoException(log, "sql statement for connection test is needed"); } String driverClassName = null; if (conStr.contains("postgresql")) { driverClassName = "org.postgresql.Driver"; } else if (conStr.contains("oracle")) { driverClassName = "oracle.jdbc.driver.OracleDriver"; } else { throw new DaoException(log, "unknown driver for conStr=" + conStr); } try { Class.forName(driverClassName); } catch (ClassNotFoundException e) { throw new DaoException(log, e); } if (log.isInfoEnabled()) { log.info("init connection pool with: user=" + userStr + ", conStr=" + conStr); } org.apache.commons.dbcp.ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(conStr, userStr, pwdStr); _connectionPool = new GenericObjectPool(null); PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, _connectionPool, null, testStr, false, true); _dataSource = new PoolingDataSource(_connectionPool); }
From source file:com.zotoh.core.db.JDBCPoolManager.java
private synchronized JDBCPool create(String pool, JDBCInfo param, Properties props) throws SQLException { if (existsPool(pool)) { throw new SQLException("Jdbc Pool already exists: " + pool); }// w w w.j a va2 s . c om PoolableConnectionFactory pcf; DriverConnectionFactory dcf; GenericObjectPool gop; DBVendor dbv; ObjectPool p; Driver d; tlog().debug("JDBCPoolMgr: Driver : {}", param.getDriver()); tlog().debug("JDBCPoolMgr: URL : {}", param.getUrl()); // Ute.loadDriver(param.getDriver()); d = DriverManager.getDriver(param.getUrl()); dbv = DBUte.getDBVendor(param); dcf = new DriverConnectionFactory(d, param.getUrl(), props); gop = new GenericObjectPool(); gop.setMaxActive(asInt(props.getProperty("max-conns"), 10)); gop.setTestOnBorrow(true); gop.setMaxIdle(gop.getMaxActive()); gop.setMinIdle(asInt(props.getProperty("min-conns"), 2)); gop.setMaxWait(asLong(props.getProperty("max-wait4-conn-millis"), 1500L)); gop.setMinEvictableIdleTimeMillis(asLong(props.getProperty("evict-conn-ifidle-millis"), 300000L)); gop.setTimeBetweenEvictionRunsMillis(asLong(props.getProperty("check-evict-every-millis"), 60000L)); pcf = new PoolableConnectionFactory(dcf, gop, null, null, true, false); pcf.setDefaultReadOnly(false); p = pcf.getPool(); JDBCPool j = new JDBCPool(dbv, param, p); _ps.put(pool, j); tlog().debug("JDBCPoolMgr: Added db pool: {}, info= {}", pool, param); return j; }