From e23f7b0aa2705fed8a4a55106b7b79731501b7e7 Mon Sep 17 00:00:00 2001
From: Doug Mealing
Date: Sat, 21 Nov 2026 14:19:08 -0500
Subject: [PATCH 01/14] refactor(codegen-spring): write the Spring controller
through the code writer (W-JV-3)
SpringControllerGenerator writes through SpringJavaWriter, a JavaWriter
adding continuation lines and indented case bodies. Each member of the
generated controller comes from its own protected write* method.
SpringGeneratorSupport's cross-field validator members and annotation
import lists go through the writer too, and both files leave the layout
ratchet's allowlist.
Output is unchanged on 1,512 controllers from every fixture model except
for sorted imports and no blank line after the class opener; the six
golden controllers are regenerated. DTO and value-object output is
byte-identical.
---
CHANGELOG.md | 11 +
.../resources/layout-ratchet/allowlist.json | 2 -
.../spring/SpringControllerGenerator.java | 2394 +++++++++--------
.../generator/spring/SpringDtoGenerator.java | 29 +-
.../spring/SpringGeneratorSupport.java | 58 +-
.../generator/spring/SpringJavaWriter.java | 59 +
.../spring/SpringValueObjectGenerator.java | 10 +-
.../acme/shop/CustomerController.java | 21 +-
.../shop/CustomerStatusTotalsController.java | 15 +-
.../expected/acme/shop/OrderController.java | 21 +-
.../acme/shop/OrderSummaryController.java | 15 +-
.../acme/shop/OrderTagController.java | 21 +-
.../expected/acme/shop/TagController.java | 21 +-
13 files changed, 1422 insertions(+), 1255 deletions(-)
create mode 100644 server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringJavaWriter.java
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 534327d4c4..6f20a91a40 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -103,6 +103,17 @@ 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 and value-object output is unchanged.
- **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
diff --git a/server/java/codegen-base/src/test/resources/layout-ratchet/allowlist.json b/server/java/codegen-base/src/test/resources/layout-ratchet/allowlist.json
index 1ad86f3d8c..0c676096b4 100644
--- a/server/java/codegen-base/src/test/resources/layout-ratchet/allowlist.json
+++ b/server/java/codegen-base/src/test/resources/layout-ratchet/allowlist.json
@@ -9,10 +9,8 @@
"codegen-spring/src/main/java/com/metaobjects/generator/spring/Fr019SharedEnum.java": "Emits the shared enum class by string concatenation with hand-typed line breaks and indentation. Converts with the Java small generators and polish writer PR (W-JV-5).",
"codegen-spring/src/main/java/com/metaobjects/generator/spring/JUnitRequirementTestsGenerator.java": "Emits the JUnit requirement test classes by string concatenation with hand-typed line breaks and indentation. Converts with the Java small generators and polish writer PR (W-JV-5).",
"codegen-spring/src/main/java/com/metaobjects/generator/spring/LlmTraceHelperGenerator.java": "Emits the LLM trace helper class by string concatenation with hand-typed line breaks and indentation. Converts with the Java small generators and polish writer PR (W-JV-5).",
- "codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringControllerGenerator.java": "Emits the Spring controller by string concatenation with hand-typed line breaks and indentation. Converts with the Java controller and support class writer PR (W-JV-3).",
"codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringDtoGenerator.java": "Emits the DTO records by string concatenation with hand-typed line breaks and indentation. Converts with the Java DTO, parser, names, repository and report export writer PR (W-JV-4).",
"codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringFilterAllowlistGenerator.java": "Emits the filter allowlist class by string concatenation with hand-typed line breaks and indentation. Converts with the Java small generators and polish writer PR (W-JV-5).",
- "codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringGeneratorSupport.java": "Emits the validator methods and import lines shared by the Spring generators by string concatenation with hand-typed line breaks and indentation. Converts with the Java controller and support class writer PR (W-JV-3).",
"codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringNamesGenerator.java": "Emits the names constants class by string concatenation with hand-typed line breaks and indentation. Converts with the Java DTO, parser, names, repository and report export writer PR (W-JV-4).",
"codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringNaming.java": "Writes the package line of a generated file with a typed line break. Converts with the Java DTO, parser, names, repository and report export writer PR (W-JV-4), when that package line comes from JavaWriter.packageName().",
"codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringOutputParserGenerator.java": "Emits the output parser class by string concatenation with hand-typed line breaks and indentation. Converts with the Java DTO, parser, names, repository and report export writer PR (W-JV-4).",
diff --git a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringControllerGenerator.java b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringControllerGenerator.java
index fc6471fcdd..03283bb26c 100644
--- a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringControllerGenerator.java
+++ b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringControllerGenerator.java
@@ -6,6 +6,7 @@
// same-package bare-name resolution, is what keeps the ejected copy compiling.
import com.metaobjects.generator.spring.AutoSetSupport;
import com.metaobjects.generator.spring.SpringGeneratorSupport;
+import com.metaobjects.generator.spring.SpringJavaWriter;
import com.metaobjects.generator.spring.SpringM2mSupport;
import com.metaobjects.generator.spring.SpringNaming;
import com.metaobjects.generator.spring.SpringTypeMapper;
@@ -21,6 +22,7 @@
import com.metaobjects.generator.RunAware;
import com.metaobjects.generator.GeneratorIOWriter;
import com.metaobjects.generator.direct.MultiFileDirectGeneratorBase;
+import com.metaobjects.generator.writer.CodeWriter;
import com.metaobjects.loader.MetaDataLoader;
import com.metaobjects.generator.util.RestSurfaceGate;
import com.metaobjects.object.MetaObject;
@@ -32,7 +34,6 @@
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
-import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
@@ -86,15 +87,11 @@
* consumer implements with their persistence layer of choice (Spring Data
* JPA / jOOQ / plain JDBC).
*
- *
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.
*/
- private static void appendReportListHandler(StringBuilder out, String shortName, String dtoName,
- String repoName, int maxRows, boolean export,
- String routeBase, List hidden) {
- StringBuilder src = new StringBuilder();
- appendReportListHandlerBody(src, shortName, dtoName, repoName, maxRows, export, routeBase, hidden);
- String handler = src.toString();
- if (export) {
- // With the export branch wired, no answer of the list route consults Accept (the
- // selector is ?format): every body carries an explicit application/json, which
- // Spring then honours instead of negotiating against the request's Accept header.
- handler = handler.replace("ResponseEntity.badRequest().body(", "badRequest(")
- .replaceAll("ResponseEntity\\.ok\\((?!\\))", "ok(");
- }
- out.append(handler);
- if (export) {
- out.append(" private static ResponseEntity