Java Code Examples for org.springframework.jdbc.datasource.SingleConnectionDataSource

The following examples show how to use org.springframework.jdbc.datasource.SingleConnectionDataSource. These examples are extracted from open source projects. 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 Project: spring-analysis-note   Source File: JdbcTemplateTests.java    License: MIT License 6 votes vote down vote up
@Test
public void testLeaveConnectionOpenOnRequest() throws Exception {
	String sql = "SELECT ID, FORENAME FROM CUSTMR WHERE ID < 3";

	given(this.resultSet.next()).willReturn(false);
	given(this.connection.isClosed()).willReturn(false);
	given(this.connection.createStatement()).willReturn(this.preparedStatement);
	// if close is called entire test will fail
	willThrow(new RuntimeException()).given(this.connection).close();

	SingleConnectionDataSource scf = new SingleConnectionDataSource(this.dataSource.getConnection(), false);
	this.template = new JdbcTemplate(scf, false);
	RowCountCallbackHandler rcch = new RowCountCallbackHandler();
	this.template.query(sql, rcch);

	verify(this.resultSet).close();
	verify(this.preparedStatement).close();
}
 
Example 2
protected List<Recipient> getRecipientList(int companyID, String statement, Object[] parameters, boolean useUnsharpRecipientQuery) throws SQLException {
	try (Connection connection = getDataSource().getConnection()) {
		try {
			// TODO: IGNORE_BOUNCELOAD_COMPANY_ID is a bad hack for CONRAD-371!!!
			if (useUnsharpRecipientQuery) {
				setRuleOptimizerMode(connection, true);
			}
			
			final SingleConnectionDataSource scds = new SingleConnectionDataSource(connection, true);
			final JdbcTemplate template = new JdbcTemplate(scds);
			RecipientRowMapper rowMapper = new RecipientRowMapper(recipientFactory, companyID);
			
			return template.query(statement, parameters, rowMapper);
			
		} finally {
			// TODO: IGNORE_BOUNCELOAD_COMPANY_ID is a bad hack for CONRAD-371!!!
			if (useUnsharpRecipientQuery) {
				setRuleOptimizerMode(connection, false);
			}
		}
	}
}
 
Example 3
private <T> T selectRecipients(@VelocityCheck int companyID, ResultSetExtractor<T> extractor, String sqlStatement, Object... sqlParameters) throws SQLException {
	// TODO: IGNORE_BOUNCELOAD_COMPANY_ID is a bad hack for CONRAD-371
	final boolean useUnsharpRecipientQuery = configService.useUnsharpRecipientQuery(companyID);

	try (Connection connection = getDataSource().getConnection()) {
		try {
			// TODO: IGNORE_BOUNCELOAD_COMPANY_ID is a bad hack for CONRAD-371!!!
			if (useUnsharpRecipientQuery) {
				setRuleOptimizerMode(connection, true);
			}

			final SingleConnectionDataSource scds = new SingleConnectionDataSource(connection, true);
			final JdbcTemplate template = new JdbcTemplate(scds);

			return template.query(sqlStatement, extractor, sqlParameters);
		} finally {
			// TODO: IGNORE_BOUNCELOAD_COMPANY_ID is a bad hack for CONRAD-371!!!
			if (useUnsharpRecipientQuery) {
				setRuleOptimizerMode(connection, false);
			}
		}
	}
}
 
Example 4
Source Project: java-technology-stack   Source File: JdbcTemplateTests.java    License: MIT License 6 votes vote down vote up
@Test
public void testLeaveConnectionOpenOnRequest() throws Exception {
	String sql = "SELECT ID, FORENAME FROM CUSTMR WHERE ID < 3";

	given(this.resultSet.next()).willReturn(false);
	given(this.connection.isClosed()).willReturn(false);
	given(this.connection.createStatement()).willReturn(this.preparedStatement);
	// if close is called entire test will fail
	willThrow(new RuntimeException()).given(this.connection).close();

	SingleConnectionDataSource scf = new SingleConnectionDataSource(this.dataSource.getConnection(), false);
	this.template = new JdbcTemplate(scf, false);
	RowCountCallbackHandler rcch = new RowCountCallbackHandler();
	this.template.query(sql, rcch);

	verify(this.resultSet).close();
	verify(this.preparedStatement).close();
}
 
