Example usage for org.apache.commons.pool.impl GenericObjectPool GenericObjectPool

List of usage examples for org.apache.commons.pool.impl GenericObjectPool GenericObjectPool

Introduction

In this page you can find the example usage for org.apache.commons.pool.impl GenericObjectPool GenericObjectPool.

Prototype

public GenericObjectPool(PoolableObjectFactory factory, int maxActive) 

Source Link

Document

Create a new GenericObjectPool using the specified values.

Usage

From source file:com.soapsnake.thrift.license.rpc.ThriftServiceClientProxyFactory.java

@Override
public void afterPropertiesSet() throws Exception {
    //        zookeeper???,?
    //        if (serverAddress != null){
    //            addressProvider = new FixedAddressProvider(serverAddress);
    //        }//  w ww. j a  v a 2s. co m
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

    //?thrift serviceclass,,??class
    objectClass = classLoader.loadClass(service + "$Iface");

    //??
    Class<TServiceClientFactory<TServiceClient>> fi = (Class<TServiceClientFactory<TServiceClient>>) classLoader
            .loadClass(service + "$Client$Factory");

    //TServiceClientFactory
    TServiceClientFactory<TServiceClient> clientFactory = fi.newInstance();

    //
    ThriftClientPoolFactory clientPool = new ThriftClientPoolFactory(serverAddress, clientFactory, callback);
    //
    GenericObjectPool.Config poolConfig = new GenericObjectPool.Config();
    poolConfig.maxActive = maxActive;
    poolConfig.minIdle = 0;
    poolConfig.minEvictableIdleTimeMillis = idleTime;
    poolConfig.timeBetweenEvictionRunsMillis = idleTime / 2L;
    //:ThriftClientPoolFactory,config
    pool = new GenericObjectPool<>(clientPool, poolConfig);

    proxyClient = Proxy.newProxyInstance(classLoader, new Class[] { objectClass }, (o, method, objects) -> {
        //pool?client
        TServiceClient client = pool.borrowObject();
        try {
            return method.invoke(client, objects);
        } catch (Exception e) {
            throw e;
        } finally {
            pool.returnObject(client);
        }
    });
}

From source file:com.eyeq.pivot4j.datasource.PooledOlapDataSource.java

/**
 * @param factory/*from   www. ja va2s. c o  m*/
 * @param config
 * @return the pool
 */
protected GenericObjectPool<OlapConnection> createPool(PoolableObjectFactory<OlapConnection> factory,
        GenericObjectPool.Config config) {
    if (logger.isInfoEnabled()) {
        logger.info("Creating connection pool with following parameters : ");
        logger.info("   - max active : " + config.maxActive);
        logger.info("   - max idle : " + config.maxIdle);
        logger.info("   - min idle: " + config.minIdle);
        logger.info("   - max wait : " + config.maxWait);
    }
    return new GenericObjectPool<OlapConnection>(factory, config);
}

From source file:com.velix.jmongo.MongoImpl.java

private synchronized void findPrimary(Set<InetSocketAddress> hostSet) {
    connectionPool.getPoolLock().lock();
    connectionPool.closeDelegate();/*  w  w  w  . j  a v  a  2 s  . co  m*/
    SimpleConnectionPool delegate = new SimpleConnectionPool(new MongoProtocol());
    connectionPool.setDelegate(delegate);
    try {
        this.allHosts = new HashSet<InetSocketAddress>(hostSet.size());
        InetSocketAddress lastPrimary = null;
        for (InetSocketAddress inetAddress : hostSet) {
            allHosts.add(inetAddress);
            InetSocketAddress primary = checkPrimary(inetAddress, delegate);
            if (null == primary || primary.equals(lastPrimary)) {
                // throw new MongoException("can not find master db");
                continue;
            }
            if (null != lastPrimary && !lastPrimary.equals(primary)) {
                throw new MongoException("multi master db " + lastPrimary + " and " + primary);
            } else {
                lastPrimary = primary;
            }
        }
        if (null == lastPrimary) {
            throw new MongoException("can not find master db");
        }
        this.address = lastPrimary;
        factory = new PoolableConnectionFactory(this.address, new MongoProtocol());
        connectionPool
                .setDelegate(new CommonsConnectionPool(new GenericObjectPool(factory, this.configuration)));
    } finally {
        connectionPool.getPoolLock().unlock();
    }
}

