List of usage examples for org.apache.commons.dbcp DriverConnectionFactory DriverConnectionFactory
public DriverConnectionFactory(Driver driver, String connectUri, Properties props)
From source file:ConnectionPoolBasics.java
public static void main(String args[]) throws Exception { GenericObjectPool gPool = new GenericObjectPool(); /*Class.forName("com.mysql.jdbc.Driver"); /*ww w . j a v a 2 s . c o 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:com.ibm.xsp.extlib.relational.jdbc.datasource.dbcp.DbcpPoolDataSource.java
/** * //from w ww . ja v a 2s.co m */ public DbcpPoolDataSource(final String dataSourceName, final String driverClass, final String url, final String username, final String password, final int minIdle, final int maxIdle, final int maxActive, final long maxWait) throws PoolException { try { ds = AccessController.doPrivileged(new PrivilegedExceptionAction<DataSource>() { public DataSource run() throws Exception { // create a driver connection factory driver = JDBCDriverLoader.loadDriver(driverClass); Properties properties = new Properties(); properties.setProperty("user", username); // $NON-NLS-1$ properties.setProperty("password", (StringUtil.isEmpty(password) ? "" : password)); // $NON-NLS-1$ ConnectionFactory connectionFactory = new DriverConnectionFactory(driver, url, properties); // create the pool pool = new GenericObjectPool(); pool.setMaxActive(maxActive); pool.setMaxWait(maxWait); pool.setMaxIdle(maxIdle); pool.setMinIdle(minIdle); // create the pool object factory PoolableConnectionFactory factory = new PoolableConnectionFactory(connectionFactory, pool, null, null, false, true); pool.setFactory(factory); // finally create the datasource PoolingDataSource bds = new PoolingDataSource(pool); return bds; } }); } catch (Exception e) { String msg = "Unable to initialize the shared connection pool DataSource"; // $NLX-DbcpPoolDataSource.Unabletoinitializethesharedconnec-1$[["connection pool" is a technical term related to databases]] // Note, this resource key is used elsewhere in this plugin // "Unable to initialize the shared connection pool DataSource" //String msg = com.ibm.xsp.extlib.relational.ResourceHandler.getSpecialAudienceString("DbcpPoolDataSource.Unabletoinitializethesharedconnec");//$NON-NLS-1$ throw new PoolException(e, msg); } }
From source file:eu.peppol.jdbc.OxalisDataSourceFactoryDbcpImpl.java
/** * Creates a DataSource with connection pooling as provided by Apache DBCP * * @return a DataSource/*from www .jav a 2s .c om*/ */ 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:edu.tamu.tcat.db.core.AbstractDataSourceFactory.java
/** * Create a new {@link BasicDataSource} from the specified {@link DSProperties} *//*from w ww . j a va 2 s . c o m*/ protected synchronized BasicDataSource createDataSource(final Properties parameters) throws DataSourceException { BasicDataSource dataSource; final Driver driver = getDriver(); final String connectionUrl = getConnectionUrl(parameters); final Properties connectionProps = getConnectionProperties(parameters); dataSource = new BasicDataSource() { @Override protected ConnectionFactory createConnectionFactory() throws SQLException { //The loading of the driver via class-loader does not work properly in OSGI. if (driver.acceptsURL(getUrl())) { if (getValidationQuery() == null) { setTestOnBorrow(false); setTestOnReturn(false); setTestWhileIdle(false); } ConnectionFactory driverConnectionFactory = new DriverConnectionFactory(driver, connectionUrl, connectionProps); return driverConnectionFactory; } return super.createConnectionFactory(); } }; // dataSource.setDriverClassLoader(Driver.class.getClassLoader()); // should be included in the connection properties and not needed // dataSource.setUsername(key.getUsername()); // dataSource.setPassword(key.getPassword()); dataSource.setDriverClassName(driver.getClass().getName()); dataSource.setUrl(connectionUrl); dataSource.setMaxActive(getMaxActiveConnections(parameters)); dataSource.setMaxIdle(getMaxIdleConnections(parameters)); dataSource.setMinIdle(0); dataSource.setMinEvictableIdleTimeMillis(10000); dataSource.setTimeBetweenEvictionRunsMillis(1000); dataSource.setLogAbandoned(true); dataSource.setRemoveAbandoned(true);//seconds dataSource.setRemoveAbandonedTimeout(60); return dataSource; }
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); }/*from w ww . j a v a 2 s .c o m*/ 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; }
From source file:eu.peppol.jdbc.OxalisDataSourceFactoryDbcpImplTest.java
private ConnectionFactory createConnectionFactory(boolean profileSql) throws MalformedURLException, ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException { String jdbcDriverClassPath = globalConfiguration.getJdbcDriverClassPath(); URL url = new URL(jdbcDriverClassPath); try {/* www. j a va 2s. c o m*/ File file = new File(url.toURI()); if (!file.exists()) { throw new IllegalStateException("JDBC driver class path not found: " + file); } } catch (URISyntaxException e) { throw new IllegalStateException( "Unable to convert URL " + url.toExternalForm() + " into URI: " + e.getMessage(), e); } URLClassLoader urlClassLoader = new URLClassLoader(new URL[] { url }, Thread.currentThread().getContextClassLoader()); String jdbcDriverClassName = globalConfiguration.getJdbcDriverClassName(); String connectURI = globalConfiguration.getJdbcConnectionURI(); // + "?initialTimeout=2"; String userName = globalConfiguration.getJdbcUsername(); String password = globalConfiguration.getJdbcPassword(); Class<?> aClass = null; try { aClass = Class.forName(jdbcDriverClassName, true, urlClassLoader); } catch (ClassNotFoundException e) { throw new IllegalStateException("Unable to locate class " + jdbcDriverClassName + " in class path '" + jdbcDriverClassPath + "'"); } Driver driver = (Driver) aClass.newInstance(); assertTrue(driver.acceptsURL(connectURI)); Properties properties = new Properties(); properties.put("user", userName); properties.put("password", password); if (profileSql) { properties.put("profileSQL", "true"); // MySQL debug option } return new DriverConnectionFactory(driver, connectURI, properties); }
From source file:ch.rgw.tools.JdbcLink.java
/** * Verbindung zur Datenbank herstellen/* ww w . j a v a 2 s .c om*/ * * TODO return value is always true because exception is thrown on error * * @param user * Username, kann null sein * @param password * Passwort, kann null sein * @return errcode * * @throws JdbcLinkException */ public boolean connect(String user, String password) { Exception cause = null; try { sUser = user; sPwd = password; Driver driver = (Driver) Class.forName(sDrv).newInstance(); verMajor = driver.getMajorVersion(); verMinor = driver.getMinorVersion(); log.log(Level.INFO, "Loading database driver " + sDrv); log.log(Level.INFO, "Connecting with database " + sConn); // // First, we'll create a ConnectionFactory that the // pool will use to create Connections. // Properties properties = new Properties(); properties.put("user", user); properties.put("password", password); ConnectionFactory connectionFactory = new DriverConnectionFactory(driver, sConn, properties); // // Next we'll create the PoolableConnectionFactory, which wraps // the "real" Connections created by the ConnectionFactory with // the classes that implement the pooling functionality. // connectionPool = new GenericObjectPool<Connection>(null); // configure the connection pool connectionPool.setMaxActive(32); connectionPool.setMinIdle(2); connectionPool.setMaxWait(10000); connectionPool.setTestOnBorrow(true); new PoolableConnectionFactory(connectionFactory, connectionPool, null, VALIDATION_QUERY, false, true); dataSource = new PoolingDataSource(connectionPool); // test establishing a connection Connection conn = dataSource.getConnection(); conn.close(); lastErrorCode = CONNECT_SUCCESS; lastErrorString = "Connect successful"; log.log("Connect successful", Log.DEBUGMSG); return true; } catch (ClassNotFoundException ex) { lastErrorCode = CONNECT_CLASSNOTFOUND; lastErrorString = "Class not found exception: " + ex.getMessage(); cause = ex; } catch (InstantiationException e) { lastErrorCode = CONNECT_UNKNOWN_ERROR; lastErrorString = "Instantiation exception: " + e.getMessage(); cause = e; } catch (IllegalAccessException e) { lastErrorCode = CONNECT_UNKNOWN_ERROR; lastErrorString = "Illegal access exception: " + e.getMessage(); cause = e; } catch (SQLException e) { lastErrorCode = CONNECT_UNKNOWN_ERROR; lastErrorString = "SQL exception: " + e.getMessage(); cause = e; } catch (IllegalStateException e) { lastErrorCode = CONNECT_UNKNOWN_ERROR; lastErrorString = "Illegal state exception: " + e.getMessage(); cause = e; } throw JdbcLinkExceptionTranslation.translateException("Connect failed: " + lastErrorString, cause); }
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();/* ww w . j a v a2s . c o 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.agnitas.dao.LoggingEnhBasicDataSource.java
/** * <p>Create (if necessary) and return the internal data source we are * using to manage our connections.</p> *// w ww. j a v a 2s . co m * <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.callimachusproject.sql.DriverConnectionPoolManager.java
public synchronized void registerDriver(String name, Driver driver, String url, Properties info, GenericObjectPool.Config config, String validationQuery) throws SQLException { ConnectionFactory factory;//from www . j a v a2s . co m PoolableDriverConnectionFactory poolable; ObjectPool<PoolableDriverConnection> pool; if (pools.containsKey(name)) { deregisterDriver(name); } factory = new DriverConnectionFactory(driver, url, info); poolable = new PoolableDriverConnectionFactory(factory, validationQuery); pool = new GenericObjectPool<PoolableDriverConnection>(poolable, config); poolable.setPool(pool); pools.put(name, pool); }