Add compatible DataGrid, filter editors, themes and JDBC example

This commit is contained in:
2026-11-16 17:29:19 +01:00
parent a35664dabe
commit 889846ca19
102 changed files with 10970 additions and 14 deletions
@@ -0,0 +1,101 @@
package de.neitzel.grid;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import java.util.*;
import java.util.concurrent.*;
class FilterCandidatesTest {
@Test
void currentPageCapturesAtOpenAndSeparatesLabelsFromValues() throws Exception {
var values =
new ArrayList<>(
List.of(
new FilterCandidates.Candidate(new FilterValue.Text("a"), "Same"),
new FilterCandidates.Candidate(new FilterValue.Text("b"), "Same"),
new FilterCandidates.Candidate(null, "Missing")));
var provider = FilterCandidates.currentPage(() -> values);
var context =
new FilterCandidates.Context("x", FilterCandidates.Scope.CURRENT_PAGE, List.of());
try (var session = provider.open(context)) {
values.clear();
var first =
session.load(new FilterCandidates.Request(context, "same", 0, 1))
.toCompletableFuture()
.get();
assertTrue(first.hasMore());
assertEquals(new FilterValue.Text("a"), first.candidates().getFirst().value());
var next =
session.load(new FilterCandidates.Request(context, "same", 1, 1))
.toCompletableFuture()
.get();
assertFalse(next.hasMore());
assertEquals(new FilterValue.Text("b"), next.candidates().getFirst().value());
}
assertThrows(
UnsupportedOperationException.class,
() ->
provider.open(
new FilterCandidates.Context(
"x", FilterCandidates.Scope.SOURCE_WIDE, List.of())));
assertThrows(
IllegalArgumentException.class,
() ->
new FilterCandidates.Context(
"x",
FilterCandidates.Scope.SOURCE_WIDE,
List.of(new MissingFilter("x", true))));
}
@Test
void sourceWideRespectsOtherFiltersAndClosingCancelsPendingWork() throws Exception {
record Item(long id, String value, long group) {}
var jobs = new ArrayDeque<Runnable>();
var data =
new ArrayList<>(
List.of(new Item(1, "a", 1), new Item(2, "b", 2), new Item(3, "a", 1)));
var source =
new MemoryGridSource<Long, Item>(
() -> data,
Item::id,
Long::compare,
List.of(
new MemoryColumn<>(
"x",
MemoryColumn.Kind.TEXT,
i -> new FilterValue.Text(i.value())),
new MemoryColumn<>(
"group",
MemoryColumn.Kind.INTEGER,
i -> new FilterValue.IntegerValue(i.group()))),
jobs::add,
50);
var context =
new FilterCandidates.Context(
"x",
FilterCandidates.Scope.SOURCE_WIDE,
List.of(
new ValueFilter(
"group", Set.of(new FilterValue.IntegerValue(1)), false)));
var session = source.candidateProvider(v -> ((FilterValue.Text) v).value()).open(context);
data.clear();
var first =
session.load(new FilterCandidates.Request(context, "", 0, 10))
.toCompletableFuture();
jobs.remove().run();
assertEquals(
List.of(new FilterCandidates.Candidate(new FilterValue.Text("a"), "a")),
first.get().candidates());
var pending =
session.load(new FilterCandidates.Request(context, "", 0, 10))
.toCompletableFuture();
session.close();
jobs.remove().run();
assertTrue(pending.isCancelled());
assertThrows(
IllegalStateException.class,
() -> session.load(new FilterCandidates.Request(context, "", 0, 10)));
}
}
@@ -0,0 +1,114 @@
package de.neitzel.grid;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import java.math.BigDecimal;
import java.util.*;
class GridContractsTest {
@Test
void textIsLiteralAndMissingIsNotEmpty() {
assertTrue(
new TextFilter("name", TextFilter.Operator.CONTAINS, "%_", false).matches("a%_B"));
assertFalse(new TextFilter("name", TextFilter.Operator.EQUALS, "", false).matches(null));
assertTrue(new TextFilter("name", TextFilter.Operator.EQUALS, "", false).matches(""));
assertThrows(
IllegalArgumentException.class,
() -> new TextFilter("name", TextFilter.Operator.CONTAINS, "", false));
assertFalse(new TextFilter("name", TextFilter.Operator.EQUALS, "ss", false).matches("ß"));
}
@Test
void decimalsAreExactAndChecklistsKeepExactText() {
assertTrue(
new NumericFilter(
"price",
NumericFilter.Operator.EQUALS,
new BigDecimal("9007199254740993.00"),
null)
.matches(new BigDecimal("9007199254740993")));
assertFalse(
new NumericFilter(
"price",
NumericFilter.Operator.EQUALS,
new BigDecimal("9007199254740993"),
null)
.matches(new BigDecimal("9007199254740992")));
var values =
new ValueFilter(
"price", Set.of(new FilterValue.Decimal(new BigDecimal("1.0"))), false);
assertTrue(values.matches(new FilterValue.Decimal(new BigDecimal("1.00"))));
assertFalse(
new ValueFilter("name", Set.of(new FilterValue.Text("Alpha")), false)
.matches(new FilterValue.Text("alpha")));
assertFalse(new ValueFilter("name", Set.of(), false).matches(null));
assertTrue(new MissingFilter("name", false).matches(""));
}
@Test
void queryAndSetupAreDefensivelyCopiedAndRejectAmbiguity() {
var filters = new ArrayList<FilterCondition>();
filters.add(new MissingFilter("name", true));
var q = new GridQuery(filters, List.of(), new PageRequest.All());
filters.clear();
assertEquals(1, q.filters().size());
assertThrows(UnsupportedOperationException.class, () -> q.filters().clear());
assertThrows(
IllegalArgumentException.class,
() ->
new GridQuery(
List.of(
new MissingFilter("a", true),
new MissingFilter("a", false)),
List.of(),
new PageRequest.All()));
assertThrows(
IllegalArgumentException.class,
() ->
new GridSetup(
1,
"products",
1,
List.of(new GridSetup.ColumnState("a", new ColumnWidth.Default())),
List.of(),
List.of(),
new PageRequest.Paged(1, 50)));
assertThrows(IllegalArgumentException.class, () -> new ColumnWidth.Explicit(Double.NaN));
}
@Test
void resultsValidateCountsButAllowDisappearedPages() {
var row = new GridRow<>(1, "one");
assertThrows(
IllegalArgumentException.class,
() ->
new PageResult<>(
new PageRequest.Paged(0, 2),
List.of(row, row),
OptionalLong.of(2),
false));
assertThrows(
IllegalArgumentException.class,
() ->
new PageResult<>(
new PageRequest.Paged(0, 2),
List.of(row),
OptionalLong.of(3),
true));
assertDoesNotThrow(
() ->
new PageResult<>(
new PageRequest.Paged(4, 2), List.of(), OptionalLong.of(2), false));
assertThrows(
IllegalArgumentException.class,
() ->
new PageResult<>(
new PageRequest.All(), List.of(row), OptionalLong.of(2), false));
assertThrows(ArithmeticException.class, () -> new PageRequest.Paged(Long.MAX_VALUE, 250));
assertThrows(
IllegalArgumentException.class,
() -> new SourceCapabilities(true, false, 100).validate(new PageRequest.All()));
}
}
@@ -0,0 +1,301 @@
package de.neitzel.grid;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
class GridCoordinatorTest {
static class Source implements GridSource<Integer, String> {
List<CompletableFuture<PageResult<Integer, String>>> futures = new ArrayList<>();
List<GridQuery> queries = new ArrayList<>();
List<QueryOptions> options = new ArrayList<>();
int cancellations;
public SourceCapabilities capabilities() {
return new SourceCapabilities(true, true, 250);
}
public QueryExecution<Integer, String> query(GridQuery q) {
return query(q, QueryOptions.defaults());
}
public QueryExecution<Integer, String> query(GridQuery q, QueryOptions o) {
queries.add(q);
options.add(o);
var f = new CompletableFuture<PageResult<Integer, String>>();
futures.add(f);
return new QueryExecution<>() {
public CompletionStage<PageResult<Integer, String>> result() {
return f;
}
public void cancel() {
cancellations++;
}
};
}
}
static GridQuery q(long page) {
return new GridQuery(List.of(), List.of(), new PageRequest.Paged(page, 1));
}
static PageResult<Integer, String> page(long index, int key) {
return new PageResult<>(
new PageRequest.Paged(index, 1),
List.of(new GridRow<>(key, "row" + key)),
OptionalLong.of(10),
index < 9);
}
static class Harness {
Source source = new Source();
ArrayDeque<Runnable> callbacks = new ArrayDeque<>();
List<PageResult<Integer, String>> published = new ArrayList<>();
GridCoordinator<Integer, String> c =
new GridCoordinator<>(source, callbacks::add, s -> {}, published::add);
void drain() {
while (!callbacks.isEmpty()) callbacks.remove().run();
}
void request(GridQuery q) {
c.request(q);
drain();
}
}
@Test
void staleSuccessFailureAndGuardApprovalCannotPublish() {
var h = new Harness();
h.request(q(0));
h.request(q(1));
assertEquals(1, h.source.cancellations);
h.source.futures.get(1).complete(page(1, 2));
h.drain();
h.source.futures.get(0).completeExceptionally(new IllegalStateException("old"));
h.drain();
assertEquals(1, h.published.size());
assertEquals(GridCoordinator.Phase.READY, h.c.state().phase());
CompletableFuture<Boolean> guard = new CompletableFuture<>();
h.c.setGuard(q -> guard);
h.c.request(q(2));
h.c.setGuard(q -> CompletableFuture.completedFuture(true));
h.request(q(3));
guard.complete(true);
h.drain();
assertEquals(3, h.source.queries.size());
assertEquals(q(3), h.source.queries.getLast());
h.c.close();
h.source.futures.getLast().complete(page(3, 4));
h.drain();
assertEquals(1, h.published.size());
}
@Test
void errorsRetainPageAndRetryLatestQuery() {
var h = new Harness();
h.request(q(0));
h.source.futures.getFirst().complete(page(0, 1));
h.drain();
h.request(q(1));
h.source.futures.getLast().completeExceptionally(new IllegalStateException("unavailable"));
h.drain();
assertEquals(GridCoordinator.Phase.ERROR, h.c.state().phase());
assertEquals(q(0), h.c.state().displayed());
h.c.retry();
h.drain();
assertEquals(q(1), h.source.queries.getLast());
h.source.futures.getLast().complete(page(1, 2));
h.drain();
assertEquals(q(1), h.c.state().displayed());
}
@Test
void disappearingPagesHaveOnlyOneCorrection() {
var h = new Harness();
h.request(q(9));
h.source
.futures
.getFirst()
.complete(new PageResult<>(q(9).page(), List.of(), OptionalLong.of(2), false));
h.drain();
assertEquals(q(1), h.source.queries.getLast());
h.source
.futures
.getLast()
.complete(new PageResult<>(q(1).page(), List.of(), OptionalLong.of(1), false));
h.drain();
assertEquals(2, h.source.queries.size());
assertEquals(GridCoordinator.Phase.ERROR, h.c.state().phase());
}
@Test
void allApprovalIsAttemptScopedAndCancellationRestoresPage() {
var h = new Harness();
h.request(q(0));
h.source.futures.getFirst().complete(page(0, 1));
h.drain();
var all = new GridQuery(List.of(), List.of(), new PageRequest.All());
CompletableFuture<Boolean> consent = new CompletableFuture<>();
h.c.setConfirmation((q, count) -> consent);
h.request(all);
h.source.futures.getLast().completeExceptionally(new AllRowsConfirmationRequired(1001));
h.drain();
assertEquals(GridCoordinator.Phase.CONFIRMATION, h.c.state().phase());
consent.complete(false);
h.drain();
assertEquals(q(0), h.c.state().requested());
assertEquals(1, h.published.size());
h.c.setConfirmation((q, count) -> CompletableFuture.completedFuture(true));
h.request(all);
h.source.futures.getLast().completeExceptionally(new AllRowsConfirmationRequired(1001));
h.drain();
assertTrue(h.source.options.getLast().allApproved());
h.request(q(2));
h.source
.futures
.get(h.source.futures.size() - 2)
.complete(
new PageResult<>(
new PageRequest.All(), List.of(), OptionalLong.of(0), false));
h.drain();
assertEquals(1, h.published.size());
}
@Test
void sourceReplacementIsNotCommittedWhenAllWarningIsCancelled() {
var h = new Harness();
h.request(q(0));
h.source.futures.getFirst().complete(page(0, 1));
h.drain();
var replacement = new Source();
h.c.setConfirmation((q, n) -> CompletableFuture.completedFuture(false));
h.c.request(replacement, new GridQuery(List.of(), List.of(), new PageRequest.All()));
h.drain();
replacement.futures.getFirst().completeExceptionally(new AllRowsConfirmationRequired(1001));
h.drain();
assertEquals(0, h.c.state().sourceVersion());
h.c.refresh();
h.drain();
assertEquals(2, h.source.queries.size());
}
@Test
void unknownTotalsRecoverToFirstPageAndInvalidResponsesAreErrors() {
var source =
new Source() {
public SourceCapabilities capabilities() {
return new SourceCapabilities(false, false, 250);
}
};
var jobs = new ArrayDeque<Runnable>();
var coordinator =
new GridCoordinator<Integer, String>(source, jobs::add, state -> {}, result -> {});
coordinator.request(q(4));
while (!jobs.isEmpty()) jobs.remove().run();
source.futures
.getFirst()
.complete(new PageResult<>(q(4).page(), List.of(), OptionalLong.empty(), false));
while (!jobs.isEmpty()) jobs.remove().run();
assertEquals(q(0), source.queries.getLast());
source.futures
.getLast()
.complete(
new PageResult<>(
q(0).page(),
List.of(new GridRow<>(1, "a")),
OptionalLong.empty(),
true));
while (!jobs.isEmpty()) jobs.remove().run();
assertEquals(GridCoordinator.Phase.READY, coordinator.state().phase());
coordinator.request(q(1));
while (!jobs.isEmpty()) jobs.remove().run();
source.futures.getLast().complete(page(0, 2));
while (!jobs.isEmpty()) jobs.remove().run();
assertEquals(GridCoordinator.Phase.ERROR, coordinator.state().phase());
assertEquals(q(0), coordinator.state().displayed());
coordinator.close();
assertNull(coordinator.state().result());
}
@Test
void lateConfirmationAndObserverTriggeredRequestsAreSerialized() {
var source = new Source();
var jobs = new ArrayDeque<Runnable>();
var holder = new AtomicReference<GridCoordinator<Integer, String>>();
var jumped = new AtomicBoolean();
var coordinator =
new GridCoordinator<Integer, String>(
source,
jobs::add,
state -> {
if (state.phase() == GridCoordinator.Phase.READY
&& jumped.compareAndSet(false, true))
holder.get().request(q(1));
},
result -> {});
holder.set(coordinator);
coordinator.request(q(0));
while (!jobs.isEmpty()) jobs.remove().run();
source.futures.getFirst().complete(page(0, 1));
while (!jobs.isEmpty()) jobs.remove().run();
assertEquals(q(1), coordinator.state().requested());
assertEquals(GridCoordinator.Phase.LOADING, coordinator.state().phase());
var consent = new CompletableFuture<Boolean>();
coordinator.setConfirmation((q, n) -> consent);
coordinator.request(new GridQuery(List.of(), List.of(), new PageRequest.All()));
while (!jobs.isEmpty()) jobs.remove().run();
source.futures.getLast().completeExceptionally(new AllRowsConfirmationRequired(1001));
while (!jobs.isEmpty()) jobs.remove().run();
coordinator.request(q(2));
while (!jobs.isEmpty()) jobs.remove().run();
int count = source.queries.size();
consent.complete(true);
while (!jobs.isEmpty()) jobs.remove().run();
assertEquals(count, source.queries.size());
assertEquals(q(2), coordinator.state().requested());
}
@Test
void closeDuringPublicationOrConfirmationDoesNotResurrectCoordinator() {
for (boolean closeInPublisher : List.of(true, false)) {
var source = new Source();
var jobs = new ArrayDeque<Runnable>();
var holder = new AtomicReference<GridCoordinator<Integer, String>>();
var coordinator =
new GridCoordinator<Integer, String>(
source,
jobs::add,
state -> {
if (!closeInPublisher
&& state.phase() == GridCoordinator.Phase.CONFIRMATION)
holder.get().close();
},
result -> holder.get().close());
holder.set(coordinator);
coordinator.setConfirmation(
(q, n) -> {
fail("Closed coordinator must not open confirmation");
return CompletableFuture.completedFuture(true);
});
coordinator.request(
closeInPublisher
? q(0)
: new GridQuery(List.of(), List.of(), new PageRequest.All()));
while (!jobs.isEmpty()) jobs.remove().run();
if (closeInPublisher) source.futures.getFirst().complete(page(0, 1));
else
source.futures
.getFirst()
.completeExceptionally(new AllRowsConfirmationRequired(1001));
while (!jobs.isEmpty()) jobs.remove().run();
assertEquals(GridCoordinator.Phase.CLOSED, coordinator.state().phase());
assertNull(coordinator.state().result());
}
}
}
@@ -0,0 +1,176 @@
package de.neitzel.grid;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import java.util.*;
class GridDefinitionTest {
static GridDefinition.Column column(String id, String type, int fixed) {
return new GridDefinition.Column(id, type, 100, 50, 200, fixed);
}
static GridSetup saved(String type) {
return new GridSetup(
1,
"products",
1,
List.of(new GridSetup.ColumnState("a", type, new ColumnWidth.Explicit(300))),
List.of(),
List.of(),
new PageRequest.Paged(0, 25));
}
@Test
void addsNewColumnsClampsWidthsAndPreservesDefaultIntent() {
var d =
new GridDefinition(
"products",
1,
List.of(column("a", "text", -1), column("b", "integer", -1)));
var prepared =
d.prepare(saved("text"), Map.of(), new SourceCapabilities(true, true, 50), f -> {});
assertEquals(
List.of(
new GridSetup.ColumnState("a", "text", new ColumnWidth.Explicit(200)),
new GridSetup.ColumnState("b", "integer", new ColumnWidth.Default())),
prepared.setup().columns());
assertEquals(1, prepared.adjustments().size());
}
@Test
void identityTypesUnknownColumnsAndFixedPositionsRequireExplicitMigration() {
var d =
new GridDefinition(
"products", 1, List.of(column("b", "text", 0), column("a", "text", -1)));
assertThrows(
IllegalArgumentException.class,
() ->
d.prepare(
saved("text"),
Map.of(),
new SourceCapabilities(true, true, 50),
f -> {}));
var changed = new GridDefinition("products", 1, List.of(column("a", "integer", -1)));
assertThrows(
IllegalArgumentException.class,
() ->
changed.prepare(
saved("text"),
Map.of(),
new SourceCapabilities(true, true, 50),
f -> {}));
var removed = new GridDefinition("products", 1, List.of(column("b", "text", -1)));
assertThrows(
IllegalArgumentException.class,
() ->
removed.prepare(
saved("text"),
Map.of(),
new SourceCapabilities(true, true, 50),
f -> {}));
assertThrows(
IllegalArgumentException.class,
() ->
new GridDefinition("other", 1, List.of(column("a", "text", -1)))
.prepare(
saved("text"),
Map.of(),
new SourceCapabilities(true, true, 50),
f -> {}));
}
@Test
void migrationsMustAdvanceAndRemainSubjectToFullValidation() {
var d = new GridDefinition("products", 2, List.of(column("a", "integer", -1)));
assertThrows(
IllegalArgumentException.class,
() ->
d.prepare(
saved("text"),
Map.of(),
new SourceCapabilities(true, true, 50),
f -> {}));
var result =
d.prepare(
saved("text"),
Map.of(
1,
s ->
new GridSetup(
1,
s.definitionId(),
2,
List.of(
new GridSetup.ColumnState(
"a",
"integer",
new ColumnWidth.Default())),
s.sort(),
s.filters(),
s.page())),
new SourceCapabilities(true, true, 50),
f -> {});
assertEquals(2, result.setup().definitionVersion());
assertThrows(
IllegalArgumentException.class,
() ->
d.prepare(
saved("text"),
Map.of(1, s -> s),
new SourceCapabilities(true, true, 50),
f -> {}));
assertThrows(
IllegalArgumentException.class,
() ->
d.prepare(
saved("text"),
Map.of(
1,
s ->
new GridSetup(
1,
s.definitionId(),
2,
s.columns(),
s.sort(),
s.filters(),
s.page())),
new SourceCapabilities(true, true, 50),
f -> {}));
}
@Test
void actualFilterAndPageCapabilitiesAreCheckedBeforeExecution() {
var d = new GridDefinition("products", 1, List.of(column("a", "text", -1)));
var s = saved("text");
var filtered =
new GridSetup(
1,
"products",
1,
s.columns(),
List.of(),
List.of(new MissingFilter("a", true)),
new PageRequest.All());
assertThrows(
IllegalArgumentException.class,
() ->
d.prepare(
filtered,
Map.of(),
new SourceCapabilities(true, false, 50),
f -> {}));
assertThrows(
UnsupportedOperationException.class,
() ->
d.prepare(
filtered,
Map.of(),
new SourceCapabilities(true, true, 50),
f -> {
throw new UnsupportedOperationException("Missing unsupported");
}));
}
}
@@ -0,0 +1,247 @@
package de.neitzel.grid;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.*;
class MemoryGridSourceTest {
record Product(long id, String name, Long quantity, BigDecimal price) {}
static MemoryGridSource<Long, Product> source(List<Product> rows, Executor executor) {
return new MemoryGridSource<>(
() -> rows,
Product::id,
Long::compare,
List.of(
new MemoryColumn<>(
"name",
MemoryColumn.Kind.TEXT,
p -> p.name() == null ? null : new FilterValue.Text(p.name())),
new MemoryColumn<>(
"quantity",
MemoryColumn.Kind.INTEGER,
p ->
p.quantity() == null
? null
: new FilterValue.IntegerValue(p.quantity())),
new MemoryColumn<>(
"price",
MemoryColumn.Kind.DECIMAL,
p ->
p.price() == null
? null
: new FilterValue.Decimal(p.price()))),
executor,
250);
}
static GridQuery query(List<FilterCondition> f, PageRequest p) {
return new GridQuery(f, List.of(new SortKey("name", SortKey.Direction.DESCENDING)), p);
}
@Test
void filteringSortingAndPagingUseWholeSnapshotAndStableKeys() {
var rows =
new ArrayList<>(
List.of(
new Product(3, "alpha", 3L, new BigDecimal("1.00")),
new Product(1, "Alpha", 1L, new BigDecimal("1.0")),
new Product(2, null, 2L, null),
new Product(4, "Zulu", 4L, new BigDecimal("2"))));
var source = source(rows, Runnable::run);
var page =
source.query(query(List.of(), new PageRequest.Paged(1, 2)))
.result()
.toCompletableFuture()
.join();
assertEquals(List.of(3L, 2L), page.rows().stream().map(GridRow::key).toList());
assertEquals(4, page.total().orElseThrow());
assertFalse(page.hasNext());
var filtered =
source.query(
query(
List.of(
new NumericFilter(
"price",
NumericFilter.Operator.EQUALS,
new BigDecimal("1"),
null)),
new PageRequest.Paged(0, 1)))
.result()
.toCompletableFuture()
.join();
assertEquals(1L, filtered.rows().getFirst().key());
assertEquals(2, filtered.total().orElseThrow());
assertTrue(filtered.hasNext());
assertEquals(List.of(3L, 1L, 2L, 4L), rows.stream().map(Product::id).toList());
}
@Test
void snapshotIsCapturedBeforeExecutorAndCancellationDoesNotInterrupt() {
var jobs = new ArrayDeque<Runnable>();
var rows = new ArrayList<>(List.of(new Product(1, "original", 1L, null)));
var source = source(rows, jobs::add);
var request = source.query(query(List.of(), new PageRequest.Paged(0, 25)));
rows.clear();
jobs.remove().run();
assertEquals(1, request.result().toCompletableFuture().join().rows().size());
var cancelled = source.query(query(List.of(), new PageRequest.Paged(0, 25)));
cancelled.cancel();
jobs.remove().run();
assertThrows(
CancellationException.class, () -> cancelled.result().toCompletableFuture().join());
}
@Test
void allChecksFilteredCountBeforeReturningRowsAndRechecksOnApproval() {
var rows =
new ArrayList<>(
List.of(new Product(1, "a", 1L, null), new Product(2, "b", 2L, null)));
var source = source(rows, Runnable::run);
var q = query(List.of(), new PageRequest.All());
var error =
assertThrows(
CompletionException.class,
() ->
source.query(q, new QueryOptions(1, false))
.result()
.toCompletableFuture()
.join());
assertInstanceOf(AllRowsConfirmationRequired.class, error.getCause());
rows.add(new Product(3, "c", 3L, null));
assertEquals(
3,
source.query(q, new QueryOptions(1, true))
.result()
.toCompletableFuture()
.join()
.rows()
.size());
assertEquals(
3,
source.query(q, new QueryOptions(3, false))
.result()
.toCompletableFuture()
.join()
.rows()
.size());
}
@Test
void typesUnsupportedConditionsAndDuplicateKeysFailVisibly() {
var source = source(List.of(new Product(1, "a", 1L, null)), Runnable::run);
assertThrows(
CompletionException.class,
() ->
source.query(
query(
List.of(
new NumericFilter(
"quantity",
NumericFilter.Operator.EQUALS,
new BigDecimal("1.5"),
null)),
new PageRequest.Paged(0, 25)))
.result()
.toCompletableFuture()
.join());
FilterCondition custom =
new FilterCondition() {
public String columnId() {
return "name";
}
public String typeId() {
return "unsupported";
}
};
assertInstanceOf(
UnsupportedOperationException.class,
assertThrows(
CompletionException.class,
() ->
source.query(
query(
List.of(custom),
new PageRequest.Paged(0, 25)))
.result()
.toCompletableFuture()
.join())
.getCause());
var dup =
source(
List.of(new Product(1, "a", 1L, null), new Product(1, "b", 2L, null)),
Runnable::run);
assertThrows(
CompletionException.class,
() ->
dup.query(query(List.of(), new PageRequest.Paged(0, 25)))
.result()
.toCompletableFuture()
.join());
}
private record LongName(String columnId) implements FilterCondition {
public String typeId() {
return "demo.long-name";
}
}
@Test
void registeredCustomEvaluationRunsOnApplicationExecutor() throws Exception {
Thread caller = Thread.currentThread();
var evaluatedOn = new java.util.concurrent.atomic.AtomicReference<Thread>();
ExecutorService executor = Executors.newSingleThreadExecutor();
try {
MemoryColumn<Product> name =
new MemoryColumn<>(
"name",
MemoryColumn.Kind.TEXT,
p -> {
assertSame(caller, Thread.currentThread());
return new FilterValue.Text(p.name());
},
Map.of(
"demo.long-name",
condition -> {
if (!(condition instanceof LongName))
throw new IllegalArgumentException(
"Unsupported custom condition");
return value -> {
evaluatedOn.set(Thread.currentThread());
return value instanceof FilterValue.Text text
&& text.value().length() > 3;
};
}));
var source =
new MemoryGridSource<Long, Product>(
() ->
List.of(
new Product(1, "Alpha", 1L, null),
new Product(2, "Bee", 2L, null)),
Product::id,
Long::compare,
List.of(name),
executor,
100);
var result =
source.query(
new GridQuery(
List.of(new LongName("name")),
List.of(),
new PageRequest.Paged(0, 25)))
.result()
.toCompletableFuture()
.get(5, TimeUnit.SECONDS);
assertEquals(List.of(1L), result.rows().stream().map(GridRow::key).toList());
assertNotSame(caller, evaluatedOn.get());
assertFalse(executor.isShutdown());
} finally {
executor.shutdownNow();
}
}
}