Example usage for org.springframework.jdbc.datasource DataSourceUtils doGetConnection

List of usage examples for org.springframework.jdbc.datasource DataSourceUtils doGetConnection

Introduction

In this page you can find the example usage for org.springframework.jdbc.datasource DataSourceUtils doGetConnection.

Prototype

public static Connection doGetConnection(DataSource dataSource) throws SQLException 

Source Link

Document

Actually obtain a JDBC Connection from the given DataSource.

Usage

From source file:com.bt.aloha.testing.DbTestCase.java

@Before
public void before() throws Exception {
    log.debug("Before DbTestCase: initiating datasource and connection to database");
    if (ds == null) {
        ds = jdbcHelper.getDefaultDataSource();
    }/*from w  w w .j  a va  2s  .  co m*/
    connection = DataSourceUtils.doGetConnection(ds);
}

From source file:grails.plugin.quartz2.LocalDataSourceJobStore.java

@Override
public void initialize(ClassLoadHelper loadHelper, SchedulerSignaler signaler) throws SchedulerConfigException {

    // Absolutely needs thread-bound DataSource to initialize.
    this.dataSource = QuartzFactoryBean.getConfigTimeDataSource();
    if (this.dataSource == null) {
        throw new SchedulerConfigException("No local DataSource found for configuration - "
                + "'dataSource' property must be set on SchedulerFactoryBean");
    }/*w  ww . j  a va 2  s.  com*/

    // Configure transactional connection settings for Quartz.
    setDataSource(TX_DATA_SOURCE_PREFIX + getInstanceName());
    setDontSetAutoCommitFalse(true);

    // Register transactional ConnectionProvider for Quartz.
    DBConnectionManager.getInstance().addConnectionProvider(TX_DATA_SOURCE_PREFIX + getInstanceName(),
            new ConnectionProvider() {
                public Connection getConnection() throws SQLException {
                    // Return a transactional Connection, if any.
                    return DataSourceUtils.doGetConnection(dataSource);
                }

                public void shutdown() {
                    // Do nothing - a Spring-managed DataSource has its own lifecycle.
                }
            });

    // Configure non-transactional connection settings for Quartz.
    setNonManagedTXDataSource(NON_TX_DATA_SOURCE_PREFIX + getInstanceName());
    final DataSource nonTxDataSourceToUse = this.dataSource;
    // Register non-transactional ConnectionProvider for Quartz.
    DBConnectionManager.getInstance().addConnectionProvider(NON_TX_DATA_SOURCE_PREFIX + getInstanceName(),
            new ConnectionProvider() {
                public Connection getConnection() throws SQLException {
                    // Always return a non-transactional Connection.
                    return nonTxDataSourceToUse.getConnection();
                }

                public void shutdown() {
                    // Do nothing - a Spring-managed DataSource has its own lifecycle.
                }
            });

    // No, if HSQL is the platform, we really don't want to use locks
    try {
        String productName = JdbcUtils.extractDatabaseMetaData(dataSource, "getDatabaseProductName").toString();
        productName = JdbcUtils.commonDatabaseName(productName);
        if (productName != null && productName.toLowerCase().contains("hsql")) {
            setUseDBLocks(false);
            setLockHandler(new SimpleSemaphore());
        }
    } catch (MetaDataAccessException e) {
        logWarnIfNonZero(1, "Could not detect database type.  Assuming locks can be taken.");
    }

    super.initialize(loadHelper, signaler);

}

From source file:com.saysth.commons.quartz.LocalDataSourceJobStore.java

@Override
public void initialize(ClassLoadHelper loadHelper, SchedulerSignaler signaler) throws SchedulerConfigException {

    // Absolutely needs thread-bound DataSource to initialize.
    this.dataSource = SchedulerFactoryBean.getConfigTimeDataSource();
    if (this.dataSource == null) {
        throw new SchedulerConfigException("No local DataSource found for configuration - "
                + "'dataSource' property must be set on SchedulerFactoryBean");
    }// w  ww  .j a va 2s .  com

    // Configure transactional connection settings for Quartz.
    setDataSource(TX_DATA_SOURCE_PREFIX + getInstanceName());
    setDontSetAutoCommitFalse(true);

    // Register transactional ConnectionProvider for Quartz.
    DBConnectionManager.getInstance().addConnectionProvider(TX_DATA_SOURCE_PREFIX + getInstanceName(),
            new ConnectionProvider() {
                public Connection getConnection() throws SQLException {
                    // Return a transactional Connection, if any.
                    return DataSourceUtils.doGetConnection(dataSource);
                }

                public void shutdown() {
                    // Do nothing - a Spring-managed DataSource has its own
                    // lifecycle.
                }
            });

    // Non-transactional DataSource is optional: fall back to default
    // DataSource if not explicitly specified.
    DataSource nonTxDataSource = SchedulerFactoryBean.getConfigTimeNonTransactionalDataSource();
    final DataSource nonTxDataSourceToUse = (nonTxDataSource != null ? nonTxDataSource : this.dataSource);

    // Configure non-transactional connection settings for Quartz.
    setNonManagedTXDataSource(NON_TX_DATA_SOURCE_PREFIX + getInstanceName());

    // Register non-transactional ConnectionProvider for Quartz.
    DBConnectionManager.getInstance().addConnectionProvider(NON_TX_DATA_SOURCE_PREFIX + getInstanceName(),
            new ConnectionProvider() {
                public Connection getConnection() throws SQLException {
                    // Always return a non-transactional Connection.
                    return nonTxDataSourceToUse.getConnection();
                }

                public void shutdown() {
                    // Do nothing - a Spring-managed DataSource has its own
                    // lifecycle.
                }
            });

    // No, if HSQL is the platform, we really don't want to use locks
    try {
        String productName = JdbcUtils.extractDatabaseMetaData(dataSource, "getDatabaseProductName").toString();
        productName = JdbcUtils.commonDatabaseName(productName);
        if (productName != null && productName.toLowerCase().contains("hsql")) {
            setUseDBLocks(false);
            setLockHandler(new SimpleSemaphore());
        }
    } catch (MetaDataAccessException e) {
        logWarnIfNonZero(1, "Could not detect database type.  Assuming locks can be taken.");
    }

    super.initialize(loadHelper, signaler);

}

