org.apache.commons.pool2.impl.DefaultPooledObject Java Examples

The following examples show how to use org.apache.commons.pool2.impl.DefaultPooledObject. 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: ProxyEnabledNettyKeyedPoolClientFactory.java    From x-pipe with Apache License 2.0 6 votes vote down vote up
@Override
public PooledObject<NettyClient> makeObject(Endpoint key) throws Exception {
    if(!isProxyEnabled(key)) {
        return super.makeObject(key);
    }
    ProxyConnectProtocol protocol = ((ProxyEnabled) key).getProxyProtocol();
    ChannelFuture f = proxyedConnectionFactory.getProxyedConnectionChannelFuture(protocol, b);
    f.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            future.channel().writeAndFlush(protocol.output());
        }
    });
    NettyClient nettyClient = new AsyncNettyClient(f, key);
    f.channel().attr(NettyClientHandler.KEY_CLIENT).set(nettyClient);
    return new DefaultPooledObject<>(nettyClient);
}
 
Example #2
Source File: AbstractScripting.java    From cuba with Apache License 2.0 6 votes vote down vote up
private synchronized GenericKeyedObjectPool<String, Script> getPool() {
    if (pool == null) {
        GenericKeyedObjectPoolConfig<Script> poolConfig = new GenericKeyedObjectPoolConfig<>();
        poolConfig.setMaxTotalPerKey(-1);
        poolConfig.setMaxIdlePerKey(globalConfig.getGroovyEvaluationPoolMaxIdle());
        pool = new GenericKeyedObjectPool<>(
                new BaseKeyedPooledObjectFactory<String, Script>() {
                    @Override
                    public Script create(String key) {
                        return createScript(key);
                    }

                    @Override
                    public PooledObject<Script> wrap(Script value) {
                        return new DefaultPooledObject<>(value);
                    }
                },
                poolConfig
        );
    }
    return pool;
}
 
