Example usage for org.apache.commons.dbcp PoolableConnectionFactory PoolableConnectionFactory

List of usage examples for org.apache.commons.dbcp PoolableConnectionFactory PoolableConnectionFactory

Introduction

In this page you can find the example usage for org.apache.commons.dbcp PoolableConnectionFactory PoolableConnectionFactory.

Prototype

public PoolableConnectionFactory(ConnectionFactory connFactory, ObjectPool pool,
        KeyedObjectPoolFactory stmtPoolFactory, String validationQuery, boolean defaultReadOnly,
        boolean defaultAutoCommit) 

Source Link

Document

Create a new PoolableConnectionFactory.

Usage

From source file:org.apache.mahout.cf.taste.impl.model.jdbc.ConnectionPoolDataSource.java

public ConnectionPoolDataSource(DataSource underlyingDataSource) {
    Preconditions.checkNotNull(underlyingDataSource);
    ConnectionFactory connectionFactory = new ConfiguringConnectionFactory(underlyingDataSource);
    GenericObjectPool objectPool = new GenericObjectPool();
    objectPool.setTestOnBorrow(false);//from  w  w  w.  ja va2  s  . com
    objectPool.setTestOnReturn(false);
    objectPool.setTestWhileIdle(true);
    objectPool.setTimeBetweenEvictionRunsMillis(60 * 1000L);
    // Constructor actually sets itself as factory on pool
    new PoolableConnectionFactory(connectionFactory, objectPool, null, "SELECT 1", false, false);
    delegate = new PoolingDataSource(objectPool);
}

From source file:org.apache.oodt.cas.workflow.repository.DataSourceWorkflowRepositoryFactory.java

/**
 * <p>//  ww w .  j  ava 2  s  .co  m
 * Default Constructor
 * </p>.
 */
public DataSourceWorkflowRepositoryFactory() throws WorkflowException {
    String jdbcUrl, user, pass, driver;

    jdbcUrl = System.getProperty("org.apache.oodt.cas.workflow.repo.datasource.jdbc.url");
    user = System.getProperty("org.apache.oodt.cas.workflow.repo.datasource.jdbc.user");
    pass = System.getProperty("org.apache.oodt.cas.workflow.repo.datasource.jdbc.pass");
    driver = System.getProperty("org.apache.oodt.cas.workflow.repo.datasource.jdbc.driver");

    try {
        Class.forName(driver);
    } catch (ClassNotFoundException e) {
        throw new WorkflowException("Cannot load driver: " + driver);
    }

    GenericObjectPool connectionPool = new GenericObjectPool(null);
    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(jdbcUrl, user, pass);
    PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,
            connectionPool, null, null, false, true);

    dataSource = new PoolingDataSource(connectionPool);
}

From source file:org.apache.oodt.commons.database.DatabaseConnectionBuilder.java

public static DataSource buildDataSource(String user, String pass, String driver, String url) {

    DataSource ds;//w w  w  .j a  v  a  2 s.  co  m

    try {
        Class.forName(driver);
    } catch (ClassNotFoundException ignore) {
    }

    GenericObjectPool connectionPool = new GenericObjectPool(null);
    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(url, user, pass);
    PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,
            connectionPool, null, null, false, true);

    return new PoolingDataSource(connectionPool);
}

From source file:org.apache.wookie.server.Start.java