From source file:com.alibaba.cobar.client.support.execution.DefaultConcurrentRequestProcessor.java

private List<RequestDepository> fetchConnectionsAndDepositForLaterUse(List<ConcurrentRequest> requests) {
    List<RequestDepository> depos = new ArrayList<RequestDepository>();
    for (ConcurrentRequest request : requests) {
        DataSource dataSource = request.getDataSource();

        Connection springCon = null;
        boolean transactionAware = (dataSource instanceof TransactionAwareDataSourceProxy);
        try {//  ww  w  .  j av  a2  s  .  c  om
            springCon = (transactionAware ? dataSource.getConnection()
                    : DataSourceUtils.doGetConnection(dataSource));
        } catch (SQLException ex) {
            throw new CannotGetJdbcConnectionException("Could not get JDBC Connection", ex);
        }

        RequestDepository depo = new RequestDepository();
        depo.setOriginalRequest(request);
        depo.setConnectionToUse(springCon);
        depo.setTransactionAware(transactionAware);
        depos.add(depo);
    }

    return depos;
}

From source file:com.haiegoo.framework.ibatis.SqlMapClientMasterSlaveTemplate.java

/**
 * Execute the given data access action on a SqlMapExecutor.
 * @param action callback object that specifies the data access action
 * @return a result object returned by the action, or <code>null</code>
 * @throws DataAccessException in case of SQL Maps errors
 *//*from w  w w. java 2s.  co  m*/
public <T> T execute(SqlMapClientCallback<T> action, SqlMapClient sqlMapClient) throws DataAccessException {
    Assert.notNull(action, "Callback object must not be null");
    Assert.notNull(sqlMapClient, "No SqlMapClient specified");

    // We always need to use a SqlMapSession, as we need to pass a Spring-managed
    // Connection (potentially transactional) in. This shouldn't be necessary if
    // we run against a TransactionAwareDataSourceProxy underneath, but unfortunately
    // we still need it to make iBATIS batch execution work properly: If iBATIS
    // doesn't recognize an existing transaction, it automatically executes the
    // batch for every single statement...

    SqlMapSession session = sqlMapClient.openSession();
    if (logger.isDebugEnabled()) {
        logger.debug("Opened SqlMapSession [" + session + "] for iBATIS operation");
    }
    Connection ibatisCon = null;

    try {
        Connection springCon = null;
        DataSource dataSource = sqlMapClient.getDataSource();
        boolean transactionAware = (dataSource instanceof TransactionAwareDataSourceProxy);

        // Obtain JDBC Connection to operate on...
        try {
            ibatisCon = session.getCurrentConnection();
            if (ibatisCon == null) {
                springCon = (transactionAware ? dataSource.getConnection()
                        : DataSourceUtils.doGetConnection(dataSource));
                session.setUserConnection(springCon);
                if (logger.isDebugEnabled()) {
                    logger.debug("Obtained JDBC Connection [" + springCon + "] for iBATIS operation");
                }
            } else {
                if (logger.isDebugEnabled()) {
                    logger.debug("Reusing JDBC Connection [" + ibatisCon + "] for iBATIS operation");
                }
            }
        } catch (SQLException ex) {
            throw new CannotGetJdbcConnectionException("Could not get JDBC Connection", ex);
        }

        // Execute given callback...
        try {
            return action.doInSqlMapClient(session);
        } catch (SQLException ex) {
            throw getExceptionTranslator().translate("SqlMapClient operation", null, ex);
        } finally {
            try {
                if (springCon != null) {
                    if (transactionAware) {
                        springCon.close();
                    } else {
                        DataSourceUtils.doReleaseConnection(springCon, dataSource);
                    }
                }
            } catch (Throwable ex) {
                logger.debug("Could not close JDBC Connection", ex);
            }
        }

        // Processing finished - potentially session still to be closed.
    } finally {
        // Only close SqlMapSession if we know we've actually opened it
        // at the present level.
        if (ibatisCon == null) {
            session.close();
        }
    }
}

