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() 

Source Link

Document

Create a new GenericObjectPool with default properties.

Usage

From source file:com.adaptris.core.services.splitter.ServiceWorkerPoolLegacyTest.java

@Test
public void testCloseQuietly() {
    closeQuietly((GenericObjectPool) null);
    closeQuietly(new GenericObjectPool());
    closeQuietly(new GenericObjectPool() {

        @Override/*from   w  w  w.  j  a v  a2 s.c  o m*/
        public void close() throws Exception {
            throw new Exception();
        }

    });
}

From source file:com.tera.common.database.factory.AbstractDatabaseFactory.java

/**
 * @param dbConfig/*from  w ww .ja  v a  2  s.com*/
 * @throws Error
 */
void createConnectionPool(DatabaseConfiguration dbConfig) throws Error {
    log.info("Creating DB pool");
    connectionPool = new GenericObjectPool();
    connectionPool.setMaxIdle(dbConfig.getConnectionsIdelMax());
    connectionPool.setMinIdle(dbConfig.getConnectionsIdleMin());
    connectionPool.setMaxActive(dbConfig.getConnectionsActiveMax());
    connectionPool.setTestOnBorrow(true);

    try {
        dataSource = setupDataSource(dbConfig);
        Connection c = getConnection();
        DatabaseMetaData dmd = c.getMetaData();
        databaseName = dmd.getDatabaseProductName();
        databaseMajorVersion = dmd.getDatabaseMajorVersion();
        databaseMinorVersion = dmd.getDatabaseMinorVersion();
        c.close();
    } catch (Exception e) {
        log.error("Error with connection string: {}", dbConfig, e);
        throw new Error("DatabaseFactory not initialized!");
    }
    log.info("Successfully connected to the database");
}

From source file:com.aionemu.commons.database.DatabaseFactory.java

public synchronized static void init(String configFilePath) {
    if (dataSource != null) {
        return;/*from   w  ww  .  ja  va2s.c  om*/
    }

    if (!configFilePath.equals("")) {
        try {
            Properties dbProps = PropertiesUtils.load(configFilePath);
            ConfigurableProcessor.process(DatabaseConfig.class, dbProps);
        } catch (IOException ex) {
            log.fatal("Cannot load database config", ex);
        }
    }

    try {
        DatabaseConfig.DATABASE_DRIVER.newInstance();
    } catch (Exception e) {
        log.fatal("Error obtaining DB driver", e);
        throw new Error("DB Driver doesnt exist!");
    }

    connectionPool = new GenericObjectPool();

    if (DatabaseConfig.DATABASE_CONNECTIONS_MIN > DatabaseConfig.DATABASE_CONNECTIONS_MAX) {
        log.error("Please check your database configuration. Minimum amount of connections is > maximum");
        DatabaseConfig.DATABASE_CONNECTIONS_MAX = DatabaseConfig.DATABASE_CONNECTIONS_MIN;
    }

    connectionPool.setMaxIdle(DatabaseConfig.DATABASE_CONNECTIONS_MIN);
    connectionPool.setMaxActive(DatabaseConfig.DATABASE_CONNECTIONS_MAX);
    /* test if connection is still valid before returning */
    //connectionPool.setTestOnBorrow(true);

    try {
        dataSource = setupDataSource();
        Connection c = getConnection();
        DatabaseMetaData dmd = c.getMetaData();
        databaseName = dmd.getDatabaseProductName();
        databaseMajorVersion = dmd.getDatabaseMajorVersion();
        databaseMinorVersion = dmd.getDatabaseMinorVersion();
        c.close();
    } catch (Exception e) {
        log.fatal("Error with connection string: " + DatabaseConfig.DATABASE_URL, e);
        throw new Error("DatabaseFactory not initialized!");
    }

    log.info("Successfully connected to database");
}

From source file:com.ibm.xsp.extlib.relational.jdbc.datasource.dbcp.DbcpPoolDataSource.java

/**
 * //w  w w. ja  va 2s.  c om
 */
