Example usage for org.springframework.jdbc.core JdbcTemplate setExceptionTranslator

List of usage examples for org.springframework.jdbc.core JdbcTemplate setExceptionTranslator

Introduction

In this page you can find the example usage for org.springframework.jdbc.core JdbcTemplate setExceptionTranslator.

Prototype

public void setExceptionTranslator(SQLExceptionTranslator exceptionTranslator) 

Source Link

Document

Set the exception translator for this instance.

Usage

From source file:io.lavagna.config.PersistenceAndServiceConfig.java

@Bean
public NamedParameterJdbcTemplate simpleJdbcTemplate(Environment env, DataSource dataSource) {
    JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
    // mysql does not support check constraints
    if ("MYSQL".equals(env.getProperty("datasource.dialect"))) {
        CustomSQLErrorCodesTranslator tr = new CustomSQLErrorCodesTranslator();
        tr.setDataSource(dataSource);//from  www  . j  av a  2s. c o  m
        jdbcTemplate.setExceptionTranslator(tr);
    }
    return new NamedParameterJdbcTemplate(jdbcTemplate);
}

From source file:nz.geek.caffe.spring.hdb.HANAExceptionMappingTest.java

/**
 *///from w  w  w.j  av a  2s .  com
@Test
public void testUnableToConnect() {
    final DriverManagerDataSource ds = new DriverManagerDataSource("jdbc:sap://blahhost:30115", "blah", "blah");

    JdbcTemplate template = new JdbcTemplate();
    template.setExceptionTranslator(new SQLErrorCodeSQLExceptionTranslator("HDB"));
    template.setDataSource(new LazyConnectionDataSourceProxy(ds));
    template.afterPropertiesSet();

    try {
        template.execute("SELECT 1 FROM DUMMY");

        Assert.fail("connect should have failed");
    } catch (final DataAccessResourceFailureException e) {
        // expected
    }
}

From source file:com.jbrisbin.vpc.jobsched.sql.SqlMessageHandler.java

