Release NeitzelLib 1.0.1 with declarative DataGrid controls and saved setups
This commit is contained in:
+6
-1
@@ -2,6 +2,11 @@
|
||||
|
||||
This module supplies existing Gson configuration/type adapters and optional DataGrid setup JSON support.
|
||||
|
||||
`de.neitzel.gson.grid.GridSetupJson` encodes explicit format-version-1 documents with independently versioned filter codecs. It depends on neutral `data-grid` contracts, not JavaFX. See [saved setups](../fx/docs/saved-setups.md) for schema behavior, custom codecs and application-owned storage. The `fx` and `data-grid` modules do not depend on this JSON implementation.
|
||||
`de.neitzel.gson.grid.GridSetupJson` encodes explicit format-version-1 and format-version-2 documents with independently versioned filter codecs. It depends on neutral `data-grid` contracts, not JavaFX. See [saved setups](../fx/docs/saved-setups.md) for schema behavior, custom codecs and application-owned storage. The `fx` and `data-grid` modules do not depend on this JSON implementation.
|
||||
|
||||
Use the repository's declared Java 25/Maven wrapper baseline. Run the Gson tests and affected data-grid/FX integration tests when changing the saved setup schema.
|
||||
|
||||
`GridSetupFiles.forApplication(name)` creates the optional application service and
|
||||
revision-aware JSON file store. It reuses core application-directory resolution;
|
||||
construction creates no files. FX attachment, failure/conflict recovery and lifecycle
|
||||
are documented in the [layout/persistence guide](../fx/docs/data-grid-layout.md).
|
||||
|
||||
+2
-1
@@ -7,7 +7,7 @@
|
||||
<parent>
|
||||
<groupId>de.neitzel.lib</groupId>
|
||||
<artifactId>neitzellib</artifactId>
|
||||
<version>1.1-SNAPSHOT</version>
|
||||
<version>1.0.1</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>gson</artifactId>
|
||||
@@ -24,6 +24,7 @@
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency><groupId>de.neitzel.lib</groupId><artifactId>core</artifactId><version>${project.version}</version></dependency>
|
||||
<dependency><groupId>de.neitzel.lib</groupId><artifactId>data-grid</artifactId><version>${project.version}</version></dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.code.gson</groupId>
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
package de.neitzel.gson.grid;
|
||||
|
||||
import de.neitzel.core.config.ApplicationDirectories;
|
||||
import de.neitzel.grid.GridApplicationConfiguration;
|
||||
|
||||
import java.nio.file.Path;
|
||||
|
||||
/** Simple opt-in factory; constructing it does not create directories or read preferences. */
|
||||
public final class GridSetupFiles {
|
||||
private GridSetupFiles() {}
|
||||
|
||||
public static GridApplicationConfiguration forApplication(String application) {
|
||||
return forApplication(
|
||||
application,
|
||||
ApplicationDirectories.configurationDirectory(application).resolve("grids"));
|
||||
}
|
||||
|
||||
public static GridApplicationConfiguration forApplication(
|
||||
String application, Path gridDirectory) {
|
||||
return forApplication(application, gridDirectory, new GridSetupJson());
|
||||
}
|
||||
|
||||
public static GridApplicationConfiguration forApplication(
|
||||
String application, Path gridDirectory, GridSetupJson codecs) {
|
||||
return new GridApplicationConfiguration(
|
||||
application, new JsonGridSetupStore(gridDirectory, codecs));
|
||||
}
|
||||
}
|
||||
@@ -26,7 +26,7 @@ public final class GridSetupJson {
|
||||
}
|
||||
|
||||
private final Map<String, FilterCodec> codecs = new LinkedHashMap<>();
|
||||
private final Gson gson = new GsonBuilder().setPrettyPrinting().create();
|
||||
private final Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls().create();
|
||||
|
||||
public GridSetupJson() {
|
||||
for (String id :
|
||||
@@ -50,10 +50,10 @@ public final class GridSetupJson {
|
||||
}
|
||||
|
||||
public String encode(GridSetup setup) {
|
||||
if (setup.formatVersion() != 1)
|
||||
if (setup.formatVersion() != 1 && setup.formatVersion() != 2)
|
||||
throw new IllegalArgumentException("Unsupported setup format version");
|
||||
JsonObject root = new JsonObject();
|
||||
root.addProperty("formatVersion", 1);
|
||||
root.addProperty("formatVersion", setup.formatVersion());
|
||||
root.addProperty("definitionId", setup.definitionId());
|
||||
root.addProperty("definitionVersion", setup.definitionVersion());
|
||||
JsonArray columns = new JsonArray();
|
||||
@@ -97,6 +97,7 @@ public final class GridSetupJson {
|
||||
page.addProperty("mode", setup.page() instanceof PageRequest.All ? "all" : "paged");
|
||||
if (setup.page() instanceof PageRequest.Paged p) page.addProperty("size", p.pageSize());
|
||||
root.add("page", page);
|
||||
if (setup.formatVersion() == 2) root.add("grouping", grouping(setup.grouping()));
|
||||
return gson.toJson(root);
|
||||
}
|
||||
|
||||
@@ -107,18 +108,29 @@ public final class GridSetupJson {
|
||||
JsonObject root = object(read(reader));
|
||||
if (reader.peek() != JsonToken.END_DOCUMENT)
|
||||
throw new IllegalArgumentException("Trailing JSON content");
|
||||
keys(
|
||||
root,
|
||||
"formatVersion",
|
||||
"definitionId",
|
||||
"definitionVersion",
|
||||
"columns",
|
||||
"sort",
|
||||
"filters",
|
||||
"page");
|
||||
int format = integer(root, "formatVersion");
|
||||
if (format != 1)
|
||||
throw new IllegalArgumentException("Unsupported setup format version: " + format);
|
||||
if (format == 1)
|
||||
keys(
|
||||
root,
|
||||
"formatVersion",
|
||||
"definitionId",
|
||||
"definitionVersion",
|
||||
"columns",
|
||||
"sort",
|
||||
"filters",
|
||||
"page");
|
||||
else if (format == 2)
|
||||
keys(
|
||||
root,
|
||||
"formatVersion",
|
||||
"definitionId",
|
||||
"definitionVersion",
|
||||
"columns",
|
||||
"sort",
|
||||
"filters",
|
||||
"page",
|
||||
"grouping");
|
||||
else throw new IllegalArgumentException("Unsupported setup format version: " + format);
|
||||
List<GridSetup.ColumnState> columns = new ArrayList<>();
|
||||
for (var entry : array(root, "columns")) {
|
||||
var c = object(entry);
|
||||
@@ -184,13 +196,69 @@ public final class GridSetupJson {
|
||||
columns,
|
||||
sort,
|
||||
filters,
|
||||
page);
|
||||
page,
|
||||
format == 2 ? grouping(object(required(root, "grouping"))) : null);
|
||||
} catch (IOException | IllegalStateException | ArithmeticException error) {
|
||||
throw new IllegalArgumentException("Invalid saved setup: " + error.getMessage(), error);
|
||||
}
|
||||
}
|
||||
|
||||
private static JsonElement read(JsonReader reader) throws IOException {
|
||||
private static JsonObject grouping(GroupingSetup grouping) {
|
||||
var object = new JsonObject();
|
||||
var columns = new JsonArray();
|
||||
grouping.columns().forEach(columns::add);
|
||||
object.add("columns", columns);
|
||||
var choices = new JsonArray();
|
||||
for (var choice : grouping.choices()) {
|
||||
var item = new JsonObject();
|
||||
item.addProperty("expanded", choice.expanded());
|
||||
var path = new JsonArray();
|
||||
for (var segment : choice.path().segments()) {
|
||||
var value = new JsonObject();
|
||||
value.addProperty("column", segment.columnId());
|
||||
value.add(
|
||||
"value",
|
||||
segment.value() == null
|
||||
? JsonNull.INSTANCE
|
||||
: BuiltIn.value(segment.value()));
|
||||
path.add(value);
|
||||
}
|
||||
item.add("path", path);
|
||||
choices.add(item);
|
||||
}
|
||||
object.add("choices", choices);
|
||||
return object;
|
||||
}
|
||||
|
||||
private static GroupingSetup grouping(JsonObject object) {
|
||||
keys(object, "columns", "choices");
|
||||
List<String> columns = new ArrayList<>();
|
||||
for (var column : array(object, "columns")) {
|
||||
if (!column.isJsonPrimitive() || !column.getAsJsonPrimitive().isString())
|
||||
throw new IllegalArgumentException("Grouping column must be text");
|
||||
columns.add(column.getAsString());
|
||||
}
|
||||
List<GroupingSetup.Choice> choices = new ArrayList<>();
|
||||
for (var entry : array(object, "choices")) {
|
||||
var item = object(entry);
|
||||
keys(item, "expanded", "path");
|
||||
List<GroupPath.Segment> path = new ArrayList<>();
|
||||
for (var part : array(item, "path")) {
|
||||
var segment = object(part);
|
||||
keys(segment, "column", "value");
|
||||
path.add(
|
||||
new GroupPath.Segment(
|
||||
string(segment, "column"),
|
||||
segment.get("value").isJsonNull()
|
||||
? null
|
||||
: BuiltIn.value(object(segment.get("value")))));
|
||||
}
|
||||
choices.add(new GroupingSetup.Choice(new GroupPath(path), bool(item, "expanded")));
|
||||
}
|
||||
return new GroupingSetup(columns, choices);
|
||||
}
|
||||
|
||||
static JsonElement read(JsonReader reader) throws IOException {
|
||||
return switch (reader.peek()) {
|
||||
case BEGIN_OBJECT -> {
|
||||
reader.beginObject();
|
||||
@@ -223,7 +291,7 @@ public final class GridSetupJson {
|
||||
};
|
||||
}
|
||||
|
||||
private static void keys(JsonObject o, String... names) {
|
||||
static void keys(JsonObject o, String... names) {
|
||||
if (!o.keySet().equals(Set.of(names)))
|
||||
throw new IllegalArgumentException(
|
||||
"Expected properties " + Arrays.toString(names) + ", found " + o.keySet());
|
||||
@@ -236,7 +304,7 @@ public final class GridSetupJson {
|
||||
return v;
|
||||
}
|
||||
|
||||
private static JsonObject object(JsonElement v) {
|
||||
static JsonObject object(JsonElement v) {
|
||||
if (!v.isJsonObject()) throw new IllegalArgumentException("Expected JSON object");
|
||||
return v.getAsJsonObject();
|
||||
}
|
||||
@@ -247,7 +315,7 @@ public final class GridSetupJson {
|
||||
return v.getAsJsonArray();
|
||||
}
|
||||
|
||||
private static String string(JsonObject o, String name) {
|
||||
static String string(JsonObject o, String name) {
|
||||
var v = required(o, name);
|
||||
if (!v.isJsonPrimitive() || !v.getAsJsonPrimitive().isString())
|
||||
throw new IllegalArgumentException("Expected string: " + name);
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
package de.neitzel.gson.grid;
|
||||
|
||||
import com.google.gson.*;
|
||||
import com.google.gson.stream.*;
|
||||
|
||||
import de.neitzel.grid.*;
|
||||
|
||||
import java.io.*;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.security.*;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
|
||||
/** Optional file store: safe opaque identities, strict JSON, locked compare-and-atomic-replace. */
|
||||
public final class JsonGridSetupStore implements GridSetupStore {
|
||||
private static final ReentrantLock[] JVM_LOCKS = new ReentrantLock[64];
|
||||
|
||||
static {
|
||||
Arrays.setAll(JVM_LOCKS, i -> new ReentrantLock());
|
||||
}
|
||||
|
||||
private final Path directory;
|
||||
private final GridSetupJson json;
|
||||
|
||||
public JsonGridSetupStore(Path directory, GridSetupJson json) {
|
||||
this.directory = Objects.requireNonNull(directory).toAbsolutePath().normalize();
|
||||
this.json = Objects.requireNonNull(json);
|
||||
}
|
||||
|
||||
public Path path(Key key) {
|
||||
String identity =
|
||||
key.gridId().length()
|
||||
+ ":"
|
||||
+ key.gridId()
|
||||
+ (key.context() == null
|
||||
? "N"
|
||||
: "S" + key.context().length() + ":" + key.context());
|
||||
return directory.resolve(hash(identity.getBytes(StandardCharsets.UTF_8)) + ".json");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Stored load(Key key) throws IOException {
|
||||
Path path = path(key);
|
||||
if (!Files.exists(path)) return new Stored(null, "absent");
|
||||
byte[] bytes = Files.readAllBytes(path);
|
||||
try (var reader =
|
||||
new JsonReader(new StringReader(new String(bytes, StandardCharsets.UTF_8)))) {
|
||||
reader.setStrictness(Strictness.STRICT);
|
||||
reader.setNestingLimit(80);
|
||||
JsonObject root = GridSetupJson.object(GridSetupJson.read(reader));
|
||||
if (reader.peek() != JsonToken.END_DOCUMENT)
|
||||
throw new IllegalArgumentException("Trailing setup document");
|
||||
GridSetupJson.keys(root, "gridId", "context", "revision", "setup");
|
||||
GridSetupJson.string(root, "revision");
|
||||
String context =
|
||||
root.get("context").isJsonNull() ? null : GridSetupJson.string(root, "context");
|
||||
if (!key.gridId().equals(GridSetupJson.string(root, "gridId"))
|
||||
|| !Objects.equals(key.context(), context))
|
||||
throw new IllegalArgumentException("Stored grid/context identity differs");
|
||||
return new Stored(json.decode(root.get("setup").toString()), hash(bytes));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String revision(Key key) throws IOException {
|
||||
Path path = path(key);
|
||||
return Files.exists(path) ? hash(Files.readAllBytes(path)) : "absent";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String save(Key key, String expected, GridSetup setup) throws IOException {
|
||||
// Encode fully before touching the existing document or acquiring its lock.
|
||||
var root = new JsonObject();
|
||||
root.addProperty("gridId", key.gridId());
|
||||
root.addProperty("context", key.context());
|
||||
root.addProperty("revision", UUID.randomUUID().toString());
|
||||
root.add("setup", JsonParser.parseString(json.encode(setup)));
|
||||
byte[] bytes =
|
||||
new GsonBuilder()
|
||||
.setPrettyPrinting()
|
||||
.serializeNulls()
|
||||
.create()
|
||||
.toJson(root)
|
||||
.getBytes(StandardCharsets.UTF_8);
|
||||
Files.createDirectories(directory);
|
||||
Path path = path(key), lock = path.resolveSibling(path.getFileName() + ".lock");
|
||||
ReentrantLock local = JVM_LOCKS[Math.floorMod(path.hashCode(), JVM_LOCKS.length)];
|
||||
local.lock();
|
||||
try (var channel =
|
||||
FileChannel.open(
|
||||
lock, StandardOpenOption.CREATE, StandardOpenOption.WRITE);
|
||||
var ignored = channel.lock()) {
|
||||
if (!Objects.equals(expected, revision(key))) throw new GridSetupStore.Conflict();
|
||||
Path temporary = Files.createTempFile(directory, ".grid-setup-", ".tmp");
|
||||
try {
|
||||
try (var output = FileChannel.open(temporary, StandardOpenOption.WRITE)) {
|
||||
var buffer = java.nio.ByteBuffer.wrap(bytes);
|
||||
while (buffer.hasRemaining()) output.write(buffer);
|
||||
output.force(true);
|
||||
}
|
||||
Files.move(
|
||||
temporary,
|
||||
path,
|
||||
StandardCopyOption.REPLACE_EXISTING,
|
||||
StandardCopyOption.ATOMIC_MOVE);
|
||||
} finally {
|
||||
Files.deleteIfExists(temporary);
|
||||
}
|
||||
return hash(bytes);
|
||||
} finally {
|
||||
local.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
private static String hash(byte[] bytes) {
|
||||
try {
|
||||
return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes));
|
||||
} catch (NoSuchAlgorithmException impossible) {
|
||||
throw new IllegalStateException(impossible);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package de.neitzel.gson.grid;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import de.neitzel.grid.*;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
class GridFileStoreTest {
|
||||
@TempDir Path directory;
|
||||
|
||||
static GridSetup setup() {
|
||||
return new GridSetup(
|
||||
2,
|
||||
"records",
|
||||
1,
|
||||
List.of(new GridSetup.ColumnState("type", "text", new ColumnWidth.Default())),
|
||||
List.of(),
|
||||
List.of(),
|
||||
new PageRequest.Paged(0, 50),
|
||||
new GroupingSetup(
|
||||
List.of("type"),
|
||||
List.of(
|
||||
new GroupingSetup.Choice(
|
||||
new GroupPath(List.of(new GroupPath.Segment("type", null))),
|
||||
true))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void strictVersionTwoRoundTripKeepsTypedMissingAndRejectsMalformedNewFormat() {
|
||||
var codec = new GridSetupJson();
|
||||
String json = codec.encode(setup());
|
||||
assertEquals(setup(), codec.decode(json));
|
||||
assertThrows(
|
||||
IllegalArgumentException.class,
|
||||
() -> codec.decode(json.replace("\"expanded\": true", "\"expanded\": \"true\"")));
|
||||
assertThrows(
|
||||
IllegalArgumentException.class,
|
||||
() -> codec.decode(json.replace("\"choices\"", "\"unknown\"")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void noFilesUntilSaveAndSafeIdentityDoesNotTreatKeysAsPaths() throws Exception {
|
||||
var root = directory.resolve("not-created");
|
||||
var store = new JsonGridSetupStore(root, new GridSetupJson());
|
||||
var key = new GridSetupStore.Key("../../records", "../outside");
|
||||
assertNull(store.load(key).setup());
|
||||
assertFalse(Files.exists(root));
|
||||
String revision = store.save(key, "absent", setup());
|
||||
assertEquals(root, store.path(key).getParent());
|
||||
assertEquals(setup(), store.load(key).setup());
|
||||
assertThrows(GridSetupStore.Conflict.class, () -> store.save(key, "absent", setup()));
|
||||
assertEquals(revision, store.revision(key));
|
||||
assertNotEquals(
|
||||
store.path(new GridSetupStore.Key("a", null)),
|
||||
store.path(new GridSetupStore.Key("a", "null")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void competingProcessesCannotBothReplaceTheSameRevision() throws Exception {
|
||||
var store = new JsonGridSetupStore(directory, new GridSetupJson());
|
||||
var key = new GridSetupStore.Key("records", null);
|
||||
String revision = store.save(key, "absent", setup());
|
||||
String java = Path.of(System.getProperty("java.home"), "bin", "java").toString();
|
||||
String cp = System.getProperty("java.class.path");
|
||||
var first =
|
||||
new ProcessBuilder(
|
||||
java,
|
||||
"-cp",
|
||||
cp,
|
||||
GridStoreRace.class.getName(),
|
||||
directory.toString(),
|
||||
revision)
|
||||
.redirectErrorStream(true)
|
||||
.start();
|
||||
var second =
|
||||
new ProcessBuilder(
|
||||
java,
|
||||
"-cp",
|
||||
cp,
|
||||
GridStoreRace.class.getName(),
|
||||
directory.toString(),
|
||||
revision)
|
||||
.redirectErrorStream(true)
|
||||
.start();
|
||||
assertTrue(first.waitFor(15, TimeUnit.SECONDS));
|
||||
assertTrue(second.waitFor(15, TimeUnit.SECONDS));
|
||||
var exits = new ArrayList<>(List.of(first.exitValue(), second.exitValue()));
|
||||
Collections.sort(exits);
|
||||
assertEquals(
|
||||
List.of(0, 3),
|
||||
exits,
|
||||
new String(first.getInputStream().readAllBytes())
|
||||
+ new String(second.getInputStream().readAllBytes()));
|
||||
assertEquals(setup(), store.load(key).setup());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package de.neitzel.gson.grid;
|
||||
|
||||
import de.neitzel.grid.*;
|
||||
|
||||
import java.nio.file.Path;
|
||||
|
||||
/** Separate-process CAS probe, deliberately independent of JUnit scheduling. */
|
||||
public final class GridStoreRace {
|
||||
public static void main(String[] args) throws Exception {
|
||||
var store = new JsonGridSetupStore(Path.of(args[0]), new GridSetupJson());
|
||||
try {
|
||||
store.save(new GridSetupStore.Key("records", null), args[1], GridFileStoreTest.setup());
|
||||
} catch (GridSetupStore.Conflict expected) {
|
||||
System.exit(3);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user