List of usage examples for org.springframework.jdbc CannotGetJdbcConnectionException CannotGetJdbcConnectionException
public CannotGetJdbcConnectionException(String msg, @Nullable SQLException ex)
From source file:com.oracle2hsqldb.spring.MetaDataJdbcTemplate.java
private Connection getConnection() { Connection connection = null; try {/*from ww w .j a va 2 s . co m*/ connection = dataSource.getConnection(); } catch (SQLException e) { throw new CannotGetJdbcConnectionException("could not get connection", e); } return connection; }
From source file:org.cfr.capsicum.datasource.DataSourceUtils.java
/** * Obtain a Connection from the given DataSource. Translates SQLExceptions into * the Spring hierarchy of unchecked generic data access exceptions, simplifying * calling code and making any exception that is thrown more meaningful. * <p>Is aware of a corresponding Connection bound to the current thread, for example * when using {@link DataSourceTransactionManager}. Will bind a Connection to the * thread if transaction synchronization is active, e.g. when running within a * {@link org.springframework.transaction.jta.JtaTransactionManager JTA} transaction). * @param dataSource the DataSource to obtain Connections from * @return a JDBC Connection from the given DataSource * @throws org.springframework.jdbc.CannotGetJdbcConnectionException * if the attempt to get a Connection failed * @see #releaseConnection/* w ww .jav a 2 s .com*/ */ public static Connection getConnection(DataSource dataSource) throws CannotGetJdbcConnectionException { try { return doGetConnection(dataSource); } catch (SQLException ex) { throw new CannotGetJdbcConnectionException("Could not get JDBC Connection", ex); } }
From source file:org.spring.data.gemfire.app.dao.provider.JdbcUserDao.java
protected Connection getConnection() { try {/*from w w w . j a v a2s. com*/ return getDataSource().getConnection(); } catch (SQLException e) { throw new CannotGetJdbcConnectionException(String.format( "Failed to get JDBC Connection from Data Source (%1$s)!", getDataSource().toString()), e); } }
From source file:com.alibaba.cobar.client.support.execution.DefaultConcurrentRequestProcessor.java
protected Object executeWith(Connection connection, SqlMapClientCallback action) { SqlMapSession session = getSqlMapClient().openSession(); try {/*from www .ja v a 2s .c o m*/ try { session.setUserConnection(connection); } catch (SQLException e) { throw new CannotGetJdbcConnectionException("Could not get JDBC Connection", e); } try { return action.doInSqlMapClient(session); } catch (SQLException ex) { throw new SQLErrorCodeSQLExceptionTranslator().translate("SqlMapClient operation", null, ex); } } finally { session.close(); } }
From source file:org.hengdao.utils.SqlSessionUtils.java
/** * If a Spring transaction is active it uses {@code DataSourceUtils} to get * a Spring managed {@code Connection}, then creates a new * {@code SqlSession} with this connection and synchronizes it with the * transaction. If there is not an active transaction it gets a connection * directly from the {@code DataSource} and creates a {@code SqlSession} * with it.//w w w.j a v a2 s . c o m * * @param sessionFactory * a MyBatis {@code SqlSessionFactory} to create new sessions * @param executorType * The executor type of the SqlSession to create * @param exceptionTranslator * Optional. Translates SqlSession.commit() exceptions to Spring * exceptions. * @throws TransientDataAccessResourceException * if a transaction is active and the {@code SqlSessionFactory} * is not using a {@code SpringManagedTransactionFactory} * @see SpringManagedTransactionFactory */ public static SqlSession getSqlSession(SqlSessionFactory sessionFactory, ExecutorType executorType, PersistenceExceptionTranslator exceptionTranslator) { Assert.notNull(sessionFactory, "No SqlSessionFactory specified"); Assert.notNull(executorType, "No ExecutorType specified"); SqlSessionHolder holder = (SqlSessionHolder) TransactionSynchronizationManager.getResource(sessionFactory); if (holder != null && holder.isSynchronizedWithTransaction()) { if (holder.getExecutorType() != executorType) { throw new TransientDataAccessResourceException( "Cannot change the ExecutorType when there is an existing transaction"); } holder.requested(); if (logger.isDebugEnabled()) { logger.debug("Fetched SqlSession [" + holder.getSqlSession() + "] from current transaction"); } return holder.getSqlSession(); } DataSource dataSource = sessionFactory.getConfiguration().getEnvironment().getDataSource(); // SqlSessionFactoryBean unwraps TransactionAwareDataSourceProxies but // we keep this check for the case that SqlSessionUtils is called from // custom code boolean transactionAware = (dataSource instanceof TransactionAwareDataSourceProxy); Connection conn; try { conn = transactionAware ? dataSource.getConnection() : DataSourceUtils.getConnection(dataSource); } catch (SQLException e) { throw new CannotGetJdbcConnectionException("Could not get JDBC Connection for SqlSession", e); } if (logger.isDebugEnabled()) { logger.debug("Creating SqlSession with JDBC Connection [" + conn + "]"); } // Assume either DataSourceTransactionManager or the underlying // connection pool already dealt with enabling auto commit. // This may not be a good assumption, but the overhead of checking // connection.getAutoCommit() again may be expensive (?) in some drivers // (see DataSourceTransactionManager.doBegin()). One option would be to // only check for auto commit if this function is being called outside // of DSTxMgr, but to do that we would need to be able to call // ConnectionHolder.isTransactionActive(), which is protected and not // visible to this class. SqlSession session = sessionFactory.openSession(executorType, conn); // Register session holder and bind it to enable synchronization. // // Note: The DataSource should be synchronized with the transaction // either through DataSourceTxMgr or another tx synchronization. // Further assume that if an exception is thrown, whatever started the // transaction will // handle closing / rolling back the Connection associated with the // SqlSession. if (TransactionSynchronizationManager.isSynchronizationActive()) { if (!(sessionFactory.getConfiguration().getEnvironment() .getTransactionFactory() instanceof SpringManagedTransactionFactory) && DataSourceUtils.isConnectionTransactional(conn, dataSource)) { throw new TransientDataAccessResourceException( "SqlSessionFactory must be using a SpringManagedTransactionFactory in order to use Spring transaction synchronization"); } if (logger.isDebugEnabled()) { logger.debug("Registering transaction synchronization for SqlSession [" + session + "]"); } holder = new SqlSessionHolder(session, executorType, exceptionTranslator); TransactionSynchronizationManager.bindResource(sessionFactory, holder); TransactionSynchronizationManager .registerSynchronization(new SqlSessionSynchronization(holder, sessionFactory)); holder.setSynchronizedWithTransaction(true); holder.requested(); } else { if (logger.isDebugEnabled()) { logger.debug("SqlSession [" + session + "] was not registered for synchronization because synchronization is not active"); } } return session; }
From source file:org.jasig.schedassist.impl.SchedulingAssistantServiceImplTest.java
/** * Expect a DataAccessException to bubble up. * @throws Exception//from w w w.j av a 2 s. c o m */ @Test public void testScheduleAppointmentAvailableScheduleDaoUnavailable() throws Exception { // construct a schedule owner MockCalendarAccount ownerAccount = new MockCalendarAccount(); ownerAccount.setUsername("user1"); DefaultScheduleOwnerImpl owner = new DefaultScheduleOwnerImpl(ownerAccount, 1); // construct a schedule visitor MockCalendarAccount visitorAccount = new MockCalendarAccount(); visitorAccount.setUsername("user2"); DefaultScheduleVisitorImpl visitor = new DefaultScheduleVisitorImpl(visitorAccount); // construct target availableblock for appointment AvailableBlock targetBlock = AvailableBlockBuilder.createBlock("20091111-1330", "20091111-1400", 1); AvailableScheduleDao mockScheduleDao = EasyMock.createMock(AvailableScheduleDao.class); EasyMock.expect(mockScheduleDao.retrieveTargetBlock(owner, targetBlock.getStartTime())) .andThrow(new CannotGetJdbcConnectionException("database unavailable", new SQLException())); EasyMock.replay(mockScheduleDao); SchedulingAssistantServiceImpl serviceImpl = new SchedulingAssistantServiceImpl(); serviceImpl.setAvailableScheduleDao(mockScheduleDao); try { serviceImpl.scheduleAppointment(visitor, owner, targetBlock, "description"); Assert.fail("expected CannotGetJdbcConnectionException not thrown"); } catch (CannotGetJdbcConnectionException e) { // success } EasyMock.verify(mockScheduleDao); }
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 {/*from ww w .ja v a 2 s. c o m*/ 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.nway.spring.jdbc.SqlExecutor.java
private void initPaginationSupport() { String databaseProductName = null; try (Connection conn = getDataSource().getConnection()) { databaseProductName = conn.getMetaData().getDatabaseProductName().toUpperCase(); } catch (SQLException e) { throw new CannotGetJdbcConnectionException("", e); }//from w w w. j av a 2s .co m if (databaseProductName.contains("ORACLE")) { this.paginationSupport = new OraclePaginationSupport(); } else if (databaseProductName.contains("MYSQL") || databaseProductName.contains("MARIADB")) { this.paginationSupport = new MysqlPaginationSupport(); } else { throw new UnsupportedOperationException( "com.nway.spring.jdbc.PaginationSupportsetPaginationSupport"); } }
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. j av a 2s. c o 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:cc.tooyoung.common.db.JdbcTemplate.java
/** * try 3 times to get connection/* w ww .ja v a 2 s . co m*/ * @param ds * @return * @throws CannotGetJdbcConnectionException */ private Connection safeGetConnection(DataSource ds, boolean isWrite) throws CannotGetJdbcConnectionException { Connection con = null; int retryCount, count; retryCount = count = (isWrite ? writeTryGetConCount : readTryGetConCount); while (count-- > 0) { try { con = DataSourceUtils.getConnection(ds); return con; } catch (CannotGetJdbcConnectionException e) { ApiLogger.info(new StringBuilder(64).append("get connection try count:") .append((retryCount - count)).append(", ds=") .append(((com.mchange.v2.c3p0.ComboPooledDataSource) ds).getJdbcUrl())); DataSourceUtils.releaseConnection(con, ds); } } ApiLogger.fire(new StringBuffer().append("DB ") .append(((com.mchange.v2.c3p0.ComboPooledDataSource) ds).getJdbcUrl()).append(" Error:") .append("Could not get JDBC Connection: ")); throw new CannotGetJdbcConnectionException("Could not get JDBC Connection: " + ", ds=" + ((com.mchange.v2.c3p0.ComboPooledDataSource) ds).getJdbcUrl(), new SQLException()); }