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:com.adaptris.core.services.splitter.ServiceWorkerPool.java

public GenericObjectPool<Worker> createCommonsObjectPool() throws CoreException {
    GenericObjectPool<Worker> pool = new GenericObjectPool<>(new WorkerFactory());
    // Make the pool the same size as the thread pool
    pool.setMaxTotal(maxThreads);// ww w . ja v  a 2  s.  com
    pool.setMinIdle(maxThreads);
    pool.setMaxIdle(maxThreads);
    pool.setMaxWaitMillis(-1L);
    pool.setBlockWhenExhausted(true);
    pool.setSoftMinEvictableIdleTimeMillis(EVICT_RUN);
    pool.setTimeBetweenEvictionRunsMillis(EVICT_RUN + ThreadLocalRandom.current().nextLong(EVICT_RUN));
    return pool;
}

From source file:com.xtesoft.xtecuannet.framework.templater.filler.utils.SQLScanner.java

private DataSource setupDataSource() {
    //Loading driver
    loadDriver();/*  www  . ja  v a 2  s . co  m*/
    //
    // First, 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.
    //
    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(url, user, pass);

    //
    // Next 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,
            null);

    //
    // Now 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.
    //
    ObjectPool<PoolableConnection> connectionPool = new GenericObjectPool<>(poolableConnectionFactory);

    // Set the factory's pool property to the owning pool
    poolableConnectionFactory.setPool(connectionPool);

    //
    // Finally, we create the PoolingDriver itself,
    // passing in the object pool we created.
    //
    PoolingDataSource<PoolableConnection> dataSource1 = new PoolingDataSource<>(connectionPool);

    return dataSource1;
}

From source file:de.qucosa.dissemination.epicur.servlet.EpicurDisseminationServlet.java

@Override
public void init() {
    httpClient = HttpClientBuilder.create().setConnectionManager(new PoolingHttpClientConnectionManager())
            .build();//from w  w  w. j a v a 2s  .c om

    marshallerPool = new GenericObjectPool<>(new BasePooledObjectFactory<Marshaller>() {
        @Override
        public Marshaller create() throws Exception {
            Marshaller marshaller = JAXBContext.newInstance(Epicur.class).createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, XEPICUR_SCHEMA_LOCATION);
            return marshaller;
        }

        @Override
        public PooledObject<Marshaller> wrap(Marshaller marshaller) {
            return new DefaultPooledObject<>(marshaller);
        }
    });
}

From source file:io.seldon.dbcp.DbcpFactory.java

private void createDbcp(DbcpConfig conf) {
    if (!dataSources.containsKey(conf.name)) {
        try {//w  w w.j  av a  2 s.  c o  m

            Class.forName(conf.driverClassName);

            DriverManagerConnectionFactory cf = new DriverManagerConnectionFactory(conf.jdbc, conf.user,
                    conf.password);

            PoolableConnectionFactory pcf = new PoolableConnectionFactory(cf, null);
            pcf.setValidationQuery(conf.validationQuery);
            //, pool, null, conf.validationQuery, false, true,abandondedConfig);

            logger.info("Creating pool " + conf.toString());
            // create a generic pool
            GenericObjectPool<PoolableConnection> pool = new GenericObjectPool<PoolableConnection>(pcf);
            pool.setMaxTotal(conf.maxTotal);
            pool.setMaxIdle(conf.maxIdle);
            pool.setMinIdle(conf.minIdle);
            pool.setMaxWaitMillis(conf.maxWait);
            pool.setTimeBetweenEvictionRunsMillis(conf.timeBetweenEvictionRunsMillis);
            pool.setMinEvictableIdleTimeMillis(conf.minEvictableIdleTimeMillis);
            pool.setTestWhileIdle(conf.testWhileIdle);
            pool.setTestOnBorrow(conf.testOnBorrow);

            AbandonedConfig abandonedConfig = new AbandonedConfig();
            abandonedConfig.setRemoveAbandonedOnMaintenance(conf.removeAbanadoned);
            abandonedConfig.setRemoveAbandonedTimeout(conf.removeAbandonedTimeout);
            abandonedConfig.setLogAbandoned(conf.logAbandonded);

            pool.setAbandonedConfig(abandonedConfig);

            pcf.setPool(pool);
            DataSource ds = new PoolingDataSource(pool);
            dataSources.put(conf.name, ds);

        } catch (ClassNotFoundException e) {
            logger.error(
                    "Failed to create datasource for " + conf.name + " with class " + conf.driverClassName);
        }

    } else {
        logger.error("Pool " + conf.name + " already exists. Can't change existing datasource at present.");
    }
}

