org.springframework.jdbc.CannotGetJdbcConnectionException Java Examples

The following examples show how to use org.springframework.jdbc.CannotGetJdbcConnectionException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JdbcTemplateTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * If beanProperty is true, initialize via exception translator bean property;
 * if false, use afterPropertiesSet().
 */
private void doTestCouldNotGetConnectionInOperationWithExceptionTranslatorInitialized(boolean beanProperty)
		throws SQLException {

	SQLException sqlException = new SQLException("foo", "07xxx");
	this.dataSource = mock(DataSource.class);
	given(this.dataSource.getConnection()).willThrow(sqlException);
	this.template = new JdbcTemplate();
	this.template.setDataSource(this.dataSource);
	this.template.setLazyInit(false);
	if (beanProperty) {
		// This will get a connection.
		this.template.setExceptionTranslator(new SQLErrorCodeSQLExceptionTranslator(this.dataSource));
	}
	else {
		// This will cause creation of default SQL translator.
		this.template.afterPropertiesSet();
	}
	RowCountCallbackHandler rcch = new RowCountCallbackHandler();
	this.thrown.expect(CannotGetJdbcConnectionException.class);
	this.thrown.expect(exceptionCause(sameInstance(sqlException)));
	this.template.query("SELECT ID, FORENAME FROM CUSTMR WHERE ID < 3", rcch);
}
 
Example #2
Source File: JdbcTemplateTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * If beanProperty is true, initialize via exception translator bean property;
 * if false, use afterPropertiesSet().
 */
private void doTestCouldntGetConnectionInOperationWithExceptionTranslatorInitialized(boolean beanProperty)
		throws SQLException {
	SQLException sqlException = new SQLException("foo", "07xxx");
	this.dataSource = mock(DataSource.class);
	given(this.dataSource.getConnection()).willThrow(sqlException);
	this.template = new JdbcTemplate();
	this.template.setDataSource(this.dataSource);
	this.template.setLazyInit(false);
	if (beanProperty) {
		// This will get a connection.
		this.template.setExceptionTranslator(new SQLErrorCodeSQLExceptionTranslator(this.dataSource));
	}
	else {
		// This will cause creation of default SQL translator.
		this.template.afterPropertiesSet();
	}
	RowCountCallbackHandler rcch = new RowCountCallbackHandler();
	this.thrown.expect(CannotGetJdbcConnectionException.class);
	this.thrown.expect(exceptionCause(sameInstance(sqlException)));
	this.template.query("SELECT ID, FORENAME FROM CUSTMR WHERE ID < 3", rcch);
}
 
Example #3
Source File: MockJdbcOperations.java    From herd with Apache License 2.0 6 votes vote down vote up
@Override
public int update(JdbcTemplate jdbcTemplate, String sql)
{
    LOGGER.debug("sql = " + sql);
    if (CASE_1_SQL.equals(sql))
    {
        return 1;
    }
    else if (CASE_2_SQL.equals(sql))
    {
        throw new DataIntegrityViolationException("test", new SQLException("test DataIntegrityViolationException cause"));
    }
    else if (CASE_3_SQL.equals(sql))
    {
        throw new CannotGetJdbcConnectionException("test", new SQLException("test CannotGetJdbcConnectionException cause"));
    }

    return 0;
}
 
Example #4
Source File: MySQLDBConnection.java    From Gatekeeper with Apache License 2.0 6 votes vote down vote up
public List<String> checkDb(RdsQuery rdsQuery) throws GKUnsupportedDBException{
    String checkGrants = "SHOW GRANTS FOR CURRENT_USER";
    String address = rdsQuery.getAddress();
    List<String> issues = new ArrayList<>();

    try{
        logger.info("Checking the gatekeeper setup for " + address);
        JdbcTemplate template = connect(address, gkUserCredentialsProvider.getGatekeeperSecret(rdsQuery));
        String roleCheckResult = template.queryForObject(checkGrants, String.class);
        if(!roleCheckResult.contains("CREATE USER")){
            issues.add("gatekeeper is missing CREATE USER");
        }
    }catch(SQLException e){
        logger.error("Error running check query", e);
    }
    catch(CannotGetJdbcConnectionException ex){
        logger.error("Could not connect", ex);
        if(ex.getMessage().contains("password")) {
            issues.add("Password authentication failed for gatekeeper user");
        } else{
            issues.add("Unable to connect to DB (Check network configuration)");
        }
    }

    return issues;
}
 
