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) 

Source Link

Document

Create a new GenericObjectPool using the specified factory.

Usage

From source file:edu.illinois.imunit.examples.apache.pool.TestGenericObjectPool.java

public void setUp() throws Exception {
    super.setUp();
    pool = new GenericObjectPool(new SimpleFactory());
}

From source file:de.othsoft.codeGen.requirements.jdbc.ConnectionFactory.java

private void initPool() throws DaoException {
    if (_connectionPool != null) {
        return;//from ww w.ja v  a  2s  . c  om
    }
    if (conStr == null) {
        throw new DaoException(log, "connection string is needed");
    }
    if (userStr == null) {
        throw new DaoException(log, "user name is needed");
    }
    if (pwdStr == null) {
        throw new DaoException(log, "password is needed");
    }
    if (testStr == null) {
        throw new DaoException(log, "sql statement for connection test is needed");
    }
    String driverClassName = null;
    if (conStr.contains("postgresql")) {
        driverClassName = "org.postgresql.Driver";
    } else if (conStr.contains("oracle")) {
        driverClassName = "oracle.jdbc.driver.OracleDriver";
    } else {
        throw new DaoException(log, "unknown driver for conStr=" + conStr);
    }
    try {
        Class.forName(driverClassName);
    } catch (ClassNotFoundException e) {
        throw new DaoException(log, e);
    }

    if (log.isInfoEnabled()) {
        log.info("init connection pool with: user=" + userStr + ", conStr=" + conStr);
    }
    org.apache.commons.dbcp.ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(conStr,
            userStr, pwdStr);
    _connectionPool = new GenericObjectPool(null);
    PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,
            _connectionPool, null, testStr, false, true);
    _dataSource = new PoolingDataSource(_connectionPool);
}

From source file:ManualPoolingDataSourceExample.java

public static DataSource setupDataSource(String connectURI) {
    ///*from w ww. j  av  a2  s  .  c  o m*/
    // 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.
    //
    ObjectPool connectionPool = new GenericObjectPool(null);

    //
    // 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.
    //
    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(connectURI, null);

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

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

    return dataSource;
}

From source file:com.glaf.core.jdbc.connection.DBCPConnectionProvider.java

