javax.sql.DataSource源码实例Demo

org.junit.jupiter.api.BeforeAll#javax.sql.DataSource源码实例Demo

下面列出了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");
    });
}
 
源代码2 项目: obevo   文件: TableSyncher.java
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());
}
 
源代码3 项目: jactiverecord   文件: DB.java
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());
    }
}
 
源代码5 项目: rice   文件: TestUtilities.java
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;
        }
    });
}
 
源代码6 项目: rice   文件: AnnotationTestParent.java
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();
                }
            }
        }
    });
}
 
源代码7 项目: gemfirexd-oss   文件: TestTaskBase.java
/**
 * 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;
}
 
源代码10 项目: spliceengine   文件: J2EEDataSourceTest.java
/**
 * 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();
}
 
源代码11 项目: fahrschein   文件: Main.java
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");
    });
}
 
源代码13 项目: gemfirexd-oss   文件: AuthenticationTest.java
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();
}
 
源代码18 项目: qmq   文件: DefaultDataSourceFactory.java
@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);
   }
}
 
源代码20 项目: javasimon   文件: SimonDataSource.java
DataSource datasource() throws SQLException {
	if (ds == null) {
		ds = createDataSource(DataSource.class);
		ds.setLogWriter(logWriter);
		wrapperSupport = new WrapperSupport<>(ds, DataSource.class);
	}
	return ds;
}
 
源代码21 项目: tddl   文件: BaseGroupTest.java
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;

}
 
源代码22 项目: spring-analysis-note   文件: SqlQueryTests.java
@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);
}
 
源代码24 项目: curiostack   文件: DatabaseModule.java
@Provides
@ElementsIntoSet
@CloseOnStop
static Set<Closeable> close(
    DataSource dataSource, @ForDatabase ListeningExecutorService executor) {
  return ImmutableSet.of((HikariDataSource) dataSource, executor::shutdownNow);
}
 
源代码25 项目: effectivejava   文件: SimpleJdbcCallTests.java
@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);
}
 
源代码26 项目: oneops   文件: DeployerConfiguration.java
@Bean
public SqlSessionFactoryBean getSessionFactoryBean(DataSource dataSource) {
  SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
  sqlSessionFactoryBean.setDataSource(dataSource);
  sqlSessionFactoryBean.setTypeAliasesPackage("com.oneops.cms.dj.domain");
  return sqlSessionFactoryBean;
}
 
源代码27 项目: myjdbc-rainbow   文件: ConnectionManager.java
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;
}
 
源代码28 项目: canal-1.1.3   文件: RoleSyncJoinOne2Test.java
/**
 * 带函数非子查询从表更新
 */
@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"));
}
 
源代码29 项目: nano-framework   文件: C3P0DataSourceFactory.java
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);
    }
}
 
源代码30 项目: spliceengine   文件: EncryptDatabaseTest.java
private static void assertSuccessfulBoot(String bootPassword)
        throws SQLException {

    DataSource ds = JDBCDataSource.getDataSource();
    JDBCDataSource.setBeanProperty(
        ds, "connectionAttributes", "bootPassword=" + bootPassword);
    ds.getConnection().close();
}
 
源代码评论
动弹
沙发等你来抢
 同类方法