Example #5
Source File: JdbcTemplateTests.java    From effectivejava with Apache License 2.0 6 votes vote down vote up
/**
 * If beanProperty is true, initialize via exception translator bean property;
 * if false, use afterPropertiesSet().
 */
private void doTestCouldntGetConnectionInOperationWithExceptionTranslatorInitialized(boolean beanProperty)
		throws SQLException {
	SQLException sqlException = new SQLException("foo", "07xxx");
	this.dataSource = mock(DataSource.class);
	given(this.dataSource.getConnection()).willThrow(sqlException);
	this.template = new JdbcTemplate();
	this.template.setDataSource(this.dataSource);
	this.template.setLazyInit(false);
	if (beanProperty) {
		// This will get a connection.
		this.template.setExceptionTranslator(new SQLErrorCodeSQLExceptionTranslator(this.dataSource));
	}
	else {
		// This will cause creation of default SQL translator.
		this.template.afterPropertiesSet();
	}
	RowCountCallbackHandler rcch = new RowCountCallbackHandler();
	this.thrown.expect(CannotGetJdbcConnectionException.class);
	this.thrown.expect(exceptionCause(sameInstance(sqlException)));
	this.template.query("SELECT ID, FORENAME FROM CUSTMR WHERE ID < 3", rcch);
}
 
Example #6
Source File: DefaultConcurrentRequestProcessor.java    From cobarclient with Apache License 2.0 6 votes vote down vote up
protected Object executeWith(Connection connection, SqlMapClientCallback action) {
    SqlMapSession session = getSqlMapClient().openSession();
    try {
        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();
    }
}
 
Example #7
Source File: MultiDataSourceTransaction.java    From Milkomeda with MIT License 6 votes vote down vote up
@Override
public Connection getConnection() throws SQLException {
    // 动态的根据DatabaseType获取不同的Connection
    String dataSourceType = SundialHolder.getDataSourceType();
    if (dataSourceType.equals(mainDataSourceType)) {
        if (mainConnection == null) {
            openMainConnection();
        }
        return mainConnection;
    } else {
        if (!otherConnectionMap.containsKey(dataSourceType)) {
            try {
                Connection conn = dataSource.getConnection();
                otherConnectionMap.put(dataSourceType, conn);
                return conn;
            } catch (SQLException ex) {
                throw new CannotGetJdbcConnectionException("Could not get JDBC Connection", ex);
            }
        }
        return otherConnectionMap.get(dataSourceType);
    }
}
 
Example #8
Source File: JdbcTemplateTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * If beanProperty is true, initialize via exception translator bean property;
 * if false, use afterPropertiesSet().
 */
private void doTestCouldNotGetConnectionInOperationWithExceptionTranslatorInitialized(boolean beanProperty)
		throws SQLException {

	SQLException sqlException = new SQLException("foo", "07xxx");
	this.dataSource = mock(DataSource.class);
	given(this.dataSource.getConnection()).willThrow(sqlException);
	this.template = new JdbcTemplate();
	this.template.setDataSource(this.dataSource);
	this.template.setLazyInit(false);
	if (beanProperty) {
		// This will get a connection.
		this.template.setExceptionTranslator(new SQLErrorCodeSQLExceptionTranslator(this.dataSource));
	}
	else {
		// This will cause creation of default SQL translator.
		this.template.afterPropertiesSet();
	}
	RowCountCallbackHandler rcch = new RowCountCallbackHandler();
	assertThatExceptionOfType(CannotGetJdbcConnectionException.class).isThrownBy(() ->
			this.template.query("SELECT ID, FORENAME FROM CUSTMR WHERE ID < 3", rcch))
		.withCause(sqlException);
}
 
Example #9
Source File: DefaultConcurrentRequestProcessor.java    From cobarclient with Apache License 2.0 6 votes vote down vote up
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 {
            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;
}
 
Example #10
Source File: DataServiceRetryAspect.java    From genie with Apache License 2.0 6 votes vote down vote up
/**
 * Constructor.
 *
 * @param dataServiceRetryProperties retry properties
 */
