org.apache.commons.pool2.ObjectPool Java Examples
The following examples show how to use
org.apache.commons.pool2.ObjectPool.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SmsService.java From Openfire with Apache License 2.0 | 7 votes |
SmsTask( ObjectPool<SMPPSession> sessionPool, String message, String destinationAddress ) { this.sessionPool = sessionPool; this.message = message.getBytes(); this.destinationAddress = destinationAddress; }
Example #2
Source File: TransactionLegacy.java From cloudstack with Apache License 2.0 | 6 votes |
/** * Creates a data source */ private static DataSource createDataSource(String uri, String username, String password, Integer maxActive, Integer maxIdle, Long maxWait, Long timeBtwnEvictionRuns, Long minEvictableIdleTime, Boolean testWhileIdle, Boolean testOnBorrow, String validationQuery, Integer isolationLevel) { ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(uri, username, password); PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, null); GenericObjectPoolConfig config = createPoolConfig(maxActive, maxIdle, maxWait, timeBtwnEvictionRuns, minEvictableIdleTime, testWhileIdle, testOnBorrow); ObjectPool<PoolableConnection> connectionPool = new GenericObjectPool<>(poolableConnectionFactory, config); poolableConnectionFactory.setPool(connectionPool); if (validationQuery != null) { poolableConnectionFactory.setValidationQuery(validationQuery); } if (isolationLevel != null) { poolableConnectionFactory.setDefaultTransactionIsolation(isolationLevel); } return new PoolingDataSource<>(connectionPool); }
Example #3
Source File: TestRetryProcessor.java From phoenix-omid with Apache License 2.0 | 6 votes |
@Test(timeOut = 10_000) public void testRetriedRequestForInvalidatedTransactionReturnsAnAbort() throws Exception { // Invalidate the transaction commitTable.getClient().tryInvalidateTransaction(ST_TX_1); // Pre-start verification: Validate that the transaction is invalidated // NOTE: This test should be in the a test class for InMemoryCommitTable Optional<CommitTimestamp> invalidTxMarker = commitTable.getClient().getCommitTimestamp(ST_TX_1).get(); Assert.assertTrue(invalidTxMarker.isPresent()); Assert.assertEquals(invalidTxMarker.get().getValue(), InMemoryCommitTable.INVALID_TRANSACTION_MARKER); ObjectPool<Batch> batchPool = new BatchPoolModule(new TSOServerConfig()).getBatchPool(); // The element to test RetryProcessor retryProc = new RetryProcessorImpl(new YieldingWaitStrategy(), metrics, commitTable, replyProc, panicker, batchPool); // Test we return an Abort to a retry request when the transaction id IS in the commit table BUT invalidated retryProc.disambiguateRetryRequestHeuristically(ST_TX_1, channel, new MonitoringContextImpl(metrics)); ArgumentCaptor<Long> startTSCapture = ArgumentCaptor.forClass(Long.class); verify(replyProc, timeout(100).times(1)).sendAbortResponse(startTSCapture.capture(), any(Channel.class), any(MonitoringContextImpl.class)); long startTS = startTSCapture.getValue(); Assert.assertEquals(startTS, ST_TX_1, "Captured timestamp should be the same as NON_EXISTING_ST_TX"); }
Example #4
Source File: TestPStmtPooling.java From commons-dbcp with Apache License 2.0 | 6 votes |
private DataSource createPoolingDataSource() throws Exception { DriverManager.registerDriver(new TesterDriver()); final ConnectionFactory connFactory = new DriverManagerConnectionFactory( "jdbc:apache:commons:testdriver","u1","p1"); final PoolableConnectionFactory pcf = new PoolableConnectionFactory(connFactory, null); pcf.setPoolStatements(true); pcf.setDefaultReadOnly(Boolean.FALSE); pcf.setDefaultAutoCommit(Boolean.TRUE); final ObjectPool<PoolableConnection> connPool = new GenericObjectPool<>(pcf); pcf.setPool(connPool); return new PoolingDataSource<>(connPool); }
Example #5
Source File: PoolingDataSource.java From commons-dbcp with Apache License 2.0 | 6 votes |
/** * Constructs a new instance backed by the given connection pool. * * @param pool * the given connection pool. */ public PoolingDataSource(final ObjectPool<C> pool) { Objects.requireNonNull(pool, "Pool must not be null."); this.pool = pool; // Verify that pool's factory refers back to it. If not, log a warning and try to fix. if (this.pool instanceof GenericObjectPool<?>) { final PoolableConnectionFactory pcf = (PoolableConnectionFactory) ((GenericObjectPool<?>) this.pool) .getFactory(); Objects.requireNonNull(pcf, "PoolableConnectionFactory must not be null."); if (pcf.getPool() != this.pool) { log.warn(Utils.getMessage("poolingDataSource.factoryConfig")); @SuppressWarnings("unchecked") // PCF must have a pool of PCs final ObjectPool<PoolableConnection> p = (ObjectPool<PoolableConnection>) this.pool; pcf.setPool(p); } } }
Example #6
Source File: BaseTestProxiedObjectPool.java From commons-pool with Apache License 2.0 | 6 votes |
@Before public void setUp() { log = new StringWriter(); final PrintWriter pw = new PrintWriter(log); final AbandonedConfig abandonedConfig = new AbandonedConfig(); abandonedConfig.setLogAbandoned(true); abandonedConfig.setRemoveAbandonedOnBorrow(true); abandonedConfig.setUseUsageTracking(true); abandonedConfig.setRemoveAbandonedTimeout(ABANDONED_TIMEOUT_SECS); abandonedConfig.setLogWriter(pw); final GenericObjectPoolConfig<TestObject> config = new GenericObjectPoolConfig<>(); config.setMaxTotal(3); final PooledObjectFactory<TestObject> factory = new TestObjectFactory(); @SuppressWarnings("resource") final ObjectPool<TestObject> innerPool = new GenericObjectPool<>(factory, config, abandonedConfig); pool = new ProxiedObjectPool<>(innerPool, getproxySource()); }
Example #7
Source File: MonetaConfiguration.java From moneta with Apache License 2.0 | 6 votes |
/** * Will return a dbConnection for a given information topic. * @param sourceName Data source name * @return topicDbConnection connection topic */ public Connection getConnection(String sourceName) { Validate.notEmpty(sourceName, "Null or blank sourceName not allowed"); Validate.isTrue(this.initRun, "Moneta not properly initialized."); ObjectPool connectionPool = connectionPoolMap.get(sourceName); if (connectionPool == null) { throw new MonetaException("Data Source Not Found") .addContextValue("sourceName", sourceName); } try { return (Connection)connectionPool.borrowObject(); } catch (Exception e) { throw new MonetaException("Error creating JDBC connection") .addContextValue("sourceName", sourceName); } }
Example #8
Source File: TestPersistenceProcessor.java From phoenix-omid with Apache License 2.0 | 6 votes |
private PersistenceProcessorHandler[] configureHandlers(TSOServerConfig tsoConfig, LeaseManager leaseManager, ObjectPool<Batch> batchPool) throws Exception { PersistenceProcessorHandler[] handlers = new PersistenceProcessorHandler[tsoConfig.getNumConcurrentCTWriters()]; for (int i = 0; i < tsoConfig.getNumConcurrentCTWriters(); i++) { handlers[i] = new PersistenceProcessorHandler(metrics, "localhost:1234", leaseManager, commitTable, new ReplyProcessorImpl(new BlockingWaitStrategy(), metrics, panicker, batchPool, lowWatermarkWriter), retryProcessor, new RuntimeExceptionPanicker()); } return handlers; }
Example #9
Source File: TestPersistenceProcessor.java From phoenix-omid with Apache License 2.0 | 6 votes |
private void testPersistenceWithHALeaseManagerFailingToPreserveLease3(TSOServerConfig tsoConfig) throws Exception { // Init a HA lease manager LeaseManager simulatedHALeaseManager = mock(LeaseManager.class); ObjectPool<Batch> batchPool = spy(new BatchPoolModule(tsoConfig).getBatchPool()); PersistenceProcessorHandler[] handlers = configureHandlers (tsoConfig, simulatedHALeaseManager, batchPool); // Component under test PersistenceProcessorImpl proc = new PersistenceProcessorImpl(tsoConfig, new BlockingWaitStrategy(), commitTable, batchPool, panicker, handlers, metrics); // Test: Configure the lease manager to return true first and false later for stillInLeasePeriod and raise // an exception when flush // Configure mock writer to flush unsuccessfully doThrow(new IOException("Unable to write")).when(mockWriter).flush(); doReturn(true).doReturn(false).when(simulatedHALeaseManager).stillInLeasePeriod(); proc.addCommitToBatch(ANY_ST, ANY_CT, mock(Channel.class), mock(MonitoringContextImpl.class), Optional.<Long>absent()); proc.triggerCurrentBatchFlush(); verify(simulatedHALeaseManager, timeout(1000).times(1)).stillInLeasePeriod(); verify(batchPool, times(2)).borrowObject(); }
Example #10
Source File: TestPersistenceProcessor.java From phoenix-omid with Apache License 2.0 | 6 votes |
private void testPersistenceWithHALeaseManagerFailingToPreserveLease2(TSOServerConfig tsoConfig) throws Exception { // Init a HA lease manager LeaseManager simulatedHALeaseManager = mock(LeaseManager.class); ObjectPool<Batch> batchPool = spy(new BatchPoolModule(tsoConfig).getBatchPool()); PersistenceProcessorHandler[] handlers = configureHandlers (tsoConfig, simulatedHALeaseManager, batchPool); // Component under test PersistenceProcessorImpl proc = new PersistenceProcessorImpl(tsoConfig, new BlockingWaitStrategy(), commitTable, batchPool, panicker, handlers, metrics); // Test: Configure the lease manager to return false for stillInLeasePeriod doReturn(false).when(simulatedHALeaseManager).stillInLeasePeriod(); proc.addCommitToBatch(ANY_ST, ANY_CT, mock(Channel.class), mock(MonitoringContextImpl.class), Optional.<Long>absent()); proc.triggerCurrentBatchFlush(); verify(simulatedHALeaseManager, timeout(1000).times(1)).stillInLeasePeriod(); verify(batchPool, times(2)).borrowObject(); }
Example #11
Source File: TestPersistenceProcessor.java From phoenix-omid with Apache License 2.0 | 6 votes |
private void testPersistenceWithHALeaseManagerFailingToPreserveLease1(TSOServerConfig tsoConfig) throws Exception { // Init a HA lease manager LeaseManager simulatedHALeaseManager = mock(LeaseManager.class); ObjectPool<Batch> batchPool = spy(new BatchPoolModule(tsoConfig).getBatchPool()); PersistenceProcessorHandler[] handlers = configureHandlers (tsoConfig, simulatedHALeaseManager, batchPool); // Component under test PersistenceProcessorImpl proc = new PersistenceProcessorImpl(tsoConfig, new BlockingWaitStrategy(), commitTable, batchPool, panicker, handlers, metrics); // Test: Configure the lease manager to return true first and false later for stillInLeasePeriod doReturn(true).doReturn(false).when(simulatedHALeaseManager).stillInLeasePeriod(); proc.addCommitToBatch(ANY_ST, ANY_CT, mock(Channel.class), mock(MonitoringContextImpl.class), Optional.<Long>absent()); proc.triggerCurrentBatchFlush(); verify(simulatedHALeaseManager, timeout(1000).times(2)).stillInLeasePeriod(); verify(batchPool, times(2)).borrowObject(); }
Example #12
Source File: TestPersistenceProcessor.java From phoenix-omid with Apache License 2.0 | 6 votes |
private void testPersistenceWithHALeaseManagerPreservingLease(TSOServerConfig tsoConfig) throws Exception { // Init a HA lease manager LeaseManager simulatedHALeaseManager = mock(LeaseManager.class); ObjectPool<Batch> batchPool = spy(new BatchPoolModule(tsoConfig).getBatchPool()); PersistenceProcessorHandler[] handlers = configureHandlers (tsoConfig, simulatedHALeaseManager, batchPool); // Component under test PersistenceProcessorImpl proc = new PersistenceProcessorImpl(tsoConfig, new BlockingWaitStrategy(), commitTable, batchPool, panicker, handlers, metrics); // Test: Configure the lease manager to return true always doReturn(true).when(simulatedHALeaseManager).stillInLeasePeriod(); proc.addCommitToBatch(ANY_ST, ANY_CT, mock(Channel.class), mock(MonitoringContextImpl.class), Optional.<Long>absent()); proc.triggerCurrentBatchFlush(); verify(simulatedHALeaseManager, timeout(1000).times(2)).stillInLeasePeriod(); verify(batchPool, times(2)).borrowObject(); }
Example #13
Source File: TestObjectPool.java From commons-pool with Apache License 2.0 | 6 votes |
@Test public void testPOFClearUsages() throws Exception { final MethodCallPoolableObjectFactory factory = new MethodCallPoolableObjectFactory(); final ObjectPool<Object> pool; try { pool = makeEmptyPool(factory); } catch (final UnsupportedOperationException uoe) { return; // test not supported } final List<MethodCall> expectedMethods = new ArrayList<>(); /// Test correct behavior code paths pool.addObjects(5); pool.clear(); //// Test exception handling clear should swallow destroy object failures reset(pool, factory, expectedMethods); factory.setDestroyObjectFail(true); pool.addObjects(5); pool.clear(); pool.close(); }
Example #14
Source File: PoolableConnection.java From commons-dbcp with Apache License 2.0 | 6 votes |
/** * * @param conn * my underlying connection * @param pool * the pool to which I should return when closed * @param jmxObjectName * JMX name * @param disconnectSqlCodes * SQL_STATE codes considered fatal disconnection errors * @param fastFailValidation * true means fatal disconnection errors cause subsequent validations to fail immediately (no attempt to * run query or isValid) */ public PoolableConnection(final Connection conn, final ObjectPool<PoolableConnection> pool, final ObjectName jmxObjectName, final Collection<String> disconnectSqlCodes, final boolean fastFailValidation) { super(conn); this.pool = pool; this.jmxObjectName = ObjectNameWrapper.wrap(jmxObjectName); this.disconnectionSqlCodes = disconnectSqlCodes; this.fastFailValidation = fastFailValidation; if (jmxObjectName != null) { try { MBEAN_SERVER.registerMBean(this, jmxObjectName); } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e) { // For now, simply skip registration } } }
Example #15
Source File: TestPoolingDriver.java From commons-dbcp with Apache License 2.0 | 6 votes |
@Test public void testInvalidateConnection() throws Exception { final Connection conn = DriverManager.getConnection("jdbc:apache:commons:dbcp:test"); assertNotNull(conn); final ObjectPool<?> pool = driver.getConnectionPool("test"); assertEquals(1, pool.getNumActive()); assertEquals(0, pool.getNumIdle()); final PoolingDriver driver2 = (PoolingDriver) DriverManager.getDriver("jdbc:apache:commons:dbcp:"); driver2.invalidateConnection(conn); assertEquals(0, pool.getNumActive()); assertEquals(0, pool.getNumIdle()); assertTrue(conn.isClosed()); }
Example #16
Source File: TestPStmtPooling.java From commons-dbcp with Apache License 2.0 | 6 votes |
@Test public void testBatchUpdate() throws Exception { DriverManager.registerDriver(new TesterDriver()); final ConnectionFactory connFactory = new DriverManagerConnectionFactory( "jdbc:apache:commons:testdriver","u1","p1"); final PoolableConnectionFactory pcf = new PoolableConnectionFactory(connFactory, null); pcf.setPoolStatements(true); pcf.setDefaultReadOnly(Boolean.FALSE); pcf.setDefaultAutoCommit(Boolean.TRUE); final ObjectPool<PoolableConnection> connPool = new GenericObjectPool<>(pcf); pcf.setPool(connPool); final PoolingDataSource<?> ds = new PoolingDataSource<>(connPool); final Connection conn = ds.getConnection(); final PreparedStatement ps = conn.prepareStatement("select 1 from dual"); final Statement inner = ((DelegatingPreparedStatement) ps).getInnermostDelegate(); // Check DBCP-372 ps.addBatch(); ps.close(); conn.close(); Assertions.assertFalse(inner.isClosed()); ds.close(); }
Example #17
Source File: PoolingDriverExample.java From commons-dbcp with Apache License 2.0 | 5 votes |
public static void printDriverStats() throws Exception { PoolingDriver driver = (PoolingDriver) DriverManager.getDriver("jdbc:apache:commons:dbcp:"); ObjectPool<? extends Connection> connectionPool = driver.getConnectionPool("example"); System.out.println("NumActive: " + connectionPool.getNumActive()); System.out.println("NumIdle: " + connectionPool.getNumIdle()); }
Example #18
Source File: TestPersistenceProcessor.java From phoenix-omid with Apache License 2.0 | 5 votes |
@Test(timeOut = 30_000) public void testRuntimeExceptionOnCommitPersistenceTakesDownDaemon() throws Exception { TSOServerConfig config = new TSOServerConfig(); ObjectPool<Batch> batchPool = new BatchPoolModule(config).getBatchPool(); ReplyProcessor replyProcessor = new ReplyProcessorImpl(new BlockingWaitStrategy(), metrics, panicker, batchPool, lowWatermarkWriter); PersistenceProcessorHandler[] handlers = new PersistenceProcessorHandler[config.getNumConcurrentCTWriters()]; for (int i = 0; i < config.getNumConcurrentCTWriters(); i++) { handlers[i] = new PersistenceProcessorHandler(metrics, "localhost:1234", mock(LeaseManager.class), commitTable, replyProcessor, retryProcessor, panicker); } PersistenceProcessorImpl proc = new PersistenceProcessorImpl(config, new BlockingWaitStrategy(), commitTable, batchPool, panicker, handlers, metrics); // Configure writer to explode with a runtime exception doThrow(new RuntimeException("Kaboom!")).when(mockWriter).addCommittedTransaction(anyLong(), anyLong()); MonitoringContextImpl monCtx = new MonitoringContextImpl(metrics); // Check the panic is extended! proc.addCommitToBatch(ANY_ST, ANY_CT, mock(Channel.class), monCtx, Optional.<Long>absent()); proc.triggerCurrentBatchFlush(); verify(panicker, timeout(1000).atLeastOnce()).panic(anyString(), any(Throwable.class)); }
Example #19
Source File: PersistenceProcessorImpl.java From phoenix-omid with Apache License 2.0 | 5 votes |
@Inject PersistenceProcessorImpl(TSOServerConfig config, @Named("PersistenceStrategy") WaitStrategy strategy, CommitTable commitTable, ObjectPool<Batch> batchPool, Panicker panicker, PersistenceProcessorHandler[] handlers, MetricsRegistry metrics) throws Exception { // ------------------------------------------------------------------------------------------------------------ // Disruptor initialization // ------------------------------------------------------------------------------------------------------------ ThreadFactoryBuilder threadFactory = new ThreadFactoryBuilder().setNameFormat("persist-%d"); this.disruptorExec = Executors.newFixedThreadPool(config.getNumConcurrentCTWriters(), threadFactory.build()); this.disruptor = new Disruptor<>(EVENT_FACTORY, 1 << 20, disruptorExec , SINGLE, strategy); disruptor.handleExceptionsWith(new FatalExceptionHandler(panicker)); // This must be before handleEventsWith() disruptor.handleEventsWithWorkerPool(handlers); this.persistRing = disruptor.start(); // ------------------------------------------------------------------------------------------------------------ // Attribute initialization // ------------------------------------------------------------------------------------------------------------ this.metrics = metrics; this.batchSequence = 0L; this.batchPool = batchPool; this.currentBatch = batchPool.borrowObject(); LOG.info("PersistentProcessor initialized"); }
Example #20
Source File: TestRetryProcessor.java From phoenix-omid with Apache License 2.0 | 5 votes |
@Test(timeOut = 10_000) public void testRetriedRequestForANonExistingTxReturnsAbort() throws Exception { ObjectPool<Batch> batchPool = new BatchPoolModule(new TSOServerConfig()).getBatchPool(); // The element to test RetryProcessor retryProc = new RetryProcessorImpl(new YieldingWaitStrategy(), metrics, commitTable, replyProc, panicker, batchPool); // Test we'll reply with an abort for a retry request when the start timestamp IS NOT in the commit table retryProc.disambiguateRetryRequestHeuristically(NON_EXISTING_ST_TX, channel, monCtx); ArgumentCaptor<Long> firstTSCapture = ArgumentCaptor.forClass(Long.class); verify(replyProc, timeout(100).times(1)).sendAbortResponse(firstTSCapture.capture(), any(Channel.class), any(MonitoringContextImpl.class)); long startTS = firstTSCapture.getValue(); assertEquals(startTS, NON_EXISTING_ST_TX, "Captured timestamp should be the same as NON_EXISTING_ST_TX"); }
Example #21
Source File: CommonsPoolImpl.java From ikasoa with MIT License | 5 votes |
@Override @SneakyThrows public synchronized void releaseThriftSocket(ThriftSocket thriftSocket, String host, int port) { if (ObjectUtil.isNull(thriftSocket)) return; ObjectPool<ThriftSocket> pool = poolMap.get(ServerUtil.buildCacheKey(host, port)); if (ObjectUtil.isNotNull(pool)) pool.returnObject(thriftSocket); }
Example #22
Source File: DataSourceFactory.java From athenz with Apache License 2.0 | 5 votes |
static PoolableDataSource create(ConnectionFactory connectionFactory) { // setup our pool config object GenericObjectPoolConfig config = setupPoolConfig(); PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, null); // Set max lifetime of a connection in milli-secs, after which it will // always fail activation, passivation, and validation. // Value of -1 means infinite life time. The default value // defined in this class is 10 minutes. long connTtlMillis = retrieveConfigSetting(ATHENZ_PROP_DBPOOL_MAX_TTL, MAX_TTL_CONN_MS); poolableConnectionFactory.setMaxConnLifetimeMillis(connTtlMillis); if (LOG.isInfoEnabled()) { LOG.info("Setting Time-To-Live interval for live connections ({}) msecs", connTtlMillis); } // set the validation query for our jdbc connector final String validationQuery = System.getProperty(ATHENZ_PROP_DBPOOL_VALIDATION_QUERY, MYSQL_VALIDATION_QUERY); poolableConnectionFactory.setValidationQuery(validationQuery); ObjectPool<PoolableConnection> connectionPool = new GenericObjectPool<>(poolableConnectionFactory, config); poolableConnectionFactory.setPool(connectionPool); return new AthenzDataSource(connectionPool); }
Example #23
Source File: AthenzDataSource.java From athenz with Apache License 2.0 | 5 votes |
public AthenzDataSource(ObjectPool<PoolableConnection> pool) { super(pool); int timeoutThreads = Integer.parseInt(System.getProperty(ATHENZ_PROP_DATASTORE_TIMEOUT_THREADS, "8")); if (timeoutThreads <= 0) { timeoutThreads = 1; } networkTimeout = Integer.parseInt(System.getProperty(ATHENZ_PROP_DATASTORE_NETWORK_TIMEOUT, "0")); // create our executors pool timeoutThreadPool = Executors.newScheduledThreadPool(timeoutThreads); }
Example #24
Source File: MockedDbcp2PoolingConnection.java From liquibase-percona with Apache License 2.0 | 5 votes |
/** * Creates a mocked SQL connection, that looks like a apache commons dbcp pooled connection. * @param username the username to use * @param password the password to use * @return the connection * @throws SQLException */ public static Connection create(String username, String password) throws SQLException { ObjectPool<Connection> pool = new MockedObjectPool(username, password); PoolingDataSource<Connection> ds = new PoolingDataSource<Connection>(pool); try { return ds.getConnection(); } finally { try { ds.close(); } catch (Exception ignored) { // ignored } } }
Example #25
Source File: AthenzDataSourceTest.java From athenz with Apache License 2.0 | 5 votes |
@Test public void testClearPoolConnectionsException() throws Exception { ObjectPool<PoolableConnection> pool = Mockito.mock(ObjectPool.class); Mockito.doThrow(new SQLException()).when(pool).clear(); AthenzDataSource dataSource = new AthenzDataSource(pool); dataSource.clearPoolConnections(); }
Example #26
Source File: TestObjectPool.java From commons-pool with Apache License 2.0 | 5 votes |
@Test public void testToString() throws Exception { ObjectPool<Object> pool; try { pool = makeEmptyPool(new MethodCallPoolableObjectFactory()); } catch (final UnsupportedOperationException uoe) { return; // test not supported } pool.toString(); pool.close(); }
Example #27
Source File: TestPStmtPooling.java From commons-dbcp with Apache License 2.0 | 5 votes |
@Test public void testClosePool() throws Exception { DriverManager.registerDriver(new TesterDriver()); final ConnectionFactory connFactory = new DriverManagerConnectionFactory( "jdbc:apache:commons:testdriver","u1","p1"); final PoolableConnectionFactory pcf = new PoolableConnectionFactory(connFactory, null); pcf.setPoolStatements(true); pcf.setDefaultReadOnly(Boolean.FALSE); pcf.setDefaultAutoCommit(Boolean.TRUE); final ObjectPool<PoolableConnection> connPool = new GenericObjectPool<>(pcf); pcf.setPool(connPool); final PoolingDataSource<?> ds = new PoolingDataSource<>(connPool); ((PoolingDataSource<?>) ds).setAccessToUnderlyingConnectionAllowed(true); final Connection conn = ds.getConnection(); try (Statement s = conn.prepareStatement("select 1 from dual")) {} final Connection poolableConnection = ((DelegatingConnection<?>) conn).getDelegate(); final Connection poolingConnection = ((DelegatingConnection<?>) poolableConnection).getDelegate(); poolingConnection.close(); try (PreparedStatement ps = conn.prepareStatement("select 1 from dual")) { fail("Expecting SQLException"); } catch (final SQLException ex) { assertTrue(ex.getMessage().endsWith("invalid PoolingConnection.")); } ds.close(); }
Example #28
Source File: JDBCInterpreter.java From zeppelin with Apache License 2.0 | 5 votes |
private void createConnectionPool(String url, String user, String dbPrefix, Properties properties) throws SQLException, ClassNotFoundException { String driverClass = properties.getProperty(DRIVER_KEY); if (driverClass != null && (driverClass.equals("com.facebook.presto.jdbc.PrestoDriver") || driverClass.equals("io.prestosql.jdbc.PrestoDriver"))) { // Only add valid properties otherwise presto won't work. for (String key : properties.stringPropertyNames()) { if (!PRESTO_PROPERTIES.contains(key)) { properties.remove(key); } } } ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(url, properties); PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory( connectionFactory, null); final String maxConnectionLifetime = StringUtils.defaultIfEmpty(getProperty("zeppelin.jdbc.maxConnLifetime"), "-1"); poolableConnectionFactory.setMaxConnLifetimeMillis(Long.parseLong(maxConnectionLifetime)); poolableConnectionFactory.setValidationQuery("show databases"); ObjectPool connectionPool = new GenericObjectPool(poolableConnectionFactory); poolableConnectionFactory.setPool(connectionPool); Class.forName(driverClass); PoolingDriver driver = new PoolingDriver(); driver.registerPool(dbPrefix + user, connectionPool); getJDBCConfiguration(user).saveDBDriverPool(dbPrefix, driver); }
Example #29
Source File: CommonsPool2TargetSource.java From spring-analysis-note with MIT License | 5 votes |
/** * Subclasses can override this if they want to return a specific Commons pool. * They should apply any configuration properties to the pool here. * <p>Default is a GenericObjectPool instance with the given pool size. * @return an empty Commons {@code ObjectPool}. * @see GenericObjectPool * @see #setMaxSize */ protected ObjectPool createObjectPool() { GenericObjectPoolConfig config = new GenericObjectPoolConfig(); config.setMaxTotal(getMaxSize()); config.setMaxIdle(getMaxIdle()); config.setMinIdle(getMinIdle()); config.setMaxWaitMillis(getMaxWait()); config.setTimeBetweenEvictionRunsMillis(getTimeBetweenEvictionRunsMillis()); config.setMinEvictableIdleTimeMillis(getMinEvictableIdleTimeMillis()); config.setBlockWhenExhausted(isBlockWhenExhausted()); return new GenericObjectPool(this, config); }
Example #30
Source File: ConnectionPoolFactoryTest.java From moneta with Apache License 2.0 | 5 votes |
@Test public void testBasicHappyPath() throws Exception { ObjectPool<PoolableConnection> pool = ConnectionPoolFactory.createConnectionPool(dataSource); Assert.assertTrue(pool != null); Connection conn = pool.borrowObject(); Assert.assertTrue(conn != null); Assert.assertTrue(!conn.isClosed() ); }