Example 5
@Override
public void migrate(Context context) throws Exception {
	logger.info("About to check if mssql hibernate_sequence needs fix from table to a sequence");
	try {
		JdbcTemplate jdbcTemplate = new JdbcTemplate(new SingleConnectionDataSource(context.getConnection(), true));
		// in case we have old wrongly created table, this command should succeed
		jdbcTemplate.execute("select 1 from hibernate_sequence");
		fixHibernateSequence = true;
		logger.info("Looks like we have hibernate_sequence table, initiate fix");
	}
	catch (Exception e) {
		logger.debug("Unable to query hibernate_sequence table, looks like we have a proper sequence", e);
	}
	// will result call to get commands from this class and then we choose which ones to run
	super.migrate(context);
}
 
Example 6
Source Project: multitenant   Source File: DatabaseResourceAllocator.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void allocate(Organization organization) {
	SingleConnectionDataSource dataSource = dataSourceService.createSingleConnectionDataSource(organization);
	try {
		scriptService.runScripts(organization.getId(), dataSource, resourceScript, "database");
	} finally {
		if (dataSource != null) {
			try {
				dataSource.destroy();
			} catch (Throwable ex) {
				logger.debug("Could not destroy DataSource", ex);
			}
		}
	}
	entityManagerFactoryService.getOrCreateEntityManagerFactory(organization);
}
 
Example 7
@Override
public void generateTables(Organization organization) {
	SingleConnectionDataSource dataSource = dataSourceService.createSingleConnectionDataSource(organization);
	if (dataSource != null) {
		Map<String, Object> vendorProperties = getVendorProperties(dataSource);
		customizeVendorProperties(vendorProperties);
		Builder builder = getEntityManagerFactoryBuilder(dataSource).dataSource(dataSource).packages(packagesToScan.split(","))
				.properties(vendorProperties).jta(isJta());
		LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = builder.build();

	    publishEvent(organization, builder);

		entityManagerFactoryBean.setBeanClassLoader(classLoader);
		entityManagerFactoryBean.setBeanFactory(beanFactory);
		entityManagerFactoryBean.setBeanName(beanName);
		entityManagerFactoryBean.setLoadTimeWeaver(loadTimeWeaver);
		entityManagerFactoryBean.setResourceLoader(resourceLoader);
		entityManagerFactoryBean.afterPropertiesSet();
		entityManagerFactoryBean.destroy();
		dataSource.destroy();
	}
}
 
Example 8
@Override
public EntityManagerFactory createTempEntityManagerFactory(
		Organization organization) {
	SingleConnectionDataSource dataSource = dataSourceService.createSingleConnectionDataSource(organization);
	if (dataSource != null) {
		Map<String, Object> vendorProperties = getVendorProperties(dataSource);
		customizeVendorProperties(vendorProperties);
	    Builder builder = getEntityManagerFactoryBuilder(dataSource).dataSource(dataSource).packages(mergePackagesToScan())
				.properties(vendorProperties).jta(isJta());
		LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = builder.build();
		entityManagerFactoryBean.setBeanClassLoader(classLoader);
		entityManagerFactoryBean.setBeanFactory(beanFactory);
		entityManagerFactoryBean.setBeanName(beanName);
		entityManagerFactoryBean.setLoadTimeWeaver(loadTimeWeaver);
		entityManagerFactoryBean.setResourceLoader(resourceLoader);
		entityManagerFactoryBean.afterPropertiesSet();
		return entityManagerFactoryBean.getObject();
	}
	return null;
}
 
Example 9
Source Project: multiapps   Source File: TestDataSourceProvider.java    License: Apache License 2.0 6 votes vote down vote up
public static DataSource getDataSource(String liquibaseChangelogLocation) throws Exception {
    // create a hsql in memory connection
    Connection connection = createH2InMemory();

    // Create the schema for unit testing
    Database liquibaseDb = DatabaseFactory.getInstance()
                                          .findCorrectDatabaseImplementation(new JdbcConnection(connection));
    Liquibase lq = new Liquibase(liquibaseChangelogLocation, new ClassLoaderResourceAccessor(), liquibaseDb);
    try {
        lq.update("");
    } catch (MigrationFailedException e) {
        // catch the exception because in PopulateConfigurationRegistrySpaceIdColumnChange liquibase change there is rest call
        if (e.getCause()
             .getClass() != UnexpectedLiquibaseException.class) {
            throw e;
        }
    }

    // Initialize the fileService to use our in-memory connection through a pool emulation (so
    // that close releases rather than close)
    return new SingleConnectionDataSource(connection, true);
}
 