public DataServiceRetryAspect(final DataServiceRetryProperties dataServiceRetryProperties) {
    this.retryTemplate = new RetryTemplate();
    this.retryTemplate.setRetryPolicy(
        new SimpleRetryPolicy(
            dataServiceRetryProperties.getNoOfRetries(),
            new ImmutableMap.Builder<Class<? extends Throwable>, Boolean>()
                .put(CannotGetJdbcConnectionException.class, true)
                .put(CannotAcquireLockException.class, true)
                .put(DeadlockLoserDataAccessException.class, true)
                .put(OptimisticLockingFailureException.class, true)
                .put(PessimisticLockingFailureException.class, true)
                .put(ConcurrencyFailureException.class, true)
                // Will this work for cases where the write queries timeout on the client?
                .put(QueryTimeoutException.class, true)
                .put(TransientDataAccessResourceException.class, true)
                .put(JpaSystemException.class, true)
                .build()
        )
    );
    final ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();
    backOffPolicy.setInitialInterval(dataServiceRetryProperties.getInitialInterval());
    backOffPolicy.setMaxInterval(dataServiceRetryProperties.getMaxInterval());
    this.retryTemplate.setBackOffPolicy(backOffPolicy);
}
 
Example #11
Source File: JdbcTemplateTests.java    From effectivejava with Apache License 2.0 5 votes vote down vote up
@Test
public void testCouldntGetConnectionForOperationWithLazyExceptionTranslator() throws SQLException {
	SQLException sqlException = new SQLException("foo", "07xxx");
	this.dataSource = mock(DataSource.class);
	given(this.dataSource.getConnection()).willThrow(sqlException);
	this.template = new JdbcTemplate();
	this.template.setDataSource(this.dataSource);
	this.template.afterPropertiesSet();
	RowCountCallbackHandler rcch = new RowCountCallbackHandler();
	this.thrown.expect(CannotGetJdbcConnectionException.class);
	this.thrown.expect(exceptionCause(sameInstance(sqlException)));
	this.template.query("SELECT ID, FORENAME FROM CUSTMR WHERE ID < 3", rcch);
}
 
Example #12
Source File: JdbcTemplateTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testCouldntGetConnectionForOperationWithLazyExceptionTranslator() throws SQLException {
	SQLException sqlException = new SQLException("foo", "07xxx");
	this.dataSource = mock(DataSource.class);
	given(this.dataSource.getConnection()).willThrow(sqlException);
	this.template = new JdbcTemplate();
	this.template.setDataSource(this.dataSource);
	this.template.afterPropertiesSet();
	RowCountCallbackHandler rcch = new RowCountCallbackHandler();
	this.thrown.expect(CannotGetJdbcConnectionException.class);
	this.thrown.expect(exceptionCause(sameInstance(sqlException)));
	this.template.query("SELECT ID, FORENAME FROM CUSTMR WHERE ID < 3", rcch);
}
 
Example #13
Source File: JdbcTemplateTests.java    From effectivejava with Apache License 2.0 5 votes vote down vote up
@Test
public void testCouldntGetConnectionForOperationOrExceptionTranslator() throws SQLException {
	SQLException sqlException = new SQLException("foo", "07xxx");
	this.dataSource = mock(DataSource.class);
	given(this.dataSource.getConnection()).willThrow(sqlException);
	JdbcTemplate template = new JdbcTemplate(this.dataSource, false);
	RowCountCallbackHandler rcch = new RowCountCallbackHandler();
	this.thrown.expect(CannotGetJdbcConnectionException.class);
	this.thrown.expect(exceptionCause(sameInstance(sqlException)));
	template.query("SELECT ID, FORENAME FROM CUSTMR WHERE ID < 3", rcch);
}
 
Example #14
Source File: DataSourceUtils.java    From easyooo-framework with Apache License 2.0 5 votes vote down vote up
public static Connection getConnection(DataSource dataSource, String user, String pwd)
		throws CannotGetJdbcConnectionException {
	try {
		return doGetConnection(dataSource, user, pwd);
	} catch (SQLException ex) {
		throw new CannotGetJdbcConnectionException(
				"Could not get JDBC Connection", ex);
	}
}
 
Example #15
Source File: DataSourceUtils.java    From easyooo-framework with Apache License 2.0 5 votes vote down vote up
/**
 * 从数据源获取一个连接,该连接是否新连接,取决于连接池厂商是否会缓存Connection的策略
 * 
 * @param dataSource 
 * @return
 * @throws CannotGetJdbcConnectionException
 */
public static Connection getConnection(DataSource dataSource)
		throws CannotGetJdbcConnectionException {
	try {
		return doGetConnection(dataSource, null, null);
	} catch (SQLException ex) {
		throw new CannotGetJdbcConnectionException(
				"Could not get JDBC Connection", ex);
	}
}
 
