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.sakaiproject.kernel.persistence.dbcp.DataSourceServiceImpl.java

/**
 * Construct a DBCP data source service.
 *
 * @param driverClassName// w w  w.  j a v  a 2s . c om
 * @param url
 * @param username
 * @param password
 * @param validationQuery
 * @param defaultReadOnly
 * @param defaultAutoCommit
 * @param poolPreparedStatements
 * @throws ClassNotFoundException
 * @throws SQLException
 */
@Inject
@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = {
        "URF_UNREAD_FIELD" }, justification = "The conection factory must be initialized before use")
public DataSourceServiceImpl(@Named(KernelConstants.JDBC_DRIVER_NAME) String driverClassName,
        @Named(KernelConstants.JDBC_URL) String url, @Named(KernelConstants.JDBC_USERNAME) String username,
        @Named(KernelConstants.JDBC_PASSWORD) String password,
        @Named(KernelConstants.JDBC_VALIDATION_QUERY) String validationQuery,
        @Named(KernelConstants.JDBC_DEFAULT_READ_ONLY) boolean defaultReadOnly,
        @Named(KernelConstants.JDBC_DEFAULT_AUTO_COMMIT) boolean defaultAutoCommit,
        @Named(KernelConstants.JDBC_DEFAULT_PREPARED_STATEMENTS) boolean poolPreparedStatements)
        throws ClassNotFoundException, SQLException {

    Class.forName(driverClassName);
    GenericObjectPool connectionPool = new GenericObjectPool(null);
    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(url, username, password);

    // Set up statement pool, if desired
    GenericKeyedObjectPoolFactory statementPoolFactory = null;
    if (poolPreparedStatements) {
        int maxActive = -1;
        byte whenExhaustedAction = GenericKeyedObjectPool.WHEN_EXHAUSTED_FAIL;
        long maxWait = 0L;
        int maxIdlePerKey = 1;
        int maxOpenPreparedStatements = 0;
        statementPoolFactory = new GenericKeyedObjectPoolFactory(null, maxActive, whenExhaustedAction, maxWait,
                maxIdlePerKey, maxOpenPreparedStatements);
    }

    poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, connectionPool,
            statementPoolFactory, validationQuery, defaultReadOnly, defaultAutoCommit);
    dataSource = new PoolingDataSource(connectionPool);
}

From source file:org.sakaiproject.nakamura.persistence.dbcp.DataSourceServiceImpl.java

@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = { "URF_UNREAD_FIELD",
        "UWF_UNWRITTEN_FIELD" }, justification = "PoolableConnectionFactory injects itself into connectionPool, but we need a reference to it, ConfigurationService is OSgi managed.")
protected void activate(ComponentContext componentContext) throws ClassNotFoundException {
    String driverClassName = confurationService.getProperty(NakamuraConstants.JDBC_DRIVER_NAME);

    String url = confurationService.getProperty(NakamuraConstants.JDBC_URL);
    String username = confurationService.getProperty(NakamuraConstants.JDBC_USERNAME);
    String password = confurationService.getProperty(NakamuraConstants.JDBC_PASSWORD);
    String validationQuery = confurationService.getProperty(NakamuraConstants.JDBC_VALIDATION_QUERY);
    boolean defaultReadOnly = Boolean
            .valueOf(confurationService.getProperty(NakamuraConstants.JDBC_DEFAULT_READ_ONLY));
    boolean defaultAutoCommit = Boolean
            .valueOf(confurationService.getProperty(NakamuraConstants.JDBC_DEFAULT_AUTO_COMMIT));
    boolean poolPreparedStatements = Boolean
            .valueOf(confurationService.getProperty(NakamuraConstants.JDBC_DEFAULT_PREPARED_STATEMENTS));

    Class.forName(driverClassName);
    GenericObjectPool connectionPool = new GenericObjectPool(null);
    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(url, username, password);

    // Set up statement pool, if desired
    GenericKeyedObjectPoolFactory statementPoolFactory = null;
    if (poolPreparedStatements) {
        int maxActive = -1;
        byte whenExhaustedAction = GenericKeyedObjectPool.WHEN_EXHAUSTED_FAIL;
        long maxWait = 0L;
        int maxIdlePerKey = 1;
        int maxOpenPreparedStatements = 0;
        statementPoolFactory = new GenericKeyedObjectPoolFactory(null, maxActive, whenExhaustedAction, maxWait,
                maxIdlePerKey, maxOpenPreparedStatements);
    }/*  w w w  .  ja  va  2s .co m*/

    poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, connectionPool,
            statementPoolFactory, validationQuery, defaultReadOnly, defaultAutoCommit);
    dataSource = new PoolingDataSource(connectionPool);
}

From source file:org.seadva.access.security.model.DatabaseSingleton.java