From source file:ch.ethz.coss.nervous.pulse.sql.SqlConnection.java

private DataSource setup() {

    try {//from  w  ww .  java  2  s  .co  m
        Class.forName("com.mysql.jdbc.Driver").newInstance();
    } catch (Exception e) {
        e.printStackTrace();
        Log.getInstance().append(Log.FLAG_ERROR, "Error loading the SQL driver");
        return null;
    }

    ConnectionFactory cf = null;
    try {
        cf = new DriverManagerConnectionFactory("jdbc:mysql://" + hostname + ":" + port + "/" + database,
                username, password);
        // System.out.println("CF - " + cf.toString());
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    PoolableConnectionFactory pcf = new PoolableConnectionFactory(cf, null);

    ObjectPool<PoolableConnection> connPool = new GenericObjectPool<PoolableConnection>(pcf);

    pcf.setPool(connPool);
    PoolingDataSource<PoolableConnection> dataSource = new PoolingDataSource<PoolableConnection>(connPool);
    // System.out.println("DataSource -- " + dataSource);
    return dataSource;
}

From source file:net.sf.jasperreports.phantomjs.ProcessDirector.java

private GenericObjectPool<PhantomJSProcess> createProcessPool(JRPropertiesUtil properties) {
    ProcessFactory processFactory = new ProcessFactory(this, properties);
    GenericObjectPool<PhantomJSProcess> pool = new GenericObjectPool<>(processFactory);
    pool.setLifo(true);//w w  w .ja v a  2 s. c o  m

    int maxProcessCount = properties.getIntegerProperty(PhantomJS.PROPERTY_PHANTOMJS_MAX_PROCESS_COUNT,
            PhantomJS.DEFAULT_PHANTOMJS_MAX_PROCESS_COUNT);
    pool.setMaxTotal(maxProcessCount);
    pool.setMaxIdle(maxProcessCount);

    int borrowTimeout = properties.getIntegerProperty(PhantomJS.PROPERTY_PHANTOMJS_POOL_BORROW_TIMEOUT,
            PhantomJS.DEFAULT_PHANTOMJS_POOL_BORROW_TIMEOUT);
    pool.setMaxWaitMillis(borrowTimeout);

    int idleTimeout = properties.getIntegerProperty(PhantomJS.PROPERTY_PHANTOMJS_IDLE_TIMEOUT,
            PhantomJS.DEFAULT_PHANTOMJS_IDLE_TIMEOUT);
    pool.setMinEvictableIdleTimeMillis(idleTimeout);

    pool.setTimeBetweenEvictionRunsMillis(idlePingInterval);

    pool.setTestWhileIdle(true);
    pool.setNumTestsPerEvictionRun(Integer.MAX_VALUE);

    pool.setSwallowedExceptionListener(new SwallowedExceptionListener() {
        @Override
        public void onSwallowException(Exception e) {
            if (log.isDebugEnabled()) {
                log.debug("Pool exception", e);
            }
        }
    });

    return pool;
}

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

/**
 * Verifies that we can create a pooled jdbc data source using the JDBC .jar-file supplied in the global configuration
 * file./*from w ww.j ava 2  s.  co m*/
 *
 * @throws Exception
 */
@Test
public void testLoadJdbcDriverUsingCustomClassLoader() throws Exception {
    ConnectionFactory driverConnectionFactory = createConnectionFactory(false);

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

    GenericObjectPool<PoolableConnection> pool = new GenericObjectPool<>(factory);
    factory.setPool(pool);

    pool.setMaxTotal(10);
    pool.setMaxWaitMillis(100);

    assertEquals(pool.getFactory(), factory);

    PoolableConnectionFactory pcf = (PoolableConnectionFactory) ((GenericObjectPool<?>) pool).getFactory();
    ObjectPool<PoolableConnection> pool1 = pcf.getPool();

    PoolingDataSource<PoolableConnection> poolingDataSource = new PoolingDataSource<>(pool);

    Connection connection = poolingDataSource.getConnection();
    assertNotNull(connection);

    Statement statement = connection.createStatement();
    ResultSet resultSet = statement.executeQuery("select current_date()");

    assertTrue(resultSet.next());
}

From source file:ddc.commons.jdbc.PooledDatasourceFactory.java

public DataSource createDataSource(JdbcConnectionFactory conn) throws ClassNotFoundException {
    conn.loadDriver();/*from  w  w  w  . j  a va2  s  . c om*/
    //
    // First, 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.
    //
    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(conn.getUrl(), conn.getUser(),
            conn.getPassword());

    //
    // Next 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,
            null);

    //
    // Now 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.
    //
    ObjectPool<PoolableConnection> connectionPool = new GenericObjectPool<PoolableConnection>(
            poolableConnectionFactory);

    // Set the factory's pool property to the owning pool
    poolableConnectionFactory.setPool(connectionPool);

    //
    // Finally, we create the PoolingDriver itself,
    // passing in the object pool we created.
    //
    DataSource ds = new PoolingDataSource<PoolableConnection>(connectionPool);
    return ds;
}

