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

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

Introduction

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

Prototype

public GenericObjectPool(PooledObjectFactory<T> factory) 

Source Link

Document

Create a new GenericObjectPool using defaults from GenericObjectPoolConfig .

Usage

From source file:ch.cyberduck.core.pool.DefaultSessionPoolTest.java

@Test
public void testCheckReconnectApplicationFailure() throws Exception {
    final AtomicBoolean interrupt = new AtomicBoolean();
    final Host bookmark = new Host(new TestProtocol());
    final TestLoginConnectionService connect = new TestLoginConnectionService() {
        @Override/*from   w  w w  .  ja  v a2 s  .co m*/
        public boolean check(final Session<?> session, final Cache<Path> cache, final CancelCallback callback)
                throws BackgroundException {
            return true;
        }
    };
    final DefaultSessionPool pool = new DefaultSessionPool(connect,
            new DefaultVaultRegistry(new DisabledPasswordCallback()), PathCache.empty(),
            new DisabledTranscriptListener(), bookmark,
            new GenericObjectPool<Session>(new PooledSessionFactory(connect, new DisabledX509TrustManager(),
                    new DefaultX509KeyManager(), PathCache.empty(), bookmark,
                    new DefaultVaultRegistry(new DisabledPasswordCallback())) {
                @Override
                public Session create() {
                    return new NullSession(bookmark) {
                        @Override
                        public void interrupt() throws BackgroundException {
                            interrupt.set(true);
                            super.interrupt();
                        }
                    };
                }
            }));
    final Session<?> session = pool.borrow(BackgroundActionState.running);
    pool.release(session, new BackgroundException("m", "d"));
    assertFalse(interrupt.get());
}

From source file:com.github.brandtg.switchboard.TestMysqlReplicationApplier.java

private PoolingDataSource<PoolableConnection> getDataSource() throws Exception {
    // DBCP2 pool
    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(jdbc, "root", "");
    ObjectName poolName = new ObjectName(JdbcBasedLogIndex.class.getCanonicalName(),
            URLEncoder.encode(jdbc, "UTF-8"), "replicatorConnectionPool");
    PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,
            poolName);//from   w  w w  .j a  v  a 2 s  . com
    ObjectPool<PoolableConnection> connectionPool = new GenericObjectPool<PoolableConnection>(
            poolableConnectionFactory);
    poolableConnectionFactory.setPool(connectionPool);
    return new PoolingDataSource<PoolableConnection>(connectionPool);
}

From source file:net.identio.server.service.authentication.ldap.LdapAuthenticationProvider.java

private void initPool(List<LdapAuthMethod> ldapAuthMethods) {

    for (LdapAuthMethod ldapAuthMethod : ldapAuthMethods) {

        LOG.debug("* Auth Method: {}", ldapAuthMethod.getName());

        LdapConnectionFactory factory = new LdapConnectionFactory(ldapAuthMethod);

        GenericObjectPool<InitialLdapContext> pool = new GenericObjectPool<>(factory);

        LdapAuthenticationProviderConfiguration.LdapPoolConfig poolConfig = ldapAuthMethod.getPoolConfig();

        pool.setMinIdle(poolConfig.getMinIdleConnections());
        pool.setMaxIdle(poolConfig.getMaxIdleConnections());
        pool.setBlockWhenExhausted(true);
        pool.setTestWhileIdle(poolConfig.isTestWhileIdle());
        pool.setTestOnBorrow(poolConfig.isTestOnBorrow());
        pool.setTimeBetweenEvictionRunsMillis(1000 * poolConfig.getTimeBetweenEvictionRuns());
        pool.setNumTestsPerEvictionRun(poolConfig.getNumTestsPerEvictionRun());
        pool.setMinEvictableIdleTimeMillis(1000 * poolConfig.getMinEvictableIdleTime());

        pools.put(ldapAuthMethod.getName(), pool);

    }/*w  ww.  j  ava2 s  .  co  m*/
}

From source file:hornet.framework.clamav.service.ClamAVCheckService.java