Example #16
Source File: CobarAdapter.java    From tddl5 with Apache License 2.0 5 votes vote down vote up
@Override
public boolean checkConnection() {
    try {
        return null != getVersion();
    } catch (CannotGetJdbcConnectionException ex) {
        logger.error(new StringBuilder("checkConnection error for Url:").append(((DruidDataSource) this.getDataSource()).getUrl())
            .toString());
        return false;
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        return false;
    }
}
 
Example #17
Source File: DataUtils.java    From bamboobsc with Apache License 2.0 5 votes vote down vote up
public static Connection getConnection(DataSource dataSource) 
	throws CannotGetJdbcConnectionException, Exception {
	
	if (dataSource==null) {
		return null;
	}
	return DataSourceUtils.getConnection(dataSource);
}
 
Example #18
Source File: JdbcTemplateTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testCouldntGetConnectionForOperationOrExceptionTranslator() throws SQLException {
	SQLException sqlException = new SQLException("foo", "07xxx");
	this.dataSource = mock(DataSource.class);
	given(this.dataSource.getConnection()).willThrow(sqlException);
	JdbcTemplate template = new JdbcTemplate(this.dataSource, false);
	RowCountCallbackHandler rcch = new RowCountCallbackHandler();
	this.thrown.expect(CannotGetJdbcConnectionException.class);
	this.thrown.expect(exceptionCause(sameInstance(sqlException)));
	template.query("SELECT ID, FORENAME FROM CUSTMR WHERE ID < 3", rcch);
}
 
Example #19
Source File: JdbcTemplateTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testCouldNotGetConnectionForOperationOrExceptionTranslator() throws SQLException {
	SQLException sqlException = new SQLException("foo", "07xxx");
	this.dataSource = mock(DataSource.class);
	given(this.dataSource.getConnection()).willThrow(sqlException);
	JdbcTemplate template = new JdbcTemplate(this.dataSource, false);
	RowCountCallbackHandler rcch = new RowCountCallbackHandler();

	assertThatExceptionOfType(CannotGetJdbcConnectionException.class).isThrownBy(() ->
			template.query("SELECT ID, FORENAME FROM CUSTMR WHERE ID < 3", rcch))
		.withCause(sqlException);
}
 
Example #20
Source File: JdbcTemplateTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testCouldNotGetConnectionForOperationWithLazyExceptionTranslator() throws SQLException {
	SQLException sqlException = new SQLException("foo", "07xxx");
	this.dataSource = mock(DataSource.class);
	given(this.dataSource.getConnection()).willThrow(sqlException);
	this.template = new JdbcTemplate();
	this.template.setDataSource(this.dataSource);
	this.template.afterPropertiesSet();
	RowCountCallbackHandler rcch = new RowCountCallbackHandler();

	assertThatExceptionOfType(CannotGetJdbcConnectionException.class).isThrownBy(() ->
			this.template.query("SELECT ID, FORENAME FROM CUSTMR WHERE ID < 3", rcch))
		.withCause(sqlException);
}
 
Example #21
Source File: JdbcTemplateTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testCouldNotGetConnectionForOperationOrExceptionTranslator() throws SQLException {
	SQLException sqlException = new SQLException("foo", "07xxx");
	this.dataSource = mock(DataSource.class);
	given(this.dataSource.getConnection()).willThrow(sqlException);
	JdbcTemplate template = new JdbcTemplate(this.dataSource, false);
	RowCountCallbackHandler rcch = new RowCountCallbackHandler();

	this.thrown.expect(CannotGetJdbcConnectionException.class);
	this.thrown.expect(exceptionCause(sameInstance(sqlException)));
	template.query("SELECT ID, FORENAME FROM CUSTMR WHERE ID < 3", rcch);
}
 
Example #22
Source File: JdbcTemplateTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testCouldNotGetConnectionForOperationWithLazyExceptionTranslator() throws SQLException {
	SQLException sqlException = new SQLException("foo", "07xxx");
	this.dataSource = mock(DataSource.class);
	given(this.dataSource.getConnection()).willThrow(sqlException);
	this.template = new JdbcTemplate();
	this.template.setDataSource(this.dataSource);
	this.template.afterPropertiesSet();
	RowCountCallbackHandler rcch = new RowCountCallbackHandler();

	this.thrown.expect(CannotGetJdbcConnectionException.class);
	this.thrown.expect(exceptionCause(sameInstance(sqlException)));
	this.template.query("SELECT ID, FORENAME FROM CUSTMR WHERE ID < 3", rcch);
}
 