private static void configureServer() throws Exception {
    // create embedded jetty instance
    logger.info("Configuring Jetty server");
    server = new Server(port);

    // configure embedded jetty to handle wookie web application
    WebAppContext context = new WebAppContext();
    context.setServer(server);/*from  w  w  w.  ja v a2  s  .  c om*/
    context.setContextPath("/wookie");
    context.setWar("build/webapp/wookie");

    // enable and configure JNDI container resources
    context.setConfigurationClasses(new String[] { "org.mortbay.jetty.webapp.WebInfConfiguration",
            "org.mortbay.jetty.plus.webapp.EnvConfiguration", "org.mortbay.jetty.plus.webapp.Configuration",
            "org.mortbay.jetty.webapp.JettyWebXmlConfiguration",
            "org.mortbay.jetty.webapp.TagLibConfiguration" });
    if (persistenceManagerType.equals(PERSISTENCE_MANAGER_TYPE_JPA)) {
        logger.info("Configuring JPA persistence manager");

        // setup derby database directory and logging properties
        if (dbType.equals("derby") && dbUri.startsWith("jdbc:derby:")) {
            int dbUriArgsIndex = dbUri.indexOf(";", 11);
            if (dbUriArgsIndex == -1) {
                dbUriArgsIndex = dbUri.length();
            }
            String databasePath = dbUri.substring(11, dbUriArgsIndex);
            int databaseDirIndex = databasePath.lastIndexOf(File.separatorChar);
            if ((databaseDirIndex == -1) && (File.separatorChar != '/')) {
                databaseDirIndex = databasePath.lastIndexOf('/');
            }
            if (databaseDirIndex != -1) {
                String databaseDir = databasePath.substring(0, databaseDirIndex);
                File databaseDirFile = new File(databaseDir);
                if (!databaseDirFile.exists()) {
                    databaseDirFile.mkdirs();
                }
                String derbyLog = databaseDirFile.getAbsolutePath() + File.separator + "derby.log";
                System.setProperty("derby.stream.error.file", derbyLog);
            }
        }

        // Setup a database connection resource using DBCP
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName(dbDriver);
        dataSource.setUrl(dbUri);
        dataSource.setUsername(dbUser);
        dataSource.setPassword(dbPassword);
        dataSource.setMaxActive(80);
        dataSource.setMaxIdle(80);
        dataSource.setInitialSize(5);
        dataSource.setMaxOpenPreparedStatements(0);

        // Set up connection pool
        GenericObjectPool pool = new GenericObjectPool();
        // setup factory and pooling DataSource
        DataSourceConnectionFactory factory = new DataSourceConnectionFactory(dataSource);
        @SuppressWarnings("unused")
        PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(factory, pool, null,
                null, false, true);
        DataSource poolingDataSource = new PoolingDataSource(pool);

        new Resource(JPAPersistenceManager.WIDGET_DATABASE_JNDI_DATASOURCE_NAME, poolingDataSource);
    } else if (persistenceManagerType.equals(PERSISTENCE_MANAGER_TYPE_JCR)) {
        logger.info("Configuring JCR persistence manager");

        // setup repository directory and derby logging properties
        File repositoryDirFile = new File("widgetRepository");
        if (!repositoryDirFile.exists()) {
            repositoryDirFile.mkdirs();
        }
        String derbyLog = repositoryDirFile.getAbsolutePath() + File.separator + "derby.log";
        System.setProperty("derby.stream.error.file", derbyLog);

        // setup Jackrabbit JCR repository JNDI resource
        String repositoryConfig = repositoryDirFile.getAbsolutePath() + File.separator + "repository.xml";
        Repository repository = new TransientRepository(repositoryConfig, repositoryDirFile.getAbsolutePath());
        new Resource(JCRPersistenceManager.WIDGET_REPOSITORY_JNDI_REPOSITORY_NAME, repository);
    }

    // configure embedded jetty web application handler
    server.addHandler(context);

    // configure embedded jetty authentication realm
    HashUserRealm authedRealm = new HashUserRealm("Authentication Required", "etc/jetty-realm.properties");
    server.setUserRealms(new UserRealm[] { authedRealm });

    logger.info("Configured Jetty server");
}

From source file:org.apache.wookie.tests.beans.JPAPersistenceTest.java

/**
 * Set up JPA persistence runtime test environment.
 * /*from w  w  w .  j  ava2  s.  co  m*/
 * @throws Exception
 */