public DbcpPoolDataSource(final String dataSourceName, final String driverClass, final String url,
        final String username, final String password, final int minIdle, final int maxIdle, final int maxActive,
        final long maxWait) throws PoolException {
    try {
        ds = AccessController.doPrivileged(new PrivilegedExceptionAction<DataSource>() {
            public DataSource run() throws Exception {
                // create a driver connection factory
                driver = JDBCDriverLoader.loadDriver(driverClass);

                Properties properties = new Properties();
                properties.setProperty("user", username); // $NON-NLS-1$
                properties.setProperty("password", (StringUtil.isEmpty(password) ? "" : password)); // $NON-NLS-1$

                ConnectionFactory connectionFactory = new DriverConnectionFactory(driver, url, properties);

                // create the pool
                pool = new GenericObjectPool();
                pool.setMaxActive(maxActive);
                pool.setMaxWait(maxWait);
                pool.setMaxIdle(maxIdle);
                pool.setMinIdle(minIdle);

                // create the pool object factory
                PoolableConnectionFactory factory = new PoolableConnectionFactory(connectionFactory, pool, null,
                        null, false, true);
                pool.setFactory(factory);

                // finally create the datasource
                PoolingDataSource bds = new PoolingDataSource(pool);

                return bds;
            }
        });

    } catch (Exception e) {
        String msg = "Unable to initialize the shared connection pool DataSource"; // $NLX-DbcpPoolDataSource.Unabletoinitializethesharedconnec-1$[["connection pool" is a technical term related to databases]]
        // Note, this resource key is used elsewhere in this plugin
        // "Unable to initialize the shared connection pool DataSource"
        //String msg = com.ibm.xsp.extlib.relational.ResourceHandler.getSpecialAudienceString("DbcpPoolDataSource.Unabletoinitializethesharedconnec");//$NON-NLS-1$
        throw new PoolException(e, msg);
    }
}

From source file:com.zotoh.core.db.JDBCPoolManager.java

private synchronized JDBCPool create(String pool, JDBCInfo param, Properties props) throws SQLException {
    if (existsPool(pool)) {
        throw new SQLException("Jdbc Pool already exists: " + pool);
    }//from   www  .jav  a 2  s.  co  m

    PoolableConnectionFactory pcf;
    DriverConnectionFactory dcf;
    GenericObjectPool gop;
    DBVendor dbv;
    ObjectPool p;
    Driver d;

    tlog().debug("JDBCPoolMgr: Driver : {}", param.getDriver());
    tlog().debug("JDBCPoolMgr: URL : {}", param.getUrl());

    //        Ute.loadDriver(param.getDriver());
    d = DriverManager.getDriver(param.getUrl());
    dbv = DBUte.getDBVendor(param);

    dcf = new DriverConnectionFactory(d, param.getUrl(), props);
    gop = new GenericObjectPool();
    gop.setMaxActive(asInt(props.getProperty("max-conns"), 10));
    gop.setTestOnBorrow(true);
    gop.setMaxIdle(gop.getMaxActive());
    gop.setMinIdle(asInt(props.getProperty("min-conns"), 2));
    gop.setMaxWait(asLong(props.getProperty("max-wait4-conn-millis"), 1500L));
    gop.setMinEvictableIdleTimeMillis(asLong(props.getProperty("evict-conn-ifidle-millis"), 300000L));
    gop.setTimeBetweenEvictionRunsMillis(asLong(props.getProperty("check-evict-every-millis"), 60000L));

    pcf = new PoolableConnectionFactory(dcf, gop, null, null, true, false);
    pcf.setDefaultReadOnly(false);
    p = pcf.getPool();

    JDBCPool j = new JDBCPool(dbv, param, p);
    _ps.put(pool, j);

    tlog().debug("JDBCPoolMgr: Added db pool: {}, info= {}", pool, param);
    return j;
}

From source file:de.xirp.db.XConnectionProvider.java

/**
 * This methos initializes the connection pool using the given
 * URL, user name and password./*from w ww.ja  va 2s  .com*/
 * 
 * @param url
 *            The db URL.
 * @param user
 *            The db user.
 * @param password
 *            The users password.
 */
private void initPool(String url, String user, String password) {

    connectionPool = new GenericObjectPool();
    connectionFactory = new DriverManagerConnectionFactory(url, user, password);
    poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, connectionPool, null, null,
            false, true);
    dataSource = new PoolingDataSource(connectionPool);

    dataSource.setAccessToUnderlyingConnectionAllowed(false);

    connectionPool.setMaxActive(MAX_ACTIVE);
    connectionPool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_GROW);
    connectionPool.setMinIdle(MIN_IDLE);
    connectionPool.setTimeBetweenEvictionRunsMillis(EVICTION_TIME);
    connectionPool.setTestOnBorrow(true);
    connectionPool.setTestWhileIdle(false);
    connectionPool.setTestOnReturn(false);

    ds = dataSource;
}

From source file:com.iciql.test.IciqlSuite.java

/**
 * Open a new Db object. All connections are cached and re-used to eliminate
 * embedded database startup costs./*from w w w.jav a  2  s.com*/
 * 
 * @return a fresh Db object
 */