/**
 * Constructeur./*from w ww. ja v  a  2s .c  o m*/
 */
public ClamAVCheckService() {

    super();
    this.socketPool = new GenericObjectPool<SocketChannel>(new PooledSocketFactory());
}

From source file:de.alexandria.cms.config.SpringConfigBackendDatabase.java

private ObjectPool<PoolableConnection> getObjectPool() {
    PoolableConnectionFactory poolableConnectionFactory = getPoolableConnectionFactory();
    ObjectPool<PoolableConnection> connectionPool = new GenericObjectPool<>(poolableConnectionFactory);
    // Set the factory's pool property to the owning pool
    poolableConnectionFactory.setPool(connectionPool);
    return connectionPool;
}

From source file:eu.peppol.persistence.jdbc.OxalisDataSourceFactoryDbcpImplTest.java

private PoolingDataSource createPoolingDataSource(ConnectionFactory driverConnectionFactory) {

    PoolableConnectionFactory poolableConnectionFactory = null;
    try {// w  w  w.j a  v a 2  s .  co  m

        poolableConnectionFactory = new PoolableConnectionFactory(driverConnectionFactory,
                new ObjectName("no.difi.oxalis", "connectionPool", "TestPool"));

        GenericObjectPool<PoolableConnection> pool = new GenericObjectPool<PoolableConnection>(
                poolableConnectionFactory);
        poolableConnectionFactory.setPool(pool);
        poolableConnectionFactory.setValidationQuery("select 1");
        return new PoolingDataSource(pool);

    } catch (MalformedObjectNameException e) {
        throw new IllegalStateException("Unable to create poolable conneciton factory: " + e.getMessage(), e);
    }

}

From source file:com.github.brandtg.switchboard.JdbcBasedLogIndex.java

@Override
public void start() throws Exception {
    Class.forName(driverClass);/*from   ww  w .  j a v a 2 s .c o m*/
    LOG.info("Loaded driver {}", driverClass);

    // DBCP2 pool
    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(connectionString, user, password);
    ObjectName poolName = new ObjectName(JdbcBasedLogIndex.class.getCanonicalName(),
            URLEncoder.encode(connectionString, ENCODING), "indexConnectionPool");
    PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,
            poolName);
    ObjectPool<PoolableConnection> connectionPool = new GenericObjectPool<PoolableConnection>(
            poolableConnectionFactory);
    poolableConnectionFactory.setPool(connectionPool);
    this.dataSource = new PoolingDataSource<PoolableConnection>(connectionPool);
    LOG.info("Opened connection pool to {} as {}", connectionString, user);

    createTable();
}

From source file:com.adaptris.core.PoolingWorkflow.java

private GenericObjectPool<Worker> createObjectPool() {
    GenericObjectPool<Worker> pool = new GenericObjectPool<>(new WorkerFactory());
    long lifetime = threadLifetimeMs();
    pool.setMaxTotal(poolSize());/*from   w w  w.  j  a  va  2s  .  co m*/
    pool.setMinIdle(minIdle());
    pool.setMaxIdle(maxIdle());
    pool.setMaxWaitMillis(-1L);
    pool.setBlockWhenExhausted(true);
    pool.setSoftMinEvictableIdleTimeMillis(lifetime);
    pool.setTimeBetweenEvictionRunsMillis(lifetime + ThreadLocalRandom.current().nextLong(lifetime));
    return pool;
}

From source file:com.ibm.broker.analytics.r.RNode.java

/**
 * Called by Integration Bus after an instance of this node has been created and configured, but before it processes any messages.
 * @throws MbException if an exception occurs initializing this node.
 *//*from w ww . j  a v  a 2 s  .  c  o m*/