@Before
public void setUpPerTest() throws Exception {
    logger.info("JPA set up test");

    // load database configuration from environment
    String testDatabaseDir = (System.getProperty("user.dir") + "/build/test-database")
            .replace(File.separatorChar, '/');
    dbUser = getSystemProperty(DB_USER_PROPERTY_NAME, "java");
    dbPassword = getSystemProperty(DB_PASSWORD_PROPERTY_NAME, "java");
    dbDriver = getSystemProperty(DB_DRIVER_CLASS_PROPERTY_NAME, "org.apache.derby.jdbc.EmbeddedDriver");
    dbUri = getSystemProperty(DB_URI_PROPERTY_NAME, "jdbc:derby:" + testDatabaseDir + "/widgetdb;create=true");
    dbType = getSystemProperty(DB_TYPE_PROPERTY_NAME, "derby");

    // load driver
    Class.forName(dbDriver);

    // test connection
    Connection conn = DriverManager.getConnection(dbUri, dbUser, dbPassword);
    conn.close();

    // construct pooling datasource
    connectionPool = new GenericObjectPool(null, 0, GenericObjectPool.WHEN_EXHAUSTED_GROW, 0, 5);
    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(dbUri, dbUser, dbPassword);
    new PoolableConnectionFactory(connectionFactory, connectionPool, null, null, false, true);
    DataSource dataSource = new PoolingDataSource(connectionPool);

    // create JNDI context
    rootContext = new InitialContext();
    Context namingContext = lookupOrCreateNamingContext(rootContext, "java:comp");
    namingContext = lookupOrCreateNamingContext(namingContext, "env");
    lookupOrCreateNamingContext(namingContext, "jdbc");

    // bind datasource to JNDI context
    rootContext.rebind(JPAPersistenceManager.WIDGET_DATABASE_JNDI_DATASOURCE_FULL_NAME, dataSource);

    // initialize persistence manager factory and persistence manager;
    // truncate and initialize persistent store
    Configuration configuration = new PropertiesConfiguration();
    configuration.setProperty(PersistenceManagerFactory.PERSISTENCE_MANAGER_CLASS_NAME_PROPERTY_NAME,
            JPAPersistenceManager.class.getName());
    configuration.setProperty(PersistenceManagerFactory.PERSISTENCE_MANAGER_INITIALIZE_STORE_PROPERTY_NAME,
            "true");
    configuration.setProperty(JPAPersistenceManager.PERSISTENCE_MANAGER_CACHE_SIZE_PROPERTY_NAME, "1000");
    configuration.setProperty(JPAPersistenceManager.PERSISTENCE_MANAGER_DB_TYPE_PROPERTY_NAME, dbType);
    PersistenceManagerFactory.initialize(configuration);

    logger.info("JPA test set up");
    configured = true;
}

From source file:org.codehaus.griffon.runtime.datasource.DefaultDataSourceFactory.java

@Nonnull
@SuppressWarnings("ConstantConditions")
private DataSource createDataSource(@Nonnull Map<String, Object> config, @Nonnull String name) {
    String driverClassName = getConfigValueAsString(config, "driverClassName", "");
    requireNonBlank(driverClassName, "Configuration for " + name + ".driverClassName must not be blank");
    String url = getConfigValueAsString(config, "url", "");
    requireNonBlank(url, "Configuration for " + name + ".url must not be blank");

    try {/* w  w  w  .  j  a  v a  2s  .co  m*/
        getApplication().getApplicationClassLoader().get().loadClass(driverClassName);
    } catch (ClassNotFoundException e) {
        throw new GriffonException(e);
    }

    GenericObjectPool<DataSource> connectionPool = new GenericObjectPool<>(null);
    Map<String, Object> pool = getConfigValue(config, "pool", Collections.<String, Object>emptyMap());
    GriffonClassUtils.setPropertiesNoException(connectionPool, pool);

    String username = getConfigValueAsString(config, "username", "");
    String password = getConfigValueAsString(config, "password", "");
    ConnectionFactory connectionFactory = null;
    if (isBlank(username)) {
        connectionFactory = new DriverManagerConnectionFactory(url, null);
    } else {
        connectionFactory = new DriverManagerConnectionFactory(url, username, password);
    }

    new PoolableConnectionFactory(connectionFactory, connectionPool, null, null, false, true);
    return new PoolingDataSource(connectionPool);
}