Example 10
Source Project: spring4-understanding   Source File: JdbcTemplateTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testLeaveConnectionOpenOnRequest() throws Exception {
	String sql = "SELECT ID, FORENAME FROM CUSTMR WHERE ID < 3";

	given(this.resultSet.next()).willReturn(false);
	given(this.connection.isClosed()).willReturn(false);
	given(this.connection.createStatement()).willReturn(this.preparedStatement);
	// if close is called entire test will fail
	willThrow(new RuntimeException()).given(this.connection).close();

	SingleConnectionDataSource scf = new SingleConnectionDataSource(this.dataSource.getConnection(), false);
	this.template = new JdbcTemplate(scf, false);
	RowCountCallbackHandler rcch = new RowCountCallbackHandler();
	this.template.query(sql, rcch);

	verify(this.resultSet).close();
	verify(this.preparedStatement).close();
}
 
Example 11
@Override
public void migrate(Context context) throws Exception {
	logger.info("About to check if mssql hibernate_sequence needs fix from table to a sequence");
	try {
		JdbcTemplate jdbcTemplate = new JdbcTemplate(new SingleConnectionDataSource(context.getConnection(), true));
		// in case we have old wrongly created table, this command should succeed
		jdbcTemplate.execute("select 1 from hibernate_sequence");
		fixHibernateSequence = true;
		logger.info("Looks like we have hibernate_sequence table, initiate fix");
	}
	catch (Exception e) {
		logger.debug("Unable to query hibernate_sequence table, looks like we have a proper sequence", e);
	}
	// will result call to get commands from this class and then we choose which ones to run
	super.migrate(context);
}
 
Example 12
Source Project: openid4java   Source File: JdbcNonceVerifierTest.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public NonceVerifier createVerifier(int maxAge) {
	DataSource dataSource = new SingleConnectionDataSource(
			"org.hsqldb.jdbcDriver",
			"jdbc:hsqldb:mem:saasstore_security_client", "sa", "", true);
	SimpleJdbcTemplate jdbcTemplate = new SimpleJdbcTemplate(dataSource);
	jdbcTemplate.getJdbcOperations().execute(
			"DROP TABLE IF EXISTS openid_nonce;");
	jdbcTemplate
			.getJdbcOperations()
			.execute(
					"CREATE TABLE openid_nonce (  "
							+ "opurl varchar(255) NOT NULL,  nonce varchar(25) NOT NULL,  "
							+ "date datetime DEFAULT NULL,  PRIMARY KEY (opurl,nonce))");

	JdbcNonceVerifier jdbcNonceVerifier = new JdbcNonceVerifier(maxAge,
			"openid_nonce");
	jdbcNonceVerifier.setDataSource(dataSource);
	return jdbcNonceVerifier;
}
 
Example 13
Source Project: booties   Source File: PostgreSqlRule.java    License: Apache License 2.0 6 votes vote down vote up
private void applyScripts(String url) throws SQLException, IOException {
    log.info("Apply Scripts ...");
    Connection connection = getConnection(url);
    DataSource ds = new SingleConnectionDataSource(connection, false);
    FileSystemScanner scanner = new FileSystemScanner();
    for (String location : builder.locations) {
        File directory = new File(location);
        if (directory.exists() && directory.isDirectory()) {
            Resource[] resources = scanner.scanForResources(location, "", ".sql");
            ResourceDatabasePopulator populator = new ResourceDatabasePopulator(resources);
            populator.setSeparator(builder.separator);
            populator.execute(ds);
        } else {
            // log not existing directory
        }
    }
    log.info("Scripts applied!");
}
 
Example 14
Source Project: SimpleFlatMapper   Source File: Sql2oIntegrationTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testSql2O() throws SQLException, ParseException {
    Connection connection = DbHelper.objectDb();
    try {
        SingleConnectionDataSource scds = new SingleConnectionDataSource(connection, true);
        Sql2o sql2o = new Sql2o(scds);

        Query query = sql2o.open().createQuery(DbHelper.TEST_DB_OBJECT_QUERY);
        query.setAutoDeriveColumnNames(true);
        query.setResultSetHandlerFactoryBuilder(new SfmResultSetHandlerFactoryBuilder());

        List<DbObject> dbObjects = query.executeAndFetch(DbObject.class);

        assertEquals(1, dbObjects.size());
        DbHelper.assertDbObjectMapping(dbObjects.get(0));

    } finally {
        connection.close();
    }
}
 