Example #3
Source File: PooledConnectionFactory.java    From seppb with MIT License 6 votes vote down vote up
@Override
public PooledObject<TrackerServer> makeObject() {
    TrackerClient trackerClient = new TrackerClient();
    TrackerServer trackerServer = null;
    try {
        trackerServer = trackerClient.getConnection();
        int flag = 0;
        while (trackerServer == null && flag < 5) {
            log.info("[创建TrackerServer(createTrackerServer)][第" + flag + "次重建]");
            flag++;
            trackerServer = trackerClient.getConnection();
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    return new DefaultPooledObject<>(trackerServer);
}
 
Example #4
Source File: JedisFactory.java    From cachecloud with Apache License 2.0 6 votes vote down vote up
@Override
public PooledObject<Jedis> makeObject() throws Exception {
  final HostAndPort hostAndPort = this.hostAndPort.get();
  final Jedis jedis = new Jedis(hostAndPort.getHost(), hostAndPort.getPort(), connectionTimeout,
      soTimeout);

  try {
    jedis.connect();
    if (null != this.password) {
      jedis.auth(this.password);
    }
    if (database != 0) {
      jedis.select(database);
    }
    if (clientName != null) {
      jedis.clientSetname(clientName);
    }
  } catch (JedisException je) {
    jedis.close();
    throw je;
  }

  return new DefaultPooledObject<Jedis>(jedis);

}
 
Example #5
Source File: CommonsObjectPool2MetricsTest.java    From micrometer with Apache License 2.0 6 votes vote down vote up
private void createGenericObjectPool() {
    genericObjectPoolCount++;
    GenericObjectPoolConfig<Object> config = new GenericObjectPoolConfig<>();
    config.setMaxTotal(10);

    new GenericObjectPool<>(new BasePooledObjectFactory<Object>() {
        @Override
        public Object create() {
            return new Object();
        }

        @Override
        public PooledObject<Object> wrap(Object testObject) {
            return new DefaultPooledObject<>(testObject);
        }
    }, config);
}
 
Example #6
Source File: FTPClientFactory.java    From hsweb-framework with Apache License 2.0 6 votes vote down vote up
public PooledObject<FTPClient> makeObject() throws Exception {
    FTPClient ftpClient = new FTPClient();
    ftpClient.setConnectTimeout(config.getClientTimeout());
    ftpClient.connect(config.getHost(), config.getPort());
    int reply = ftpClient.getReplyCode();
    if (!FTPReply.isPositiveCompletion(reply)) {
        ftpClient.disconnect();
        logger.warn("FTPServer refused connection");
        return null;
    }
    boolean result = ftpClient.login(config.getUsername(), config.getPassword());
    if (!result) {
        throw new ConnectException("ftp登陆失败:" + config.getUsername() + "/password:" + config.getPassword() + "@" + config.getHost());
    }
    ftpClient.setFileType(config.getTransferFileType());
    ftpClient.setBufferSize(1024);
    ftpClient.setControlEncoding(config.getEncoding());
    if (config.isPassiveMode()) {
        ftpClient.enterLocalPassiveMode();
    }
    return new DefaultPooledObject<>(ftpClient);

}
 
Example #7
Source File: JedisFactory.java    From feeyo-redisproxy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public PooledObject<JedisConnection> makeObject() throws Exception {
	final HostAndPort hostAndPort = this.hostAndPort.get();

	final JedisConnection jedis = new JedisConnection(hostAndPort.getHost(), hostAndPort.getPort(),
			connectionTimeout, soTimeout);

	try {
		jedis.connect();
		if (password != null) {
			jedis.sendCommand(RedisCommand.AUTH, password);
			jedis.getStatusCodeReply();
		}
	} catch (JedisException je) {
		jedis.close();
		throw je;
	}

	return new DefaultPooledObject<JedisConnection>(jedis);

}
 
Example #8
Source File: SmtpConnectionFactory.java    From smtp-connection-pool with Apache License 2.0 5 votes vote down vote up
@Override
public PooledObject<ClosableSmtpConnection> makeObject() throws Exception {
  LOG.debug("makeObject");

  Transport transport = transportFactory.getTransport(session);
  connectionStrategy.connect(transport);

  DefaultClosableSmtpConnection closableSmtpTransport = new DefaultClosableSmtpConnection(transport, invalidateConnectionOnException);
  initDefaultListeners(closableSmtpTransport);

  return new DefaultPooledObject(closableSmtpTransport);
}
 
Example #9
Source File: SuppliedPooledObjectFactoryTests.java    From vividus with Apache License 2.0 5 votes vote down vote up
@Test
void testWrap()
{
    PooledObject<String> actual = factory.wrap(VALUE);
    assertThat(actual, instanceOf(DefaultPooledObject.class));
    assertEquals(VALUE, actual.getObject());
}
 
Example #10
Source File: JenkinsFactory.java    From seppb with MIT License 5 votes vote down vote up
@Override
public PooledObject<JenkinsClient> makeObject() throws Exception {
    final JenkinsClient jenkinsClient = new JenkinsClient(url, username, password, clientBuilder());
    try {
        jenkinsClient.isRunning();
    } catch (Exception e) {
        jenkinsClient.close();
        throw e;
    }
    return new DefaultPooledObject<>(jenkinsClient);
}
 
Example #11
Source File: ElasticSearchClientFactory.java    From elasticsearch-pool with Apache License 2.0 5 votes vote down vote up
public PooledObject<RestHighLevelClient> makeObject() throws Exception {
    HttpHost[] nodes = new HttpHost[nodesReference.get().size()];
    List<HttpHost> nodeList = new ArrayList<HttpHost>();
    for(HostAndPort each: nodesReference.get()){
        nodeList.add(new HttpHost(each.getHost(),each.getPort(),each.getSchema()));
    }
    nodes = nodeList.toArray(nodes);
    RestClientBuilder clientBuilder = RestClient.builder(nodes);
    RestHighLevelClient client = new RestHighLevelClient(clientBuilder);
    return new DefaultPooledObject(client);
}
 
Example #12
Source File: ValidatingPoolableLdapConnectionFactory.java    From directory-ldap-api with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 * 
 * Specifically, we are creating a new connection based on the LdapConnection Factory
 * we used to create this pool of connections. The default is to create bound connections.
 * 
 * @throws LdapException If unable to connect.
 */
@Override
public PooledObject<LdapConnection> makeObject() throws LdapException
{
    if ( LOG.isDebugEnabled() )
    {
        LOG.debug( I18n.msg( I18n.MSG_04150_CREATING_LDAP_CONNECTION ) );
    }
    
    return new DefaultPooledObject<LdapConnection>( new MonitoringLdapConnection( connectionFactory.newLdapConnection() ) );
}
 
Example #13
Source File: AbstractPoolableLdapConnectionFactory.java    From directory-ldap-api with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 * Specifically, we are creating a new connection based on the LdapConnection Factory
 * we used to create this pool of connections. The default is to create bound connections.
 * 
 * @throws LdapException If unable to connect.
 */
@Override
public PooledObject<LdapConnection> makeObject() throws LdapException
{
    if ( LOG.isDebugEnabled() )
    {
        LOG.debug( I18n.msg( I18n.MSG_04150_CREATING_LDAP_CONNECTION ) );
    }
    
    return new DefaultPooledObject<>( connectionFactory.newLdapConnection() );
}
 
Example #14
Source File: CommonsObjectPool2MetricsTest.java    From micrometer with Apache License 2.0 5 votes vote down vote up
private void createGenericKeyedObjectPool() {
    new GenericKeyedObjectPool<>(new BaseKeyedPooledObjectFactory<Object, Object>() {
        @Override
        public Object create(Object key) {
            return key;
        }

        @Override
        public PooledObject<Object> wrap(Object value) {
            return new DefaultPooledObject<>(value);
        }
    });
}
 
Example #15
Source File: ThriftConnectionFactory.java    From ThriftJ with Apache License 2.0 5 votes vote down vote up
@Override
public PooledObject<TTransport> makeObject(ThriftServer thriftServer) throws Exception {
	TSocket tsocket = new TSocket(thriftServer.getHost(), thriftServer.getPort());
	tsocket.setTimeout(timeout);
	TFramedTransport transport = new TFramedTransport(tsocket);
	
	transport.open();
	DefaultPooledObject<TTransport> result = new DefaultPooledObject<TTransport>(transport);
	logger.trace("Make new thrift connection: {}:{}", thriftServer.getHost(), thriftServer.getPort());
	
	return result;
}
 
Example #16
Source File: WsClientFactory.java    From timely with Apache License 2.0 5 votes vote down vote up
@Override
public PooledObject<WebSocketSubscriptionClient> makeObject(TimelyBalancedHost k) throws Exception {

    int bufferSize = balancerConfig.getWebsocket().getIncomingBufferSize();
    WebSocketSubscriptionClient client = new WebSocketSubscriptionClient(sslContext, k.getHost(), k.getHttpPort(),
            k.getWsPort(), balancerConfig.getSecurity().getClientSsl().isUseClientCert(),
            balancerConfig.isLoginRequired(), "", "",
            balancerConfig.getSecurity().getClientSsl().isHostVerificationEnabled(), bufferSize);
    return new DefaultPooledObject<>(client);
}
 
Example #17
Source File: PooledCloseableHttpClientFactory.java    From timely with Apache License 2.0 5 votes vote down vote up
@Override
public PooledObject<CloseableHttpClient> makeObject() throws Exception {
    RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(connectionRequestTimeout)
            .setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout).build();
    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setDefaultRequestConfig(requestConfig);
    builder.setConnectionTimeToLive(connectionTimeToLive, TimeUnit.MILLISECONDS);
    return new DefaultPooledObject<>(builder.build());
}
 
Example #18
Source File: ProcessFactory.java    From jasperreports with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void activateObject(PooledObject<PhantomJSProcess> pooledObject) throws Exception
{
	super.activateObject(pooledObject);
	
	PhantomJSProcess process = pooledObject.getObject();
	if (process.hasEnded())
	{
		if (log.isDebugEnabled())
		{
			log.debug(process.getId() + " has ended");
		}
		
		throw new JRRuntimeException("Process " + process.getId() + " has ended");
	}
	
	long borrowedCount = ((DefaultPooledObject<PhantomJSProcess>) pooledObject).getBorrowedCount();
	if (borrowedCount >= expirationCount)
	{
		if (log.isDebugEnabled())
		{
			log.debug(process.getId() + " borrow count " + borrowedCount 
					+ " exceeded expiration count " + expirationCount);
		}
		
		throw new JRRuntimeException("Process " + process.getId() + " borrow count exceeded");
	}
	
	long now = System.currentTimeMillis();
	if (now >= pooledObject.getCreateTime() + expirationTime)
	{
		if (log.isDebugEnabled())
		{
			log.debug(process.getId() + " expiration time " + expirationTime 
					+ " from " + pooledObject.getCreateTime() + " exceeded");
		}
		
		throw new JRRuntimeException("Process " + process.getId() + " expiration time exceeded");
	}
}
 
Example #19
Source File: SslEnabledNettyClientFactory.java    From x-pipe with Apache License 2.0 5 votes vote down vote up
@Override
public PooledObject<NettyClient> makeObject(Endpoint key) {
    ProxyEndpoint endpoint = (ProxyEndpoint) key;
    ChannelFuture f = getBootstrap(endpoint).connect(key.getHost(), key.getPort());
    NettyClient nettyClient = new AsyncNettyClient(f, key);
    f.channel().attr(NettyClientHandler.KEY_CLIENT).set(nettyClient);
    return new DefaultPooledObject<>(nettyClient);
}
 
Example #20
Source File: NettyKeyedPoolClientFactory.java    From x-pipe with Apache License 2.0 5 votes vote down vote up
@Override
public PooledObject<NettyClient> makeObject(Endpoint key) throws Exception {

	ChannelFuture f = b.connect(key.getHost(), key.getPort());
	NettyClient nettyClient = new AsyncNettyClient(f, key);
	f.channel().attr(NettyClientHandler.KEY_CLIENT).set(nettyClient);
	return new DefaultPooledObject<NettyClient>(nettyClient);
}
 
Example #21
Source File: NettyClientFactory.java    From x-pipe with Apache License 2.0 5 votes vote down vote up
@Override
public PooledObject<NettyClient> makeObject() throws Exception {

	ChannelFuture f = b.connect(endpoint.getHost(), endpoint.getPort());
	f.get(connectTimeoutMilli, TimeUnit.MILLISECONDS);
	Channel channel = f.channel();
	sendProxyProtocolIfNeeded(channel);
	logger.info("[makeObject]{}", channel);
	NettyClient nettyClient = new DefaultNettyClient(channel);
	channel.attr(NettyClientHandler.KEY_CLIENT).set(nettyClient);
	return new DefaultPooledObject<NettyClient>(nettyClient);
}
 
Example #22
Source File: TcpRpcEndpoint.java    From nutzcloud with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("resource")
@Override
      public PooledObject<SocketHolder> makeObject(SocketAddress addr) throws Exception {
          SocketHolder socketHolder = new SocketHolder();
          Socket socket = new Socket();
          socket.connect(addr, 1000);
          socketHolder.socket = socket;
          socketHolder.dis = new DataInputStream(socket.getInputStream());
          socketHolder.dos = new DataOutputStream(socket.getOutputStream());
          return new DefaultPooledObject<TcpRpcEndpoint.SocketHolder>(socketHolder);
      }
 
Example #23
Source File: CacheObjectFactory.java    From AutoLoadCache with Apache License 2.0 4 votes vote down vote up
@Override
public PooledObject<ReadByteBuf> wrap(ReadByteBuf obj) {
    return new DefaultPooledObject<>(obj);
}
 
Example #24
Source File: PooledConnectionFactory.java    From fastdfs-java-client with Apache License 2.0 4 votes vote down vote up
/**
 * 将对象池化pooledObject
 */
@Override
public PooledObject<Connection> wrap(Connection conn) {
    return new DefaultPooledObject<Connection>(conn);
}
 
Example #25
Source File: CommonsPoolImpl.java    From ikasoa with MIT License 4 votes vote down vote up
@Override
public PooledObject<ThriftSocket> wrap(ThriftSocket thriftSocket) {
	return new DefaultPooledObject<>(thriftSocket);
}
 
Example #26
Source File: ProcessFactory.java    From jasperreports with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public PooledObject<PhantomJSProcess> wrap(PhantomJSProcess process)
{
	return new DefaultPooledObject<PhantomJSProcess>(process);
}
 
Example #27
Source File: ShardedJedisPool.java    From cachecloud with Apache License 2.0 4 votes vote down vote up
@Override
public PooledObject<ShardedJedis> makeObject() throws Exception {
  ShardedJedis jedis = new ShardedJedis(shards, algo, keyTagPattern);
  return new DefaultPooledObject<ShardedJedis>(jedis);
}
 
Example #28
Source File: CarreraConnectionFactory.java    From DDMQ with Apache License 2.0 4 votes vote down vote up
@Override
public PooledObject<CarreraConnection> wrap(CarreraConnection value) {
    return new DefaultPooledObject<>(value);
}
 
Example #29
Source File: BasicHerdDBDataSource.java    From herddb with Apache License 2.0 4 votes vote down vote up
@Override
public PooledObject<HerdDBConnection> makeObject() throws Exception {
    HerdDBConnection res = new HerdDBConnection(BasicHerdDBDataSource.this, getHDBConnection(), defaultSchema);
    return new DefaultPooledObject<>(res);
}
 
Example #30
Source File: ReactorRabbitMQChannelPool.java    From james-project with Apache License 2.0 4 votes vote down vote up
@Override
public PooledObject<Channel> wrap(Channel obj) {
    return new DefaultPooledObject<>(obj);
}