From source file:org.dataconservancy.index.gqmpsql.DatabaseSessionPool.java

private static DataSource setupDataSource(String uri, String user, String pass) {
    if (LOG.isDebugEnabled()) {
        StringBuilder sb = new StringBuilder("Creating database session pool: ")
                .append("URL: {} User: {} Password: {}");
        LOG.debug(sb.toString(),/*from ww  w . ja  v a 2  s.  c  o m*/
                new Object[] { uri, user, (pass != null && pass.trim().length() != 0) ? "****" : pass });
    }
    ConnectionFactory cf = new DriverManagerConnectionFactory(uri, user, pass);

    ObjectPool pool = new GenericObjectPool();
    new PoolableConnectionFactory(cf, pool, null, null, false, false);

    return new PoolingDataSource(pool);
}

From source file:org.deegree.commons.jdbc.ConnectionPool.java

/**
 * Creates a new {@link ConnectionPool} instance.
 * /* ww w  .  j  ava  2s.  c  o  m*/
 * @param id
 * @param connectURI
 * @param user
 * @param password
 * @param readOnly
 * @param minIdle
 * @param maxActive
 */
public ConnectionPool(String id, String connectURI, String user, String password, boolean readOnly, int minIdle,
        int maxActive) {

    this.id = id;
    pool = new GenericObjectPool<Connection>(null);
    pool.setMinIdle(minIdle);
    pool.setMaxActive(maxActive);

    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(connectURI, user, password);
    // TODO make this configurable
    new PoolableConnectionFactory(connectionFactory, pool, null, null, readOnly, true);
    ds = new PoolingDataSource(pool);
    // needed, so users can retrieve the underlying connection from pooled
    // connections, e.g. to access the
    // LargeObjectManager from a PGConnection
    ds.setAccessToUnderlyingConnectionAllowed(true);
}

From source file:org.dspace.storage.rdbms.DataSourceInit.java