public SqlMessage handleMessage(final SqlMessage msg) throws Exception {
    log.debug("handling message: " + msg.toString());

    DataSource ds = appCtx.getBean(msg.getDatasource(), DataSource.class);
    JdbcTemplate tmpl = new JdbcTemplate(ds);

    String sql = msg.getSql();// w ww .j a v  a  2  s  .  c o m
    CallableStatementCreator stmtCreator = null;
    CallableStatementCallback<SqlMessage> callback = null;
    if (sql.startsWith("plugin:")) {
        // Use a plugin to get the sql
        String pluginName = (sql.contains("?") ? sql.substring(7, sql.indexOf('?')) : sql.substring(7));
        final Plugin plugin = groovyPluginManager.getPlugin(pluginName);
        Map<String, Object> vars = new LinkedHashMap<String, Object>();
        vars.put("message", msg);
        vars.put("datasource", ds);
        vars.put("listen", groovyClosureFactory.createListenClosure(msg));
        vars.put("mapreduce", groovyClosureFactory.createMapReduceClosure(msg));
        plugin.setContext(vars);

        // Execute this plugin
        plugin.run();

        Object o = plugin.get("sql");
        if (null != o && o instanceof Closure) {
            sql = ((Closure) o).call(msg).toString();
        } else if (o instanceof String || o instanceof GString) {
            sql = o.toString();
        } else {
            throw new IllegalStateException("Can't convert " + String.valueOf(o) + " to SQL statement.");
        }
        msg.setSql(sql);

        o = plugin.get("statementCreator");
        if (null != o && o instanceof Closure) {
            stmtCreator = new CallableStatementCreator() {
                public CallableStatement createCallableStatement(Connection con) throws SQLException {
                    Object obj = ((Closure) plugin.get("statementCreator")).call(new Object[] { con, msg });
                    log.debug("from plugin statementCreator: " + String.valueOf(obj));
                    return (CallableStatement) obj;
                }
            };
        } else {
            throw new IllegalStateException("Can't convert " + String.valueOf(o)
                    + " to CallableStatementCreator. Define a closure named 'statementCreator' in your plugin.");
        }

        o = plugin.get("callback");
        if (null != o && o instanceof Closure) {
            callback = new CallableStatementCallback<SqlMessage>() {
                public SqlMessage doInCallableStatement(CallableStatement cs)
                        throws SQLException, DataAccessException {
                    Object obj = ((Closure) plugin.get("callback")).call(new Object[] { cs, msg });
                    log.debug("from plugin callback: " + String.valueOf(obj));
                    return (SqlMessage) obj;
                }
            };
        } else {
            throw new IllegalStateException("Can't convert " + String.valueOf(o)
                    + " to CallableStatementCallback. Define a closure named 'callback' in your plugin.");
        }
    } else {
        stmtCreator = new CallableStatementCreator() {
            public CallableStatement createCallableStatement(Connection connection) throws SQLException {
                CallableStatement stmt = connection.prepareCall(msg.getSql());
                List<Object> params = msg.getParams();
                if (null != params) {
                    int index = 1;
                    for (Object obj : params) {
                        stmt.setObject(index++, obj);
                    }
                }
                return stmt;
            }
        };
        callback = new CallableStatementCallback<SqlMessage>() {
            public SqlMessage doInCallableStatement(CallableStatement callableStatement)
                    throws SQLException, DataAccessException {
                if (null == msg.getResults().getData()) {
                    msg.getResults().setData(new ArrayList<List<Object>>());
                }
                if (callableStatement.execute()) {
                    ResultSet results = callableStatement.getResultSet();

                    // Pull out column names
                    ResultSetMetaData meta = results.getMetaData();
                    String[] columns = new String[meta.getColumnCount()];
                    for (int i = 1; i <= meta.getColumnCount(); i++) {
                        columns[i - 1] = meta.getColumnName(i);
                    }
                    msg.getResults().getColumnNames().addAll(Arrays.asList(columns));

                    int total = 0;
                    while (results.next()) {
                        List<Object> row = new ArrayList<Object>(columns.length);
                        for (int i = 1; i <= columns.length; i++) {
                            row.add(results.getObject(i));
                        }
                        msg.getResults().getData().add(row);
                        total++;
                    }
                    msg.getResults().setTotalRows(total);

                } else {
                    msg.getResults().getColumnNames().add("updateCount");
                    msg.getResults().setTotalRows(1);
                    List<Object> updCnt = new ArrayList<Object>(1);
                    updCnt.add(callableStatement.getUpdateCount());
                    msg.getResults().getData().add(updCnt);
                }
                return msg;
            }
        };
    }
    try {
        tmpl.setExceptionTranslator(appCtx.getBean(SQLExceptionTranslator.class));
    } catch (NoSuchBeanDefinitionException notfound) {
        // IGNORED
    }

    if (null != stmtCreator && null != callback) {
        try {
            tmpl.execute(stmtCreator, callback);
        } catch (Throwable t) {
            log.error(t.getMessage(), t);
            List<String> errors = new ArrayList<String>();
            errors.add(t.getMessage());
            Throwable cause = t.getCause();
            if (null != cause) {
                do {
                    errors.add(cause.getMessage());
                } while (null != (cause = cause.getCause()));
            }
            msg.getResults().setErrors(errors);
        }
    } else {
        log.warn("CallableStatementCreator and/or CallableStatementCallback where empty. "
                + "Make sure your plugin provides these under 'statementCreator' and 'callback' respectively.");
    }
    return msg;
}

From source file:org.springframework.jdbc.core.JdbcTemplateTests.java

/**
 * If beanProperty is true, initialize via exception translator bean property;
 * if false, use afterPropertiesSet().//from ww w . j  a  v  a  2 s  . c om
 */
