diff --git a/.github/workflows/conformance.yml b/.github/workflows/conformance.yml
index d25a080c2c..06fda1ea0d 100644
--- a/.github/workflows/conformance.yml
+++ b/.github/workflows/conformance.yml
@@ -20,13 +20,15 @@ name: conformance
# ts-fast — workspace build + typecheck, TS conformance, completeness (mutation) gate
# (the FULL pass here: MO_CI_MUTATION_SCOPE=full on that job)
# csharp / java-fast (java + kotlin) / python — each port's conformance corpora
-# java-reactor — full-reactor `mvn clean install`, tests on (`--only java-slow`)
-# The Java lanes point the script's Maven repository at ~/.m2/repository so setup-java's
-# maven cache applies; the script's own default (~/.m2-ci) protects a developer's ~/.m2,
-# which an ephemeral hosted runner does not have.
+# java-reactor — full-reactor `mvn clean verify`, tests on (`--only java-slow`)
+# The Java lanes make ~/.m2/repository the script's per-run Maven repository
+# (METAOBJECTS_CI_M2_RUN_REPO) so setup-java's maven cache applies. That is safe only because
+# a hosted runner is ephemeral: the script's own default is a private repository under
+# $DEV_SCRATCH in front of a read-only shared cache, so a developer's or a self-hosted
+# runner's shared repository is never written (scripts/lib/maven-private-repo.sh).
#
# WHY A SCHEDULE, given local-ci already runs nightly: local-ci's `java-slow` lane runs
-# the same full reactor (`gate_java_reactor`, `mvn clean install`) — so "it does not run
+# the same full reactor (`gate_java_reactor`, `mvn clean verify`) — so "it does not run
# the reactor" is NOT the gap. The gap is environmental, and it is measured. Two Java
# test defects (a test asserting on an NPE message HotSpot's fast-throw is entitled to
# stop producing once the path is hot; two test classes sharing files with nothing
@@ -134,7 +136,7 @@ jobs:
# changed ones ts-fast mutates elsewhere (see gate_completeness_diff).
MO_CI_MUTATION_SCOPE: full
run: |
- METAOBJECTS_CI_M2_REPO="$HOME/.m2/repository" \
+ METAOBJECTS_CI_M2_RUN_REPO="$HOME/.m2/repository" \
scripts/ci-local.sh --only "$LANE" --no-integration --strict-toolchains
java-reactor:
@@ -157,5 +159,5 @@ jobs:
env:
MO_CI_JACOCO: '1'
run: |
- METAOBJECTS_CI_M2_REPO="$HOME/.m2/repository" \
+ METAOBJECTS_CI_M2_RUN_REPO="$HOME/.m2/repository" \
scripts/ci-local.sh --only java-slow --no-integration --strict-toolchains
diff --git a/.github/workflows/integration-tests.yml b/.github/workflows/integration-tests.yml
index 48d92dfe15..937869a975 100644
--- a/.github/workflows/integration-tests.yml
+++ b/.github/workflows/integration-tests.yml
@@ -149,5 +149,5 @@ jobs:
MIGRATE_TS_PG_EXPECT: '1'
RUNTIME_TS_PG_EXPECT: '1'
run: |
- METAOBJECTS_CI_M2_REPO="$HOME/.m2/repository" \
+ METAOBJECTS_CI_M2_RUN_REPO="$HOME/.m2/repository" \
scripts/ci-local.sh --only "$LANE" --integration-only --strict-toolchains
diff --git a/.github/workflows/pr-ci.yml b/.github/workflows/pr-ci.yml
index b6422a3246..7e30d2ce37 100644
--- a/.github/workflows/pr-ci.yml
+++ b/.github/workflows/pr-ci.yml
@@ -142,7 +142,7 @@ jobs:
env:
LANE: ${{ matrix.lane }}
run: |
- METAOBJECTS_CI_M2_REPO="$HOME/.m2/repository" \
+ METAOBJECTS_CI_M2_RUN_REPO="$HOME/.m2/repository" \
scripts/ci-local.sh --only "$LANE" --no-integration --strict-toolchains
python:
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 534327d4c4..664bd0207b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -103,6 +103,28 @@ here.**
TypeScript passes both. The other ports take them on in their 1.3.0 REST-standard work. The
decision is [ADR-0068](spec/decisions/ADR-0068-list-query-cross-port-contract.md). A
scenario can now send a body that is not JSON with `rawBody`.
+- **Java: the Spring controller generator writes through the code writer (ADR-0063).**
+ `SpringControllerGenerator` writes through `SpringJavaWriter`, a `JavaWriter` that adds the two
+ layouts Spring source uses and a block does not: a continuation line (two indents deeper) and an
+ indented `case` body. Every member of the generated controller comes from its own protected
+ `write*` method, so an owned copy changes one handler by overriding one method; the `append*`
+ helpers that took a `StringBuilder` are gone. The shared validator members and the decimal and
+ duration import lists in `SpringGeneratorSupport` are written through the writer too
+ (`writeCrossFieldValidationMembers`; `decimalAnnotationImports` and `durationAnnotationImports`
+ now return qualified names). A generated controller changes in two layout details only, checked
+ on 1,512 controllers from every fixture model: its imports are sorted, and the blank line after
+ `public class ... {` is gone.
+
+ The DTO, value-object and shared-enum generators follow (`SpringDtoGenerator`,
+ `SpringValueObjectGenerator`, `Fr019SharedEnum`). A record, patch class, stamping helper and
+ enum declaration each come from a protected method, and the string-returning helpers they used
+ are replaced by writer ones: `SpringTypeMapper.enumDeclaration` by `writeEnumDeclaration`,
+ `SpringRecordBuilder.members` by `writeMembers` (with `applies` to ask first), and an owned DTO
+ generator customizes every file it writes by overriding `newWriter`. Their output changes in
+ layout only, checked on every fixture model in two wire and API configurations: sorted imports
+ with no blank between groups, no blank line after `public final class ...Patch {` or a doubled
+ one in a patch with no settable fields, no trailing indent on the blank lines of a nested enum,
+ and no leading blank line in a file with no package.
- **runtime-ts: one list-query parse for every mount.** `parseListQuery` (exported from
`@metaobjectsdev/runtime-ts`; it does not depend on Drizzle) reads a list request into a
port-neutral `ListQuery`, and each mount compiles that for its own query library. The Drizzle
@@ -112,6 +134,28 @@ here.**
and refuses what the Drizzle mount refuses, with the same bodies;
- `pagination`: the `api.pagination` page size.
+ The names, repository and report-export generators follow (`SpringNamesGenerator`,
+ `SpringRepositoryGenerator`, `SpringReportExportGenerator`), each finder, constant block and
+ writer section from its own protected method; the one layout change in their output is that
+ the blank line after the class or interface opener is gone. So does the output-parser generator
+ (`SpringOutputParserGenerator`), whose `StringBuilder` seams (`emitMapperMethods`, `emitMapper`,
+ `appendMapperHelpers`) now take the writer, and whose parsers gain a blank line after the
+ leading `// GENERATED` comment besides sorted imports. The filter-allowlist, response-format and
+ render-helper generators follow: the allowlist output is unchanged, and the other two gain the
+ same blank after the leading comment, sorted imports and no blank after the class opener.
+ `SpringNaming.packageHeader` is removed; the writer's `packageName` replaces it. The LLM-trace
+ helper and the `requirement-tests` generator follow with the same layout changes, and the
+ witness-key collision error now lists its colliding pairs on one line, separated by `; `.
+ In `codegen-base`, the entity extractor (`ExtractorCodeGenerator`, whose `write*` seams now take
+ a `JavaWriter`, and whose `writeHeader` no longer takes the extractor name or writes the class
+ opener) and the generated `ObjectClassBindingProvider` move to the writer too, with sorted imports
+ and no blank after the class opener; the older object code writers take their indentation unit
+ from `WriterOptions` (`JAVA`, and the new two-space `DIRECT`) instead of a typed string. Every
+ Java generator now writes through the code writer, so the layout ratchet's `unconverted` list
+ is empty. `CodeWriter`, `JavaWriter`, `WriterOptions` and `SpringJavaWriter` join the Java
+ engine surface (`eject.engineSurface.java.engine`), so an ejected generator imports them from
+ the package rather than copying them.
+
With no sort, the `ObjectManager` mount now orders by the primary key. The `ObjectManager`
`Filter` gains `$or` and a case-insensitive `$ilike`, and the class gains `keyFields()` and
`fieldNames()`.
diff --git a/docs/RELEASING-java.md b/docs/RELEASING-java.md
index 99e8281767..a9c94e0886 100644
--- a/docs/RELEASING-java.md
+++ b/docs/RELEASING-java.md
@@ -172,11 +172,12 @@ git push origin main
### 3. Local smoke build
```bash
-cd server/java && mvn clean install
+cd server/java && mvn clean verify
```
-All 14 publishable modules should reach SUCCESS with the full test suite green. The build also installs
-locally into `~/.m2/repository/com/metaobjects/*/7.X.Y/`.
+All 14 publishable modules should reach SUCCESS with the full test suite green. Use `verify`, not
+`install`: a reactor build needs no installed artifacts, and installing writes this version into the
+shared `~/.m2`, where every other checkout building the same number then resolves it.
### 4. Tag the release
diff --git a/docs/RELEASING.md b/docs/RELEASING.md
index 5793e78d22..321e05c8e3 100644
--- a/docs/RELEASING.md
+++ b/docs/RELEASING.md
@@ -929,7 +929,7 @@ versioned on its own major line — npm major + 7, so `7.x` while npm was `0.x`
that happens to share the number.)
Then assert the excluded modules are in sync: `scripts/check-pom-versions.sh`
(also enforced on every push by `.githooks/pre-push` and by `scripts/ci-local.sh`).
-2. **Validate locally:** `cd server/java && mvn -q clean install -DskipTests` (or with tests / `scripts/integration-test.sh java` if runtime changed).
+2. **Validate locally:** `cd server/java && mvn -q clean verify -DskipTests` (or with tests / `scripts/integration-test.sh java` if runtime changed). Use `verify`, not `install`: installing writes this unreleased version into the shared `~/.m2` ([RELEASING-java.md](RELEASING-java.md#3-local-smoke-build)).
3. **Deploy — ONE of two routes, never both** (a second deploy of a published version fails
with `Component … already exists`): push a `java-v` tag, and
`publish-java.yml` runs the deploy below in CI with the signing secrets (how `8.0.4`
diff --git a/docs/features/own-your-codegen.md b/docs/features/own-your-codegen.md
index 94bd9be9a3..9777cb5bfd 100644
--- a/docs/features/own-your-codegen.md
+++ b/docs/features/own-your-codegen.md
@@ -1264,8 +1264,9 @@ flavor, so the writers come with it:
| `JavaCodeWriter` | The Java type of each field; accessor, parameter, class and package names; the body of the interface flavor. |
| `PojoAwareCodeWriter`, `ValueObjectCodeWriter` | The fields, the constructor and the accessor bodies of the two concrete flavors. |
-All seven land in one package and use one another, never the packaged classes: eject
-rewrites the package line of each and, where one imports another, that import. To change a
+All seven land in one package and use one another, never the packaged copies: eject
+rewrites the package line of each and, where one imports another, that import. They do call
+the code writer (`JavaWriter`, `WriterOptions`), which is engine and stays in the package. To change a
field, a constructor or an accessor, edit the writer. You subclass nothing. `-Dlist` gives
`entity` one verdict over all seven files.
@@ -1327,7 +1328,9 @@ the packaged sibling classes they still call, so they compile from any package.
**What stays in the package is the engine**, public and unchanged: the generator base and
runner types, the naming and type-mapping tables (`SpringNaming`, `SpringTypeMapper`,
`KotlinNaming`, `KotlinTypeMapper`), the questions a generator asks of the model
-(`FindInbound`, `TphPlan`, the M:N support, `RestSurfaceGate`), and the Kotlin
+(`FindInbound`, `TphPlan`, the M:N support, `RestSurfaceGate`), the code writer the Java
+generators lay their output out with (`CodeWriter`, `JavaWriter`, `WriterOptions`, and
+`SpringJavaWriter` for Spring source), and the Kotlin
`Fr019SharedEnum`. Anything that returns emitted text is handed over; a table or a model
question is not. The Kotlin `Fr019SharedEnum` writes no output. It answers where a shared or
`@provided` enum lives, and the type mapper and the generator utilities take its
diff --git a/docs/ports/java.md b/docs/ports/java.md
index 3e9858e8f2..75b753685f 100644
--- a/docs/ports/java.md
+++ b/docs/ports/java.md
@@ -884,11 +884,11 @@ engine, `com.metaobjects.config.SharedModel`, stays in the package, so the owned
**Own a generator.** `mvn metaobjects:eject -Dnames=` copies a reference generator into a `codegen/` Maven module under your own package, and prints the module, dependency and `` to wire. See [Own your codegen → Java and Kotlin](../features/own-your-codegen.md#java-and-kotlin-mvn-metaobjectseject). Every generator in the table above can be ejected except `template` and the deprecated `mustache` (see [the primitive](../features/own-your-codegen.md#java-and-kotlin-mvn-metaobjectseject)).
-**`entity` and `extractor` eject from `metaobjects-codegen-base`, each with the rest of its emit.** `mvn metaobjects:eject -Dnames=entity,extractor -Dport=java` (pass `-Dport`: both names are ejectable on both JVM ports). `entity` copies seven files into one package: `JavaObjectCodeGenerator`, the bases it extends (`JavaCodeGenerator`, `BaseObjectCodeGenerator`) and the four writers that emit each class body (`BaseObjectCodeWriter`, `JavaCodeWriter`, `PojoAwareCodeWriter`, `ValueObjectCodeWriter`). The copies use one another, never the packaged classes, so you change a field, a constructor or an accessor by editing the writer. `extractor` copies `ExtractorCodeGenerator` with `JavaCodeWriter` and `BaseObjectCodeWriter`, where it reads class names from; in the same package as `entity` the two share those writers. The file-by-file table is in [Own your codegen → Java `entity` and `extractor`](../features/own-your-codegen.md#java-entity-and-extractor).
+**`entity` and `extractor` eject from `metaobjects-codegen-base`, each with the rest of its emit.** `mvn metaobjects:eject -Dnames=entity,extractor -Dport=java` (pass `-Dport`: both names are ejectable on both JVM ports). `entity` copies seven files into one package: `JavaObjectCodeGenerator`, the bases it extends (`JavaCodeGenerator`, `BaseObjectCodeGenerator`) and the four writers that emit each class body (`BaseObjectCodeWriter`, `JavaCodeWriter`, `PojoAwareCodeWriter`, `ValueObjectCodeWriter`). The copies use one another, never the packaged copies, so you change a field, a constructor or an accessor by editing the writer. (The code writer they call, `JavaWriter` and `WriterOptions`, is engine and comes from the package.) `extractor` copies `ExtractorCodeGenerator` with `JavaCodeWriter` and `BaseObjectCodeWriter`, where it reads class names from; in the same package as `entity` the two share those writers. The file-by-file table is in [Own your codegen → Java `entity` and `extractor`](../features/own-your-codegen.md#java-entity-and-extractor).
**Class headers changed once, and `mvn metaobjects:verify` no longer depends on the clock.** The header comment of every class `entity` writes used to carry an `ObjectCodeWriter:` line (the writer's class name) and a `Generated On:` line (the wall-clock second of the run). Both are gone, so the first regeneration after upgrading changes every generated class file in its header comment and nowhere else. Because of the timestamp, `mvn metaobjects:verify` reported `[content-differs]` for every one of those files unless it ran in the same second as the generate it was checking. Output now holds nothing that varies between runs: regenerating an unchanged model writes the same bytes, and verify passes whenever it runs.
-**Ejecting hands over the shared emit rules.** The `routes`, `dto`, `repository` and `value-object` generators apply rules they share (which fields a DTO and a patch carry, validation annotations, M:N finder names) through `SpringGeneratorSupport`. Ejecting any of them writes one copy of that class beside the owned generators, in their package, and points each owned generator's import at it, so an owned generator never calls the packaged rules and you can change them. The engine classes the copies still import (`SpringNaming`, `SpringTypeMapper`, `SpringM2mSupport`, `AutoSetSupport`, `TphPlan`) never call `SpringGeneratorSupport`; `SpringTypeMapper.mapValueObjectRefOf` is a type-mapping fact and stays engine. The copy is left alone without `-Dforce`, `-Dlist` marks it `identical` or `DIFFERS`, and `mvn metaobjects:verify` does not report it as stale output.
+**Ejecting hands over the shared emit rules.** The `routes`, `dto`, `repository` and `value-object` generators apply rules they share (which fields a DTO and a patch carry, validation annotations, M:N finder names) through `SpringGeneratorSupport`. Ejecting any of them writes one copy of that class beside the owned generators, in their package, and points each owned generator's import at it, so an owned generator never calls the packaged rules and you can change them. The engine classes the copies still import (`SpringNaming`, `SpringTypeMapper`, `SpringM2mSupport`, `AutoSetSupport`, `TphPlan`, and the code writer `SpringJavaWriter` with `JavaWriter`) never call `SpringGeneratorSupport`; `SpringTypeMapper.mapValueObjectRefOf` is a type-mapping fact and stays engine. The copy is left alone without `-Dforce`, `-Dlist` marks it `identical` or `DIFFERS`, and `mvn metaobjects:verify` does not report it as stale output.
**Ejecting hands over the helper runtime too.** The `routes`, `dto` and `repository` output imports helper classes from `com.metaobjects.generator.spring.runtime` (`FilterParser`, `FilterParseResult`, `FilterPredicate`, `PatchValidationException`, `ConstraintErrors`, `RecordComponentNames`). These are helpers, not core. Ejecting one of those generators copies the classes its output imports into `src/main/java//` (default `.runtime`) of the module that compiles the generated code, and the owned generator's output imports that copy. The copies are JDK-only. The owned web tier then builds with no MetaObjects artifact on the application classpath, and you can fix a helper bug in your copy without waiting for a release. A packaged generator that must use the same copy takes `…`. What stays core: the loader and registry, render and extract, OMDB and `metaobjects-om`. `mvn metaobjects:verify` treats the copies as owned code, not stale output. The table, the aggregator rule and a diff recipe for pulling an upstream fix are in [Own your codegen → What eject hands over](../features/own-your-codegen.md#what-eject-hands-over-and-what-stays-core).
diff --git a/examples/showcase/.metaobjects/.gen-state/.hashes/acme.json b/examples/showcase/.metaobjects/.gen-state/.hashes/acme.json
index 774179acca..2d0a306469 100644
--- a/examples/showcase/.metaobjects/.gen-state/.hashes/acme.json
+++ b/examples/showcase/.metaobjects/.gen-state/.hashes/acme.json
@@ -6,7 +6,7 @@
"generated/csharp/SubscriberRoutes.g.cs": "2a217ff5a37674ce5038802631b1d8fd90b22b9849e0288f7daf3bba7f9e862f",
"generated/python/Subscriber.py": "9dd4c0acea47f99d1daf79930f9de2e400f30780ebce6c63f023be528a72b762",
"generated/python/SubscriberBlurbPayload.py": "a5ef8a08e63efbe0f73e39a21a368cff5150c68cc8beeea6e8aab0c755f8bbdd",
- "generated/python/subscriber_filter_allowlist.py": "b0414cc95ff3982c80a0e1a06839f090c0b423e41f5a94275df93426cea09df5",
+ "generated/python/subscriber_filter_allowlist.py": "1762fb8b41516c9ca4d4384563046b73c25ed681e4e5da3db19d7d290f9e8b25",
"generated/python/subscriber_names.py": "269637a02bf9b46f55658b58cb42f83196c03a877e1e2101337847fd406c1561",
"generated/python/subscriber_router.py": "16502ff815bf9ae29c7dba4700d0465d06058a9fd7ea8db5f98334d52d284851",
"generated/ts/Subscriber.queries.ts": {
diff --git a/examples/showcase/generated/java/acme/SubscriberPatch.java b/examples/showcase/generated/java/acme/SubscriberPatch.java
index aeeb00156f..6b416fda76 100644
--- a/examples/showcase/generated/java/acme/SubscriberPatch.java
+++ b/examples/showcase/generated/java/acme/SubscriberPatch.java
@@ -11,7 +11,6 @@
/** GENERATED — presence-tracked partial-update (PATCH) shape for Subscriber. Do not hand-edit; regenerated from metadata. */
public final class SubscriberPatch {
-
private final Map assigned;
private SubscriberPatch(Map assigned) { this.assigned = assigned; }
diff --git a/examples/showcase/generated/python/subscriber_filter_allowlist.py b/examples/showcase/generated/python/subscriber_filter_allowlist.py
index 81f4389fec..136a15cbf7 100644
--- a/examples/showcase/generated/python/subscriber_filter_allowlist.py
+++ b/examples/showcase/generated/python/subscriber_filter_allowlist.py
@@ -4,7 +4,8 @@
"""GENERATED — per-entity FR-009 filter allowlist for Subscriber.
SUBSCRIBER_FILTER_FIELDS lists the filterable field names; SUBSCRIBER_FILTER_OPS_BY_FIELD
-constrains the operator vocabulary for each field by its subtype."""
+constrains the operator vocabulary for each field by its subtype.
+"""
from __future__ import annotations
diff --git a/examples/showcase/jvm/.metaobjects/.gitignore b/examples/showcase/jvm/.metaobjects/.gitignore
new file mode 100644
index 0000000000..8c12b0baef
--- /dev/null
+++ b/examples/showcase/jvm/.metaobjects/.gitignore
@@ -0,0 +1,10 @@
+# Gen-state bodies are a second full copy of all generated output — not worth
+# committing. The MANIFEST is: the `.hashes/` directory (one file per model
+# package) is the only thing that lets `meta gen` tell "this file is exactly
+# what I wrote" from "somebody edited this" on a machine that did not
+# generate it (CLAUDE.md, Storage format).
+#
+# The glob matters. Git will not descend into an excluded DIRECTORY, so a
+# negation under `.gen-state/` can never apply — it has to be `.gen-state/*`.
+.gen-state/*
+!.gen-state/.hashes/
diff --git a/fixtures/generator-registry-conformance/registry.json b/fixtures/generator-registry-conformance/registry.json
index 3326538dd9..2608e5aee6 100644
--- a/fixtures/generator-registry-conformance/registry.json
+++ b/fixtures/generator-registry-conformance/registry.json
@@ -508,6 +508,7 @@
"com.metaobjects.generator.requirement.RequirementTestRenderer",
"com.metaobjects.generator.spring.AutoSetSupport",
"com.metaobjects.generator.spring.FindInbound",
+ "com.metaobjects.generator.spring.SpringJavaWriter",
"com.metaobjects.generator.spring.SpringM2mSupport",
"com.metaobjects.generator.spring.SpringNaming",
"com.metaobjects.generator.spring.SpringTypeMapper",
@@ -515,7 +516,10 @@
"com.metaobjects.generator.util.GeneratedFileWriter",
"com.metaobjects.generator.util.GeneratorUtil",
"com.metaobjects.generator.util.JavaIdentifiers",
- "com.metaobjects.generator.util.RestSurfaceGate"
+ "com.metaobjects.generator.util.RestSurfaceGate",
+ "com.metaobjects.generator.writer.CodeWriter",
+ "com.metaobjects.generator.writer.JavaWriter",
+ "com.metaobjects.generator.writer.WriterOptions"
]
},
"kotlin": {
diff --git a/scripts/ci-local.sh b/scripts/ci-local.sh
index 08c2971735..b5488748b9 100755
--- a/scripts/ci-local.sh
+++ b/scripts/ci-local.sh
@@ -232,16 +232,25 @@ step_passed() { # step_passed "" — true when a step of that name has PAS
cat "$CI_TMP"/*.tsv 2>/dev/null | awk -F'\t' -v n="$1" '$1 == "PASS" && $3 == n { f = 1 } END { exit !f }'
}
-# Every Maven call a gate makes — here and in the scripts it spawns (integration-test.sh,
-# fatjar-smoke.sh) — resolves and INSTALLS into a CI-owned local repository, never the
-# developer's ~/.m2. The Java lanes `mvn install` the tree at the CURRENT version, and on the
-# shared ~/.m2 that silently replaced what Maven Central published under that number: an
-# estate pinned to the current release, or a showcase regen resolving the plugin by version,
-# then built against unreleased main (found cutting 1.0.2 — the "8.0.1" codegen-kotlin jar held
-# a builder 8.0.1 never shipped). MAVEN_ARGS (Maven 3.9+) reaches every `mvn`, spawned
-# scripts included, without touching a call site. The repository persists between runs, so
-# only the first run downloads. Override with METAOBJECTS_CI_M2_REPO.
-export MAVEN_ARGS="${MAVEN_ARGS:+$MAVEN_ARGS }-Dmaven.repo.local=${METAOBJECTS_CI_M2_REPO:-$HOME/.m2-ci/repository}"
+# No Maven call a gate makes — here or in the scripts it spawns (integration-test.sh,
+# regen-showcase.ts) — writes a repository anyone else reads: not ~/.m2, and not the shared
+# ~/.m2-ci this script once installed into. Every worktree builds the same unreleased version,
+# so a shared install silently replaced what other checkouts resolved under that number (found
+# cutting 1.0.2, when the "8.0.1" codegen-kotlin jar held a builder 8.0.1 never shipped, and
+# again in 1.3.0, when branch-built 8.3.0 jars in ~/.m2 had other lanes testing code they did
+# not have). So the conformance and reactor gates are reactor builds that install nothing
+# (`mvn -pl X -am test`, `mvn verify`), and the one step that needs installed artifacts — the
+# out-of-reactor JVM integration modules — installs into THIS run's private repository: a
+# small head under $DEV_SCRATCH in front of the shared cache, which is read only
+# (scripts/lib/maven-private-repo.sh). ci_cleanup deletes the head. MAVEN_ARGS (Maven 3.9+)
+# carries it to every `mvn`, spawned scripts included, without touching a call site.
+# Override the cache with METAOBJECTS_CI_M2_REPO; METAOBJECTS_CI_M2_RUN_REPO names a head to
+# keep (an ephemeral hosted runner passes ~/.m2/repository so setup-java can cache it).
+# shellcheck source=scripts/lib/maven-private-repo.sh
+. "$(dirname "${BASH_SOURCE[0]}")/lib/maven-private-repo.sh"
+mo_maven_private_repo
+CI_M2_OWNED="$MO_M2_OWNED"
+trap 'rm -rf "$CI_TMP" ${CI_M2_OWNED:+"$CI_M2_OWNED"}' EXIT # replaced by ci_cleanup below
# bun exits 1 when an OPTIONAL native dep fails its install script (the
# ssh2/cpu-features chain needs node-gyp on the machine — `npm i -g node-gyp`
@@ -800,14 +809,23 @@ gate_conf_csharp() {
# eject goal and the only one that sees every codegen module, so that module is built here
# for the one test. Kotlin's runs in its own lane below.
gate_conf_java() {
+ # ONE reactor build, so every module tests against this tree's upstream modules and nothing
+ # is installed. Names are fully qualified: the same simple name exists in more than one
+ # module (ObjectModelConformanceTest is in metadata and codegen-kotlin).
+ local t=com.metaobjects tests
+ tests="$t.conformance.ConformanceTest,$t.conformance.YamlConformanceTest"
+ tests+=",$t.object.ObjectModelConformanceTest,$t.registry.RegistryManifestConformanceTest"
+ tests+=",$t.render.RenderCrossPortReportTest,$t.render.VerifyConformanceTest"
+ tests+=",$t.render.extract.ExtractConformanceTest,$t.render.prompt.OutputPromptConformanceTest"
+ tests+=",$t.generator.util.GeneratedFileWriterTest,$t.generator.direct.object.JavaCodegenWriteGuardTest"
+ tests+=",$t.generator.direct.object.JavaAccessorNameCollisionTest"
+ tests+=",$t.generator.spring.ValidationConformanceTest,$t.generator.GeneratorRegistryConformanceTest"
+ tests+=",$t.generator.spring.NoMagicPhysicalNamesTest,$t.generator.spring.CodegenCompileConformanceTest"
+ tests+=",$t.generator.spring.IllegalRecordComponentNameTest,$t.generator.spring.SpringIllegalNameCompileRunTest"
+ tests+=",$t.mojo.EjectContractTest"
( cd server/java \
- && mvn -pl metadata,render,codegen-base,codegen-spring -am install -DskipTests -q \
- && mvn -pl metadata test -Dtest='ConformanceTest,YamlConformanceTest,ObjectModelConformanceTest,RegistryManifestConformanceTest' -q \
- && mvn -pl render test -Dtest='RenderCrossPortReportTest,VerifyConformanceTest,ExtractConformanceTest,OutputPromptConformanceTest' -q \
- && mvn -pl codegen-base test -Dtest='GeneratedFileWriterTest,JavaCodegenWriteGuardTest,JavaAccessorNameCollisionTest' -q \
- && mvn -pl codegen-spring test -Dtest='ValidationConformanceTest,GeneratorRegistryConformanceTest,NoMagicPhysicalNamesTest,CodegenCompileConformanceTest,IllegalRecordComponentNameTest,SpringIllegalNameCompileRunTest' -q \
- && mvn -pl maven-plugin -am install -DskipTests -q \
- && mvn -pl maven-plugin test -Dtest='EjectContractTest' -q )
+ && mvn -pl metadata,render,codegen-base,codegen-spring,maven-plugin -am test -q \
+ -Dsurefire.failIfNoSpecifiedTests=false -Dtest="$tests" )
}
gate_conf_python() {
# FULL suite, not cherry-picked paths. Until 2026-07-19 this ran only
@@ -878,9 +896,11 @@ gate_rust_gen_bench() {
cargo run --release --locked -q -p metaobjects-codegen --example gen_bench -- 20 9
}
gate_conf_kotlin() {
+ # A reactor build, like gate_conf_java: nothing installed, every name fully qualified.
+ local k=com.metaobjects.generator.kotlin
( cd server/java \
- && mvn -pl codegen-kotlin -am install -DskipTests -q \
- && mvn -pl codegen-kotlin test -Dtest='ObjectModelConformanceTest,OutputPromptConformanceTest,ValidationConformanceTest,GeneratorRegistryConformanceTest,RegistryManifestConformanceTest,NoMagicPhysicalNamesTest,CodegenCompileConformanceTest,EjectContractTest' -q )
+ && mvn -pl codegen-kotlin -am test -q -Dsurefire.failIfNoSpecifiedTests=false \
+ -Dtest="$k.ObjectModelConformanceTest,$k.OutputPromptConformanceTest,$k.ValidationConformanceTest,$k.GeneratorRegistryConformanceTest,$k.RegistryManifestConformanceTest,$k.NoMagicPhysicalNamesTest,$k.CodegenCompileConformanceTest,$k.EjectContractTest" )
}
# ── conformance.yml — full reactor + drift/mutation gates ─────────────────────
@@ -892,11 +912,13 @@ gate_conf_kotlin() {
gate_java_reactor() {
local jacoco="-Djacoco.skip=true"
[ "${MO_CI_JACOCO:-0}" = "1" ] && jacoco=""
- ( cd server/java && mvn -q clean install $jacoco )
+ ( cd server/java && mvn -q clean verify $jacoco )
}
-# The full run's JVM integration lanes need the reactor installed and must not install it
-# themselves (two concurrent `mvn install`s clobber the shared module jars). When the reactor
-# step is not selected — `--integration-only` — this installs it without its tests.
+# The full run's JVM integration modules live outside the reactor, so they — alone — need
+# the tree installed. This installs it without tests into THIS run's private repository
+# (MAVEN_ARGS, above), never a shared one, and only the java lane runs it: the two JVM
+# integration lanes read it side by side, and installing there too would race them over
+# the same jars. No `clean`: it reuses the reactor step's compiled classes.
gate_java_install() { ( cd server/java && mvn -q -DskipTests -Djacoco.skip=true install ); }
# ── The mutation (completeness) gate: two scopes over ONE file list ───────────
# Stryker mutates the files listed in `mutate` in server/typescript/packages/metadata/
@@ -1231,8 +1253,9 @@ run_integration_for() { # run_integration_for "
*
- *
Substrate justification (hand-rolled string builder rather than
- * JavaPoet): same trade-off as
- * {@code KotlinSpringControllerGenerator}. Spring annotations
- * ({@code @GetMapping}, {@code @PathVariable}, {@code @RequestParam}) plus
- * generic types ({@code ResponseEntity>}, {@code Optional})
- * don't translate cleanly to JavaPoet's {@code MethodSpec}/{@code AnnotationSpec}
- * APIs without a verbose dance of {@code $T} placeholders; the syntactic
- * surface is small (~110 lines per file) and matches the idiomatic Spring
- * style without the indirection of a typed-emit DSL.
+ *
Layout (ADR-0063): the controller is written through a {@link SpringJavaWriter}. The
+ * imports are collected and sorted by the writer, fixed code is written as it reads with
+ * {@code text()}, and every member of the generated class comes from its own protected
+ * {@code write*} method, so an owned copy (or a subclass) changes one handler by overriding
+ * one method.
*
*
Args:
*
@@ -129,7 +126,21 @@ public class SpringControllerGenerator extends MultiFileDirectGeneratorBase run) {
@@ -150,7 +161,7 @@ public void setRun(Collection extends Generator> run) {
}
/** The runtime package this run's output imports ({@link #ARG_RUNTIME_PACKAGE}). */
- private String runtimePackage = RUNTIME_PACKAGE;
+ protected String runtimePackage = RUNTIME_PACKAGE;
private static final Logger LOG = LoggerFactory.getLogger(SpringControllerGenerator.class);
@@ -159,7 +170,7 @@ protected Class getFilterClass() {
return MetaObject.class;
}
- private MetaDataLoader loader;
+ protected MetaDataLoader loader;
@Override
public void execute(MetaDataLoader loader) {
@@ -233,6 +244,125 @@ protected void logSkip(String entityName, String kind) {
}
}
+ // -----------------------------------------------------------------------
+ // The file: writer, imports, class head, write.
+ // -----------------------------------------------------------------------
+
+ /** The writer one controller file is written with, set to its package. */
+ protected SpringJavaWriter newWriter(String pkg) {
+ SpringJavaWriter w = new SpringJavaWriter();
+ if (!pkg.isEmpty()) w.packageName(pkg);
+ return w;
+ }
+
+ /** A class of the helper runtime, by its qualified name in {@link #runtimePackage}. */
+ protected String runtimeType(String simpleName) {
+ return runtimePackage + "." + simpleName;
+ }
+
+ /** The imports of a WRITABLE controller (vanilla and single-table hierarchy alike). */
+ protected void useWritableImports(SpringJavaWriter w) {
+ w.use("com.fasterxml.jackson.databind.JsonNode");
+ w.use("com.fasterxml.jackson.databind.ObjectMapper");
+ w.use(runtimeType("ConstraintErrors"));
+ w.use(runtimeType("PatchValidationException"));
+ w.use(runtimeType("UnreadableBody"));
+ w.use(runtimeType("UnknownBodyKeys"));
+ w.use(runtimeType("ValidationIssues"));
+ // The escape the PATCH loop applies to each assigned key before naming a Bean
+ // Validation property — see RecordComponentNames for why it is needed at run time.
+ w.use(runtimeType("RecordComponentNames"));
+ w.use("org.springframework.http.HttpStatus");
+ w.use("org.springframework.http.ResponseEntity");
+ w.use("org.springframework.web.bind.annotation.DeleteMapping");
+ w.use("org.springframework.web.bind.annotation.GetMapping");
+ w.use("org.springframework.web.bind.annotation.PathVariable");
+ w.use("org.springframework.web.bind.annotation.PostMapping");
+ w.use("org.springframework.web.bind.annotation.RequestBody");
+ w.use("org.springframework.web.bind.annotation.RequestMapping");
+ w.use("org.springframework.web.bind.annotation.RequestMethod");
+ w.use("org.springframework.web.bind.annotation.RequestParam");
+ w.use("org.springframework.web.bind.annotation.RestController");
+ useFilterImports(w);
+ w.use("jakarta.servlet.http.HttpServletRequest");
+ w.use("jakarta.validation.Validator");
+ useCollectionImports(w);
+ }
+
+ /** The imports of a READ-ONLY controller (projection or served report). */
+ protected void useReadOnlyImports(SpringJavaWriter w, MetaObject entity, boolean hasItem) {
+ w.use("org.springframework.http.HttpStatus");
+ w.use("org.springframework.http.ResponseEntity");
+ w.use("org.springframework.web.bind.annotation.GetMapping");
+ if (hasItem) w.use("org.springframework.web.bind.annotation.PathVariable");
+ w.use("org.springframework.web.bind.annotation.PostMapping");
+ w.use("org.springframework.web.bind.annotation.RequestMapping");
+ if (hasItem) w.use("org.springframework.web.bind.annotation.RequestMethod");
+ w.use("org.springframework.web.bind.annotation.RequestParam");
+ w.use("org.springframework.web.bind.annotation.RestController");
+ useFilterImports(w);
+ if (reportExport && com.metaobjects.generator.util.GeneratorUtil.isReport(entity)) {
+ w.use(runtimeType("ReportExport"));
+ w.use("org.springframework.http.MediaType");
+ }
+ w.use("jakarta.servlet.http.HttpServletRequest");
+ useCollectionImports(w);
+ }
+
+ protected void useFilterImports(SpringJavaWriter w) {
+ w.use(runtimeType("FilterParseResult"));
+ w.use(runtimeType("FilterParser"));
+ w.use(runtimeType("FilterPredicate"));
+ }
+
+ protected void useCollectionImports(SpringJavaWriter w) {
+ w.use("java.util.List");
+ w.use("java.util.Map");
+ w.use("java.util.Set");
+ }
+
+ /** The Javadoc paragraph telling an adopter where the routes' authentication belongs. */
+ protected List authDoc(String routeBase, boolean readOnly) {
+ List out = new ArrayList<>();
+ if (readOnly) {
+ out.add("
Auth: these read endpoints are unauthenticated. Require authentication for this path");
+ out.add("in your Spring Security config, e.g. {@code http.authorizeHttpRequests(a ->");
+ } else {
+ out.add("
Auth: these endpoints are unauthenticated. Require authentication for this path in");
+ out.add("your Spring Security config, e.g. {@code http.authorizeHttpRequests(a ->");
+ }
+ out.add("a.requestMatchers(\"" + routeBase + "/**\").authenticated())}.");
+ out.add("A row-ownership rule (\"only the owner may read this row\") can't be expressed in path");
+ out.add("config — eject this generator with {@code mvn metaobjects:eject} and hand-write those");
+ out.add("endpoints.");
+ return out;
+ }
+
+ /** The class Javadoc, its two annotations and its opening line; the caller closes the block. */
+ protected CodeWriter.Block openControllerClass(SpringJavaWriter w, List doc, String routeBase,
+ String controllerName) {
+ w.doc(doc.toArray(new String[0]));
+ w.line("@RestController");
+ w.line("@RequestMapping(\"" + routeBase + "\")");
+ return w.block("public class " + controllerName + " {");
+ }
+
+ /** Write the finished controller through the shared write path. */
+ protected void writeControllerFile(Path outRoot, String pkg, String controllerName, SpringJavaWriter w,
+ String failureContext) {
+ try {
+ Path outFile = outRoot.resolve(pkg.replace('.', '/')).resolve(controllerName + ".java");
+ GeneratedFileWriter.write(outFile, w.toString());
+ } catch (IOException e) {
+ throw new GeneratorException(
+ "failed writing " + failureContext.replace("{file}", controllerName + ".java") + ": " + e, e);
+ }
+ }
+
+ // -----------------------------------------------------------------------
+ // The WRITABLE controller.
+ // -----------------------------------------------------------------------
+
protected void emit(MetaObject entity, Path outRoot) {
String[] split = SpringNaming.splitFqn(entity.getName());
String pkg = split[0];
@@ -255,99 +385,77 @@ protected void emit(MetaObject entity, Path outRoot) {
// ordering, and a 400 on the ports that reject it.)
List sortFields = sortableFields(entity);
- StringBuilder src = new StringBuilder();
- if (!pkg.isEmpty()) {
- src.append("package ").append(pkg).append(";\n\n");
- }
- src.append("import com.fasterxml.jackson.databind.JsonNode;\n");
- src.append("import com.fasterxml.jackson.databind.ObjectMapper;\n");
- src.append("import ").append(runtimePackage).append(".ConstraintErrors;\n");
- src.append("import ").append(runtimePackage).append(".PatchValidationException;\n");
- src.append("import ").append(runtimePackage).append(".UnreadableBody;\n");
- src.append("import ").append(runtimePackage).append(".UnknownBodyKeys;\n");
- src.append("import ").append(runtimePackage).append(".ValidationIssues;\n");
- // The escape the PATCH loop applies to each assigned key before naming a Bean
- // Validation property — see RecordComponentNames for why it is needed at run time.
- src.append("import ").append(runtimePackage).append(".RecordComponentNames;\n");
- src.append("import org.springframework.http.HttpStatus;\n");
- src.append("import org.springframework.http.ResponseEntity;\n");
- src.append("import org.springframework.web.bind.annotation.DeleteMapping;\n");
- src.append("import org.springframework.web.bind.annotation.GetMapping;\n");
- src.append("import org.springframework.web.bind.annotation.PathVariable;\n");
- src.append("import org.springframework.web.bind.annotation.PostMapping;\n");
- src.append("import org.springframework.web.bind.annotation.RequestBody;\n");
- src.append("import org.springframework.web.bind.annotation.RequestMapping;\n");
- src.append("import org.springframework.web.bind.annotation.RequestMethod;\n");
- src.append("import org.springframework.web.bind.annotation.RequestParam;\n");
- src.append("import org.springframework.web.bind.annotation.RestController;\n");
- src.append("import ").append(runtimePackage).append(".FilterParseResult;\n");
- src.append("import ").append(runtimePackage).append(".FilterParser;\n");
- src.append("import ").append(runtimePackage).append(".FilterPredicate;\n");
- src.append("import jakarta.servlet.http.HttpServletRequest;\n");
- src.append("import jakarta.validation.Validator;\n");
- src.append("import java.util.List;\n");
- src.append("import java.util.Map;\n");
- src.append("import java.util.Set;\n\n");
-
- src.append("/**\n");
- src.append(" * GENERATED — REST controller for ").append(shortName)
- .append(" entity. Implements the cross-port API contract.\n");
- src.append(" *\n");
- src.append(" *
Auth: these endpoints are unauthenticated. Require authentication for this path in\n");
- src.append(" * your Spring Security config, e.g. {@code http.authorizeHttpRequests(a ->\n");
- src.append(" * a.requestMatchers(\"").append(routeBase).append("/**\").authenticated())}.\n");
- src.append(" * A row-ownership rule (\"only the owner may read this row\") can't be expressed in path\n");
- src.append(" * config — eject this generator with {@code mvn metaobjects:eject} and hand-write those\n");
- src.append(" * endpoints.\n");
- src.append(" */\n");
- src.append("@RestController\n");
- src.append("@RequestMapping(\"").append(routeBase).append("\")\n");
- src.append("public class ").append(controllerName).append(" {\n\n");
-
- // Sort allowlist — static per-entity Set. Field-prefixed inner constant keeps it
- // private to this controller (no cross-file collision risk).
- appendSortAllowlist(src, entity, sortFields);
- appendServerOwnedOnCreate(src, entity);
- ApiSettings api = ApiSettings.of(entity);
- appendKnownFields(src, api, new ArrayList<>(entity.getMetaFields()));
- // #484: the credential fields this entity's rows carry, hidden from every response body.
- List hidden = SpringGeneratorSupport.credentialNames(entity);
- List navs = SpringM2mSupport.resolve(entity, loader);
- boolean redacts = !hidden.isEmpty() || navs.stream().anyMatch(n -> !targetCredentials(entity, n).isEmpty());
-
- // Repository wiring — constructor injection (Spring's recommended idiom; avoids
- // field-injection magic, plays well with final fields + final test seams). The
- // ObjectMapper (Spring's configured bean) binds the FR-035 patch body's per-field
- // values via Patch.fromJson, so the same wire codecs apply as on create.
- // FR-036: the injected jakarta Validator runs the DTO's field constraints over HTTP
- // (POST validates the whole DTO; PATCH validates each present value) so a constraint
- // violation returns the cross-port {"error":"validation"} envelope, not Spring's default.
- src.append(" private final ").append(repoName).append(" repository;\n");
- src.append(" private final ObjectMapper objectMapper;\n");
- src.append(" private final Validator validator;\n\n");
- src.append(" public ").append(controllerName).append("(").append(repoName)
- .append(" repository, ObjectMapper objectMapper, Validator validator) {\n");
- src.append(" this.repository = repository;\n");
- src.append(" this.objectMapper = objectMapper;\n");
- src.append(" this.validator = validator;\n");
- src.append(" }\n\n");
- appendUnreadableBodyHandler(src);
- if (redacts) appendRedactHelpers(src);
-
- // GET (list) — pagination + sort + withCount + FR-009 filter operators.
- // HttpServletRequest carries the raw query string so the bracketed
- // filter[][]= grammar reaches FilterParser intact
- // (Spring's @RequestParam would collapse same-key occurrences).
- appendListHandler(src, shortName, dtoName, repoName, hidden, api.pagination());
-
- // GET /{id} — single by primary key.
- appendGetByIdHandler(src, pkType, hidden);
-
- // POST — create. FR-036: bind the raw DTO (no @Valid, whose default 400 body is NOT the
- // cross-port envelope and does not even fire under the standaloneSetup test harness) and
- // validate it EXPLICITLY with the injected Validator, emitting {"error":"validation"} on
- // any field-constraint violation BEFORE persisting.
- src.append(" @PostMapping\n");
+ SpringJavaWriter w = newWriter(pkg);
+ useWritableImports(w);
+ List doc = new ArrayList<>();
+ doc.add("GENERATED — REST controller for " + shortName + " entity. Implements the cross-port API contract.");
+ doc.add("");
+ doc.addAll(authDoc(routeBase, false));
+ try (CodeWriter.Block cls = openControllerClass(w, doc, routeBase, controllerName)) {
+ // Sort allowlist — static per-entity Set. Field-prefixed inner constant keeps it
+ // private to this controller (no cross-file collision risk).
+ writeSortAllowlist(w, entity, sortFields);
+ writeServerOwnedOnCreate(w, entity);
+ ApiSettings api = ApiSettings.of(entity);
+ writeKnownFields(w, api, new ArrayList<>(entity.getMetaFields()));
+ // #484: the credential fields this entity's rows carry, hidden from every response body.
+ List hidden = SpringGeneratorSupport.credentialNames(entity);
+ List navs = SpringM2mSupport.resolve(entity, loader);
+ boolean redacts = !hidden.isEmpty() || navs.stream().anyMatch(n -> !targetCredentials(entity, n).isEmpty());
+
+ // Repository wiring — constructor injection (Spring's recommended idiom; avoids
+ // field-injection magic, plays well with final fields + final test seams). The
+ // ObjectMapper (Spring's configured bean) binds the FR-035 patch body's per-field
+ // values via Patch.fromJson, so the same wire codecs apply as on create.
+ // FR-036: the injected jakarta Validator runs the DTO's field constraints over HTTP
+ // (POST validates the whole DTO; PATCH validates each present value) so a constraint
+ // violation returns the cross-port {"error":"validation"} envelope, not Spring's default.
+ writeWritableConstructor(w, controllerName, repoName);
+ writeUnreadableBodyHandler(w);
+ if (redacts) writeRedactHelpers(w);
+
+ // GET (list) — pagination + sort + withCount + FR-009 filter operators.
+ writeListHandler(w, shortName, dtoName, repoName, hidden, api.pagination());
+ // GET /{id} — single by primary key.
+ writeGetByIdHandler(w, pkType, hidden);
+ writeCreateHandler(w, entity, dtoName, repoName, api, hidden);
+ writeUpdateHandler(w, entity, shortName, dtoName, pkType, api, hidden);
+ writeDeleteHandler(w, pkType);
+ for (SpringM2mSupport.M2mNav nav : navs) writeM2mHandler(w, entity, nav, pkType);
+ writeParseSortHelper(w, repoName);
+ }
+ writeControllerFile(outRoot, pkg, controllerName, w, "{file} for entity " + entity.getName());
+ }
+
+ /**
+ * The three injected fields and the constructor of a writable controller: the repository,
+ * the ObjectMapper (binds each present PATCH value) and the jakarta Validator.
+ */
+ protected void writeWritableConstructor(SpringJavaWriter w, String controllerName, String repoName) {
+ w.line("private final " + repoName + " repository;");
+ w.line("private final ObjectMapper objectMapper;");
+ w.line("private final Validator validator;");
+ w.blank();
+ try (CodeWriter.Block b = w.block(
+ "public " + controllerName + "(" + repoName + " repository, ObjectMapper objectMapper, Validator validator) {")) {
+ w.text("""
+ this.repository = repository;
+ this.objectMapper = objectMapper;
+ this.validator = validator;
+ """);
+ }
+ w.blank();
+ }
+
+ /**
+ * POST — create. FR-036: bind the raw DTO (no @Valid, whose default 400 body is NOT the
+ * cross-port envelope and does not even fire under the standaloneSetup test harness) and
+ * validate it EXPLICITLY with the injected Validator, emitting {"error":"validation"} on
+ * any field-constraint violation BEFORE persisting.
+ */
+ protected void writeCreateHandler(SpringJavaWriter w, MetaObject entity, String dtoName, String repoName,
+ ApiSettings api, List hidden) {
+ w.line("@PostMapping");
// A create body that omits a field with a literal @default binds @default, as every
// other port's create shape does. The DTO is a record, which cannot default a component,
// so the handler binds the raw body, fills the absent defaulted fields, and then binds the
@@ -358,143 +466,140 @@ protected void emit(MetaObject entity, Path outRoot) {
// api.unknownFields = reject (the default) binds the raw body too: the undeclared keys are
// read off the JSON itself, so the answer does not depend on how the host's ObjectMapper
// treats an unknown property.
- if (defaultPuts.isEmpty() && !api.rejectsUnknownFields()) {
- src.append(" public ResponseEntity> create(@RequestBody ").append(dtoName).append(" dto) {\n");
- } else {
- src.append(" public ResponseEntity> create(@RequestBody JsonNode body) {\n");
- appendFillDefaults(src, dtoName, defaultPuts, api.rejectsUnknownFields());
- }
- // #484: a @formExclude / credential value is IGNORED (never rejected): the DTO is rebuilt
- // without it, so the column is left to the repository's default.
- // Also dropped (never rejected): a server-generated primary key, a readOnly field and a derived
- // field, none of which a client may set on create.
- appendStripWriteDenied(src, dtoName, components, createDeniedNames(entity, components));
- // A caller does not supply server-owned columns, so a @NotNull on one must not reject
- // the request. The DTO is BOTH the request and the response body, so `id` carries
- // @NotNull because it is @required in the RESPONSE — while being identity.primary
- // @generation:uuid, i.e. a column the database defaults and the caller must not invent.
- // Validating the whole DTO therefore made every POST a 400 for any entity whose PK is
- // @required, and the only "workaround" was a client-invented primary key.
- //
- // The TPH create path has always applied this rule, through
- // SpringGeneratorSupport.settableFields ("the PK is auto-generated and the discriminator is
- // injected from the URL, so neither is validated from the body") — which is why a TPH
- // entity POSTed fine while a vanilla one did not. This is the vanilla path adopting the
- // same rule, so the two write surfaces finally agree.
- //
- // validator.validate(dto) is KEPT rather than narrowed to per-property validateValue:
- // it is what cascades @Valid into nested value objects. The violations are FILTERED,
- // and only by TOP-LEVEL property name — a nested path like "labels[0].code" can never
- // match, so cascaded constraints still reject.
- // Every violation is listed (never just the first): the issues are collected, then answered once.
- if (serverOwnedOnCreate(entity).isEmpty()) {
- src.append(" ValidationIssues __issues = new ValidationIssues().addViolations(validator.validate(dto));\n");
- } else {
- src.append(" ValidationIssues __issues = new ValidationIssues()\n");
- src.append(" .addViolationsExcept(validator.validate(dto), SERVER_OWNED_ON_CREATE);\n");
- }
- src.append(" if (!__issues.isEmpty()) {\n");
- src.append(" return ResponseEntity.badRequest().body(__issues.body());\n");
- src.append(" }\n");
- // Issue #203: honor @autoSet — stamp EVERY onCreate AND onUpdate column with now() before
- // persisting (the caller's value is ignored; a fresh row's updated_at equals its created_at).
- // The stamp is a static helper on the DTO record; entities with no @autoSet field call
- // repository.create(dto) verbatim (byte-identical to the pre-#203 handler).
- String createArg = SpringGeneratorSupport.hasAutoSetFields(entity)
- ? dtoName + ".stampForInsert(dto)" : "dto";
- src.append(" try {\n");
- src.append(" ").append(dtoName).append(" saved = repository.create(").append(createArg).append(");\n");
- src.append(" return ResponseEntity.status(HttpStatus.CREATED).body(")
- .append(redactOne("saved", hidden)).append(");\n");
- appendConstraintCatch(src);
- src.append(" }\n\n");
-
- // PATCH + PUT — single handler (per API contract; same body shape both verbs).
- // Both verbs MUST be expressed on one @RequestMapping with method={PATCH, PUT}.
- // Stacking @PatchMapping + @PutMapping on the same method does NOT register both
- // in Spring MVC — only one composed @RequestMapping per method is honored, so the
- // other verb 405s. (Surfaced by the SP-F generated-controller HTTP lane.)
- // FR-035 present-key PATCH: bind the RAW JsonNode (not the @Valid full DTO, which
- // conflates absent with null and 400s an omitted @required field), build the
- // presence-tracked Patch, and delegate to repository.patch. An explicit
- // null clears a nullable column; an explicit null on a @required field throws
- // PatchValidationException → 400 {"error":"validation"}. update(id, dto) stays on
- // the interface for programmatic full-DTO use.
- String patchName = SpringNaming.patchName(shortName);
- src.append(" @RequestMapping(value = \"/{id}\", method = { RequestMethod.PATCH, RequestMethod.PUT })\n");
- src.append(" public ResponseEntity> update(@PathVariable ").append(pkType)
- .append(" id, @RequestBody JsonNode body) {\n");
- appendUnknownFieldsGuard(src, api);
- appendPatchBinding(src, patchName, dtoName);
- // Program D (spec section 0): validateValue does NOT cascade @Valid into a nested value
- // object's own constraints, so validate each PRESENT VO element EXPLICITLY. The property's
- // OWN constraints (@NotNull on a @required column, present-null tristate) are already
- // covered above / in Patch.fromJson; this closes the nested-constraint gap (e.g. a
- // Marker.label over @maxLength, or null on a @required nested member) with a 400.
- appendValueObjectValidation(src, entity);
- appendPatchVerdict(src);
- // Issue #203: honor @autoSet onUpdate — bump every onUpdate column to now() on EVERY partial
- // update (the model value is ignored; the server owns the timestamp), injected AFTER the
- // caller's present values are validated and BEFORE delegating so a PATCH that omits the
- // timestamp still bumps it. onCreate columns are never touched here (created_at is immutable).
- if (SpringGeneratorSupport.hasOnUpdateFields(entity)) {
- src.append(" patch.stampAutoSetOnUpdate();\n");
- }
- src.append(" try {\n");
- src.append(" return repository.patch(id, patch)\n");
- src.append(" .>map(").append(okMapper(hidden)).append(")\n");
- src.append(" .orElseGet(() -> ResponseEntity.status(HttpStatus.NOT_FOUND).body(Map.of(\"error\", \"not_found\")));\n");
- appendConstraintCatch(src);
- src.append(" }\n\n");
-
- // DELETE — 204 on success, 404 envelope on miss.
- src.append(" @DeleteMapping(\"/{id}\")\n");
- src.append(" public ResponseEntity> delete(@PathVariable ").append(pkType).append(" id) {\n");
- src.append(" try {\n");
- src.append(" if (repository.delete(id)) {\n");
- src.append(" return ResponseEntity.noContent().build();\n");
- src.append(" }\n");
- src.append(" return ResponseEntity.status(HttpStatus.NOT_FOUND).body(Map.of(\"error\", \"not_found\"));\n");
- appendConstraintCatch(src);
- src.append(" }\n\n");
-
- // FR-018 M:N traversal — GET /{id}/ exposes each
- // @cardinality:"many" + @through relationship as a sub-resource of the source,
- // returning the related target rows. The source URL segment is the entity name
- // pluralized (handled by @RequestMapping above); the relation segment is the
- // relationship name. Related-row order is not contractual. The repository finder
- // traverses the junction (hetero / directed self-join / symmetric union-on-read).
- for (SpringM2mSupport.M2mNav nav : navs) {
- String finder = SpringGeneratorSupport.m2mFinderName(nav.relationName());
- String navCall = "repository." + finder + "(id" + SpringGeneratorSupport.targetSubtypeCallArg(nav) + ")";
- src.append(" @GetMapping(\"/{id}/").append(nav.relationName()).append("\")\n");
- if (targetCredentials(entity, nav).isEmpty()) {
- src.append(" public ResponseEntity> ")
- .append(finder).append("(@PathVariable ").append(pkType).append(" id) {\n");
- src.append(" return ResponseEntity.ok(").append(navCall).append(");\n");
+ boolean bindsRaw = !defaultPuts.isEmpty() || api.rejectsUnknownFields();
+ String head = bindsRaw
+ ? "public ResponseEntity> create(@RequestBody JsonNode body) {"
+ : "public ResponseEntity> create(@RequestBody " + dtoName + " dto) {";
+ try (CodeWriter.Block m = w.block(head)) {
+ if (bindsRaw) writeFillDefaults(w, dtoName, defaultPuts, api.rejectsUnknownFields());
+ // #484: a @formExclude / credential value is IGNORED (never rejected): the DTO is rebuilt
+ // without it, so the column is left to the repository's default.
+ // Also dropped (never rejected): a server-generated primary key, a readOnly field and a derived
+ // field, none of which a client may set on create.
+ writeStripWriteDenied(w, dtoName, components, createDeniedNames(entity, components));
+ // A caller does not supply server-owned columns, so a @NotNull on one must not reject
+ // the request. The DTO is BOTH the request and the response body, so `id` carries
+ // @NotNull because it is @required in the RESPONSE — while being identity.primary
+ // @generation:uuid, i.e. a column the database defaults and the caller must not invent.
+ // Validating the whole DTO therefore made every POST a 400 for any entity whose PK is
+ // @required, and the only "workaround" was a client-invented primary key.
+ //
+ // The TPH create path has always applied this rule, through
+ // SpringGeneratorSupport.settableFields ("the PK is auto-generated and the discriminator is
+ // injected from the URL, so neither is validated from the body") — which is why a TPH
+ // entity POSTed fine while a vanilla one did not. This is the vanilla path adopting the
+ // same rule, so the two write surfaces finally agree.
+ //
+ // validator.validate(dto) is KEPT rather than narrowed to per-property validateValue:
+ // it is what cascades @Valid into nested value objects. The violations are FILTERED,
+ // and only by TOP-LEVEL property name — a nested path like "labels[0].code" can never
+ // match, so cascaded constraints still reject.
+ // Every violation is listed (never just the first): the issues are collected, then answered once.
+ if (serverOwnedOnCreate(entity).isEmpty()) {
+ w.line("ValidationIssues __issues = new ValidationIssues().addViolations(validator.validate(dto));");
} else {
- src.append(" public ResponseEntity> ")
- .append(finder).append("(@PathVariable ").append(pkType).append(" id) {\n");
- src.append(" return ResponseEntity.ok(")
- .append(redactAll(navCall, targetCredentials(entity, nav))).append(");\n");
+ w.text("""
+ ValidationIssues __issues = new ValidationIssues()
+ .addViolationsExcept(validator.validate(dto), SERVER_OWNED_ON_CREATE);
+ """);
+ }
+ writeIssuesVerdict(w);
+ // Issue #203: honor @autoSet — stamp EVERY onCreate AND onUpdate column with now() before
+ // persisting (the caller's value is ignored; a fresh row's updated_at equals its created_at).
+ // The stamp is a static helper on the DTO record; entities with no @autoSet field call
+ // repository.create(dto) verbatim (byte-identical to the pre-#203 handler).
+ String createArg = SpringGeneratorSupport.hasAutoSetFields(entity)
+ ? dtoName + ".stampForInsert(dto)" : "dto";
+ try (CodeWriter.Block t = w.block("try {", CATCH_RUNTIME)) {
+ w.line(dtoName + " saved = repository.create(" + createArg + ");");
+ w.line("return ResponseEntity.status(HttpStatus.CREATED).body(" + redactOne("saved", hidden) + ");");
}
- src.append(" }\n\n");
+ writeConstraintCatch(w);
}
+ w.blank();
+ }
- // parseSort — returns null on malformed/disallowed input. Returning null lets the
- // list handler emit the 400 envelope itself rather than throwing — cleaner
- // separation. The DEFAULT_PK_FIELD constant below is referenced from the per-entity
- // controller so this helper is package-internal to each generated file.
- appendParseSortHelper(src, repoName);
- src.append("}\n");
+ /**
+ * PATCH + PUT — single handler (per API contract; same body shape both verbs).
+ * Both verbs MUST be expressed on one @RequestMapping with method={PATCH, PUT}.
+ * Stacking @PatchMapping + @PutMapping on the same method does NOT register both
+ * in Spring MVC — only one composed @RequestMapping per method is honored, so the
+ * other verb 405s. (Surfaced by the SP-F generated-controller HTTP lane.)
+ * FR-035 present-key PATCH: bind the RAW JsonNode (not the @Valid full DTO, which
+ * conflates absent with null and 400s an omitted @required field), build the
+ * presence-tracked Patch, and delegate to repository.patch. An explicit
+ * null clears a nullable column; an explicit null on a @required field throws
+ * PatchValidationException → 400 {"error":"validation"}. update(id, dto) stays on
+ * the interface for programmatic full-DTO use.
+ */
+ protected void writeUpdateHandler(SpringJavaWriter w, MetaObject entity, String shortName, String dtoName,
+ String pkType, ApiSettings api, List hidden) {
+ String patchName = SpringNaming.patchName(shortName);
+ w.line("@RequestMapping(value = \"/{id}\", method = { RequestMethod.PATCH, RequestMethod.PUT })");
+ try (CodeWriter.Block m = w.block(
+ "public ResponseEntity> update(@PathVariable " + pkType + " id, @RequestBody JsonNode body) {")) {
+ writeUnknownFieldsGuard(w, api);
+ writePatchBinding(w, patchName, dtoName);
+ // Program D (spec section 0): validateValue does NOT cascade @Valid into a nested value
+ // object's own constraints, so validate each PRESENT VO element EXPLICITLY. The property's
+ // OWN constraints (@NotNull on a @required column, present-null tristate) are already
+ // covered above / in Patch.fromJson; this closes the nested-constraint gap (e.g. a
+ // Marker.label over @maxLength, or null on a @required nested member) with a 400.
+ writeValueObjectValidation(w, entity);
+ writePatchVerdict(w);
+ // Issue #203: honor @autoSet onUpdate — bump every onUpdate column to now() on EVERY partial
+ // update (the model value is ignored; the server owns the timestamp), injected AFTER the
+ // caller's present values are validated and BEFORE delegating so a PATCH that omits the
+ // timestamp still bumps it. onCreate columns are never touched here (created_at is immutable).
+ if (SpringGeneratorSupport.hasOnUpdateFields(entity)) {
+ w.line("patch.stampAutoSetOnUpdate();");
+ }
+ try (CodeWriter.Block t = w.block("try {", CATCH_RUNTIME)) {
+ w.line("return repository.patch(id, patch)");
+ w.continuation(".>map(" + okMapper(hidden) + ")");
+ w.continuation(".orElseGet(() -> " + NOT_FOUND_RESPONSE + ");");
+ }
+ writeConstraintCatch(w);
+ }
+ w.blank();
+ }
- try {
- Path outFile = outRoot.resolve(pkg.replace('.', '/')).resolve(controllerName + ".java");
- GeneratedFileWriter.write(outFile, src.toString());
- } catch (IOException e) {
- throw new GeneratorException(
- "failed writing " + controllerName + ".java for entity " + entity.getName() + ": " + e, e);
+ /** DELETE — 204 on success, 404 envelope on miss. */
+ protected void writeDeleteHandler(SpringJavaWriter w, String pkType) {
+ w.line("@DeleteMapping(\"/{id}\")");
+ try (CodeWriter.Block m = w.block("public ResponseEntity> delete(@PathVariable " + pkType + " id) {")) {
+ try (CodeWriter.Block t = w.block("try {", CATCH_RUNTIME)) {
+ w.text("""
+ if (repository.delete(id)) {
+ return ResponseEntity.noContent().build();
+ }
+ """);
+ w.line("return " + NOT_FOUND_RESPONSE + ";");
+ }
+ writeConstraintCatch(w);
}
+ w.blank();
+ }
+
+ /**
+ * FR-018 M:N traversal — GET /{id}/ exposes each
+ * @cardinality:"many" + @through relationship as a sub-resource of the source,
+ * returning the related target rows. The source URL segment is the entity name
+ * pluralized (handled by @RequestMapping above); the relation segment is the
+ * relationship name. Related-row order is not contractual. The repository finder
+ * traverses the junction (hetero / directed self-join / symmetric union-on-read).
+ */
+ protected void writeM2mHandler(SpringJavaWriter w, MetaObject source, SpringM2mSupport.M2mNav nav, String pkType) {
+ String finder = SpringGeneratorSupport.m2mFinderName(nav.relationName());
+ String navCall = "repository." + finder + "(id" + SpringGeneratorSupport.targetSubtypeCallArg(nav) + ")";
+ List targetHidden = targetCredentials(source, nav);
+ w.line("@GetMapping(\"/{id}/" + nav.relationName() + "\")");
+ String rowType = targetHidden.isEmpty() ? nav.targetDtoType() : "Object";
+ try (CodeWriter.Block m = w.block("public ResponseEntity> "
+ + finder + "(@PathVariable " + pkType + " id) {")) {
+ w.line("return ResponseEntity.ok(" + redactAll(navCall, targetHidden) + ");");
+ }
+ w.blank();
}
/**
@@ -505,52 +610,61 @@ protected void emit(MetaObject entity, Path outRoot) {
* on ABSENT fields; {@code validateValue} skips null for {@code @Size}/{@code @Pattern} and a
* non-required field carries no {@code @NotNull}, so a present-null-clears composes cleanly.
* Leaves {@code __assigned} (the bound values) and {@code __patch} (null after a bind failure)
- * for {@link #appendPatchVerdict}.
+ * for {@link #writePatchVerdict}.
*/
- private static void appendPatchBinding(StringBuilder src, String patchName, String dtoName) {
- src.append(" ValidationIssues __issues = new ValidationIssues();\n");
- src.append(" ").append(patchName).append(" __patch = null;\n");
- src.append(" Map __assigned;\n");
- src.append(" try {\n");
- src.append(" __patch = ").append(patchName).append(".fromJson(body, objectMapper);\n");
- src.append(" __assigned = __patch.assignedValues();\n");
- src.append(" } catch (PatchValidationException e) {\n");
- src.append(" __issues.addPatchFailure(e);\n");
- src.append(" __assigned = e.assignedValues();\n");
- src.append(" }\n");
- src.append(" for (Map.Entry __e : __assigned.entrySet()) {\n");
- src.append(" __issues.addAt(validator.validateValue(").append(dtoName)
- .append(".class, RecordComponentNames.escape(__e.getKey()), __e.getValue()), __e.getKey());\n");
- src.append(" }\n");
+ protected void writePatchBinding(SpringJavaWriter w, String patchName, String dtoName) {
+ w.line("ValidationIssues __issues = new ValidationIssues();");
+ w.line(patchName + " __patch = null;");
+ w.line("Map __assigned;");
+ try (CodeWriter.Block t = w.block("try {", "} catch (PatchValidationException e) {")) {
+ w.line("__patch = " + patchName + ".fromJson(body, objectMapper);");
+ w.line("__assigned = __patch.assignedValues();");
+ }
+ try (CodeWriter.Block c = w.bodyBlock()) {
+ w.text("""
+ __issues.addPatchFailure(e);
+ __assigned = e.assignedValues();
+ """);
+ }
+ try (CodeWriter.Block f = w.block("for (Map.Entry __e : __assigned.entrySet()) {")) {
+ w.line("__issues.addAt(validator.validateValue(" + dtoName
+ + ".class, RecordComponentNames.escape(__e.getKey()), __e.getValue()), __e.getKey());");
+ }
}
/** The end of the PATCH validation: answer every collected issue at once, else expose {@code patch}. */
- private static void appendPatchVerdict(StringBuilder src) {
- src.append(" if (!__issues.isEmpty()) {\n");
- src.append(" return ResponseEntity.badRequest().body(__issues.body());\n");
- src.append(" }\n");
- src.append(" final var patch = __patch;\n");
+ protected void writePatchVerdict(SpringJavaWriter w) {
+ writeIssuesVerdict(w);
+ w.line("final var patch = __patch;");
+ }
+
+ /** Answer the collected {@code __issues} with a 400 when there are any. */
+ protected void writeIssuesVerdict(SpringJavaWriter w) {
+ w.text("""
+ if (!__issues.isEmpty()) {
+ return ResponseEntity.badRequest().body(__issues.body());
+ }
+ """);
}
/**
- * Program D — append per-value-object nested-validation guards into a PATCH handler, one per
+ * Program D — per-value-object nested-validation guards in a PATCH handler, one per
* {@code field.object @storage:jsonb} column (spec section 0), reading the BOUND values from
* {@code __assigned}. A present single VO value is validated whole; a present array is validated
* element-by-element. Skips null (present-null clears / is caught upstream) so the tristate
* composes. Every violation is collected into {@code __issues}, its path the field's wire name
- * then the element index or key then the member. Emits nothing for an entity with no
+ * then the element index or key then the member. Writes nothing for an entity with no
* value-object columns, keeping non-VO controllers byte-identical.
*/
- private static void appendValueObjectValidation(StringBuilder src, MetaObject entity) {
+ protected void writeValueObjectValidation(SpringJavaWriter w, MetaObject entity) {
for (ObjectField vf : SpringGeneratorSupport.valueObjectJsonbFields(entity)) {
String name = SpringGeneratorSupport.escapeJavaString(vf.getName());
if (vf.isArrayType()) {
- appendAssignedElementLoop(src, name);
+ writeAssignedElementLoop(w, name);
} else {
- src.append(" if (__assigned.get(\"").append(name).append("\") != null) {\n");
- src.append(" __issues.addViolations(validator.validate(__assigned.get(\"").append(name)
- .append("\")), \"").append(name).append("\");\n");
- src.append(" }\n");
+ try (CodeWriter.Block b = w.block("if (__assigned.get(\"" + name + "\") != null) {")) {
+ w.line("__issues.addViolations(validator.validate(__assigned.get(\"" + name + "\")), \"" + name + "\");");
+ }
}
}
// A field.map @objectRef carries the same nested value objects, and the POST path
@@ -558,36 +672,35 @@ private static void appendValueObjectValidation(StringBuilder src, MetaObject en
// with validateValue, which does NOT cascade — so without this the two write paths
// disagree for maps where they agree for field.object, and a PATCH could write a
// nested value object POST rejects. The map's VALUES are the beans (keys are strings).
- appendValueObjectMapValidation(src, entity);
+ writeValueObjectMapValidation(w, entity);
}
- /** The map-of-value-object part of {@link #appendValueObjectValidation}, for a TPH subtype's PATCH. */
- private static void appendValueObjectMapValidation(StringBuilder src, MetaObject entity) {
+ /** The map-of-value-object part of {@link #writeValueObjectValidation}, for a TPH subtype's PATCH. */
+ protected void writeValueObjectMapValidation(SpringJavaWriter w, MetaObject entity) {
for (MetaField vf : SpringGeneratorSupport.valueObjectMapFields(entity)) {
- appendAssignedMapLoop(src, SpringGeneratorSupport.escapeJavaString(vf.getName()));
+ writeAssignedMapLoop(w, SpringGeneratorSupport.escapeJavaString(vf.getName()));
}
}
/** The element-wise validation of a present array-of-value-object {@code __assigned} entry. */
- private static void appendAssignedElementLoop(StringBuilder src, String name) {
- src.append(" if (__assigned.get(\"").append(name).append("\") instanceof java.util.Collection> __c) {\n");
- src.append(" int __i = 0;\n");
- src.append(" for (Object __el : __c) {\n");
- src.append(" if (__el != null) __issues.addViolations(validator.validate(__el), \"")
- .append(name).append("\", __i);\n");
- src.append(" __i++;\n");
- src.append(" }\n");
- src.append(" }\n");
+ protected void writeAssignedElementLoop(SpringJavaWriter w, String name) {
+ try (CodeWriter.Block b = w.block("if (__assigned.get(\"" + name + "\") instanceof java.util.Collection> __c) {")) {
+ w.line("int __i = 0;");
+ try (CodeWriter.Block f = w.block("for (Object __el : __c) {")) {
+ w.line("if (__el != null) __issues.addViolations(validator.validate(__el), \"" + name + "\", __i);");
+ w.line("__i++;");
+ }
+ }
}
/** The value-wise validation of a present map-of-value-object {@code __assigned} entry. */
- private static void appendAssignedMapLoop(StringBuilder src, String name) {
- src.append(" if (__assigned.get(\"").append(name).append("\") instanceof Map, ?> __m) {\n");
- src.append(" for (Map.Entry, ?> __en : __m.entrySet()) {\n");
- src.append(" if (__en.getValue() != null) __issues.addViolations(validator.validate(__en.getValue()), \"")
- .append(name).append("\", String.valueOf(__en.getKey()));\n");
- src.append(" }\n");
- src.append(" }\n");
+ protected void writeAssignedMapLoop(SpringJavaWriter w, String name) {
+ try (CodeWriter.Block b = w.block("if (__assigned.get(\"" + name + "\") instanceof Map, ?> __m) {")) {
+ try (CodeWriter.Block f = w.block("for (Map.Entry, ?> __en : __m.entrySet()) {")) {
+ w.line("if (__en.getValue() != null) __issues.addViolations(validator.validate(__en.getValue()), \""
+ + name + "\", String.valueOf(__en.getKey()));");
+ }
+ }
}
/**
@@ -601,15 +714,18 @@ private static void appendAssignedMapLoop(StringBuilder src, String name) {
* {@code @Valid} into the map's values — so a posted
* {@code {"labels": {"k": {...invalid...}}}} was accepted and written.
*/
- private static void appendMapValueValidationLoop(StringBuilder src, String accessorExpr, String wireName) {
- src.append(" if (").append(accessorExpr).append(" != null) {\n");
- src.append(" for (var __en : ").append(accessorExpr).append(".entrySet()) {\n");
- src.append(" if (__en.getValue() != null) __issues.addViolations(validator.validate(__en.getValue()), \"")
- .append(SpringGeneratorSupport.escapeJavaString(wireName)).append("\", String.valueOf(__en.getKey()));\n");
- src.append(" }\n");
- src.append(" }\n");
+ protected void writeMapValueValidationLoop(SpringJavaWriter w, String accessorExpr, String wireName) {
+ try (CodeWriter.Block b = w.block("if (" + accessorExpr + " != null) {")) {
+ try (CodeWriter.Block f = w.block("for (var __en : " + accessorExpr + ".entrySet()) {")) {
+ w.line("if (__en.getValue() != null) __issues.addViolations(validator.validate(__en.getValue()), \""
+ + SpringGeneratorSupport.escapeJavaString(wireName) + "\", String.valueOf(__en.getKey()));");
+ }
+ }
}
+ // -----------------------------------------------------------------------
+ // The READ-ONLY controller.
+ // -----------------------------------------------------------------------
/**
* F22 — emit the READ-ONLY {@code @RestController} for a view-only
@@ -632,7 +748,7 @@ private static void appendMapValueValidationLoop(StringBuilder src, String acces
* and constraint-error classification — every one of which is meaningless here, and
* threading a flag through all of them is how a read-only surface drifts into carrying
* write machinery it can never run. What the two genuinely share (the list + get
- * handlers, the sort allowlist, parseSort) they share by calling the same emitters.
+ * handlers, the sort allowlist, parseSort) they share by calling the same writers.
*
*
The item verbs follow the item GET. A projection's identity is OPTIONAL
* (ADR-0028), and a keyless one mounts no {@code /{id}} read — so it refuses only the
@@ -656,139 +772,118 @@ protected void emitReadOnly(MetaObject entity, Path outRoot) {
String routeBase = SpringNaming.controllerPath(entity);
boolean hasItem = RestSurfaceGate.hasItemRoute(entity);
String pkType = SpringTypeMapper.primaryKeyJavaType(entity);
+ boolean report = com.metaobjects.generator.util.GeneratorUtil.isReport(entity);
List sortFields = sortableFields(entity);
- StringBuilder src = new StringBuilder();
- if (!pkg.isEmpty()) {
- src.append("package ").append(pkg).append(";\n\n");
- }
- src.append("import org.springframework.http.HttpStatus;\n");
- src.append("import org.springframework.http.ResponseEntity;\n");
- src.append("import org.springframework.web.bind.annotation.GetMapping;\n");
- if (hasItem) {
- src.append("import org.springframework.web.bind.annotation.PathVariable;\n");
- }
- src.append("import org.springframework.web.bind.annotation.PostMapping;\n");
- src.append("import org.springframework.web.bind.annotation.RequestMapping;\n");
- if (hasItem) {
- src.append("import org.springframework.web.bind.annotation.RequestMethod;\n");
- }
- src.append("import org.springframework.web.bind.annotation.RequestParam;\n");
- src.append("import org.springframework.web.bind.annotation.RestController;\n");
- src.append("import ").append(runtimePackage).append(".FilterParseResult;\n");
- src.append("import ").append(runtimePackage).append(".FilterParser;\n");
- src.append("import ").append(runtimePackage).append(".FilterPredicate;\n");
- if (reportExport && com.metaobjects.generator.util.GeneratorUtil.isReport(entity)) {
- src.append("import ").append(runtimePackage).append(".ReportExport;\n");
- src.append("import org.springframework.http.MediaType;\n");
- }
- src.append("import jakarta.servlet.http.HttpServletRequest;\n");
- src.append("import java.util.List;\n");
- src.append("import java.util.Map;\n");
- src.append("import java.util.Set;\n\n");
-
- src.append("/**\n");
- src.append(" * GENERATED — READ-ONLY REST controller for the ").append(shortName)
- .append(" ").append(noun).append(".\n");
- if (!com.metaobjects.generator.util.GeneratorUtil.isReport(entity)) {
- src.append(" * Implements the cross-port API contract: GET list + GET by id; every write\n");
- src.append(" * verb answers 405 {\"error\": \"method_not_allowed\"}.\n");
+ SpringJavaWriter w = newWriter(pkg);
+ useReadOnlyImports(w, entity, hasItem);
+ List doc = new ArrayList<>();
+ doc.add("GENERATED — READ-ONLY REST controller for the " + shortName + " " + noun + ".");
+ if (!report) {
+ doc.add("Implements the cross-port API contract: GET list + GET by id; every write");
+ doc.add("verb answers 405 {\"error\": \"method_not_allowed\"}.");
} else {
- src.append(" * Implements the cross-port API contract: GET list; POST answers\n");
- src.append(" * 405 {\"error\": \"method_not_allowed\"}. A report has no identity, so no item\n");
- src.append(" * route is mounted.\n");
- }
- src.append(" *\n");
- src.append(" *
Auth: these read endpoints are unauthenticated. Require authentication for this path\n");
- src.append(" * in your Spring Security config, e.g. {@code http.authorizeHttpRequests(a ->\n");
- src.append(" * a.requestMatchers(\"").append(routeBase).append("/**\").authenticated())}.\n");
- src.append(" * A row-ownership rule (\"only the owner may read this row\") can't be expressed in path\n");
- src.append(" * config — eject this generator with {@code mvn metaobjects:eject} and hand-write those\n");
- src.append(" * endpoints.\n");
- src.append(" */\n");
- src.append("@RestController\n");
- src.append("@RequestMapping(\"").append(routeBase).append("\")\n");
- src.append("public class ").append(controllerName).append(" {\n\n");
-
- appendSortAllowlist(src, entity, sortFields);
-
- // Repository wiring — constructor injection, the read-only seam only. No
- // ObjectMapper and no Validator: nothing here binds a request body, so injecting
- // either would make a consumer wire beans this controller can never use.
- // #484: a projection field that inherits a credential (view.password) is hidden from its
- // rows. Redaction needs the ObjectMapper, so it is injected ONLY then; otherwise the
- // constructor and the whole controller stay as they were.
- // A served report is covered too: a derived column over a credential is a credential.
- List hidden = SpringGeneratorSupport.credentialNames(entity);
- src.append(" private final ").append(repoName).append(" repository;\n");
- if (hidden.isEmpty()) {
- src.append("\n");
- src.append(" public ").append(controllerName).append("(").append(repoName)
- .append(" repository) {\n");
- } else {
- src.append(" private final com.fasterxml.jackson.databind.ObjectMapper objectMapper;\n\n");
- src.append(" public ").append(controllerName).append("(").append(repoName)
- .append(" repository, com.fasterxml.jackson.databind.ObjectMapper objectMapper) {\n");
- src.append(" this.objectMapper = objectMapper;\n");
+ doc.add("Implements the cross-port API contract: GET list; POST answers");
+ doc.add("405 {\"error\": \"method_not_allowed\"}. A report has no identity, so no item");
+ doc.add("route is mounted.");
+ }
+ doc.add("");
+ doc.addAll(authDoc(routeBase, true));
+ try (CodeWriter.Block cls = openControllerClass(w, doc, routeBase, controllerName)) {
+ writeSortAllowlist(w, entity, sortFields);
+
+ // #484: a projection field that inherits a credential (view.password) is hidden from its
+ // rows. A served report is covered too: a derived column over a credential is a credential.
+ List hidden = SpringGeneratorSupport.credentialNames(entity);
+ writeReadOnlyConstructor(w, controllerName, repoName, !hidden.isEmpty());
+ if (!hidden.isEmpty()) writeRedactHelpers(w);
+
+ if (report) {
+ writeReportListHandler(w, shortName, dtoName, repoName, reportMaxRows, reportExport, routeBase, hidden);
+ } else {
+ writeListHandler(w, shortName, dtoName, repoName, hidden, ApiSettings.of(entity).pagination());
+ }
+ if (hasItem) {
+ writeGetByIdHandler(w, pkType, hidden);
+ }
+ writeRejectWrites(w, hasItem, pkType);
+ writeMethodNotAllowed(w, noun);
+ writeParseSortHelper(w, repoName);
}
- src.append(" this.repository = repository;\n");
- src.append(" }\n\n");
- if (!hidden.isEmpty()) appendRedactHelpers(src);
+ writeControllerFile(outRoot, pkg, controllerName, w, "{file} for " + noun + " " + entity.getName());
+ }
- if (com.metaobjects.generator.util.GeneratorUtil.isReport(entity)) {
- appendReportListHandler(src, shortName, dtoName, repoName, reportMaxRows, reportExport, routeBase, hidden);
+ /**
+ * Repository wiring of a read-only controller — constructor injection, the read-only seam
+ * only. No ObjectMapper and no Validator: nothing here binds a request body, so injecting
+ * either would make a consumer wire beans this controller can never use. Redaction needs
+ * the ObjectMapper, so it is injected ONLY when a row hides a credential (#484).
+ */
+ protected void writeReadOnlyConstructor(SpringJavaWriter w, String controllerName, String repoName,
+ boolean redacts) {
+ w.line("private final " + repoName + " repository;");
+ if (!redacts) {
+ w.blank();
+ try (CodeWriter.Block b = w.block("public " + controllerName + "(" + repoName + " repository) {")) {
+ w.line("this.repository = repository;");
+ }
} else {
- appendListHandler(src, shortName, dtoName, repoName, hidden, ApiSettings.of(entity).pagination());
- }
- if (hasItem) {
- appendGetByIdHandler(src, pkType, hidden);
+ w.line("private final com.fasterxml.jackson.databind.ObjectMapper objectMapper;");
+ w.blank();
+ try (CodeWriter.Block b = w.block("public " + controllerName + "(" + repoName
+ + " repository, com.fasterxml.jackson.databind.ObjectMapper objectMapper) {")) {
+ w.line("this.objectMapper = objectMapper;");
+ w.line("this.repository = repository;");
+ }
}
+ w.blank();
+ }
- src.append(" @PostMapping\n");
- src.append(" public ResponseEntity> create() {\n");
- src.append(" return methodNotAllowed(\"POST\");\n");
- src.append(" }\n\n");
+ /**
+ * The 405 mappings of a read-only controller: POST on the collection and, when an item route
+ * is mounted, PATCH / PUT / DELETE on the item. One mapping serves all three item verbs: the
+ * bodies are identical and only the verb NAME differs, which the request carries. Stacking
+ * {@code @PatchMapping} + {@code @PutMapping} on one method does NOT register both in Spring
+ * MVC (see {@link #writeUpdateHandler}), so the method= list is the form that works.
+ */
+ protected void writeRejectWrites(SpringJavaWriter w, boolean hasItem, String pkType) {
+ w.text("""
+ @PostMapping
+ public ResponseEntity> create() {
+ return methodNotAllowed("POST");
+ }
+ """);
+ w.blank();
if (hasItem) {
- // One mapping for all three item verbs: the bodies are identical and only the
- // verb NAME differs, which the request carries. Stacking @PatchMapping +
- // @PutMapping on one method does NOT register both in Spring MVC (see emit()),
- // so the method= list is the form that works.
- src.append(" @RequestMapping(value = \"/{id}\", method = { RequestMethod.PATCH, RequestMethod.PUT, RequestMethod.DELETE })\n");
- src.append(" public ResponseEntity> rejectItemWrite(@PathVariable ").append(pkType)
- .append(" id, HttpServletRequest request) {\n");
- src.append(" return methodNotAllowed(request.getMethod());\n");
- src.append(" }\n\n");
- }
- src.append(" private static ResponseEntity> methodNotAllowed(String verb) {\n");
- src.append(" return ResponseEntity.status(HttpStatus.METHOD_NOT_ALLOWED)\n");
- src.append(" .body(Map.of(\"error\", \"method_not_allowed\",\n");
- src.append(" \"message\", verb + \" is not supported on a ").append(noun)
- .append(" (read-only).\"));\n");
- src.append(" }\n\n");
-
- appendParseSortHelper(src, repoName);
- src.append("}\n");
+ w.line("@RequestMapping(value = \"/{id}\", method = { RequestMethod.PATCH, RequestMethod.PUT, RequestMethod.DELETE })");
+ try (CodeWriter.Block m = w.block(
+ "public ResponseEntity> rejectItemWrite(@PathVariable " + pkType + " id, HttpServletRequest request) {")) {
+ w.line("return methodNotAllowed(request.getMethod());");
+ }
+ w.blank();
+ }
+ }
- try {
- Path outFile = outRoot.resolve(pkg.replace('.', '/')).resolve(controllerName + ".java");
- GeneratedFileWriter.write(outFile, src.toString());
- } catch (IOException e) {
- throw new GeneratorException(
- "failed writing " + controllerName + ".java for " + noun + " " + entity.getName() + ": " + e, e);
+ /** The {@code methodNotAllowed} helper the 405 mappings answer through. */
+ protected void writeMethodNotAllowed(SpringJavaWriter w, String noun) {
+ try (CodeWriter.Block m = w.block("private static ResponseEntity> methodNotAllowed(String verb) {")) {
+ w.line("return ResponseEntity.status(HttpStatus.METHOD_NOT_ALLOWED)");
+ w.continuation(".body(Map.of(\"error\", \"method_not_allowed\",");
+ w.deeper(4, () -> w.line("\"message\", verb + \" is not supported on a " + noun + " (read-only).\"));"));
}
+ w.blank();
}
// -----------------------------------------------------------------------
- // Emitters shared by the WRITABLE controller (emit) and the READ-ONLY one
- // (emitReadOnly). Extracted verbatim from emit(), split at exactly the points
- // that keep its output byte-identical: a read-only projection serves the same
- // list + get + sort surface a table entity does, and the F22 change must not be
- // able to reword one of them and not the other.
+ // Writers shared by the WRITABLE controller (emit) and the READ-ONLY one
+ // (emitReadOnly): a read-only projection serves the same list + get + sort
+ // surface a table entity does, and the F22 change must not be able to reword
+ // one of them and not the other.
//
- // emitTph() keeps its own copies. A TPH base's list and get are DISCRIMINATOR-
+ // emitTph() keeps its own handlers. A TPH base's list and get are DISCRIMINATOR-
// scoped and its parseSort names a different repository type, so they are not the
- // same emitter wearing a flag.
+ // same writer wearing a flag.
// -----------------------------------------------------------------------
/**
@@ -801,7 +896,7 @@ protected void emitReadOnly(MetaObject entity, Path outRoot) {
* jsonb column holding a JSON object, so ORDER BY over it sorts by jsonb collation —
* meaningless as an ordering, and a 400 on the ports that reject it.)
*/
- private static List sortableFields(MetaObject entity) {
+ protected static List sortableFields(MetaObject entity) {
List sortFields = new ArrayList<>();
// #484: a served report's credential column is not sortable: ordering by it is an oracle.
List credentials = com.metaobjects.generator.util.GeneratorUtil.isReport(entity)
@@ -818,19 +913,25 @@ private static List sortableFields(MetaObject entity) {
return sortFields;
}
+ /** {@code names} as a comma-separated list of Java string literals. */
+ protected static String quotedList(Collection names) {
+ List out = new ArrayList<>(names.size());
+ for (String n : names) out.add(javaLiteral(n));
+ return String.join(", ", out);
+ }
+
/**
* The static per-controller SORT_ALLOWLIST set plus its SORT_DEFAULT_ORDER map.
* Field-prefixed inner constants keep them private to this controller (no
* cross-file collision risk).
*/
- private static void appendSortAllowlist(StringBuilder src, MetaObject entity, List sortFields) {
- src.append(" private static final Set SORT_ALLOWLIST = Set.of(");
- for (int i = 0; i < sortFields.size(); i++) {
- if (i > 0) src.append(", ");
- src.append('"').append(sortFields.get(i)).append('"');
- }
- src.append(");\n\n");
- appendSortDefaultOrders(src, entity, sortFields);
+ protected void writeSortAllowlist(SpringJavaWriter w, MetaObject owner, List sortFields) {
+ List quoted = new ArrayList<>(sortFields.size());
+ // The sortable names are the model's own and are written unescaped, as they always were.
+ for (String f : sortFields) quoted.add('"' + f + '"');
+ w.line("private static final Set SORT_ALLOWLIST = Set.of(" + String.join(", ", quoted) + ");");
+ w.blank();
+ writeSortDefaultOrders(w, owner, sortFields);
}
/**
@@ -838,13 +939,52 @@ private static void appendSortAllowlist(StringBuilder src, MetaObject entity, Li
* decimal, a wrong JSON type) answers {@code 400 {"error":"validation","field":...}}, the
* cross-port validation envelope, rather than Spring's default body.
*/
- private static void appendUnreadableBodyHandler(StringBuilder src) {
- src.append(" @org.springframework.web.bind.annotation.ExceptionHandler(")
- .append("org.springframework.http.converter.HttpMessageNotReadableException.class)\n");
- src.append(" public ResponseEntity> onUnreadableBody(")
- .append("org.springframework.http.converter.HttpMessageNotReadableException e) {\n");
- src.append(" return ResponseEntity.badRequest().body(UnreadableBody.envelope(e));\n");
- src.append(" }\n\n");
+ protected void writeUnreadableBodyHandler(SpringJavaWriter w) {
+ w.text("""
+ @org.springframework.web.bind.annotation.ExceptionHandler(org.springframework.http.converter.HttpMessageNotReadableException.class)
+ public ResponseEntity> onUnreadableBody(org.springframework.http.converter.HttpMessageNotReadableException e) {
+ return ResponseEntity.badRequest().body(UnreadableBody.envelope(e));
+ }
+ """);
+ w.blank();
+ }
+
+ /** The head of a GET handler whose parameters are one per continuation line; returns its body scope. */
+ protected CodeWriter.Block openHandler(SpringJavaWriter w, String name, List params) {
+ w.line("public ResponseEntity> " + name + "(");
+ for (int i = 0; i < params.size(); i++) {
+ w.continuation(params.get(i) + (i < params.size() - 1 ? "," : ") {"));
+ }
+ return w.bodyBlock();
+ }
+
+ /** The arguments after the query string of a {@code FilterParser.parse} call against {@code allowlist}. */
+ protected static String filterAllowlistArgs(String allowlist) {
+ return allowlist + ".FIELDS, " + allowlist + ".OPS_BY_FIELD, " + allowlist + ".DECIMAL_FIELDS, "
+ + allowlist + ".DURATION_FIELDS";
+ }
+
+ /** {@code ?sort} parsing of a list handler, answering {@code invalid_sort} through {@code badRequest}. */
+ protected void writeSortParse(SpringJavaWriter w, String repoName, String badRequest) {
+ w.line(repoName + ".SortClause sortClause = null;");
+ try (CodeWriter.Block b = w.block("if (sort != null) {")) {
+ w.line("sortClause = parseSort(sort);");
+ // `field` names the rejected sort field — required on every cross-port
+ // invalid_sort envelope. `sort` is non-null in this branch and split()
+ // always yields at least one element, so the index is safe.
+ try (CodeWriter.Block c = w.block("if (sortClause == null) {")) {
+ w.line("return " + badRequest + "Map.of(\"error\", \"invalid_sort\", \"field\", sort.split(\":\", 2)[0]));");
+ }
+ }
+ }
+
+ /** The {@code filter[...]} parse of a list handler, answering its error through {@code badRequest}. */
+ protected void writeFilterParse(SpringJavaWriter w, String allowlist, String badRequest) {
+ w.line("FilterParseResult filter = FilterParser.parse(");
+ w.continuation("request.getQueryString(), " + filterAllowlistArgs(allowlist) + ");");
+ try (CodeWriter.Block b = w.block("if (filter.error() != null) {")) {
+ w.line("return " + badRequest + "Map.of(\"error\", filter.error(), \"field\", filter.field()));");
+ }
}
/**
@@ -853,44 +993,25 @@ private static void appendUnreadableBodyHandler(StringBuilder src) {
* filter[<field>][<op>]=<value> grammar reaches FilterParser intact
* (Spring's {@code @RequestParam} would collapse same-key occurrences).
*/
- private static void appendListHandler(StringBuilder src, String shortName, String dtoName, String repoName,
- List hidden, ApiSettings.Pagination page) {
- String allowlistName = SpringNaming.filterAllowlistName(shortName);
- src.append(" @GetMapping\n");
- src.append(" public ResponseEntity> list(\n");
- src.append(" @RequestParam(required = false) Integer limit,\n");
- src.append(" @RequestParam(required = false) Integer offset,\n");
- src.append(" @RequestParam(required = false) String sort,\n");
- src.append(" @RequestParam(required = false, name = \"withCount\") Integer withCount,\n");
- src.append(" HttpServletRequest request) {\n");
- appendLimit(src, page);
- src.append(" int actualOffset = offset != null ? offset : 0;\n");
- src.append(" ").append(repoName).append(".SortClause sortClause = null;\n");
- src.append(" if (sort != null) {\n");
- src.append(" sortClause = parseSort(sort);\n");
- src.append(" if (sortClause == null) {\n");
- // `field` names the rejected sort field — required on every cross-port
- // invalid_sort envelope. `sort` is non-null in this branch and split()
- // always yields at least one element, so the index is safe.
- src.append(" return ResponseEntity.badRequest().body(Map.of(\"error\", \"invalid_sort\", \"field\", sort.split(\":\", 2)[0]));\n");
- src.append(" }\n");
- src.append(" }\n");
- src.append(" FilterParseResult filter = FilterParser.parse(\n");
- src.append(" request.getQueryString(), ").append(allowlistName).append(".FIELDS, ")
- .append(allowlistName).append(".OPS_BY_FIELD, ").append(allowlistName).append(".DECIMAL_FIELDS, ").append(allowlistName).append(".DURATION_FIELDS);\n");
- src.append(" if (filter.error() != null) {\n");
- src.append(" return ResponseEntity.badRequest().body(Map.of(\"error\", filter.error(), \"field\", filter.field()));\n");
- src.append(" }\n");
- src.append(" List filters = filter.predicates();\n");
- src.append(" List<").append(dtoName)
- .append("> rows = repository.list(actualLimit, actualOffset, sortClause, filters);\n");
- src.append(" if (withCount != null && withCount == 1) {\n");
- src.append(" long total = repository.count(filters);\n");
- src.append(" return ResponseEntity.ok(Map.of(\"rows\", ").append(redactAll("rows", hidden))
- .append(", \"total\", total));\n");
- src.append(" }\n");
- src.append(" return ResponseEntity.ok(").append(redactAll("rows", hidden)).append(");\n");
- src.append(" }\n\n");
+ protected void writeListHandler(SpringJavaWriter w, String shortName, String dtoName, String repoName,
+ List hidden, ApiSettings.Pagination page) {
+ String bad = "ResponseEntity.badRequest().body(";
+ w.line("@GetMapping");
+ try (CodeWriter.Block m = openHandler(w, "list",
+ List.of(PARAM_LIMIT, PARAM_OFFSET, PARAM_SORT, PARAM_WITH_COUNT, PARAM_REQUEST))) {
+ writeLimit(w, page);
+ w.line("int actualOffset = offset != null ? offset : 0;");
+ writeSortParse(w, repoName, bad);
+ writeFilterParse(w, SpringNaming.filterAllowlistName(shortName), bad);
+ w.line("List filters = filter.predicates();");
+ w.line("List<" + dtoName + "> rows = repository.list(actualLimit, actualOffset, sortClause, filters);");
+ try (CodeWriter.Block b = w.block("if (withCount != null && withCount == 1) {")) {
+ w.line("long total = repository.count(filters);");
+ w.line("return ResponseEntity.ok(Map.of(\"rows\", " + redactAll("rows", hidden) + ", \"total\", total));");
+ }
+ w.line("return ResponseEntity.ok(" + redactAll("rows", hidden) + ");");
+ }
+ w.blank();
}
/**
@@ -902,116 +1023,113 @@ private static void appendListHandler(StringBuilder src, String shortName, Strin
* {@code pagination.invalid_value}, the envelope the TypeScript mounts use, instead of being
* ignored or answered by the framework's own conversion error. The bounds arrive as text so
* this handler, not Spring, decides what a bad one answers.
+ *
+ *
With the export branch wired, no answer of the list route consults Accept (the
+ * selector is ?format): every body goes through the {@code badRequest} / {@code ok} helpers,
+ * which carry an explicit application/json that Spring then honours instead of negotiating
+ * against the request's Accept header.
{@code ?sort=field} with no {@code :order} takes the field's DECLARED
+ * {@code @sortableDefaultOrder}. The "asc" fallback stays HERE, at the read, so it is
+ * spelled once per port and SORT_DEFAULT_ORDER carries declarations only.
*/
- private static void appendParseSortHelper(StringBuilder src, String repoName) {
- src.append(" private static ").append(repoName).append(".SortClause parseSort(String raw) {\n");
- src.append(" String[] parts = raw.split(\":\", 2);\n");
- src.append(" if (parts.length == 0 || parts[0].isEmpty() || !SORT_ALLOWLIST.contains(parts[0])) return null;\n");
- // `?sort=field` with no `:order` takes the field's DECLARED @sortableDefaultOrder.
- // The "asc" fallback stays HERE, at the read, so it is spelled once per port and
- // SORT_DEFAULT_ORDER carries declarations only.
- src.append(" String dir = parts.length == 2 ? parts[1].toLowerCase()\n");
- src.append(" : SORT_DEFAULT_ORDER.getOrDefault(parts[0], \"asc\");\n");
- src.append(" if (!dir.equals(\"asc\") && !dir.equals(\"desc\")) return null;\n");
- src.append(" return new ").append(repoName).append(".SortClause(parts[0], dir);\n");
- src.append(" }\n");
+ protected void writeParseSortHelper(SpringJavaWriter w, String repoName) {
+ try (CodeWriter.Block m = w.block("private static " + repoName + ".SortClause parseSort(String raw) {")) {
+ w.text("""
+ String[] parts = raw.split(":", 2);
+ if (parts.length == 0 || parts[0].isEmpty() || !SORT_ALLOWLIST.contains(parts[0])) return null;
+ String dir = parts.length == 2 ? parts[1].toLowerCase()
+ : SORT_DEFAULT_ORDER.getOrDefault(parts[0], "asc");
+ if (!dir.equals("asc") && !dir.equals("desc")) return null;
+ """);
+ w.line("return new " + repoName + ".SortClause(parts[0], dir);");
+ }
+ w.blank();
}
+ // -----------------------------------------------------------------------
+ // The single-table hierarchy (TPH) controller.
+ // -----------------------------------------------------------------------
+
/**
* FR-017 TPH: emit the discriminator-base controller. ONE {@code @RestController} at
* {@code /api/} mounting:
@@ -1167,257 +1273,220 @@ protected void emitTph(MetaObject base, TphPlan.Plan plan, Path outRoot) {
sortFields.add(field.getName());
}
- StringBuilder src = new StringBuilder();
- if (!pkg.isEmpty()) src.append("package ").append(pkg).append(";\n\n");
+ SpringJavaWriter w = newWriter(pkg);
// FR-036 Program B: the per-subtype update handler binds the RAW JsonNode + builds the
// presence-tracked Patch (present-key PATCH tristate), so it needs Jackson + the
// PatchValidationException + the jakarta Validator (present-value constraint checks) —
// exactly the vanilla update handler's dependency set.
- src.append("import com.fasterxml.jackson.databind.JsonNode;\n");
- src.append("import com.fasterxml.jackson.databind.ObjectMapper;\n");
- src.append("import ").append(runtimePackage).append(".ConstraintErrors;\n");
- src.append("import ").append(runtimePackage).append(".PatchValidationException;\n");
- src.append("import ").append(runtimePackage).append(".UnreadableBody;\n");
- src.append("import ").append(runtimePackage).append(".UnknownBodyKeys;\n");
- src.append("import ").append(runtimePackage).append(".ValidationIssues;\n");
- // The escape the PATCH loop applies to each assigned key before naming a Bean
- // Validation property — see RecordComponentNames for why it is needed at run time.
- src.append("import ").append(runtimePackage).append(".RecordComponentNames;\n");
- src.append("import org.springframework.http.HttpStatus;\n");
- src.append("import org.springframework.http.ResponseEntity;\n");
- src.append("import org.springframework.web.bind.annotation.DeleteMapping;\n");
- src.append("import org.springframework.web.bind.annotation.GetMapping;\n");
- src.append("import org.springframework.web.bind.annotation.PathVariable;\n");
- src.append("import org.springframework.web.bind.annotation.PostMapping;\n");
- src.append("import org.springframework.web.bind.annotation.RequestBody;\n");
- src.append("import org.springframework.web.bind.annotation.RequestMapping;\n");
- src.append("import org.springframework.web.bind.annotation.RequestMethod;\n");
- src.append("import org.springframework.web.bind.annotation.RequestParam;\n");
- src.append("import org.springframework.web.bind.annotation.RestController;\n");
- src.append("import ").append(runtimePackage).append(".FilterParseResult;\n");
- src.append("import ").append(runtimePackage).append(".FilterParser;\n");
- src.append("import ").append(runtimePackage).append(".FilterPredicate;\n");
- src.append("import jakarta.servlet.http.HttpServletRequest;\n");
- src.append("import jakarta.validation.Validator;\n");
- src.append("import java.util.List;\n");
- src.append("import java.util.Map;\n");
- src.append("import java.util.Set;\n\n");
-
- src.append("/**\n");
- src.append(" * GENERATED — TPH discriminator-base controller for ").append(shortName)
- .append(" (polymorphic collection + per-subtype CRUD).\n");
- src.append(" * Implements the cross-port API contract.\n");
- src.append(" *\n");
- src.append(" *
Auth: these endpoints are unauthenticated. Require authentication for this path in\n");
- src.append(" * your Spring Security config, e.g. {@code http.authorizeHttpRequests(a ->\n");
- src.append(" * a.requestMatchers(\"").append(routeBase).append("/**\").authenticated())}.\n");
- src.append(" * A row-ownership rule (\"only the owner may read this row\") can't be expressed in path\n");
- src.append(" * config — eject this generator with {@code mvn metaobjects:eject} and hand-write those\n");
- src.append(" * endpoints.\n");
- src.append(" */\n");
- src.append("@RestController\n");
- src.append("@RequestMapping(\"").append(routeBase).append("\")\n");
- src.append("public class ").append(controllerName).append(" {\n\n");
-
- src.append(" private static final Set SORT_ALLOWLIST = Set.of(");
- for (int i = 0; i < sortFields.size(); i++) {
- if (i > 0) src.append(", ");
- src.append('"').append(sortFields.get(i)).append('"');
- }
- src.append(");\n\n");
- // The polymorphic sort surface is the BASE's own columns, so the declared orders
- // are read off the base too — same owner the allowlist above was built from.
- appendSortDefaultOrders(src, base, sortFields);
- // A key declared by the base or by ANY subtype is known on every subtype route: a sibling
- // subtype's column is dropped there (it is not this route's to write), never refused.
- ApiSettings api = ApiSettings.of(base);
- List declared = new ArrayList<>(base.getMetaFields());
- declared.addAll(TphPlan.everySubtypeField(base, loader));
- appendKnownFields(src, api, declared);
-
- // FR-036 Program B: constructor-inject the ObjectMapper (binds each present PATCH value via
- // Patch.fromJson, same wire codecs as create) + the jakarta Validator (per-field
- // present-value constraint checks on the per-subtype update) — same 3-arg shape the vanilla
- // controller uses. The polymorphic + read routes ignore them.
- src.append(" private final ").append(repoName).append(" repository;\n");
- src.append(" private final ObjectMapper objectMapper;\n");
- src.append(" private final Validator validator;\n\n");
- src.append(" public ").append(controllerName).append("(").append(repoName)
- .append(" repository, ObjectMapper objectMapper, Validator validator) {\n");
- src.append(" this.repository = repository;\n");
- src.append(" this.objectMapper = objectMapper;\n");
- src.append(" this.validator = validator;\n");
- src.append(" }\n\n");
- appendUnreadableBodyHandler(src);
- // #484: the TPH rows are union-DTO rows, so hide a credential declared on the base or on
- // ANY subtype from every response, and ignore a write-denied one on every subtype create.
- List unionFields = new ArrayList<>(SpringGeneratorSupport.scalarFields(base));
- for (MetaField f : TphPlan.collectSubtypeFields(base, loader)) {
- if (!(f instanceof com.metaobjects.field.ObjectField)) unionFields.add(f);
- }
- List markFields = new ArrayList<>(unionFields);
- markFields.addAll(TphPlan.everySubtypeField(base, loader));
- List hidden = SpringGeneratorSupport.credentialNames(markFields);
- Set writeDenied = SpringGeneratorSupport.hierarchyWriteDeniedNames(base);
- List baseNavs = SpringM2mSupport.resolve(base, loader);
- boolean redacts = !hidden.isEmpty() || baseNavs.stream().anyMatch(n -> !targetCredentials(base, n).isEmpty())
- || plan.subtypes().stream().anyMatch(st -> SpringM2mSupport.resolve(st.entity(), loader).stream()
- .anyMatch(n -> !targetCredentials(st.entity(), n).isEmpty()));
- if (redacts) appendRedactHelpers(src);
-
- // --- polymorphic collection ---
- src.append(" // Polymorphic list — the union across all subtypes, each row tagged by its discriminator.\n");
- src.append(" @GetMapping\n");
- src.append(" public ResponseEntity> list(\n");
- src.append(" @RequestParam(required = false) Integer limit,\n");
- src.append(" @RequestParam(required = false) Integer offset,\n");
- src.append(" @RequestParam(required = false) String sort,\n");
- src.append(" @RequestParam(required = false, name = \"withCount\") Integer withCount,\n");
- src.append(" HttpServletRequest request) {\n");
- appendLimit(src, api.pagination());
- src.append(" int actualOffset = offset != null ? offset : 0;\n");
- src.append(" ").append(repoName).append(".SortClause sortClause = null;\n");
- src.append(" if (sort != null) {\n");
- src.append(" sortClause = parseSort(sort);\n");
- src.append(" if (sortClause == null) return ResponseEntity.badRequest().body(Map.of(\"error\", \"invalid_sort\", \"field\", sort.split(\":\", 2)[0]));\n");
- src.append(" }\n");
- src.append(" FilterParseResult filter = FilterParser.parse(request.getQueryString(), ")
- .append(allowlistName).append(".FIELDS, ").append(allowlistName).append(".OPS_BY_FIELD, ").append(allowlistName).append(".DECIMAL_FIELDS, ").append(allowlistName).append(".DURATION_FIELDS);\n");
- src.append(" if (filter.error() != null) return ResponseEntity.badRequest().body(Map.of(\"error\", filter.error(), \"field\", filter.field()));\n");
- src.append(" List filters = filter.predicates();\n");
- src.append(" List<").append(dtoName).append("> rows = repository.list(actualLimit, actualOffset, sortClause, filters);\n");
- src.append(" if (withCount != null && withCount == 1) {\n");
- src.append(" return ResponseEntity.ok(Map.of(\"rows\", ").append(redactAll("rows", hidden))
- .append(", \"total\", repository.count(filters)));\n");
- src.append(" }\n");
- src.append(" return ResponseEntity.ok(").append(redactAll("rows", hidden)).append(");\n");
- src.append(" }\n\n");
-
- src.append(" // Polymorphic get — one row of whatever subtype it is.\n");
- src.append(" @GetMapping(\"/{id}\")\n");
- src.append(" public ResponseEntity> get(@PathVariable ").append(pkType).append(" id) {\n");
- src.append(" return repository.findById(id)\n");
- src.append(" .>map(").append(okMapper(hidden)).append(")\n");
- src.append(" .orElseGet(this::notFound);\n");
- src.append(" }\n\n");
-
- // FR-018 x FR-017 — M:N traversal declared on the BASE: every row of the shared
- // table is a legitimate source, so this is the SAME mount + finder shape a vanilla
- // entity gets (see emit() above) — no discriminator gating needed. Per-subtype
- // traversal (including this same relationship, inherited) is emitted below, inside
- // the per-subtype loop — the overlap is deliberate (FR-017 design): a subtype
- // resource carries the same sub-resources as any other resource.
- for (SpringM2mSupport.M2mNav nav : baseNavs) {
- String finder = SpringGeneratorSupport.m2mFinderName(nav.relationName());
- String navCall = "repository." + finder + "(id" + SpringGeneratorSupport.targetSubtypeCallArg(nav) + ")";
- src.append(" @GetMapping(\"/{id}/").append(nav.relationName()).append("\")\n");
- if (targetCredentials(base, nav).isEmpty()) {
- src.append(" public ResponseEntity> ")
- .append(finder).append("(@PathVariable ").append(pkType).append(" id) {\n");
- src.append(" return ResponseEntity.ok(").append(navCall).append(");\n");
- } else {
- src.append(" public ResponseEntity> ")
- .append(finder).append("(@PathVariable ").append(pkType).append(" id) {\n");
- src.append(" return ResponseEntity.ok(")
- .append(redactAll(navCall, targetCredentials(base, nav))).append(");\n");
+ useWritableImports(w);
+ List doc = new ArrayList<>();
+ doc.add("GENERATED — TPH discriminator-base controller for " + shortName
+ + " (polymorphic collection + per-subtype CRUD).");
+ doc.add("Implements the cross-port API contract.");
+ doc.add("");
+ doc.addAll(authDoc(routeBase, false));
+ try (CodeWriter.Block cls = openControllerClass(w, doc, routeBase, controllerName)) {
+ // The polymorphic sort surface is the BASE's own columns, so the declared orders
+ // are read off the base too — same owner the allowlist above was built from.
+ writeSortAllowlist(w, base, sortFields);
+ // A key declared by the base or by ANY subtype is known on every subtype route: a sibling
+ // subtype's column is dropped there (it is not this route's to write), never refused.
+ ApiSettings api = ApiSettings.of(base);
+ List declared = new ArrayList<>(base.getMetaFields());
+ declared.addAll(TphPlan.everySubtypeField(base, loader));
+ writeKnownFields(w, api, declared);
+
+ // FR-036 Program B: constructor-inject the ObjectMapper (binds each present PATCH value via
+ // Patch.fromJson, same wire codecs as create) + the jakarta Validator (per-field
+ // present-value constraint checks on the per-subtype update) — same 3-arg shape the vanilla
+ // controller uses. The polymorphic + read routes ignore them.
+ writeWritableConstructor(w, controllerName, repoName);
+ writeUnreadableBodyHandler(w);
+ // #484: the TPH rows are union-DTO rows, so hide a credential declared on the base or on
+ // ANY subtype from every response, and ignore a write-denied one on every subtype create.
+ List unionFields = new ArrayList<>(SpringGeneratorSupport.scalarFields(base));
+ for (MetaField f : TphPlan.collectSubtypeFields(base, loader)) {
+ if (!(f instanceof com.metaobjects.field.ObjectField)) unionFields.add(f);
}
- src.append(" }\n\n");
- }
-
- // --- per-subtype CRUD ---
- for (TphPlan.Subtype st : plan.subtypes()) {
- String seg = st.routeSegment(); // url segment (e.g. "bridge")
- String disc = st.value(); // discriminator value (e.g. "Bridge")
- String suffix = SpringNaming.capitalize(disc); // method-name suffix (e.g. "Bridge")
- // FR-036 Program B: the per-subtype route binds this subtype's presence-tracked
- // Patch (emitted by SpringDtoGenerator) and validates present values against its
- // standalone annotated Dto. Referenced by FQN so a subtype in another package
- // still resolves without an import.
- String[] stSplit = SpringNaming.splitFqn(st.entity().getName());
- String stPrefix = stSplit[0].isEmpty() ? "" : stSplit[0] + ".";
- String subPatch = stPrefix + SpringNaming.patchName(stSplit[1]);
- String subDto = stPrefix + SpringNaming.dtoName(stSplit[1]);
-
- src.append(" // --- subtype ").append(disc).append(" (segment /").append(seg).append(") ---\n");
-
- // per-subtype list
- src.append(" @GetMapping(\"/").append(seg).append("\")\n");
- src.append(" public ResponseEntity> list").append(suffix).append("(\n");
- src.append(" @RequestParam(required = false) Integer limit,\n");
- src.append(" @RequestParam(required = false) Integer offset,\n");
- src.append(" @RequestParam(required = false) String sort,\n");
- src.append(" HttpServletRequest request) {\n");
- appendLimit(src, api.pagination());
- src.append(" int actualOffset = offset != null ? offset : 0;\n");
- src.append(" ").append(repoName).append(".SortClause sortClause = null;\n");
- src.append(" if (sort != null) {\n");
- src.append(" sortClause = parseSort(sort);\n");
- src.append(" if (sortClause == null) return ResponseEntity.badRequest().body(Map.of(\"error\", \"invalid_sort\", \"field\", sort.split(\":\", 2)[0]));\n");
- src.append(" }\n");
- src.append(" FilterParseResult filter = FilterParser.parse(request.getQueryString(), ")
- .append(allowlistName).append(".FIELDS, ").append(allowlistName).append(".OPS_BY_FIELD, ").append(allowlistName).append(".DECIMAL_FIELDS, ").append(allowlistName).append(".DURATION_FIELDS);\n");
- src.append(" if (filter.error() != null) return ResponseEntity.badRequest().body(Map.of(\"error\", filter.error(), \"field\", filter.field()));\n");
- src.append(" return ResponseEntity.ok(").append(redactAll(
- "repository.listByType(\"" + disc + "\", actualLimit, actualOffset, sortClause, filter.predicates())",
- hidden)).append(");\n");
- src.append(" }\n\n");
-
- // per-subtype get (404 cross-subtype)
- src.append(" @GetMapping(\"/").append(seg).append("/{id}\")\n");
- src.append(" public ResponseEntity> get").append(suffix)
- .append("(@PathVariable ").append(pkType).append(" id) {\n");
- src.append(" return repository.findByIdAndType(id, \"").append(disc).append("\")\n");
- src.append(" .>map(").append(okMapper(hidden)).append(")\n");
- src.append(" .orElseGet(this::notFound);\n");
- src.append(" }\n\n");
-
- // per-subtype create (discriminator injected from URL) — FR-036: validate each body
- // value against the subtype's ANNOTATED Dto constraints BEFORE persisting, emitting
- // the cross-port {"error":"validation"} envelope on any violation (so an over-@maxLength
- // or missing-@required column is a 400, not a silent 201). The bound body stays the union
- // Dto (the shape repository.createWithType consumes), but the union is annotation-
- // free — so validation runs PER FIELD against the subtype DTO (the annotated shape), the
- // exact type the per-subtype PATCH validates against. The validated set is the sibling
- // Patch's settable fields (effective scalars MINUS PK MINUS discriminator): the PK
- // is auto-generated and the discriminator is injected from the URL, so neither is checked.
- // validateValue applies @NotNull to a null value, so an absent @required column 400s too —
- // matching the vanilla create's whole-bean validate, scoped to this subtype.
- String discField = TphPlan.discriminatorFieldOf(st.entity());
- List createValidated = SpringGeneratorSupport.settableFields(st.entity(), discField);
- // The subtype's cross-field rules are class-level @AssertTrue methods on Dto, which
- // the per-property validateValue below never reaches. They are evaluated here against the
- // bound union body instead, the discriminator read as this route's pinned value.
- List> crossFieldRules = SpringGeneratorSupport.crossFieldRules(
- st.entity(), SpringGeneratorSupport.dtoComponentFields(st.entity()),
- f -> f.getName().equals(discField)
- ? "\"" + SpringGeneratorSupport.escapeJavaString(disc) + "\""
- : "dto." + SpringNaming.recordComponentName(f.getName()) + "()");
- if (!crossFieldRules.isEmpty()) src.append(" @SuppressWarnings(\"unchecked\")\n");
- src.append(" @PostMapping(\"/").append(seg).append("\")\n");
- // As the vanilla create — fill the subtype's omitted literal @default fields into
- // the raw body, then bind the union DTO. No such field: the direct binding, byte-identical.
- List subDefaultPuts = createDefaultPuts(st.entity(), SpringGeneratorSupport.dtoComponentFields(st.entity()));
- if (subDefaultPuts.isEmpty() && !api.rejectsUnknownFields()) {
- src.append(" public ResponseEntity> create").append(suffix)
- .append("(@RequestBody ").append(dtoName).append(" dto) {\n");
- } else {
- src.append(" public ResponseEntity> create").append(suffix).append("(@RequestBody JsonNode body) {\n");
- appendFillDefaults(src, dtoName, subDefaultPuts, api.rejectsUnknownFields());
+ List markFields = new ArrayList<>(unionFields);
+ markFields.addAll(TphPlan.everySubtypeField(base, loader));
+ List hidden = SpringGeneratorSupport.credentialNames(markFields);
+ Set writeDenied = SpringGeneratorSupport.hierarchyWriteDeniedNames(base);
+ List baseNavs = SpringM2mSupport.resolve(base, loader);
+ boolean redacts = !hidden.isEmpty() || baseNavs.stream().anyMatch(n -> !targetCredentials(base, n).isEmpty())
+ || plan.subtypes().stream().anyMatch(st -> SpringM2mSupport.resolve(st.entity(), loader).stream()
+ .anyMatch(n -> !targetCredentials(st.entity(), n).isEmpty()));
+ if (redacts) writeRedactHelpers(w);
+
+ writeTphListHandler(w, dtoName, repoName, allowlistName, api, hidden);
+ writeTphGetHandler(w, pkType, hidden);
+ // FR-018 x FR-017 — M:N traversal declared on the BASE: every row of the shared
+ // table is a legitimate source, so this is the SAME mount + finder shape a vanilla
+ // entity gets — no discriminator gating needed. Per-subtype traversal (including this
+ // same relationship, inherited) is written inside the per-subtype set — the overlap is
+ // deliberate (FR-017 design): a subtype resource carries the same sub-resources as any
+ // other resource.
+ for (SpringM2mSupport.M2mNav nav : baseNavs) writeM2mHandler(w, base, nav, pkType);
+
+ for (TphPlan.Subtype st : plan.subtypes()) {
+ writeTphSubtypeHandlers(w, base, st, dtoName, repoName, allowlistName, pkType, api, hidden,
+ unionFields, writeDenied);
+ }
+
+ writeTphNotFound(w);
+ writeParseSortHelper(w, repoName);
+ }
+ writeControllerFile(outRoot, pkg, controllerName, w, "TPH {file} for entity " + base.getName());
+ }
+
+ /** Polymorphic list — the union across all subtypes, each row tagged by its discriminator. */
+ protected void writeTphListHandler(SpringJavaWriter w, String dtoName, String repoName, String allowlistName,
+ ApiSettings api, List hidden) {
+ w.line("// Polymorphic list — the union across all subtypes, each row tagged by its discriminator.");
+ w.line("@GetMapping");
+ try (CodeWriter.Block m = openHandler(w, "list",
+ List.of(PARAM_LIMIT, PARAM_OFFSET, PARAM_SORT, PARAM_WITH_COUNT, PARAM_REQUEST))) {
+ writeTphListHead(w, repoName, allowlistName, api);
+ w.line("List filters = filter.predicates();");
+ w.line("List<" + dtoName + "> rows = repository.list(actualLimit, actualOffset, sortClause, filters);");
+ try (CodeWriter.Block b = w.block("if (withCount != null && withCount == 1) {")) {
+ w.line("return ResponseEntity.ok(Map.of(\"rows\", " + redactAll("rows", hidden)
+ + ", \"total\", repository.count(filters)));");
}
- src.append(" ValidationIssues __issues = new ValidationIssues();\n");
+ w.line("return ResponseEntity.ok(" + redactAll("rows", hidden) + ");");
+ }
+ w.blank();
+ }
+
+ /** The paging, sort and filter parsing a TPH list handler (polymorphic or per subtype) opens with. */
+ protected void writeTphListHead(SpringJavaWriter w, String repoName, String allowlistName, ApiSettings api) {
+ writeLimit(w, api.pagination());
+ w.line("int actualOffset = offset != null ? offset : 0;");
+ w.line(repoName + ".SortClause sortClause = null;");
+ try (CodeWriter.Block b = w.block("if (sort != null) {")) {
+ w.text("""
+ sortClause = parseSort(sort);
+ if (sortClause == null) return ResponseEntity.badRequest().body(Map.of("error", "invalid_sort", "field", sort.split(":", 2)[0]));
+ """);
+ }
+ w.line("FilterParseResult filter = FilterParser.parse(request.getQueryString(), "
+ + filterAllowlistArgs(allowlistName) + ");");
+ w.line("if (filter.error() != null) return ResponseEntity.badRequest().body(Map.of(\"error\", filter.error(), \"field\", filter.field()));");
+ }
+
+ /** Polymorphic get — one row of whatever subtype it is. */
+ protected void writeTphGetHandler(SpringJavaWriter w, String pkType, List hidden) {
+ w.line("// Polymorphic get — one row of whatever subtype it is.");
+ w.line("@GetMapping(\"/{id}\")");
+ try (CodeWriter.Block m = w.block("public ResponseEntity> get(@PathVariable " + pkType + " id) {")) {
+ w.line("return repository.findById(id)");
+ w.continuation(".>map(" + okMapper(hidden) + ")");
+ w.continuation(".orElseGet(this::notFound);");
+ }
+ w.blank();
+ }
+
+ /** The per-subtype CRUD set and M:N traversal of one TPH subtype. */
+ protected void writeTphSubtypeHandlers(SpringJavaWriter w, MetaObject base, TphPlan.Subtype st, String dtoName,
+ String repoName, String allowlistName, String pkType, ApiSettings api,
+ List hidden, List unionFields, Set writeDenied) {
+ String seg = st.routeSegment(); // url segment (e.g. "bridge")
+ String disc = st.value(); // discriminator value (e.g. "Bridge")
+ String suffix = SpringNaming.capitalize(disc); // method-name suffix (e.g. "Bridge")
+ w.line("// --- subtype " + disc + " (segment /" + seg + ") ---");
+ writeTphSubtypeList(w, seg, disc, suffix, repoName, allowlistName, api, hidden);
+ writeTphSubtypeGet(w, seg, disc, suffix, pkType, hidden);
+ writeTphSubtypeCreate(w, base, st, seg, disc, suffix, dtoName, api, hidden, unionFields, writeDenied);
+ writeTphSubtypeUpdate(w, base, st, seg, disc, suffix, pkType, api, hidden);
+ writeTphSubtypeDelete(w, seg, disc, suffix, pkType);
+ // FR-018 x FR-017 — M:N traversal scoped to THIS subtype: every relationship it
+ // resolves, inherited ones (e.g. a base-declared relationship) included.
+ for (SpringM2mSupport.M2mNav nav : SpringM2mSupport.resolve(st.entity(), loader)) {
+ writeTphSubtypeM2mHandler(w, st, seg, disc, nav, pkType);
+ }
+ }
+
+ /** Per-subtype list, scoped by the discriminator. */
+ protected void writeTphSubtypeList(SpringJavaWriter w, String seg, String disc, String suffix, String repoName,
+ String allowlistName, ApiSettings api, List hidden) {
+ w.line("@GetMapping(\"/" + seg + "\")");
+ try (CodeWriter.Block m = openHandler(w, "list" + suffix,
+ List.of(PARAM_LIMIT, PARAM_OFFSET, PARAM_SORT, PARAM_REQUEST))) {
+ writeTphListHead(w, repoName, allowlistName, api);
+ w.line("return ResponseEntity.ok(" + redactAll(
+ "repository.listByType(\"" + disc + "\", actualLimit, actualOffset, sortClause, filter.predicates())",
+ hidden) + ");");
+ }
+ w.blank();
+ }
+
+ /** Per-subtype get (404 cross-subtype). */
+ protected void writeTphSubtypeGet(SpringJavaWriter w, String seg, String disc, String suffix, String pkType,
+ List hidden) {
+ w.line("@GetMapping(\"/" + seg + "/{id}\")");
+ try (CodeWriter.Block m = w.block("public ResponseEntity> get" + suffix + "(@PathVariable " + pkType + " id) {")) {
+ w.line("return repository.findByIdAndType(id, \"" + disc + "\")");
+ w.continuation(".>map(" + okMapper(hidden) + ")");
+ w.continuation(".orElseGet(this::notFound);");
+ }
+ w.blank();
+ }
+
+ /**
+ * Per-subtype create (discriminator injected from URL) — FR-036: validate each body
+ * value against the subtype's ANNOTATED Dto constraints BEFORE persisting, emitting
+ * the cross-port {"error":"validation"} envelope on any violation (so an over-@maxLength
+ * or missing-@required column is a 400, not a silent 201). The bound body stays the union
+ * Dto (the shape repository.createWithType consumes), but the union is annotation-
+ * free — so validation runs PER FIELD against the subtype DTO (the annotated shape), the
+ * exact type the per-subtype PATCH validates against. The validated set is the sibling
+ * Patch's settable fields (effective scalars MINUS PK MINUS discriminator): the PK
+ * is auto-generated and the discriminator is injected from the URL, so neither is checked.
+ * validateValue applies @NotNull to a null value, so an absent @required column 400s too —
+ * matching the vanilla create's whole-bean validate, scoped to this subtype.
+ */
+ protected void writeTphSubtypeCreate(SpringJavaWriter w, MetaObject base, TphPlan.Subtype st, String seg,
+ String disc, String suffix, String dtoName, ApiSettings api,
+ List hidden, List unionFields, Set writeDenied) {
+ // FR-036 Program B: referenced by FQN so a subtype in another package still resolves
+ // without an import.
+ String[] stSplit = SpringNaming.splitFqn(st.entity().getName());
+ String stPrefix = stSplit[0].isEmpty() ? "" : stSplit[0] + ".";
+ String subDto = stPrefix + SpringNaming.dtoName(stSplit[1]);
+ String discField = TphPlan.discriminatorFieldOf(st.entity());
+ List createValidated = SpringGeneratorSupport.settableFields(st.entity(), discField);
+ // The subtype's cross-field rules are class-level @AssertTrue methods on Dto, which
+ // the per-property validateValue below never reaches. They are evaluated here against the
+ // bound union body instead, the discriminator read as this route's pinned value.
+ List> crossFieldRules = SpringGeneratorSupport.crossFieldRules(
+ st.entity(), SpringGeneratorSupport.dtoComponentFields(st.entity()),
+ f -> f.getName().equals(discField)
+ ? "\"" + SpringGeneratorSupport.escapeJavaString(disc) + "\""
+ : "dto." + SpringNaming.recordComponentName(f.getName()) + "()");
+ if (!crossFieldRules.isEmpty()) w.line("@SuppressWarnings(\"unchecked\")");
+ w.line("@PostMapping(\"/" + seg + "\")");
+ // As the vanilla create — fill the subtype's omitted literal @default fields into
+ // the raw body, then bind the union DTO. No such field: the direct binding, byte-identical.
+ List subDefaultPuts = createDefaultPuts(st.entity(), SpringGeneratorSupport.dtoComponentFields(st.entity()));
+ boolean bindsRaw = !subDefaultPuts.isEmpty() || api.rejectsUnknownFields();
+ String head = bindsRaw
+ ? "public ResponseEntity> create" + suffix + "(@RequestBody JsonNode body) {"
+ : "public ResponseEntity> create" + suffix + "(@RequestBody " + dtoName + " dto) {";
+ try (CodeWriter.Block m = w.block(head)) {
+ if (bindsRaw) writeFillDefaults(w, dtoName, subDefaultPuts, api.rejectsUnknownFields());
+ w.line("ValidationIssues __issues = new ValidationIssues();");
for (MetaField vf : createValidated) {
// Both the property STRING and the accessor take the escaped component name:
// Bean Validation resolves a record's property by its COMPONENT, and
// `dto.notify()` would bind to Object.notify().
String vc = SpringNaming.recordComponentName(vf.getName());
- src.append(" __issues.addAt(validator.validateValue(").append(subDto).append(".class, \"")
- .append(vc).append("\", dto.").append(vc).append("()), \"")
- .append(SpringGeneratorSupport.escapeJavaString(vf.getName())).append("\");\n");
+ w.line("__issues.addAt(validator.validateValue(" + subDto + ".class, \"" + vc + "\", dto." + vc
+ + "()), \"" + SpringGeneratorSupport.escapeJavaString(vf.getName()) + "\");");
}
for (Map.Entry rule : crossFieldRules) {
- src.append(" if (!(").append(rule.getValue()).append(")) {\n");
- src.append(" __issues.add(ValidationIssues.CUSTOM, java.util.List.of(), \"a cross-field rule failed\");\n");
- src.append(" }\n");
+ try (CodeWriter.Block b = w.block("if (!(" + rule.getValue() + ")) {")) {
+ w.line("__issues.add(ValidationIssues.CUSTOM, java.util.List.of(), \"a cross-field rule failed\");");
+ }
}
// #362: validateValue above checks each property against the subtype DTO's own
// constraints and stops there — it does NOT cascade @Valid into a nested bean. A
@@ -1426,140 +1495,131 @@ protected void emitTph(MetaObject base, TphPlan.Plan plan, Path outRoot) {
// The vanilla create cascades via @Valid on the DTO component; this is the TPH
// path's equivalent, so the two write surfaces agree.
for (MetaField vf : SpringGeneratorSupport.valueObjectMapFields(st.entity())) {
- appendMapValueValidationLoop(
- src, "dto." + SpringNaming.recordComponentName(vf.getName()) + "()", vf.getName());
+ writeMapValueValidationLoop(
+ w, "dto." + SpringNaming.recordComponentName(vf.getName()) + "()", vf.getName());
}
- src.append(" if (!__issues.isEmpty()) {\n");
- src.append(" return ResponseEntity.badRequest().body(__issues.body());\n");
- src.append(" }\n");
+ writeIssuesVerdict(w);
// ADR-0045 (#203/#229): honor @autoSet on the TPH per-subtype create — stamp EVERY
// onCreate AND onUpdate column with now() before persisting (the caller's value is
- // ignored), mirroring the vanilla create handler's createArg above. The stamp helper
- // is the BASE union Dto's static method (NOT a standalone Dto's): dto above
- // is declared as that same union type (createWithType binds/returns it), so a
- // subtype-typed stampForInsert(SubDto) would not type-check against it.
+ // ignored), mirroring the vanilla create handler. The stamp helper is the BASE union
+ // Dto's static method (NOT a standalone Dto's): dto above is declared as
+ // that same union type (createWithType binds/returns it), so a subtype-typed
+ // stampForInsert(SubDto) would not type-check against it.
//
- // Review fix (Task 3): gate on `base`, NOT `st.entity()`. The helper this emits
- // (Dto.stampForInsert) is only ever generated by
- // SpringDtoGenerator.emitTphUnion when SpringGeneratorSupport.hasAutoSetFields(base) is true
- // (@autoSet columns live on the base, shared by every subtype row in the single
- // table) — gating this call on the subtype's own resolving field set instead let a
- // subtype-declared @autoSet column fire `true` here while the helper it calls was
- // never emitted, producing a non-compiling controller. A TPH subtype declaring its
- // OWN @autoSet column is a documented non-goal (uniform with the Kotlin and Python
- // ports, both base-scoped): the column is simply never stamped, not a compile break.
+ // Gate on `base`, NOT `st.entity()`. The helper this emits (Dto.stampForInsert)
+ // is only ever generated by SpringDtoGenerator.emitTphUnion when
+ // SpringGeneratorSupport.hasAutoSetFields(base) is true (@autoSet columns live on the
+ // base, shared by every subtype row in the single table) — gating on the subtype's own
+ // resolving field set instead let a subtype-declared @autoSet column fire `true` here
+ // while the helper it calls was never emitted, producing a non-compiling controller. A
+ // TPH subtype declaring its OWN @autoSet column is a documented non-goal (uniform with
+ // the Kotlin and Python ports, both base-scoped): the column is simply never stamped.
// #484: ignore (never reject) a @formExclude / credential value in the body.
// Also dropped: the generated key, readOnly/derived columns, the discriminator (the
// route's subtype is its only source) and every column only a SIBLING subtype declares.
- appendStripWriteDenied(src, dtoName, unionFields,
+ writeStripWriteDenied(w, dtoName, unionFields,
tphCreateDeniedNames(st.entity(), unionFields, writeDenied, discField));
String createArg = SpringGeneratorSupport.hasAutoSetFields(base)
? dtoName + ".stampForInsert(dto)" : "dto";
- src.append(" try {\n");
- src.append(" ").append(dtoName).append(" saved = repository.createWithType(\"").append(disc)
- .append("\", ").append(createArg).append(");\n");
- src.append(" return ResponseEntity.status(HttpStatus.CREATED).body(")
- .append(redactOne("saved", hidden)).append(");\n");
- appendConstraintCatch(src);
- src.append(" }\n\n");
-
- // per-subtype update — FR-036 Program B present-key PATCH tristate (mirrors the vanilla
- // update handler; 404 cross-subtype; id + discriminator immutable). Bind the RAW
- // JsonNode (NOT the union DTO, which conflates absent with null and would 400 an omitted
- // @required column), build the presence-tracked Patch (an explicit null clears a
- // nullable column; an explicit null on a @required base column throws
- // PatchValidationException → 400), validate each PRESENT value against the subtype DTO's
- // constraints, then patch scoped to the discriminator.
- src.append(" @RequestMapping(value = \"/").append(seg)
- .append("/{id}\", method = { RequestMethod.PATCH, RequestMethod.PUT })\n");
- src.append(" public ResponseEntity> update").append(suffix)
- .append("(@PathVariable ").append(pkType).append(" id, @RequestBody JsonNode body) {\n");
- appendUnknownFieldsGuard(src, api);
- appendPatchBinding(src, subPatch, subDto);
- appendValueObjectMapValidation(src, st.entity());
- appendPatchVerdict(src);
+ try (CodeWriter.Block t = w.block("try {", CATCH_RUNTIME)) {
+ w.line(dtoName + " saved = repository.createWithType(\"" + disc + "\", " + createArg + ");");
+ w.line("return ResponseEntity.status(HttpStatus.CREATED).body(" + redactOne("saved", hidden) + ");");
+ }
+ writeConstraintCatch(w);
+ }
+ w.blank();
+ }
+
+ /**
+ * Per-subtype update — FR-036 Program B present-key PATCH tristate (mirrors the vanilla
+ * update handler; 404 cross-subtype; id + discriminator immutable). Bind the RAW
+ * JsonNode (NOT the union DTO, which conflates absent with null and would 400 an omitted
+ * @required column), build the presence-tracked Patch (an explicit null clears a
+ * nullable column; an explicit null on a @required base column throws
+ * PatchValidationException → 400), validate each PRESENT value against the subtype DTO's
+ * constraints, then patch scoped to the discriminator.
+ */
+ protected void writeTphSubtypeUpdate(SpringJavaWriter w, MetaObject base, TphPlan.Subtype st, String seg,
+ String disc, String suffix, String pkType, ApiSettings api,
+ List hidden) {
+ String[] stSplit = SpringNaming.splitFqn(st.entity().getName());
+ String stPrefix = stSplit[0].isEmpty() ? "" : stSplit[0] + ".";
+ String subPatch = stPrefix + SpringNaming.patchName(stSplit[1]);
+ String subDto = stPrefix + SpringNaming.dtoName(stSplit[1]);
+ w.line("@RequestMapping(value = \"/" + seg + "/{id}\", method = { RequestMethod.PATCH, RequestMethod.PUT })");
+ try (CodeWriter.Block m = w.block("public ResponseEntity> update" + suffix + "(@PathVariable " + pkType
+ + " id, @RequestBody JsonNode body) {")) {
+ writeUnknownFieldsGuard(w, api);
+ writePatchBinding(w, subPatch, subDto);
+ writeValueObjectMapValidation(w, st.entity());
+ writePatchVerdict(w);
// ADR-0045 (#203/#229): bump every onUpdate @autoSet column on the per-subtype PATCH,
- // mirroring the vanilla update handler above — injected after present-value
- // validation, before delegating, so the timestamp bumps even when the caller omits
- // it. onCreate columns are never touched here (immutable on update).
- //
- // Review fix (Task 3): gate on `base`, matching the create-arg gate above, for the
- // same reason — a subtype-own @autoSet column is a documented non-goal, never
- // stamped, uniform across ports.
+ // mirroring the vanilla update handler — injected after present-value validation,
+ // before delegating, so the timestamp bumps even when the caller omits it. onCreate
+ // columns are never touched here (immutable on update). Gated on `base`, matching the
+ // create-arg gate, for the same reason.
if (SpringGeneratorSupport.hasOnUpdateFields(base)) {
- src.append(" patch.stampAutoSetOnUpdate();\n");
+ w.line("patch.stampAutoSetOnUpdate();");
}
- src.append(" try {\n");
- src.append(" return repository.patchByIdAndType(id, \"").append(disc)
- .append("\", patch.assignedValues())\n");
- src.append(" .>map(").append(okMapper(hidden)).append(")\n");
- src.append(" .orElseGet(this::notFound);\n");
- appendConstraintCatch(src);
- src.append(" }\n\n");
-
- // per-subtype delete (404 cross-subtype)
- src.append(" @DeleteMapping(\"/").append(seg).append("/{id}\")\n");
- src.append(" public ResponseEntity> delete").append(suffix)
- .append("(@PathVariable ").append(pkType).append(" id) {\n");
- src.append(" try {\n");
- src.append(" if (repository.deleteByIdAndType(id, \"").append(disc).append("\")) return ResponseEntity.noContent().build();\n");
- src.append(" return notFound();\n");
- appendConstraintCatch(src);
- src.append(" }\n\n");
-
- // FR-018 x FR-017 — M:N traversal scoped to THIS subtype: every relationship it
- // resolves, inherited ones (e.g. a base-declared relationship) included — a
- // subtype resource carries the same sub-resources as any other. The GENERATED
- // controller enforces the gate itself (never left to the repository
- // implementation): it composes the SAME repository.findByIdAndType(id, disc) lookup
- // the per-subtype GET above already relies on — a sibling subtype's id returns
- // Optional.empty() there (the tph-cross-subtype-404 contract) — and short-circuits
- // to an EMPTY list, HTTP 200, before ever calling the traversal finder. This costs
- // one redundant primary-key lookup and adds no new persistence assumption: it reuses
- // a seam the consumer must already implement correctly for the per-subtype GET to
- // pass conformance. Without it, a copy-paste finder body (e.g. findTagsForBridge
- // implemented identically to findTags) compiles, type-checks, and silently 200s a
- // sibling's rows — nothing else in the pipeline catches that.
- for (SpringM2mSupport.M2mNav nav : SpringM2mSupport.resolve(st.entity(), loader)) {
- String subFinder = SpringGeneratorSupport.m2mFinderNameForSubtype(nav.relationName(), disc);
- src.append(" @GetMapping(\"/").append(seg).append("/{id}/").append(nav.relationName()).append("\")\n");
- boolean navHides = !targetCredentials(st.entity(), nav).isEmpty();
- src.append(" public ResponseEntity> ")
- .append(subFinder).append("(@PathVariable ").append(pkType).append(" id) {\n");
- src.append(" if (repository.findByIdAndType(id, \"").append(disc).append("\").isEmpty()) {\n");
- src.append(" return ResponseEntity.ok(List.of());\n");
- src.append(" }\n");
- src.append(" return ResponseEntity.ok(").append(redactAll(
- "repository." + subFinder + "(id" + SpringGeneratorSupport.targetSubtypeCallArg(nav) + ")",
- targetCredentials(st.entity(), nav))).append(");\n");
- src.append(" }\n\n");
+ try (CodeWriter.Block t = w.block("try {", CATCH_RUNTIME)) {
+ w.line("return repository.patchByIdAndType(id, \"" + disc + "\", patch.assignedValues())");
+ w.continuation(".>map(" + okMapper(hidden) + ")");
+ w.continuation(".orElseGet(this::notFound);");
}
+ writeConstraintCatch(w);
}
+ w.blank();
+ }
- // shared helpers
- src.append(" private ResponseEntity> notFound() {\n");
- src.append(" return ResponseEntity.status(HttpStatus.NOT_FOUND).body(Map.of(\"error\", \"not_found\"));\n");
- src.append(" }\n\n");
- src.append(" private static ").append(repoName).append(".SortClause parseSort(String raw) {\n");
- src.append(" String[] parts = raw.split(\":\", 2);\n");
- src.append(" if (parts.length == 0 || parts[0].isEmpty() || !SORT_ALLOWLIST.contains(parts[0])) return null;\n");
- // `?sort=field` with no `:order` takes the field's DECLARED @sortableDefaultOrder.
- // The "asc" fallback stays HERE, at the read, so it is spelled once per port and
- // SORT_DEFAULT_ORDER carries declarations only.
- src.append(" String dir = parts.length == 2 ? parts[1].toLowerCase()\n");
- src.append(" : SORT_DEFAULT_ORDER.getOrDefault(parts[0], \"asc\");\n");
- src.append(" if (!dir.equals(\"asc\") && !dir.equals(\"desc\")) return null;\n");
- src.append(" return new ").append(repoName).append(".SortClause(parts[0], dir);\n");
- src.append(" }\n");
- src.append("}\n");
+ /** Per-subtype delete (404 cross-subtype). */
+ protected void writeTphSubtypeDelete(SpringJavaWriter w, String seg, String disc, String suffix, String pkType) {
+ w.line("@DeleteMapping(\"/" + seg + "/{id}\")");
+ try (CodeWriter.Block m = w.block("public ResponseEntity> delete" + suffix + "(@PathVariable " + pkType + " id) {")) {
+ try (CodeWriter.Block t = w.block("try {", CATCH_RUNTIME)) {
+ w.line("if (repository.deleteByIdAndType(id, \"" + disc + "\")) return ResponseEntity.noContent().build();");
+ w.line("return notFound();");
+ }
+ writeConstraintCatch(w);
+ }
+ w.blank();
+ }
- try {
- Path outFile = outRoot.resolve(pkg.replace('.', '/')).resolve(controllerName + ".java");
- GeneratedFileWriter.write(outFile, src.toString());
- } catch (IOException e) {
- throw new GeneratorException(
- "failed writing TPH " + controllerName + ".java for entity " + base.getName() + ": " + e, e);
+ /**
+ * FR-018 x FR-017 — M:N traversal scoped to ONE subtype. The GENERATED controller enforces
+ * the gate itself (never left to the repository implementation): it composes the SAME
+ * repository.findByIdAndType(id, disc) lookup the per-subtype GET already relies on — a
+ * sibling subtype's id returns Optional.empty() there (the tph-cross-subtype-404 contract) —
+ * and short-circuits to an EMPTY list, HTTP 200, before ever calling the traversal finder.
+ * This costs one redundant primary-key lookup and adds no new persistence assumption: it
+ * reuses a seam the consumer must already implement correctly for the per-subtype GET to
+ * pass conformance. Without it, a copy-paste finder body (e.g. findTagsForBridge
+ * implemented identically to findTags) compiles, type-checks, and silently 200s a
+ * sibling's rows — nothing else in the pipeline catches that.
+ */
+ protected void writeTphSubtypeM2mHandler(SpringJavaWriter w, TphPlan.Subtype st, String seg, String disc,
+ SpringM2mSupport.M2mNav nav, String pkType) {
+ String subFinder = SpringGeneratorSupport.m2mFinderNameForSubtype(nav.relationName(), disc);
+ List targetHidden = targetCredentials(st.entity(), nav);
+ w.line("@GetMapping(\"/" + seg + "/{id}/" + nav.relationName() + "\")");
+ String rowType = targetHidden.isEmpty() ? nav.targetDtoType() : "Object";
+ try (CodeWriter.Block m = w.block("public ResponseEntity> " + subFinder
+ + "(@PathVariable " + pkType + " id) {")) {
+ try (CodeWriter.Block b = w.block("if (repository.findByIdAndType(id, \"" + disc + "\").isEmpty()) {")) {
+ w.line("return ResponseEntity.ok(List.of());");
+ }
+ w.line("return ResponseEntity.ok(" + redactAll(
+ "repository." + subFinder + "(id" + SpringGeneratorSupport.targetSubtypeCallArg(nav) + ")",
+ targetHidden) + ");");
+ }
+ w.blank();
+ }
+
+ /** The {@code notFound()} helper the TPH handlers answer a miss through. */
+ protected void writeTphNotFound(SpringJavaWriter w) {
+ try (CodeWriter.Block m = w.block("private ResponseEntity> notFound() {")) {
+ w.line("return " + NOT_FOUND_RESPONSE + ";");
}
+ w.blank();
}
// === MultiFileDirectGeneratorBase abstract-method stubs ====================
@@ -1594,7 +1654,7 @@ protected String getSingleOutputFilename(MetaObject md) {
}
/**
- * Emit the per-entity {@code SORT_DEFAULT_ORDER} constant the generated {@code parseSort}
+ * Write the per-entity {@code SORT_DEFAULT_ORDER} constant the generated {@code parseSort}
* reads for a {@code ?sort=field} carrying no {@code :order}.
*
*
Carries DECLARED orders only — a field with no {@code @sortableDefaultOrder} is absent
@@ -1605,7 +1665,7 @@ protected String getSingleOutputFilename(MetaObject md) {
*
ADR-0039: resolving accessor — {@code @sortableDefaultOrder} may be inherited via
* {@code extends}.
*
- *
Emitted as {@code Map.ofEntries(Map.entry(..), ..)}, deliberately NOT {@code Map.of(..)}.
+ *
Written as {@code Map.ofEntries(Map.entry(..), ..)}, deliberately NOT {@code Map.of(..)}.
* {@code Map.of} is a set of fixed-arity overloads topping out at TEN pairs with no varargs
* form — alternating key/value types make one impossible — so an entity whose eleventh field
* declares {@code @sortableDefaultOrder} emits a controller that does not compile
@@ -1616,7 +1676,7 @@ protected String getSingleOutputFilename(MetaObject md) {
* assignment target at zero entries, so the empty case — the common one, since most models
* declare no {@code @sortableDefaultOrder} at all — needs no special branch.
*/
- private static void appendSortDefaultOrders(StringBuilder src, MetaObject owner, List sortFields) {
+ protected void writeSortDefaultOrders(SpringJavaWriter w, MetaObject owner, List sortFields) {
// Walk the owner's OWN field list and keep the sortable ones, rather than looking each
// allowlist name back up. `MetaObject.getMetaField(name)` does not return null for an
// absent name — it THROWS MetaDataNotFoundException — so a name-keyed lookup turns any
@@ -1624,18 +1684,18 @@ private static void appendSortDefaultOrders(StringBuilder src, MetaObject owner,
// a skipped entry. Today both are sourced from this same owner, so nothing diverges;
// this keeps that from being load-bearing. Mirrors the Kotlin sibling's `firstOrNull`.
java.util.Set sortable = new java.util.LinkedHashSet<>(sortFields);
- StringBuilder entries = new StringBuilder();
+ List entries = new ArrayList<>();
for (MetaField f : owner.getMetaFields()) {
String name = f.getName();
if (!sortable.contains(name)) continue;
if (!f.hasMetaAttr(MetaField.ATTR_SORTABLE_DEFAULT_ORDER)) continue;
String v = f.getMetaAttr(MetaField.ATTR_SORTABLE_DEFAULT_ORDER).getValueAsString();
if (!"asc".equals(v) && !"desc".equals(v)) continue;
- if (entries.length() > 0) entries.append(", ");
- entries.append("Map.entry(\"").append(name).append("\", \"").append(v).append("\")");
+ entries.add("Map.entry(\"" + name + "\", \"" + v + "\")");
}
- src.append(" private static final Map SORT_DEFAULT_ORDER = Map.ofEntries(")
- .append(entries).append(");\n\n");
+ w.line("private static final Map SORT_DEFAULT_ORDER = Map.ofEntries("
+ + String.join(", ", entries) + ");");
+ w.blank();
}
/**
@@ -1650,7 +1710,7 @@ private static void appendSortDefaultOrders(StringBuilder src, MetaObject owner,
*
Returned as record-component names, which is what a {@code ConstraintViolation}'s
* property path spells for a record.
*/
- private static List serverOwnedOnCreate(MetaObject entity) {
+ protected static List serverOwnedOnCreate(MetaObject entity) {
List pkFields = entity.getIdentities(true).stream()
.filter(com.metaobjects.identity.MetaIdentity::isPrimary)
.findFirst()
@@ -1686,18 +1746,23 @@ private static List serverOwnedOnCreate(MetaObject entity) {
*
{@code RuntimeException} rather than {@code Exception}: every Spring data-access failure
* is unchecked, and widening it here would force a checked-exception signature onto handlers
* that cannot throw one.
+ *
+ *
The caller opens its {@code try} with {@link #CATCH_RUNTIME} as the block's closing
+ * line, so this writes the body of that {@code catch}.
*/
- private static void appendConstraintCatch(StringBuilder src) {
- src.append(" } catch (RuntimeException e) {\n");
- src.append(" ConstraintErrors.Failure failure = ConstraintErrors.classify(e);\n");
- src.append(" if (failure == null) throw e;\n");
- src.append(" return ResponseEntity.status(failure.status())\n");
- src.append(" .body(Map.of(\"error\", failure.error(), \"constraint\", failure.constraint()));\n");
- src.append(" }\n");
+ protected void writeConstraintCatch(SpringJavaWriter w) {
+ try (CodeWriter.Block c = w.bodyBlock()) {
+ w.text("""
+ ConstraintErrors.Failure failure = ConstraintErrors.classify(e);
+ if (failure == null) throw e;
+ return ResponseEntity.status(failure.status())
+ .body(Map.of("error", failure.error(), "constraint", failure.constraint()));
+ """);
+ }
}
/** The credential wire names of the TARGET of {@code source}'s M:N relationship {@code nav} (#484). */
- private static List targetCredentials(MetaObject source, SpringM2mSupport.M2mNav nav) {
+ protected static List targetCredentials(MetaObject source, SpringM2mSupport.M2mNav nav) {
for (com.metaobjects.relationship.MetaRelationship rel : source.getRelationships()) {
if (!nav.relationName().equals(rel.getShortName())) continue;
MetaObject target = com.metaobjects.loader.References.refTarget(
@@ -1718,7 +1783,7 @@ private static List targetCredentials(MetaObject source, SpringM2mSuppor
* the body. A SQL-expression default is the database's, an array or a temporal default has no
* literal here, and a server-owned or {@code @autoSet} column is never the caller's to send.
*/
- private static List createDefaultPuts(MetaObject entity, List components) {
+ protected static List createDefaultPuts(MetaObject entity, List components) {
List out = new ArrayList<>();
List serverOwned = serverOwnedOnCreate(entity);
for (MetaField f : components) {
@@ -1755,27 +1820,31 @@ private static List createDefaultPuts(MetaObject entity, List
return out;
}
- private static String javaLiteral(String text) {
+ protected static String javaLiteral(String text) {
return "\"" + SpringGeneratorSupport.escapeJavaString(text) + "\"";
}
/** The body of a create handler bound to the raw {@code JsonNode body}: refuse a
* non-object body, fill the absent defaulted fields ({@link #createDefaultPuts}), bind
* {@code dto}. */
- private static void appendFillDefaults(StringBuilder src, String dtoName, List puts, boolean rejectUnknown) {
- src.append(" if (!(body instanceof com.fasterxml.jackson.databind.node.ObjectNode given)) {\n");
- src.append(" return ResponseEntity.badRequest().body(new ValidationIssues()\n");
- src.append(" .add(ValidationIssues.INVALID_TYPE, java.util.List.of(), \"request body must be a JSON object\").body());\n");
- src.append(" }\n");
- if (rejectUnknown) appendUnknownFieldsGuard(src, true);
- src.append(" com.fasterxml.jackson.databind.node.ObjectNode filled = given.deepCopy();\n");
- for (String put : puts) src.append(" ").append(put).append("\n");
- src.append(" ").append(dtoName).append(" dto;\n");
- src.append(" try {\n");
- src.append(" dto = objectMapper.treeToValue(filled, ").append(dtoName).append(".class);\n");
- src.append(" } catch (com.fasterxml.jackson.core.JsonProcessingException | IllegalArgumentException e) {\n");
- src.append(" return ResponseEntity.badRequest().body(UnreadableBody.envelope(e));\n");
- src.append(" }\n");
+ protected void writeFillDefaults(SpringJavaWriter w, String dtoName, List puts, boolean rejectUnknown) {
+ w.text("""
+ if (!(body instanceof com.fasterxml.jackson.databind.node.ObjectNode given)) {
+ return ResponseEntity.badRequest().body(new ValidationIssues()
+ .add(ValidationIssues.INVALID_TYPE, java.util.List.of(), "request body must be a JSON object").body());
+ }
+ """);
+ if (rejectUnknown) writeUnknownFieldsGuard(w, true);
+ w.line("com.fasterxml.jackson.databind.node.ObjectNode filled = given.deepCopy();");
+ for (String put : puts) w.line(put);
+ w.line(dtoName + " dto;");
+ try (CodeWriter.Block t = w.block("try {",
+ "} catch (com.fasterxml.jackson.core.JsonProcessingException | IllegalArgumentException e) {")) {
+ w.line("dto = objectMapper.treeToValue(filled, " + dtoName + ".class);");
+ }
+ try (CodeWriter.Block c = w.bodyBlock()) {
+ w.line("return ResponseEntity.badRequest().body(UnreadableBody.envelope(e));");
+ }
}
/**
@@ -1783,35 +1852,32 @@ private static void appendFillDefaults(StringBuilder src, String dtoName, List declared) {
+ protected void writeKnownFields(SpringJavaWriter w, ApiSettings api, List declared) {
if (!api.rejectsUnknownFields()) return;
Set names = new java.util.LinkedHashSet<>();
for (MetaField f : declared) names.add(f.getName());
- src.append(" /** Every field the entity declares, as named on the wire: a body key outside it is refused. */\n");
- src.append(" private static final Set KNOWN_FIELDS = Set.of(");
- int i = 0;
- for (String n : names) {
- if (i++ > 0) src.append(", ");
- src.append(javaLiteral(n));
- }
- src.append(");\n\n");
+ w.doc("Every field the entity declares, as named on the wire: a body key outside it is refused.");
+ w.line("private static final Set KNOWN_FIELDS = Set.of(" + quotedList(names) + ");");
+ w.blank();
}
- /** The unknown-key check at the head of a PUT/PATCH handler (see {@link #appendUnknownFieldsGuard(StringBuilder, boolean)}). */
- private static void appendUnknownFieldsGuard(StringBuilder src, ApiSettings api) {
- if (api.rejectsUnknownFields()) appendUnknownFieldsGuard(src, true);
+ /** The unknown-key check at the head of a PUT/PATCH handler (see {@link #writeUnknownFieldsGuard(SpringJavaWriter, boolean)}). */
+ protected void writeUnknownFieldsGuard(SpringJavaWriter w, ApiSettings api) {
+ if (api.rejectsUnknownFields()) writeUnknownFieldsGuard(w, true);
}
/** Answer {@code 400 unknown_fields} for an undeclared top-level key of {@code body}, checked on the raw JSON before any binding. */
- private static void appendUnknownFieldsGuard(StringBuilder src, boolean enabled) {
+ protected void writeUnknownFieldsGuard(SpringJavaWriter w, boolean enabled) {
if (!enabled) return;
- src.append(" Map __unknown = UnknownBodyKeys.refusal(body, KNOWN_FIELDS);\n");
- src.append(" if (__unknown != null) {\n");
- src.append(" return ResponseEntity.badRequest().body(__unknown);\n");
- src.append(" }\n");
+ w.text("""
+ Map __unknown = UnknownBodyKeys.refusal(body, KNOWN_FIELDS);
+ if (__unknown != null) {
+ return ResponseEntity.badRequest().body(__unknown);
+ }
+ """);
}
/**
@@ -1822,29 +1888,29 @@ private static void appendUnknownFieldsGuard(StringBuilder src, boolean enabled)
* envelope, as the TypeScript routes refuse it, so it never reaches a store that reads
* {@code LIMIT -1} as no limit (SQLite) and steps around the cap.
*/
- private static void appendLimit(StringBuilder src, ApiSettings.Pagination page) {
+ protected void writeLimit(SpringJavaWriter w, ApiSettings.Pagination page) {
if (page == null) {
- src.append(" int actualLimit = limit != null ? limit : 50;\n");
+ w.line("int actualLimit = limit != null ? limit : 50;");
return;
}
- src.append(" if (limit != null && limit < 0) {\n");
- src.append(" return ResponseEntity.badRequest().body(Map.of(\"error\", \"pagination.invalid_value\", \"param\", \"limit\", ")
- .append("\"value\", String.valueOf(limit), \"expected\", \"a non-negative integer (0 or more)\"));\n");
- src.append(" }\n");
- src.append(" if (limit != null && limit > ").append(page.maxLimit()).append(") {\n");
- src.append(" return ResponseEntity.badRequest().body(Map.of(\"error\", \"limit_too_large\", \"maxLimit\", ")
- .append(page.maxLimit()).append("));\n");
- src.append(" }\n");
- src.append(" int actualLimit = limit != null ? limit : ").append(page.defaultLimit()).append(";\n");
+ try (CodeWriter.Block b = w.block("if (limit != null && limit < 0) {")) {
+ w.line("return ResponseEntity.badRequest().body(Map.of(\"error\", \"pagination.invalid_value\", \"param\", \"limit\", "
+ + "\"value\", String.valueOf(limit), \"expected\", \"a non-negative integer (0 or more)\"));");
+ }
+ try (CodeWriter.Block b = w.block("if (limit != null && limit > " + page.maxLimit() + ") {")) {
+ w.line("return ResponseEntity.badRequest().body(Map.of(\"error\", \"limit_too_large\", \"maxLimit\", "
+ + page.maxLimit() + "));");
+ }
+ w.line("int actualLimit = limit != null ? limit : " + page.defaultLimit() + ";");
}
/** A field no client may set on create regardless of the entity's key: readOnly or derived. */
- private static boolean isNonSettableOnCreate(MetaField f) {
+ protected static boolean isNonSettableOnCreate(MetaField f) {
return MetaField.MUTABILITY_READ_ONLY.equals(f.getMutability()) || f.isDerived();
}
/** The names of {@code fields} that are a server-generated primary key of {@code entity}. */
- private static Set generatedPkNames(MetaObject entity) {
+ protected static Set generatedPkNames(MetaObject entity) {
com.metaobjects.identity.PrimaryIdentity pk = entity.getPrimaryIdentity();
if (pk == null || !pk.isAutoGenerated()) return Set.of();
return new java.util.LinkedHashSet<>(pk.getFields());
@@ -1855,7 +1921,7 @@ private static Set generatedPkNames(MetaObject entity) {
* repository: write-denied ({@code @formExclude} / credential), a generated primary key (an
* assigned key is the caller's), {@code readOnly} and derived fields.
*/
- private static Set createDeniedNames(MetaObject entity, List components) {
+ protected static Set createDeniedNames(MetaObject entity, List components) {
Set out = new java.util.LinkedHashSet<>(SpringGeneratorSupport.writeDeniedNames(components));
Set pk = generatedPkNames(entity);
for (MetaField f : components) {
@@ -1869,8 +1935,8 @@ private static Set createDeniedNames(MetaObject entity, List
* {@link #createDeniedNames}, the discriminator, and every column the route's subtype does not
* itself declare (a sibling subtype's, never this route's to write).
*/
- private static Set tphCreateDeniedNames(MetaObject subtype, List union,
- Set writeDenied, String discField) {
+ protected static Set tphCreateDeniedNames(MetaObject subtype, List union,
+ Set writeDenied, String discField) {
Set out = new java.util.LinkedHashSet<>(writeDenied);
Set pk = generatedPkNames(subtype);
java.util.Map own = new java.util.HashMap<>();
@@ -1884,21 +1950,20 @@ private static Set tphCreateDeniedNames(MetaObject subtype, List components,
- Set writeDenied) {
+ /** Rebuild {@code dto} with every write-denied component nulled; nothing when none is denied. */
+ protected void writeStripWriteDenied(SpringJavaWriter w, String dtoName, List components,
+ Set writeDenied) {
if (components.stream().noneMatch(f -> writeDenied.contains(f.getName()))) return;
- src.append(" dto = new ").append(dtoName).append("(");
- for (int i = 0; i < components.size(); i++) {
- MetaField f = components.get(i);
- if (i > 0) src.append(", ");
- src.append(writeDenied.contains(f.getName())
+ List args = new ArrayList<>(components.size());
+ for (MetaField f : components) {
+ args.add(writeDenied.contains(f.getName())
? "null" : "dto." + SpringNaming.recordComponentName(f.getName()) + "()");
}
- src.append(");\n");
+ w.line("dto = new " + dtoName + "(" + String.join(", ", args) + ");");
}
/** Java source for a {@code String...} argument list naming {@code hidden}. */
- private static String hiddenArgs(List hidden) {
+ protected static String hiddenArgs(List hidden) {
StringBuilder b = new StringBuilder();
// The record component's name, which is the member Jackson's contract knows it by.
for (String h : hidden) b.append(", \"").append(SpringNaming.recordComponentName(h)).append('"');
@@ -1906,17 +1971,17 @@ private static String hiddenArgs(List hidden) {
}
/** Expression for one response row with {@code hidden} removed (the row itself when none). */
- private static String redactOne(String expr, List hidden) {
+ protected static String redactOne(String expr, List hidden) {
return hidden.isEmpty() ? expr : "redact(" + expr + hiddenArgs(hidden) + ")";
}
/** Expression for a list of response rows with {@code hidden} removed from each. */
- private static String redactAll(String expr, List hidden) {
+ protected static String redactAll(String expr, List hidden) {
return hidden.isEmpty() ? expr : "redactAll(" + expr + hiddenArgs(hidden) + ")";
}
/** The {@code Optional.map} argument that answers 200 with a row, minus {@code hidden}. */
- private static String okMapper(List hidden) {
+ protected static String okMapper(List hidden) {
return hidden.isEmpty() ? "ResponseEntity::ok" : "r -> ResponseEntity.ok(" + redactOne("r", hidden) + ")";
}
@@ -1934,82 +1999,91 @@ private static String okMapper(List hidden) {
* sent unstripped. As a second line of defence any key that spells a credential ignoring case,
* {@code _} and {@code -} is removed too.
*/
- private static void appendRedactHelpers(StringBuilder src) {
- src.append(" /** #484: the wire keys of each row class's credentials, read once from objectMapper's contract. */\n");
- src.append(" private final java.util.Map, java.util.Set> credentialWireKeys = new java.util.concurrent.ConcurrentHashMap<>();\n\n");
- src.append(" private Object redact(Object row, String... hidden) {\n");
- src.append(" com.fasterxml.jackson.databind.node.ObjectNode node = objectMapper.valueToTree(row);\n");
- src.append(" node.remove(credentialWireKeys.computeIfAbsent(\n");
- src.append(" List.of(row.getClass(), List.of(hidden)), k -> credentialKeysOf(row.getClass(), hidden)));\n");
- src.append(" java.util.Set spelled = new java.util.HashSet<>();\n");
- src.append(" for (String h : hidden) spelled.add(normalizedKey(h));\n");
- src.append(" List stray = new java.util.ArrayList<>();\n");
- src.append(" node.fieldNames().forEachRemaining(k -> { if (spelled.contains(normalizedKey(k))) stray.add(k); });\n");
- src.append(" node.remove(stray);\n");
- src.append(" return node;\n");
- src.append(" }\n\n");
- src.append(" private List redactAll(List> rows, String... hidden) {\n");
- src.append(" List out = new java.util.ArrayList<>(rows.size());\n");
- src.append(" for (Object row : rows) out.add(redact(row, hidden));\n");
- src.append(" return out;\n");
- src.append(" }\n\n");
- src.append(" /**\n");
- src.append(" * The JSON keys objectMapper writes the credential members {@code hidden} of {@code type} under,\n");
- src.append(" * read from its serialization contract so a naming strategy, mixin or @JsonProperty is honoured.\n");
- src.append(" * Throws (the response is refused, never sent unstripped) when the contract cannot be read.\n");
- src.append(" */\n");
- src.append(" private java.util.Set credentialKeysOf(Class> type, String... hidden) {\n");
- src.append(" com.fasterxml.jackson.databind.SerializationConfig config = objectMapper.getSerializationConfig();\n");
- src.append(" com.fasterxml.jackson.databind.BeanDescription desc = config.introspect(objectMapper.constructType(type));\n");
- src.append(" try {\n");
- src.append(" if (!(objectMapper.getSerializerProviderInstance().findValueSerializer(type)\n");
- src.append(" instanceof com.fasterxml.jackson.databind.ser.std.BeanSerializerBase)) {\n");
- src.append(" throw unstrippable(type, hidden, \"its serializer is not a bean serializer (a custom serializer?)\");\n");
- src.append(" }\n");
- src.append(" } catch (com.fasterxml.jackson.databind.JsonMappingException e) {\n");
- src.append(" throw unstrippable(type, hidden, \"the mapper has no serializer for it\");\n");
- src.append(" }\n");
- src.append(" java.util.Set keys = new java.util.HashSet<>();\n");
- src.append(" for (String name : hidden) {\n");
- src.append(" boolean matched = false;\n");
- src.append(" for (com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition p : desc.findProperties()) {\n");
- src.append(" if (p.getInternalName().equals(name)) { keys.add(p.getName()); matched = true; }\n");
- src.append(" }\n");
- src.append(" if (!matched && declaresMember(type, name) && !desc.getIgnoredPropertyNames().contains(name)) {\n");
- src.append(" throw unstrippable(type, new String[] {name}, \"the credential has no property in the mapper's contract\");\n");
- src.append(" }\n");
- src.append(" }\n");
- src.append(" return keys;\n");
- src.append(" }\n\n");
- src.append(" private static boolean declaresMember(Class> type, String name) {\n");
- src.append(" for (Class> c = type; c != null && c != Object.class; c = c.getSuperclass()) {\n");
- src.append(" for (java.lang.reflect.Field f : c.getDeclaredFields()) if (f.getName().equals(name)) return true;\n");
- src.append(" }\n");
- src.append(" return false;\n");
- src.append(" }\n\n");
- src.append(" private static String normalizedKey(String key) {\n");
- src.append(" return key.replace(\"_\", \"\").replace(\"-\", \"\").toLowerCase(java.util.Locale.ROOT);\n");
- src.append(" }\n\n");
- src.append(" private static IllegalStateException unstrippable(Class> type, String[] credentials, String why) {\n");
- src.append(" return new IllegalStateException(\"cannot strip the credential \" + type.getSimpleName() + \".\"\n");
- src.append(" + String.join(\", \" + type.getSimpleName() + \".\", credentials) + \" from a response: \" + why\n");
- src.append(" + \". Credential stripping reads the ObjectMapper's serialization contract; the response is\"\n");
- src.append(" + \" refused rather than sent unstripped.\");\n");
- src.append(" }\n\n");
- }
-
- private static void appendServerOwnedOnCreate(StringBuilder src, MetaObject entity) {
- List serverOwned = serverOwnedOnCreate(entity);
- if (serverOwned.isEmpty()) return; // no constant, and the handler keeps its old shape
- src.append(" /** Components the server owns on create (primary key, @autoSet): a\n");
- src.append(" * @NotNull on one of these describes the RESPONSE shape and must not\n");
- src.append(" * reject a create body that legitimately omits it. */\n");
- src.append(" private static final Set SERVER_OWNED_ON_CREATE = Set.of(");
- for (int i = 0; i < serverOwned.size(); i++) {
- if (i > 0) src.append(", ");
- src.append('"').append(serverOwned.get(i)).append('"');
- }
- src.append(");\n\n");
+ protected void writeRedactHelpers(SpringJavaWriter w) {
+ w.text("""
+ /** #484: the wire keys of each row class's credentials, read once from objectMapper's contract. */
+ private final java.util.Map, java.util.Set> credentialWireKeys = new java.util.concurrent.ConcurrentHashMap<>();
+
+ private Object redact(Object row, String... hidden) {
+ com.fasterxml.jackson.databind.node.ObjectNode node = objectMapper.valueToTree(row);
+ node.remove(credentialWireKeys.computeIfAbsent(
+ List.of(row.getClass(), List.of(hidden)), k -> credentialKeysOf(row.getClass(), hidden)));
+ java.util.Set spelled = new java.util.HashSet<>();
+ for (String h : hidden) spelled.add(normalizedKey(h));
+ List stray = new java.util.ArrayList<>();
+ node.fieldNames().forEachRemaining(k -> { if (spelled.contains(normalizedKey(k))) stray.add(k); });
+ node.remove(stray);
+ return node;
+ }
+
+ private List redactAll(List> rows, String... hidden) {
+ List out = new java.util.ArrayList<>(rows.size());
+ for (Object row : rows) out.add(redact(row, hidden));
+ return out;
+ }
+
+ /**
+ * The JSON keys objectMapper writes the credential members {@code hidden} of {@code type} under,
+ * read from its serialization contract so a naming strategy, mixin or @JsonProperty is honoured.
+ * Throws (the response is refused, never sent unstripped) when the contract cannot be read.
+ */
+ private java.util.Set credentialKeysOf(Class> type, String... hidden) {
+ com.fasterxml.jackson.databind.SerializationConfig config = objectMapper.getSerializationConfig();
+ com.fasterxml.jackson.databind.BeanDescription desc = config.introspect(objectMapper.constructType(type));
+ try {
+ if (!(objectMapper.getSerializerProviderInstance().findValueSerializer(type)
+ instanceof com.fasterxml.jackson.databind.ser.std.BeanSerializerBase)) {
+ throw unstrippable(type, hidden, "its serializer is not a bean serializer (a custom serializer?)");
+ }
+ } catch (com.fasterxml.jackson.databind.JsonMappingException e) {
+ throw unstrippable(type, hidden, "the mapper has no serializer for it");
+ }
+ java.util.Set keys = new java.util.HashSet<>();
+ for (String name : hidden) {
+ boolean matched = false;
+ for (com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition p : desc.findProperties()) {
+ if (p.getInternalName().equals(name)) { keys.add(p.getName()); matched = true; }
+ }
+ if (!matched && declaresMember(type, name) && !desc.getIgnoredPropertyNames().contains(name)) {
+ throw unstrippable(type, new String[] {name}, "the credential has no property in the mapper's contract");
+ }
+ }
+ return keys;
+ }
+
+ private static boolean declaresMember(Class> type, String name) {
+ for (Class> c = type; c != null && c != Object.class; c = c.getSuperclass()) {
+ for (java.lang.reflect.Field f : c.getDeclaredFields()) if (f.getName().equals(name)) return true;
+ }
+ return false;
+ }
+
+ private static String normalizedKey(String key) {
+ return key.replace("_", "").replace("-", "").toLowerCase(java.util.Locale.ROOT);
+ }
+
+ private static IllegalStateException unstrippable(Class> type, String[] credentials, String why) {
+ return new IllegalStateException("cannot strip the credential " + type.getSimpleName() + "."
+ + String.join(", " + type.getSimpleName() + ".", credentials) + " from a response: " + why
+ + ". Credential stripping reads the ObjectMapper's serialization contract; the response is"
+ + " refused rather than sent unstripped.");
+ }
+ """);
+ w.blank();
}
+ /** The {@code SERVER_OWNED_ON_CREATE} constant; nothing, and the create handler keeps its old shape, when none. */
+ protected void writeServerOwnedOnCreate(SpringJavaWriter w, MetaObject entity) {
+ List serverOwned = serverOwnedOnCreate(entity);
+ if (serverOwned.isEmpty()) return;
+ w.text("""
+ /** Components the server owns on create (primary key, @autoSet): a
+ * @NotNull on one of these describes the RESPONSE shape and must not
+ * reject a create body that legitimately omits it. */
+ """);
+ List quoted = new ArrayList<>(serverOwned.size());
+ for (String s : serverOwned) quoted.add('"' + s + '"');
+ w.line("private static final Set SERVER_OWNED_ON_CREATE = Set.of(" + String.join(", ", quoted) + ");");
+ w.blank();
+ }
}
diff --git a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringDtoGenerator.java b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringDtoGenerator.java
index bda50c8518..7c07a22190 100644
--- a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringDtoGenerator.java
+++ b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringDtoGenerator.java
@@ -9,6 +9,7 @@
import com.metaobjects.generator.spring.Fr019SharedEnum;
import com.metaobjects.generator.spring.SpringGeneratorSupport;
import com.metaobjects.generator.spring.SpringNaming;
+import com.metaobjects.generator.spring.SpringJavaWriter;
import com.metaobjects.generator.spring.SpringRecordBuilder;
import com.metaobjects.generator.spring.SpringTypeMapper;
import com.metaobjects.generator.spring.TphPlan;
@@ -22,6 +23,7 @@
import com.metaobjects.field.StringField;
import com.metaobjects.field.UriField;
import com.metaobjects.generator.GeneratorException;
+import com.metaobjects.generator.writer.CodeWriter;
import com.metaobjects.generator.GeneratorIOWriter;
import com.metaobjects.generator.direct.MultiFileDirectGeneratorBase;
import com.metaobjects.generator.util.GeneratorUtil;
@@ -247,14 +249,10 @@ protected void emit(MetaObject entity, Path outRoot) {
// "writable" reading of this flag stays true.
boolean writableForAutoSet = !GeneratorUtil.isReport(entity)
&& (SpringGeneratorSupport.repositoryAppliesTo(entity) || TphPlan.isTphSubtype(entity));
- List extraBodyMembers = new ArrayList<>(
- (writableForAutoSet && SpringGeneratorSupport.hasAutoSetFields(entity))
- ? autoSetStampHelpers(entity, fields, SpringNaming.dtoName(
- SpringNaming.splitFqn(entity.getName())[1]))
- : List.of());
+ boolean stamps = writableForAutoSet && SpringGeneratorSupport.hasAutoSetFields(entity);
// Entity-scoped cross-field validators: class-level @AssertTrue rules on the full DTO only.
- extraBodyMembers.addAll(SpringGeneratorSupport.crossFieldValidationMembers(entity, fields));
- emitRecord(entity, outRoot, fields, annotationsPerField, extraBodyMembers);
+ boolean crossField = !SpringGeneratorSupport.crossFieldRules(entity, fields, f -> "").isEmpty();
+ emitRecord(entity, outRoot, fields, annotationsPerField, stamps, crossField);
}
/**
@@ -308,247 +306,291 @@ private void emitTphSubtypePatch(MetaObject subtype, Path outRoot) {
* TPH {@link #emitTphSubtypePatch} paths funnel through here so the tristate semantics (absent /
* present-null-clears / present-null-on-@required-throws / present-value-binds) cannot drift.
*/
- private void writePatch(MetaObject entity, Path outRoot, String patchName, String dtoName,
+ protected void writePatch(MetaObject entity, Path outRoot, String patchName, String dtoName,
List settable, List onUpdateAutoSet) {
String[] split = SpringNaming.splitFqn(entity.getName());
String pkg = split[0];
String shortName = split[1];
- StringBuilder src = new StringBuilder();
- if (!pkg.isEmpty()) src.append("package ").append(pkg).append(";\n\n");
- src.append("import com.fasterxml.jackson.core.JsonProcessingException;\n");
- src.append("import com.fasterxml.jackson.core.type.TypeReference;\n");
- src.append("import com.fasterxml.jackson.databind.JsonNode;\n");
- src.append("import com.fasterxml.jackson.databind.ObjectMapper;\n");
- src.append("import ").append(runtimePackage).append(".PatchValidationException;\n");
- src.append("import java.util.LinkedHashMap;\n");
- src.append("import java.util.Map;\n");
- src.append("import java.util.Set;\n\n");
- src.append("/** GENERATED — presence-tracked partial-update (PATCH) shape for ")
- .append(shortName).append(". Do not hand-edit; regenerated from metadata. */\n");
- src.append("public final class ").append(patchName).append(" {\n\n");
- src.append(" private final Map assigned;\n\n");
- src.append(" private ").append(patchName)
- .append("(Map assigned) { this.assigned = assigned; }\n\n");
-
- // Per settable field: has() (presence, incl. explicit null) + () (value).
- //
- // The ACCESSOR takes the escaped name; the map KEY keeps the declared one. A Patch is a
- // plain class rather than a record, so javac does not reject an illegal name here — it
- // resolves it against Object. `notify` fails loudly (the Boolean accessor cannot override
- // the final void one), but `toString` compiles CLEANLY and silently overrides
- // Object.toString(), so every log line and debugger view of the patch returns a field
- // value instead. has() needs no escape: capitalisation already clears the collision.
+ SpringJavaWriter w = newWriter(pkg);
+ w.use("com.fasterxml.jackson.core.JsonProcessingException");
+ w.use("com.fasterxml.jackson.core.type.TypeReference");
+ w.use("com.fasterxml.jackson.databind.JsonNode");
+ w.use("com.fasterxml.jackson.databind.ObjectMapper");
+ w.use(runtimePackage + ".PatchValidationException");
+ w.use("java.util.LinkedHashMap");
+ w.use("java.util.Map");
+ w.use("java.util.Set");
+ w.line("/** GENERATED — presence-tracked partial-update (PATCH) shape for " + shortName
+ + ". Do not hand-edit; regenerated from metadata. */");
+ try (CodeWriter.Block cls = w.block("public final class " + patchName + " {")) {
+ w.line("private final Map assigned;");
+ w.blank();
+ w.line("private " + patchName + "(Map assigned) { this.assigned = assigned; }");
+ w.blank();
+ writePatchAccessors(w, entity, dtoName, settable);
+ w.blank();
+ // FR-036: the assigned name→value map (present values, incl. an explicit null), for the
+ // controller to bean-validate each PRESENT non-null value against the DTO's constraints.
+ w.text("""
+ /** The field names ASSIGNED by this patch (present in the body), in order. */
+ public Set assignedFields() { return assigned.keySet(); }
+
+ /** The name→value map of fields ASSIGNED by this patch (present values, incl. explicit null). */
+ public java.util.Map assignedValues() { return java.util.Collections.unmodifiableMap(assigned); }
+ """);
+ w.blank();
+ // Issue #203 — @autoSet onUpdate stamping. The generated controller's PATCH handler calls
+ // this AFTER binding + validating the caller's present values and BEFORE delegating to
+ // repository.patch, so every partial update bumps updated_at (the model value is ignored:
+ // the server owns onUpdate timestamps). now() is keyed off each column's temporal type. Only
+ // emitted for entities that declare an @autoSet onUpdate column.
+ if (!onUpdateAutoSet.isEmpty()) {
+ writeStampAutoSetOnUpdate(w, onUpdateAutoSet);
+ w.blank();
+ }
+ PatchBinders binders = writePatchFromJson(w, entity, patchName, dtoName, settable);
+ w.blank();
+ writePatchBinder(w);
+ if (binders.decimal() || binders.decimalList()) {
+ w.use(runtimePackage + ".CanonicalDecimalDeserializer");
+ w.blank();
+ writePatchDecimalBinder(w);
+ }
+ if (binders.decimalList()) {
+ w.blank();
+ writePatchDecimalListBinder(w);
+ }
+ if (binders.duration() || binders.durationList()) {
+ w.use(runtimePackage + ".CanonicalDurationDeserializer");
+ }
+ if (binders.duration()) {
+ w.blank();
+ writePatchDurationBinder(w);
+ }
+ if (binders.durationList()) {
+ w.blank();
+ writePatchDurationListBinder(w);
+ }
+ }
+ writeJavaFile(entity, outRoot, pkg, patchName, w);
+ }
+
+ /** Which typed binders a patch's {@code fromJson} calls, so only those are written. */
+ protected record PatchBinders(boolean decimal, boolean decimalList, boolean duration, boolean durationList) {}
+
+ /**
+ * Per settable field: {@code has()} (presence, incl. explicit null) and
+ * {@code ()} (value).
+ *
+ *
The ACCESSOR takes the escaped name; the map KEY keeps the declared one. A Patch is a
+ * plain class rather than a record, so javac does not reject an illegal name here — it
+ * resolves it against Object. {@code notify} fails loudly (the Boolean accessor cannot override
+ * the final void one), but {@code toString} compiles CLEANLY and silently overrides
+ * Object.toString(), so every log line and debugger view of the patch returns a field
+ * value instead. has<Cap>() needs no escape: capitalisation already clears the collision.
+ */
+ protected void writePatchAccessors(SpringJavaWriter w, MetaObject entity, String dtoName,
+ List settable) {
for (MetaField field : settable) {
String name = field.getName();
String accessor = SpringNaming.recordComponentName(name);
String cap = SpringNaming.capitalize(name);
String type = patchComponentType(field, entity, dtoName);
- src.append(" public boolean has").append(cap)
- .append("() { return assigned.containsKey(\"").append(name).append("\"); }\n");
- src.append(" public ").append(type).append(' ').append(accessor).append("() { return (")
- .append(type).append(") assigned.get(\"").append(name).append("\"); }\n");
+ w.line("public boolean has" + cap + "() { return assigned.containsKey(\"" + name + "\"); }");
+ w.line("public " + type + " " + accessor + "() { return (" + type + ") assigned.get(\"" + name + "\"); }");
}
- src.append("\n /** The field names ASSIGNED by this patch (present in the body), in order. */\n");
- src.append(" public Set assignedFields() { return assigned.keySet(); }\n\n");
- // FR-036: the assigned name→value map (present values, incl. an explicit null), for the
- // controller to bean-validate each PRESENT non-null value against the DTO's constraints.
- src.append(" /** The name→value map of fields ASSIGNED by this patch (present values, incl. explicit null). */\n");
- src.append(" public java.util.Map assignedValues() { return java.util.Collections.unmodifiableMap(assigned); }\n\n");
-
- // Issue #203 — @autoSet onUpdate stamping. The generated controller's PATCH handler calls
- // this AFTER binding + validating the caller's present values and BEFORE delegating to
- // repository.patch, so every partial update bumps updated_at (the model value is ignored:
- // the server owns onUpdate timestamps). now() is keyed off each column's temporal type. Only
- // emitted for entities that declare an @autoSet onUpdate column.
- if (!onUpdateAutoSet.isEmpty()) {
- src.append(" /** Issue #203 @autoSet: stamp every onUpdate column to now() (server-owned; bumps on every PATCH). */\n");
- src.append(" public void stampAutoSetOnUpdate() {\n");
+ }
+
+ /** Issue #203: the patch's {@code stampAutoSetOnUpdate()}, bumping every onUpdate column to now(). */
+ protected void writeStampAutoSetOnUpdate(SpringJavaWriter w, List onUpdateAutoSet) {
+ w.line("/** Issue #203 @autoSet: stamp every onUpdate column to now() (server-owned; bumps on every PATCH). */");
+ try (CodeWriter.Block m = w.block("public void stampAutoSetOnUpdate() {")) {
for (MetaField field : onUpdateAutoSet) {
- src.append(" assigned.put(\"").append(field.getName()).append("\", ")
- .append(AutoSetSupport.nowExpr(field)).append(");\n");
+ w.line("assigned.put(\"" + field.getName() + "\", " + AutoSetSupport.nowExpr(field) + ");");
}
- src.append(" }\n\n");
}
+ }
- // fromJson — the presence-tracked builder.
- src.append(" /**\n");
- src.append(" * Build from a JSON body. A non-object body is rejected; an ABSENT key is\n");
- src.append(" * untouched; a present null CLEARS a non-@required field and is a validation\n");
- src.append(" * error on a @required one; a present value binds via Jackson exactly as\n");
- src.append(" * create does. Unknown keys are ignored (FR-035 PATCH-3 deferred).\n");
- src.append(" */\n");
- src.append(" public static ").append(patchName)
- .append(" fromJson(JsonNode body, ObjectMapper mapper) {\n");
- src.append(" if (!body.isObject()) throw new PatchValidationException(\"(request body)\");\n");
- src.append(" Map assigned = new LinkedHashMap<>();\n");
- // Every field is bound even after one fails, so the one exception below lists them all.
- src.append(" java.util.List problems = PatchValidationException.newProblems();\n");
- boolean usesDecimalPatch = false;
- boolean usesDecimalListPatch = false;
- boolean usesDurationPatch = false;
- boolean usesDurationListPatch = false;
- for (MetaField field : settable) {
- String name = field.getName();
- String type = patchComponentType(field, entity, dtoName);
- boolean required = SpringGeneratorSupport.isRequired(field);
- // A TypeReference (not a raw Class) so a generic component — e.g. a
- // field. @isArray List — binds with its element type intact.
- if ("java.math.BigDecimal".equals(type)) {
- // ADR-0019 Amendment 1 (W2): a decimal binds through the strict rule, not the
- // mapper's coercion: "" or "NaN" is a 400, a number is read exactly.
- int[] bound = SpringGeneratorSupport.declaredDecimalBound(field);
- src.append(" PatchValidationException.collect(problems, () -> bindDecimal(body, assigned, \"").append(name).append("\", ")
- .append(required).append(", ").append(bound == null ? 0 : bound[0])
- .append(", ").append(bound == null ? 0 : bound[1]).append("));\n");
- usesDecimalPatch = true;
- continue;
- }
- if ("java.util.List".equals(type)) {
- // The same strict rule per element of a decimal array.
- int[] bound = SpringGeneratorSupport.declaredDecimalBound(field);
- src.append(" PatchValidationException.collect(problems, () -> bindDecimalList(body, assigned, \"").append(name).append("\", ")
- .append(required).append(", ").append(bound == null ? 0 : bound[0])
- .append(", ").append(bound == null ? 0 : bound[1]).append("));\n");
- usesDecimalPatch = true;
- usesDecimalListPatch = true;
- continue;
- }
- if (wire.durationsIso()
- && ("java.time.Duration".equals(type) || "java.util.List".equals(type))) {
- // wire.durations: iso. field.duration binds through the strict accepted-form rule, not the mapper's
- // Duration.parse (which takes fractional hours, lowercase and numbers of seconds).
- boolean list = !"java.time.Duration".equals(type);
- src.append(" PatchValidationException.collect(problems, () -> bindDuration").append(list ? "List" : "").append("(body, assigned, \"")
- .append(name).append("\", ").append(required).append("));\n");
- if (list) usesDurationListPatch = true; else usesDurationPatch = true;
- continue;
- }
- src.append(" PatchValidationException.collect(problems, () -> bind(body, mapper, assigned, \"").append(name)
- .append("\", new TypeReference<").append(type).append(">() {}, ")
- .append(required).append("));\n");
- }
- src.append(" if (!problems.isEmpty()) throw new PatchValidationException(problems, assigned);\n");
- src.append(" return new ").append(patchName).append("(assigned);\n");
- src.append(" }\n\n");
-
- // bind — one settable field. treeToValue lets Jackson handle every subtype (no hand-rolled arms).
- src.append(" private static void bind(JsonNode body, ObjectMapper mapper, Map assigned,\n");
- src.append(" String field, TypeReference> type, boolean required) {\n");
- src.append(" if (!body.has(field)) return; // absent → untouched\n");
- src.append(" JsonNode node = body.get(field);\n");
- src.append(" if (node.isNull()) {\n");
- src.append(" if (required) throw new PatchValidationException(field);\n");
- src.append(" assigned.put(field, null); // explicit null → clear\n");
- src.append(" return;\n");
- src.append(" }\n");
- src.append(" try {\n");
- src.append(" assigned.put(field, mapper.treeToValue(node, type));\n");
- src.append(" } catch (JsonProcessingException e) {\n");
- src.append(" throw new PatchValidationException(field, e);\n");
- src.append(" }\n");
- src.append(" }\n");
- if (usesDecimalPatch) {
- // The import line is written before the body; add the one the body now needs.
- String pve = "import " + runtimePackage + ".PatchValidationException;\n";
- int at = src.indexOf(pve);
- src.insert(at, "import " + runtimePackage + ".CanonicalDecimalDeserializer;\n");
- // ADR-0019 Amendment 1 (W2): the strict decimal rule over the tree node.
- src.append("\n private static void bindDecimal(JsonNode body, Map assigned,\n");
- src.append(" String field, boolean required, int precision, int scale) {\n");
- src.append(" if (!body.has(field)) return; // absent → untouched\n");
- src.append(" JsonNode node = body.get(field);\n");
- src.append(" if (node.isNull()) {\n");
- src.append(" if (required) throw new PatchValidationException(field);\n");
- src.append(" assigned.put(field, null); // explicit null → clear\n");
- src.append(" return;\n");
- src.append(" }\n");
- src.append(" try {\n");
- src.append(" // precision 0 declares no @precision: only the engine-wide W3 limits apply\n");
- src.append(" assigned.put(field, precision == 0 ? CanonicalDecimalDeserializer.fromNode(node)\n");
- src.append(" : CanonicalDecimalDeserializer.fromNode(node, precision, scale));\n");
- src.append(" } catch (IllegalArgumentException e) {\n");
- src.append(" throw new PatchValidationException(field, e);\n");
- src.append(" }\n");
- src.append(" }\n");
- if (usesDecimalListPatch) {
- src.append("\n private static void bindDecimalList(JsonNode body, Map assigned,\n");
- src.append(" String field, boolean required, int precision, int scale) {\n");
- src.append(" if (!body.has(field)) return; // absent → untouched\n");
- src.append(" JsonNode node = body.get(field);\n");
- src.append(" if (node.isNull()) {\n");
- src.append(" if (required) throw new PatchValidationException(field);\n");
- src.append(" assigned.put(field, null); // explicit null → clear\n");
- src.append(" return;\n");
- src.append(" }\n");
- src.append(" if (!node.isArray()) throw new PatchValidationException(field);\n");
- src.append(" java.util.List items = new java.util.ArrayList<>();\n");
- src.append(" for (JsonNode item : node) {\n");
- src.append(" if (item.isNull()) throw new PatchValidationException(field);\n");
- src.append(" try {\n");
- src.append(" items.add(precision == 0 ? CanonicalDecimalDeserializer.fromNode(item)\n");
- src.append(" : CanonicalDecimalDeserializer.fromNode(item, precision, scale));\n");
- src.append(" } catch (IllegalArgumentException e) {\n");
- src.append(" throw new PatchValidationException(field, e);\n");
- src.append(" }\n");
- src.append(" }\n");
- src.append(" assigned.put(field, items);\n");
- src.append(" }\n");
+ /** {@code fromJson} — the presence-tracked builder; returns which typed binders it calls. */
+ protected PatchBinders writePatchFromJson(SpringJavaWriter w, MetaObject entity, String patchName,
+ String dtoName, List settable) {
+ boolean decimal = false;
+ boolean decimalList = false;
+ boolean duration = false;
+ boolean durationList = false;
+ w.text("""
+ /**
+ * Build from a JSON body. A non-object body is rejected; an ABSENT key is
+ * untouched; a present null CLEARS a non-@required field and is a validation
+ * error on a @required one; a present value binds via Jackson exactly as
+ * create does. Unknown keys are ignored (FR-035 PATCH-3 deferred).
+ */
+ """);
+ try (CodeWriter.Block m = w.block("public static " + patchName + " fromJson(JsonNode body, ObjectMapper mapper) {")) {
+ w.text("""
+ if (!body.isObject()) throw new PatchValidationException("(request body)");
+ Map assigned = new LinkedHashMap<>();
+ java.util.List problems = PatchValidationException.newProblems();
+ """);
+ // Every field is bound even after one fails, so the one exception below lists them all.
+ for (MetaField field : settable) {
+ String name = field.getName();
+ String type = patchComponentType(field, entity, dtoName);
+ String required = String.valueOf(SpringGeneratorSupport.isRequired(field));
+ String collect = "PatchValidationException.collect(problems, () -> ";
+ // A TypeReference (not a raw Class) so a generic component — e.g. a
+ // field. @isArray List — binds with its element type intact.
+ if ("java.math.BigDecimal".equals(type) || "java.util.List".equals(type)) {
+ // ADR-0019 Amendment 1 (W2): a decimal binds through the strict rule, not the
+ // mapper's coercion: "" or "NaN" is a 400, a number is read exactly. The same
+ // strict rule applies per element of a decimal array.
+ boolean list = !"java.math.BigDecimal".equals(type);
+ int[] bound = SpringGeneratorSupport.declaredDecimalBound(field);
+ w.line(collect + "bindDecimal" + (list ? "List" : "") + "(body, assigned, \"" + name + "\", "
+ + required + ", " + (bound == null ? 0 : bound[0]) + ", " + (bound == null ? 0 : bound[1]) + "));");
+ decimal = true;
+ if (list) decimalList = true;
+ continue;
+ }
+ if (wire.durationsIso()
+ && ("java.time.Duration".equals(type) || "java.util.List".equals(type))) {
+ // wire.durations: iso. field.duration binds through the strict accepted-form rule, not the mapper's
+ // Duration.parse (which takes fractional hours, lowercase and numbers of seconds).
+ boolean list = !"java.time.Duration".equals(type);
+ w.line(collect + "bindDuration" + (list ? "List" : "") + "(body, assigned, \"" + name + "\", "
+ + required + "));");
+ if (list) durationList = true; else duration = true;
+ continue;
+ }
+ w.line(collect + "bind(body, mapper, assigned, \"" + name + "\", new TypeReference<" + type + ">() {}, "
+ + required + "));");
}
+ w.line("if (!problems.isEmpty()) throw new PatchValidationException(problems, assigned);");
+ w.line("return new " + patchName + "(assigned);");
}
- if (usesDurationPatch || usesDurationListPatch) {
- String pve = "import " + runtimePackage + ".PatchValidationException;\n";
- int at = src.indexOf(pve);
- src.insert(at, "import " + runtimePackage + ".CanonicalDurationDeserializer;\n");
- }
- if (usesDurationPatch) {
- src.append("\n private static void bindDuration(JsonNode body, Map assigned,\n");
- src.append(" String field, boolean required) {\n");
- src.append(" if (!body.has(field)) return; // absent → untouched\n");
- src.append(" JsonNode node = body.get(field);\n");
- src.append(" if (node.isNull()) {\n");
- src.append(" if (required) throw new PatchValidationException(field);\n");
- src.append(" assigned.put(field, null); // explicit null → clear\n");
- src.append(" return;\n");
- src.append(" }\n");
- src.append(" try {\n");
- src.append(" assigned.put(field, CanonicalDurationDeserializer.fromNode(node));\n");
- src.append(" } catch (IllegalArgumentException e) {\n");
- src.append(" throw new PatchValidationException(field, e);\n");
- src.append(" }\n");
- src.append(" }\n");
- }
- if (usesDurationListPatch) {
- src.append("\n private static void bindDurationList(JsonNode body, Map assigned,\n");
- src.append(" String field, boolean required) {\n");
- src.append(" if (!body.has(field)) return; // absent → untouched\n");
- src.append(" JsonNode node = body.get(field);\n");
- src.append(" if (node.isNull()) {\n");
- src.append(" if (required) throw new PatchValidationException(field);\n");
- src.append(" assigned.put(field, null); // explicit null → clear\n");
- src.append(" return;\n");
- src.append(" }\n");
- src.append(" if (!node.isArray()) throw new PatchValidationException(field);\n");
- src.append(" java.util.List items = new java.util.ArrayList<>();\n");
- src.append(" for (JsonNode item : node) {\n");
- src.append(" if (item.isNull()) throw new PatchValidationException(field);\n");
- src.append(" try {\n");
- src.append(" items.add(CanonicalDurationDeserializer.fromNode(item));\n");
- src.append(" } catch (IllegalArgumentException e) {\n");
- src.append(" throw new PatchValidationException(field, e);\n");
- src.append(" }\n");
- src.append(" }\n");
- src.append(" assigned.put(field, items);\n");
- src.append(" }\n");
- }
- src.append("}\n");
+ return new PatchBinders(decimal, decimalList, duration, durationList);
+ }
- writeJavaFile(entity, outRoot, pkg, patchName, src.toString());
+ /** {@code bind} — one settable field. treeToValue lets Jackson handle every subtype (no hand-rolled arms). */
+ protected void writePatchBinder(SpringJavaWriter w) {
+ w.text("""
+ private static void bind(JsonNode body, ObjectMapper mapper, Map assigned,
+ String field, TypeReference> type, boolean required) {
+ if (!body.has(field)) return; // absent → untouched
+ JsonNode node = body.get(field);
+ if (node.isNull()) {
+ if (required) throw new PatchValidationException(field);
+ assigned.put(field, null); // explicit null → clear
+ return;
+ }
+ try {
+ assigned.put(field, mapper.treeToValue(node, type));
+ } catch (JsonProcessingException e) {
+ throw new PatchValidationException(field, e);
+ }
+ }
+ """);
}
+ /** ADR-0019 Amendment 1 (W2): the strict decimal rule over the tree node. */
+ protected void writePatchDecimalBinder(SpringJavaWriter w) {
+ w.text("""
+ private static void bindDecimal(JsonNode body, Map assigned,
+ String field, boolean required, int precision, int scale) {
+ if (!body.has(field)) return; // absent → untouched
+ JsonNode node = body.get(field);
+ if (node.isNull()) {
+ if (required) throw new PatchValidationException(field);
+ assigned.put(field, null); // explicit null → clear
+ return;
+ }
+ try {
+ // precision 0 declares no @precision: only the engine-wide W3 limits apply
+ assigned.put(field, precision == 0 ? CanonicalDecimalDeserializer.fromNode(node)
+ : CanonicalDecimalDeserializer.fromNode(node, precision, scale));
+ } catch (IllegalArgumentException e) {
+ throw new PatchValidationException(field, e);
+ }
+ }
+ """);
+ }
+ /** The strict decimal rule per element of a decimal array. */
+ protected void writePatchDecimalListBinder(SpringJavaWriter w) {
+ w.text("""
+ private static void bindDecimalList(JsonNode body, Map assigned,
+ String field, boolean required, int precision, int scale) {
+ if (!body.has(field)) return; // absent → untouched
+ JsonNode node = body.get(field);
+ if (node.isNull()) {
+ if (required) throw new PatchValidationException(field);
+ assigned.put(field, null); // explicit null → clear
+ return;
+ }
+ if (!node.isArray()) throw new PatchValidationException(field);
+ java.util.List items = new java.util.ArrayList<>();
+ for (JsonNode item : node) {
+ if (item.isNull()) throw new PatchValidationException(field);
+ try {
+ items.add(precision == 0 ? CanonicalDecimalDeserializer.fromNode(item)
+ : CanonicalDecimalDeserializer.fromNode(item, precision, scale));
+ } catch (IllegalArgumentException e) {
+ throw new PatchValidationException(field, e);
+ }
+ }
+ assigned.put(field, items);
+ }
+ """);
+ }
+ /** {@code wire.durations: iso}: the strict accepted-form duration rule over the tree node. */
+ protected void writePatchDurationBinder(SpringJavaWriter w) {
+ w.text("""
+ private static void bindDuration(JsonNode body, Map assigned,
+ String field, boolean required) {
+ if (!body.has(field)) return; // absent → untouched
+ JsonNode node = body.get(field);
+ if (node.isNull()) {
+ if (required) throw new PatchValidationException(field);
+ assigned.put(field, null); // explicit null → clear
+ return;
+ }
+ try {
+ assigned.put(field, CanonicalDurationDeserializer.fromNode(node));
+ } catch (IllegalArgumentException e) {
+ throw new PatchValidationException(field, e);
+ }
+ }
+ """);
+ }
+ /** The strict duration rule per element of a duration array. */
+ protected void writePatchDurationListBinder(SpringJavaWriter w) {
+ w.text("""
+ private static void bindDurationList(JsonNode body, Map assigned,
+ String field, boolean required) {
+ if (!body.has(field)) return; // absent → untouched
+ JsonNode node = body.get(field);
+ if (node.isNull()) {
+ if (required) throw new PatchValidationException(field);
+ assigned.put(field, null); // explicit null → clear
+ return;
+ }
+ if (!node.isArray()) throw new PatchValidationException(field);
+ java.util.List items = new java.util.ArrayList<>();
+ for (JsonNode item : node) {
+ if (item.isNull()) throw new PatchValidationException(field);
+ try {
+ items.add(CanonicalDurationDeserializer.fromNode(item));
+ } catch (IllegalArgumentException e) {
+ throw new PatchValidationException(field, e);
+ }
+ }
+ assigned.put(field, items);
+ }
+ """);
+ }
/** The {@code Patch} component type for {@code field}. Identical to the DTO's
* FR-019-aware {@link #componentTypeFr019} EXCEPT for an INLINE {@code field.enum}: its
@@ -589,43 +631,36 @@ protected void emitTphUnion(MetaObject base, MetaDataLoader loader, Path outRoot
// path (SpringGeneratorSupport.hasAutoSetFields(base) — @autoSet columns live on the base, shared
// by every subtype row in the single table): empty for a non-@autoSet hierarchy, so the
// union DTO stays byte-identical.
- List extraBodyMembers =
- (SpringGeneratorSupport.repositoryAppliesTo(base) && SpringGeneratorSupport.hasAutoSetFields(base))
- ? autoSetStampHelpers(base, fields, SpringNaming.dtoName(SpringNaming.splitFqn(base.getName())[1]))
- : List.of();
- emitRecord(base, outRoot, fields, annotationsPerField, extraBodyMembers);
+ boolean stamps = SpringGeneratorSupport.repositoryAppliesTo(base) && SpringGeneratorSupport.hasAutoSetFields(base);
+ emitRecord(base, outRoot, fields, annotationsPerField, stamps, false);
}
/** Shared record emitter: write {@code Dto} record from a field + per-field annotation
- * list, plus {@code extraBodyMembers} (static methods / declarations) appended after the
- * nested-enum declarations in the record body — e.g. the issue #203 @autoSet stamping helpers.
- * Every DTO but a projection's carries the Java builder (#365): a projection's read DTO arrives
- * from a query and nothing should construct it, the line the Kotlin port draws too. An entity
- * cannot have a read-only primary source, so "not a projection" is exactly "constructable". */
- private void emitRecord(MetaObject entity, Path outRoot, List fields,
- List annotationsPerField, List extraBodyMembers) {
+ * list. The record body carries the nested inline enums, then (when {@code stamps}) the
+ * issue #203 @autoSet stamping helpers, then (when {@code crossField}) the class-level
+ * cross-field validators, then the Java builder (#365) — on every DTO but a projection's: a
+ * projection's read DTO arrives from a query and nothing should construct it, the line the
+ * Kotlin port draws too. An entity cannot have a read-only primary source, so "not a
+ * projection" is exactly "constructable". */
+ protected void emitRecord(MetaObject entity, Path outRoot, List fields,
+ List annotationsPerField, boolean stamps, boolean crossField) {
String[] split = SpringNaming.splitFqn(entity.getName());
String pkg = split[0];
String shortName = split[1];
String recordName = SpringNaming.dtoName(shortName);
// A jakarta constraint is any annotation content OTHER than the Jackson @JsonDeserialize
- // (#234) — stripping only @JsonDeserialize keeps this byte-identical for every pre-#234
- // DTO (which never carries one) while a uri/inet-only component doesn't pull an unused
- // jakarta.validation import.
+ // (#234) — stripping only @JsonDeserialize keeps a uri/inet-only component from pulling an
+ // unused jakarta.validation import.
boolean usesValidation = annotationsPerField.stream()
.anyMatch(a -> !a.replaceAll("@JsonDeserialize\\([^)]*\\)", "").trim().isEmpty());
// @Valid (jakarta.validation, NOT ...constraints) cascades validation into a
// value-object jsonb component — emitted on VO fields by emit() (Program D).
- boolean crossField = extraBodyMembers.stream().anyMatch(m -> m.contains("@AssertTrue"));
boolean usesValid = annotationsPerField.stream().anyMatch(a -> a.contains("@Valid"));
// #234: a strict field.uri / field.inet component carries @JsonDeserialize(using = …).
boolean usesNetDeser = annotationsPerField.stream().anyMatch(a -> a.contains("@JsonDeserialize"));
- StringBuilder src = new StringBuilder();
- if (!pkg.isEmpty()) {
- src.append("package ").append(pkg).append(";\n\n");
- }
+ SpringJavaWriter w = newWriter(pkg);
// ADR-0019 Amendment 1: a decimal component binds the canonical serializer / strict
// deserializer (JsonDeserialize is imported once, for either reason).
boolean usesDecimal = fields.stream()
@@ -634,83 +669,69 @@ private void emitRecord(MetaObject entity, Path outRoot, List fields,
boolean usesDuration = wire.durationsIso() && fields.stream()
.anyMatch(f -> SpringGeneratorSupport.isDurationComponent(componentTypeFr019(f, entity)));
if (usesDecimal) {
- src.append(SpringGeneratorSupport.decimalAnnotationImports(runtimePackage, wire));
+ for (String fqn : SpringGeneratorSupport.decimalAnnotationImports(runtimePackage, wire)) w.use(fqn);
} else if (usesNetDeser || usesDuration) {
- src.append("import com.fasterxml.jackson.databind.annotation.JsonDeserialize;\n");
+ w.use("com.fasterxml.jackson.databind.annotation.JsonDeserialize");
}
if (usesDuration) {
- src.append(SpringGeneratorSupport.durationAnnotationImports(
- runtimePackage, usesDecimal && wire.decimalsAsString()));
+ for (String fqn : SpringGeneratorSupport.durationAnnotationImports(
+ runtimePackage, usesDecimal && wire.decimalsAsString())) {
+ w.use(fqn);
+ }
}
+ if (usesValid) w.use("jakarta.validation.Valid");
// Wildcard import keeps the emit simple — record components carry a small,
// closed set of jakarta.validation.constraints annotations.
- if (usesValid) {
- src.append("import jakarta.validation.Valid;\n");
- }
- if (usesValidation || crossField) {
- src.append("import jakarta.validation.constraints.*;\n");
- }
- if (usesDecimal || usesNetDeser || usesDuration || usesValid || usesValidation || crossField) {
- src.append('\n');
- }
- src.append("/** GENERATED — wire DTO for ").append(shortName)
- .append(". Do not hand-edit; regenerated from metadata. */\n");
+ if (usesValidation || crossField) w.use("jakarta.validation.constraints.*");
+ w.line("/** GENERATED — wire DTO for " + shortName + ". Do not hand-edit; regenerated from metadata. */");
// A request body DROPS an undeclared key, never rejects it, whatever FAIL_ON_UNKNOWN_PROPERTIES
// the host's ObjectMapper carries (a plain ObjectMapper has it on). Only a class bound from a
// write route's body is one; a projection or report row keeps the host mapper's strictness.
if (requestBodies.contains(entity.getName())) {
- src.append("@com.fasterxml.jackson.annotation.JsonIgnoreProperties(ignoreUnknown = true)\n");
+ w.line("@com.fasterxml.jackson.annotation.JsonIgnoreProperties(ignoreUnknown = true)");
}
- src.append("public record ").append(recordName).append("(\n");
-
+ w.line("public record " + recordName + "(");
// Filter ObjectField — see class javadoc. Same reason as the Kotlin port's
// KotlinExposedTableGenerator scalar-only filter.
List components = new ArrayList<>(fields.size());
- for (int i = 0; i < fields.size(); i++) {
- MetaField field = fields.get(i);
- String annotations = annotationsPerField.get(i);
- String type = componentTypeFr019(field, entity);
- // A field named notify/wait/toString/… cannot BE a record component (JLS 8.10.3),
- // so it is escaped here and pinned back to its declared name on the wire.
- String component = SpringNaming.recordComponentName(field.getName());
- String jsonName = SpringNaming.jsonPropertyAnnotation(field.getName());
- src.append(" ");
- if (!annotations.isEmpty()) src.append(annotations).append(' ');
- String decimalJson = SpringGeneratorSupport.decimalJsonAnnotations(type, runtimePackage, field, wire);
- if (!decimalJson.isEmpty()) src.append(decimalJson).append(' ');
- String durationJson = SpringGeneratorSupport.durationJsonAnnotations(type, wire);
- if (!durationJson.isEmpty()) src.append(durationJson).append(' ');
- if (!jsonName.isEmpty()) src.append(jsonName).append(' ');
- src.append(type).append(' ').append(component);
- if (i < fields.size() - 1) src.append(',');
- src.append('\n');
- components.add(new String[] { type, component });
- }
+ w.deeper(1, () -> {
+ for (int i = 0; i < fields.size(); i++) {
+ MetaField field = fields.get(i);
+ String type = componentTypeFr019(field, entity);
+ // A field named notify/wait/toString/… cannot BE a record component (JLS 8.10.3),
+ // so it is escaped here and pinned back to its declared name on the wire.
+ String component = SpringNaming.recordComponentName(field.getName());
+ w.line(SpringGeneratorSupport.recordComponentDeclaration(
+ annotationsPerField.get(i), type, component, field, runtimePackage, wire)
+ + (i < fields.size() - 1 ? "," : ""));
+ components.add(new String[] { type, component });
+ }
+ });
- // Nested `public enum { }` declarations for this record's INLINE enum
- // fields, deduped by enum-type name. FR-019: a field resolving to a package-level shared
- // enum is NOT nested here — its type is materialized standalone (or @provided externally)
- // and merely referenced. Inline enums stay nested (cross-port parity, byte-identical default).
- List enumDecls = collectEnumDecls(entity, fields);
// FR-044: a report row is not constructable either, for the projection's reason.
- String builder = MetaObject.SUBTYPE_PROJECTION.equals(entity.getSubType()) || GeneratorUtil.isReport(entity)
- ? "" : SpringRecordBuilder.members(recordName, components);
- if (enumDecls.isEmpty() && extraBodyMembers.isEmpty() && builder.isEmpty()) {
- src.append(") {}\n");
+ boolean builder = !MetaObject.SUBTYPE_PROJECTION.equals(entity.getSubType()) && !GeneratorUtil.isReport(entity)
+ && SpringRecordBuilder.applies(recordName, components);
+ if (!hasEnumDecls(fields) && !stamps && !crossField && !builder) {
+ w.line(") {}");
} else {
- src.append(") {\n");
- for (String decl : enumDecls) src.append(" ").append(decl.replace("\n", "\n ")).append('\n');
- for (String member : extraBodyMembers) src.append(member);
- src.append(builder);
- src.append("}\n");
+ try (CodeWriter.Block body = w.block(") {")) {
+ // Nested `public enum { }` declarations for this record's INLINE enum
+ // fields, deduped by enum-type name. FR-019: a field resolving to a package-level shared
+ // enum is NOT nested here — its type is materialized standalone (or @provided externally)
+ // and merely referenced.
+ writeEnumDecls(w, entity, fields);
+ if (stamps) writeAutoSetStampHelpers(w, entity, fields, recordName);
+ if (crossField) SpringGeneratorSupport.writeCrossFieldValidationMembers(w, entity, fields);
+ if (builder) SpringRecordBuilder.writeMembers(w, recordName, components);
+ }
}
-
- writeJavaFile(entity, outRoot, pkg, recordName, src.toString());
+ writeJavaFile(entity, outRoot, pkg, recordName, w);
}
/**
- * Issue #203 — build the record-body {@code @autoSet} stamping helpers for {@code entity}
- * (whose DTO record is {@code recordName}, over the component list {@code fields}):
+ * Issue #203 — write the record-body {@code @autoSet} stamping helpers for {@code entity}
+ * (whose DTO record is {@code recordName}, over the component list {@code fields}), each after
+ * a blank line:
*