Example 15
Source Project: score   Source File: SimpleHiloIdentifierGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private void updateCurrentChunk() {
    if (logger.isDebugEnabled()) {
        logger.debug("Updating HILO chunk...");
    }

    long t = System.currentTimeMillis();
    try (Connection conn = dataSource.getConnection()) {
        conn.setAutoCommit(false);
        JdbcTemplate jdbcTemplate = new JdbcTemplate(new SingleConnectionDataSource(conn, true));

        jdbcTemplate.update(SQL_LOCK);
        currentChunk = jdbcTemplate.queryForObject(SQL_SELECT, Integer.class);
        if (logger.isDebugEnabled())
            logger.debug("Current chunk: " + currentChunk);
        jdbcTemplate.execute(SQL_UPDATE);
        jdbcTemplate.execute("commit");

        if (logger.isDebugEnabled()) {
            logger.debug("Updating HILO chunk done in " + (System.currentTimeMillis() - t) + " ms");
        }
        currentId = 0;
    } catch (SQLException e) {
        logger.error("Unable to update current chunk", e);
        throw new IllegalStateException("Unable to update current chunk");
    }
}
 
Example 16
public void migrate(Context context) {
    JdbcTemplate jdbcTemplate = new JdbcTemplate(new SingleConnectionDataSource(context.getConnection(), true));
    SimpleJdbcInsert insertOp = new SimpleJdbcInsert(jdbcTemplate).withTableName("m_prj_ticket_relation");

    List<Map<String, Object>> rows = jdbcTemplate.queryForList("SELECT * FROM m_tracker_related_bug");
    rows.forEach(row -> {
        Map<String, Object> parameters = new HashMap<>(6);
        parameters.put("ticketId", row.get("bugid"));
        parameters.put("ticketType", "Project-Bug");
        parameters.put("type", "Project-Bug");
        parameters.put("typeId", row.get("relatedid"));
        parameters.put("rel", row.get("relatetype"));
        parameters.put("comment", row.get("comment"));
        insertOp.execute(parameters);
    });
    jdbcTemplate.execute("DROP TABLE `m_tracker_related_bug`;");
}
 
Example 17
Source Project: effectivejava   Source File: JdbcTemplateTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testLeaveConnectionOpenOnRequest() throws Exception {
	String sql = "SELECT ID, FORENAME FROM CUSTMR WHERE ID < 3";

	given(this.resultSet.next()).willReturn(false);
	given(this.connection.isClosed()).willReturn(false);
	given(this.connection.createStatement()).willReturn(this.preparedStatement);
	// if close is called entire test will fail
	willThrow(new RuntimeException()).given(this.connection).close();

	SingleConnectionDataSource scf = new SingleConnectionDataSource(this.dataSource.getConnection(), false);
	this.template = new JdbcTemplate(scf, false);
	RowCountCallbackHandler rcch = new RowCountCallbackHandler();
	this.template.query(sql, rcch);

	verify(this.resultSet).close();
	verify(this.preparedStatement).close();
}
 
Example 18
Source Project: effectivejava   Source File: RowMapperTests.java    License: Apache License 2.0 6 votes vote down vote up
@Override
@Before
public void setUp() throws SQLException {
	connection = mock(Connection.class);
	statement = mock(Statement.class);
	preparedStatement = mock(PreparedStatement.class);
	resultSet = mock(ResultSet.class);
	given(connection.createStatement()).willReturn(statement);
	given(connection.prepareStatement(anyString())).willReturn(preparedStatement);
	given(statement.executeQuery(anyString())).willReturn(resultSet);
	given(preparedStatement.executeQuery()).willReturn(resultSet);
	given(resultSet.next()).willReturn(true, true, false);
	given(resultSet.getString(1)).willReturn("tb1", "tb2");
	given(resultSet.getInt(2)).willReturn(1, 2);
	template = new JdbcTemplate();
	template.setDataSource(new SingleConnectionDataSource(connection, false));
	template.setExceptionTranslator(new SQLStateSQLExceptionTranslator());
	template.afterPropertiesSet();
}
 