From source file:io.dockstore.common.BasicPostgreSQL.java

public BasicPostgreSQL(HierarchicalINIConfiguration settings) {
    if (dataSource == null) {
        try {//from   w ww . ja  v a  2  s .com
            String nullConfigs = "";
            String host = settings.getString(Constants.POSTGRES_HOST);
            if (host == null) {
                nullConfigs += "postgresHost ";
            }

            String user = settings.getString(Constants.POSTGRES_USERNAME);
            if (user == null) {
                nullConfigs += "postgresUser ";
            }

            String pass = settings.getString(Constants.POSTGRES_PASSWORD);
            if (pass == null) {
                nullConfigs += "postgresPass ";
            }

            String db = settings.getString(Constants.POSTGRES_DBNAME);
            if (db == null) {
                nullConfigs += "postgresDBName ";
            }

            String maxConnections = settings.getString(Constants.POSTGRES_MAX_CONNECTIONS, "5");

            if (!nullConfigs.trim().isEmpty()) {
                throw new NullPointerException("The following configuration values are null: " + nullConfigs
                        + ". Please check your configuration file.");
            }

            Class.forName("org.postgresql.Driver");

            String url = "jdbc:postgresql://" + host + "/" + db;
            LOG.debug("PostgreSQL URL is: " + url);
            Properties props = new Properties();
            props.setProperty("user", user);
            props.setProperty("password", pass);
            // props.setProperty("ssl","true");
            props.setProperty("initialSize", "5");
            props.setProperty("maxActive", maxConnections);

            ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(url, props);
            PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(
                    connectionFactory, null);
            poolableConnectionFactory.setValidationQuery("select count(*) from container;");
            ObjectPool<PoolableConnection> connectionPool = new GenericObjectPool<>(poolableConnectionFactory);
            poolableConnectionFactory.setPool(connectionPool);
            dataSource = new PoolingDataSource<>(connectionPool);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
}

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

@Test
public void testCheckReconnectSocketFailure() throws Exception {
    final AtomicBoolean interrupt = new AtomicBoolean();
    final Host bookmark = new Host(new TestProtocol());
    final TestLoginConnectionService connect = new TestLoginConnectionService() {
        @Override// ww w . j a  v  a 2 s.c  o 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", new SocketException("m")));
    assertTrue(interrupt.get());
}