protected DatabaseSingleton()
        throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {

    Class.forName(this.driver).newInstance();

    connectionPool = new GenericObjectPool();
    connectionPool.setMaxActive(10);/*from w  ww  . j a va  2  s . c  om*/

    Properties props = new Properties();
    props.setProperty("user", dbUsername);
    props.setProperty("password", dbUserPwd);

    ConnectionFactory cf = new DriverConnectionFactory(new com.mysql.jdbc.Driver(), dbUrl, props);
    PoolableConnectionFactory pcf = new PoolableConnectionFactory(cf, connectionPool, null, null, false, true);

    this.dataSource = new PoolingDataSource(connectionPool);

}

From source file:org.snipsnap.util.ConnectionManager.java

private void update(Configuration config) {
    if (null == dataSource) {
        try {//from   ww  w  .j  a  v  a 2  s  .  c  o m
            System.err.println("ConnectionManager: Registering JDBC driver: " + config.getJdbcDriver());
            Class.forName(config.getJdbcDriver());
        } catch (Exception e) {
            Logger.fatal("unable to register JDBC driver: " + config.getJdbcDriver(), e);
        }

        String jdbcUrl = config.getJdbcUrl();
        //      if (jdbcUrl.indexOf("?") != -1) {
        //        jdbcUrl = jdbcUrl.concat("&");
        //      } else {
        //        jdbcUrl = jdbcUrl.concat("?");
        //      }
        String jdbcPassword = config.getJdbcPassword();
        //      if (null == jdbcPassword) {
        //        jdbcPassword = "";
        //      }
        //      jdbcUrl = jdbcUrl.concat("user=" + config.getJdbcUser()).concat("&password=" + jdbcPassword);
        //      System.err.println("ConnectionManager: using: "+ jdbcUrl);
        ObjectPool connectionPool = new GenericObjectPool(null);
        ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(jdbcUrl, config.getJdbcUser(),
                jdbcPassword);
        PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,
                connectionPool, null, null, false, true);
        dataSource = new PoolingDataSource(connectionPool);
    }
}

From source file:org.topazproject.ambra.auth.db.DatabaseContext.java

/**
 * Construct a db context//from w w  w.j a va 2  s .co m
 * @param jdbcDriver jdbcDriver
 * @param dbProperties dbProperties including url, user, password
 * @param initialSize initialSize of the pool
 * @param maxActive maxActive number of connections, after which it will block until a connection is
 *                  released
 * @param validationQuery to validate that the connection is still valid
 * @throws DatabaseException DatabaseException
 */
private DatabaseContext(final String jdbcDriver, final Properties dbProperties, final int initialSize,
        final int maxActive, final String validationQuery) throws DatabaseException {
    try {
        Class.forName(jdbcDriver);
    } catch (final ClassNotFoundException e) {
        throw new DatabaseException("Unable to load the db driver:" + jdbcDriver, e);
    }

    final ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(
            dbProperties.getProperty("url"), dbProperties.getProperty("user"),
            dbProperties.getProperty("password"));

    connectionPool = new GenericObjectPool();
    connectionPool.setTestOnReturn(true);
    connectionPool.setMaxActive(maxActive);
    connectionPool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_BLOCK);
    connectionPool.getMaxActive();

    final KeyedObjectPoolFactory stmtPool = new GenericKeyedObjectPoolFactory(null);

    /*
     * During instantiation, the PoolableConnectionFactory class registers itself to the
     * GenericObjectPool instance passed in its constructor. This factory class is used to create
     * new instances of the JDBC connections.
     */
    new PoolableConnectionFactory(connectionFactory, connectionPool, stmtPool, validationQuery, false, true);

    for (int i = 0; i < initialSize; i++) {
        try {
            connectionPool.addObject();
        } catch (final Exception e) {
            throw new DatabaseException("Error initlaizing initial number of connections", e);
        }
    }
    dataSource = new PoolingDataSource(connectionPool);
}

From source file:org.wsm.database.tools.util.FANConnectionManager.java