Example 19
Source Project: yaks   Source File: JdbcSteps.java    License: Apache License 2.0 5 votes vote down vote up
@Given("^(?:D|d)atabase connection$")
public void setConnection(DataTable properties) {
    Map<String, String> connectionProps = properties.asMap(String.class, String.class);

    String driver = connectionProps.getOrDefault("driver", "org.postgresql.Driver");
    String url = connectionProps.getOrDefault("url", "jdbc:postgresql://localhost:5432/testdb");
    String username = connectionProps.getOrDefault("username", "test");
    String password = connectionProps.getOrDefault("password", "test");
    boolean suppressClose = Boolean.parseBoolean(connectionProps.getOrDefault("suppressClose", Boolean.TRUE.toString()));

    SingleConnectionDataSource singleConnectionDataSource = new SingleConnectionDataSource(url, username, password, suppressClose);
    singleConnectionDataSource.setDriverClassName(driver);
    this.dataSource = singleConnectionDataSource;
}
 
Example 20
Source Project: spring-analysis-note   Source File: AbstractRowMapperTests.java    License: MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
public Mock(MockType type) throws Exception {
	connection = mock(Connection.class);
	statement = mock(Statement.class);
	resultSet = mock(ResultSet.class);
	resultSetMetaData = mock(ResultSetMetaData.class);

	given(connection.createStatement()).willReturn(statement);
	given(statement.executeQuery(anyString())).willReturn(resultSet);
	given(resultSet.getMetaData()).willReturn(resultSetMetaData);

	given(resultSet.next()).willReturn(true, false);
	given(resultSet.getString(1)).willReturn("Bubba");
	given(resultSet.getLong(2)).willReturn(22L);
	given(resultSet.getTimestamp(3)).willReturn(new Timestamp(1221222L));
	given(resultSet.getObject(anyInt(), any(Class.class))).willThrow(new SQLFeatureNotSupportedException());
	given(resultSet.getDate(3)).willReturn(new java.sql.Date(1221222L));
	given(resultSet.getBigDecimal(4)).willReturn(new BigDecimal("1234.56"));
	given(resultSet.wasNull()).willReturn(type == MockType.TWO);

	given(resultSetMetaData.getColumnCount()).willReturn(4);
	given(resultSetMetaData.getColumnLabel(1)).willReturn(
			type == MockType.THREE ? "Last Name" : "name");
	given(resultSetMetaData.getColumnLabel(2)).willReturn("age");
	given(resultSetMetaData.getColumnLabel(3)).willReturn("birth_date");
	given(resultSetMetaData.getColumnLabel(4)).willReturn("balance");

	jdbcTemplate = new JdbcTemplate();
	jdbcTemplate.setDataSource(new SingleConnectionDataSource(connection, false));
	jdbcTemplate.setExceptionTranslator(new SQLStateSQLExceptionTranslator());
	jdbcTemplate.afterPropertiesSet();
}
 
Example 21
Source Project: spring-analysis-note   Source File: RowMapperTests.java    License: MIT License 5 votes vote down vote up
@Before
public void setUp() throws SQLException {
	given(connection.createStatement()).willReturn(statement);
	given(connection.prepareStatement(anyString())).willReturn(preparedStatement);
	given(statement.executeQuery(anyString())).willReturn(resultSet);
	given(preparedStatement.executeQuery()).willReturn(resultSet);
	given(resultSet.next()).willReturn(true, true, false);
	given(resultSet.getString(1)).willReturn("tb1", "tb2");
	given(resultSet.getInt(2)).willReturn(1, 2);

	template.setDataSource(new SingleConnectionDataSource(connection, false));
	template.setExceptionTranslator(new SQLStateSQLExceptionTranslator());
	template.afterPropertiesSet();
}
 