From source file:com.alibaba.cobar.client.CobarSqlMapClientTemplate.java

protected Object executeWith(DataSource dataSource, SqlMapClientCallback action) {
    SqlMapSession session = getSqlMapClient().openSession();

    try {/* ww  w.  j  a  va2s . c om*/
        Connection springCon = null;
        boolean transactionAware = (dataSource instanceof TransactionAwareDataSourceProxy);

        // Obtain JDBC Connection to operate on...
        try {
            springCon = (transactionAware ? dataSource.getConnection()
                    : DataSourceUtils.doGetConnection(dataSource));
            session.setUserConnection(springCon);
        } catch (SQLException ex) {
            throw new CannotGetJdbcConnectionException("Could not get JDBC Connection", ex);
        }

        try {
            return action.doInSqlMapClient(session);
        } catch (SQLException ex) {
            throw new SQLErrorCodeSQLExceptionTranslator().translate("SqlMapClient operation", null, ex);
        } catch (Throwable t) {
            throw new UncategorizedCobarClientException(
                    "unknown excepton when performing data access operation.", t);
        } finally {
            try {
                if (springCon != null) {
                    if (transactionAware) {
                        springCon.close();
                    } else {
                        DataSourceUtils.doReleaseConnection(springCon, dataSource);
                    }
                }
            } catch (Throwable ex) {
                logger.debug("Could not close JDBC Connection", ex);
            }
        }
        // Processing finished - potentially session still to be closed.
    } finally {
        session.close();
    }
}

From source file:org.artifactory.storage.db.util.JdbcHelper.java

/**
 * @return A transaction aware connection
 *//*  w  w  w  .j av  a 2 s  .c  o m*/
private Connection getConnection() throws SQLException {
    Connection connection = DataSourceUtils.doGetConnection(dataSource);
    if (Connection.TRANSACTION_READ_COMMITTED != connection.getTransactionIsolation()) {
        connection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
    }
    return connection;
}

From source file:org.springframework.batch.item.database.IbatisBatchItemWriter.java

@SuppressWarnings("unchecked")
private List<BatchResult> execute(final List<? extends T> items) {
    // We always need to use a SqlMapSession, as we need to pass a Spring-managed
    // Connection (potentially transactional) in. This shouldn't be necessary if
    // we run against a TransactionAwareDataSourceProxy underneath, but unfortunately
    // we still need it to make iBATIS batch execution work properly: If iBATIS
    // doesn't recognize an existing transaction, it automatically executes the
    // batch for every single statement...

    SqlMapSession session = this.sqlMapClient.openSession();
    if (logger.isDebugEnabled()) {
        logger.debug("Opened SqlMapSession [" + session + "] for iBATIS operation");
    }/* w w  w  .  ja va  2 s . co m*/
    Connection ibatisCon = null;

    try {
        Connection springCon = null;
        boolean transactionAware = (dataSource instanceof TransactionAwareDataSourceProxy);

        // Obtain JDBC Connection to operate on...
        try {
            ibatisCon = session.getCurrentConnection();
            if (ibatisCon == null) {
                springCon = (transactionAware ? dataSource.getConnection()
                        : DataSourceUtils.doGetConnection(dataSource));
                session.setUserConnection(springCon);
                if (logger.isDebugEnabled()) {
                    logger.debug("Obtained JDBC Connection [" + springCon + "] for iBATIS operation");
                }
            } else {
                if (logger.isDebugEnabled()) {
                    logger.debug("Reusing JDBC Connection [" + ibatisCon + "] for iBATIS operation");
                }
            }
        } catch (SQLException ex) {
            throw new CannotGetJdbcConnectionException("Could not get JDBC Connection", ex);
        }

        // Execute given callback...
        try {
            session.startBatch();
            for (T item : items) {
                session.update(statementId, item);
            }
            try {
                return session.executeBatchDetailed();
            } catch (BatchException e) {
                throw e.getBatchUpdateException();
            }
        } catch (SQLException ex) {
            SQLExceptionTranslator sqlStateSQLExceptionTranslator;

            if (dataSource != null) {
                sqlStateSQLExceptionTranslator = new SQLStateSQLExceptionTranslator();
            } else {
                sqlStateSQLExceptionTranslator = new SQLErrorCodeSQLExceptionTranslator(dataSource);
            }

            throw sqlStateSQLExceptionTranslator.translate("SqlMapClient operation", null, ex);
        }

        // Processing finished - potentially session still to be closed.
    } finally {
        // Only close SqlMapSession if we know we've actually opened it
        // at the present level.
        if (ibatisCon == null) {
            session.close();
        }
    }
}