public void onInitialize() throws MbException {
    final String methodName = "onInitialize";

    // Load the RData file if one has been provided.
    iRDataFile = !iRDataFileProperty.isEmpty() ? new RNodeFile(this, iRDataFileProperty) : null;

    // Parse the connect script if one has been provided.
    iConnectScript = !iConnectScriptProperty.isEmpty() ? new RNodeScript(this, iConnectScriptProperty) : null;

    // Parse the evaluate script, which must always be provided.
    if (iEvaluateScriptProperty.isEmpty()) {
        throw new RNodeException(this, methodName, 7868, "Unrecognised parameter type", getName());
    }
    iEvaluateScript = new RNodeScript(this, iEvaluateScriptProperty);

    // Parse the disconnect script if one has been provided.
    iDisconnectScript = !iDisconnectScriptProperty.isEmpty() ? new RNodeScript(this, iDisconnectScriptProperty)
            : null;

    // Parse the namespace bindings table if one has been provided.
    iNamespaceBindings = new MbNamespaceBindings();
    MbTable nsMappingTable = (MbTable) getUserDefinedAttribute("nsMappingTable");
    if (nsMappingTable != null) {
        for (nsMappingTable.first(); nsMappingTable.lastMove(); nsMappingTable.next()) {
            String prefix = (String) nsMappingTable.getValue("nsPrefix");
            String uri = (String) nsMappingTable.getValue("namespace");
            iNamespaceBindings.addBinding(prefix, uri);
        }
    }

    // Mapping of variable and data frames to names.
    Map<String, RNodeVariable> variables = new HashMap<>();
    Map<String, RNodeDataFrame> dataFrames = new HashMap<>();

    // Parse the parameter table if one has been provided.
    MbTable parameterTable = (MbTable) getUserDefinedAttribute("parameterTable");
    if (parameterTable != null) {

        // Loop over all rows in the parameter table.
        for (parameterTable.first(); parameterTable.lastMove(); parameterTable.next()) {

            // Grab the parameter types from the row.
            String dataFrame = (String) parameterTable.getValue("parameterDataFrame");
            String name = (String) parameterTable.getValue("parameterName");
            String stringType = (String) parameterTable.getValue("parameterType");
            RNodeType type;
            try {
                type = RNodeType.fromString(stringType);
            } catch (IllegalArgumentException iae) {
                throw new RNodeException(this, methodName, 7812, "Unrecognised parameter type", getName(), name,
                        stringType);
            }
            String stringDirection = (String) parameterTable.getValue("parameterDirection");
            RNodeDirection direction;
            try {
                direction = RNodeDirection.valueOf(stringDirection);
            } catch (IllegalArgumentException iae) {
                throw new RNodeException(this, methodName, 7813, "Unrecognised parameter direction", getName(),
                        name, stringDirection);
            }
            String xpathExpression = (String) parameterTable.getValue("xpathExpression");

            // Validate that it has a name and XPath expression.
            if (name == null || name.isEmpty()) {
                throw new RNodeException(this, methodName, 7814, "Parameter has an empty name", getName());
            } else if (xpathExpression == null || xpathExpression.isEmpty()) {
                throw new RNodeException(this, methodName, 7816, "Parameter has an empty XPath expression",
                        getName());
            }

            // Parse the XPath expression.
            MbXPath xpath = new MbXPath(xpathExpression, iNamespaceBindings);

            // If this is a data frame, create it.
            if (type == RNodeType.DATA_FRAME) {
                if (!dataFrames.containsKey(name)) {
                    dataFrames.put(name, new RNodeDataFrame(this, name, xpathExpression, xpath));
                } else {
                    throw new RNodeException(this, methodName, 7869, "Two data frames with the same name",
                            getName(), name);
                }

                // Else, if it's a column in a data frame column add it.
            } else if (dataFrame != null && !dataFrame.isEmpty()) {
                RNodeDataFrame actualDataFrame = dataFrames.get(dataFrame);
                if (actualDataFrame != null) {
                    actualDataFrame.addColumn(name, type, direction, xpathExpression, xpath);
                } else {
                    throw new RNodeException(this, methodName, 7870, "Data frame does not exist", getName(),
                            actualDataFrame);
                }
                if (direction == RNodeDirection.IN || direction == RNodeDirection.INOUT) {
                    iInDataFrames.put(dataFrame, actualDataFrame);
                }
                if (direction == RNodeDirection.OUT || direction == RNodeDirection.INOUT) {
                    iOutDataFrames.put(dataFrame, actualDataFrame);
                }

                // Else, create a variable.
            } else {
                RNodeVariable variable = new RNodeVariable(this, name, type, direction, xpathExpression, xpath);
                if (!variables.containsKey(name)) {
                    variables.put(name, variable);
                } else {
                    throw new RNodeException(this, methodName, 7815, "Two variables with the same name",
                            getName(), name);
                }
                if (direction == RNodeDirection.IN || direction == RNodeDirection.INOUT) {
                    iInVariables.put(name, variable);
                }
                if (direction == RNodeDirection.OUT || direction == RNodeDirection.INOUT) {
                    iOutVariables.put(name, variable);
                }
            }

        }

    }

    // Catch any exceptions - we must shutdown the pool if we fail to open a connecton.
    try {

        // Create a new connection pool for this node.
        iConnectionPool = new GenericObjectPool<Connection>(iConnectionFactory);

        // Configure the connection pool.
        iConnectionPool.setMaxTotal(iMaximumConnections);
        iConnectionPool.setMaxIdle(Integer.MAX_VALUE);
        iConnectionPool.setMinIdle(iMinimumConnections);
        iConnectionPool.setMinEvictableIdleTimeMillis(Long.MAX_VALUE);
        iConnectionPool.setSoftMinEvictableIdleTimeMillis(iIdleConnectionTimeout * 1000);
        iConnectionPool.setNumTestsPerEvictionRun(iMaximumConnections);
        iConnectionPool.setTimeBetweenEvictionRunsMillis(100);

    } catch (Exception e) {

        // Shutdown the pool and rethrow the exception.
        if (iConnectionPool != null) {
            iConnectionPool.close();
            iConnectionPool = null;
        }
        throw e;

    }

}