Example 22
Source Project: java-technology-stack   Source File: AbstractRowMapperTests.java    License: MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
public Mock(MockType type) throws Exception {
	connection = mock(Connection.class);
	statement = mock(Statement.class);
	resultSet = mock(ResultSet.class);
	resultSetMetaData = mock(ResultSetMetaData.class);

	given(connection.createStatement()).willReturn(statement);
	given(statement.executeQuery(anyString())).willReturn(resultSet);
	given(resultSet.getMetaData()).willReturn(resultSetMetaData);

	given(resultSet.next()).willReturn(true, false);
	given(resultSet.getString(1)).willReturn("Bubba");
	given(resultSet.getLong(2)).willReturn(22L);
	given(resultSet.getTimestamp(3)).willReturn(new Timestamp(1221222L));
	given(resultSet.getObject(anyInt(), any(Class.class))).willThrow(new SQLFeatureNotSupportedException());
	given(resultSet.getDate(3)).willReturn(new java.sql.Date(1221222L));
	given(resultSet.getBigDecimal(4)).willReturn(new BigDecimal("1234.56"));
	given(resultSet.wasNull()).willReturn(type == MockType.TWO);

	given(resultSetMetaData.getColumnCount()).willReturn(4);
	given(resultSetMetaData.getColumnLabel(1)).willReturn(
			type == MockType.THREE ? "Last Name" : "name");
	given(resultSetMetaData.getColumnLabel(2)).willReturn("age");
	given(resultSetMetaData.getColumnLabel(3)).willReturn("birth_date");
	given(resultSetMetaData.getColumnLabel(4)).willReturn("balance");

	jdbcTemplate = new JdbcTemplate();
	jdbcTemplate.setDataSource(new SingleConnectionDataSource(connection, false));
	jdbcTemplate.setExceptionTranslator(new SQLStateSQLExceptionTranslator());
	jdbcTemplate.afterPropertiesSet();
}
 
Example 23
Source Project: java-technology-stack   Source File: RowMapperTests.java    License: MIT License 5 votes vote down vote up
@Before
public void setUp() throws SQLException {
	given(connection.createStatement()).willReturn(statement);
	given(connection.prepareStatement(anyString())).willReturn(preparedStatement);
	given(statement.executeQuery(anyString())).willReturn(resultSet);
	given(preparedStatement.executeQuery()).willReturn(resultSet);
	given(resultSet.next()).willReturn(true, true, false);
	given(resultSet.getString(1)).willReturn("tb1", "tb2");
	given(resultSet.getInt(2)).willReturn(1, 2);

	template.setDataSource(new SingleConnectionDataSource(connection, false));
	template.setExceptionTranslator(new SQLStateSQLExceptionTranslator());
	template.afterPropertiesSet();
}
 
Example 24
Source Project: multitenant   Source File: DataSourceServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public SingleConnectionDataSource createSingleConnectionDataSource(Organization organization) {
	DataSourceInfo dataSourceInfo = dataSourceInfoService.get(organization);
	if (!StringUtils.isEmpty(dataSourceInfo.getJndiName())) {
		return null;
	}
	SingleConnectionDataSource dataSource = new SingleConnectionDataSource(
			dataSourceInfo.getUrl(), dataSourceInfo.getUsername(), dataSourceInfo.getPassword(), true);
	dataSource.setAutoCommit(true);
	return dataSource;
}
 
Example 25
Source Project: code-examples   Source File: V2__InsertRandomUsers.java    License: MIT License 5 votes vote down vote up
public void migrate(Context context) {

    final JdbcTemplate jdbcTemplate = new JdbcTemplate(new SingleConnectionDataSource(context.getConnection(), true));

    // Create 10 random users
    for (int i = 1; i <= 10; i++) {
      jdbcTemplate.execute(String.format("insert into test_user(username, first_name, last_name) "
                                             + "values('%[email protected]', 'Elvis_%d', 'Presley_%d')", i, i, i));
    }
  }
 
Example 26
@Test
public void testPartitionedSql() throws Exception {
	factory.setColumnNames("foo, bar");
	factory.setTableName("baz");
	factory.setPartitionClause("WHERE foo BETWEEN 17 AND 42");
	DataSource dataSource = new SingleConnectionDataSource("jdbc:hsqldb:mem:test", "sa", "", false);
	factory.setDataSource(dataSource);
	factory.afterPropertiesSet();
	assertEquals("Partitioned SQL", "SELECT foo, bar FROM baz WHERE foo BETWEEN 17 AND 42",
			ReflectionTestUtils.getField(factory, "sql"));
}
 