public static DataSource getDatasource() throws SQLException {
    if (dataSource != null) {
        return dataSource;
    }/*from  ww  w .  j av a 2  s  . c om*/

    try {
        // Register basic JDBC driver
        Class driverClass = Class.forName(ConfigurationManager.getProperty("db.driver"));
        Driver basicDriver = (Driver) driverClass.newInstance();
        DriverManager.registerDriver(basicDriver);

        // Read pool configuration parameter or use defaults
        // Note we check to see if property is null; getIntProperty returns
        // '0' if the property is not set OR if it is actually set to zero.
        // But 0 is a valid option...
        int maxConnections = ConfigurationManager.getIntProperty("db.maxconnections");

        if (ConfigurationManager.getProperty("db.maxconnections") == null) {
            maxConnections = 30;
        }

        int maxWait = ConfigurationManager.getIntProperty("db.maxwait");

        if (ConfigurationManager.getProperty("db.maxwait") == null) {
            maxWait = 5000;
        }

        int maxIdle = ConfigurationManager.getIntProperty("db.maxidle");

        if (ConfigurationManager.getProperty("db.maxidle") == null) {
            maxIdle = -1;
        }

        boolean useStatementPool = ConfigurationManager.getBooleanProperty("db.statementpool", true);

        // Create object pool
        ObjectPool connectionPool = new GenericObjectPool(null, // PoolableObjectFactory
                // - set below
                maxConnections, // max connections
                GenericObjectPool.WHEN_EXHAUSTED_BLOCK, maxWait, // don't
                // block
                // more than 5
                // seconds
                maxIdle, // max idle connections (unlimited)
                true, // validate when we borrow connections from pool
                false // don't bother validation returned connections
        );

        // ConnectionFactory the pool will use to create connections.
        ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(
                ConfigurationManager.getProperty("db.url"), ConfigurationManager.getProperty("db.username"),
                ConfigurationManager.getProperty("db.password"));

        //
        // Now we'll create the PoolableConnectionFactory, which wraps
        // the "real" Connections created by the ConnectionFactory with
        // the classes that implement the pooling functionality.
        //
        String validationQuery = "SELECT 1";

        // Oracle has a slightly different validation query
        if ("oracle".equals(ConfigurationManager.getProperty("db.name"))) {
            validationQuery = "SELECT 1 FROM DUAL";
        }

        GenericKeyedObjectPoolFactory statementFactory = null;
        if (useStatementPool) {
            // The statement Pool is used to pool prepared statements.
            GenericKeyedObjectPool.Config statementFactoryConfig = new GenericKeyedObjectPool.Config();
            // Just grow the pool size when needed.
            //
            // This means we will never block when attempting to
            // create a query. The problem is unclosed statements,
            // they can never be reused. So if we place a maximum
            // cap on them, then we might reach a condition where
            // a page can only be viewed X number of times. The
            // downside of GROW_WHEN_EXHAUSTED is that this may
            // allow a memory leak to exist. Both options are bad,
            // but I'd prefer a memory leak over a failure.
            //
            // FIXME: Perhaps this decision should be derived from config parameters?
            statementFactoryConfig.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_GROW;

            statementFactory = new GenericKeyedObjectPoolFactory(null, statementFactoryConfig);
        }

        PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,
                connectionPool, statementFactory, validationQuery, // validation query
                false, // read only is not default for now
                false); // Autocommit defaults to none

        //
        // Finally, we create the PoolingDataSource itself...
        //
        PoolingDataSource poolingDataSource = new PoolingDataSource();

        //
        // ...and register our pool with it.
        //
        poolingDataSource.setPool(connectionPool);

        dataSource = poolingDataSource;
        return poolingDataSource;
    } catch (Exception e) {
        // Need to be able to catch other exceptions. Pretend they are
        // SQLExceptions, but do log
        log.warn("Exception initializing DB pool", e);
        throw new SQLException(e.toString(), e);
    }
}

From source file:org.dspace.storage.rdbms.MockDatabaseManager.java

/**
 * Initialize the DatabaseManager.//ww w . j  a  va  2  s . co  m
 */
