javax.sql.DataSource Java Examples

The following examples show how to use javax.sql.DataSource. 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 File: DB.java    From jactiverecord with MIT License 7 votes vote down vote up
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);
  }
}
 
Example #2
Source File: AbstractProcessEngineConfiguration.java    From activiti6-boot2 with Apache License 2.0 7 votes vote down vote up
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;
}
 
Example #3
Source File: TestTaskBase.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #4
Source File: TestUtilities.java    From rice with Educational Community License v2.0 6 votes vote down vote up
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;
        }
    });
}
 
Example #5
Source File: FeatureManagerImplTest.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
@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());
    }
}
 
Example #6
Source File: TableSyncher.java    From obevo with Apache License 2.0 6 votes vote down vote up
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());
}
 
Example #7
Source File: AnnotationTestParent.java    From rice with Educational Community License v2.0 6 votes vote down vote up
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();
                }
            }
        }
    });
}
 
Example #8
Source File: TracingJdbcEventListenerTests.java    From spring-boot-data-source-decorator with Apache License 2.0 6 votes vote down vote up
@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");
    });
}
 
Example #9
Source File: FlexyPoolConfiguration.java    From spring-boot-data-source-decorator with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #10
Source File: J2EEDataSourceTest.java    From spliceengine with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 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();
}
 
Example #11
Source File: Main.java    From fahrschein with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #12
Source File: SpringPropagationTest.java    From camelinaction2 with Apache License 2.0 5 votes vote down vote up
@Before
public void setupDatabase() throws Exception {
    DataSource ds = context.getRegistry().lookupByNameAndType("myDataSource", DataSource.class);
    jdbc = new JdbcTemplate(ds);

    jdbc.execute("create table bookorders "
            + "( order_id varchar(10), order_book varchar(50) )");
    jdbc.execute("create table bookaudit "
            + "( order_id varchar(10), order_book varchar(50), order_redelivery varchar(5) )");
}
 
Example #13
Source File: StoredProcedureTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
public AddInvoice(DataSource ds) {
	setDataSource(ds);
	setSql(SQL);
	declareParameter(new SqlParameter("amount", Types.INTEGER));
	declareParameter(new SqlParameter("custid", Types.INTEGER));
	declareParameter(new SqlOutParameter("newid", Types.INTEGER));
	compile();
}
 
Example #14
Source File: DatabaseModule.java    From curiostack with MIT License 5 votes vote down vote up
@Provides
@ElementsIntoSet
@CloseOnStop
static Set<Closeable> close(
    DataSource dataSource, @ForDatabase ListeningExecutorService executor) {
  return ImmutableSet.of((HikariDataSource) dataSource, executor::shutdownNow);
}
 
Example #15
Source File: JdbcConnectionConfiguration.java    From incubator-batchee with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #16
Source File: OrmDataSourceProperties.java    From sample-boot-micro with MIT License 5 votes vote down vote up
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);
}
 
Example #17
Source File: InventoryDataTaskSplitter.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
private Collection<SyncConfiguration> splitByPrimaryKeyRange(final SyncConfiguration syncConfiguration, final MetaDataManager metaDataManager, final DataSource dataSource) {
    int concurrency = syncConfiguration.getConcurrency();
    Collection<SyncConfiguration> result = new LinkedList<>();
    RdbmsConfiguration dumperConfiguration = syncConfiguration.getDumperConfiguration();
    String primaryKey = metaDataManager.getTableMetaData(dumperConfiguration.getTableName()).getPrimaryKeyColumns().get(0);
    try (Connection connection = dataSource.getConnection()) {
        PreparedStatement ps = connection.prepareStatement(String.format("SELECT MIN(%s),MAX(%s) FROM %s LIMIT 1", primaryKey, primaryKey, dumperConfiguration.getTableName()));
        ResultSet rs = ps.executeQuery();
        rs.next();
        long min = rs.getLong(1);
        long max = rs.getLong(2);
        long step = (max - min) / concurrency;
        for (int i = 0; i < concurrency && min <= max; i++) {
            RdbmsConfiguration splitDumperConfig = RdbmsConfiguration.clone(dumperConfiguration);
            if (i < concurrency - 1) {
                splitDumperConfig.setWhereCondition(String.format("WHERE %s BETWEEN %d AND %d", primaryKey, min, min + step));
                min = min + step + 1;
            } else {
                splitDumperConfig.setWhereCondition(String.format("WHERE %s BETWEEN %d AND %d", primaryKey, min, max));
            }
            splitDumperConfig.setSpiltNum(i);
            result.add(new SyncConfiguration(concurrency, syncConfiguration.getTableNameMap(),
                splitDumperConfig, RdbmsConfiguration.clone(syncConfiguration.getImporterConfiguration())));
        }
    } catch (SQLException e) {
        throw new PrepareFailedException(String.format("Split task for table %s by primary key %s error", dumperConfiguration.getTableName(), primaryKey), e);
    }
    return result;
}
 