@SuppressWarnings({ "rawtypes", "unchecked" })
public void configure(Properties props) throws RuntimeException {
    String jdbcDriverClass = props.getProperty(DBConfiguration.JDBC_DRIVER);
    String jdbcUrl = props.getProperty(DBConfiguration.JDBC_URL);
    Properties connectionProps = ConnectionProviderFactory.getConnectionProperties(props);

    log.info("DBCP using driver: " + jdbcDriverClass + " at URL: " + jdbcUrl);
    log.info("Connection properties: " + PropertiesHelper.maskOut(connectionProps, "password"));

    autocommit = PropertiesHelper.getBoolean(DBConfiguration.JDBC_AUTOCOMMIT, props);
    log.info("autocommit mode: " + autocommit);

    if (jdbcDriverClass == null) {
        log.warn("No JDBC Driver class was specified by property " + DBConfiguration.JDBC_DRIVER);
    } else {//ww w  .  j a v a  2 s. co m
        try {
            Class.forName(jdbcDriverClass);
        } catch (ClassNotFoundException cnfe) {
            try {
                ClassUtils.classForName(jdbcDriverClass);
            } catch (Exception e) {
                String msg = "JDBC Driver class not found: " + jdbcDriverClass;
                log.error(msg, e);
                throw new RuntimeException(msg, e);
            }
        }
    }

    String dbUser = props.getProperty(DBConfiguration.JDBC_USER);
    String dbPassword = props.getProperty(DBConfiguration.JDBC_PASSWORD);

    if (dbUser == null) {
        dbUser = ""; // Some RDBMS (e.g Postgresql) don't like null
                     // usernames
    }

    if (dbPassword == null) {
        dbPassword = ""; // Some RDBMS (e.g Postgresql) don't like null
                         // passwords
    }

    // Create the actual pool of connections
    ObjectPool connectionPool = new GenericObjectPool(null);

    // Apply any properties
    if (props.getProperty(ConnectionConstants.PROP_MAXIDLE) != null) {
        int value = PropertiesHelper.getInt(ConnectionConstants.PROP_MAXIDLE, props, 0);
        if (value > 0) {
            ((GenericObjectPool) connectionPool).setMaxIdle(value);
        }
    }
    if (props.getProperty(ConnectionConstants.PROP_MINIDLE) != null) {
        int value = PropertiesHelper.getInt(ConnectionConstants.PROP_MINIDLE, props, 0);
        if (value > 0) {
            ((GenericObjectPool) connectionPool).setMinIdle(value);
        }
    }
    if (props.getProperty(ConnectionConstants.PROP_MAXACTIVE) != null) {
        int value = PropertiesHelper.getInt(ConnectionConstants.PROP_MAXACTIVE, props, 0);
        if (value > 0) {
            ((GenericObjectPool) connectionPool).setMaxActive(value);
        }
    }
    if (props.getProperty(ConnectionConstants.PROP_MAXWAIT) != null) {
        int value = PropertiesHelper.getInt(ConnectionConstants.PROP_MAXWAIT, props, 0);
        if (value > 0) {
            ((GenericObjectPool) connectionPool).setMaxWait(value);
        }
    }
    // how often should the evictor run (if ever, default is -1 = off)
    if (props.getProperty(ConnectionConstants.PROP_TIMEBETWEENEVICTIONRUNSMILLIS) != null) {
        int value = PropertiesHelper.getInt(ConnectionConstants.PROP_TIMEBETWEENEVICTIONRUNSMILLIS, props, 0);
        if (value > 0) {
            ((GenericObjectPool) connectionPool).setTimeBetweenEvictionRunsMillis(value);

            // in each eviction run, ecict at least a fourth of "maxIdle"
            // connections
            int maxIdle = ((GenericObjectPool) connectionPool).getMaxIdle();
            int numTestsPerEvictionRun = (int) Math.ceil(((double) maxIdle / 4));
            ((GenericObjectPool) connectionPool).setNumTestsPerEvictionRun(numTestsPerEvictionRun);
        }
    }
    // how long may a connection sit idle in the pool before it may be
    // evicted
    if (props.getProperty(ConnectionConstants.PROP_MINEVICTABLEIDLETIMEMILLIS) != null) {
        int value = PropertiesHelper.getInt(ConnectionConstants.PROP_MINEVICTABLEIDLETIMEMILLIS, props, 0);
        if (value > 0) {
            ((GenericObjectPool) connectionPool).setMinEvictableIdleTimeMillis(value);
        }
    }

    // Create a factory to be used by the pool to create the connections
    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(jdbcUrl, dbUser, dbPassword);

    // Create a factory for caching the PreparedStatements
    KeyedObjectPoolFactory kpf = null;
    if (props.getProperty(ConnectionConstants.PROP_MAXSTATEMENTS) != null) {
        int value = PropertiesHelper.getInt(ConnectionConstants.PROP_MAXSTATEMENTS, props, 0);
        if (value > 0) {
            kpf = new StackKeyedObjectPoolFactory(null, value);
        }
    }

    // Wrap the connections and statements with pooled variants
    try {
        String testSQL = null;
        if (props.getProperty(ConnectionConstants.PROP_VALIDATIONQUERY) != null) {
            testSQL = PropertiesHelper.getString(ConnectionConstants.PROP_VALIDATIONQUERY, props, null);
        }
        new PoolableConnectionFactory(connectionFactory, connectionPool, kpf, testSQL, false, false);
        if (testSQL != null) {
            ((GenericObjectPool) connectionPool).setTestOnBorrow(true);
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        log.error("could not instantiate DBCP connection pool", ex);
        throw new ConnectionPoolException("DBCP", jdbcDriverClass, jdbcUrl, ex);
    }

    ds = new PoolingDataSource(connectionPool);

    Connection conn = null;
    try {
        conn = ds.getConnection();
        if (conn == null) {
            throw new RuntimeException("DBCP connection pool can't get jdbc connection");
        }
    } catch (SQLException ex) {
        ex.printStackTrace();
        throw new RuntimeException(ex);
    } finally {
        JdbcUtils.close(conn);
    }

    String i = props.getProperty(DBConfiguration.JDBC_ISOLATION);
    if (i == null) {
        isolation = null;
    } else {
        isolation = new Integer(i);
        log.info("JDBC isolation level: " + DBConfiguration.isolationLevelToString(isolation.intValue()));
    }

}

From source file:com.glaf.jbpm.connection.DbcpConnectionProvider.java

@SuppressWarnings({ "rawtypes", "unchecked" })
public void configure(Properties props) throws RuntimeException {
    String jdbcDriverClass = props.getProperty(Environment.DRIVER);
    String jdbcUrl = props.getProperty(Environment.URL);
    Properties connectionProps = ConnectionProviderFactory.getConnectionProperties(props);

    log.info("DBCP using driver: " + jdbcDriverClass + " at URL: " + jdbcUrl);
    log.info("Connection properties: " + PropertiesHelper.maskOut(connectionProps, "password"));

    autocommit = PropertiesHelper.getBoolean(Environment.AUTOCOMMIT, props);
    log.info("autocommit mode: " + autocommit);

    if (jdbcDriverClass == null) {
        log.warn("No JDBC Driver class was specified by property " + Environment.DRIVER);
    } else {//from w w  w .  j a  v a  2 s . co m
        try {
            Class.forName(jdbcDriverClass);
        } catch (ClassNotFoundException cnfe) {
            try {
                ClassUtils.classForName(jdbcDriverClass);
            } catch (Exception e) {
                String msg = "JDBC Driver class not found: " + jdbcDriverClass;
                log.error(msg, e);
                throw new RuntimeException(msg, e);
            }
        }
    }

    String dbUser = props.getProperty(Environment.USER);
    String dbPassword = props.getProperty(Environment.PASS);

    if (dbUser == null) {
        dbUser = "";
    }

    if (dbPassword == null) {
        dbPassword = "";
    }

    Properties properties = new Properties();

    for (Iterator<Object> ii = props.keySet().iterator(); ii.hasNext();) {
        String key = (String) ii.next();
        if (key.startsWith("hibernate.dbcp.")) {
            String newKey = key.substring(15);
            properties.put(newKey, props.get(key));
        }
    }

    // Create the actual pool of connections
    ObjectPool connectionPool = new GenericObjectPool(null);

    if (props.getProperty("hibernate.connection.maxIdle") != null) {
        int value = PropertiesHelper.getInt("hibernate.connection.maxIdle", props, 0);
        if (value > 0) {
            ((GenericObjectPool) connectionPool).setMaxIdle(value);
        }
    }

    if (props.getProperty("hibernate.connection.minIdle") != null) {
        int value = PropertiesHelper.getInt("hibernate.connection.minIdle", props, 0);
        if (value > 0) {
            ((GenericObjectPool) connectionPool).setMinIdle(value);
        }
    }

    if (props.getProperty("hibernate.connection.maxActive") != null) {
        int value = PropertiesHelper.getInt("hibernate.connection.maxActive", props, 0);
        if (value > 0) {
            ((GenericObjectPool) connectionPool).setMaxActive(value);
        }
    }

    if (props.getProperty("hibernate.connection.maxWait") != null) {
        int value = PropertiesHelper.getInt("hibernate.connection.maxWait", props, 0);
        if (value > 0) {
            ((GenericObjectPool) connectionPool).setMaxWait(value);
        }
    }

    // how often should the evictor run (if ever, default is -1 = off)
    if (props.getProperty("hibernate.connection.timeBetweenEvictionRunsMillis") != null) {
        int value = PropertiesHelper.getInt("hibernate.connection.timeBetweenEvictionRunsMillis", props, 0);
        if (value > 0) {
            ((GenericObjectPool) connectionPool).setTimeBetweenEvictionRunsMillis(value);

            // in each eviction run, ecict at least a fourth of "maxIdle"
            // connections
            int maxIdle = ((GenericObjectPool) connectionPool).getMaxIdle();
            int numTestsPerEvictionRun = (int) Math.ceil(((double) maxIdle / 4));
            ((GenericObjectPool) connectionPool).setNumTestsPerEvictionRun(numTestsPerEvictionRun);
        }
    }
    // how long may a connection sit idle in the pool before it may be
    // evicted
    if (props.getProperty("hibernate.connection.minEvictableIdleTimeMillis") != null) {
        int value = PropertiesHelper.getInt("hibernate.connection.minEvictableIdleTimeMillis", props, 0);
        if (value > 0) {
            ((GenericObjectPool) connectionPool).setMinEvictableIdleTimeMillis(value);
        }
    }

    // Create a factory to be used by the pool to create the connections
    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(jdbcUrl, dbUser, dbPassword);

    // Create a factory for caching the PreparedStatements
    KeyedObjectPoolFactory kpf = null;

    if (props.getProperty("hibernate.connection.maxStatements") != null) {
        int value = PropertiesHelper.getInt("hibernate.connection.maxStatements", props, 0);
        if (value > 0) {
            kpf = new StackKeyedObjectPoolFactory(null, value);
        }
    } else {
        kpf = new StackKeyedObjectPoolFactory(null, 200);
    }

    // Wrap the connections and statements with pooled variants
    try {
        String testSQL = null;
        if (props.getProperty("hibernate.connection.testSQL") != null) {
            testSQL = PropertiesHelper.getString("hibernate.connection.testSQL", props, null);
        }
        new PoolableConnectionFactory(connectionFactory, connectionPool, kpf, testSQL, false, false);
        if (testSQL != null) {
            ((GenericObjectPool) connectionPool).setTestOnBorrow(true);
        }
    } catch (Exception e) {
        throw new ConnectionPoolException("DBCP", jdbcDriverClass, jdbcUrl, e);
    }

    ds = new PoolingDataSource(connectionPool);

    Connection conn = null;
    try {
        conn = ds.getConnection();
        if (conn == null) {
            throw new RuntimeException("DBCP connection pool can't get jdbc connection");
        }
    } catch (SQLException ex) {
        throw new RuntimeException(ex);
    } finally {
        JdbcUtils.close(conn);
    }

    String i = props.getProperty(Environment.ISOLATION);
    if (i == null) {
        isolation = null;
    } else {
        isolation = new Integer(i);
        log.info("JDBC isolation level: " + Environment.isolationLevelToString(isolation.intValue()));
    }

}

From source file:ManualPoolingDriverExample.java

public static void setupDriver(String connectURI) throws Exception {
    ///*from  ww  w. ja va 2s .  com*/
    // 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.
    //
    ObjectPool connectionPool = new GenericObjectPool(null);

    //
    // 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.
    //
    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(connectURI, null);

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

    //
    // Finally, we create the PoolingDriver itself...
    //
    Class.forName("org.apache.commons.dbcp.PoolingDriver");
    PoolingDriver driver = (PoolingDriver) DriverManager.getDriver("jdbc:apache:commons:dbcp:");

    //
    // ...and register our pool with it.
    //
    driver.registerPool("example", connectionPool);

    //
    // Now we can just use the connect string "jdbc:apache:commons:dbcp:example"
    // to access our pool of Connections.
    //
}

From source file:com.jt.dbcp.example.ManualPoolingDataSourceExample.java

public static DataSource setupDataSource(String connectURI) {
    ////from  ww w  .j  a  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.
    //
    ObjectPool connectionPool = new GenericObjectPool(null);

    //
    // 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.
    //
    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(connectURI, "root", "root");

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

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

    return dataSource;
}

From source file:com.jt.dbcp.example.ManualPoolingDriverExample.java

public static void setupDriver(String connectURI) throws Exception {
    ///*  w  w w  .  java  2 s.c  o  m*/
    // 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.
    //
    ObjectPool connectionPool = new GenericObjectPool(null);

    //
    // 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.
    //
    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(connectURI, "root", "root");

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

    //
    // Finally, we create the PoolingDriver itself...
    //
    Class.forName("org.apache.commons.dbcp.PoolingDriver");
    PoolingDriver driver = (PoolingDriver) DriverManager.getDriver("jdbc:apache:commons:dbcp:");

    //
    // ...and register our pool with it.
    //
    driver.registerPool("example", connectionPool);

    //
    // Now we can just use the connect string "jdbc:apache:commons:dbcp:example"
    // to access our pool of Connections.
    //
}

From source file:Pool162.java

public void testWhenExhaustedBlockInterupt() throws Exception {
    GenericObjectPool pool = new GenericObjectPool(new SimpleFactory());
    //Set this value to 1 to get the deadlock. No deadlock when it sets to 
    //other values.
    pool.setMaxActive(2);//from www  .  j  a va 2  s  . c  om
    pool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_BLOCK);

    Object obj1 = pool.borrowObject();

    // Make sure one object was obtained
    if (obj1 == null) {
        throw new Exception("obj1 is null");
    }

    // Create a separate thread to try and borrow another object
    WaitingTestThread wtt = new WaitingTestThread(pool, 200);
    wtt.start();
    // Give wtt time to start
    Thread.sleep(200);
    //bug trigger #1
    wtt.interrupt();
    //bug trigger #1
    // Give interrupt time to take effect
    Thread.sleep(200);
    // Return object to the pool
    pool.returnObject(obj1);
    Object obj2 = null;
    obj2 = pool.borrowObject();
    if (obj2 == null) {
        throw new Exception("obj2 is null");
    }
    pool.returnObject(obj2);
    pool.close();
}

From source file:com.stgmastek.birt.report.ReportService.java

/**
 * Initializes the service.//from   ww  w . j  av a  2s . c  o  m
 * @param config
 * @throws ReportServiceException
 */
private void initialize(EngineConfigWrapper configWrapper) {
    //// Create Executor Service to hold ReportService Instance
    Integer size = new Integer((String) configWrapper.getEngineConfig().getProperty("threadPoolSize"));
    this.service = Executors.newFixedThreadPool(size.intValue());
    try {
        Platform.startup(configWrapper.getEngineConfig());
    } catch (BirtException e) {
        throw new ReportServiceException(e.getMessage(), e);
    }

    //// Engine Object Pool
    pool = new GenericObjectPool(new BIRTEngineFactory(configWrapper.getEngineConfig()));
    pool.setMaxActive(size);
    pool.setTimeBetweenEvictionRunsMillis(TimeUnit.MINUTES.toMillis(5));
    initialized = true;
    logger.debug("ReportService pool initialized !! Total Pool size : [" + size + "]");
}