Example usage for org.apache.commons.dbcp PoolingDataSource getConnection

List of usage examples for org.apache.commons.dbcp PoolingDataSource getConnection

Introduction

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

Prototype

public Connection getConnection() throws SQLException 

Source Link

Document

Return a java.sql.Connection from my pool, according to the contract specified by ObjectPool#borrowObject .

Usage

From source file:com.zimbra.cs.db.DbPool.java

public static DbConnection getConnection(Mailbox mbox) throws ServiceException {
    if (!isInitialized()) {
        throw ServiceException.FAILURE("Database connection pool not initialized.", null);
    }//from w w w.j  a  va  2s. c o m
    Integer mboxId = mbox != null ? mbox.getId() : -1; //-1 == zimbra db and/or initialization where mbox isn't known yet
    try {
        Db.getInstance().preOpen(mboxId);
        long start = ZimbraPerf.STOPWATCH_DB_CONN.start();

        // If the connection pool is overutilized, warn about potential leaks
        PoolingDataSource pool = getPool();
        checkPoolUsage();

        Connection dbconn = null;
        DbConnection conn = null;
        try {
            dbconn = pool.getConnection();

            if (dbconn.getAutoCommit() != false)
                dbconn.setAutoCommit(false);

            // We want READ COMMITTED transaction isolation level for duplicate
            // handling code in BucketBlobStore.newBlobInfo().
            if (Db.supports(Db.Capability.READ_COMMITTED_ISOLATION))
                dbconn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);

            conn = new DbConnection(dbconn, mboxId);
            Db.getInstance().postOpen(conn);
        } catch (SQLException e) {
            try {
                if (dbconn != null && !dbconn.isClosed())
                    dbconn.close();
            } catch (SQLException e2) {
                ZimbraLog.sqltrace.warn("DB connection close caught exception", e);
            }
            throw ServiceException.FAILURE("getting database connection", e);
        }

        // If we're debugging, update the counter with the current stack trace
        if (ZimbraLog.dbconn.isDebugEnabled()) {
            Throwable t = new Throwable();
            conn.setStackTrace(t);

            String stackTrace = SystemUtil.getStackTrace(t);
            synchronized (sConnectionStackCounter) {
                sConnectionStackCounter.increment(stackTrace);
            }
        }
        if (mbox != null)
            Db.registerDatabaseInterest(conn, mbox);

        ZimbraPerf.STOPWATCH_DB_CONN.stop(start);
        return conn;
    } catch (ServiceException se) {
        //if connection open fails unlock
        Db.getInstance().abortOpen(mboxId);
        throw se;
    }
}

From source file:com.toolsverse.etl.sql.connection.PooledAliasConnectionProvider.java

@Override
protected Connection createConnection(Alias alias) throws Exception {
    java.sql.Driver driver = (java.sql.Driver) Class.forName(alias.getJdbcDriverClass()).newInstance();

    DriverManager.registerDriver(driver);

    org.apache.commons.dbcp.ConnectionFactory connectionFactory = null;

    Properties props = Utils.getProperties(alias.getParams());

    String userId = alias.getUserId();
    String password = alias.getPassword();

    String url = alias.getUrl();//from   w ww  .  jav  a  2 s  . c  o  m

    if (props.size() > 0) {
        if (!Utils.isNothing(userId)) {
            props.put("user", userId);
            if (!Utils.isNothing(password))
                props.put("password", password);
        }

        connectionFactory = new DriverManagerConnectionFactory(url, props);
    } else
        connectionFactory = new DriverManagerConnectionFactory(url, userId, password);

    ObjectPool connectionPool = new GenericObjectPool(null, _config);

    @SuppressWarnings("unused")
    PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,
            connectionPool, null, null, false, true);

    PoolingDataSource poolingDataSource = new PoolingDataSource(connectionPool);

    return poolingDataSource.getConnection();
}

From source file:com.springsource.insight.plugin.jdbc.PoolingConnectionTest.java

@Test
public void testOperationCollection() throws SQLException {
    DataSourceConnectionFactory connFactory = new DataSourceConnectionFactory(dataSource);
    ObjectPool connPool = new GenericObjectPool();
    PoolableConnectionFactory poolFactory = new PoolableConnectionFactory(connFactory, connPool, null, null,
            false, true);/* w  w  w.  j  a  v a 2s  .c o m*/
    PoolingDataSource poolDs = new PoolingDataSource(poolFactory.getPool());
    String sql = "select * from appointment where owner = 'Agim'";
    Connection c = poolDs.getConnection();
    try {
        PreparedStatement ps = c.prepareStatement(sql);
        try {
            System.out.println("Prepared statement=" + ps.getClass());

            ResultSet rs = ps.executeQuery();
            rs.close();
        } finally {
            ps.close();
        }
    } finally {
        c.close();
    }

    ArgumentCaptor<Operation> opCaptor = ArgumentCaptor.forClass(Operation.class);
    verify(spiedOperationCollector, times(3)).enter(opCaptor.capture());

    List<Operation> ops = opCaptor.getAllValues();
    assertEquals("Mismatched number of operations", 3, ops.size());
    assertSourceCodeLocation("top-op", ops.get(0),
            "org.apache.commons.dbcp.PoolingDataSource$PoolGuardConnectionWrapper", "prepareStatement");
    assertSourceCodeLocation("mid-op", ops.get(1), "org.apache.commons.dbcp.DelegatingConnection",
            "prepareStatement");
    assertSourceCodeLocation("bottom-op", ops.get(2), "org.hsqldb.jdbc.jdbcConnection", "prepareStatement");
}

