List of usage examples for org.apache.commons.pool2 PooledObject getObject
T getObject();
From source file:org.openhab.io.transport.modbus.internal.pooling.ModbusSlaveConnectionFactoryImpl.java
@Override public void activateObject(ModbusSlaveEndpoint endpoint, @Nullable PooledObject<ModbusSlaveConnection> obj) throws Exception { if (obj == null) { return;//from w w w. j a va2 s . co m } ModbusSlaveConnection connection = obj.getObject(); if (connection == null) { return; } try { @Nullable EndpointPoolConfiguration config = getEndpointPoolConfiguration(endpoint); if (!connection.isConnected()) { tryConnect(endpoint, obj, connection, config); } if (config != null) { long waited = waitAtleast(lastPassivateMillis.get(endpoint), config.getInterTransactionDelayMillis()); logger.trace( "Waited {}ms (interTransactionDelayMillis {}ms) before giving returning connection {} for endpoint {}, to ensure delay between transactions.", waited, config.getInterTransactionDelayMillis(), obj.getObject(), endpoint); } } catch (InterruptedException e) { // Someone wants to cancel us, reset the connection and abort if (connection.isConnected()) { connection.resetConnection(); } } catch (Exception e) { logger.error("Error connecting connection {} for endpoint {}: {}", obj.getObject(), endpoint, e.getMessage()); } }
From source file:org.openhab.io.transport.modbus.internal.pooling.ModbusSlaveConnectionFactoryImpl.java
@Override public void passivateObject(ModbusSlaveEndpoint endpoint, @Nullable PooledObject<ModbusSlaveConnection> obj) { if (obj == null) { return;//w w w. ja v a2 s.co m } ModbusSlaveConnection connection = obj.getObject(); if (connection == null) { return; } logger.trace("Passivating connection {} for endpoint {}...", connection, endpoint); lastPassivateMillis.put(endpoint, System.currentTimeMillis()); @Nullable EndpointPoolConfiguration configuration = endpointPoolConfigs.get(endpoint); long connected = ((PooledConnection) obj).getLastConnected(); long reconnectAfterMillis = configuration == null ? 0 : configuration.getReconnectAfterMillis(); long connectionAgeMillis = System.currentTimeMillis() - ((PooledConnection) obj).getLastConnected(); long disconnectIfConnectedBeforeMillis = disconnectIfConnectedBefore.getOrDefault(endpoint, -1L); boolean disconnectSinceTooOldConnection = disconnectIfConnectedBeforeMillis < 0L ? false : connected <= disconnectIfConnectedBeforeMillis; if (reconnectAfterMillis == 0 || (reconnectAfterMillis > 0 && connectionAgeMillis > reconnectAfterMillis) || disconnectSinceTooOldConnection) { logger.trace( "(passivate) Connection {} (endpoint {}) age {}ms is over the reconnectAfterMillis={}ms limit or has been connection time ({}) is after the \"disconnectBeforeConnectedMillis\"={} -> disconnecting.", connection, endpoint, connectionAgeMillis, reconnectAfterMillis, connected, disconnectIfConnectedBeforeMillis); connection.resetConnection(); } else { logger.trace( "(passivate) Connection {} (endpoint {}) age ({}ms) is below the reconnectAfterMillis ({}ms) limit and connection time ({}) is after the \"disconnectBeforeConnectedMillis\"={}. Keep the connection open.", connection, endpoint, connectionAgeMillis, reconnectAfterMillis, connected, disconnectIfConnectedBeforeMillis); } logger.trace("...Passivated connection {} for endpoint {}", obj.getObject(), endpoint); }
From source file:org.openhab.io.transport.modbus.internal.pooling.ModbusSlaveConnectionFactoryImpl.java
@Override public boolean validateObject(ModbusSlaveEndpoint key, @Nullable PooledObject<ModbusSlaveConnection> p) { boolean valid = p != null && p.getObject() != null && p.getObject().isConnected(); logger.trace("Validating endpoint {} connection {} -> {}", key, p.getObject(), valid); return valid; }
From source file:org.openhab.io.transport.modbus.internal.pooling.ModbusSlaveConnectionFactoryImpl.java
private void tryConnect(ModbusSlaveEndpoint endpoint, PooledObject<ModbusSlaveConnection> obj, ModbusSlaveConnection connection, @Nullable EndpointPoolConfiguration config) throws Exception { if (connection.isConnected()) { return;/*from ww w .j ava2 s.co m*/ } int tryIndex = 0; Long lastConnect = lastConnectMillis.get(endpoint); int maxTries = config == null ? 1 : config.getConnectMaxTries(); do { try { if (config != null) { long waited = waitAtleast(lastConnect, Math.max(config.getInterConnectDelayMillis(), config.getInterTransactionDelayMillis())); if (waited > 0) { logger.trace( "Waited {}ms (interConnectDelayMillis {}ms, interTransactionDelayMillis {}ms) before " + "connecting disconnected connection {} for endpoint {}, to allow delay " + "between connections re-connects", waited, config.getInterConnectDelayMillis(), config.getInterTransactionDelayMillis(), obj.getObject(), endpoint); } } connection.connect(); long curTime = System.currentTimeMillis(); ((PooledConnection) obj).setLastConnected(curTime); lastConnectMillis.put(endpoint, curTime); break; } catch (InterruptedException e) { logger.error("connect try {}/{} error: {}. Aborting since interrupted. Connection {}. Endpoint {}.", tryIndex, maxTries, e.getMessage(), connection, endpoint); throw e; } catch (Exception e) { tryIndex++; logger.error("connect try {}/{} error: {}. Connection {}. Endpoint {}", tryIndex, maxTries, e.getMessage(), connection, endpoint); if (tryIndex >= maxTries) { logger.error( "re-connect reached max tries {}, throwing last error: {}. Connection {}. Endpoint {}", maxTries, e.getMessage(), connection, endpoint); throw e; } lastConnect = System.currentTimeMillis(); } } while (true); }
From source file:org.springframework.aop.target.CommonsPool2TargetSource.java
@Override public void destroyObject(PooledObject<Object> p) throws Exception { destroyPrototypeInstance(p.getObject()); }
From source file:org.springframework.boot.actuate.metrics.ambari.pool.TimelineMetricFactory.java
@Override public void passivateObject(PooledObject<TimelineMetric> tm) throws Exception { // When the TimelineMetric is returned to the pool, clean the previous state tm.getObject().setInstanceId(null); tm.getObject().setAppId(null);//from w w w .j a v a 2 s.com tm.getObject().setHostName(null); tm.getObject().setMetricName(null); tm.getObject().getMetricValues().clear(); tm.getObject().setStartTime(-1); }
From source file:org.springframework.boot.actuate.metrics.ambari.pool.TimelineMetricsFactory.java
@Override public void passivateObject(PooledObject<TimelineMetrics> tlms) throws Exception { // When the TimelineMetrics is returned to the pool, clean the previous state tlms.getObject().getMetrics().clear(); }
From source file:org.springframework.ldap.pool2.factory.DirContextPooledObjectFactory.java
/** * @see BaseKeyedPooledObjectFactory#validateObject(Object, PooledObject) * * *//*from w w w . j a va 2s .c o m*/ @Override public boolean validateObject(Object key, PooledObject<Object> pooledObject) { Assert.notNull(this.dirContextValidator, "DirContextValidator may not be null"); Assert.isTrue(key instanceof DirContextType, "key must be a DirContextType"); Assert.notNull(pooledObject, "The Object to validate must not be null"); Assert.isTrue(pooledObject.getObject() instanceof DirContext, "The Object to validate must be of type '" + DirContext.class + "'"); try { final DirContextType contextType = (DirContextType) key; final DirContext dirContext = (DirContext) pooledObject.getObject(); return this.dirContextValidator.validateDirContext(contextType, dirContext); } catch (Exception e) { this.logger.warn( "Failed to validate '" + pooledObject.getObject() + "' due to an unexpected exception.", e); return false; } }
From source file:org.springframework.ldap.pool2.factory.DirContextPooledObjectFactory.java
/** * @see BaseKeyedPooledObjectFactory#destroyObject(Object, PooledObject) * * */// ww w. j a v a2 s .com @Override public void destroyObject(Object key, PooledObject<Object> pooledObject) throws Exception { Assert.notNull(pooledObject, "The Object to destroy must not be null"); Assert.isTrue(pooledObject.getObject() instanceof DirContext, "The Object to destroy must be of type '" + DirContext.class + "'"); try { final DirContext dirContext = (DirContext) pooledObject.getObject(); if (this.logger.isDebugEnabled()) { this.logger.debug("Closing " + key + " DirContext='" + dirContext + "'"); } dirContext.close(); if (this.logger.isDebugEnabled()) { this.logger.debug("Closed " + key + " DirContext='" + dirContext + "'"); } } catch (Exception e) { this.logger.warn("An exception occured while closing '" + pooledObject.getObject() + "'", e); } }
From source file:org.springframework.ldap.pool2.factory.DirContextPooledObjectFactoryTest.java
@Test public void testMakeObjectReadOnly() throws Exception { final DirContextPooledObjectFactory objectFactory = new DirContextPooledObjectFactory(); DirContext readOnlyContextMock = mock(DirContext.class); when(contextSourceMock.getReadOnlyContext()).thenReturn(readOnlyContextMock); objectFactory.setContextSource(contextSourceMock); final PooledObject createdDirContext = objectFactory.makeObject(DirContextType.READ_ONLY); InvocationHandler invocationHandler = Proxy.getInvocationHandler(createdDirContext.getObject()); assertThat(readOnlyContextMock).isEqualTo(Whitebox.getInternalState(invocationHandler, "target")); }