private void doTestCouldntGetConnectionInOperationWithExceptionTranslatorInitialized(boolean beanProperty)
        throws SQLException {

    SQLException sex = new SQLException("foo", "07xxx");

    ctrlConnection = MockControl.createControl(Connection.class);
    mockConnection = (Connection) ctrlConnection.getMock();
    //mockConnection.getMetaData();
    //ctrlConnection.setReturnValue(null, 1);
    //mockConnection.close();
    //ctrlConnection.setVoidCallable(1);
    ctrlConnection.replay();

    // Change behaviour in setUp() because we only expect one call to getConnection():
    // none is necessary to get metadata for exception translator
    ctrlDataSource = MockControl.createControl(DataSource.class);
    mockDataSource = (DataSource) ctrlDataSource.getMock();
    // Upfront call for metadata - no longer the case
    //mockDataSource.getConnection();
    //ctrlDataSource.setReturnValue(mockConnection, 1);
    // One call for operation
    mockDataSource.getConnection();
    ctrlDataSource.setThrowable(sex, 2);
    ctrlDataSource.replay();

    try {
        JdbcTemplate template2 = new JdbcTemplate();
        template2.setDataSource(mockDataSource);
        template2.setLazyInit(false);
        if (beanProperty) {
            // This will get a connection.
            template2.setExceptionTranslator(new SQLErrorCodeSQLExceptionTranslator(mockDataSource));
        } else {
            // This will cause creation of default SQL translator.
            // Note that only call should be effective.
            template2.afterPropertiesSet();
            template2.afterPropertiesSet();
        }
        RowCountCallbackHandler rcch = new RowCountCallbackHandler();
        template2.query("SELECT ID, FORENAME FROM CUSTMR WHERE ID < 3", rcch);
        fail("Shouldn't have executed query without a connection");
    } catch (CannotGetJdbcConnectionException ex) {
        // pass
        assertTrue("Check root cause", ex.getCause() == sex);
    }

    ctrlDataSource.verify();
    ctrlConnection.verify();
}

From source file:org.springframework.jdbc.core.JdbcTemplateTests.java

/**
 * Test that we see an SQLException translated using Error Code.
 * If we provide the SQLExceptionTranslator, we shouldn't use a connection
 * to get the metadata/* ww  w.j a  v a  2 s . c o m*/
 */
public void testUseCustomSQLErrorCodeTranslator() throws Exception {
    // Bad SQL state
    final SQLException sex = new SQLException("I have a known problem", "07000", 1054);
    final String sql = "SELECT ID FROM CUSTOMER";

    MockControl ctrlResultSet = MockControl.createControl(ResultSet.class);
    ResultSet mockResultSet = (ResultSet) ctrlResultSet.getMock();
    mockResultSet.next();
    ctrlResultSet.setReturnValue(true);
    mockResultSet.close();
    ctrlResultSet.setVoidCallable();

    MockControl ctrlStatement = MockControl.createControl(PreparedStatement.class);
    PreparedStatement mockStatement = (PreparedStatement) ctrlStatement.getMock();
    mockStatement.executeQuery(sql);
    ctrlStatement.setReturnValue(mockResultSet);
    mockStatement.close();
    ctrlStatement.setVoidCallable();

    mockConnection.createStatement();
    ctrlConnection.setReturnValue(mockStatement);

    // Change behaviour in setUp() because we only expect one call to getConnection():
    // none is necessary to get metadata for exception translator
    ctrlConnection = MockControl.createControl(Connection.class);
    mockConnection = (Connection) ctrlConnection.getMock();
    mockConnection.createStatement();
    ctrlConnection.setReturnValue(mockStatement, 1);
    mockConnection.close();
    ctrlConnection.setVoidCallable(1);
    ctrlConnection.replay();

    ctrlDataSource = MockControl.createControl(DataSource.class);
    mockDataSource = (DataSource) ctrlDataSource.getMock();
    mockDataSource.getConnection();
    ctrlDataSource.setReturnValue(mockConnection, 1);
    ctrlDataSource.replay();
    ///// end changed behaviour

    ctrlResultSet.replay();
    ctrlStatement.replay();

    JdbcTemplate template = new JdbcTemplate();
    template.setDataSource(mockDataSource);
    // Set custom exception translator
    template.setExceptionTranslator(new SQLStateSQLExceptionTranslator());
    template.afterPropertiesSet();
    try {
        template.query(sql, new RowCallbackHandler() {
            public void processRow(ResultSet rs) throws SQLException {
                throw sex;
            }
        });
        fail("Should have thrown exception");
    } catch (BadSqlGrammarException ex) {
        assertTrue("Wanted same exception back, not " + ex, sex == ex.getCause());
    }

    ctrlResultSet.verify();
    ctrlStatement.verify();

    // We didn't call superclass replay() so we need to check these ourselves
    ctrlDataSource.verify();
    ctrlConnection.verify();
}