@Mock
private static synchronized void initialize() throws SQLException {
    if (initialized) {
        return;
    }

    try {
        // Register basic JDBC driver
        Class.forName(ConfigurationManager.getProperty("db.driver"));

        // Register the DBCP driver
        Class.forName("org.apache.commons.dbcp.PoolingDriver");

        // Read pool configuration parameter or use defaults
        // Note we check to see if property is null; getIntProperty returns
        // '0' if the property is not set OR if it is actually set to zero.
        // But 0 is a valid option...
        int maxConnections = ConfigurationManager.getIntProperty("db.maxconnections");

        if (ConfigurationManager.getProperty("db.maxconnections") == null) {
            maxConnections = 30;
        }

        int maxWait = ConfigurationManager.getIntProperty("db.maxwait");

        if (ConfigurationManager.getProperty("db.maxwait") == null) {
            maxWait = 5000;
        }

        int maxIdle = ConfigurationManager.getIntProperty("db.maxidle");

        if (ConfigurationManager.getProperty("db.maxidle") == null) {
            maxIdle = -1;
        }

        boolean useStatementPool = ConfigurationManager.getBooleanProperty("db.statementpool", true);

        // Create object pool
        connectionPool = new GenericObjectPool(null, // PoolableObjectFactory
                // - set below
                maxConnections, // max connections
                GenericObjectPool.WHEN_EXHAUSTED_BLOCK, maxWait, // don't
                // block
                // more than 5
                // seconds
                maxIdle, // max idle connections (unlimited)
                true, // validate when we borrow connections from pool
                false // don't bother validation returned connections
        );

        // ConnectionFactory the pool will use to create connections.
        ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(
                ConfigurationManager.getProperty("db.url"), ConfigurationManager.getProperty("db.username"),
                ConfigurationManager.getProperty("db.password"));

        //
        // Now we'll create the PoolableConnectionFactory, which wraps
        // the "real" Connections created by the ConnectionFactory with
        // the classes that implement the pooling functionality.
        //
        String validationQuery = "SELECT 1";

        // Oracle has a slightly different validation query
        if ("oracle".equals(ConfigurationManager.getProperty("db.name"))) {
            validationQuery = "SELECT 1 FROM DUAL";
        }

        GenericKeyedObjectPoolFactory statementFactory = null;
        if (useStatementPool) {
            // The statement Pool is used to pool prepared statements.
            GenericKeyedObjectPool.Config statementFactoryConfig = new GenericKeyedObjectPool.Config();
            // Just grow the pool size when needed.
            //
            // This means we will never block when attempting to
            // create a query. The problem is unclosed statements,
            // they can never be reused. So if we place a maximum
            // cap on them, then we might reach a condition where
            // a page can only be viewed X number of times. The
            // downside of GROW_WHEN_EXHAUSTED is that this may
            // allow a memory leak to exist. Both options are bad,
            // but I'd prefer a memory leak over a failure.
            //
            // Perhaps this decision should be derived from config parameters?
            statementFactoryConfig.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_GROW;

            statementFactory = new GenericKeyedObjectPoolFactory(null, statementFactoryConfig);
        }

        PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,
                connectionPool, statementFactory, validationQuery, // validation query
                false, // read only is not default for now
                false); // Autocommit defaults to none

        // Obtain a poolName from the config, default is "dspacepool"
        if (ConfigurationManager.getProperty("db.poolname") != null) {
            poolName = ConfigurationManager.getProperty("db.poolname");
        }

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

        //
        // ...and register our pool with it.
        //
        if (driver != null)
            driver.registerPool(poolName, connectionPool);

        //preload the contents of the database
        String s = new String();
        StringBuilder sb = new StringBuilder();

        String schemaPath = System.getProperty("db.schema.path");
        if (null == schemaPath)
            throw new IllegalArgumentException("System property db.schema.path must be defined");

        FileReader fr = new FileReader(new File(schemaPath));
        BufferedReader br = new BufferedReader(fr);

        while ((s = br.readLine()) != null) {
            //we skip white lines and comments
            if (!"".equals(s.trim()) && !s.trim().startsWith("--")) {
                sb.append(s);
            }
        }
        br.close();

        //we use ";" as a delimiter for each request. This assumes no triggers
        //nor other calls besides CREATE TABLE, CREATE SEQUENCE and INSERT
        //exist in the file
        String[] stmts = sb.toString().split(";");

        //stablish the connection using the pool
        Connection con = DriverManager.getConnection("jdbc:apache:commons:dbcp:" + poolName);
        Statement st = con.createStatement();

        for (int i = 0; i < stmts.length; i++) {
            // we ensure that there is no spaces before or after the request string
            // in order to not execute empty statements
            if (!stmts[i].trim().equals("")) {
                st.executeUpdate(stmts[i]);
                log.debug("Loading into database: " + stmts[i]);
            }
        }

        //commit changes
        con.commit();
        con.close();

        // Old SimplePool init
        //DriverManager.registerDriver(new SimplePool());
        initialized = true;
    } catch (SQLException se) {
        // Simply throw up SQLExceptions
        throw se;
    } catch (Exception e) {
        // Need to be able to catch other exceptions. Pretend they are
        // SQLExceptions, but do log
        log.warn("Exception initializing DB pool", e);
        throw new SQLException(e.toString());
    }
}