Example #23
Source File: MaintenanceManagerSupport.java    From OpenCue with Apache License 2.0 5 votes vote down vote up
/**
 * Checks the cue for down hosts. If there are any down they are cleared of
 * procs. Additionally the orphaned proc check is done.
 *
 * If a DB Connection exception is thrown, its caught and the current time
 * is noted. Once the DB comes back up, down proc checks will not resume for
 * WAIT_FOR_HOST_REPORTS_MS milliseconds. This is to give procs a chance to
 * report back in.
 *
 */
public void checkHardwareState() {
    try {

        if (!maintenanceDao
                .lockTask(MaintenanceTask.LOCK_HARDWARE_STATE_CHECK)) {
            return;
        }
        try {
            if (dbConnectionFailureTime > 0) {
                if (System.currentTimeMillis() - dbConnectionFailureTime < WAIT_FOR_HOST_REPORTS_MS) {
                    logger.warn("NOT running checkHardwareState, waiting for hosts to report in.");
                    return;
                }
                dbConnectionFailureTime = 0;
            }

            int hosts = maintenanceDao.setUpHostsToDown();
            if (hosts > 0) {
                clearDownProcs();
            }
            clearOrphanedProcs();
        } finally {
            maintenanceDao
                    .unlockTask(MaintenanceTask.LOCK_HARDWARE_STATE_CHECK);
        }
    } catch (CannotGetJdbcConnectionException db) {
        logger.warn("error obtaining DB connection for hardware state check");
        // If this fails, then the network went down, set the current time.
        dbConnectionFailureTime = System.currentTimeMillis();
    }
}
 
Example #24
Source File: PostgresDBConnection.java    From Gatekeeper with Apache License 2.0 4 votes vote down vote up
public List<String> checkDb(RdsQuery rdsQuery) throws GKUnsupportedDBException {
    String address = rdsQuery.getAddress();

    String gkUserCreateRoleCheck = "select rolcreaterole from pg_roles where rolname = 'gatekeeper'";
    String gkRoleCheck = "select rolname from pg_roles where rolname in ('gk_datafix','gk_dba','gk_readonly')";

    List<String> issues = new ArrayList<>();
    List<String> gkRoles = new ArrayList<>();
    gkRoles.addAll(Arrays.asList("gk_datafix", "gk_readonly", "gk_dba"));
    PGPoolingDataSource dataSource = null;

    try{
        logger.info("Checking the gatekeeper setup for " + address);
        dataSource = connect(address, gkUserCredentialsProvider.getGatekeeperSecret(rdsQuery));
        JdbcTemplate conn = new JdbcTemplate(dataSource);
        Boolean createRolePermCheckResult = conn.queryForObject(gkUserCreateRoleCheck, Boolean.class);
        List<String> roleCheckResult = conn.queryForList(gkRoleCheck, String.class);

        if(!createRolePermCheckResult){
            issues.add("gatekeeper user missing createrole");
        }
        gkRoles.removeAll(roleCheckResult);
        if(!gkRoles.isEmpty()) {
            issues.add("missing the following roles: " + gkRoles);
        }
    }catch(SQLException e){
        logger.error("Error running check query", e);
    } catch(CannotGetJdbcConnectionException ex){
        logger.error("Failed to connect to DB", ex);
        if(ex.getMessage().contains("password")) {
            issues.add("Password authentication failed for gatekeeper user");
        }else{
            issues.add("Unable to connect to DB (" + ex.getCause().getMessage() + ")");
        }
    }finally{
        if(dataSource != null) {
            dataSource.close();
        }
    }

    return issues;

}
 
Example #25
Source File: JdbcServiceImpl.java    From herd with Apache License 2.0 4 votes vote down vote up
/**
 * Executes a single statement using the given JDBC template. The given statement will be updated with the result and status.
 *
 * @param jdbcTemplate the JDBC template
 * @param jdbcStatement the JDBC statement to execute
 * @param variables the mapping of variables
 * @param jdbcStatementIndex the index of the statement
 */
