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
+39
View File
@@ -0,0 +1,39 @@
# data-grid foundations
Toolkit-independent contracts for opt-in DataGrid development. This module does not depend on JavaFX or a JDBC driver. Parent-provided compile/test tooling is inherited, including Lombok annotation processing; immutable public models are Java records.
- `FilterCondition` is open to custom immutable implementations. Built-ins provide literal text, exact decimal, missing/present and explicit checklist conditions. A custom type must declare capabilities separately; editor registration is in `fx`, codecs are in optional `gson`, and adapter compilation remains separate.
- `GridQuery` combines one condition per column with AND and ordered sort keys. The source must append its stable row-key tie-breaker and validate column types, precision, matching semantics and capabilities.
- `PageRequest.Paged` uses zero-based indexes; `All` is explicit. `PageResult` defensively copies lists and checks row identities/count consistency, allowing empty out-of-range pages for coordinator recovery.
- `GridSource` separates asynchronous result completion from best-effort cancellation. The coordinator must independently discard obsolete completions. Models inside `GridRow` remain application-owned; they are not deep-copied.
- `GridSetup` separates format and definition versions, default versus explicit widths, and All versus paging. It rejects persisted nonzero page indexes. Selection, credentials and warning approvals are deliberately absent.
`TextFilter.matches` uses Locale.ROOT lowercasing with no normalization; `%` and `_` are literal. `NumericFilter` accepts BigDecimal operands and compares numerically, avoiding double conversion. The mapping layer remains responsible for the declared integer/decimal domain and scale limits. `FilterValue.Decimal` canonicalizes scale so checklist membership treats 1.0 and 1.00 equally. Text checklist membership is exact.
`MemoryGridSource` now executes mapped local queries, and `GridCoordinator` manages guarded requests, All confirmation, stale-result rejection, recovery and publication. Definition migrations are available here and JSON codecs are in optional `gson`; SQL execution is available in the optional [data-grid-jdbc module](../data-grid-jdbc/README.md). No executor is created or shut down by these classes.
Run from the repository root: `./mvnw -pl data-grid test`.
## Local execution
`MemoryGridSource<K,T>` accepts a collection supplier, stable-key function and comparator, explicit `MemoryColumn<T>` scalar mappings, an application-owned executor and a maximum page size. Built-in mappings cover text, long integers, arbitrary-precision decimals and booleans; null mapping values mean missing. Per-column custom filter compilers explicitly opt into additional local conditions; unsupported types fail rather than being ignored. Numeric mapping constraints beyond the generic long/BigDecimal domains remain the application's responsibility.
A query captures collection membership, keys and mapped scalar values on the calling thread. The supplier/readers must provide a consistent view (for example, call from the FX thread for FX-owned models, or synchronize the snapshot). Filtering, sorting and slicing run on the supplied executor. This preserves scalar/count consistency across later model changes without reading FX-owned properties on a worker. Model objects in results are application-owned references, not deep copies. Snapshot capture is O(n) caller-thread work; use a source with its own background snapshot mechanism for very large mutable datasets.
Filters combine with AND. Text sort uses Locale.ROOT lowercase lexical comparison; nulls remain last in either direction. The key comparator provides the final tie-breaker and must distinguish unique keys. Data is never reordered in the source collection.
`query(query, QueryOptions)` is the guarded All protocol. Without attempt-scoped approval, a count above the configured threshold fails with `AllRowsConfirmationRequired` before sorting/materializing the unpaged result. The caller asks the person, then submits the same query with approval in a **fresh** snapshot. A changed query or later attempt needs fresh approval. Sources not overriding the guarded overload reject All by default. Do not fetch All first and then ask.
## Owner-thread coordinator
Create `GridCoordinator` on its owner thread and supply an executor that **queues** callbacks to that same thread (`Platform::runLater` for FX). Public mutators also run there. Observers should not throw. A publisher may reject a result before committing it, allowing the coordinator to preserve its prior displayed state. Observer-triggered requests are queued rather than applied reentrantly.
State exposes requested versus displayed query, result, phase and error. The coordinator validates page identity and declared exact-count support, attempts cancellation but independently ignores superseded successes/failures, and permits only one corrective page request per user attempt. A guard may approve/block edits asynchronously. All confirmation is asynchronous and never retains an execution snapshot while awaiting input.
Rejected guards and declined All warnings restore the displayed query. A replacement source is committed only when it successfully publishes a result; cancellation keeps the previous source. Retry uses the latest requested query/source. Close invalidates pending callbacks and drops retained results without closing application sources/executors. Source selection and loaded row identity are presentation responsibilities.
Collection changes do not automatically trigger requests in this slice. Call refresh explicitly from application mutation handlers; automatic collection subscriptions can be added without changing the query contract.
## Saved setups
`GridDefinition.prepare` applies explicit definition migrations and validates column types/order, widths and source support. `GridSetup.ColumnState` carries stable type IDs. JSON is provided separately by `de.neitzel.lib:gson`; `data-grid` does not depend on JavaFX or Gson. See the [saved setup guide](../fx/docs/saved-setups.md).
+6
View File
@@ -0,0 +1,6 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent><groupId>de.neitzel.lib</groupId><artifactId>neitzellib</artifactId><version>1.0-SNAPSHOT</version></parent>
<artifactId>data-grid</artifactId>
<description>Toolkit-independent filter, query and grid setup contracts</description>
</project>
@@ -0,0 +1,19 @@
package de.neitzel.grid;
/**
* Source stopped before materializing an unpaged result. Any snapshot/transaction has been
* released.
*/
public final class AllRowsConfirmationRequired extends RuntimeException {
private final long count;
public AllRowsConfirmationRequired(long count) {
super("Loading all " + count + " matching rows requires confirmation");
if (count < 0) throw new IllegalArgumentException("Negative count");
this.count = count;
}
public long count() {
return count;
}
}
@@ -0,0 +1,11 @@
package de.neitzel.grid;
final class Checks {
private Checks() {}
static String id(String value) {
if (value == null || value.isBlank())
throw new IllegalArgumentException("Identifier must not be blank");
return value;
}
}
@@ -0,0 +1,13 @@
package de.neitzel.grid;
/** Saved sizing intention, independent of a theme's current default. */
public sealed interface ColumnWidth {
record Default() implements ColumnWidth {}
record Explicit(double value) implements ColumnWidth {
public Explicit {
if (!Double.isFinite(value) || value <= 0)
throw new IllegalArgumentException("Width must be finite and positive");
}
}
}
@@ -0,0 +1,161 @@
package de.neitzel.grid;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
/** Explicit, typed candidate lookup. A session owns its snapshot and pending lookups. */
public final class FilterCandidates {
private FilterCandidates() {}
public enum Scope {
CURRENT_PAGE,
SOURCE_WIDE
}
/** A null value explicitly represents missing; labels never determine equality. */
public record Candidate(FilterValue value, String label) {
public Candidate {
Objects.requireNonNull(label);
}
}
public record Context(String columnId, Scope scope, List<FilterCondition> otherFilters) {
public Context {
Checks.id(columnId);
Objects.requireNonNull(scope);
otherFilters = List.copyOf(otherFilters);
if (otherFilters.stream().anyMatch(f -> f.columnId().equals(columnId)))
throw new IllegalArgumentException("Candidate context must exclude its own filter");
}
}
public record Request(Context context, String search, int offset, int limit) {
public Request {
Objects.requireNonNull(context);
Objects.requireNonNull(search);
if (offset < 0 || limit < 1)
throw new IllegalArgumentException("Invalid candidate batch");
}
}
public record Batch(List<Candidate> candidates, boolean hasMore) {
public Batch {
candidates = List.copyOf(candidates);
}
}
public interface Provider {
Set<Scope> scopes();
Session open(Context context);
}
public interface Session extends AutoCloseable {
CompletionStage<Batch> load(Request request);
@Override
void close();
}
/** Captures current-page values at open, never claims source-wide completeness. */
public static Provider currentPage(Supplier<List<Candidate>> values) {
return snapshot(
Set.of(Scope.CURRENT_PAGE),
c -> {
var copy = List.copyOf(values.get());
return () -> copy;
},
Runnable::run);
}
/** Capture on open's thread; evaluate the captured snapshot on the supplied executor. */
public static Provider snapshot(
Set<Scope> scopes,
Function<Context, Supplier<List<Candidate>>> capture,
Executor executor) {
Set<Scope> supported = Set.copyOf(scopes);
Objects.requireNonNull(capture);
Objects.requireNonNull(executor);
return new Provider() {
public Set<Scope> scopes() {
return supported;
}
public Session open(Context context) {
if (!supported.contains(context.scope()))
throw new UnsupportedOperationException(
"Candidate scope unavailable: " + context.scope());
var captured =
new java.util.concurrent.atomic.AtomicReference<>(
Objects.requireNonNull(capture.apply(context)));
return new Session() {
private boolean closed;
private final Set<CompletableFuture<Batch>> pending = new HashSet<>();
public synchronized CompletionStage<Batch> load(Request request) {
if (closed) throw new IllegalStateException("Candidate session closed");
if (!context.equals(request.context()))
throw new IllegalArgumentException("Wrong candidate context");
var future = new CompletableFuture<Batch>();
pending.add(future);
try {
executor.execute(
() -> {
try {
if (future.isDone()) return;
Map<FilterValue, Candidate> distinct =
new LinkedHashMap<>();
var work = captured.get();
if (work == null) {
future.cancel(false);
return;
}
for (var candidate : work.get()) {
if (future.isDone()) return;
if (candidate
.label()
.toLowerCase(Locale.ROOT)
.contains(
request.search()
.toLowerCase(Locale.ROOT)))
distinct.putIfAbsent(
candidate.value(), candidate);
}
var found = new ArrayList<>(distinct.values());
int from = Math.min(request.offset(), found.size());
int to =
(int)
Math.min(
(long) from + request.limit(),
found.size());
future.complete(
new Batch(
found.subList(from, to),
to < found.size()));
} catch (RuntimeException error) {
future.completeExceptionally(error);
} finally {
synchronized (this) {
pending.remove(future);
}
}
});
} catch (RuntimeException error) {
pending.remove(future);
future.completeExceptionally(error);
}
return future;
}
public synchronized void close() {
closed = true;
captured.set(null);
for (var future : pending) future.cancel(false);
pending.clear();
}
};
}
};
}
}
@@ -0,0 +1,15 @@
package de.neitzel.grid;
import java.util.Set;
/**
* Independent registration capabilities; a translator must additionally validate each concrete
* condition.
*/
public record FilterCapabilities(
boolean localEvaluation, boolean persistence, Set<String> adapters) {
public FilterCapabilities {
adapters = Set.copyOf(adapters);
adapters.forEach(Checks::id);
}
}
@@ -0,0 +1,11 @@
package de.neitzel.grid;
/**
* Immutable column condition. Custom implementations must preserve value semantics and declare a
* stable type ID.
*/
public interface FilterCondition {
String columnId();
String typeId();
}
@@ -0,0 +1,24 @@
package de.neitzel.grid;
import java.math.BigDecimal;
import java.util.Objects;
/** Immutable portable checklist values; missing is represented separately by ValueFilter. */
public sealed interface FilterValue {
record Text(String value) implements FilterValue {
public Text {
Objects.requireNonNull(value);
}
}
record IntegerValue(long value) implements FilterValue {}
record Decimal(BigDecimal value) implements FilterValue {
public Decimal {
Objects.requireNonNull(value);
value = value.stripTrailingZeros();
}
}
record BooleanValue(boolean value) implements FilterValue {}
}
@@ -0,0 +1,469 @@
package de.neitzel.grid;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
/**
* Serial, owner-thread coordinator. Supply an executor that dispatches callbacks to the creating
* thread, always enqueueing rather than invoking inline (for JavaFX, Platform::runLater). It never
* owns/shuts down sources or executors.
*/
public final class GridCoordinator<K, T> implements AutoCloseable {
public enum Phase {
IDLE,
GUARD,
LOADING,
CONFIRMATION,
READY,
ERROR,
CLOSED
}
public record State<K, T>(
long generation,
GridQuery requested,
GridQuery displayed,
PageResult<K, T> result,
Phase phase,
Throwable error,
long sourceVersion) {}
private final Thread owner = Thread.currentThread();
private final Executor dispatch;
private final Consumer<State<K, T>> observer;
private final Consumer<PageResult<K, T>> publisher;
private GridSource<K, T> source;
private GridSource<K, T> requestedSource;
private GridSource.QueryExecution<K, T> execution;
private State<K, T> state = new State<>(0, null, null, null, Phase.IDLE, null, 0);
private long generation, sourceVersion;
private long threshold = 1000;
private boolean closed;
private boolean notifying;
private boolean restoring;
private State<K, T> restoreBefore;
private Consumer<PageResult<K, T>> requestPublisher;
private Function<GridQuery, CompletionStage<Boolean>> guard =
q -> CompletableFuture.completedFuture(true);
private BiFunction<GridQuery, Long, CompletionStage<Boolean>> confirmation =
(q, n) ->
CompletableFuture.failedFuture(
new IllegalStateException("No All confirmation handler configured"));
public GridCoordinator(
GridSource<K, T> source,
Executor dispatch,
Consumer<State<K, T>> observer,
Consumer<PageResult<K, T>> publisher) {
this.source = Objects.requireNonNull(source);
this.requestedSource = source;
this.dispatch = Objects.requireNonNull(dispatch);
this.observer = Objects.requireNonNull(observer);
this.publisher = Objects.requireNonNull(publisher);
}
public State<K, T> state() {
return state;
}
public SourceCapabilities capabilities() {
check();
return requestedSource.capabilities();
}
public String filterExecutionId() {
check();
return requestedSource.filterExecutionId();
}
public void validateFilters(List<FilterCondition> filters) {
check();
filters.forEach(requestedSource::validateFilter);
}
public void setGuard(Function<GridQuery, CompletionStage<Boolean>> guard) {
check();
this.guard = Objects.requireNonNull(guard);
}
public void setConfirmation(
BiFunction<GridQuery, Long, CompletionStage<Boolean>> confirmation) {
check();
this.confirmation = Objects.requireNonNull(confirmation);
}
public void setAllWarningThreshold(long value) {
check();
if (value < 0) throw new IllegalArgumentException("Negative warning threshold");
threshold = value;
}
public void request(GridQuery query) {
request(requestedSource, query);
}
/** A replacement source becomes committed only after its guarded query succeeds. */
public void request(GridSource<K, T> replacement, GridQuery query) {
request(replacement, query, () -> {}, publisher, false);
}
/** A newer layout-only operation supersedes pending restoration without querying. */
public void cancelRestore() {
check();
if (!restoring) return;
if (notifying) {
dispatch.execute(
() -> {
if (!closed) cancelRestore();
});
return;
}
++generation;
cancelExecution();
var before = restoreBefore;
restore(before);
}
public boolean isRestoring() {
return restoring;
}
/**
* Validated restore: one guard, then one initial query, then atomic application publication.
*/
public void restoreSetup(
GridQuery query, Runnable afterGuard, Consumer<PageResult<K, T>> publish) {
request(
requestedSource,
query,
Objects.requireNonNull(afterGuard),
Objects.requireNonNull(publish),
true);
}
/** Report decode/preparation failure without querying or discarding displayed data. */
public void rejectSetup(Throwable failure) {
check();
if (notifying) {
dispatch.execute(
() -> {
if (!closed) rejectSetup(failure);
});
return;
}
++generation;
cancelExecution();
restoring = false;
restoreBefore = null;
requestPublisher = null;
requestedSource = source;
update(state.displayed(), Phase.ERROR, Objects.requireNonNull(failure));
}
private void request(
GridSource<K, T> replacement,
GridQuery query,
Runnable afterGuard,
Consumer<PageResult<K, T>> publish,
boolean transactional) {
check();
Objects.requireNonNull(replacement);
Objects.requireNonNull(query);
if (notifying) {
dispatch.execute(
() -> {
if (!closed)
request(replacement, query, afterGuard, publish, transactional);
});
return;
}
long token = ++generation;
cancelExecution();
requestedSource = replacement;
var before =
new State<K, T>(
token,
state.displayed() != null ? state.displayed() : state.requested(),
state.displayed(),
state.result(),
state.result() == null ? Phase.IDLE : Phase.READY,
null,
sourceVersion);
restoring = transactional;
restoreBefore = transactional ? before : null;
requestPublisher = publish;
update(query, Phase.GUARD, null);
if (!current(token)) return;
try {
replacement.capabilities().validate(query.page());
await(
Objects.requireNonNull(guard.apply(query)),
token,
(allowed, failure) -> {
if (failure != null) {
fail(query, failure);
return;
}
if (!Boolean.TRUE.equals(allowed)) {
restore(before);
return;
}
try {
afterGuard.run();
if (current(token))
execute(replacement, query, token, false, false, before, threshold);
} catch (RuntimeException error) {
if (current(token)) fail(query, error);
}
});
} catch (RuntimeException failure) {
fail(query, failure);
}
}
public void retry() {
check();
if (state.requested() != null) request(state.requested());
}
public void refresh() {
retry();
}
private void execute(
GridSource<K, T> target,
GridQuery query,
long token,
boolean approved,
boolean corrected,
State<K, T> before,
long attemptThreshold) {
if (!current(token)) return;
update(query, Phase.LOADING, null);
if (!current(token)) return;
try {
execution =
Objects.requireNonNull(
target.query(query, new QueryOptions(attemptThreshold, approved)),
"Missing execution");
await(
Objects.requireNonNull(execution.result()),
token,
(result, failure) -> {
execution = null;
if (failure != null) {
Throwable cause = unwrap(failure);
if (cause instanceof AllRowsConfirmationRequired required
&& query.page() instanceof PageRequest.All
&& !approved) {
update(query, Phase.CONFIRMATION, null);
if (!current(token)) return;
try {
await(
Objects.requireNonNull(
confirmation.apply(query, required.count())),
token,
(allowed, error) -> {
if (error != null) fail(query, error);
else if (Boolean.TRUE.equals(allowed))
execute(
target,
query,
token,
true,
corrected,
before,
attemptThreshold);
else restore(before);
});
} catch (RuntimeException error) {
fail(query, error);
}
} else fail(query, cause);
return;
}
try {
Objects.requireNonNull(result, "Missing page result");
if (!query.page().equals(result.request()))
throw new IllegalArgumentException(
"Source returned a different page request");
if (target.capabilities().exactTotal() && result.total().isEmpty())
throw new IllegalArgumentException(
"Source promised an exact count");
if (query.page() instanceof PageRequest.Paged page
&& page.pageIndex() > 0
&& result.rows().isEmpty()
&& (result.total().isEmpty()
|| result.total().getAsLong() > 0)) {
if (corrected)
throw new IllegalStateException(
"Page changed again during recovery; retry");
long last =
result.total().isPresent()
? (result.total().getAsLong() - 1) / page.pageSize()
: 0;
execute(
target,
new GridQuery(
query.filters(),
query.sort(),
new PageRequest.Paged(last, page.pageSize())),
token,
approved,
true,
before,
attemptThreshold);
return;
}
notifying = true;
try {
requestPublisher.accept(result);
} finally {
notifying = false;
}
if (!current(token)) return;
if (source != target) {
source = target;
sourceVersion++;
}
restoring = false;
restoreBefore = null;
requestPublisher = null;
state =
new State<>(
generation,
query,
query,
result,
Phase.READY,
null,
sourceVersion);
notifyState();
} catch (RuntimeException invalid) {
fail(query, invalid);
}
});
} catch (RuntimeException failure) {
execution = null;
fail(query, failure);
}
}
private <V> void await(
CompletionStage<V> stage, long token, BiConsumer<V, Throwable> callback) {
stage.whenComplete(
(value, failure) ->
dispatch.execute(
() -> {
checkThread();
if (current(token)) callback.accept(value, failure);
}));
}
private void restore(State<K, T> before) {
restoring = false;
restoreBefore = null;
requestPublisher = null;
requestedSource = source;
state =
new State<>(
generation,
before.requested(),
before.displayed(),
before.result(),
before.phase(),
null,
sourceVersion);
notifyState();
}
private void update(GridQuery query, Phase phase, Throwable error) {
state =
new State<>(
generation,
query,
state.displayed(),
state.result(),
phase,
error,
sourceVersion);
notifyState();
}
private void notifyState() {
notifying = true;
try {
observer.accept(state);
} finally {
notifying = false;
}
}
private void fail(GridQuery query, Throwable error) {
if (closed) return;
if (restoring) {
query = restoreBefore.requested();
requestedSource = source;
restoring = false;
restoreBefore = null;
}
requestPublisher = null;
update(query, Phase.ERROR, unwrap(error));
}
private static Throwable unwrap(Throwable failure) {
while ((failure instanceof CompletionException || failure instanceof ExecutionException)
&& failure.getCause() != null) failure = failure.getCause();
return failure;
}
private boolean current(long token) {
return !closed && generation == token;
}
private void cancelExecution() {
if (execution != null) {
var old = execution;
execution = null;
try {
old.cancel();
} catch (RuntimeException ignored) {
/* cancellation is advisory; identity still rejects stale completion */
}
}
}
private void checkThread() {
if (Thread.currentThread() != owner)
throw new IllegalStateException("Use the coordinator owner thread");
}
private void check() {
checkThread();
if (closed) throw new IllegalStateException("Coordinator is closed");
}
public void close() {
checkThread();
if (closed) return;
closed = true;
restoring = false;
restoreBefore = null;
requestPublisher = null;
generation++;
cancelExecution();
state =
new State<>(
generation,
state.requested(),
null,
null,
Phase.CLOSED,
null,
sourceVersion);
source = null;
requestedSource = null;
notifyState();
}
}
@@ -0,0 +1,129 @@
package de.neitzel.grid;
import java.util.*;
import java.util.function.*;
/** Definition identity and layout constraints, independent of JSON and JavaFX. */
public record GridDefinition(String id, int version, List<Column> columns) {
public record Column(
String id,
String type,
double defaultWidth,
double minimumWidth,
double maximumWidth,
int fixedPosition) {
public Column {
Checks.id(id);
Checks.id(type);
if (!Double.isFinite(defaultWidth)
|| !Double.isFinite(minimumWidth)
|| !Double.isFinite(maximumWidth)
|| minimumWidth <= 0
|| defaultWidth < minimumWidth
|| maximumWidth < defaultWidth
|| fixedPosition < -1)
throw new IllegalArgumentException("Invalid column constraints: " + id);
}
}
public GridDefinition {
Checks.id(id);
if (version < 1) throw new IllegalArgumentException("Invalid definition version");
columns = List.copyOf(columns);
if (columns.isEmpty()) throw new IllegalArgumentException("Missing columns");
Set<String> ids = new HashSet<>();
for (int i = 0; i < columns.size(); i++) {
var c = columns.get(i);
if (!ids.add(c.id())) throw new IllegalArgumentException("Duplicate definition column");
if (c.fixedPosition() != -1 && c.fixedPosition() != i)
throw new IllegalArgumentException("Fixed column must match declaration position");
}
}
public record Prepared(GridSetup setup, List<String> adjustments) {
public Prepared {
Objects.requireNonNull(setup);
adjustments = List.copyOf(adjustments);
}
}
/**
* Each migration explicitly advances exactly one definition version; output is fully validated.
*/
public Prepared prepare(
GridSetup input,
Map<Integer, UnaryOperator<GridSetup>> migrations,
SourceCapabilities source,
Consumer<FilterCondition> validateFilter) {
Objects.requireNonNull(input);
Objects.requireNonNull(migrations);
if (input.formatVersion() != 1)
throw new IllegalArgumentException(
"Unsupported setup format version: " + input.formatVersion());
if (!id.equals(input.definitionId()))
throw new IllegalArgumentException(
"Setup belongs to another grid definition: " + input.definitionId());
if (input.definitionVersion() > version)
throw new IllegalArgumentException("Setup uses a future definition version");
GridSetup setup = input;
while (setup.definitionVersion() < version) {
int old = setup.definitionVersion();
var migrate = migrations.get(old);
if (migrate == null)
throw new IllegalArgumentException(
"Missing definition migration from version " + old);
setup = Objects.requireNonNull(migrate.apply(setup), "Migration returned no setup");
if (!id.equals(setup.definitionId())
|| setup.definitionVersion() != old + 1
|| setup.formatVersion() != 1)
throw new IllegalArgumentException(
"Migration must preserve identity/format and advance one definition"
+ " version");
}
Map<String, Column> definitions = new LinkedHashMap<>();
columns.forEach(c -> definitions.put(c.id(), c));
List<GridSetup.ColumnState> next = new ArrayList<>();
List<String> adjustments = new ArrayList<>();
Set<String> seen = new HashSet<>();
for (var saved : setup.columns()) {
var c = definitions.get(saved.id());
if (c == null)
throw new IllegalArgumentException(
"Unknown saved column: " + saved.id() + "; provide a migration");
if (!c.type().equals(saved.type()))
throw new IllegalArgumentException(
"Column type changed: " + saved.id() + "; provide a migration");
ColumnWidth width = saved.width();
if (width instanceof ColumnWidth.Explicit explicit) {
double clamped = Math.clamp(explicit.value(), c.minimumWidth(), c.maximumWidth());
if (clamped != explicit.value())
adjustments.add(
"Column "
+ c.id()
+ " width clamped from "
+ explicit.value()
+ " to "
+ clamped);
width = new ColumnWidth.Explicit(clamped);
}
next.add(new GridSetup.ColumnState(c.id(), c.type(), width));
seen.add(c.id());
}
for (var c : columns)
if (!seen.contains(c.id()))
next.add(new GridSetup.ColumnState(c.id(), c.type(), new ColumnWidth.Default()));
for (int i = 0; i < next.size(); i++) {
int fixed = definitions.get(next.get(i).id()).fixedPosition();
if (fixed >= 0 && fixed != i)
throw new IllegalArgumentException(
"Saved order violates fixed position for "
+ next.get(i).id()
+ "; provide a migration");
}
source.validate(setup.page());
setup.filters().forEach(validateFilter);
return new Prepared(
new GridSetup(1, id, version, next, setup.sort(), setup.filters(), setup.page()),
adjustments);
}
}
@@ -0,0 +1,24 @@
package de.neitzel.grid;
import java.util.*;
/**
* Immutable query. Filters combine with AND; sort keys include the source's stable-key tie-breaker.
*/
public record GridQuery(List<FilterCondition> filters, List<SortKey> sort, PageRequest page) {
public GridQuery {
filters = List.copyOf(filters);
sort = List.copyOf(sort);
Objects.requireNonNull(page);
Set<String> ids = new HashSet<>();
for (var f : filters) {
Checks.id(f.columnId());
Checks.id(f.typeId());
if (!ids.add(f.columnId()))
throw new IllegalArgumentException("Multiple filters for " + f.columnId());
}
ids.clear();
for (var key : sort)
if (!ids.add(key.columnId())) throw new IllegalArgumentException("Duplicate sort key");
}
}
@@ -0,0 +1,13 @@
package de.neitzel.grid;
import java.util.Objects;
/**
* Row identity is independent of page position. The model is application-owned, not deep-copied.
*/
public record GridRow<K, T>(K key, T model) {
public GridRow {
Objects.requireNonNull(key);
Objects.requireNonNull(model);
}
}
@@ -0,0 +1,50 @@
package de.neitzel.grid;
import java.util.*;
/** Plain versioned setup. No selection, credentials, page index, drafts, or approval tokens. */
public record GridSetup(
int formatVersion,
String definitionId,
int definitionVersion,
List<ColumnState> columns,
List<SortKey> sort,
List<FilterCondition> filters,
PageRequest page) {
public record ColumnState(String id, String type, ColumnWidth width) {
/** Older callers must supply a definition type before persistence/restoration. */
public ColumnState(String id, ColumnWidth width) {
this(id, "unspecified", width);
}
public ColumnState {
Checks.id(id);
Checks.id(type);
Objects.requireNonNull(width);
}
}
public GridSetup {
if (formatVersion <= 0 || definitionVersion <= 0)
throw new IllegalArgumentException("Invalid version");
Checks.id(definitionId);
columns = List.copyOf(columns);
sort = List.copyOf(sort);
filters = List.copyOf(filters);
Objects.requireNonNull(page);
Set<String> ids = new HashSet<>();
for (var c : columns)
if (!ids.add(c.id())) throw new IllegalArgumentException("Duplicate column ID");
if (sort.size() > 1)
throw new IllegalArgumentException("Only one user-selected sort is supported");
for (var key : sort)
if (!ids.contains(key.columnId()))
throw new IllegalArgumentException("Unknown sort column");
for (var f : filters)
if (!ids.contains(f.columnId()))
throw new IllegalArgumentException("Unknown filter column");
new GridQuery(filters, sort, page);
if (page instanceof PageRequest.Paged p && p.pageIndex() != 0)
throw new IllegalArgumentException("Setups must start on the first page");
}
}
@@ -0,0 +1,56 @@
package de.neitzel.grid;
import java.util.concurrent.CompletionStage;
/**
* Toolkit-independent source. Implementations validate mappings/semantics and own per-request
* resources.
*/
public interface GridSource<K, T> {
SourceCapabilities capabilities();
QueryExecution<K, T> query(GridQuery query);
/** Stable execution capability ID: "local" or an adapter-specific registration ID. */
default String filterExecutionId() {
return "unspecified";
}
/** Validate concrete semantics before accepting an editor/programmatic draft. */
default void validateFilter(FilterCondition condition) {
throw new UnsupportedOperationException(
"Source does not declare filter support: " + condition.typeId());
}
/**
* Guarded execution. Sources supporting All must override and count in their execution snapshot
* before materializing rows, failing with AllRowsConfirmationRequired when consent is needed.
* The default deliberately rejects All rather than performing an unsafe fetch-first check.
*/
default QueryExecution<K, T> query(GridQuery query, QueryOptions options) {
java.util.Objects.requireNonNull(options);
if (query.page() instanceof PageRequest.All) {
var failure =
java.util.concurrent.CompletableFuture.<PageResult<K, T>>failedFuture(
new UnsupportedOperationException(
"Source does not support guarded All execution"));
return new QueryExecution<>() {
public CompletionStage<PageResult<K, T>> result() {
return failure;
}
public void cancel() {}
};
}
return query(query);
}
/**
* Cancellation is best-effort; coordinators must reject superseded completions independently.
*/
interface QueryExecution<K, T> {
CompletionStage<PageResult<K, T>> result();
void cancel();
}
}
@@ -0,0 +1,44 @@
package de.neitzel.grid;
import java.util.*;
import java.util.function.*;
/**
* Explicit scalar mapping; custom compilers validate their condition and produce local evaluators.
*/
public record MemoryColumn<T>(
String id,
Kind kind,
Function<T, FilterValue> read,
Map<String, Function<FilterCondition, Predicate<FilterValue>>> customFilters) {
public enum Kind {
TEXT,
INTEGER,
DECIMAL,
BOOLEAN
}
public MemoryColumn(String id, Kind kind, Function<T, FilterValue> read) {
this(id, kind, read, Map.of());
}
public MemoryColumn {
Checks.id(id);
Objects.requireNonNull(kind);
Objects.requireNonNull(read);
customFilters = Map.copyOf(customFilters);
customFilters.keySet().forEach(Checks::id);
}
void validate(FilterValue value) {
if (value == null) return;
boolean valid =
switch (kind) {
case TEXT -> value instanceof FilterValue.Text;
case INTEGER -> value instanceof FilterValue.IntegerValue;
case DECIMAL -> value instanceof FilterValue.Decimal;
case BOOLEAN -> value instanceof FilterValue.BooleanValue;
};
if (!valid) throw new IllegalArgumentException("Value type does not match column " + id);
}
}
@@ -0,0 +1,268 @@
package de.neitzel.grid;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.*;
/**
* Local source with caller-thread scalar snapshot capture and executor-based query processing. The
* supplier must return a consistent view; FX-owned lists may be captured on the FX caller thread.
* Captured scalar values are immutable; row models remain application-owned. No executor is closed.
*/
public final class MemoryGridSource<K, T> implements GridSource<K, T> {
private final Supplier<? extends Collection<T>> data;
private final Function<T, K> key;
private final Comparator<K> keyOrder;
private final Map<String, MemoryColumn<T>> columns;
private final Executor executor;
private final SourceCapabilities capabilities;
private record Snapshot<K, T>(K key, T model, Map<String, FilterValue> values) {}
public MemoryGridSource(
Supplier<? extends Collection<T>> data,
Function<T, K> key,
Comparator<K> keyOrder,
List<MemoryColumn<T>> columns,
Executor executor,
int maximumPageSize) {
this.data = Objects.requireNonNull(data);
this.key = Objects.requireNonNull(key);
this.keyOrder = Objects.requireNonNull(keyOrder);
this.executor = Objects.requireNonNull(executor);
Map<String, MemoryColumn<T>> mapped = new LinkedHashMap<>();
for (var column : columns)
if (mapped.putIfAbsent(column.id(), column) != null)
throw new IllegalArgumentException("Duplicate column mapping");
this.columns = Map.copyOf(mapped);
capabilities = new SourceCapabilities(true, true, maximumPageSize);
}
public SourceCapabilities capabilities() {
return capabilities;
}
public QueryExecution<K, T> query(GridQuery query) {
return query(query, QueryOptions.defaults());
}
public QueryExecution<K, T> query(GridQuery query, QueryOptions options) {
CompletableFuture<PageResult<K, T>> result = new CompletableFuture<>();
AtomicBoolean cancelled = new AtomicBoolean();
try {
Objects.requireNonNull(query);
Objects.requireNonNull(options);
capabilities.validate(query.page());
List<Predicate<Snapshot<K, T>>> predicates = new ArrayList<>();
for (var condition : query.filters()) {
var column = column(condition.columnId());
var test = compile(column, condition);
predicates.add(row -> test.test(row.values().get(column.id())));
}
for (var sort : query.sort()) column(sort.columnId());
List<Snapshot<K, T>> snapshot = new ArrayList<>();
Set<K> keys = new HashSet<>();
for (T model : List.copyOf(data.get())) {
K id = Objects.requireNonNull(key.apply(model), "Missing row key");
if (!keys.add(id)) throw new IllegalArgumentException("Duplicate row key");
Map<String, FilterValue> values = new HashMap<>();
for (var column : columns.values()) {
FilterValue value = column.read().apply(model);
column.validate(value);
values.put(column.id(), value);
}
snapshot.add(new Snapshot<>(id, model, Collections.unmodifiableMap(values)));
}
executor.execute(
() -> {
try {
checkCancelled(cancelled);
List<Snapshot<K, T>> matching = new ArrayList<>();
for (var row : snapshot) {
checkCancelled(cancelled);
if (predicates.stream().allMatch(p -> p.test(row)))
matching.add(row);
}
long count = matching.size();
if (query.page() instanceof PageRequest.All
&& !options.allApproved()
&& count > options.allWarningThreshold())
throw new AllRowsConfirmationRequired(count);
matching.sort(
(left, right) -> {
checkCancelled(cancelled);
for (var sort : query.sort()) {
FilterValue a = left.values().get(sort.columnId()),
b = right.values().get(sort.columnId());
if (a == null || b == null) {
if (a != b) return a == null ? 1 : -1;
continue;
}
int c = compare(a, b);
if (c != 0)
return sort.direction()
== SortKey.Direction.ASCENDING
? c
: -c;
}
int byKey = keyOrder.compare(left.key(), right.key());
if (byKey == 0
&& !Objects.equals(left.key(), right.key())) {
throw new IllegalArgumentException(
"Row key comparator must distinguish keys");
}
return byKey;
});
int from = 0, to = matching.size();
boolean hasNext = false;
if (query.page() instanceof PageRequest.Paged page) {
from = (int) Math.min(count, page.offset());
to = (int) Math.min(count, (long) from + page.pageSize());
hasNext = to < count;
}
List<GridRow<K, T>> rows = new ArrayList<>();
for (int i = from; i < to; i++) {
checkCancelled(cancelled);
var row = matching.get(i);
rows.add(new GridRow<>(row.key(), row.model()));
}
checkCancelled(cancelled);
result.complete(
new PageResult<>(
query.page(), rows, OptionalLong.of(count), hasNext));
} catch (RuntimeException failure) {
result.completeExceptionally(failure);
}
});
} catch (RuntimeException failure) {
result.completeExceptionally(failure);
}
return new QueryExecution<>() {
public CompletionStage<PageResult<K, T>> result() {
return result;
}
public void cancel() {
cancelled.set(true);
result.completeExceptionally(new CancellationException("Superseded query"));
}
};
}
@Override
public String filterExecutionId() {
return "local";
}
@Override
public void validateFilter(FilterCondition condition) {
compile(column(condition.columnId()), condition);
}
/** Explicitly attached source-wide candidates; all other column conditions are respected. */
public FilterCandidates.Provider candidateProvider(Function<FilterValue, String> label) {
Objects.requireNonNull(label);
return FilterCandidates.snapshot(
Set.of(FilterCandidates.Scope.SOURCE_WIDE),
context -> {
var selected = column(context.columnId());
var tests =
context.otherFilters().stream()
.map(
condition ->
Map.entry(
condition.columnId(),
compile(
column(condition.columnId()),
condition)))
.toList();
List<Map<String, FilterValue>> snapshot = new ArrayList<>();
for (T model : List.copyOf(data.get())) {
Map<String, FilterValue> values = new HashMap<>();
for (var column : columns.values()) {
var value = column.read().apply(model);
column.validate(value);
values.put(column.id(), value);
}
snapshot.add(Collections.unmodifiableMap(values));
}
return () ->
snapshot.stream()
.filter(
values ->
tests.stream()
.allMatch(
test ->
test.getValue()
.test(
values
.get(
test
.getKey()))))
.map(values -> values.get(selected.id()))
.distinct()
.map(
value ->
new FilterCandidates.Candidate(
value, label.apply(value)))
.toList();
},
executor);
}
private MemoryColumn<T> column(String id) {
var column = columns.get(id);
if (column == null) throw new IllegalArgumentException("Unknown column: " + id);
return column;
}
private Predicate<FilterValue> compile(MemoryColumn<T> column, FilterCondition condition) {
if (condition instanceof MissingFilter filter) return value -> filter.matches(value);
if (condition instanceof ValueFilter filter) {
filter.values().forEach(column::validate);
return filter::matches;
}
if (condition instanceof TextFilter filter) {
if (column.kind() != MemoryColumn.Kind.TEXT)
throw new IllegalArgumentException("Text filter requires a text column");
return value ->
filter.matches(value == null ? null : ((FilterValue.Text) value).value());
}
if (condition instanceof NumericFilter filter) {
if (column.kind() != MemoryColumn.Kind.INTEGER
&& column.kind() != MemoryColumn.Kind.DECIMAL)
throw new IllegalArgumentException("Numeric filter requires a numeric column");
if (column.kind() == MemoryColumn.Kind.INTEGER) {
filter.operand().longValueExact();
if (filter.upper() != null) filter.upper().longValueExact();
}
return value -> filter.matches(value == null ? null : number(value));
}
var compiler = column.customFilters().get(condition.typeId());
if (compiler == null)
throw new UnsupportedOperationException("Unsupported filter: " + condition.typeId());
return Objects.requireNonNull(compiler.apply(condition));
}
private static BigDecimal number(FilterValue value) {
return value instanceof FilterValue.IntegerValue i
? BigDecimal.valueOf(i.value())
: ((FilterValue.Decimal) value).value();
}
private static int compare(FilterValue a, FilterValue b) {
if (a instanceof FilterValue.Text text)
return text.value()
.toLowerCase(Locale.ROOT)
.compareTo(((FilterValue.Text) b).value().toLowerCase(Locale.ROOT));
if (a instanceof FilterValue.BooleanValue bool)
return Boolean.compare(bool.value(), ((FilterValue.BooleanValue) b).value());
return number(a).compareTo(number(b));
}
private static void checkCancelled(AtomicBoolean cancelled) {
if (cancelled.get()) throw new CancellationException("Superseded query");
}
}
@@ -0,0 +1,16 @@
package de.neitzel.grid;
/** Explicit missing/present test; empty strings are present. */
public record MissingFilter(String columnId, boolean missing) implements FilterCondition {
public MissingFilter {
Checks.id(columnId);
}
public String typeId() {
return "neitzel.missing";
}
public boolean matches(Object value) {
return (value == null) == missing;
}
}
@@ -0,0 +1,46 @@
package de.neitzel.grid;
import java.math.BigDecimal;
import java.util.Objects;
/** Exact numeric comparison. Column/domain precision validation belongs to the source mapping. */
public record NumericFilter(
String columnId, Operator operator, BigDecimal operand, BigDecimal upper)
implements FilterCondition {
public enum Operator {
EQUALS,
LESS,
LESS_OR_EQUAL,
GREATER,
GREATER_OR_EQUAL,
RANGE
}
public NumericFilter {
Checks.id(columnId);
Objects.requireNonNull(operator);
Objects.requireNonNull(operand);
if (operator == Operator.RANGE) {
Objects.requireNonNull(upper);
if (operand.compareTo(upper) > 0) throw new IllegalArgumentException("Reversed range");
} else if (upper != null)
throw new IllegalArgumentException("Upper bound is only valid for a range");
}
public String typeId() {
return "neitzel.number";
}
public boolean matches(BigDecimal value) {
if (value == null) return false;
int c = value.compareTo(operand);
return switch (operator) {
case EQUALS -> c == 0;
case LESS -> c < 0;
case LESS_OR_EQUAL -> c <= 0;
case GREATER -> c > 0;
case GREATER_OR_EQUAL -> c >= 0;
case RANGE -> c >= 0 && value.compareTo(upper) <= 0;
};
}
}
@@ -0,0 +1,18 @@
package de.neitzel.grid;
/** Explicit offset paging or unpaged execution. All is never encoded as a magic page size. */
public sealed interface PageRequest {
/** Zero-based page index. UI page labels may be one-based. */
record Paged(long pageIndex, int pageSize) implements PageRequest {
public Paged {
if (pageIndex < 0 || pageSize <= 0) throw new IllegalArgumentException("Invalid page");
Math.multiplyExact(pageIndex, (long) pageSize);
}
public long offset() {
return Math.multiplyExact(pageIndex, (long) pageSize);
}
}
record All() implements PageRequest {}
}
@@ -0,0 +1,29 @@
package de.neitzel.grid;
import java.util.*;
/** A materialized result with exact filtered total or an explicit next-page indication. */
public record PageResult<K, T>(
PageRequest request, List<GridRow<K, T>> rows, OptionalLong total, boolean hasNext) {
public PageResult {
Objects.requireNonNull(request);
rows = List.copyOf(rows);
Objects.requireNonNull(total);
Set<K> keys = new HashSet<>();
for (var row : rows)
if (!keys.add(row.key())) throw new IllegalArgumentException("Duplicate row key");
if (total.isPresent() && total.getAsLong() < 0)
throw new IllegalArgumentException("Negative total");
if (request instanceof PageRequest.Paged p) {
if (rows.size() > p.pageSize()) throw new IllegalArgumentException("Too many rows");
if (total.isPresent()) {
long remaining = Math.max(0, total.getAsLong() - p.offset());
if (rows.size() != Math.min(remaining, p.pageSize())
|| hasNext != (remaining > p.pageSize()))
throw new IllegalArgumentException("Rows/count/navigation disagree");
} else if (hasNext && rows.size() != p.pageSize())
throw new IllegalArgumentException("Next page requires a full page");
} else if (hasNext || (total.isPresent() && total.getAsLong() != rows.size()))
throw new IllegalArgumentException("Invalid unpaged result");
}
}
@@ -0,0 +1,13 @@
package de.neitzel.grid;
/** Per-attempt execution consent. Never persist this with a setup or reuse across user requests. */
public record QueryOptions(long allWarningThreshold, boolean allApproved) {
public QueryOptions {
if (allWarningThreshold < 0)
throw new IllegalArgumentException("Negative All warning threshold");
}
public static QueryOptions defaults() {
return new QueryOptions(1000, false);
}
}
@@ -0,0 +1,16 @@
package de.neitzel.grid;
import java.util.Objects;
/** Sort by mapped column, with missing values last in either direction. */
public record SortKey(String columnId, Direction direction) {
public enum Direction {
ASCENDING,
DESCENDING
}
public SortKey {
Checks.id(columnId);
Objects.requireNonNull(direction);
}
}
@@ -0,0 +1,16 @@
package de.neitzel.grid;
/** Source-level page support; filter semantics are validated separately. */
public record SourceCapabilities(boolean exactTotal, boolean all, int maximumPageSize) {
public SourceCapabilities {
if (maximumPageSize <= 0) throw new IllegalArgumentException("Invalid maximum page size");
}
public void validate(PageRequest request) {
java.util.Objects.requireNonNull(request);
if (request instanceof PageRequest.All && !all)
throw new IllegalArgumentException("Source does not support All");
if (request instanceof PageRequest.Paged p && p.pageSize() > maximumPageSize)
throw new IllegalArgumentException("Unsupported page size");
}
}
@@ -0,0 +1,41 @@
package de.neitzel.grid;
import java.util.Locale;
import java.util.Objects;
/**
* Literal text comparison; missing values never match. No accent removal or Unicode normalization.
*/
public record TextFilter(String columnId, Operator operator, String operand, boolean caseSensitive)
implements FilterCondition {
public enum Operator {
EQUALS,
CONTAINS,
STARTS_WITH,
ENDS_WITH
}
public TextFilter {
Checks.id(columnId);
Objects.requireNonNull(operator);
Objects.requireNonNull(operand);
if (operand.isEmpty() && operator != Operator.EQUALS)
throw new IllegalArgumentException("Empty search operand");
}
public String typeId() {
return "neitzel.text";
}
public boolean matches(String value) {
if (value == null) return false;
String left = caseSensitive ? value : value.toLowerCase(Locale.ROOT),
right = caseSensitive ? operand : operand.toLowerCase(Locale.ROOT);
return switch (operator) {
case EQUALS -> left.equals(right);
case CONTAINS -> left.contains(right);
case STARTS_WITH -> left.startsWith(right);
case ENDS_WITH -> left.endsWith(right);
};
}
}
@@ -0,0 +1,22 @@
package de.neitzel.grid;
import java.util.Set;
/**
* Explicit allowed values. An empty set with includeMissing=false matches nothing, not everything.
*/
public record ValueFilter(String columnId, Set<FilterValue> values, boolean includeMissing)
implements FilterCondition {
public ValueFilter {
Checks.id(columnId);
values = Set.copyOf(values);
}
public String typeId() {
return "neitzel.values";
}
public boolean matches(FilterValue value) {
return value == null ? includeMissing : values.contains(value);
}
}
@@ -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();
}
}
}