List of usage examples for org.apache.commons.pool.impl GenericObjectPool GenericObjectPool
public GenericObjectPool(PoolableObjectFactory factory)
From source file:eu.peppol.jdbc.OxalisDataSourceFactoryDbcpImplTest.java
/** * Verifies that we can create a pooled jdbc data source using the JDBC .jar-file supplied in the global configuration * file./*from www . ja va 2 s . c o m*/ * * @throws Exception */ @Test public void testLoadJdbcDriverUsingCustomClassLoader() throws Exception { ConnectionFactory driverConnectionFactory = createConnectionFactory(false); GenericObjectPool genericObjectPool = new GenericObjectPool(null); PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(driverConnectionFactory, genericObjectPool, null, "select 1", false, true); PoolingDataSource poolingDataSource = new PoolingDataSource(genericObjectPool); Connection connection = poolingDataSource.getConnection(); assertNotNull(connection); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery("select current_date()"); assertTrue(resultSet.next()); }
From source file:edu.jhu.pha.vospace.DbPoolServlet.java
@Override public void init() throws ServletException { ServletContext context = this.getServletContext(); Configuration conf = (Configuration) context.getAttribute("configuration"); try {/*from www . ja v a 2 s .co m*/ Class.forName(conf.getString("db.driver")); } catch (ClassNotFoundException e) { logger.error(e); throw new ServletException(e); } GenericObjectPool pool = new GenericObjectPool(null); pool.setMinEvictableIdleTimeMillis(6 * 60 * 60 * 1000); pool.setTimeBetweenEvictionRunsMillis(30 * 60 * 1000); pool.setNumTestsPerEvictionRun(-1); DriverManagerConnectionFactory cf = new DriverManagerConnectionFactory(conf.getString("db.url"), conf.getString("db.login"), conf.getString("db.password")); PoolableConnectionFactory pcf = new PoolableConnectionFactory(cf, pool, null, "SELECT * FROM mysql.db", false, true); new PoolingDriver().registerPool("dbPool", pool); }
From source file:com.laudandjolynn.paper2swf.OpenOfficeConverter.java
/** * //from w w w . ja va 2 s .c o m * @param host * openoffice?? * @param port * openoffice?? */ public OpenOfficeConverter(String host, int port) { SocketOpenOfficeConnectionFactory factory = new SocketOpenOfficeConnectionFactory(host, port); this.gop = new GenericObjectPool<SocketOpenOfficeConnection>(factory); }
From source file:lineage2.commons.dbcp.BasicDataSource.java
/** * Constructor for BasicDataSource./*from ww w. j ava 2s. co 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:iudex.da.DataSourceFactory.java
public DataSource create(Map<String, String> params) { String className = params.remove("dsf.driver.class"); if (className != null) { try {/*from ww w . j a va2 s.c om*/ Class<?> driverClass = Class.forName(className); assert (driverClass != null); } catch (ClassNotFoundException x) { throw new RuntimeException(x); } } setLogWriter(); String uri = params.remove("dsf.uri"); Properties props = new Properties(); for (Map.Entry<String, String> e : params.entrySet()) { props.setProperty(e.getKey(), e.getValue()); } DriverManagerConnectionFactory conFactory = new DriverManagerConnectionFactory(uri, props); ObjectPool conPool = new GenericObjectPool(null); //min, max, etc. connections // Sets self on conPool new PoolableConnectionFactory(conFactory, conPool, null, //stmtPoolFactory null, false, true); return new PoolingDataSource(conPool); }
From source file:ambit2.database.DatasourceFactory.java
public static DataSource setupDataSource(String connectURI) throws AmbitException { try {/* w ww. j av a 2 s. c o m*/ Class.forName("com.mysql.jdbc.Driver"); // // 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. // ObjectPool connectionPool = new GenericObjectPool(null); // // 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. // ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(connectURI, null); // // 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, null, false, true); // // Finally, we create the PoolingDriver itself, // passing in the object pool we created. // PoolingDataSource dataSource = new PoolingDataSource(connectionPool); return dataSource; } catch (Exception x) { throw new AmbitException(x); } }
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)/*w w w . ja v a 2s. c om*/ 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:au.org.paperminer.common.AbstractServlet.java
private boolean testConnectionPool() { boolean res = false; String dbDriver = getInitParameter("jdbc.driver.class"); String dbUrl = getInitParameter("db.url"); String dbUser = getInitParameter("db.user"); String dbPass = getInitParameter("db.passwd"); try {/* w ww. j a v a 2 s . c o m*/ m_logger.debug("DB init class=" + dbDriver + ", url=" + dbUrl + ", user=" + dbUser + " pwd=" + dbPass.substring(0, 3) + "..."); Class.forName(dbDriver); GenericObjectPool connectionPool = new GenericObjectPool(null); ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(dbUrl, dbUser, dbPass); PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, connectionPool, null, null, false, true); m_poolDriver = new PoolingDriver(); m_poolDriver.registerPool(POOL_NAME, connectionPool); //Connection conn = DriverManager.getConnection("jdbc:apache:commons:dbcp:/poolconf"); TableMaker.checkCreateTables(false); res = true; m_logger.info("Connection pool started ok"); } catch (ClassNotFoundException ex) { m_logger.error("DB Driver registration failed for " + dbDriver, ex); } catch (PaperMinerException ex) { m_logger.error("Connection pool check failed", ex); } return res; }
From source file:it.greenvulcano.gvesb.j2ee.db.connections.impl.DriverPoolConnectionBuilder.java
public void init(Node node) throws GVDBException { try {/* w w w.j a va 2s. 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:eu.peppol.jdbc.OxalisDataSourceFactoryDbcpImplTest.java
@Test public void testFailWithStaleConnection() throws Exception { ConnectionFactory driverConnectionFactory = createConnectionFactory(false); GenericObjectPool genericObjectPool = new GenericObjectPool(null); genericObjectPool.setMaxActive(1);/*www. j a v a 2 s . co m*/ PoolingDataSource poolingDataSource = createPoolingDataSource(driverConnectionFactory, genericObjectPool); try { runTwoSqlStatementsWithTwoConnections(poolingDataSource); } catch (Exception e) { assertTrue(e.getClass().getName().contains("CommunicationsException")); } }