From source file:com.tremolosecurity.provisioning.core.ProvisioningEngineImpl.java

private void initLocalBroker() throws ProvisioningException {
    if (this.isInternalQueue()) {
        this.broker = BrokerHolder.getInstance(cfgMgr, "local", this);

    } else {/*from w ww. j a  v  a 2 s  .  co m*/

        this.mpPools = new ArrayList<GenericObjectPool<MessageProducerHolder>>();

        if (this.cfgMgr.getCfg().getProvisioning().getQueueConfig().isMultiTaskQueues()) {
            for (int j = 1; j <= this.cfgMgr.getCfg().getProvisioning().getQueueConfig().getNumQueues(); j++) {
                String name = this.cfgMgr.getCfg().getProvisioning().getQueueConfig().getTaskQueueName()
                        .replace("{x}", Integer.toString(j));
                GenericObjectPool<MessageProducerHolder> lpool = new GenericObjectPool<MessageProducerHolder>(
                        new PooledMessageProducerFactory(this.cfgMgr, this, name));
                lpool.setMaxTotal(this.cfgMgr.getCfg().getProvisioning().getQueueConfig().getMaxProducers());
                this.mpPools.add(lpool);
            }
        } else {
            this.mpPools = new ArrayList<GenericObjectPool<MessageProducerHolder>>();
            GenericObjectPool<MessageProducerHolder> lpool = new GenericObjectPool<MessageProducerHolder>(
                    new PooledMessageProducerFactory(this.cfgMgr, this,
                            this.cfgMgr.getCfg().getProvisioning().getQueueConfig().getTaskQueueName()));
            lpool.setMaxTotal(this.cfgMgr.getCfg().getProvisioning().getQueueConfig().getMaxProducers());
            this.mpPools.add(lpool);
        }

        this.cfgMgr.addThread(new StopableThread() {

            @Override
            public void run() {
                // TODO Auto-generated method stub

            }

            @Override
            public void stop() {
                for (GenericObjectPool<MessageProducerHolder> mpPool : mpPools) {
                    mpPool.close();
                    mpPool.clear();
                }

            }

        });
    }
}