下面列出了org.junit.jupiter.api.BeforeAll#javax.sql.DataSource 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
void testShouldIncludeOnlyQueryTraces() {
contextRunner.withPropertyValues("decorator.datasource.sleuth.include: query").run(context -> {
DataSource dataSource = context.getBean(DataSource.class);
ArrayListSpanReporter spanReporter = context.getBean(ArrayListSpanReporter.class);
Connection connection = dataSource.getConnection();
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT 1 FROM dual");
resultSet.next();
resultSet.close();
statement.close();
connection.close();
assertThat(spanReporter.getSpans()).hasSize(1);
Span statementSpan = spanReporter.getSpans().get(0);
assertThat(statementSpan.name()).isEqualTo("jdbc:/test/query");
});
}
public void execute(DbFileMergerArgs args) {
Configuration config;
try {
config = new FileBasedConfigurationBuilder<>(PropertiesConfiguration.class)
.configure(new Parameters().properties()
.setFile(args.getDbMergeConfigFile())
.setListDelimiterHandler(new LegacyListDelimiterHandler(','))
).getConfiguration();
} catch (ConfigurationException e) {
throw new RuntimeException(e);
}
RichIterable<DbMergeInfo> dbMergeInfos = DbMergeInfo.parseFromProperties(config);
RichIterable<TableSyncSide> tableSyncSides = dbMergeInfos.collect(new Function<DbMergeInfo, TableSyncSide>() {
@Override
public TableSyncSide valueOf(DbMergeInfo dbMergeInfo) {
DataSource ds = ds(dbMergeInfo.getDriverClassName(), dbMergeInfo.getUrl(), dbMergeInfo.getUsername(),
dbMergeInfo.getPassword());
return new TableSyncSide(ds, PhysicalSchema.parseFromString(dbMergeInfo.getPhysicalSchema()));
}
});
this.syncSchemaTables(DbPlatformConfiguration.getInstance().valueOf(config.getString("dbType")), tableSyncSides, args.getOutputDir());
}
public static DB open(DataSource pool) {
try (Connection base = pool.getConnection()) {
for (Dialect dialect : dialects) {
if (dialect.accept(base)) {
base.close();
return new DB(pool, dialect);
}
}
DatabaseMetaData meta = base.getMetaData();
String version = String.format("%s %d.%d/%s", meta.getDatabaseProductName(),
meta.getDatabaseMajorVersion(),
meta.getDatabaseMinorVersion(),
meta.getDatabaseProductVersion());
throw new UnsupportedDatabaseException(version);
} catch (SQLException e) {
throw new DBOpenException(e);
}
}
@Test(description = "This test case tests handling SQLException when adding new profile feature",
dependsOnMethods = "testAddProfileFeatureThrowingFeatureManagerDAOException",
expectedExceptions = IllegalTransactionStateException.class)
public void testAddProfileThrowingIllegalTransactionStateException() throws Exception {
//Creating profile object
Profile profile = ProfileCreator.getProfile(FeatureCreator.getFeatureList(), DEVICE_TYPE_D);
ProfileFeature profileFeature = profile.getProfileFeaturesList().get(0);
Pair<Connection, Pair<DataSource, DataSource>> pair = mockConnection();
PowerMockito.doThrow(new SQLException()).when(pair.first()).setAutoCommit(anyBoolean());
try {
featureManager.addProfileFeature(profileFeature, profile.getProfileId());
} finally {
PolicyManagementDAOFactory.init(pair.second().first());
}
}
public static void verifyTestEnvironment(DataSource dataSource) {
if (dataSource == null) {
Assert.fail("Could not locate the data source.");
}
JdbcTemplate template = new JdbcTemplate(dataSource);
template.execute(new ConnectionCallback() {
public Object doInConnection(Connection connection) throws SQLException {
ResultSet resultSet = connection.getMetaData().getTables(null, null, TEST_TABLE_NAME, null);
if (!resultSet.next()) {
LOG.error("No table named '"+TEST_TABLE_NAME+"' was found in the configured database. " +
"You are attempting to run tests against a non-test database!!!");
LOG.error("The test environment will not start up properly!!!");
Assert.fail("No table named '"+TEST_TABLE_NAME+"' was found in the configured database. " +
"You are attempting to run tests against a non-test database!!!");
}
return null;
}
});
}
protected int countTableResults(String valueToVerify) {
final String valueToCheck = valueToVerify;
final DataSource dataSource = TestHarnessServiceLocator.getDataSource();
return (Integer) new JdbcTemplate(dataSource).execute(new ConnectionCallback() {
public Object doInConnection(final Connection connection) throws SQLException {
Statement statement = null;
try {
statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
final ResultSet resultSet = statement.executeQuery("Select * from " + TEST_TABLE_NAME + " where COL = '" + valueToCheck + "'");
assertNotNull("ResultSet should not be null",resultSet);
int count = 0;
while (resultSet.next()) {
count++;
}
return count;
} finally {
if (statement != null) {
statement.close();
}
}
}
});
}
/**
* Returns an instance of the {@link DatabaseToDdlTask}, already configured with
* a project and the tested database.
*
* @return The task object
*/
protected DatabaseToDdlTask getDatabaseToDdlTaskInstance()
{
DatabaseToDdlTask task = new DatabaseToDdlTask();
Properties props = getTestProperties();
String catalog = props.getProperty(DDLUTILS_CATALOG_PROPERTY);
String schema = props.getProperty(DDLUTILS_SCHEMA_PROPERTY);
DataSource dataSource = getDataSource();
if (!(dataSource instanceof BasicDataSource))
{
fail("Datasource needs to be of type " + BasicDataSource.class.getName());
}
task.setProject(new Project());
task.addConfiguredDatabase((BasicDataSource)getDataSource());
task.setCatalogPattern(catalog);
task.setSchemaPattern(schema);
task.setUseDelimitedSqlIdentifiers(isUseDelimitedIdentifiers());
return task;
}
static <T extends DataSource> List<ConnectionAcquiringStrategyFactory<?, T>> mergeFactories(
List<ConnectionAcquiringStrategyFactory<?, T>> factories, FlexyPoolProperties flexyPool) {
List<ConnectionAcquiringStrategyFactory<?, T>> newFactories = new ArrayList<>();
List<? extends Class<?>> factoryClasses;
if (factories != null) {
factoryClasses = factories.stream().map(Object::getClass).collect(Collectors.toList());
newFactories.addAll(factories);
}
else {
factoryClasses = Collections.emptyList();
}
if (!factoryClasses.contains(IncrementPoolOnTimeoutConnectionAcquiringStrategy.Factory.class)) {
IncrementPool incrementPool = flexyPool.getAcquiringStrategy().getIncrementPool();
if (incrementPool.getMaxOverflowPoolSize() > 0) {
newFactories.add(new IncrementPoolOnTimeoutConnectionAcquiringStrategy.Factory<>(
incrementPool.getMaxOverflowPoolSize(), incrementPool.getTimeoutMillis()));
}
}
if (!factoryClasses.contains(RetryConnectionAcquiringStrategy.Factory.class)) {
Retry retry = flexyPool.getAcquiringStrategy().getRetry();
if (retry.getAttempts() > 0) {
newFactories.add(new RetryConnectionAcquiringStrategy.Factory<>(retry.getAttempts()));
}
}
return newFactories;
}
public SpringProcessEngineConfiguration processEngineConfigurationBean(Resource[] processDefinitions,
DataSource dataSource,
PlatformTransactionManager transactionManager,
SpringAsyncExecutor springAsyncExecutor)
throws IOException {
SpringProcessEngineConfiguration engine = new SpringProcessEngineConfiguration();
if (processDefinitions != null && processDefinitions.length > 0) {
engine.setDeploymentResources(processDefinitions);
}
engine.setDataSource(dataSource);
engine.setTransactionManager(transactionManager);
if (null != springAsyncExecutor) {
engine.setAsyncExecutor(springAsyncExecutor);
}
return engine;
}
/**
* check whether commit without statement will flow by checking its transaction id
* on client. This test is run only for client where commits without an
* active transactions will not flow to the server.
* DERBY-4653
*
* @throws SQLException
**/
public void testConnectionFlowCommit()
throws SQLException {
ConnectionPoolDataSource ds = J2EEDataSource.getConnectionPoolDataSource();
PooledConnection pc = ds.getPooledConnection();
Connection conn = pc.getConnection();
testConnectionFlowCommitWork(conn);
conn.close();
//Test for XADataSource
XADataSource xs = J2EEDataSource.getXADataSource();
XAConnection xc = xs.getXAConnection();
conn = xc.getConnection();
testConnectionFlowCommitWork(conn);
conn.close();
//Test for DataSource
DataSource jds = JDBCDataSource.getDataSource();
conn = jds.getConnection();
testConnectionFlowCommitWork(conn);
conn.close();
}
private static void persistentListen(ObjectMapper objectMapper, Listener<SalesOrderPlaced> listener) throws IOException {
final HikariConfig hikariConfig = new HikariConfig();
hikariConfig.setJdbcUrl(JDBC_URL);
hikariConfig.setUsername(JDBC_USERNAME);
hikariConfig.setPassword(JDBC_PASSWORD);
final DataSource dataSource = new HikariDataSource(hikariConfig);
final JdbcCursorManager cursorManager = new JdbcCursorManager(dataSource, "fahrschein-demo");
final NakadiClient nakadiClient = NakadiClient.builder(NAKADI_URI)
.withAccessTokenProvider(new ZignAccessTokenProvider())
.withCursorManager(cursorManager)
.build();
final List<Partition> partitions = nakadiClient.getPartitions(SALES_ORDER_SERVICE_ORDER_PLACED);
nakadiClient.stream(SALES_ORDER_SERVICE_ORDER_PLACED)
.readFromBegin(partitions)
.withObjectMapper(objectMapper)
.listen(SalesOrderPlaced.class, listener);
}
@Test
void testShouldNotFailWhenResourceIsAlreadyClosed2() {
contextRunner.run(context -> {
DataSource dataSource = context.getBean(DataSource.class);
ArrayListSpanReporter spanReporter = context.getBean(ArrayListSpanReporter.class);
Connection connection = dataSource.getConnection();
try {
connection.close();
connection.prepareStatement("SELECT NOW()");
fail("should fail due to closed connection");
}
catch (SQLException expected) {
}
assertThat(spanReporter.getSpans()).hasSize(1);
Span connectionSpan = spanReporter.getSpans().get(0);
assertThat(connectionSpan.name()).isEqualTo("jdbc:/test/connection");
});
}
protected void assertShutdownWOUPFail(
String expectedSqlState, String dbName, String user, String password)
throws SQLException
{
DataSource ds = JDBCDataSource.getDataSource(dbName);
JDBCDataSource.setBeanProperty(ds, "shutdownDatabase", "shutdown");
JDBCDataSource.setBeanProperty(ds, "user", user);
JDBCDataSource.setBeanProperty(ds, "password", password);
try {
ds.getConnection();
fail("expected shutdown to fail");
} catch (SQLException e) {
assertSQLState(expectedSqlState, e);
}
}
public DataSource dataSource() {
HikariConfig config = new HikariConfig();
config.setDriverClassName(driverClassName());
config.setJdbcUrl(url);
config.setUsername(username);
config.setPassword(password);
config.setMinimumIdle(minIdle);
config.setMaximumPoolSize(maxPoolSize);
if (validation) {
config.setConnectionTestQuery(validationQuery());
}
config.setDataSourceProperties(props);
return new HikariDataSource(config);
}
protected DataSource getDataSource(DataSourceConfig config) {
if (!isMock()) {
PoolProperties properties = new PoolProperties();
properties.setUrl(config.getUrl());
properties.setDriverClassName(config.getDriverClassName());
properties.setUsername(config.getUser());
properties.setPassword(config.getPassword());
return new org.apache.tomcat.jdbc.pool.DataSource(properties);
} else {
return new MockDataSource(config.getUrl());
}
}
@Override
public Object postProcessAfterInitialization(final Object bean, final String beanName) throws BeansException {
if (bean instanceof DataSource) {
ProxyFactory factory = new ProxyFactory(bean);
factory.setProxyTargetClass(true);
factory.addAdvice(new ProxyDataSourceInterceptor((DataSource) bean));
return factory.getProxy();
}
return bean;
}
public AbstractPipelineMavenPluginDao(@Nonnull DataSource ds) {
ds.getClass(); // check non null
this.ds = ds;
registerJdbcDriver();
initializeDatabase();
testDatabase();
}
@Override
public DataSource createDataSource(DynamicConfig config) {
final HikariConfig cpConfig = new HikariConfig();
cpConfig.setDriverClassName(config.getString("jdbc.driverClassName", "com.mysql.jdbc.Driver"));
cpConfig.setJdbcUrl(config.getString("jdbc.url"));
cpConfig.setUsername(config.getString("jdbc.username"));
cpConfig.setPassword(config.getString("jdbc.password"));
cpConfig.setMaximumPoolSize(config.getInt("pool.size.max", 10));
return new HikariDataSource(cpConfig);
}
public static void resetOACC(DataSource dataSource, String dbSchema, char[] oaccRootPwd,
PasswordEncryptor passwordEncryptor)
throws SQLException {
try (Connection connection = dataSource.getConnection()) {
deleteAllOACCData(connection, dbSchema);
SQLAccessControlSystemInitializer.initializeOACC(connection, dbSchema, oaccRootPwd, passwordEncryptor, true);
}
}
DataSource datasource() throws SQLException {
if (ds == null) {
ds = createDataSource(DataSource.class);
ds.setLogWriter(logWriter);
wrapperSupport = new WrapperSupport<>(ds, DataSource.class);
}
return ds;
}
public static DataSource getMySQLDataSource(int num) {
if (num > 2) {
num = 2;
}
DruidDataSource ds = new DruidDataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUsername("tddl");
ds.setPassword("tddl");
ds.setUrl("jdbc:mysql://10.232.31.154/tddl_sample_" + num);
return ds;
}
@Test
public void testListCustomersIntInt() throws SQLException {
given(resultSet.next()).willReturn(true, true, false);
given(resultSet.getInt("id")).willReturn(1, 2);
given(resultSet.getString("forename")).willReturn("rod", "dave");
class CustomerQuery extends MappingSqlQuery<Customer> {
public CustomerQuery(DataSource ds) {
super(ds, SELECT_ID_WHERE);
declareParameter(new SqlParameter(Types.NUMERIC));
declareParameter(new SqlParameter(Types.NUMERIC));
compile();
}
@Override
protected Customer mapRow(ResultSet rs, int rownum) throws SQLException {
Customer cust = new Customer();
cust.setId(rs.getInt(COLUMN_NAMES[0]));
cust.setForename(rs.getString(COLUMN_NAMES[1]));
return cust;
}
}
CustomerQuery query = new CustomerQuery(dataSource);
List<Customer> list = query.execute(1, 1);
assertTrue("2 results in list", list.size() == 2);
assertThat(list.get(0).getForename(), is("rod"));
assertThat(list.get(1).getForename(), is("dave"));
verify(preparedStatement).setObject(1, 1, Types.NUMERIC);
verify(preparedStatement).setObject(2, 1, Types.NUMERIC);
verify(connection).prepareStatement(SELECT_ID_WHERE);
verify(resultSet).close();
verify(preparedStatement).close();
verify(connection).close();
}
protected Connection connection() throws Exception {
if (jndi != null) {
return DataSource.class.cast(new InitialContext().lookup(jndi)).getConnection();
}
try {
Class.forName(driver);
} catch (final ClassNotFoundException e) {
throw new BatchRuntimeException(e);
}
return DriverManager.getConnection(url, user, password);
}
@Provides
@ElementsIntoSet
@CloseOnStop
static Set<Closeable> close(
DataSource dataSource, @ForDatabase ListeningExecutorService executor) {
return ImmutableSet.of((HikariDataSource) dataSource, executor::shutdownNow);
}
@Before
public void setUp() throws Exception {
connection = mock(Connection.class);
databaseMetaData = mock(DatabaseMetaData.class);
dataSource = mock(DataSource.class);
callableStatement = mock(CallableStatement.class);
given(connection.getMetaData()).willReturn(databaseMetaData);
given(dataSource.getConnection()).willReturn(connection);
}
@Bean
public SqlSessionFactoryBean getSessionFactoryBean(DataSource dataSource) {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
sqlSessionFactoryBean.setTypeAliasesPackage("com.oneops.cms.dj.domain");
return sqlSessionFactoryBean;
}
public static Connection getConnection(DataSource dataSource) throws Exception {
SqlContext sqlContext = SqlContext.getContext();
Connection conn = sqlContext.getDataSourceMap().get(dataSource);
if (conn == null || conn.isClosed()) {
conn = dataSource.getConnection();
sqlContext.getDataSourceMap().put(dataSource, conn);
sqlContext.setCurrentDataSource(dataSource);
}
// 设置事务
conn.setAutoCommit(!sqlContext.getTransaction());
conn.setReadOnly(sqlContext.getReadOnly());
return conn;
}
/**
* 带函数非子查询从表更新
*/
@Test
public void test02() {
DataSource ds = DatasourceConfig.DATA_SOURCES.get("defaultDS");
Common.sqlExe(ds, "update role set role_name='admin3' where id=1");
Dml dml = new Dml();
dml.setDestination("example");
dml.setTs(new Date().getTime());
dml.setType("UPDATE");
dml.setDatabase("mytest");
dml.setTable("role");
List<Map<String, Object>> dataList = new ArrayList<>();
Map<String, Object> data = new LinkedHashMap<>();
dataList.add(data);
data.put("id", 1L);
data.put("role_name", "admin3");
dml.setData(dataList);
List<Map<String, Object>> oldList = new ArrayList<>();
Map<String, Object> old = new LinkedHashMap<>();
oldList.add(old);
old.put("role_name", "admin");
dml.setOld(oldList);
String database = dml.getDatabase();
String table = dml.getTable();
Map<String, ESSyncConfig> esSyncConfigs = esAdapter.getDbTableEsSyncConfig().get(database + "-" + table);
esAdapter.getEsSyncService().sync(esSyncConfigs.values(), dml);
GetResponse response = esAdapter.getTransportClient().prepareGet("mytest_user", "_doc", "1").get();
Assert.assertEquals("admin3_", response.getSource().get("_role_name"));
}
public C3P0DataSourceFactory() {
try {
Class<?> comboPooledDataSource = Class.forName("com.mchange.v2.c3p0.ComboPooledDataSource");
this.dataSource = (DataSource) comboPooledDataSource.newInstance();
} catch (final ClassNotFoundException | InstantiationException | IllegalAccessException e) {
throw new DataSourceException(e.getMessage(), e);
}
}
private static void assertSuccessfulBoot(String bootPassword)
throws SQLException {
DataSource ds = JDBCDataSource.getDataSource();
JDBCDataSource.setBeanProperty(
ds, "connectionAttributes", "bootPassword=" + bootPassword);
ds.getConnection().close();
}