From source file:eu.peppol.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  www. j av a 2 s.c  om
 *
 * @throws Exception
 */
@Test
public void testLoadJdbcDriverUsingCustomClassLoader() throws Exception {
    ConnectionFactory driverConnectionFactory = createConnectionFactory(false);

    GenericObjectPool genericObjectPool = new GenericObjectPool(null);

    PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(driverConnectionFactory,
            genericObjectPool, null, "select 1", false, true);
    PoolingDataSource poolingDataSource = new PoolingDataSource(genericObjectPool);

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

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

    assertTrue(resultSet.next());
}

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

private void runTwoSqlStatementsWithTwoConnections(PoolingDataSource poolingDataSource)
        throws SQLException, InterruptedException {
    Connection connection = poolingDataSource.getConnection();
    assertNotNull(connection);//w  ww. j  ava2  s .c o m

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

    statement = connection.createStatement();
    statement.execute("set session wait_timeout=1");
    assertTrue(resultSet.next());

    connection.close(); // return to pool

    // Wait for 2 seconds
    System.err.print("Sleeping for 2 seconds....");
    Thread.sleep(2 * 1000L);
    System.err.println("Running again now");
    connection = poolingDataSource.getConnection();
    statement = connection.createStatement();
    resultSet = statement.executeQuery("select current_time()");
}

From source file:org.apache.hadoop.hive.metastore.MyXid.java

public static Connection getConnectionFromPool(String url) throws SQLException, MetaStoreConnectException {
    if (poolEnable) {
        PoolingDataSource pool = getSegPoolingDataSource(url, user, passwd);

        return pool.getConnection();
    } else {//from   www .j a  va2  s .c om
        return openConnect(url, user, passwd);
    }
}

From source file:org.pentaho.reporting.engine.classic.extensions.modules.connections.PooledDatasourceHelperIT.java

@Test
public void testCreatePool() throws Exception {
    DatabaseConnection con = ConnectionUtil.createConnection();
    con.getAttributes().put(DatabaseConnection.ATTRIBUTE_CUSTOM_DRIVER_CLASS, ConnectionUtil.DRIVER_CLASS);
    con.getAttributes().put(DatabaseConnection.ATTRIBUTE_CUSTOM_URL, ConnectionUtil.CON_URL);

    PoolingDataSource poolingDataSource = PooledDatasourceHelper.setupPooledDataSource(con);

    assertThat(poolingDataSource, is(notNullValue()));
    Connection connection = poolingDataSource.getConnection();
    assertThat(connection, is(notNullValue()));
    connection.close();/* w ww .  j a  va 2 s .c o  m*/

    DataSourceCacheManager cacheManager = ClassicEngineBoot.getInstance().getObjectFactory()
            .get(DataSourceCacheManager.class);
    DataSource ds = cacheManager.getDataSourceCache().get(con.getName());
    assertThat(ds, is(instanceOf(PoolingDataSource.class)));
    assertThat((PoolingDataSource) ds, is(equalTo(poolingDataSource)));
}

From source file:org.pentaho.reporting.engine.classic.extensions.modules.connections.PooledDatasourceHelperIT.java

@Test
public void testCreatePoolWithAttrs() throws Exception {
    DatabaseConnection con = ConnectionUtil.createConnectionWithAttrs();

    PoolingDataSource poolingDataSource = PooledDatasourceHelper.setupPooledDataSource(con);

    assertThat(poolingDataSource, is(notNullValue()));
    Connection connection = poolingDataSource.getConnection();
    assertThat(connection, is(notNullValue()));
    connection.close();//  ww w  . j  ava 2 s  .  co m

    DataSourceCacheManager cacheManager = ClassicEngineBoot.getInstance().getObjectFactory()
            .get(DataSourceCacheManager.class);
    DataSource ds = cacheManager.getDataSourceCache().get(con.getName());
    assertThat(ds, is(instanceOf(PoolingDataSource.class)));
    assertThat((PoolingDataSource) ds, is(equalTo(poolingDataSource)));
}