Example #18
Source File: DbSchemaDrop.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    try {
        ContentEngine contentEngine = ContentEngines.getDefaultContentEngine();
        DataSource dataSource = contentEngine.getContentEngineConfiguration().getDataSource();

        DatabaseConnection connection = new JdbcConnection(dataSource.getConnection());
        Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(connection);
        database.setDatabaseChangeLogTableName(ContentEngineConfiguration.LIQUIBASE_CHANGELOG_PREFIX + database.getDatabaseChangeLogTableName());
        database.setDatabaseChangeLogLockTableName(ContentEngineConfiguration.LIQUIBASE_CHANGELOG_PREFIX + database.getDatabaseChangeLogLockTableName());

        if (StringUtils.isNotEmpty(contentEngine.getContentEngineConfiguration().getDatabaseSchema())) {
            database.setDefaultSchemaName(contentEngine.getContentEngineConfiguration().getDatabaseSchema());
            database.setLiquibaseSchemaName(contentEngine.getContentEngineConfiguration().getDatabaseSchema());
        }

        if (StringUtils.isNotEmpty(contentEngine.getContentEngineConfiguration().getDatabaseCatalog())) {
            database.setDefaultCatalogName(contentEngine.getContentEngineConfiguration().getDatabaseCatalog());
            database.setLiquibaseCatalogName(contentEngine.getContentEngineConfiguration().getDatabaseCatalog());
        }

        Liquibase liquibase = new Liquibase("org/flowable/content/db/liquibase/flowable-content-db-changelog.xml", new ClassLoaderResourceAccessor(), database);
        liquibase.dropAll();
        liquibase.getDatabase().close();

    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #19
Source File: AuthenticationTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example #20
Source File: SimpleJdbcCallTests.java    From effectivejava with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #21
Source File: DeployerConfiguration.java    From oneops with Apache License 2.0 5 votes vote down vote up
@Bean
public SqlSessionFactoryBean getSessionFactoryBean(DataSource dataSource) {
  SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
  sqlSessionFactoryBean.setDataSource(dataSource);
  sqlSessionFactoryBean.setTypeAliasesPackage("com.oneops.cms.dj.domain");
  return sqlSessionFactoryBean;
}
 
Example #22
Source File: ConnectionManager.java    From myjdbc-rainbow with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #23
Source File: RoleSyncJoinOne2Test.java    From canal-1.1.3 with Apache License 2.0 5 votes vote down vote up
/**
 * 带函数非子查询从表更新
 */
@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"));
}
 
Example #24
Source File: C3P0DataSourceFactory.java    From nano-framework with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example #25
Source File: EncryptDatabaseTest.java    From spliceengine with GNU Affero General Public License v3.0 5 votes vote down vote up
private static void assertSuccessfulBoot(String bootPassword)
        throws SQLException {

    DataSource ds = JDBCDataSource.getDataSource();
    JDBCDataSource.setBeanProperty(
        ds, "connectionAttributes", "bootPassword=" + bootPassword);
    ds.getConnection().close();
}
 