From source file:com.honnix.jaxo.core.internal.services.PoolableCoreServiceImpl.java

@Override
public Validator getValidator(Schema schema) {
    /*//from w  ww.  j  ava2s.com
     * this looks stupid but to avoid lock, hope creating a GenericObjectPool does not cost too much
     * java suck with no lazy evaluation support
     */
    validatorObjectPoolMap.putIfAbsent(schema,
            new GenericObjectPool<Validator>(new ValidatorObjectFactory(schema), validatorConfig));
    ObjectPool<Validator> validatorObjectPool = validatorObjectPoolMap.get(schema);

    try {
        return validatorObjectPool.borrowObject();
    } catch (Exception e) {
        throw new JAXOException(e.getMessage(), e);
    }
}

From source file:com.toolsverse.etl.sql.connection.PooledAliasConnectionProvider.java

@Override
protected Connection createConnection(Alias alias) throws Exception {
    java.sql.Driver driver = (java.sql.Driver) Class.forName(alias.getJdbcDriverClass()).newInstance();

    DriverManager.registerDriver(driver);

    org.apache.commons.dbcp.ConnectionFactory connectionFactory = null;

    Properties props = Utils.getProperties(alias.getParams());

    String userId = alias.getUserId();
    String password = alias.getPassword();

    String url = alias.getUrl();//from  w  ww.  j a v  a2s.  c  om

    if (props.size() > 0) {
        if (!Utils.isNothing(userId)) {
            props.put("user", userId);
            if (!Utils.isNothing(password))
                props.put("password", password);
        }

        connectionFactory = new DriverManagerConnectionFactory(url, props);
    } else
        connectionFactory = new DriverManagerConnectionFactory(url, userId, password);

    ObjectPool connectionPool = new GenericObjectPool(null, _config);

    @SuppressWarnings("unused")
    PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,
            connectionPool, null, null, false, true);

    PoolingDataSource poolingDataSource = new PoolingDataSource(connectionPool);

    return poolingDataSource.getConnection();
}

From source file:com.att.cspd.SimpleSipServlet.java