public void setupDataSource(String dsName) {
    try {/*  w w  w. j  a  va2s. c  o m*/
        OracleDataSource ods = super.getBasicDataSourceSetup(dsName);

        java.util.Properties prop = new java.util.Properties();
        prop.setProperty("MinLimit", "5");
        prop.setProperty("MaxLimit", "45");
        ods.setConnectionCacheName("FanConnectionCache01");
        ods.setConnectionCachingEnabled(true);
        ods.setConnectionCacheProperties(prop);
        ods.setFastConnectionFailoverEnabled(true);
        ObjectPool connectionPool = new GenericObjectPool(null);
        ConnectionFactory connectionFactory = new DataSourceConnectionFactory(ods);
        PoolableConnectionFactory pcf = new PoolableConnectionFactory(connectionFactory, connectionPool, null,
                null, false, true);
        PoolingDataSource pds = new PoolingDataSource(connectionPool);
        addPoolingDataSourceToBucket(dsName, pds);
        //addOracleDataSourceToBucket(dsName, ods);
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

From source file:paqueteClases.DBConnector.java

private DBConnector(String url, String user, String password) throws Exception {
    ////from   w  w  w .j a  v a  2  s  . co 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.
    //
    Class.forName("com.mysql.jdbc.Driver");
    GenericObjectPool connectionPool = new GenericObjectPool(null);
    connectionPool.setMaxActive(5);
    connectionPool.setMaxWait(2);
    connectionPool.setMaxIdle(2);

    //
    // 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(url, user, password);

    //
    // 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.
    //
    dataSource_ = new PoolingDataSource(connectionPool);

}

From source file:sce.ConnectionPool.java

/**
 *
 * @return @throws Exception//from   w w w . j  a  v  a 2s  . com
 */
public DataSource setUp() throws Exception {
    /**
     * Load JDBC Driver class.
     */
    Class.forName(ConnectionPool.DRIVER).newInstance();

    /**
     * Creates an instance of GenericObjectPool that holds our pool of
     * connections object.
     */
    connectionPool = new GenericObjectPool();
    // set the max number of connections
    connectionPool.setMaxActive(connections);
    // if the pool is exhausted (i.e., the maximum number of active objects has been reached), the borrowObject() method should simply create a new object anyway
    connectionPool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_GROW);

    /**
     * Creates a connection factory object which will be used by the pool to
     * create the connection object. We pass the JDBC url info, username
     * and password.
     */
    ConnectionFactory cf = new DriverManagerConnectionFactory(ConnectionPool.URL, ConnectionPool.USERNAME,
            ConnectionPool.PASSWORD);

    /**
     * Creates a PoolableConnectionFactory that will wrap the connection
     * object created by the ConnectionFactory to add object pooling
     * functionality.
     */
    PoolableConnectionFactory pcf = new PoolableConnectionFactory(cf, connectionPool, null, null, false, true);
    return new PoolingDataSource(connectionPool);
}

From source file:storm.scheduler.DataManager.java

private DataManager() {
    logger = Logger.getLogger(DataManager.class);
    logger.info("Starting DataManager (working directory: " + System.getProperty("user.dir") + ")");

    try {//from  www. jav  a 2 s .c o m
        // load configuration from file
        logger.debug("Loading configuration from file");
        Properties properties = new Properties();
        properties.load(new FileInputStream("/home/miller/research/storm/apache-storm-0.9.3/db.ini"));
        logger.debug("Configuration loaded");

        // load JDBC driver
        logger.debug("Loading JDBC driver");
        String jdbc_driver = properties.getProperty("jdbc.driver").trim();
        Class.forName(jdbc_driver);
        logger.debug("Driver loaded");

        // set up data source
        logger.debug("Setting up pooling data source");
        String connection_uri = properties.getProperty("data.connection.uri");
        String validation_query = properties.getProperty("validation.query");
        ObjectPool connectionPool = new GenericObjectPool(null);
        ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(connection_uri, properties);
        PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,
                connectionPool, null, validation_query, false, true);
        poolableConnectionFactory.hashCode();
        dataSource = new PoolingDataSource(connectionPool);
        logger.debug("Data source set up");

        nodeName = properties.getProperty("node-name");
        if (properties.getProperty("capacity") != null) {
            capacity = Integer.parseInt(properties.getProperty("capacity"));
            if (capacity < 1 || capacity > 100)
                throw new RuntimeException("Wrong capacity: " + capacity + ", expected in the range [1, 100]");
        }

        logger.info("DataManager started");
    } catch (Exception e) {
        logger.error("Error starting DataManager", e);
    }
}

From source file:ua.company.model.factory.PostgreDAOFactory.java

private void initSource(/*Logger logger*/) {

    // load the underlying driver
    try {//from ww w . j a v  a  2 s .  c o  m
        Class.forName("org.postgresql.Driver");
    } catch (ClassNotFoundException ex) {
        logger.error(ex.getMessage());
        System.exit(1);
    }

    ConnectionFactory connectionFactory = null;
    ObjectPool connectionPool = null;
    PoolableConnectionFactory poolableConnectionFactory = null;

    // Build the DSN: jdbc:postgresql://host:port/database
    String buf = "jdbc:postgresql://127.0.0.1:5432/Restaurant";

    Properties props = new Properties();
    props.setProperty("user", "postgres");
    props.setProperty("password", "postgres");
    props.setProperty("initialSize", "50");

    props.setProperty("maxActive", "25");

    connectionFactory = new DriverManagerConnectionFactory(buf, props);
    connectionPool = new GenericObjectPool(null);
    poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, connectionPool, null, null,
            false, true);

    dataSource = new PoolingDataSource(connectionPool);
}