Example #26
Source File: FQueryPropertiesTest.java    From fastquery with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public Map<String, DataSource> getDataSources() {
	try {
		Class<FQueryProperties> clazz = FQueryProperties.class;
		Field f = clazz.getDeclaredField("dataSources");
		f.setAccessible(true);
		return (Map<String, DataSource>) f.get(null);
	} catch (Exception e) {
		e.printStackTrace();
	}
	return null;
}
 
Example #27
Source File: StandardProviderFactory.java    From nifi-registry with Apache License 2.0 5 votes vote down vote up
private void performMethodInjection(final Object instance, final Class providerClass) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    for (final Method method : providerClass.getMethods()) {
        if (method.isAnnotationPresent(ProviderContext.class)) {
            // make the method accessible
            final boolean isAccessible = method.isAccessible();
            method.setAccessible(true);

            try {
                final Class<?>[] argumentTypes = method.getParameterTypes();

                // look for setters (single argument)
                if (argumentTypes.length == 1) {
                    final Class<?> argumentType = argumentTypes[0];

                    // look for well known types, currently we only support injecting the DataSource
                    if (DataSource.class.isAssignableFrom(argumentType)) {
                        method.invoke(instance, dataSource);
                    }
                }
            } finally {
                method.setAccessible(isAccessible);
            }
        }
    }

    final Class parentClass = providerClass.getSuperclass();
    if (parentClass != null && Provider.class.isAssignableFrom(parentClass)) {
        performMethodInjection(instance, parentClass);
    }
}
 
Example #28
Source File: PrimaryTransactionManagerTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Bean
public DataSource dataSource1() {
	return new EmbeddedDatabaseBuilder()
			.generateUniqueName(true)
			.addScript("classpath:/org/springframework/test/context/jdbc/schema.sql")
			.build();
}
 
Example #29
Source File: DataSourceTracerTest.java    From opentracing-toolbox with MIT License 5 votes vote down vote up
@Test
void shouldTraceErrors() {
    final DataSource dataSource = unit.trace(original);

    assertThrows(SQLException.class, () -> {
        try (final Connection connection = dataSource.getConnection();
             final Statement statement = connection.createStatement()) {

            statement.execute("SELECT * FROM MATRIX(4)");
        }
    });

    final List<MockSpan> spans = tracer.finishedSpans();
    final MockSpan span = getOnlyElement(spans);

    assertThat(span.operationName(), is("execute"));
    assertThat(span.tags(), hasEntry("component", "JDBC"));
    assertThat(span.tags(), hasEntry("db.statement", "SELECT * FROM MATRIX(4)"));
    assertThat(span.tags(), hasEntry("db.type", "sql"));
    assertThat(span.tags(), hasEntry("span.kind", "client"));
    assertThat(span.tags(), hasEntry("flow_id", "REcCvlqMSReeo7adheiYFA"));
    assertThat(span.tags(), hasEntry("error", true));

    final List<MockSpan.LogEntry> entries = span.logEntries();
    assertThat(entries, hasSize(3));

    assertThat(entries.get(0).fields().get("message").toString(),
            containsString("Function \"MATRIX\" not found"));

    assertThat(entries.get(1).fields(), hasEntry("error.kind", "JdbcSQLSyntaxErrorException"));
    assertThat(entries.get(1).fields(), hasEntry(equalTo("error.object"), instanceOf(SQLException.class)));

    assertThat(entries.get(2).fields().get("stack").toString(), containsString("at org.h2.jdbc"));
}
 
Example #30
Source File: DaoImplSupportTest.java    From doma with Apache License 2.0 5 votes vote down vote up
@Test
public void testConstructorParameter5() throws Exception {
  Config config = mock(Config.class);
  DataSource dataSource = null;
  try {
    new DaoImplSupport(config, dataSource) {};
    fail();
  } catch (DomaNullPointerException expected) {
    assertEquals("dataSource", expected.getParameterName());
  }
}