@Override
public void init(ServletConfig servletConfig) throws ServletException {
    logger.info("the simple sip servlet has been started");
    super.init(servletConfig);

    RABBITMQ_CONN_URL = servletConfig.getInitParameter("rabbitmq_conn_url");
    EXCHANGE_NAME = servletConfig.getInitParameter("exchange_name");
    String pool_max_active = servletConfig.getInitParameter("rabbitmq_pool_max_active");
    String pool_max_idle = servletConfig.getInitParameter("rabbitmq_pool_max_idle");
    String pool_min_idle = servletConfig.getInitParameter("rabbitmq_pool_min_idle");
    String time_between_evication = servletConfig.getInitParameter("rabbitmq_pool_time_between_eviction");
    String idle_time_before_eviction = servletConfig
            .getInitParameter("rabbitmq_pool_idle_time_before_eviction");

    logger.info("INIT PARAM:  rabbitmq_conn_url = " + RABBITMQ_CONN_URL);
    logger.info("INIT PARAM : exchange name  = " + EXCHANGE_NAME);
    logger.info("INIT PARAM : pool max active = " + pool_max_active);
    logger.info("INIT PARAM : pool max idle  = " + pool_max_idle);
    logger.info("INIT PARAM : pool min idle = " + pool_min_idle);
    logger.info("INIT PARAM : time_between_evication  = " + time_between_evication);
    logger.info("INIT PARAM : idle_time_before_eviction  = " + idle_time_before_eviction);

    try {/* w w w .  j a va  2  s  .  com*/
        POOL_MAX_ACTIVE = Integer.parseInt(pool_max_active);
    } catch (NumberFormatException e) {
        logger.error("Impossible to parse the pool max active : " + pool_max_active, e);
    }

    try {
        POOL_MAX_IDLE = Integer.parseInt(pool_max_idle);
    } catch (NumberFormatException e) {
        logger.error("Impossible to parse the pool max idle : " + pool_max_idle, e);
    }

    try {
        POOL_MIN_IDLE = Integer.parseInt(pool_min_idle);
    } catch (NumberFormatException e) {
        logger.error("Impossible to parse the pool min idle  : " + pool_min_idle, e);
    }

    try {
        TIME_BETWEEN_EVICTION = Integer.parseInt(time_between_evication);
    } catch (NumberFormatException e) {
        logger.error("Impossible to parse the time between eviction : " + time_between_evication, e);
    }
    try {
        IDL_TIME_BEFORE_EVICTION = Integer.parseInt(idle_time_before_eviction);
    } catch (NumberFormatException e) {
        logger.error("Impossible to parse idle time before eviction : " + idle_time_before_eviction, e);
    }

    /**
     * create static instance of rabbitmq connection pool
     */
    try {

        GenericObjectPool.Config config = new GenericObjectPool.Config();
        config.maxActive = POOL_MAX_ACTIVE;
        config.maxIdle = POOL_MAX_IDLE;
        config.minIdle = POOL_MIN_IDLE;
        config.timeBetweenEvictionRunsMillis = TIME_BETWEEN_EVICTION;
        config.minEvictableIdleTimeMillis = IDL_TIME_BEFORE_EVICTION;
        config.testOnBorrow = true;
        config.testOnReturn = true;
        config.lifo = GenericObjectPool.DEFAULT_LIFO;
        config.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_FAIL;

        pool = new GenericObjectPool<Channel>(new ConnectionPoolableObjectFactory(RABBITMQ_CONN_URL), config);

        //create an initial pool instances.
        /*
        int initSize = 25;
        for (int i =0; i < initSize; i++) {
           try {
              pool.addObject();
           } catch (Exception e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
           }
        }
        */

        /*
        pool.setMaxActive(POOL_MAX_ACTIVE);   //maximum connection allowed in the pool (100). If reached, worker thread needs to be blocked to wait.
        pool.setMinIdle(POOL_MIN_IDLE);       //keep minimum idle connection (set to 3) in pool in all time.
        pool.setMaxIdle(POOL_MAX_IDLE);      //No minimum to create new connection when needed (set to -1).
        pool.setTimeBetweenEvictionRunsMillis(TIME_BETWEEN_EVICTION);   //wait up eviction thread in 10 second
        pool.setMinEvictableIdleTimeMillis(IDL_TIME_BEFORE_EVICTION);  //kill the idle connection that is 5 second old
        pool.setTestOnBorrow(true);   //sanity checking when getting connection from pool.
        pool.setTestOnReturn(true);   //sanity check when returning connection to pool.
        */

    } catch (IOException ex) {

        logger.error("RabbitMQ Pool failed to create. Error = " + ex.getMessage());
        throw new ServletException(ex);
    }

    //logger.info("HELLO... FINISHED LOADING THE RABBITMQ CONNECTION/CHANNEL POOL");

}

From source file:dev.utils.db.dbcp.ManualPoolingDataSource.java

public DataSource setupDataSource(String connectURI) {
    ///*  ww w  .  ja va  2 s  . c om*/
    // First, we'll need a ObjectPool that serves as the
    // actual pool of connections.
    //
    // We'll use a GenericObjectPool instance, although
    // any ObjectPool implementation will suffice.
    //

    GenericObjectPool.Config config = new GenericObjectPool.Config();
    config.maxActive = maxActive; // ex: 150;
    config.maxIdle = maxIdle; // ex: 100;
    config.minIdle = minIdle; //30;
    config.maxWait = maxWait; //1000;
    config.testOnBorrow = testOnBorrow;
    config.testOnReturn = testOnReturn;
    config.testWhileIdle = testWhileIdle;
    config.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
    config.numTestsPerEvictionRun = numTestsPerEvictionRun;
    config.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;

    ObjectPool connectionPool = new GenericObjectPool(null, config);

    //
    // Next, we'll create a ConnectionFactory that the
    // pool will use to create Connections.
    // We'll use the DriverManagerConnectionFactory,
    // using the connect string passed in the command line
    // arguments.
    //
    Properties connProps = new Properties();
    connProps.setProperty("user", username);
    connProps.setProperty("password", password);
    //p.setProperty("useUnicode", "true");
    //p.setProperty("characterEncoding", "UTF-8");

    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(connectURI, connProps);

    //
    // Now we'll create the PoolableConnectionFactory, which wraps
    // the "real" Connections created by the ConnectionFactory with
    // the classes that implement the pooling functionality.
    //
    PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,
            connectionPool, null, validationQuery, defaultReadOnly, defaultAutoCommit);

    //
    // Finally, we create the PoolingDriver itself,
    // passing in the object pool we created.
    //
    return new PoolingDataSource(connectionPool);
}

