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

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

Introduction

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

Prototype

@Override
public void afterPropertiesSet() 

Source Link

Document

Eagerly initialize the exception translator, if demanded, creating a default one for the specified DataSource if none set.

Usage

From source file:com.github.totyumengr.minicubes.cluster.DiscardController.java

@RequestMapping(value = "/dummyMerge", method = { RequestMethod.POST, RequestMethod.GET })
public @ResponseBody String mergePrepare(@NotBlank @RequestParam String timeSeries, @RequestParam String sql) {

    LOGGER.info("Try to merge data to {}.", sql, timeSeries);
    JdbcTemplate template = new JdbcTemplate(dataSource);
    template.afterPropertiesSet();
    template.execute(sql);//from  ww w  .ja va 2  s. c o m
    LOGGER.info("Success for merge data to {}.", sql, timeSeries);

    return OK;
}

From source file:be.solidx.hot.spring.config.DataConfig.java

@Bean
public Map<be.solidx.hot.spring.config.HotConfig.DataSource, DataSource> dataSources() throws Exception {
    Map<be.solidx.hot.spring.config.HotConfig.DataSource, DataSource> dataSources = new HashMap<be.solidx.hot.spring.config.HotConfig.DataSource, DataSource>();
    for (be.solidx.hot.spring.config.HotConfig.DataSource dataSource : hotConfig.getDataSources()) {
        switch (dataSource.getEngine()) {
        case ORACLE:
            dataSources.put(dataSource,/*from w w  w . j av  a2  s  .com*/
                    oracleSimpleDriverDataSource(dataSource.getHostname(), dataSource.getPort(),
                            dataSource.getDatabase(), dataSource.getUsername(), dataSource.getPassword()));
            break;
        case DB2:
            dataSources.put(dataSource,
                    db2SimpleDriverDataSource(dataSource.getHostname(), dataSource.getPort(),
                            dataSource.getDatabase(), dataSource.getUsername(), dataSource.getPassword()));
            break;
        case MYSQL:
            dataSources.put(dataSource,
                    mysqlSimpleDriverDataSource(dataSource.getHostname(), dataSource.getPort(),
                            dataSource.getDatabase(), dataSource.getUsername(), dataSource.getPassword()));
            break;
        case PGSQL:
            dataSources.put(dataSource,
                    pgsqlSimpleDriverDataSource(dataSource.getHostname(), dataSource.getPort(),
                            dataSource.getDatabase(), dataSource.getUsername(), dataSource.getPassword()));
            break;
        case HSQLDB:
            DataSource sqlDataSource = hsqldbSimpleDriverDataSource(dataSource.getDatabase(),
                    dataSource.getUsername(), dataSource.getPassword());
            try {
                JdbcTemplate jdbcTemplate = new JdbcTemplate(sqlDataSource);
                jdbcTemplate.afterPropertiesSet();
                for (Resource resource : applicationContext.getResources("classpath*:/sql/*-init.sql")) {
                    String[] statements = IOUtils.toString(resource.getInputStream()).split(";");
                    jdbcTemplate.batchUpdate(statements);
                }
            } catch (Exception e) {
                logger.error("", e);
            }
            dataSources.put(dataSource, sqlDataSource);
            break;
        default:
            break;
        }
    }
    return dataSources;
}

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

/**
 *///from   ww  w  .  jav  a  2 s .c o m
@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:org.kuali.rice.kew.test.TestUtilities.java

public static JdbcTemplate getJdbcTemplate() {
    JdbcTemplate jdbcTemplate = new JdbcTemplate(KEWServiceLocator.getDataSource());
    jdbcTemplate.afterPropertiesSet();
    return jdbcTemplate;
}

From source file:org.springframework.integration.jdbc.JdbcMessageStoreTests.java

@Test
@Transactional//from   w  ww . ja  v  a 2  s. c om
public void testRemoveMessageGroup() throws Exception {
    JdbcTemplate template = new JdbcTemplate(dataSource);
    template.afterPropertiesSet();
    String groupId = "X";

    Message<String> message = MessageBuilder.withPayload("foo").setCorrelationId(groupId).build();
    messageStore.addMessageToGroup(groupId, message);
    messageStore.removeMessageGroup(groupId);
    MessageGroup group = messageStore.getMessageGroup(groupId);
    assertEquals(0, group.size());

    String uuidGroupId = UUIDConverter.getUUID(groupId).toString();
    assertTrue(
            template.queryForList("SELECT * from INT_GROUP_TO_MESSAGE where GROUP_KEY = '" + uuidGroupId + "'")
                    .size() == 0);
}

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

public void testCouldntGetConnectionForOperationWithLazyExceptionTranslator() throws SQLException {
    SQLException sex = new SQLException("foo", "07xxx");

    ctrlDataSource = MockControl.createControl(DataSource.class);
    mockDataSource = (DataSource) ctrlDataSource.getMock();
    mockDataSource.getConnection();/*  w  ww . j a v a  2  s .  com*/
    ctrlDataSource.setThrowable(sex, 1);
    replay();

    try {
        JdbcTemplate template2 = new JdbcTemplate();
        template2.setDataSource(mockDataSource);
        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();
}

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 .java2  s. c  o m
 */
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

public void testSQLErrorCodeTranslationWithSpecifiedDbName() throws Exception {
    final SQLException sex = new SQLException("I have a known problem", "99999", 1054);
    final String sql = "SELECT ID FROM CUSTOMER";

    MockControl ctrlResultSet = MockControl.createControl(ResultSet.class);
    ResultSet mockResultSet = (ResultSet) ctrlResultSet.getMock();
    mockResultSet.next();//from w w  w  . j a v a 2 s.  c  o  m
    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);

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

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

    ctrlResultSet.verify();
    ctrlStatement.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//from w ww  .j ava2  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();
}

From source file:org.springframework.session.jdbc.JdbcOperationsSessionRepository.java

private static JdbcTemplate createDefaultJdbcTemplate(DataSource dataSource) {
    JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
    jdbcTemplate.afterPropertiesSet();
    return jdbcTemplate;
}