use of org.eclipse.dataspaceconnector.spi.transaction.TransactionContext in project DataSpaceConnector by eclipse-dataspaceconnector.
the class AtomikosTransactionExtensionTest method verifyEndToEndTransactions.
@Test
void verifyEndToEndTransactions() {
var extensionContext = mock(ServiceExtensionContext.class);
when(extensionContext.getConnectorId()).thenReturn(randomUUID().toString());
when(extensionContext.getConfig()).thenReturn(ConfigFactory.fromMap(Map.of(TransactionManagerConfigurationKeys.LOGGING, "false")));
when(extensionContext.getConfig(isA(String.class))).thenAnswer(a -> createDataSourceConfig());
when(extensionContext.getConfig()).thenAnswer(a -> createAtomikosConfig());
when(extensionContext.getMonitor()).thenReturn(mock(Monitor.class));
var dsRegistry = new DataSourceRegistry[1];
doAnswer(invocation -> {
dsRegistry[0] = invocation.getArgument(1);
return null;
}).when(extensionContext).registerService(eq(DataSourceRegistry.class), isA(DataSourceRegistry.class));
var transactionContext = new TransactionContext[1];
doAnswer(invocation -> {
transactionContext[0] = invocation.getArgument(1);
return null;
}).when(extensionContext).registerService(eq(TransactionContext.class), isA(TransactionContext.class));
extension.initialize(extensionContext);
extension.start();
transactionContext[0].execute(() -> {
try (var conn = dsRegistry[0].resolve("default").getConnection()) {
Statement s1 = conn.createStatement();
s1.execute("DROP ALL OBJECTS");
s1.execute("CREATE TABLE Foo (id number)");
s1.execute("INSERT into Foo values (1)");
} catch (SQLException e) {
throw new EdcException(e);
}
});
// verify committed data available in separate transaction
int[] numberOfResults = new int[1];
transactionContext[0].execute(() -> {
try (var conn = dsRegistry[0].resolve("default").getConnection()) {
Statement s1 = conn.createStatement();
var results = s1.executeQuery("SELECT * FROM Foo where id = 1");
numberOfResults[0] = results.last() ? results.getRow() : 0;
} catch (SQLException e) {
throw new EdcException(e);
}
});
assertThat(numberOfResults[0]).isEqualTo(1);
// verify rollback on exception in a nested block
assertThatExceptionOfType(EdcException.class).isThrownBy(() -> transactionContext[0].execute(() -> {
try (var conn = dsRegistry[0].resolve("default").getConnection()) {
Statement s1 = conn.createStatement();
s1.execute("INSERT into Foo values (2)");
transactionContext[0].execute(() -> {
throw new RuntimeException();
});
} catch (SQLException e) {
throw new EdcException(e);
}
}));
transactionContext[0].execute(() -> {
try (var conn = dsRegistry[0].resolve("default").getConnection()) {
Statement s1 = conn.createStatement();
var results = s1.executeQuery("SELECT * FROM Foo where id <= 2");
numberOfResults[0] = results.last() ? results.getRow() : 0;
} catch (SQLException e) {
throw new EdcException(e);
}
});
// the second rollsback; only one row should be present
assertThat(numberOfResults[0]).isEqualTo(1);
extension.shutdown();
}
Aggregations