From source file:com.honnix.jaxo.core.internal.services.PoolableCoreServiceImpl.java

private void createPools(Map<String, GenericObjectPool.Config> configMap) {
    close();//from w w w  .ja  v a 2s  .c  o m

    objectPoolMap.put(DocumentBuilder.class.getName(), new GenericObjectPool<DocumentBuilder>(
            new DocumentBuilderObjectFactory(), configMap.get(DocumentBuilder.class.getName())));
    objectPoolMap.put(SAXParser.class.getName(), new GenericObjectPool<SAXParser>(new SAXParserObjectFactory(),
            configMap.get(SAXParser.class.getName())));
    objectPoolMap.put(XPath.class.getName(),
            new GenericObjectPool<XPath>(new XPathObjectFactory(), configMap.get(XPath.class.getName())));
    objectPoolMap.put(Transformer.class.getName(), new GenericObjectPool<Transformer>(
            new TransformerObjectFactory(), configMap.get(Transformer.class.getName())));
}

From source file:com.verisign.epp.pool.EPPSessionPool.java

/**
 * Initialize the pool with a specific <code>EPPSessionPoolableFactory</code> 
 * and <code>GenericObjectPool.Config</code> setting.
 * /*w  w w.  j a v  a  2  s .  co m*/
 * @param aFactory EPP session poolable object factory
 * @param aConfig Configuration attributes for pool
 */
public void init(EPPSessionPoolableFactory aFactory, GenericObjectPool.Config aConfig) {
    this.pool = new GenericObjectPool(aFactory, aConfig);

}

From source file:com.netspective.axiom.connection.JakartaCommonsDbcpConnectionProvider.java

protected DataSource createDataSource(ValueContext vc, String dataSourceId) throws NamingException {

    DataSourceInfo dataSourceInfo = (DataSourceInfo) dataSourcesInfo.get(dataSourceId);

    if (dataSourceInfo == null)
        throw new NamingException("Data Source: '" + dataSourceId
                + "' not defined as a data source for Jakarta Commons DBCP provider.");

    String driverClassName = dataSourceInfo.driverClass.getTextValueOrBlank(vc);
    try {/*from  ww  w .j  ava 2s.c om*/
        Class.forName(driverClassName);
    } catch (ClassNotFoundException cnfe) {
        log.error("Driver '" + driverClassName + "' not found for name '" + dataSourceId + "'");
        throw new NamingException("Driver '" + driverClassName + "' not found for name '" + dataSourceId + "'");
    }

    if (log.isDebugEnabled()) {
        log.debug("Initializing data source: '" + dataSourceInfo.getName() + "'\n"
                + "                  driver: '" + driverClassName + "'\n" + "                     url: '"
                + dataSourceInfo.url.getTextValueOrBlank(vc) + "'\n" + "                    user: '"
                + dataSourceInfo.user.getTextValueOrBlank(vc) + "'\n" + "                password: '"
                + dataSourceInfo.password.getTextValueOrBlank(vc) + "'");
    }

    ObjectPool connectionPool = new GenericObjectPool(null, dataSourceInfo.getPoolConfig());
    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(
            dataSourceInfo.url.getTextValueOrBlank(vc), dataSourceInfo.user.getTextValueOrBlank(vc),
            dataSourceInfo.password.getTextValueOrBlank(vc));
    try {
        //The reference to this object is not used within this method.  It's constuctor sets a reference of itself
        //in the conectionPool object we pass as a parameter.
        PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,
                connectionPool, null, null, false, true);
    } catch (IllegalStateException e) {
        log.error("Trying to reset the pool factory for data source: '" + dataSourceInfo.name
                + "' when the pool objects are already in use, thus the pool is active.");
        return null;
    }

    catch (Exception e) //Generic Exception being caught here because Constructor of PoolableConnectionFactory is declared that way
    {
        log.error(
                "An Exception was encountered when creating the pool factory in the Jakarta Commons DBCP framework.",
                e);
        return null;
    }

    DbcpPoolingDataSource dataSource = new DbcpPoolingDataSource(connectionPool);

    return dataSource;
}