public static Db openNewDb() {
    String testUrl = System.getProperty("iciql.url", DEFAULT_TEST_DB.url);
    String testUser = System.getProperty("iciql.user", DEFAULT_TEST_DB.username);
    String testPassword = System.getProperty("iciql.password", DEFAULT_TEST_DB.password);

    Db db = null;
    PoolingDataSource dataSource = dataSources.get(testUrl);
    if (dataSource == null) {
        ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(testUrl, testUser,
                testPassword);
        GenericObjectPool pool = new GenericObjectPool();
        pool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_GROW);
        PoolableConnectionFactory factory = new PoolableConnectionFactory(connectionFactory, pool, null, null,
                false, true);
        dataSource = new PoolingDataSource(pool);
        dataSources.put(testUrl, dataSource);
        connectionFactories.put(testUrl, factory);
    }
    db = Db.open(dataSource);

    // drop views
    db.dropView(ProductView.class);
    db.dropView(ProductViewInherited.class);
    db.dropView(ProductViewFromQuery.class);
    db.dropView(ProductViewInheritedComplex.class);

    // drop tables
    db.dropTable(BooleanModel.class);
    db.dropTable(ComplexObject.class);
    db.dropTable(Customer.class);
    db.dropTable(DefaultValuesModel.class);
    db.dropTable(EnumIdModel.class);
    db.dropTable(EnumOrdinalModel.class);
    db.dropTable(EnumStringModel.class);
    db.dropTable(Order.class);
    db.dropTable(PrimitivesModel.class);
    db.dropTable(Product.class);
    db.dropTable(ProductAnnotationOnly.class);
    db.dropTable(ProductInheritedAnnotation.class);
    db.dropTable(ProductMixedAnnotation.class);
    db.dropTable(SupportedTypes.class);
    db.dropTable(JoinTest.UserId.class);
    db.dropTable(JoinTest.UserNote.class);
    db.dropTable(EnumsTest.BadEnums.class);
    db.dropTable(MultipleBoolsModel.class);
    db.dropTable(ProductAnnotationOnlyWithForeignKey.class);
    db.dropTable(CategoryAnnotationOnly.class);

    return db;
}

From source file:com.iver.utiles.connections.ConnectionDB.java

/**
 * Registers in the driverpool a new connection
 * /*from   ww w.j  a  v a 2  s .  c o m*/
 * @param ct
 *            Data connection
 * @param driver
 *            Driver
 * 
 * @throws ConnectionException
 */
public void setupDriver(ConnectionTrans ct) throws ConnectionException {
    String url = ct.getConnBeginning() + "//" + ct.getHost() + ":" + ct.getPort() + "/" + ct.getDb();
    String user = ct.getUser();
    String password = ct.getPassword();
    String name = ct.getHost() + "_" + ct.getName();
    ObjectPool connectionPool = new GenericObjectPool();
    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(url, user, password);

    try {
        PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,
                connectionPool, null, null, false, true);
    } catch (Exception e) {
        throw new ConnectionException(JDBCManager.getTranslation("fallo_crear_pool"), e);
    }

    try {
        Class.forName("org.apache.commons.dbcp.PoolingDriver");
    } catch (ClassNotFoundException e) {
        throw new ConnectionException("Clase : " + "org.apache.commons.dbcp.PoolingDriver", e);
    }

    PoolingDriver driverPool;

    try {
        driverPool = (PoolingDriver) DriverManager.getDriver("jdbc:apache:commons:dbcp:");
    } catch (SQLException e) {
        throw new ConnectionException(JDBCManager.getTranslation("fallo_registrar_conexion"), e);
    }

    driverPool.registerPool(name, connectionPool);
    ct.setConnected(true);
}

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

public void testSetFactoryWithActiveObjects() throws Exception {
    GenericObjectPool pool = new GenericObjectPool();
    pool.setMaxIdle(10);/*from   ww  w  .ja  va  2s  . com*/
    pool.setFactory(new SimpleFactory());
    Object obj = pool.borrowObject();
    assertNotNull(obj);
    try {
        pool.setFactory(null);
        fail("Expected IllegalStateException");
    } catch (IllegalStateException e) {
        // expected
    }
    try {
        pool.setFactory(new SimpleFactory());
        fail("Expected IllegalStateException");
    } catch (IllegalStateException e) {
        // expected
    }
}

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

public void testSetFactoryWithNoActiveObjects() throws Exception {
    GenericObjectPool pool = new GenericObjectPool();
    pool.setMaxIdle(10);/* w ww.  j ava 2s  . c  o m*/
    pool.setFactory(new SimpleFactory());
    Object obj = pool.borrowObject();
    pool.returnObject(obj);
    assertEquals(1, pool.getNumIdle());
    pool.setFactory(new SimpleFactory());
    assertEquals(0, pool.getNumIdle());
}