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,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);
}
}