Release NeitzelLib 1.0.1 with declarative DataGrid controls and saved setups
This commit is contained in:
@@ -37,3 +37,16 @@ Collection changes do not automatically trigger requests in this slice. Call ref
|
||||
## 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).
|
||||
|
||||
## Page-local grouping and application configuration
|
||||
|
||||
`GroupColumn`, `GroupProjection`, `GroupPath` and `GroupExpansion` capture typed
|
||||
values and project a returned page without fetching or mutating source order.
|
||||
GroupingSetup extends GridSetup v2 with ordered columns and explicit path choices;
|
||||
old constructors/version-one documents remain supported. Group expansion retains
|
||||
current choices plus a configurable inactive LRU history, never historical rows.
|
||||
|
||||
`GridApplicationConfiguration` owns debounced immutable setup snapshots and queued
|
||||
saves after views detach. `GridSetupStore` requires revision-aware conditional
|
||||
writes. The default optional JSON/file implementation is in Gson; no toolkit or
|
||||
JSON dependency is introduced here. See the [integration guide](../fx/docs/data-grid-layout.md).
|
||||
|
||||
+1
-1
@@ -1,6 +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.1-SNAPSHOT</version></parent>
|
||||
<parent><groupId>de.neitzel.lib</groupId><artifactId>neitzellib</artifactId><version>1.0.1</version></parent>
|
||||
<artifactId>data-grid</artifactId>
|
||||
<description>Toolkit-independent filter, query and grid setup contracts</description>
|
||||
</project>
|
||||
|
||||
@@ -0,0 +1,378 @@
|
||||
package de.neitzel.grid;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/**
|
||||
* Application-owned, toolkit-independent save coordination. Accept immutable snapshots on the owner
|
||||
* thread; this service serializes blocking store work on its scheduled worker. No I/O runs in
|
||||
* construction. A detached view does not own or discard already accepted saves.
|
||||
*/
|
||||
public final class GridApplicationConfiguration {
|
||||
public enum Phase {
|
||||
IDLE,
|
||||
LOADING,
|
||||
PENDING,
|
||||
SAVING,
|
||||
SAVED,
|
||||
ERROR,
|
||||
CONFLICT,
|
||||
CLOSED
|
||||
}
|
||||
|
||||
public record State(Phase phase, long generation, boolean dirty, Throwable error) {}
|
||||
|
||||
public record Loaded(
|
||||
GridSetupStore.Key key, GridSetupStore.Stored stored, long storageVersion) {}
|
||||
|
||||
private record Pending(long generation, GridSetup setup, boolean overwrite) {}
|
||||
|
||||
private static final class Slot {
|
||||
final java.util.concurrent.locks.ReentrantLock io =
|
||||
new java.util.concurrent.locks.ReentrantLock();
|
||||
String revision;
|
||||
long generation, storageVersion;
|
||||
Pending pending;
|
||||
ScheduledFuture<?> delay;
|
||||
State state = new State(Phase.IDLE, 0, false, null);
|
||||
final List<Consumer<State>> listeners = new ArrayList<>();
|
||||
}
|
||||
|
||||
@lombok.Getter
|
||||
@lombok.experimental.Accessors(fluent = true)
|
||||
private final String applicationName;
|
||||
|
||||
private final GridSetupStore store;
|
||||
private final ScheduledExecutorService worker;
|
||||
private final boolean ownsWorker;
|
||||
private final long debounceMillis;
|
||||
private final Map<GridSetupStore.Key, Slot> slots = new LinkedHashMap<>();
|
||||
private boolean closing, closed;
|
||||
|
||||
public GridApplicationConfiguration(String applicationName, GridSetupStore store) {
|
||||
this(
|
||||
applicationName,
|
||||
store,
|
||||
Duration.ofMillis(500),
|
||||
Executors.newSingleThreadScheduledExecutor(r -> {
|
||||
Thread thread = new Thread(r, "grid-setup-storage");
|
||||
thread.setDaemon(true);
|
||||
return thread;
|
||||
}),
|
||||
true);
|
||||
}
|
||||
|
||||
public GridApplicationConfiguration(
|
||||
String applicationName,
|
||||
GridSetupStore store,
|
||||
Duration debounce,
|
||||
ScheduledExecutorService worker,
|
||||
boolean ownsWorker) {
|
||||
if (applicationName == null
|
||||
|| applicationName.isBlank()
|
||||
|| applicationName.equals(".")
|
||||
|| applicationName.equals("..")
|
||||
|| applicationName.contains("/")
|
||||
|| applicationName.contains("\\")
|
||||
|| applicationName.indexOf(0) >= 0)
|
||||
throw new IllegalArgumentException("Application name must be a directory name");
|
||||
this.applicationName = applicationName;
|
||||
this.store = Objects.requireNonNull(store);
|
||||
debounceMillis = Objects.requireNonNull(debounce).toMillis();
|
||||
if (debounceMillis < 0) throw new IllegalArgumentException("Negative debounce");
|
||||
this.worker = Objects.requireNonNull(worker);
|
||||
this.ownsWorker = ownsWorker;
|
||||
}
|
||||
|
||||
private Slot slot(GridSetupStore.Key key) {
|
||||
return slots.computeIfAbsent(key, k -> new Slot());
|
||||
}
|
||||
|
||||
private void requireOpen() {
|
||||
if (closed || closing) throw new IllegalStateException("Configuration is closing/closed");
|
||||
}
|
||||
|
||||
public synchronized State state(GridSetupStore.Key key) {
|
||||
return slot(key).state;
|
||||
}
|
||||
|
||||
/** Listener callbacks may run on the storage thread; an FX adapter must dispatch them. */
|
||||
public synchronized AutoCloseable observe(GridSetupStore.Key key, Consumer<State> listener) {
|
||||
requireOpen();
|
||||
var s = slot(key);
|
||||
s.listeners.add(listener);
|
||||
listener.accept(s.state);
|
||||
return () -> {
|
||||
synchronized (this) {
|
||||
s.listeners.remove(listener);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private void emit(Slot slot, Phase phase, Throwable error) {
|
||||
slot.state = new State(phase, slot.generation, slot.pending != null, error);
|
||||
for (var listener : List.copyOf(slot.listeners)) listener.accept(slot.state);
|
||||
}
|
||||
|
||||
public CompletionStage<Loaded> loadAsync(GridSetupStore.Key key) {
|
||||
synchronized (this) {
|
||||
requireOpen();
|
||||
emit(slot(key), Phase.LOADING, null);
|
||||
}
|
||||
return submit(() -> {
|
||||
Slot target;
|
||||
synchronized (this) {
|
||||
target = slot(key);
|
||||
}
|
||||
target.io.lock();
|
||||
try {
|
||||
GridSetupStore.Stored loaded = store.load(key);
|
||||
synchronized (this) {
|
||||
return new Loaded(key, loaded, target.storageVersion);
|
||||
}
|
||||
} catch (Exception failure) {
|
||||
synchronized (this) {
|
||||
emit(target, Phase.ERROR, failure);
|
||||
}
|
||||
throw failure;
|
||||
} finally {
|
||||
target.io.unlock();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** Called only after the grid has successfully validated/published this loaded setup. */
|
||||
public synchronized void adopt(Loaded loaded, long discardedOwnGeneration) {
|
||||
requireOpen();
|
||||
Slot s = slot(loaded.key());
|
||||
if (s.storageVersion == loaded.storageVersion()) s.revision = loaded.stored().revision();
|
||||
if (s.pending != null && s.pending.generation() == discardedOwnGeneration) {
|
||||
s.pending = null;
|
||||
if (s.delay != null) s.delay.cancel(false);
|
||||
}
|
||||
emit(s, s.pending == null ? Phase.SAVED : Phase.PENDING, null);
|
||||
}
|
||||
|
||||
public synchronized long accept(GridSetupStore.Key key, GridSetup setup, Object owner) {
|
||||
return accept(key, setup, owner, false);
|
||||
}
|
||||
|
||||
public synchronized long acceptOverwrite(
|
||||
GridSetupStore.Key key, GridSetup setup, Object owner) {
|
||||
return accept(key, setup, owner, true);
|
||||
}
|
||||
|
||||
private long accept(GridSetupStore.Key key, GridSetup setup, Object owner, boolean overwrite) {
|
||||
requireOpen();
|
||||
Slot s = slot(key);
|
||||
// Owner is an attribution token, never retained: it may be a closed UI view.
|
||||
Objects.requireNonNull(owner);
|
||||
s.pending = new Pending(++s.generation, Objects.requireNonNull(setup), overwrite);
|
||||
if (s.delay != null) s.delay.cancel(false);
|
||||
emit(s, Phase.PENDING, null);
|
||||
long acceptedGeneration = s.generation;
|
||||
s.delay =
|
||||
worker.schedule(
|
||||
() -> {
|
||||
try {
|
||||
write(key, acceptedGeneration);
|
||||
} catch (Exception ignored) {
|
||||
/* retained and exposed through state */
|
||||
}
|
||||
},
|
||||
debounceMillis,
|
||||
TimeUnit.MILLISECONDS);
|
||||
return s.generation;
|
||||
}
|
||||
|
||||
/** Explicit user recovery: still performs a conditional write against a fresh revision. */
|
||||
public CompletionStage<Void> overwriteAsync(
|
||||
GridSetupStore.Key key, GridSetup setup, Object owner) {
|
||||
synchronized (this) {
|
||||
accept(key, setup, owner, true);
|
||||
}
|
||||
return retryAsync(key);
|
||||
}
|
||||
|
||||
public CompletionStage<Void> retryAsync(GridSetupStore.Key key) {
|
||||
synchronized (this) {
|
||||
requireOpen();
|
||||
Slot s = slot(key);
|
||||
if (s.delay != null) s.delay.cancel(false);
|
||||
}
|
||||
return submit(() -> {
|
||||
write(key);
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
private void write(GridSetupStore.Key key) throws Exception {
|
||||
write(key, -1);
|
||||
}
|
||||
|
||||
private void write(GridSetupStore.Key key, long scheduledGeneration) throws Exception {
|
||||
Slot target;
|
||||
synchronized (this) {
|
||||
target = slot(key);
|
||||
}
|
||||
target.io.lock();
|
||||
try {
|
||||
writeLocked(key, scheduledGeneration);
|
||||
} finally {
|
||||
target.io.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
private void writeLocked(GridSetupStore.Key key, long scheduledGeneration) throws Exception {
|
||||
Pending pending;
|
||||
String expected;
|
||||
synchronized (this) {
|
||||
Slot s = slot(key);
|
||||
pending = s.pending;
|
||||
if (pending == null
|
||||
|| closed
|
||||
|| (scheduledGeneration >= 0 && pending.generation() != scheduledGeneration))
|
||||
return;
|
||||
expected = s.revision;
|
||||
emit(s, Phase.SAVING, null);
|
||||
}
|
||||
try {
|
||||
if (pending.overwrite()) expected = store.revision(key);
|
||||
if (expected == null)
|
||||
throw new IllegalStateException(
|
||||
"Load or explicitly reset the saved setup before writing");
|
||||
String revision = store.save(key, expected, pending.setup());
|
||||
synchronized (this) {
|
||||
Slot s = slot(key);
|
||||
s.revision = revision;
|
||||
s.storageVersion++;
|
||||
if (s.pending != null && s.pending.generation() == pending.generation())
|
||||
s.pending = null;
|
||||
emit(s, s.pending == null ? Phase.SAVED : Phase.PENDING, null);
|
||||
}
|
||||
} catch (Exception failure) {
|
||||
synchronized (this) {
|
||||
emit(
|
||||
slot(key),
|
||||
failure instanceof GridSetupStore.Conflict ? Phase.CONFLICT : Phase.ERROR,
|
||||
failure);
|
||||
}
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
|
||||
public CompletionStage<Void> flushAsync() {
|
||||
synchronized (this) {
|
||||
if (closed) return CompletableFuture.completedFuture(null);
|
||||
cancelDelays();
|
||||
}
|
||||
return submit(() -> {
|
||||
flush();
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
private void cancelDelays() {
|
||||
slots.values()
|
||||
.forEach(s -> {
|
||||
if (s.delay != null) s.delay.cancel(false);
|
||||
});
|
||||
}
|
||||
|
||||
private void flush() throws Exception {
|
||||
while (true) {
|
||||
List<GridSetupStore.Key> pending;
|
||||
synchronized (this) {
|
||||
pending =
|
||||
slots.entrySet().stream()
|
||||
.filter(e -> e.getValue().pending != null)
|
||||
.map(Map.Entry::getKey)
|
||||
.toList();
|
||||
}
|
||||
if (pending.isEmpty()) return;
|
||||
for (var key : pending) write(key);
|
||||
}
|
||||
}
|
||||
|
||||
public CompletionStage<Void> closeAsync() {
|
||||
synchronized (this) {
|
||||
if (closed) return CompletableFuture.completedFuture(null);
|
||||
if (closing) throw new IllegalStateException("Close already pending");
|
||||
closing = true;
|
||||
cancelDelays();
|
||||
}
|
||||
return submit(() -> {
|
||||
try {
|
||||
flush();
|
||||
finishClose();
|
||||
return null;
|
||||
} catch (Exception failure) {
|
||||
synchronized (this) {
|
||||
closing = false;
|
||||
}
|
||||
throw failure;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** Explicit quit-without-saving path. It cannot undo a write already committed. */
|
||||
public CompletionStage<Void> discardAndCloseAsync() {
|
||||
synchronized (this) {
|
||||
if (closed) return CompletableFuture.completedFuture(null);
|
||||
closing = true;
|
||||
cancelDelays();
|
||||
slots.values().forEach(s -> s.pending = null);
|
||||
}
|
||||
return submit(() -> {
|
||||
finishClose();
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
private void finishClose() {
|
||||
// A supplied scheduler may have multiple workers. Drain all in-flight slot I/O
|
||||
// before publishing CLOSED, including an already-committing discarded write.
|
||||
List<Slot> targets;
|
||||
synchronized (this) {
|
||||
targets = List.copyOf(slots.values());
|
||||
}
|
||||
targets.forEach(s -> s.io.lock());
|
||||
try {
|
||||
finishCloseLocked();
|
||||
} finally {
|
||||
for (int index = targets.size() - 1; index >= 0; index--)
|
||||
targets.get(index).io.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
private void finishCloseLocked() {
|
||||
synchronized (this) {
|
||||
closed = true;
|
||||
closing = false;
|
||||
slots.values()
|
||||
.forEach(s -> {
|
||||
emit(s, Phase.CLOSED, null);
|
||||
s.listeners.clear();
|
||||
});
|
||||
}
|
||||
if (ownsWorker) worker.shutdown();
|
||||
}
|
||||
|
||||
private <V> CompletionStage<V> submit(Callable<V> action) {
|
||||
CompletableFuture<V> future = new CompletableFuture<>();
|
||||
try {
|
||||
worker.execute(() -> {
|
||||
try {
|
||||
future.complete(action.call());
|
||||
} catch (Exception failure) {
|
||||
future.completeExceptionally(failure);
|
||||
}
|
||||
});
|
||||
} catch (RejectedExecutionException failure) {
|
||||
future.completeExceptionally(failure);
|
||||
}
|
||||
return future;
|
||||
}
|
||||
}
|
||||
@@ -57,7 +57,7 @@ public record GridDefinition(String id, int version, List<Column> columns) {
|
||||
Consumer<FilterCondition> validateFilter) {
|
||||
Objects.requireNonNull(input);
|
||||
Objects.requireNonNull(migrations);
|
||||
if (input.formatVersion() != 1)
|
||||
if (input.formatVersion() != 1 && input.formatVersion() != 2)
|
||||
throw new IllegalArgumentException(
|
||||
"Unsupported setup format version: " + input.formatVersion());
|
||||
if (!id.equals(input.definitionId()))
|
||||
@@ -75,10 +75,10 @@ public record GridDefinition(String id, int version, List<Column> columns) {
|
||||
setup = Objects.requireNonNull(migrate.apply(setup), "Migration returned no setup");
|
||||
if (!id.equals(setup.definitionId())
|
||||
|| setup.definitionVersion() != old + 1
|
||||
|| setup.formatVersion() != 1)
|
||||
|| setup.formatVersion() != input.formatVersion())
|
||||
throw new IllegalArgumentException(
|
||||
"Migration must preserve identity/format and advance one definition"
|
||||
+ " version");
|
||||
+ " version");
|
||||
}
|
||||
Map<String, Column> definitions = new LinkedHashMap<>();
|
||||
columns.forEach(c -> definitions.put(c.id(), c));
|
||||
@@ -123,7 +123,15 @@ public record GridDefinition(String id, int version, List<Column> columns) {
|
||||
source.validate(setup.page());
|
||||
setup.filters().forEach(validateFilter);
|
||||
return new Prepared(
|
||||
new GridSetup(1, id, version, next, setup.sort(), setup.filters(), setup.page()),
|
||||
new GridSetup(
|
||||
setup.formatVersion(),
|
||||
id,
|
||||
version,
|
||||
next,
|
||||
setup.sort(),
|
||||
setup.filters(),
|
||||
setup.page(),
|
||||
setup.grouping()),
|
||||
adjustments);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,7 +10,20 @@ public record GridSetup(
|
||||
List<ColumnState> columns,
|
||||
List<SortKey> sort,
|
||||
List<FilterCondition> filters,
|
||||
PageRequest page) {
|
||||
PageRequest page,
|
||||
GroupingSetup grouping) {
|
||||
/** Source/binary-compatible constructor for version-one clients. */
|
||||
public GridSetup(
|
||||
int formatVersion,
|
||||
String definitionId,
|
||||
int definitionVersion,
|
||||
List<ColumnState> columns,
|
||||
List<SortKey> sort,
|
||||
List<FilterCondition> filters,
|
||||
PageRequest page) {
|
||||
this(formatVersion, definitionId, definitionVersion, columns, sort, filters, page, null);
|
||||
}
|
||||
|
||||
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) {
|
||||
@@ -43,6 +56,17 @@ public record GridSetup(
|
||||
for (var f : filters)
|
||||
if (!ids.contains(f.columnId()))
|
||||
throw new IllegalArgumentException("Unknown filter column");
|
||||
if (formatVersion == 2 && grouping == null)
|
||||
throw new IllegalArgumentException("Version two requires grouping preferences");
|
||||
if (grouping != null) {
|
||||
for (String id : grouping.columns())
|
||||
if (!ids.contains(id))
|
||||
throw new IllegalArgumentException("Unknown grouping column");
|
||||
for (var choice : grouping.choices())
|
||||
for (var segment : choice.path().segments())
|
||||
if (!ids.contains(segment.columnId()))
|
||||
throw new IllegalArgumentException("Unknown group path 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,38 @@
|
||||
package de.neitzel.grid;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Objects;
|
||||
|
||||
/** Blocking store port. The configuration service calls it off the UI thread. */
|
||||
public interface GridSetupStore {
|
||||
record Key(String gridId, String context) {
|
||||
public Key {
|
||||
Checks.id(gridId);
|
||||
if (context != null) Checks.id(context);
|
||||
}
|
||||
}
|
||||
|
||||
record Stored(GridSetup setup, String revision) {
|
||||
public Stored {
|
||||
Objects.requireNonNull(revision);
|
||||
}
|
||||
}
|
||||
|
||||
Stored load(Key key) throws IOException;
|
||||
|
||||
/**
|
||||
* Revision alone must remain readable even when setup decoding fails, for explicit recovery.
|
||||
*/
|
||||
String revision(Key key) throws IOException;
|
||||
|
||||
/** Atomically compare revision and replace the entire setup; never a blind overwrite. */
|
||||
String save(Key key, String expectedRevision, GridSetup setup) throws IOException;
|
||||
|
||||
final class Conflict extends IOException {
|
||||
public Conflict() {
|
||||
super(
|
||||
"Saved grid setup changed in another application instance. Reload or explicitly"
|
||||
+ " overwrite.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package de.neitzel.grid;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.function.Function;
|
||||
|
||||
/** Explicit owner-thread mapping. Labels never determine identity or ordering. */
|
||||
public record GroupColumn<T>(
|
||||
String id,
|
||||
MemoryColumn.Kind kind,
|
||||
Function<T, FilterValue> read,
|
||||
Function<FilterValue, String> label) {
|
||||
public GroupColumn {
|
||||
Checks.id(id);
|
||||
Objects.requireNonNull(kind);
|
||||
Objects.requireNonNull(read);
|
||||
Objects.requireNonNull(label);
|
||||
}
|
||||
|
||||
public static <T> GroupColumn<T> text(String id, Function<T, String> reader) {
|
||||
return new GroupColumn<>(
|
||||
id,
|
||||
MemoryColumn.Kind.TEXT,
|
||||
row -> {
|
||||
String value = reader.apply(row);
|
||||
return value == null ? null : new FilterValue.Text(value);
|
||||
},
|
||||
GroupColumn::display);
|
||||
}
|
||||
|
||||
public static <T> GroupColumn<T> integer(String id, Function<T, Long> reader) {
|
||||
return new GroupColumn<>(
|
||||
id,
|
||||
MemoryColumn.Kind.INTEGER,
|
||||
row -> {
|
||||
Long value = reader.apply(row);
|
||||
return value == null ? null : new FilterValue.IntegerValue(value);
|
||||
},
|
||||
GroupColumn::display);
|
||||
}
|
||||
|
||||
public static <T> GroupColumn<T> decimal(String id, Function<T, java.math.BigDecimal> reader) {
|
||||
return new GroupColumn<>(
|
||||
id,
|
||||
MemoryColumn.Kind.DECIMAL,
|
||||
row -> {
|
||||
var value = reader.apply(row);
|
||||
return value == null ? null : new FilterValue.Decimal(value);
|
||||
},
|
||||
GroupColumn::display);
|
||||
}
|
||||
|
||||
public static <T> GroupColumn<T> bool(String id, Function<T, Boolean> reader) {
|
||||
return new GroupColumn<>(
|
||||
id,
|
||||
MemoryColumn.Kind.BOOLEAN,
|
||||
row -> {
|
||||
Boolean value = reader.apply(row);
|
||||
return value == null ? null : new FilterValue.BooleanValue(value);
|
||||
},
|
||||
GroupColumn::display);
|
||||
}
|
||||
|
||||
public 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("Grouping value type changed: " + id);
|
||||
}
|
||||
|
||||
public static String display(FilterValue value) {
|
||||
return switch (value) {
|
||||
case null -> "(Missing)";
|
||||
case FilterValue.Text t -> t.value().isEmpty() ? "(Empty)" : t.value();
|
||||
case FilterValue.IntegerValue i -> Long.toString(i.value());
|
||||
case FilterValue.Decimal d -> d.value().toPlainString();
|
||||
case FilterValue.BooleanValue b -> Boolean.toString(b.value());
|
||||
};
|
||||
}
|
||||
|
||||
public static int compare(FilterValue a, FilterValue b) {
|
||||
if (a == null) return b == null ? 0 : 1;
|
||||
if (b == null) return -1;
|
||||
return switch (a) {
|
||||
case FilterValue.Text t -> {
|
||||
String right = ((FilterValue.Text) b).value();
|
||||
int order =
|
||||
t.value()
|
||||
.toLowerCase(Locale.ROOT)
|
||||
.compareTo(right.toLowerCase(Locale.ROOT));
|
||||
yield order == 0 ? t.value().compareTo(right) : order;
|
||||
}
|
||||
case FilterValue.IntegerValue i ->
|
||||
Long.compare(i.value(), ((FilterValue.IntegerValue) b).value());
|
||||
case FilterValue.Decimal d -> d.value().compareTo(((FilterValue.Decimal) b).value());
|
||||
case FilterValue.BooleanValue v ->
|
||||
Boolean.compare(v.value(), ((FilterValue.BooleanValue) b).value());
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package de.neitzel.grid;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/** Owner-thread expansion history retaining scalar paths, never rows/models. */
|
||||
public final class GroupExpansion {
|
||||
private final LinkedHashMap<GroupPath, Boolean> choices = new LinkedHashMap<>();
|
||||
private Set<GroupPath> current = Set.of();
|
||||
private boolean defaultCollapsed;
|
||||
private int inactiveLimit;
|
||||
|
||||
public GroupExpansion(boolean defaultCollapsed, int inactiveLimit) {
|
||||
configure(defaultCollapsed, inactiveLimit);
|
||||
}
|
||||
|
||||
public void configure(boolean collapsed, int limit) {
|
||||
if (limit < 0) throw new IllegalArgumentException("Negative expansion history capacity");
|
||||
defaultCollapsed = collapsed;
|
||||
inactiveLimit = limit;
|
||||
trim();
|
||||
}
|
||||
|
||||
public boolean expanded(GroupPath path) {
|
||||
return choices.getOrDefault(path, !defaultCollapsed);
|
||||
}
|
||||
|
||||
public void set(GroupPath path, boolean expanded) {
|
||||
choices.remove(path);
|
||||
choices.put(path, expanded);
|
||||
trim();
|
||||
}
|
||||
|
||||
public void current(Collection<GroupPath> paths) {
|
||||
current = Set.copyOf(paths);
|
||||
for (var path : paths)
|
||||
if (choices.containsKey(path)) {
|
||||
boolean choice = choices.remove(path);
|
||||
choices.put(path, choice);
|
||||
}
|
||||
trim();
|
||||
}
|
||||
|
||||
public List<GroupingSetup.Choice> snapshot() {
|
||||
return choices.entrySet().stream()
|
||||
.map(e -> new GroupingSetup.Choice(e.getKey(), e.getValue()))
|
||||
.toList();
|
||||
}
|
||||
|
||||
public void restore(List<GroupingSetup.Choice> saved) {
|
||||
choices.clear();
|
||||
saved.forEach(c -> choices.put(c.path(), c.expanded()));
|
||||
trim();
|
||||
}
|
||||
|
||||
public void reset() {
|
||||
choices.clear();
|
||||
}
|
||||
|
||||
private void trim() {
|
||||
int inactive = (int) choices.keySet().stream().filter(p -> !current.contains(p)).count();
|
||||
for (var iterator = choices.keySet().iterator();
|
||||
inactive > inactiveLimit && iterator.hasNext(); ) {
|
||||
if (!current.contains(iterator.next())) {
|
||||
iterator.remove();
|
||||
inactive--;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package de.neitzel.grid;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/** Stable typed identity, independent of labels, page position and row identity. */
|
||||
public record GroupPath(List<Segment> segments) {
|
||||
public record Segment(String columnId, FilterValue value) {
|
||||
public Segment {
|
||||
Checks.id(columnId);
|
||||
}
|
||||
}
|
||||
|
||||
public GroupPath {
|
||||
segments = List.copyOf(segments);
|
||||
if (segments.isEmpty()) throw new IllegalArgumentException("Empty group path");
|
||||
Set<String> seen = new HashSet<>();
|
||||
for (var segment : segments)
|
||||
if (!seen.add(segment.columnId()))
|
||||
throw new IllegalArgumentException("Repeated group column");
|
||||
}
|
||||
|
||||
public GroupPath child(String column, FilterValue value) {
|
||||
var next = new ArrayList<>(segments);
|
||||
next.add(new Segment(column, value));
|
||||
return new GroupPath(next);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package de.neitzel.grid;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/** Pure current-page projection. Capture all eligible scalar values before publishing a page. */
|
||||
public final class GroupProjection {
|
||||
private GroupProjection() {}
|
||||
|
||||
public record Value(FilterValue key, String label) {
|
||||
public Value {
|
||||
Objects.requireNonNull(label);
|
||||
}
|
||||
}
|
||||
|
||||
public record Captured<K, T>(GridRow<K, T> row, Map<String, Value> values) {
|
||||
public Captured {
|
||||
Objects.requireNonNull(row);
|
||||
values = Map.copyOf(values);
|
||||
}
|
||||
}
|
||||
|
||||
public record Snapshot<K, T>(List<Captured<K, T>> rows, Map<String, GroupColumn<T>> columns) {
|
||||
public Snapshot {
|
||||
rows = List.copyOf(rows);
|
||||
columns = Map.copyOf(columns);
|
||||
}
|
||||
}
|
||||
|
||||
public record Node<K, T>(
|
||||
GroupPath path, String label, List<Node<K, T>> children, List<GridRow<K, T>> rows) {
|
||||
public Node {
|
||||
children = List.copyOf(children);
|
||||
rows = List.copyOf(rows);
|
||||
}
|
||||
|
||||
public int count() {
|
||||
return rows.size();
|
||||
}
|
||||
}
|
||||
|
||||
public static <K, T> Snapshot<K, T> capture(
|
||||
List<GridRow<K, T>> rows, Collection<GroupColumn<T>> columns) {
|
||||
Map<String, GroupColumn<T>> mappings = new LinkedHashMap<>();
|
||||
for (var c : columns)
|
||||
if (mappings.putIfAbsent(c.id(), c) != null)
|
||||
throw new IllegalArgumentException("Duplicate group mapping");
|
||||
List<Captured<K, T>> captured = new ArrayList<>();
|
||||
for (var row : rows) {
|
||||
Map<String, Value> values = new LinkedHashMap<>();
|
||||
for (var c : columns) {
|
||||
FilterValue key = c.read().apply(row.model());
|
||||
c.validate(key);
|
||||
values.put(c.id(), new Value(key, c.label().apply(key)));
|
||||
}
|
||||
captured.add(new Captured<>(row, values));
|
||||
}
|
||||
return new Snapshot<>(captured, mappings);
|
||||
}
|
||||
|
||||
public static <K, T> List<Node<K, T>> project(Snapshot<K, T> snapshot, List<String> order) {
|
||||
if (new HashSet<>(order).size() != order.size()
|
||||
|| !snapshot.columns().keySet().containsAll(order))
|
||||
throw new IllegalArgumentException("Unknown/repeated grouping column");
|
||||
return build(snapshot.rows(), order, 0, null);
|
||||
}
|
||||
|
||||
private static <K, T> List<Node<K, T>> build(
|
||||
List<Captured<K, T>> rows, List<String> order, int depth, GroupPath parent) {
|
||||
if (depth == order.size()) return List.of();
|
||||
String id = order.get(depth);
|
||||
Map<FilterValue, List<Captured<K, T>>> buckets = new LinkedHashMap<>();
|
||||
for (var row : rows)
|
||||
buckets.computeIfAbsent(row.values().get(id).key(), ignored -> new ArrayList<>())
|
||||
.add(row);
|
||||
List<FilterValue> keys = new ArrayList<>(buckets.keySet());
|
||||
keys.sort(GroupColumn::compare);
|
||||
List<Node<K, T>> nodes = new ArrayList<>();
|
||||
for (var key : keys) {
|
||||
var bucket = buckets.get(key);
|
||||
String label = bucket.getFirst().values().get(id).label();
|
||||
if (bucket.stream().anyMatch(r -> !r.values().get(id).label().equals(label)))
|
||||
throw new IllegalArgumentException("Inconsistent label for group value in " + id);
|
||||
GroupPath path =
|
||||
parent == null
|
||||
? new GroupPath(List.of(new GroupPath.Segment(id, key)))
|
||||
: parent.child(id, key);
|
||||
nodes.add(
|
||||
new Node<>(
|
||||
path,
|
||||
label,
|
||||
build(bucket, order, depth + 1, path),
|
||||
bucket.stream().map(Captured::row).toList()));
|
||||
}
|
||||
return List.copyOf(nodes);
|
||||
}
|
||||
|
||||
public static <K, T> List<GroupPath> paths(List<Node<K, T>> nodes) {
|
||||
List<GroupPath> paths = new ArrayList<>();
|
||||
for (var node : nodes) {
|
||||
paths.add(node.path());
|
||||
paths.addAll(paths(node.children()));
|
||||
}
|
||||
return paths;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package de.neitzel.grid;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/** Committed grouping preferences. Choices are ordered least-recently to most-recently used. */
|
||||
public record GroupingSetup(List<String> columns, List<Choice> choices) {
|
||||
public record Choice(GroupPath path, boolean expanded) {
|
||||
public Choice {
|
||||
Objects.requireNonNull(path);
|
||||
}
|
||||
}
|
||||
|
||||
public GroupingSetup {
|
||||
columns = List.copyOf(columns);
|
||||
choices = List.copyOf(choices);
|
||||
Set<String> ids = new HashSet<>();
|
||||
for (String id : columns) {
|
||||
Checks.id(id);
|
||||
if (!ids.add(id)) throw new IllegalArgumentException("Repeated grouping column");
|
||||
}
|
||||
Set<GroupPath> paths = new HashSet<>();
|
||||
for (var choice : choices)
|
||||
if (!paths.add(choice.path()))
|
||||
throw new IllegalArgumentException("Repeated expansion choice");
|
||||
}
|
||||
|
||||
public static GroupingSetup empty() {
|
||||
return new GroupingSetup(List.of(), List.of());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
package de.neitzel.grid;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.time.Duration;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
|
||||
class GridConfigurationTest {
|
||||
static GridSetup setup(double width) {
|
||||
return new GridSetup(
|
||||
2,
|
||||
"records",
|
||||
1,
|
||||
List.of(new GridSetup.ColumnState("type", "text", new ColumnWidth.Explicit(width))),
|
||||
List.of(),
|
||||
List.of(),
|
||||
new PageRequest.Paged(0, 50),
|
||||
new GroupingSetup(List.of("type"), List.of()));
|
||||
}
|
||||
|
||||
static final GridSetupStore.Key KEY = new GridSetupStore.Key("records", null);
|
||||
|
||||
static final class MemoryStore implements GridSetupStore {
|
||||
GridSetup value;
|
||||
int revision, writes;
|
||||
boolean fail;
|
||||
|
||||
public synchronized Stored load(Key key) {
|
||||
return new Stored(value, Integer.toString(revision));
|
||||
}
|
||||
|
||||
public synchronized String revision(Key key) {
|
||||
return Integer.toString(revision);
|
||||
}
|
||||
|
||||
public synchronized String save(Key key, String expected, GridSetup setup)
|
||||
throws IOException {
|
||||
if (fail) throw new IOException("disk unavailable");
|
||||
if (!expected.equals(Integer.toString(revision))) throw new Conflict();
|
||||
value = setup;
|
||||
writes++;
|
||||
return Integer.toString(++revision);
|
||||
}
|
||||
}
|
||||
|
||||
static GridApplicationConfiguration config(MemoryStore store) {
|
||||
return new GridApplicationConfiguration(
|
||||
"Example",
|
||||
store,
|
||||
Duration.ofHours(1),
|
||||
Executors.newSingleThreadScheduledExecutor(),
|
||||
true);
|
||||
}
|
||||
|
||||
static void load(GridApplicationConfiguration config) throws Exception {
|
||||
config.adopt(config.loadAsync(KEY).toCompletableFuture().get(5, TimeUnit.SECONDS), -1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void coalescesWholeSnapshotsAndDoesNotSaveUnchangedLoadsOrClose() throws Exception {
|
||||
var store = new MemoryStore();
|
||||
var config = config(store);
|
||||
load(config);
|
||||
assertEquals(0, store.writes);
|
||||
config.accept(KEY, setup(100), new Object());
|
||||
config.accept(KEY, setup(200), new Object());
|
||||
config.flushAsync().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
assertEquals(setup(200), store.value);
|
||||
assertEquals(1, store.writes);
|
||||
config.closeAsync().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
assertEquals(1, store.writes);
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedCloseRetainsLatestUnsavedStateAndCanRetry() throws Exception {
|
||||
var store = new MemoryStore();
|
||||
var config = config(store);
|
||||
load(config);
|
||||
config.accept(KEY, setup(100), this);
|
||||
config.flushAsync().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
store.fail = true;
|
||||
config.accept(KEY, setup(200), this);
|
||||
assertThrows(
|
||||
ExecutionException.class,
|
||||
() -> config.closeAsync().toCompletableFuture().get(5, TimeUnit.SECONDS));
|
||||
assertEquals(setup(100), store.value);
|
||||
assertTrue(config.state(KEY).dirty());
|
||||
store.fail = false;
|
||||
config.retryAsync(KEY).toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
assertEquals(setup(200), store.value);
|
||||
config.closeAsync().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Test
|
||||
void reloadCannotDiscardAnotherViewsNewerGeneration() throws Exception {
|
||||
var store = new MemoryStore();
|
||||
var config = config(store);
|
||||
load(config);
|
||||
long old = config.accept(KEY, setup(100), this);
|
||||
var read = config.loadAsync(KEY).toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
config.accept(KEY, setup(200), new Object());
|
||||
config.adopt(read, old);
|
||||
assertTrue(config.state(KEY).dirty());
|
||||
config.flushAsync().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
assertEquals(setup(200), store.value);
|
||||
config.closeAsync().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Test
|
||||
void crossInstanceConflictRequiresExplicitOverwriteAndDiscardCloseDoesNotWrite()
|
||||
throws Exception {
|
||||
var store = new MemoryStore();
|
||||
var first = config(store);
|
||||
var second = config(store);
|
||||
load(first);
|
||||
load(second);
|
||||
first.accept(KEY, setup(100), first);
|
||||
first.flushAsync().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
second.accept(KEY, setup(200), second);
|
||||
assertThrows(
|
||||
ExecutionException.class,
|
||||
() -> second.flushAsync().toCompletableFuture().get(5, TimeUnit.SECONDS));
|
||||
assertEquals(GridApplicationConfiguration.Phase.CONFLICT, second.state(KEY).phase());
|
||||
second.overwriteAsync(KEY, setup(200), second)
|
||||
.toCompletableFuture()
|
||||
.get(5, TimeUnit.SECONDS);
|
||||
assertEquals(setup(200), store.value);
|
||||
second.accept(KEY, setup(300), second);
|
||||
second.discardAndCloseAsync().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
assertEquals(setup(200), store.value);
|
||||
first.closeAsync().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Test
|
||||
void debounceWaitsForQuietPeriodRatherThanSavingEveryChange() throws Exception {
|
||||
var store = new MemoryStore();
|
||||
var clock = new Clock();
|
||||
var config =
|
||||
new GridApplicationConfiguration(
|
||||
"Example", store, Duration.ofMillis(500), clock, false);
|
||||
load(config);
|
||||
config.accept(KEY, setup(100), this);
|
||||
clock.advance(499);
|
||||
assertEquals(0, store.writes);
|
||||
config.accept(KEY, setup(200), this);
|
||||
clock.advance(1);
|
||||
assertEquals(0, store.writes);
|
||||
clock.advance(499);
|
||||
assertEquals(1, store.writes);
|
||||
assertEquals(setup(200), store.value);
|
||||
config.closeAsync().toCompletableFuture().get();
|
||||
}
|
||||
|
||||
@Test
|
||||
void discardCloseWaitsForAnAlreadyCommittingWriteOnAParallelScheduler() throws Exception {
|
||||
var entered = new CountDownLatch(1);
|
||||
var release = new CountDownLatch(1);
|
||||
var closed = new CountDownLatch(1);
|
||||
var backing = new MemoryStore();
|
||||
GridSetupStore store =
|
||||
new GridSetupStore() {
|
||||
public Stored load(Key key) {
|
||||
return backing.load(key);
|
||||
}
|
||||
|
||||
public String revision(Key key) {
|
||||
return backing.revision(key);
|
||||
}
|
||||
|
||||
public String save(Key key, String revision, GridSetup setup)
|
||||
throws IOException {
|
||||
entered.countDown();
|
||||
try {
|
||||
if (!release.await(5, TimeUnit.SECONDS))
|
||||
throw new IOException("Timed out");
|
||||
} catch (InterruptedException failure) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IOException(failure);
|
||||
}
|
||||
return backing.save(key, revision, setup);
|
||||
}
|
||||
};
|
||||
var worker = Executors.newScheduledThreadPool(2);
|
||||
var config =
|
||||
new GridApplicationConfiguration(
|
||||
"Example", store, Duration.ofHours(1), worker, true);
|
||||
load(config);
|
||||
config.observe(
|
||||
KEY,
|
||||
state -> {
|
||||
if (state.phase() == GridApplicationConfiguration.Phase.CLOSED)
|
||||
closed.countDown();
|
||||
});
|
||||
config.accept(KEY, setup(100), this);
|
||||
var write = config.retryAsync(KEY);
|
||||
assertTrue(entered.await(5, TimeUnit.SECONDS));
|
||||
var close = config.discardAndCloseAsync();
|
||||
try {
|
||||
assertFalse(closed.await(100, TimeUnit.MILLISECONDS));
|
||||
} finally {
|
||||
release.countDown();
|
||||
}
|
||||
close.toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
write.toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
assertEquals(GridApplicationConfiguration.Phase.CLOSED, config.state(KEY).phase());
|
||||
assertFalse(config.state(KEY).dirty());
|
||||
}
|
||||
|
||||
/** Deterministic scheduled worker: no wall-clock sleeps in debounce assertions. */
|
||||
static final class Clock extends java.util.concurrent.AbstractExecutorService
|
||||
implements java.util.concurrent.ScheduledExecutorService {
|
||||
long now;
|
||||
boolean shutdown;
|
||||
final List<Job> jobs = new ArrayList<>();
|
||||
|
||||
static final class Job extends java.util.concurrent.FutureTask<Void>
|
||||
implements java.util.concurrent.ScheduledFuture<Void> {
|
||||
final long due;
|
||||
|
||||
Job(Runnable action, long due) {
|
||||
super(action, null);
|
||||
this.due = due;
|
||||
}
|
||||
|
||||
public long getDelay(java.util.concurrent.TimeUnit unit) {
|
||||
return unit.convert(due, java.util.concurrent.TimeUnit.MILLISECONDS);
|
||||
}
|
||||
|
||||
public int compareTo(java.util.concurrent.Delayed other) {
|
||||
return Long.compare(due, ((Job) other).due);
|
||||
}
|
||||
}
|
||||
|
||||
void advance(long millis) {
|
||||
now += millis;
|
||||
var ready = jobs.stream().filter(job -> job.due <= now).toList();
|
||||
jobs.removeAll(ready);
|
||||
ready.forEach(Job::run);
|
||||
}
|
||||
|
||||
public java.util.concurrent.ScheduledFuture<?> schedule(
|
||||
Runnable action, long delay, java.util.concurrent.TimeUnit unit) {
|
||||
var job = new Job(action, now + unit.toMillis(delay));
|
||||
jobs.add(job);
|
||||
return job;
|
||||
}
|
||||
|
||||
public <V> java.util.concurrent.ScheduledFuture<V> schedule(
|
||||
java.util.concurrent.Callable<V> action,
|
||||
long delay,
|
||||
java.util.concurrent.TimeUnit unit) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public java.util.concurrent.ScheduledFuture<?> scheduleAtFixedRate(
|
||||
Runnable r, long a, long b, java.util.concurrent.TimeUnit u) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public java.util.concurrent.ScheduledFuture<?> scheduleWithFixedDelay(
|
||||
Runnable r, long a, long b, java.util.concurrent.TimeUnit u) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public void execute(Runnable command) {
|
||||
command.run();
|
||||
}
|
||||
|
||||
public void shutdown() {
|
||||
shutdown = true;
|
||||
}
|
||||
|
||||
public List<Runnable> shutdownNow() {
|
||||
shutdown = true;
|
||||
return List.of();
|
||||
}
|
||||
|
||||
public boolean isShutdown() {
|
||||
return shutdown;
|
||||
}
|
||||
|
||||
public boolean isTerminated() {
|
||||
return shutdown;
|
||||
}
|
||||
|
||||
public boolean awaitTermination(long timeout, java.util.concurrent.TimeUnit unit) {
|
||||
return shutdown;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
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.atomic.AtomicInteger;
|
||||
|
||||
class GroupingTest {
|
||||
record Item(String type, String status) {}
|
||||
|
||||
static GroupPath path(String value) {
|
||||
return new GroupPath(List.of(new GroupPath.Segment("type", new FilterValue.Text(value))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void snapshotSeparatesExactIdentityAndLabelsFromOrderingAndRetainsLeafSourceOrder() {
|
||||
AtomicInteger calls = new AtomicInteger();
|
||||
var mapping =
|
||||
new GroupColumn<Item>(
|
||||
"type",
|
||||
MemoryColumn.Kind.TEXT,
|
||||
i -> {
|
||||
calls.incrementAndGet();
|
||||
return i.type() == null ? null : new FilterValue.Text(i.type());
|
||||
},
|
||||
GroupColumn::display);
|
||||
var rows =
|
||||
List.of(
|
||||
new GridRow<>(1, new Item("a", "one")),
|
||||
new GridRow<>(2, new Item(null, "two")),
|
||||
new GridRow<>(3, new Item("A", "three")),
|
||||
new GridRow<>(4, new Item("a", "four")),
|
||||
new GridRow<>(5, new Item("", "five")));
|
||||
var snapshot = GroupProjection.capture(rows, List.of(mapping));
|
||||
var groups = GroupProjection.project(snapshot, List.of("type"));
|
||||
assertEquals(
|
||||
List.of("(Empty)", "A", "a", "(Missing)"),
|
||||
groups.stream().map(GroupProjection.Node::label).toList());
|
||||
assertEquals(List.of(1, 4), groups.get(2).rows().stream().map(GridRow::key).toList());
|
||||
assertEquals(5, calls.get());
|
||||
GroupProjection.project(snapshot, List.of("type"));
|
||||
assertEquals(5, calls.get(), "Regroup must use captured scalars, not reread models");
|
||||
assertEquals(List.of(1, 2, 3, 4, 5), rows.stream().map(GridRow::key).toList());
|
||||
}
|
||||
|
||||
@Test
|
||||
void decimalScaleDoesNotCreateDifferentGroupsAndWrongTypesFailBeforePublication() {
|
||||
var mapping =
|
||||
new GroupColumn<BigDecimal>(
|
||||
"amount",
|
||||
MemoryColumn.Kind.DECIMAL,
|
||||
FilterValue.Decimal::new,
|
||||
GroupColumn::display);
|
||||
var groups =
|
||||
GroupProjection.project(
|
||||
GroupProjection.capture(
|
||||
List.of(
|
||||
new GridRow<>(1, new BigDecimal("1.0")),
|
||||
new GridRow<>(2, new BigDecimal("1.00"))),
|
||||
List.of(mapping)),
|
||||
List.of("amount"));
|
||||
assertEquals(1, groups.size());
|
||||
assertEquals(2, groups.getFirst().count());
|
||||
var invalid =
|
||||
new GroupColumn<String>(
|
||||
"type",
|
||||
MemoryColumn.Kind.TEXT,
|
||||
s -> new FilterValue.BooleanValue(true),
|
||||
GroupColumn::display);
|
||||
assertThrows(
|
||||
IllegalArgumentException.class,
|
||||
() -> GroupProjection.capture(List.of(new GridRow<>(1, "x")), List.of(invalid)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void expansionPreservesCurrentChoicesAndBoundsOnlyInactiveHistory() {
|
||||
var expansion = new GroupExpansion(true, 1);
|
||||
expansion.current(List.of(path("A"), path("B")));
|
||||
expansion.set(path("A"), true);
|
||||
expansion.set(path("B"), false);
|
||||
expansion.set(path("C"), true);
|
||||
expansion.set(path("D"), true);
|
||||
assertEquals(3, expansion.snapshot().size());
|
||||
assertTrue(expansion.expanded(path("A")));
|
||||
assertFalse(expansion.expanded(path("C")));
|
||||
expansion.configure(false, 1);
|
||||
assertFalse(
|
||||
expansion.expanded(path("B")),
|
||||
"Explicit choice equal to old default must survive default change");
|
||||
expansion.reset();
|
||||
assertTrue(expansion.expanded(path("B")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void nestedCountsAndPathsDoNotConflateEqualLabelsOrParentCollapse() {
|
||||
var cols =
|
||||
List.of(
|
||||
new GroupColumn<Item>(
|
||||
"type",
|
||||
MemoryColumn.Kind.TEXT,
|
||||
i -> new FilterValue.Text(i.type()),
|
||||
v -> "same"),
|
||||
new GroupColumn<Item>(
|
||||
"status",
|
||||
MemoryColumn.Kind.TEXT,
|
||||
i -> new FilterValue.Text(i.status()),
|
||||
GroupColumn::display));
|
||||
var tree =
|
||||
GroupProjection.project(
|
||||
GroupProjection.capture(
|
||||
List.of(
|
||||
new GridRow<>(1, new Item("A", "live")),
|
||||
new GridRow<>(2, new Item("B", "live"))),
|
||||
cols),
|
||||
List.of("type", "status"));
|
||||
assertEquals(2, tree.size());
|
||||
assertNotEquals(tree.get(0).path(), tree.get(1).path());
|
||||
var expansion = new GroupExpansion(true, 1000);
|
||||
expansion.current(GroupProjection.paths(tree));
|
||||
var parent = tree.get(0).path();
|
||||
var child = tree.get(0).children().getFirst().path();
|
||||
expansion.set(child, true);
|
||||
expansion.set(parent, false);
|
||||
expansion.set(parent, true);
|
||||
assertTrue(expansion.expanded(child));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user