private void executeStatement(JdbcTemplate jdbcTemplate, JdbcStatement jdbcStatement, Map<String, Object> variables, int jdbcStatementIndex)
{
    // This is the exception to be set as the error message in the response
    Throwable exception = null;
    try
    {
        String sql = evaluate(jdbcStatement.getSql(), variables, "jdbc statement sql");
        validateSqlStatement(sql, jdbcStatementIndex);

        // Process UPDATE type statements
        if (JdbcStatementType.UPDATE.equals(jdbcStatement.getType()))
        {
            int result = jdbcDao.update(jdbcTemplate, sql);

            jdbcStatement.setStatus(JdbcStatementStatus.SUCCESS);
            jdbcStatement.setResult(String.valueOf(result));
        }
        // Process QUERY type statements
        else if (JdbcStatementType.QUERY.equals(jdbcStatement.getType()))
        {
            Integer maxResults = configurationHelper.getProperty(ConfigurationValue.JDBC_RESULT_MAX_ROWS, Integer.class);

            JdbcStatementResultSet jdbcStatementResultSet = jdbcDao.query(jdbcTemplate, sql, maxResults);

            jdbcStatement.setStatus(JdbcStatementStatus.SUCCESS);
            jdbcStatement.setResultSet(jdbcStatementResultSet);
        }
        // Any other statement types are unrecognized. This case should not be possible unless developer error.
        else
        {
            throw new IllegalStateException("Unsupported JDBC statement type '" + jdbcStatement.getType() + "'");
        }
    }
    catch (CannotGetJdbcConnectionException cannotGetJdbcConnectionException)
    {
        /*
         * When the statement fails to execute due to connection errors. This usually indicates that the connection information which was specified is
         * wrong, or there is a network issue. Either way, it would indicate user error.
         * We get the wrapped exception and throw again as an IllegalArgumentException.
         */
        Throwable causeThrowable = cannotGetJdbcConnectionException.getCause();
        throw new IllegalArgumentException(String.valueOf(causeThrowable).trim(), cannotGetJdbcConnectionException);
    }
    catch (DataAccessException dataAccessException)
    {
        // DataAccessException's cause is a SQLException which is thrown by driver
        // We will use the SQLException message result
        exception = dataAccessException.getCause();
    }

    // If there was an error
    if (exception != null)
    {
        // Set status to error and result as message
        jdbcStatement.setStatus(JdbcStatementStatus.ERROR);
        jdbcStatement.setErrorMessage(maskSensitiveInformation(exception, variables));
    }
}
 
Example #26
Source File: CannotGetJdbcConnectionExceptionManualTest.java    From tutorials with MIT License 4 votes vote down vote up
@Test(expected = CannotGetJdbcConnectionException.class)
public void whenJdbcUrlIncorrect_thenCannotGetJdbcConnectionException() {
    JdbcTemplate jdbcTemplate = new JdbcTemplate(restDataSource);
    jdbcTemplate.execute("select * from foo");
}
 
Example #27
Source File: DataSourceUtils.java    From lams with GNU General Public License v2.0 3 votes vote down vote up
/**
 * 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
 */
public static Connection getConnection(DataSource dataSource) throws CannotGetJdbcConnectionException {
	try {
		return doGetConnection(dataSource);
	}
	catch (SQLException ex) {
		throw new CannotGetJdbcConnectionException("Could not get JDBC Connection", ex);
	}
}
 
Example #28
Source File: DataSourceUtils.java    From effectivejava with Apache License 2.0 3 votes vote down vote up
/**
 * 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
 */
public static Connection getConnection(DataSource dataSource) throws CannotGetJdbcConnectionException {
	try {
		return doGetConnection(dataSource);
	}
	catch (SQLException ex) {
		throw new CannotGetJdbcConnectionException("Could not get JDBC Connection", ex);
	}
}
 
Example #29
Source File: DataSourceUtils.java    From spring4-understanding with Apache License 2.0 3 votes vote down vote up
/**
 * 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
 */
public static Connection getConnection(DataSource dataSource) throws CannotGetJdbcConnectionException {
	try {
		return doGetConnection(dataSource);
	}
	catch (SQLException ex) {
		throw new CannotGetJdbcConnectionException("Could not get JDBC Connection", ex);
	}
}
 
Example #30
Source File: JdbcDaoSupport.java    From effectivejava with Apache License 2.0 2 votes vote down vote up
/**
 * Get a JDBC Connection, either from the current transaction or a new one.
 * @return the JDBC Connection
 * @throws CannotGetJdbcConnectionException if the attempt to get a Connection failed
 * @see org.springframework.jdbc.datasource.DataSourceUtils#getConnection(javax.sql.DataSource)
 */
protected final Connection getConnection() throws CannotGetJdbcConnectionException {
	return DataSourceUtils.getConnection(getDataSource());
}