List of usage examples for org.apache.commons.pool.impl GenericObjectPool GenericObjectPool
public GenericObjectPool()
From source file:org.okinawaopenlabs.orientdb.client.ConnectionManagerJdbc.java
/** * @param config//from w w w. ja va 2 s . c om * @throws SQLException */ private void initializeDataSource(Config config) { String user = config.getString(CONFIG_KEY_DB_USER); String password = config.getString(CONFIG_KEY_DB_PASSWORD); Properties params = new Properties(); if (isNotEmpty(user) && isNotEmpty(password)) { params.put("user", user); params.put("password", password); } // ?? String driver = config.getString(CONFIG_KEY_DB_DRIVER); boolean loadSuccess = DbUtils.loadDriver(driver); if (!loadSuccess) { String message = "failed to load driver."; throw new RuntimeException(message); } // ??DataSource ?? @SuppressWarnings("rawtypes") GenericObjectPool pool = new GenericObjectPool(); // ??? int maxActive = config.getInt(CONFIG_KEY_DB_MAX_ACTIVE_CONN, 100); long maxWait = Long.parseLong(config.getString(CONFIG_KEY_DB_WAIT, "-1")); pool.setMaxActive(maxActive); pool.setMaxIdle(maxActive); pool.setMaxWait(maxWait); driverUrl = config.getString(CONFIG_KEY_DB_URL); ConnectionFactory connFactory = new DriverManagerConnectionFactory(driverUrl, params); new PoolableConnectionFactory(connFactory, pool, null, null, // validationQuery false, // defaultReadOnly false); // defaultAutoCommit dataSource = new PoolingDataSource(pool); }
From source file:org.onecmdb.core.utils.transform.jdbc.ClassLoaderBasicDataSource.java
/** * <p>Create (if necessary) and return the internal data source we are * using to manage our connections.</p> * * <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>//from w w w . j a va2s. c o m * * @throws 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); } // Load the JDBC driver class Driver driver = null; if (driverClassName != null) { try { Class driverClass = Class.forName(driverClassName, true, driverLoader); driver = (Driver) driverClass.newInstance(); //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 if (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 if ((abandonedConfig != null) && (abandonedConfig.getRemoveAbandoned())) { connectionPool = new AbandonedObjectPool(null, abandonedConfig); } else { connectionPool = new GenericObjectPool(); } 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 { log("DBCP DataSource configured without a 'username'"); } if (password != null) { connectionProperties.put("password", password); } else { log("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, abandonedConfig); 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.openanzo.datasource.nodecentric.internal.NodeCentricDatasource.java
/** * Initialize a jdbc connection pool//from w ww .j a v a 2s. c o m * * @param type * either rw or query pool * @param maxActive * maximum number of connections in pool * @param configuration * configuration properties used for creating database connections * @return connection pool * @throws AnzoException * {@link ExceptionConstants#RDB.DRIVER_NAME} if there was a problem loading class for database driver */ private GenericObjectPool initializeConnectionFactory(boolean write, int maxActive) throws AnzoException { // Will use in jndi // DataSource ds = (DataSource) ctx.lookup(RepositoryProperties.getDatabaseJndiName(properties)); try { Class.forName(configuration.getDriverClassName()); } catch (ClassNotFoundException e1) { throw new AnzoException(ExceptionConstants.RDB.DRIVER_NAME, e1, configuration.getDriverClassName()); } Properties props = new Properties(); props.put("user", configuration.getUser()); props.put("password", configuration.getPassword()); props.put("SetBigStringTryClob", "true"); ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(configuration.getJdbcUrl(), props); GenericObjectPool connectionPool = new GenericObjectPool(); connectionPool.setMaxActive(maxActive); connectionPool.setMaxIdle(Math.max(1, maxActive / 2)); connectionPool.setMinIdle(0); connectionPool.setMinEvictableIdleTimeMillis(1000 * 60 * 10); connectionPool.setTimeBetweenEvictionRunsMillis(1000 * 60 * 10); connectionPool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_BLOCK); connectionPool.setMaxWait(GenericKeyedObjectPool.DEFAULT_MAX_WAIT); connectionPool.setTestOnBorrow(true); GenericKeyedObjectPoolFactory statementPool = new GenericKeyedObjectPoolFactory(null, PS_CACHE_SIZE, GenericKeyedObjectPool.WHEN_EXHAUSTED_BLOCK, GenericKeyedObjectPool.DEFAULT_MAX_WAIT, PS_CACHE_SIZE, PS_CACHE_SIZE, GenericKeyedObjectPool.DEFAULT_TEST_ON_BORROW, GenericKeyedObjectPool.DEFAULT_TEST_ON_RETURN, GenericKeyedObjectPool.DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS, GenericKeyedObjectPool.DEFAULT_NUM_TESTS_PER_EVICTION_RUN, GenericKeyedObjectPool.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS, GenericKeyedObjectPool.DEFAULT_TEST_WHILE_IDLE); PoolableConnectionFactory pcf = new PoolableConnectionFactory(connectionFactory, connectionPool, statementPool, configuration.getValidationQuery(), false, true) { @Override public synchronized Object makeObject() throws Exception { Connection connection = (Connection) super.makeObject(); initializeConnection(connection); return connection; } }; if (configuration.getSupportsIsolation() && write) pcf.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED); else if (configuration.getSupportsIsolation() && !write) pcf.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED); return connectionPool; }
From source file:org.openanzo.jdbc.container.RDBQuadStoreFactory.java
private PoolableConnectionFactory initializeConnectionFactory(boolean write, int maxActive, CoreDBConfiguration configuration) { // Will use in jndi // DataSource ds = (DataSource) ctx.lookup(RepositoryProperties.getDatabaseJndiName(properties)); try {//from w ww. j a v a 2s . c om Class.forName(configuration.getDriverClassName()); } catch (ClassNotFoundException e1) { throw new AnzoRuntimeException(ExceptionConstants.RDB.DRIVER_NAME, e1, configuration.getDriverClassName()); } ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(configuration.getJdbcUrl(), configuration.getUser(), configuration.getPassword()); connectionPool = new GenericObjectPool(); connectionPool.setMaxActive(maxActive); connectionPool.setMinIdle(1); connectionPool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_BLOCK); connectionPool.setMaxWait(30000); connectionPool.setMaxActive(maxActive); pcf = new PoolableConnectionFactory(connectionFactory, connectionPool, null, null, false, true); if ((!write && configuration.getSupportsIsolation())) pcf.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED); return pcf; }
From source file:org.openanzo.jdbc.container.RDBQuadStorePool.java
private void setupPools() { readPool = new GenericObjectPool(); factoryRead = new RDBQuadStoreFactory(this, literalIndexer, false, MAX_READ_CONNECTIONS, configuration); setupPool(readPool, factoryRead, MAX_READ_CONNECTIONS, MAX_READ_CONNECTIONS / 2, 60000); rwPool = new GenericObjectPool(); factoryRw = new RDBQuadStoreFactory(this, literalIndexer, true, MAX_WRITE_CONNECTIONS, configuration); setupPool(rwPool, factoryRw, MAX_WRITE_CONNECTIONS, (MAX_WRITE_CONNECTIONS > 1) ? MAX_WRITE_CONNECTIONS / 2 : 1, 60000); }
From source file:org.openpythia.dbconnection.ConnectionPoolUtils.java
/** * Configures an Apache DBCP pool called POOL_NAME. For the given connectionUrl * and connectionProperties.//from w w w.j a v a 2s .c o m * * @param connectionUrl the connection url * @param connectionProperties the connectionProperties */ public static void configurePool(String connectionUrl, Properties connectionProperties) throws SQLException { try { ConnectionFactory connectionFactory = new DriverConnectionFactory(JDBCHandler.getOracleJDBCDriver(), connectionUrl, connectionProperties); userName = connectionProperties.getProperty("user"); GenericObjectPool connectionPool = new GenericObjectPool(); connectionPool.setFactory( new PoolableConnectionFactory(connectionFactory, connectionPool, null, null, false, true)); Class.forName(POOLING_DRIVER); PoolingDriver driver = (PoolingDriver) DriverManager.getDriver(POOL_DRIVER_URL); driver.registerPool(POOL_NAME, connectionPool); Connection connection = DriverManager.getConnection(POOL_DRIVER_URL + POOL_NAME); connection.close(); hasBeenSuccessfullyConfigured = true; } catch (ClassNotFoundException e) { throw new RuntimeException(e); } }
From source file:org.openspaces.jdbc.datasource.DbcpBasicDataSource.java
/** * <p>Create (if necessary) and return the internal data source we are * using to manage our connections.</p> * * <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>//w w w . j av a 2 s . c o m * * @throws SQLException if the object pool cannot be created. */ protected void createDataSource() throws SQLException { // Can't test without a validationQuery if (validationQuery == null) { setTestOnBorrow(false); setTestOnReturn(false); setTestWhileIdle(false); } // Create an object pool to contain our active connections if ((abandonedConfig != null) && (abandonedConfig.getRemoveAbandoned() == true)) { connectionPool = new AbandonedObjectPool(null, abandonedConfig); } else { connectionPool = new GenericObjectPool(); } 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); } DataSourceConnectionFactory dataSourceConnectionFactory = new DataSourceConnectionFactory( new SpaceDriverManagerDataSource(space)); // Set up the poolable connection factory we will use try { PoolableConnectionFactory connectionFactory = new PoolableConnectionFactory(dataSourceConnectionFactory, connectionPool, statementPoolFactory, validationQuery, defaultReadOnly, defaultAutoCommit, defaultTransactionIsolation, defaultCatalog, abandonedConfig); 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); } }
From source file:org.pentaho.di.core.database.ConnectionPoolUtil.java
private static void createPool(LogChannelInterface log, DatabaseMeta databaseMeta, String partitionId, int initialSize, int maximumSize) throws KettleDatabaseException { log.logBasic(BaseMessages.getString(PKG, "Database.CreatingConnectionPool", databaseMeta.getName())); GenericObjectPool gpool = new GenericObjectPool(); gpool.setMaxIdle(-1);/*w w w . j a v a 2s .c o m*/ gpool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_GROW); gpool.setMaxActive(maximumSize); String clazz = databaseMeta.getDriverClass(); try { Class.forName(clazz).newInstance(); } catch (Exception e) { throw new KettleDatabaseException(BaseMessages.getString(PKG, "Database.UnableToLoadConnectionPoolDriver.Exception", databaseMeta.getName(), clazz), e); } String url; String userName; String password; try { url = databaseMeta.environmentSubstitute(databaseMeta.getURL(partitionId)); userName = databaseMeta.environmentSubstitute(databaseMeta.getUsername()); password = databaseMeta.environmentSubstitute(databaseMeta.getPassword()); } catch (RuntimeException e) { url = databaseMeta.getURL(partitionId); userName = databaseMeta.getUsername(); password = databaseMeta.getPassword(); } password = Encr.decryptPasswordOptionallyEncrypted(password); // Get the list of pool properties Properties originalProperties = databaseMeta.getConnectionPoolingProperties(); // Add user/pass originalProperties.setProperty("user", Const.NVL(userName, "")); originalProperties.setProperty("password", Const.NVL(password, "")); // Now, replace the environment variables in there... Properties properties = new Properties(); Iterator<Object> iterator = originalProperties.keySet().iterator(); while (iterator.hasNext()) { String key = (String) iterator.next(); String value = originalProperties.getProperty(key); properties.put(key, databaseMeta.environmentSubstitute(value)); } // Create factory using these properties. // ConnectionFactory cf = new DriverManagerConnectionFactory(url, properties); new PoolableConnectionFactory(cf, gpool, null, null, false, false); for (int i = 0; i < initialSize; i++) { try { gpool.addObject(); } catch (Exception e) { throw new KettleDatabaseException( BaseMessages.getString(PKG, "Database.UnableToPreLoadConnectionToConnectionPool.Exception"), e); } } pd.registerPool(databaseMeta.getName(), gpool); log.logBasic(BaseMessages.getString(PKG, "Database.CreatedConnectionPool", databaseMeta.getName())); }
From source file:org.seadva.access.security.model.DatabaseSingleton.java
protected DatabaseSingleton() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException { Class.forName(this.driver).newInstance(); connectionPool = new GenericObjectPool(); connectionPool.setMaxActive(10);//from w w w. java2s. co m Properties props = new Properties(); props.setProperty("user", dbUsername); props.setProperty("password", dbUserPwd); ConnectionFactory cf = new DriverConnectionFactory(new com.mysql.jdbc.Driver(), dbUrl, props); PoolableConnectionFactory pcf = new PoolableConnectionFactory(cf, connectionPool, null, null, false, true); this.dataSource = new PoolingDataSource(connectionPool); }
From source file:org.topazproject.ambra.auth.db.DatabaseContext.java
/** * Construct a db context/* ww w . j av a 2s. c o m*/ * @param jdbcDriver jdbcDriver * @param dbProperties dbProperties including url, user, password * @param initialSize initialSize of the pool * @param maxActive maxActive number of connections, after which it will block until a connection is * released * @param validationQuery to validate that the connection is still valid * @throws DatabaseException DatabaseException */ private DatabaseContext(final String jdbcDriver, final Properties dbProperties, final int initialSize, final int maxActive, final String validationQuery) throws DatabaseException { try { Class.forName(jdbcDriver); } catch (final ClassNotFoundException e) { throw new DatabaseException("Unable to load the db driver:" + jdbcDriver, e); } final ConnectionFactory connectionFactory = new DriverManagerConnectionFactory( dbProperties.getProperty("url"), dbProperties.getProperty("user"), dbProperties.getProperty("password")); connectionPool = new GenericObjectPool(); connectionPool.setTestOnReturn(true); connectionPool.setMaxActive(maxActive); connectionPool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_BLOCK); connectionPool.getMaxActive(); final KeyedObjectPoolFactory stmtPool = new GenericKeyedObjectPoolFactory(null); /* * During instantiation, the PoolableConnectionFactory class registers itself to the * GenericObjectPool instance passed in its constructor. This factory class is used to create * new instances of the JDBC connections. */ new PoolableConnectionFactory(connectionFactory, connectionPool, stmtPool, validationQuery, false, true); for (int i = 0; i < initialSize; i++) { try { connectionPool.addObject(); } catch (final Exception e) { throw new DatabaseException("Error initlaizing initial number of connections", e); } } dataSource = new PoolingDataSource(connectionPool); }