List of usage examples for org.apache.commons.dbcp PoolingDriver PoolingDriver
public PoolingDriver()
From source file:DBCPDemo.java
public static void main(String args[]) throws Exception { // create a generic pool GenericObjectPool pool = new GenericObjectPool(null); // use the connection factory which will wraped by // the PoolableConnectionFactory DriverManagerConnectionFactory cf = new DriverManagerConnectionFactory( "jdbc:jtds:sqlserver://myserver:1433/tandem", "user", "pass"); PoolableConnectionFactory pcf = new PoolableConnectionFactory(cf, pool, null, "SELECT * FROM mysql.db", false, true);// ww w . j av a2 s .c o m // register our pool and give it a name new PoolingDriver().registerPool("myPool", pool); // get a connection and test it Connection conn = DriverManager.getConnection("jdbc:apache:commons:dbcp:myPool"); // now we can use this pool the way we want. System.err.println("Are we connected? " + !conn.isClosed()); System.err.println("Idle Connections: " + pool.getNumIdle() + ", out of " + pool.getNumActive()); }
From source file:ConnectionPoolBasics.java
public static void main(String args[]) throws Exception { GenericObjectPool gPool = new GenericObjectPool(); /*Class.forName("com.mysql.jdbc.Driver"); /*from www . ja v 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:edu.jhu.pha.vospace.DbPoolServlet.java
@Override public void init() throws ServletException { ServletContext context = this.getServletContext(); Configuration conf = (Configuration) context.getAttribute("configuration"); try {/*from ww w. j av a2 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: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 {//from www . java2 s .com 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: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 va 2s .co m } // 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.aitools.programd.Core.java
/** * Returns a database connection backed by a pooling driver. * This is initialized lazily, since some people may not be * using any database-based features.//from w w w .j a v a2 s . co m * * @return a dbmanager */ public Connection getDBConnection() { if (this._connectionPool == null) { try { Class.forName(this._settings.getDatabaseDriver()); } catch (ClassNotFoundException e) { throw new UserError("Could not find your database driver.", e); } this._connectionPool = new GenericObjectPool(); ConnectionFactory connectionFactory = new DriverManagerConnectionFactory( this._settings.getDatabaseURL(), this._settings.getDatabaseUsername(), this._settings.getDatabasePassword()); new PoolableConnectionFactory(connectionFactory, this._connectionPool, null, null, false, true); PoolingDriver driver = new PoolingDriver(); driver.registerPool("programd", this._connectionPool); } try { return DriverManager.getConnection("jdbc:apache:commons:dbcp:programd"); } catch (SQLException e) { this._logger.error("SQL exception when getting a db connection.", e); return null; } }
From source file:org.apache.slide.store.impl.rdbms.JDBCStore.java
/** * Initializes driver.//from w w w . j a va 2 s . c om * <p/> * Occurs in four steps : * <li>Driver class is loaded</li> * <li>Driver is instantiated</li> * <li>Driver registration in the driver manager</li> * <li>Creation of the basic tables, if they didn't exist before</li> * * @exception ServiceInitializationFailedException Throws an exception * if the data source has already been initialized before */ public synchronized void initialize(NamespaceAccessToken token) throws ServiceInitializationFailedException { // XXX might be done already in setParameter if (!alreadyInitialized) { try { // Loading and registering driver getLogger().log("Loading and registering driver '" + driver + "'", LOG_CHANNEL, Logger.INFO); Class driverClass = Class.forName(driver); Driver driverInstance = (Driver) driverClass.newInstance(); String levelString = isolationLevelToString(isolationLevel); getLogger().log("Setting isolation level '" + levelString + "'", LOG_CHANNEL, Logger.INFO); // use DBCP pooling if enabled if (useDbcpPooling) { getLogger().log("Using DBCP pooling", LOG_CHANNEL, Logger.INFO); GenericObjectPool connectionPool = new GenericObjectPool(null); if (maxPooledConnections != -1) { connectionPool.setMaxActive(maxPooledConnections); } getLogger().log("Number of connections set to " + connectionPool.getMaxActive(), LOG_CHANNEL, Logger.INFO); DriverManagerConnectionFactory connectionFactory = new DriverManagerConnectionFactory(url, user, password); new PoolableConnectionFactory(connectionFactory, connectionPool, // TODO switching on pooling of prepared statements causes problems with closing of connections // switched off for now // new StackKeyedObjectPoolFactory(), null, null, false, false, isolationLevel); PoolingDriver driver = new PoolingDriver(); driver.registerPool(dbcpPoolName, connectionPool); // already done when loding PoolingDriver class // DriverManager.registerDriver(driver); } else { DriverManager.registerDriver(driverInstance); getLogger().log("Not using DBCP pooling", LOG_CHANNEL, Logger.WARNING); } } catch (Exception e) { getLogger().log("Loading and registering driver '" + driver + "' failed (" + e.getMessage() + ")", LOG_CHANNEL, Logger.ERROR); throw new ServiceInitializationFailedException(this, e); } finally { alreadyInitialized = true; } } }
From source file:org.methodize.nntprss.feed.db.JdbcChannelDAO.java
private void initializeDatabasePool(Document config) throws Exception { Element rootElm = config.getDocumentElement(); Element dbConfig = (Element) rootElm.getElementsByTagName("db").item(0); String connectString = dbConfig.getAttribute("connect"); if (log.isInfoEnabled()) { log.info("Initializing JDBC, connection string = " + connectString); }/*w w w .ja va 2 s . c o m*/ ObjectPool connectionPool = new GenericObjectPool(null); String dbDriver = dbConfig.getAttribute("driverClass"); if (dbDriver != null && dbDriver.length() > 0) { Class.forName(dbDriver); } else { // Default to HSSQLDB Class.forName("org.hsqldb.jdbcDriver"); } String user = dbConfig.getAttribute("user"); String password = dbConfig.getAttribute("password"); if (user == null) { user = "sa"; } if (password == null) { password = ""; } ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(connectString, user, password); // // 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... // PoolingDriver driver = new PoolingDriver(); // // ...and register our pool with it. // driver.registerPool("nntprss", connectionPool); }
From source file:org.opencms.db.CmsDbPool.java
/** * Creates a JDBC DriverManager based DBCP connection pool.<p> * /*ww w . j av a2s . c o m*/ * @param config the configuration (opencms.properties) * @param key the key of the database pool in the configuration * @return String the URL to access the created DBCP pool * @throws Exception if the pool could not be initialized */ public static PoolingDriver createDriverManagerConnectionPool(CmsParameterConfiguration config, String key) throws Exception { // read the values of the pool configuration specified by the given key String jdbcDriver = config.get(KEY_DATABASE_POOL + '.' + key + '.' + KEY_JDBC_DRIVER); String jdbcUrl = config.get(KEY_DATABASE_POOL + '.' + key + '.' + KEY_JDBC_URL); String jdbcUrlParams = config.get(KEY_DATABASE_POOL + '.' + key + '.' + KEY_JDBC_URL_PARAMS); int maxActive = config.getInteger(KEY_DATABASE_POOL + '.' + key + '.' + KEY_MAX_ACTIVE, 10); int maxWait = config.getInteger(KEY_DATABASE_POOL + '.' + key + '.' + KEY_MAX_WAIT, 2000); int maxIdle = config.getInteger(KEY_DATABASE_POOL + '.' + key + '.' + KEY_MAX_IDLE, 5); int minEvictableIdleTime = config .getInteger(KEY_DATABASE_POOL + '.' + key + '.' + KEY_MIN_EVICTABLE_IDLE_TIME, 1800000); int minIdle = config.getInteger(KEY_DATABASE_POOL + '.' + key + '.' + KEY_MIN_IDLE, 0); int numTestsPerEvictionRun = config .getInteger(KEY_DATABASE_POOL + '.' + key + '.' + KEY_NUM_TESTS_PER_EVICTION_RUN, 3); int timeBetweenEvictionRuns = config .getInteger(KEY_DATABASE_POOL + '.' + key + '.' + KEY_TIME_BETWEEN_EVICTION_RUNS, 3600000); String testQuery = config.get(KEY_DATABASE_POOL + '.' + key + '.' + KEY_TEST_QUERY); String username = config.get(KEY_DATABASE_POOL + '.' + key + '.' + KEY_USERNAME); String password = config.get(KEY_DATABASE_POOL + '.' + key + '.' + KEY_PASSWORD); String poolUrl = config.get(KEY_DATABASE_POOL + '.' + key + '.' + KEY_POOL_URL); String whenExhaustedActionValue = config .get(KEY_DATABASE_POOL + '.' + key + '.' + KEY_WHEN_EXHAUSTED_ACTION).trim(); byte whenExhaustedAction = 0; boolean testOnBorrow = Boolean .valueOf(config.getString(KEY_DATABASE_POOL + '.' + key + '.' + KEY_TEST_ON_BORROW, "false").trim()) .booleanValue(); boolean testWhileIdle = Boolean .valueOf( config.getString(KEY_DATABASE_POOL + '.' + key + '.' + KEY_TEST_WHILE_IDLE, "false").trim()) .booleanValue(); if ("block".equalsIgnoreCase(whenExhaustedActionValue)) { whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_BLOCK; } else if ("fail".equalsIgnoreCase(whenExhaustedActionValue)) { whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_FAIL; } else if ("grow".equalsIgnoreCase(whenExhaustedActionValue)) { whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_GROW; } else { whenExhaustedAction = GenericObjectPool.DEFAULT_WHEN_EXHAUSTED_ACTION; } if ("".equals(testQuery)) { testQuery = null; } if (username == null) { username = ""; } if (password == null) { password = ""; } // read the values of the statement pool configuration specified by the given key boolean poolingStmts = Boolean.valueOf(config .getString(KEY_DATABASE_STATEMENTS + '.' + key + '.' + KEY_POOLING, CmsStringUtil.TRUE).trim()) .booleanValue(); int maxActiveStmts = config.getInteger(KEY_DATABASE_STATEMENTS + '.' + key + '.' + KEY_MAX_ACTIVE, 25); int maxWaitStmts = config.getInteger(KEY_DATABASE_STATEMENTS + '.' + key + '.' + KEY_MAX_WAIT, 250); int maxIdleStmts = config.getInteger(KEY_DATABASE_STATEMENTS + '.' + key + '.' + KEY_MAX_IDLE, 15); String whenStmtsExhaustedActionValue = config .get(KEY_DATABASE_STATEMENTS + '.' + key + '.' + KEY_WHEN_EXHAUSTED_ACTION); byte whenStmtsExhaustedAction = GenericKeyedObjectPool.WHEN_EXHAUSTED_GROW; if (whenStmtsExhaustedActionValue != null) { whenStmtsExhaustedActionValue = whenStmtsExhaustedActionValue.trim(); whenStmtsExhaustedAction = ("block".equalsIgnoreCase(whenStmtsExhaustedActionValue)) ? GenericKeyedObjectPool.WHEN_EXHAUSTED_BLOCK : ("fail".equalsIgnoreCase(whenStmtsExhaustedActionValue)) ? GenericKeyedObjectPool.WHEN_EXHAUSTED_FAIL : GenericKeyedObjectPool.WHEN_EXHAUSTED_GROW; } int connectionAttempts = config.getInteger(KEY_DATABASE_POOL + '.' + key + '.' + KEY_CONNECT_ATTEMTS, 10); int connetionsWait = config.getInteger(KEY_DATABASE_POOL + '.' + key + '.' + KEY_CONNECT_WAITS, 5000); // create an instance of the JDBC driver Class.forName(jdbcDriver).newInstance(); // initialize a keyed object pool to store connections GenericObjectPool connectionPool = new GenericObjectPool(null); /* Abandoned pool configuration: * * In case the systems encounters "pool exhaustion" (runs out of connections), * comment the above line with "new GenericObjectPool(null)" and uncomment the * 5 lines below. This will generate an "abandoned pool" configuration that logs * abandoned connections to the System.out. Unfortunatly this code is deprecated, * so to avoid code warnings it's also disabled here. * Tested with commons-pool v 1.2. */ // AbandonedConfig abandonedConfig = new AbandonedConfig(); // abandonedConfig.setLogAbandoned(true); // abandonedConfig.setRemoveAbandoned(true); // abandonedConfig.setRemoveAbandonedTimeout(5); // GenericObjectPool connectionPool = new AbandonedObjectPool(null, abandonedConfig); // initialize an object pool to store connections connectionPool.setMaxActive(maxActive); connectionPool.setMaxIdle(maxIdle); connectionPool.setMinIdle(minIdle); connectionPool.setMaxWait(maxWait); connectionPool.setWhenExhaustedAction(whenExhaustedAction); if (testQuery != null) { connectionPool.setTestOnBorrow(testOnBorrow); connectionPool.setTestWhileIdle(testWhileIdle); connectionPool.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRuns); connectionPool.setNumTestsPerEvictionRun(numTestsPerEvictionRun); connectionPool.setMinEvictableIdleTimeMillis(minEvictableIdleTime); } // initialize a connection factory to make the DriverManager taking connections from the pool if (jdbcUrlParams != null) { jdbcUrl += jdbcUrlParams; } ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(jdbcUrl, username, password); // Set up statement pool, if desired GenericKeyedObjectPoolFactory statementFactory = null; if (poolingStmts) { statementFactory = new GenericKeyedObjectPoolFactory(null, maxActiveStmts, whenStmtsExhaustedAction, maxWaitStmts, maxIdleStmts); } // initialize a factory to obtain pooled connections and prepared statements new PoolableConnectionFactory(connectionFactory, connectionPool, statementFactory, testQuery, false, true); // initialize a new pooling driver using the pool PoolingDriver driver = new PoolingDriver(); driver.registerPool(poolUrl, connectionPool); Connection con = null; boolean connect = false; int connectionTests = 0; // try to connect once to the database to ensure it can be connected to at all // if the conection cannot be established, multiple attempts will be done to connect // just in cast the database was not fast enough to start before OpenCms was started do { try { // try to connect con = connectionFactory.createConnection(); connect = true; } catch (Exception e) { // connection failed, increase attempts, sleept for some seconds and log a message connectionTests++; if (CmsLog.INIT.isInfoEnabled()) { CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_WAIT_FOR_DB_4, new Object[] { poolUrl, jdbcUrl, new Integer(connectionTests), new Integer(connetionsWait) })); } Thread.sleep(connetionsWait); } finally { if (con != null) { con.close(); } } } while (!connect && (connectionTests < connectionAttempts)); if (CmsLog.INIT.isInfoEnabled()) { CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_JDBC_POOL_2, poolUrl, jdbcUrl)); } return driver; }
From source file:org.pentaho.agilebi.platform.InstaviewDatasourceService.java
public DataSource getDataSource(String dsName) throws DBDatasourceServiceException { DatabaseMeta databaseMeta = databaseMetaMap.get(dsName); if (knownPools.contains(dsName)) { try {//from w w w .ja v a 2 s.com DatabaseMetaDataSource dataSource = new DatabaseMetaDataSource(dsName); return dataSource; } catch (Exception e) { throw new DBDatasourceServiceException(e); } } // nothing in the pool so create a new pool Domain domain = null; try { XmiParser parser = new XmiParser(); FileInputStream fis = new FileInputStream(new File(dsName)); domain = parser.parseXmi(fis); } catch (Exception e) { throw new DBDatasourceServiceException(e); } if (domain.getPhysicalModels().size() == 0 || !(domain.getPhysicalModels().get(0) instanceof SqlPhysicalModel)) { throw new DBDatasourceServiceException("No SQL Physical Model Available"); } SqlPhysicalModel model = (SqlPhysicalModel) domain.getPhysicalModels().get(0); databaseMeta = ThinModelConverter.convertToLegacy(model.getId(), model.getDatasource()); ConnectionFactory cf = new DatabaseMetaConnectionFactory(databaseMeta); GenericObjectPool.Config config = new GenericObjectPool.Config(); config.testOnBorrow = true; gPool.setConfig(config); PoolableConnectionFactory pcf = new PoolableConnectionFactory(cf, gPool, kopf, "select 1", false, true); try { // for(int i = 0; i < 5; i++) { // gPool.addObject(); // } // PoolingDataSource pds = new PoolingDataSource(gPool); PoolingDriver pd = new PoolingDriver(); pd.registerPool(dsName, gPool); for (int i = 0; i < 5; i++) { gPool.addObject(); } } catch (Exception e) { throw new DBDatasourceServiceException(e); } Database database = new Database(databaseMeta); try { database.connect(); } catch (Exception e) { throw new DBDatasourceServiceException(e); } Connection connection = database.getConnection(); knownPools.add(dsName); databaseMetaMap.put(dsName, databaseMeta); return new DatabaseMetaDataSource(dsName); }