Example 27
public Mock(MockType type)
		throws Exception {
	connection = mock(Connection.class);
	statement = mock(Statement.class);
	resultSet = mock(ResultSet.class);
	resultSetMetaData = mock(ResultSetMetaData.class);

	given(connection.createStatement()).willReturn(statement);
	given(statement.executeQuery(anyString())).willReturn(resultSet);
	given(resultSet.getMetaData()).willReturn(resultSetMetaData);

	given(resultSet.next()).willReturn(true, false);
	given(resultSet.getString(1)).willReturn("Bubba");
	given(resultSet.getLong(2)).willReturn(22L);
	given(resultSet.getTimestamp(3)).willReturn(new Timestamp(1221222L));
	given(resultSet.getBigDecimal(4)).willReturn(new BigDecimal("1234.56"));
	given(resultSet.wasNull()).willReturn(type == MockType.TWO ? true : false);

	given(resultSetMetaData.getColumnCount()).willReturn(4);
	given(resultSetMetaData.getColumnLabel(1)).willReturn(
			type == MockType.THREE ? "Last Name" : "name");
	given(resultSetMetaData.getColumnLabel(2)).willReturn("age");
	given(resultSetMetaData.getColumnLabel(3)).willReturn("birth_date");
	given(resultSetMetaData.getColumnLabel(4)).willReturn("balance");

	jdbcTemplate = new JdbcTemplate();
	jdbcTemplate.setDataSource(new SingleConnectionDataSource(connection, false));
	jdbcTemplate.setExceptionTranslator(new SQLStateSQLExceptionTranslator());
	jdbcTemplate.afterPropertiesSet();
}
 
Example 28
Source Project: spring4-understanding   Source File: RowMapperTests.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws SQLException {
	given(connection.createStatement()).willReturn(statement);
	given(connection.prepareStatement(anyString())).willReturn(preparedStatement);
	given(statement.executeQuery(anyString())).willReturn(resultSet);
	given(preparedStatement.executeQuery()).willReturn(resultSet);
	given(resultSet.next()).willReturn(true, true, false);
	given(resultSet.getString(1)).willReturn("tb1", "tb2");
	given(resultSet.getInt(2)).willReturn(1, 2);

	template.setDataSource(new SingleConnectionDataSource(connection, false));
	template.setExceptionTranslator(new SQLStateSQLExceptionTranslator());
	template.afterPropertiesSet();
}
 
Example 29
@Override
public List<SqlCommand> getCommands(Event event, Context context) {
	List<SqlCommand> commands = new ArrayList<>();
	List<SqlCommand> defaultCommands = super.getCommands(event, context);
	if (defaultCommands != null) {
		commands.addAll(defaultCommands);
	}

	boolean migrateToInitial = true;
	try {
		JdbcTemplate jdbcTemplate = new JdbcTemplate(new SingleConnectionDataSource(context.getConnection(), true));
		jdbcTemplate.execute("select 1 from APP_REGISTRATION");
		migrateToInitial = false;
	} catch (Exception e) {
	}

	if (migrateToInitial) {
		logger.info("Did not detect prior Data Flow schema, doing baseline.");
		commands.addAll(initialSetupMigration.getCommands());
	}
	else {
		logger.info("Detected old Data Flow schema, doing baseline.");
		commands.addAll(dropIndexes());
		commands.addAll(changeAppRegistrationTable());
		commands.addAll(changeUriRegistryTable());
		commands.addAll(changeStreamDefinitionsTable());
		commands.addAll(changeTaskDefinitionsTable());
		commands.addAll(changeAuditRecordsTable());
		commands.addAll(createTaskLockTable());
		commands.addAll(createTaskDeploymentTable());
		commands.addAll(createIndexes());
	}

	return commands;
}
 
Example 30
Source Project: zstack   Source File: ManagementNodeManagerImpl.java    License: Apache License 2.0 5 votes vote down vote up
HeartBeatDBSource() {
    try {
        connectionTimeoutExecutor = Executors.newFixedThreadPool(3);
        conn = dbf.getExtraDataSource().getConnection();
        conn.setNetworkTimeout(connectionTimeoutExecutor, (int) TimeUnit.SECONDS.toMillis(PortalGlobalProperty.HEART_BEAT_QUERY_TIMEOUT));
        source = new SingleConnectionDataSource(conn, true);
        jdbc = new JdbcTemplate(source);
    } catch (SQLException e) {
        throw new CloudRuntimeException(e);
    }
}