diff --git a/CHANGELOG.md b/CHANGELOG.md index 31e524e19c..6537a9f080 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -990,6 +990,15 @@ Each item below is described in full under Security, Added, Changed or Fixed; th the new `fixtures/writer-conformance/` corpus. No shipped generator uses the writer yet, so generated output does not change in this release. +- **A code writer for Java generators: `CodeWriter` and `JavaWriter` in `metaobjects-codegen-base`** + (ADR-0063). The same contract as the TypeScript writer: `JavaWriter` collects imports while the + body is written (`use("java.util.List")` returns the name to write), skips `java.lang` and + same-package types, prints static imports first, writes Javadoc, and breaks a call that does not + fit 120 columns with no trailing comma. `block` is a `try`-with-resources scope. It runs the + shared `core` cases and nine new `java` cases, and a layout ratchet (a `javac` parse-tree test + with a written, shrink-only allowlist) now holds Java generator source to it. No shipped Java + generator uses the writer yet, so generated output does not change in this release. + - **Select objects to regenerate in every port.** C# `dotnet meta gen --entities A,B` (and `verify --codegen --entities`) and, for Java and Kotlin, `mvn metaobjects:generate -Dmeta.entities=A,B` regenerate only the named objects' files, like TypeScript's diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 5e5114c432..a911a910e7 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -66,7 +66,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | [`fixtures/codegen-skip-conformance/`](../fixtures/codegen-skip-conformance/) (when `gen` may skip and what a local `verify --codegen` may answer, ADR-0064) | one case table in `cases.json`, plus the manifest layout vectors in `manifests.json` (ADR-0064 Amendment 1) | ✓ | ✓ | ✓ (through the Java runner) | ✓ | ✓ | | [`fixtures/codegen-noop/`](../fixtures/codegen-noop/) (vocabulary with no lowering yet: FR-044 reporting, what is lowered and what stays inert; ADR-0066 business rules, inert everywhere) | 2 model pairs (`reporting/` and `rules/`, each `with` vs `without`) | ✓ (codegen + migrate) | ✓ | ✓ | ✓ | ✓ | | [`fixtures/cube-model/`](../fixtures/cube-model/) (FR-044 Plan 4 — the `cube-model` generator's golden Cube files, plus the canonical model's golden) | 46 cases (36 trees + 10 errors) + 1 canonical golden | ✓ (the exporter is TypeScript-only, spec R6; its `cube` lane also loads the files into a real Cube) | — | — | — | — | -| [`fixtures/writer-conformance/`](../fixtures/writer-conformance/) (ADR-0063 — the code writer generators write through) | 41 cases (31 core + 10 TypeScript) | ✓ (the first writer; core and TypeScript dialect) | — (writer not built yet) | — (writer not built yet) | — (writer not built yet) | — (writer not built yet) | +| [`fixtures/writer-conformance/`](../fixtures/writer-conformance/) (ADR-0063 — the code writer generators write through) | 50 cases (31 core + 10 TypeScript + 9 Java) | ✓ (the first writer; core and TypeScript dialect) | ✓ (core and Java dialect; `JavaWriter` in `codegen-base`) | — (writer not built yet) | — (writer not built yet) | — (writer not built yet) | | [`fixtures/contract-conformance/`](../fixtures/contract-conformance/) (FR-022 — the `contract-schema` and `openapi` generators' golden trees and refusals) | 19 cases (14 trees + 5 errors) | ✓ (one neutral engine, ADR-0034 Amendment 10; the generated API lanes also hold real traffic to the documents) | — | — | — | — | | [`fixtures/explorer-conformance/`](../fixtures/explorer-conformance/) (the `explorer.json` data spine: `meta export --effective` + `meta verify --format json` + the generated-file manifest in, one explorer document out) | 1 case (`shop`) | ✓ (the builder is TypeScript, and reads only port-neutral inputs) | — | — | — | — | diff --git a/fixtures/writer-conformance/README.md b/fixtures/writer-conformance/README.md index e6fbe73d4f..c31bdc4319 100644 --- a/fixtures/writer-conformance/README.md +++ b/fixtures/writer-conformance/README.md @@ -7,9 +7,15 @@ format are in [`spec/code-writer.md`](../../spec/code-writer.md). - `cases/*.json` with `"dialect": "core"` pin the language-neutral core: indentation, blocks, blank-line requests, snippets, fit-or-break lists, line endings and the error codes. Every port's writer runs them with the options the case states. -- Cases with a language dialect (`"dialect": "typescript"`) pin that language's writer: import - collection and ordering, doc comments and its defaults. +- Cases with a language dialect (`"dialect": "typescript"`, `"dialect": "java"`) pin that + language's writer: import collection and ordering, doc comments and its defaults. A runner + skips the dialects that are not its own. -Runner: TypeScript, `server/typescript/packages/codegen-ts/test/writer-conformance.test.ts`. -The other ports run the `core` cases when their writers land, and add cases for their own -dialect beside these. +Runners: + +- TypeScript, `server/typescript/packages/codegen-ts/test/writer-conformance.test.ts` (`core` and `typescript`). +- Java, `server/java/codegen-base/src/test/java/com/metaobjects/generator/writer/WriterConformanceTest.java` (`core` and `java`). +- Rust, `server/rust/metaobjects-codegen/tests/writer_conformance.rs` (`core`). + +The ports without a writer yet (C#, Kotlin, Python) run the `core` cases when their writers +land, and add cases for their own dialect beside these. diff --git a/fixtures/writer-conformance/cases/java-defaults.json b/fixtures/writer-conformance/cases/java-defaults.json new file mode 100644 index 0000000000..fa8d7eef04 --- /dev/null +++ b/fixtures/writer-conformance/cases/java-defaults.json @@ -0,0 +1,61 @@ +{ + "description": "The Java dialect indents four spaces, breaks at 120 columns and puts no comma after the last item of a broken list.", + "dialect": "java", + "ops": [ + [ + "open", + "class A {" + ], + [ + "line", + "static final List NAMES = ", + { + "list": { + "open": "List.of(", + "items": [ + "\"n00\"", + "\"n01\"", + "\"n02\"", + "\"n03\"", + "\"n04\"", + "\"n05\"", + "\"n06\"", + "\"n07\"", + "\"n08\"", + "\"n09\"", + "\"n10\"", + "\"n11\"", + "\"n12\"", + "\"n13\"" + ], + "close": ")" + } + }, + ";" + ], + [ + "close", + "}" + ] + ], + "expected": [ + "class A {", + " static final List NAMES = List.of(", + " \"n00\",", + " \"n01\",", + " \"n02\",", + " \"n03\",", + " \"n04\",", + " \"n05\",", + " \"n06\",", + " \"n07\",", + " \"n08\",", + " \"n09\",", + " \"n10\",", + " \"n11\",", + " \"n12\",", + " \"n13\"", + " );", + "}" + ] +} diff --git a/fixtures/writer-conformance/cases/java-doc-comment.json b/fixtures/writer-conformance/cases/java-doc-comment.json new file mode 100644 index 0000000000..359f7c200a --- /dev/null +++ b/fixtures/writer-conformance/cases/java-doc-comment.json @@ -0,0 +1,44 @@ +{ + "description": "A one-entry doc comment that fits is one line; more entries, or one that does not fit, make a block. An empty entry is a bare ` *` line, and a comment terminator inside the text is neutralised.", + "dialect": "java", + "ops": [ + [ + "doc", + "The user." + ], + [ + "line", + "a();" + ], + [ + "doc", + "First line.", + "", + "@see other" + ], + [ + "line", + "b();" + ], + [ + "doc", + "ends */ here" + ], + [ + "line", + "c();" + ] + ], + "expected": [ + "/** The user. */", + "a();", + "/**", + " * First line.", + " *", + " * @see other", + " */", + "b();", + "/** ends */ here */", + "c();" + ] +} diff --git a/fixtures/writer-conformance/cases/java-header-package-imports-body.json b/fixtures/writer-conformance/cases/java-header-package-imports-body.json new file mode 100644 index 0000000000..2b382f6f0f --- /dev/null +++ b/fixtures/writer-conformance/cases/java-header-package-imports-body.json @@ -0,0 +1,41 @@ +{ + "description": "Header lines print first, then a blank line, the package line, a blank line, the imports, a blank line and the body. A file with no imports has no import block.", + "dialect": "java", + "ops": [ + [ + "header", + "// Generated by MetaObjects. Do not edit." + ], + [ + "package", + "com.acme.api" + ], + [ + "use", + "java.util.List" + ], + [ + "open", + "interface A {" + ], + [ + "line", + "List names();" + ], + [ + "close", + "}" + ] + ], + "expected": [ + "// Generated by MetaObjects. Do not edit.", + "", + "package com.acme.api;", + "", + "import java.util.List;", + "", + "interface A {", + " List names();", + "}" + ] +} diff --git a/fixtures/writer-conformance/cases/java-imports-collected-and-sorted.json b/fixtures/writer-conformance/cases/java-imports-collected-and-sorted.json new file mode 100644 index 0000000000..4db35f89ae --- /dev/null +++ b/fixtures/writer-conformance/cases/java-imports-collected-and-sorted.json @@ -0,0 +1,50 @@ +{ + "description": "Imports print in code-unit order, one per line, after the package line. Static imports come first, then a blank line, then the others. A name used twice is imported once.", + "dialect": "java", + "ops": [ + [ + "package", + "com.acme" + ], + [ + "use", + "java.util.Map" + ], + [ + "use", + "com.acme.other.Zed" + ], + [ + "useStatic", + "org.junit.Assert.assertEquals" + ], + [ + "use", + "java.util.List" + ], + [ + "use", + "java.util.List" + ], + [ + "useStatic", + "java.util.Objects.requireNonNull" + ], + [ + "line", + "class A {}" + ] + ], + "expected": [ + "package com.acme;", + "", + "import static java.util.Objects.requireNonNull;", + "import static org.junit.Assert.assertEquals;", + "", + "import com.acme.other.Zed;", + "import java.util.List;", + "import java.util.Map;", + "", + "class A {}" + ] +} diff --git a/fixtures/writer-conformance/cases/java-imports-conflict.json b/fixtures/writer-conformance/cases/java-imports-conflict.json new file mode 100644 index 0000000000..aa0405d9ae --- /dev/null +++ b/fixtures/writer-conformance/cases/java-imports-conflict.json @@ -0,0 +1,15 @@ +{ + "description": "One simple name imported from two types is an error, not a silent shadow.", + "dialect": "java", + "ops": [ + [ + "use", + "java.util.Date" + ], + [ + "use", + "java.sql.Date" + ] + ], + "error": "ERR_WRITER_IMPORT_CONFLICT" +} diff --git a/fixtures/writer-conformance/cases/java-imports-nested-type.json b/fixtures/writer-conformance/cases/java-imports-nested-type.json new file mode 100644 index 0000000000..671a362695 --- /dev/null +++ b/fixtures/writer-conformance/cases/java-imports-nested-type.json @@ -0,0 +1,19 @@ +{ + "description": "A nested type is imported as written and used by its last segment.", + "dialect": "java", + "ops": [ + [ + "use", + "java.util.Map.Entry" + ], + [ + "line", + "class A {}" + ] + ], + "expected": [ + "import java.util.Map.Entry;", + "", + "class A {}" + ] +} diff --git a/fixtures/writer-conformance/cases/java-imports-skip-lang-and-package.json b/fixtures/writer-conformance/cases/java-imports-skip-lang-and-package.json new file mode 100644 index 0000000000..675ce0a617 --- /dev/null +++ b/fixtures/writer-conformance/cases/java-imports-skip-lang-and-package.json @@ -0,0 +1,33 @@ +{ + "description": "A type in java.lang or in the file's own package is written by its simple name and imports nothing, whichever order the package and the types were named in.", + "dialect": "java", + "ops": [ + [ + "use", + "java.lang.String" + ], + [ + "use", + "com.acme.Sibling" + ], + [ + "use", + "java.util.UUID" + ], + [ + "package", + "com.acme" + ], + [ + "line", + "class A {}" + ] + ], + "expected": [ + "package com.acme;", + "", + "import java.util.UUID;", + "", + "class A {}" + ] +} diff --git a/fixtures/writer-conformance/cases/java-package-without-imports.json b/fixtures/writer-conformance/cases/java-package-without-imports.json new file mode 100644 index 0000000000..c7b28cdc7d --- /dev/null +++ b/fixtures/writer-conformance/cases/java-package-without-imports.json @@ -0,0 +1,19 @@ +{ + "description": "A file with a package line and no imports has no import block.", + "dialect": "java", + "ops": [ + [ + "package", + "com.acme.api" + ], + [ + "line", + "interface A {}" + ] + ], + "expected": [ + "package com.acme.api;", + "", + "interface A {}" + ] +} diff --git a/fixtures/writer-conformance/cases/java-static-imports-conflict.json b/fixtures/writer-conformance/cases/java-static-imports-conflict.json new file mode 100644 index 0000000000..365ac18e33 --- /dev/null +++ b/fixtures/writer-conformance/cases/java-static-imports-conflict.json @@ -0,0 +1,15 @@ +{ + "description": "One static member name imported from two types is an error.", + "dialect": "java", + "ops": [ + [ + "useStatic", + "a.A.of" + ], + [ + "useStatic", + "b.B.of" + ] + ], + "error": "ERR_WRITER_IMPORT_CONFLICT" +} diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/CodeWriter.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/CodeWriter.java new file mode 100644 index 0000000000..fe77e5be81 --- /dev/null +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/CodeWriter.java @@ -0,0 +1,278 @@ +package com.metaobjects.generator.writer; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.regex.Pattern; + +/** + * The language-neutral code writer (ADR-0063; contract: {@code spec/code-writer.md}). + * + *

A generator says WHAT a line contains; the writer decides WHERE it sits. It builds the file + * in memory and returns a string, so nothing here touches the disk and no formatter ever runs + * over the result. It never parses the text it is handed: it lays out the structure the + * generator gave it, which is lines, blocks, blank-line requests and breakable lists. + * + *

This package is the only generator source allowed to type layout (line breaks and + * indentation). The layout ratchet test holds every other generator file to that. + * + *

The class is built to be extended (ADR-0063, item 7): nothing is final or private, so a + * dialect or an adopter's subclass overrides the one step it needs to change, such as where a + * line breaks ({@link #breakAt}) or what a part becomes ({@link #piece}). These methods are not + * a stability contract and may change between minor versions. + */ +public class CodeWriter { + + private static final String NEWLINE = "\n"; + private static final Pattern ANY_LINE_BREAK = Pattern.compile("\r\n?|\n"); + + protected final WriterOptions options; + protected final List out = new ArrayList<>(); + /** The text of each line that opened a block still open, outermost first. */ + protected final List openers = new ArrayList<>(); + protected final List prefixes = new ArrayList<>(List.of("")); + protected boolean wantBlank = false; + /** True at the start of the file and right after a block opens: no blank line goes here. */ + protected boolean atBlockStart = true; + + public CodeWriter(WriterOptions options) { + this.options = options; + } + + public WriterOptions options() { + return options; + } + + /** + * One line at the current indent. The parts are concatenated; when the line does not fit the + * width, the LAST non-empty list in it is printed one item per line. A line whose text is + * empty is a blank-line request. + */ + public CodeWriter line(Object... parts) { + return put(piece(Arrays.asList(parts))); + } + + /** Ask for one blank line before whatever is written next. Requests never stack. */ + public CodeWriter blank() { + wantBlank = true; + return this; + } + + /** Write the line that opens a block, then indent. */ + public CodeWriter open(Object... parts) { + return openPiece(piece(Arrays.asList(parts))); + } + + /** Dedent, then write the line that closes the block. */ + public CodeWriter close(Object... parts) { + return closePiece(piece(Arrays.asList(parts))); + } + + /** + * A block, scoped: {@code try (var b = w.block("class A {")) { ... }} writes the head, indents, + * and on leaving the {@code try} dedents and writes {@code "}"}. The indent cannot be left + * unbalanced. + */ + public Block block(Object head) { + return block(head, "}"); + } + + /** A block closed by {@code tail} instead of {@code "}"}, such as {@code "});"}. */ + public Block block(Object head, Object tail) { + open(head); + return new Block(tail); + } + + /** The scope {@link #block} returns; closing it writes the block's closing line. */ + public class Block implements AutoCloseable { + private final Object tail; + + protected Block(Object tail) { + this.tail = tail; + } + + @Override + public void close() { + CodeWriter.this.close(tail); + } + } + + /** + * A multi-line snippet written as it should read: a Java text block is the natural argument. + * Its common left margin is removed and it is re-indented to the current level; a blank line in + * it is a blank-line request. Every line is re-indented, including lines inside a multi-line + * string literal. + */ + public CodeWriter text(String snippet) { + List lines = new ArrayList<>(List.of(ANY_LINE_BREAK.split(snippet, -1))); + if (lines.size() > 1 && lines.get(0).isBlank()) lines.remove(0); + if (!lines.isEmpty() && lines.get(lines.size() - 1).isBlank()) lines.remove(lines.size() - 1); + int margin = Integer.MAX_VALUE; + for (String l : lines) { + if (!l.isBlank()) margin = Math.min(margin, l.length() - l.stripLeading().length()); + } + for (String l : lines) { + if (l.isBlank()) blank(); + else put(l.substring(margin)); + } + return this; + } + + /** The body text: every line joined, with no final newline. Throws if a block is still open. */ + protected String body() { + if (!openers.isEmpty()) { + throw new WriterException( + WriterException.UNCLOSED_BLOCK, + "unclosed block opened by: " + openers.get(openers.size() - 1)); + } + return String.join(NEWLINE, out); + } + + /** The finished file: {@code \n} line endings, no trailing whitespace, one final newline (none when empty). */ + @Override + public String toString() { + String body = body(); + return body.isEmpty() ? "" : body + NEWLINE; + } + + /** + * Turn one argument of {@code line()} into a writer piece. A dialect overrides this to accept + * its own fragment types, and calls {@code super} for the rest. + */ + protected Object piece(Object p) { + if (p instanceof CharSequence cs) return cs.toString(); + if (p instanceof Group g) { + List items = new ArrayList<>(g.items().size()); + for (Object i : g.items()) items.add(piece(i)); + return new Group(g.open(), items, g.close(), g.pad()); + } + if (p instanceof List l) { + List parts = new ArrayList<>(l.size()); + for (Object x : l) parts.add(piece(x)); + return parts; + } + if (p instanceof Object[] a) return piece(Arrays.asList(a)); + throw new WriterException(WriterException.UNKNOWN_PIECE, "cannot write " + describe(p)); + } + + /** Whether {@code text} fits on one line at the current indent. */ + protected boolean fits(String text) { + return widthOf(prefix()) + widthOf(text) <= options.width(); + } + + /** + * Where a line that does not fit breaks: the text before, the list that breaks, the text + * after; or null to print the line as it is. The default is the line's LAST non-empty list. + */ + protected Split breakAt(Object piece) { + return lastGroup(piece); + } + + protected CodeWriter openPiece(Object piece) { + put(piece); + openers.add(flat(piece).strip()); + atBlockStart = true; + return this; + } + + protected CodeWriter closePiece(Object piece) { + if (openers.isEmpty()) { + throw new WriterException( + WriterException.UNBALANCED_CLOSE, "close(\"" + flat(piece) + "\") with no block open"); + } + openers.remove(openers.size() - 1); + wantBlank = false; + return put(piece); + } + + protected String prefix() { + int depth = openers.size(); + while (prefixes.size() <= depth) prefixes.add(prefixes.get(prefixes.size() - 1) + options.indent()); + return prefixes.get(depth); + } + + protected CodeWriter put(Object piece) { + String raw = flat(piece); + if (ANY_LINE_BREAK.matcher(raw).find()) { + throw new WriterException( + WriterException.NEWLINE_IN_LINE, + "line text contains a line break; write each line separately or use text(): \"" + raw + "\""); + } + String text = raw.stripTrailing(); + if (text.isEmpty()) return blank(); + if (wantBlank && !atBlockStart) out.add(""); + wantBlank = false; + atBlockStart = false; + String pre = prefix(); + Split split = fits(text) ? null : breakAt(piece); + if (split == null) { + out.add(pre + text); + return this; + } + openPiece(split.before() + split.group().open()); + List items = split.group().items(); + for (int n = 0; n < items.size(); n++) { + boolean comma = n < items.size() - 1 || options.trailingComma(); + put(List.of(items.get(n), comma ? "," : "")); + } + return closePiece(split.group().close() + split.after()); + } + + /** The text before a list that breaks, the list, and the text after it. */ + public record Split(String before, Group group, String after) {} + + /** A list with no padding inside its brackets: {@code [a, b]}, {@code f(a, b)}, {@code }. */ + public static Group list(String open, List items, String close) { + return new Group(open, items, close, false); + } + + /** A list with a space inside its brackets: {@code { a, b }}. */ + public static Group padded(String open, List items, String close) { + return new Group(open, items, close, true); + } + + /** A piece printed on one line. */ + public static String flat(Object p) { + if (p instanceof String s) return s; + if (p instanceof Group g) { + if (g.items().isEmpty()) return g.open() + g.close(); + StringBuilder inner = new StringBuilder(); + for (int i = 0; i < g.items().size(); i++) { + if (i > 0) inner.append(", "); + inner.append(flat(g.items().get(i))); + } + return g.pad() ? g.open() + " " + inner + " " + g.close() : g.open() + inner + g.close(); + } + if (p instanceof List l) { + StringBuilder s = new StringBuilder(); + for (Object x : l) s.append(flat(x)); + return s.toString(); + } + return String.valueOf(p); + } + + /** Split a piece around its LAST non-empty list: the text before, the list, the text after. */ + protected static Split lastGroup(Object p) { + if (p instanceof Group g) return g.items().isEmpty() ? null : new Split("", g, ""); + if (p instanceof List l) { + for (int i = l.size() - 1; i >= 0; i--) { + Split hit = lastGroup(l.get(i)); + if (hit != null) { + return new Split( + flat(l.subList(0, i)) + hit.before(), hit.group(), hit.after() + flat(l.subList(i + 1, l.size()))); + } + } + } + return null; + } + + /** Width in Unicode code points, so an emoji counts as one although it is two UTF-16 units. */ + protected static int widthOf(String s) { + return s.codePointCount(0, s.length()); + } + + private static String describe(Object p) { + if (p == null) return "null"; + return "an object (" + p.getClass().getName() + ")"; + } +} diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/Group.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/Group.java new file mode 100644 index 0000000000..ee20a4bf22 --- /dev/null +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/Group.java @@ -0,0 +1,48 @@ +package com.metaobjects.generator.writer; + +import java.util.List; + +/** + * A bracketed, comma-separated list. Printed on one line when the line fits the width; + * otherwise opener, one item per line (each followed by a comma) and closer. + * + *

The items are pieces: a {@code String}, another {@code Group}, or a {@code List} or array + * of pieces, which are concatenated. + */ +public class Group { + private final String open; + private final List items; + private final String close; + private final boolean pad; + + /** + * @param pad {@code { a, b }} (true) versus {@code [a, b]} or {@code f(a, b)} (false) when + * printed on one line + */ + public Group(String open, List items, String close, boolean pad) { + this.open = open; + this.items = List.copyOf(items); + this.close = close; + this.pad = pad; + } + + public Group(String open, List items, String close) { + this(open, items, close, false); + } + + public String open() { + return open; + } + + public List items() { + return items; + } + + public String close() { + return close; + } + + public boolean pad() { + return pad; + } +} diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/JavaWriter.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/JavaWriter.java new file mode 100644 index 0000000000..5d6707035e --- /dev/null +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/JavaWriter.java @@ -0,0 +1,183 @@ +package com.metaobjects.generator.writer; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.TreeMap; +import java.util.TreeSet; + +/** + * The Java dialect of the code writer (ADR-0063; contract: {@code spec/code-writer.md}). + * + *

Adds what is Java's own: the {@code package} line, imports collected while the body is + * written and printed first, string quoting and Javadoc comments. A generator names a type once + * with {@link #use} and writes what comes back, so the imports can never disagree with the body. + * + *

Like {@link CodeWriter} it is built to be extended: each section of the file + * ({@link #writeHeader}, {@link #writePackage}, {@link #writeImports}) is its own overridable + * method, and none of them is a stability contract. + */ +public class JavaWriter extends CodeWriter { + + private static final String JAVA_LANG = "java.lang"; + + /** Simple name to the fully qualified name that owns it, so one name cannot come from two types. */ + protected final Map locals = new TreeMap<>(); + /** Fully qualified names to import, in code-unit order. */ + protected final TreeSet imports = new TreeSet<>(Comparator.naturalOrder()); + /** Static members to import, as {@code pkg.Type.member}. */ + protected final TreeSet staticImports = new TreeSet<>(Comparator.naturalOrder()); + /** Member name to the type that owns it: one static name cannot come from two types. */ + protected final Map staticLocals = new TreeMap<>(); + protected final List headLines = new ArrayList<>(); + protected String packageName; + + public JavaWriter() { + this(WriterOptions.JAVA); + } + + public JavaWriter(WriterOptions options) { + super(options); + } + + /** A correctly quoted Java string literal. */ + public static String str(String value) { + StringBuilder sb = new StringBuilder(value.length() + 2).append('"'); + for (int i = 0; i < value.length(); i++) { + char c = value.charAt(i); + switch (c) { + case '"' -> sb.append("\\\""); + case '\\' -> sb.append("\\\\"); + case '\n' -> sb.append("\\n"); + case '\r' -> sb.append("\\r"); + case '\t' -> sb.append("\\t"); + case '\b' -> sb.append("\\b"); + case '\f' -> sb.append("\\f"); + default -> { + if (c < 0x20 || c == 0x7f) sb.append(String.format("\\u%04x", (int) c)); + else sb.append(c); + } + } + } + return sb.append('"').toString(); + } + + /** A call: {@code fn(a, b)}. */ + public static Group call(String fn, Object... args) { + return list(fn + "(", Arrays.asList(args), ")"); + } + + /** The {@code package} this file is in; types of that package need no import. */ + public JavaWriter packageName(String name) { + this.packageName = Objects.requireNonNull(name); + return this; + } + + /** + * Reference a type by its fully qualified name; returns the name to write (its simple name). + * A type in {@code java.lang} or in this file's package imports nothing. A nested type + * ({@code java.util.Map.Entry}) is imported as written and written by its last segment. + */ + public String use(String qualifiedName) { + String local = simpleName(qualifiedName); + String owner = locals.get(local); + if (owner != null && !owner.equals(qualifiedName)) { + throw new WriterException( + WriterException.IMPORT_CONFLICT, local + " is imported from both " + owner + " and " + qualifiedName); + } + locals.put(local, qualifiedName); + imports.add(qualifiedName); + return local; + } + + /** + * Reference a static member by {@code pkg.Type.member}; returns the name to write (the member). + */ + public String useStatic(String qualifiedMember) { + String member = simpleName(qualifiedMember); + String owner = staticLocals.get(member); + if (owner != null && !owner.equals(qualifiedMember)) { + throw new WriterException( + WriterException.IMPORT_CONFLICT, member + " is imported from both " + owner + " and " + qualifiedMember); + } + staticLocals.put(member, qualifiedMember); + staticImports.add(qualifiedMember); + return member; + } + + /** Lines printed at the very top, before the package line: a banner comment. */ + public JavaWriter header(String... lines) { + headLines.addAll(Arrays.asList(lines)); + return this; + } + + /** A Javadoc comment: one line when it fits, otherwise a block with one {@code * } line per entry. */ + public JavaWriter doc(String... lines) { + if (lines.length == 0) return this; + List safe = new ArrayList<>(lines.length); + for (String l : lines) safe.add(l.replace("*/", "*/")); + String one = "/** " + safe.get(0) + " */"; + if (safe.size() == 1 && fits(one)) { + line(one); + return this; + } + line("/**"); + for (String l : safe) line(l.isEmpty() ? " *" : " * " + l); + line(" */"); + return this; + } + + @Override + public String toString() { + CodeWriter head = sectionWriter(); + writeHeader(head); + head.blank(); + writePackage(head); + head.blank(); + writeImports(head); + String top = head.toString(); + String body = super.toString(); + if (top.isEmpty()) return body; + if (body.isEmpty()) return top; + return top + "\n" + body; + } + + /** The writer the header, package and import sections are laid out with: same options, no dialect. */ + protected CodeWriter sectionWriter() { + return new CodeWriter(options); + } + + /** The {@link #header} lines, as given. */ + protected void writeHeader(CodeWriter w) { + for (String l : headLines) w.line(l); + } + + /** The {@code package} line, when one was set. */ + protected void writePackage(CodeWriter w) { + if (packageName != null) w.line("package ", packageName, ";"); + } + + /** Static imports, a blank line, then the other imports: each group in code-unit order. */ + protected void writeImports(CodeWriter w) { + for (String s : staticImports) w.line("import static ", s, ";"); + w.blank(); + for (String t : imports) { + if (needsImport(t)) w.line("import ", t, ";"); + } + } + + /** False for a type that is in {@code java.lang} or in the file's own package. */ + protected boolean needsImport(String qualifiedName) { + int dot = qualifiedName.lastIndexOf('.'); + if (dot < 0) return false; + String pkg = qualifiedName.substring(0, dot); + return !pkg.equals(JAVA_LANG) && !pkg.equals(packageName); + } + + private static String simpleName(String qualified) { + return qualified.substring(qualified.lastIndexOf('.') + 1); + } +} diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/WriterException.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/WriterException.java new file mode 100644 index 0000000000..672be302c9 --- /dev/null +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/WriterException.java @@ -0,0 +1,30 @@ +package com.metaobjects.generator.writer; + +/** + * An error the code writer throws (ADR-0063; contract: {@code spec/code-writer.md}). The + * {@link #code()} is one of the codes every port's writer shares, and the message starts with it. + */ +public class WriterException extends RuntimeException { + + /** {@code close()} with no block open. */ + public static final String UNBALANCED_CLOSE = "ERR_WRITER_UNBALANCED_CLOSE"; + /** The file was finished with a block still open; the message quotes the line that opened it. */ + public static final String UNCLOSED_BLOCK = "ERR_WRITER_UNCLOSED_BLOCK"; + /** {@code line()} was handed text containing a line break. */ + public static final String NEWLINE_IN_LINE = "ERR_WRITER_NEWLINE_IN_LINE"; + /** One local name imported from two different places. */ + public static final String IMPORT_CONFLICT = "ERR_WRITER_IMPORT_CONFLICT"; + /** A piece the writer does not know how to print. */ + public static final String UNKNOWN_PIECE = "ERR_WRITER_UNKNOWN_PIECE"; + + private final String code; + + public WriterException(String code, String message) { + super(code + ": " + message); + this.code = code; + } + + public String code() { + return code; + } +} diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/WriterOptions.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/WriterOptions.java new file mode 100644 index 0000000000..cc5e342254 --- /dev/null +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/WriterOptions.java @@ -0,0 +1,27 @@ +package com.metaobjects.generator.writer; + +/** + * What a writer is configured with (spec/code-writer.md, "Options"). A dialect supplies the + * defaults for its language; a shared {@code core} case states all three. + * + * @param indent one level of indentation + * @param width the last column a line may reach before its last list breaks + * @param trailingComma whether a broken list puts a comma after its last item too + */ +public record WriterOptions(String indent, int width, boolean trailingComma) { + + /** Four spaces, 120 columns, no trailing comma: what Java allows in an argument list. */ + public static final WriterOptions JAVA = new WriterOptions(" ", 120, false); + + public WriterOptions withIndent(String indent) { + return new WriterOptions(indent, width, trailingComma); + } + + public WriterOptions withWidth(int width) { + return new WriterOptions(indent, width, trailingComma); + } + + public WriterOptions withTrailingComma(boolean trailingComma) { + return new WriterOptions(indent, width, trailingComma); + } +} diff --git a/server/java/codegen-base/src/test/java/com/metaobjects/generator/writer/JavaWriterTest.java b/server/java/codegen-base/src/test/java/com/metaobjects/generator/writer/JavaWriterTest.java new file mode 100644 index 0000000000..dbdc04fd4c --- /dev/null +++ b/server/java/codegen-base/src/test/java/com/metaobjects/generator/writer/JavaWriterTest.java @@ -0,0 +1,102 @@ +package com.metaobjects.generator.writer; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.util.List; +import org.junit.Test; + +/** What the shared corpus cannot say: the Java-shaped API around the cases it pins. */ +public class JavaWriterTest { + + @Test + public void str_quotes_a_java_string_literal() { + assertEquals("\"a\\\"b\\\\c\"", JavaWriter.str("a\"b\\c")); + assertEquals("\"line\\nbreak\\ttab\\r\"", JavaWriter.str("line\nbreak\ttab\r")); + assertEquals("\"\\u0001\"", JavaWriter.str("\u0001")); + assertEquals("\"caf\u00e9\"", JavaWriter.str("caf\u00e9")); + } + + @Test + public void a_scoped_block_indents_and_closes_itself() { + JavaWriter w = new JavaWriter(); + try (var cls = w.block("class A {")) { + try (var m = w.block("void f() {")) { + w.line("g();"); + } + } + assertEquals("class A {\n void f() {\n g();\n }\n}\n", w.toString()); + } + + @Test + public void a_block_can_close_with_its_own_tail() { + JavaWriter w = new JavaWriter(); + try (var b = w.block("run(() -> {", "});")) { + w.line("g();"); + } + assertEquals("run(() -> {\n g();\n});\n", w.toString()); + } + + @Test + public void use_returns_the_name_to_write() { + JavaWriter w = new JavaWriter().packageName("com.acme"); + String list = w.use("java.util.List"); + String str = w.use("java.lang.String"); + w.line("private final ", list, "<", str, "> names;"); + assertEquals("package com.acme;\n\nimport java.util.List;\n\nprivate final List names;\n", w.toString()); + } + + @Test + public void a_call_group_breaks_at_the_last_list_without_a_trailing_comma() { + JavaWriter w = new JavaWriter(WriterOptions.JAVA.withWidth(30)); + w.line("return ", JavaWriter.call("build", "alpha", "beta", "gamma", "delta"), ";"); + assertEquals("return build(\n alpha,\n beta,\n gamma,\n delta\n);\n", w.toString()); + } + + @Test + public void a_piece_that_is_not_text_is_refused() { + try { + new JavaWriter().line("x = ", 5, ";"); + fail("expected ERR_WRITER_UNKNOWN_PIECE"); + } catch (WriterException e) { + assertEquals(WriterException.UNKNOWN_PIECE, e.code()); + assertTrue(e.getMessage(), e.getMessage().startsWith("ERR_WRITER_UNKNOWN_PIECE: ")); + } + } + + @Test + public void a_list_or_array_of_parts_is_concatenated() { + JavaWriter w = new JavaWriter(); + w.line(List.of("a", "b"), new Object[] {"c", List.of("d")}); + assertEquals("abcd\n", w.toString()); + } + + @Test + public void a_text_block_is_a_snippet() { + JavaWriter w = new JavaWriter(); + try (var b = w.block("class A {")) { + w.text( + """ + void f() { + g(); + } + """); + } + assertEquals("class A {\n void f() {\n g();\n }\n}\n", w.toString()); + } + + @Test + public void a_subclass_can_change_one_layout_step() { + JavaWriter w = + new JavaWriter() { + @Override + protected void writeImports(CodeWriter section) { + section.line("// imports are elsewhere"); + } + }; + w.use("java.util.List"); + w.line("class A {}"); + assertEquals("// imports are elsewhere\n\nclass A {}\n", w.toString()); + } +} diff --git a/server/java/codegen-base/src/test/java/com/metaobjects/generator/writer/WriterConformanceTest.java b/server/java/codegen-base/src/test/java/com/metaobjects/generator/writer/WriterConformanceTest.java new file mode 100644 index 0000000000..446b612dd3 --- /dev/null +++ b/server/java/codegen-base/src/test/java/com/metaobjects/generator/writer/WriterConformanceTest.java @@ -0,0 +1,134 @@ +package com.metaobjects.generator.writer; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Stream; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +/** + * Runs {@code fixtures/writer-conformance/} against the Java writer (spec/code-writer.md). + * {@code core} cases run on {@link CodeWriter} with the options the case states; {@code java} + * cases run on {@link JavaWriter} with its own defaults unless the case overrides them. A case + * of another dialect belongs to that port's writer and is skipped here by name. + */ +@RunWith(Parameterized.class) +public class WriterConformanceTest { + + private static final String CORE = "core"; + private static final String JAVA = "java"; + + private static Path cases() { + return Path.of(System.getProperty("user.dir")) + .resolve("../../../fixtures/writer-conformance/cases") + .normalize(); + } + + @Parameterized.Parameters(name = "{0}") + public static List corpus() throws IOException { + List out = new ArrayList<>(); + try (Stream files = Files.list(cases())) { + for (Path f : files.filter(p -> p.toString().endsWith(".json")).sorted().toList()) { + JsonObject c = new Gson().fromJson(Files.readString(f), JsonObject.class); + String dialect = c.get("dialect").getAsString(); + if (dialect.equals(CORE) || dialect.equals(JAVA)) { + out.add(new Object[] {f.getFileName().toString().replaceFirst("\\.json$", ""), c}); + } + } + } + return out; + } + + private final JsonObject c; + + public WriterConformanceTest(String name, JsonObject c) { + this.c = c; + } + + @Test + public void case_matches_expected_output() { + boolean core = c.get("dialect").getAsString().equals(CORE); + if (core) assertNotNull("a core case states its options", c.get("options")); + if (c.has("error")) { + try { + run(core); + } catch (WriterException e) { + assertEquals(c.get("error").getAsString(), e.code()); + if (c.has("errorQuotes")) assertTrue(e.getMessage(), e.getMessage().contains(c.get("errorQuotes").getAsString())); + return; + } + fail("expected " + c.get("error").getAsString()); + } + List lines = new ArrayList<>(); + for (JsonElement l : c.getAsJsonArray("expected")) lines.add(l.getAsString()); + assertEquals(lines.isEmpty() ? "" : String.join("\n", lines) + "\n", run(core)); + } + + private String run(boolean core) { + CodeWriter base = core ? new CodeWriter(options()) : new JavaWriter(options()); + for (JsonElement e : c.getAsJsonArray("ops")) { + JsonArray op = e.getAsJsonArray(); + String name = op.get(0).getAsString(); + List args = new ArrayList<>(); + for (int i = 1; i < op.size(); i++) args.add(piece(op.get(i))); + switch (name) { + case "line" -> base.line(args.toArray()); + case "open" -> base.open(args.toArray()); + case "close" -> base.close(args.toArray()); + case "blank" -> base.blank(); + case "text" -> base.text((String) args.get(0)); + default -> { + if (!(base instanceof JavaWriter w)) throw new IllegalStateException("op " + name + " is not a core op"); + String[] s = args.stream().map(String.class::cast).toArray(String[]::new); + switch (name) { + case "use" -> w.use(s[0]); + case "useStatic" -> w.useStatic(s[0]); + case "package" -> w.packageName(s[0]); + case "header" -> w.header(s); + case "doc" -> w.doc(s); + default -> throw new IllegalStateException("unknown op " + name); + } + } + } + } + return base.toString(); + } + + /** The case's options laid over the dialect's defaults (core states all three). */ + private WriterOptions options() { + WriterOptions o = c.get("dialect").getAsString().equals(CORE) ? new WriterOptions(" ", 120, true) : WriterOptions.JAVA; + if (!c.has("options")) return o; + JsonObject given = c.getAsJsonObject("options"); + if (given.has("indent")) o = o.withIndent(given.get("indent").getAsString()); + if (given.has("width")) o = o.withWidth(given.get("width").getAsInt()); + if (given.has("trailingComma")) o = o.withTrailingComma(given.get("trailingComma").getAsBoolean()); + return o; + } + + private static Object piece(JsonElement p) { + if (p.isJsonPrimitive()) return p.getAsString(); + if (p.isJsonArray()) { + List parts = new ArrayList<>(); + for (JsonElement x : p.getAsJsonArray()) parts.add(piece(x)); + return parts; + } + JsonObject l = p.getAsJsonObject().getAsJsonObject("list"); + List items = new ArrayList<>(); + for (JsonElement x : l.getAsJsonArray("items")) items.add(piece(x)); + boolean pad = l.has("pad") && l.get("pad").getAsBoolean(); + return new Group(l.get("open").getAsString(), items, l.get("close").getAsString(), pad); + } +} diff --git a/server/java/codegen-base/src/test/java/com/metaobjects/generator/writer/layout/LayoutAnalyzer.java b/server/java/codegen-base/src/test/java/com/metaobjects/generator/writer/layout/LayoutAnalyzer.java new file mode 100644 index 0000000000..0f339ca7a1 --- /dev/null +++ b/server/java/codegen-base/src/test/java/com/metaobjects/generator/writer/layout/LayoutAnalyzer.java @@ -0,0 +1,327 @@ +package com.metaobjects.generator.writer.layout; + +import com.sun.source.tree.BinaryTree; +import com.sun.source.tree.CompilationUnitTree; +import com.sun.source.tree.ConditionalExpressionTree; +import com.sun.source.tree.ConstantCaseLabelTree; +import com.sun.source.tree.ExpressionTree; +import com.sun.source.tree.IdentifierTree; +import com.sun.source.tree.LiteralTree; +import com.sun.source.tree.MemberSelectTree; +import com.sun.source.tree.MethodInvocationTree; +import com.sun.source.tree.NewClassTree; +import com.sun.source.tree.ParenthesizedTree; +import com.sun.source.tree.Tree; +import com.sun.source.tree.TypeCastTree; +import com.sun.source.tree.VariableTree; +import com.sun.source.util.JavacTask; +import com.sun.source.util.SourcePositions; +import com.sun.source.util.TreePath; +import com.sun.source.util.TreePathScanner; +import com.sun.source.util.Trees; +import java.io.IOException; +import java.net.URI; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.regex.Pattern; +import javax.tools.JavaCompiler; +import javax.tools.JavaFileObject; +import javax.tools.SimpleJavaFileObject; +import javax.tools.ToolProvider; + +/** + * The layout ratchet's analyzer (ADR-0063): finds layout a generator typed by hand. + * + *

Generators say what a line contains and the writer decides where it sits, so generator + * source should never spell a line break or an indentation run. This reads a file with javac's + * own parser (the Compiler Tree API, parse only) and walks the syntax tree. Working on the tree, + * not the text, is what makes the rules exact: a comment is never a node, a string's value is the + * parser's cooked value (so {@code "\n"}, {@code "\u000a"} and a text block are the same + * finding), and a {@code final} constant is followed to its declaration so + * {@code String NL = "\n"; xs.join(NL, ...)} is a finding at the join as well as at the + * declaration. + * + *

Four rules: + * + *

    + *
  • {@code newline-literal}: a string or char literal, text block, {@code %n} format + * directive or {@code lineSeparator()} call that writes a line break. + *
  • {@code indent-literal}: a string that starts a line of output (it is not the right-hand + * part of a {@code +}) and begins with an indentation run: two or more spaces, or a tab. + *
  • {@code newline-join}: {@code String.join(sep, ...)}, {@code Collectors.joining(sep)} or + * {@code new StringJoiner(sep)} whose separator contains a line break, resolved through + * same-file constants. + *
  • {@code indent-repeat}: {@code s.repeat(n)} where {@code s} resolves to whitespace. + *
+ * + *

Places a literal is not output, and so is not layout, are ruled out by position: a search or + * comparison (the first argument of split, indexOf, lastIndexOf, contains, startsWith, endsWith, + * replace, replaceAll, replaceFirst, matches, equals, equalsIgnoreCase, contentEquals, or an + * operand of {@code ==} or {@code !=}, or a {@code case} label), a log message (the first argument + * of trace, debug, info, warn or error), and a writer snippet (the + * argument of a {@code .text(...)} call, the writer's entry for fixed code written as it should + * read: it removes the margin and re-indents). + */ +public final class LayoutAnalyzer { + + public enum Kind { + NEWLINE_LITERAL("newline-literal"), + INDENT_LITERAL("indent-literal"), + NEWLINE_JOIN("newline-join"), + INDENT_REPEAT("indent-repeat"); + + private final String label; + + Kind(String label) { + this.label = label; + } + + @Override + public String toString() { + return label; + } + } + + /** One piece of hand-typed layout: its rule, 1-based position and shortened source text. */ + public record Finding(Kind kind, int line, int column, String excerpt) { + @Override + public String toString() { + return line + ":" + column + " " + kind + " " + excerpt; + } + } + + private static final Pattern LINE_BREAK = Pattern.compile("[\r\n]|%n"); + private static final Pattern INDENT_RUN = Pattern.compile("^(?: {2,}|\t)"); + private static final Pattern WHITESPACE = Pattern.compile("^[ \t\r\n]+$"); + private static final Set SEARCH_METHODS = + Set.of( + "split", "indexOf", "lastIndexOf", "contains", "startsWith", "endsWith", "replace", + "replaceAll", "replaceFirst", "matches", "equals", "equalsIgnoreCase", "contentEquals"); + /** A logger call's message is a diagnostic for the person running the build, not generated output. */ + private static final Set LOG_METHODS = Set.of("trace", "debug", "info", "warn", "error"); + private static final String SNIPPET_METHOD = "text"; + private static final Set JOIN_METHODS = Set.of("join", "joining"); + private static final String REPEAT_METHOD = "repeat"; + private static final String LINE_SEPARATOR = "lineSeparator"; + private static final String STRING_JOINER = "StringJoiner"; + private static final int MAX_RESOLVE_DEPTH = 8; + + private LayoutAnalyzer() {} + + /** What a string expression is known to contain. {@code complete} is false when part of it is unknown. */ + private record Resolved(String text, boolean complete) {} + + public static List analyze(String fileName, String source) { + JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); + JavaFileObject file = + new SimpleJavaFileObject(URI.create("string:///" + fileName), JavaFileObject.Kind.SOURCE) { + @Override + public CharSequence getCharContent(boolean ignoreEncodingErrors) { + return source; + } + }; + JavacTask task = (JavacTask) compiler.getTask(null, null, null, List.of("-proc:none"), null, List.of(file)); + Iterable units; + try { + units = task.parse(); + } catch (IOException e) { + throw new IllegalStateException("cannot parse " + fileName, e); + } + SourcePositions positions = Trees.instance(task).getSourcePositions(); + List findings = new ArrayList<>(); + for (CompilationUnitTree unit : units) { + Map consts = collectConsts(unit); + new Scan(unit, positions, consts, source, findings).scan(unit, null); + } + findings.sort( + java.util.Comparator.comparingInt(Finding::line).thenComparingInt(Finding::column).thenComparing(Finding::kind)); + return findings; + } + + private static final class Scan extends TreePathScanner { + private final CompilationUnitTree unit; + private final SourcePositions positions; + private final Map consts; + private final String source; + private final List findings; + + Scan( + CompilationUnitTree unit, + SourcePositions positions, + Map consts, + String source, + List findings) { + this.unit = unit; + this.positions = positions; + this.consts = consts; + this.source = source; + this.findings = findings; + } + + private void report(Kind kind, Tree node) { + long start = positions.getStartPosition(unit, node); + long end = positions.getEndPosition(unit, node); + long line = unit.getLineMap().getLineNumber(start); + long column = unit.getLineMap().getColumnNumber(start); + String raw = source.substring((int) start, (int) Math.max(start, Math.min(end, source.length()))).replaceAll("\\s+", " "); + findings.add(new Finding(kind, (int) line, (int) column, raw.length() > 60 ? raw.substring(0, 57) + "..." : raw)); + } + + @Override + public Void visitLiteral(LiteralTree node, Void unused) { + Object value = node.getValue(); + boolean string = value instanceof String; + boolean ch = value instanceof Character; + if ((string || ch) && !isSearchPattern(getCurrentPath()) && !isSnippet(getCurrentPath())) { + String v = String.valueOf(value); + if (LINE_BREAK.matcher(v).find()) report(Kind.NEWLINE_LITERAL, node); + else if (string && startsALine(getCurrentPath()) && INDENT_RUN.matcher(v).find()) report(Kind.INDENT_LITERAL, node); + } + return super.visitLiteral(node, unused); + } + + @Override + public Void visitMethodInvocation(MethodInvocationTree call, Void unused) { + String method = calledName(call.getMethodSelect()); + if (method != null) { + if (JOIN_METHODS.contains(method) && !call.getArguments().isEmpty()) { + Resolved sep = resolve(call.getArguments().get(0), 0); + if (sep != null && LINE_BREAK.matcher(sep.text()).find()) report(Kind.NEWLINE_JOIN, call); + } else if (method.equals(REPEAT_METHOD) && call.getMethodSelect() instanceof MemberSelectTree ms) { + Resolved unit = resolve(ms.getExpression(), 0); + if (unit != null && unit.complete() && WHITESPACE.matcher(unit.text()).find()) report(Kind.INDENT_REPEAT, call); + } else if (method.equals(LINE_SEPARATOR) && call.getArguments().isEmpty()) { + report(Kind.NEWLINE_LITERAL, call); + } + } + return super.visitMethodInvocation(call, unused); + } + + @Override + public Void visitNewClass(NewClassTree node, Void unused) { + if (node.getIdentifier() instanceof IdentifierTree id + && id.getName().contentEquals(STRING_JOINER) + && !node.getArguments().isEmpty()) { + Resolved sep = resolve(node.getArguments().get(0), 0); + if (sep != null && LINE_BREAK.matcher(sep.text()).find()) report(Kind.NEWLINE_JOIN, node); + } + return super.visitNewClass(node, unused); + } + + private Resolved resolve(ExpressionTree expr, int depth) { + if (depth > MAX_RESOLVE_DEPTH) return null; + if (expr instanceof LiteralTree lit && lit.getValue() instanceof String s) return new Resolved(s, true); + if (expr instanceof LiteralTree lit && lit.getValue() instanceof Character c) return new Resolved(String.valueOf(c), true); + if (expr instanceof ParenthesizedTree p) return resolve(p.getExpression(), depth + 1); + if (expr instanceof TypeCastTree c) return resolve(c.getExpression(), depth + 1); + if (expr instanceof BinaryTree b && b.getKind() == Tree.Kind.PLUS) { + Resolved l = resolve(b.getLeftOperand(), depth + 1); + Resolved r = resolve(b.getRightOperand(), depth + 1); + if (l == null && r == null) return null; + return new Resolved( + (l == null ? "" : l.text()) + (r == null ? "" : r.text()), + l != null && l.complete() && r != null && r.complete()); + } + if (expr instanceof ConditionalExpressionTree c) { + // Either branch may be written; for "does it contain a line break" both count. + Resolved a = resolve(c.getTrueExpression(), depth + 1); + Resolved b = resolve(c.getFalseExpression(), depth + 1); + if (a == null && b == null) return null; + return new Resolved((a == null ? "" : a.text()) + (b == null ? "" : b.text()), false); + } + if (expr instanceof IdentifierTree id) { + ExpressionTree init = consts.get(id.getName().toString()); + return init == null ? null : resolve(init, depth + 1); + } + if (expr instanceof MemberSelectTree ms) { + // `Type.NAME` or `this.NAME`: the member name is looked up among the file's constants. + ExpressionTree init = consts.get(ms.getIdentifier().toString()); + return init == null ? null : resolve(init, depth + 1); + } + return null; + } + } + + /** + * Every {@code final} variable with an initializer whose name is declared exactly once in the + * file. A name declared more than once is left out: it is shadowed somewhere. + */ + private static Map collectConsts(CompilationUnitTree unit) { + Map seen = new HashMap<>(); + Set shadowed = new java.util.HashSet<>(); + new TreePathScanner() { + @Override + public Void visitVariable(VariableTree v, Void unused) { + String name = v.getName().toString(); + boolean isFinal = v.getModifiers().getFlags().contains(javax.lang.model.element.Modifier.FINAL); + if (seen.containsKey(name) || shadowed.contains(name) || v.getInitializer() == null || !isFinal) { + shadowed.add(name); + seen.remove(name); + } else { + seen.put(name, v.getInitializer()); + } + return super.visitVariable(v, unused); + } + }.scan(unit, null); + return seen; + } + + /** The method name a call invokes: {@code x.join(...)} is "join", {@code join(...)} is "join". */ + private static String calledName(ExpressionTree select) { + if (select instanceof MemberSelectTree ms) return ms.getIdentifier().toString(); + if (select instanceof IdentifierTree id) return id.getName().toString(); + return null; + } + + /** A string that is the right-hand part of a {@code +} follows other text, so it does not start a line. */ + private static boolean startsALine(TreePath path) { + Tree parent = path.getParentPath().getLeaf(); + return !(parent instanceof BinaryTree b && b.getKind() == Tree.Kind.PLUS && b.getRightOperand() == path.getLeaf()); + } + + private static boolean isSearchPattern(TreePath path) { + Tree leaf = path.getLeaf(); + Tree parent = path.getParentPath().getLeaf(); + if (parent instanceof ParenthesizedTree) return isSearchPattern(path.getParentPath()); + if (parent instanceof BinaryTree b && (b.getKind() == Tree.Kind.EQUAL_TO || b.getKind() == Tree.Kind.NOT_EQUAL_TO)) { + return true; + } + if (parent instanceof ConstantCaseLabelTree) return true; + return isArgument(path, SEARCH_METHODS::contains, 0) || isArgument(path, LOG_METHODS::contains, 0); + } + + private static boolean isSnippet(TreePath path) { + return isArgument(path, SNIPPET_METHOD::equals, 0); + } + + private static boolean isArgument(TreePath path, java.util.function.Predicate method, int index) { + Tree leaf = path.getLeaf(); + Tree parent = path.getParentPath().getLeaf(); + if (!(parent instanceof MethodInvocationTree call) || !(call.getMethodSelect() instanceof MemberSelectTree ms)) return false; + return method.test(ms.getIdentifier().toString()) && call.getArguments().size() > index && call.getArguments().get(index) == leaf; + } + + // ── which files the ratchet reads ────────────────────────────────────────────────────── + + /** The modules whose {@code src/main/java} holds generator source, relative to {@code server/java/}. */ + public static final List SCANNED_MODULES = + List.of("codegen-base", "codegen-spring", "codegen-plantuml", "codegen-mustache"); + + /** The writer itself: the one package that lays text out, so the one allowed to type layout. */ + private static final String WRITER_DIR = "codegen-base/src/main/java/com/metaobjects/generator/writer/"; + + /** + * Whether a file (relative to {@code server/java/}) is generator source the ratchet reads. + * Excluded by rule, never by listing: anything outside a scanned module's {@code src/main/java}, + * tests, {@code package-info.java} and the writer. + */ + public static boolean isGeneratorSource(String rel) { + String path = rel.replace('\\', '/'); + if (SCANNED_MODULES.stream().noneMatch(m -> path.startsWith(m + "/src/main/java/"))) return false; + if (!path.endsWith(".java") || path.endsWith("/package-info.java")) return false; + return !path.startsWith(WRITER_DIR); + } +} diff --git a/server/java/codegen-base/src/test/java/com/metaobjects/generator/writer/layout/LayoutRatchetTest.java b/server/java/codegen-base/src/test/java/com/metaobjects/generator/writer/layout/LayoutRatchetTest.java new file mode 100644 index 0000000000..86d062bac5 --- /dev/null +++ b/server/java/codegen-base/src/test/java/com/metaobjects/generator/writer/layout/LayoutRatchetTest.java @@ -0,0 +1,369 @@ +package com.metaobjects.generator.writer.layout; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assume.assumeTrue; + +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; +import com.metaobjects.generator.writer.layout.LayoutAnalyzer.Finding; +import com.metaobjects.generator.writer.layout.LayoutAnalyzer.Kind; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import org.junit.Test; + +/** + * The layout ratchet (ADR-0063): generator source never types layout; the writer does. + * + *

Three parts: the analyzer's own cases (layout it must catch, and writer-based code it must + * pass), the scope rule (which files are generator source, by rule and not by list) and the + * ratchet over the real modules: every file with hand-typed layout is on the allowlist with a + * reason, every allowlisted file still needs its entry, and the allowlist only shrinks. + */ +public class LayoutRatchetTest { + + private static List kinds(String body) { + return LayoutAnalyzer.analyze("Fixture.java", "class Fixture { void f() { " + body + " } }").stream() + .map(Finding::kind) + .sorted() + .toList(); + } + + private static List sorted(Kind... k) { + return Stream.of(k).sorted().toList(); + } + + // ── 1. the analyzer ────────────────────────────────────────────────────────────────── + + @Test + public void catches_a_newline_escape() { + assertEquals(sorted(Kind.NEWLINE_LITERAL), kinds("String s = \"a\\nb\";")); + assertEquals(sorted(Kind.NEWLINE_LITERAL), kinds("String s = \"a\\r\";")); + assertEquals(sorted(Kind.NEWLINE_LITERAL), kinds("sb.append('\\n');")); + } + + @Test + public void catches_a_text_block_a_percent_n_and_a_line_separator() { + assertEquals(sorted(Kind.NEWLINE_LITERAL), kinds("String s = \"\"\"\n a\n \"\"\";")); + assertEquals(sorted(Kind.NEWLINE_LITERAL), kinds("String s = String.format(\"%s%n\", x);")); + assertEquals(sorted(Kind.NEWLINE_LITERAL), kinds("String s = System.lineSeparator();")); + } + + @Test + public void catches_a_string_that_starts_with_an_indentation_run() { + assertEquals(sorted(Kind.INDENT_LITERAL), kinds("rows.add(\" \" + name);")); + assertEquals(sorted(Kind.INDENT_LITERAL), kinds("rows.add(\"\\tx\");")); + assertEquals(sorted(Kind.INDENT_LITERAL), kinds("rows.add(\" name: String;\");")); + } + + @Test + public void catches_a_join_on_a_line_break() { + assertEquals(sorted(Kind.NEWLINE_JOIN, Kind.NEWLINE_LITERAL), kinds("String.join(\"\\n\", rows);")); + assertEquals(sorted(Kind.NEWLINE_JOIN, Kind.NEWLINE_LITERAL), kinds("rows.stream().collect(Collectors.joining(\",\\n\"));")); + assertEquals(sorted(Kind.NEWLINE_JOIN, Kind.NEWLINE_LITERAL), kinds("var j = new StringJoiner(\"\\n\");")); + } + + @Test + public void catches_an_indentation_repeat() { + assertEquals(sorted(Kind.INDENT_REPEAT, Kind.INDENT_LITERAL), kinds("String pad = \" \".repeat(depth);")); + assertEquals(sorted(Kind.INDENT_REPEAT), kinds("String pad = \" \".repeat(depth * 2);")); + } + + @Test + public void a_newline_hidden_behind_a_constant_is_caught_where_it_is_used() { + String source = "class F { static final String NL = \"\\n\"; String f() { return String.join(NL, rows); } }"; + List found = LayoutAnalyzer.analyze("F.java", source); + assertEquals( + List.of(Kind.NEWLINE_LITERAL, Kind.NEWLINE_JOIN), found.stream().map(Finding::kind).toList()); + } + + @Test + public void a_constant_built_from_other_constants_is_followed() { + String source = + "class F { static final String NL = \"\\n\"; static final String SEP = \",\" + NL;" + + " String f() { return String.join(SEP, rows); } }"; + List found = LayoutAnalyzer.analyze("F.java", source).stream().map(Finding::kind).toList(); + assertEquals(List.of(Kind.NEWLINE_LITERAL, Kind.NEWLINE_JOIN), found); + } + + @Test + public void an_indentation_unit_hidden_behind_a_constant_is_caught_at_the_repeat() { + String source = "class F { static final String UNIT = \" \"; String f() { return UNIT.repeat(4); } }"; + assertEquals(List.of(Kind.INDENT_REPEAT), LayoutAnalyzer.analyze("F.java", source).stream().map(Finding::kind).toList()); + } + + @Test + public void either_branch_of_a_conditional_separator_counts() { + assertEquals(sorted(Kind.NEWLINE_JOIN, Kind.NEWLINE_LITERAL), kinds("String.join(compact ? \", \" : \",\\n\", rows);")); + } + + @Test + public void findings_carry_the_line_and_column_of_the_node() { + Finding f = LayoutAnalyzer.analyze("F.java", "class F {\n String s = \"a\\nb\";\n}").get(0); + assertEquals(2, f.line()); + assertEquals(14, f.column()); + } + + @Test + public void passes_a_generator_written_on_the_writer() { + String source = + """ + import com.metaobjects.generator.writer.JavaWriter; + + class Gen { + // Comments may say anything, including "\\n" and + // indented text: a comment is never a node. + /* + * a block comment, indented + */ + String render(Entity entity) { + JavaWriter w = new JavaWriter(); + String list = w.use("java.util.List"); + try (var b = w.block("class " + entity.name() + " {")) { + w.line("private final ", list, " names;"); + w.blank(); + w.text(\"\"\" + void check() { + return; + } + \"\"\"); + } + return w.toString(); + } + } + """; + assertEquals(List.of(), LayoutAnalyzer.analyze("Gen.java", source)); + } + + @Test + public void a_line_break_used_as_a_search_pattern_or_comparison_is_not_output() { + assertEquals(List.of(), kinds("String[] p = description.split(\"\\n\");")); + assertEquals(List.of(), kinds("if (body.contains(\"\\n\")) flag();")); + assertEquals(List.of(), kinds("String s = body.replace(\"\\r\\n\", \" \").replaceAll(\"\\n\", \" \");")); + assertEquals(List.of(), kinds("int at = body.indexOf(\" \");")); + assertEquals(List.of(), kinds("if (c == '\\n') flag();")); + assertEquals(List.of(), kinds("switch (c) { case \"\\n\" -> flag(); default -> {} }")); + assertEquals(List.of(), kinds("switch (ch) { case '\\n': flag(); break; default: break; }")); + assertEquals(List.of(), kinds("log.debug(\" Template Path: {}\", path);")); + } + + @Test + public void a_replacement_that_writes_a_line_break_is_still_output() { + assertEquals(sorted(Kind.NEWLINE_LITERAL), kinds("String s = body.replace(\";\", \";\\n\");")); + } + + @Test + public void single_spaces_joins_on_a_space_and_text_after_a_concatenation_are_not_layout() { + assertEquals(List.of(), kinds("String a = String.join(\", \", names); String b = left + \" \" + right; String c = \" \" + x;")); + } + + @Test + public void a_variable_shadowing_a_layout_constant_is_not_resolved_to_it() { + String source = "class F { String f(String SEP) { return String.join(SEP, rows); } static final String SEP = \",\\n\"; }"; + // The declaration is a finding; the join, whose SEP is the parameter, is not. + assertEquals(List.of(Kind.NEWLINE_LITERAL), LayoutAnalyzer.analyze("F.java", source).stream().map(Finding::kind).toList()); + } + + // ── 2. the scope rule ──────────────────────────────────────────────────────────────── + + @Test + public void scope_is_decided_by_rule() { + String[][] cases = { + {"codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringControllerGenerator.java", "true"}, + {"codegen-base/src/main/java/com/metaobjects/generator/direct/object/javacode/JavaCodeWriter.java", "true"}, + {"codegen-plantuml/src/main/java/com/metaobjects/generator/direct/plantuml/PlantUMLWriter.java", "true"}, + {"codegen-base/src/main/java/com/metaobjects/generator/writer/CodeWriter.java", "false"}, + {"codegen-base/src/main/java/com/metaobjects/generator/writer/JavaWriter.java", "false"}, + {"codegen-spring/src/test/java/com/metaobjects/generator/spring/Foo.java", "false"}, + {"codegen-spring/src/main/java/com/metaobjects/generator/spring/package-info.java", "false"}, + {"codegen-spring/src/main/resources/templates/x.java", "false"}, + {"metadata/src/main/java/com/metaobjects/Foo.java", "false"}, + {"codegen-spring/README.md", "false"}, + }; + for (String[] c : cases) assertEquals(c[0], Boolean.parseBoolean(c[1]), LayoutAnalyzer.isGeneratorSource(c[0])); + } + + // ── 3. the ratchet over the real modules ───────────────────────────────────────────────── + + /** {@code server/java/}: the tests run with the module as the working directory. */ + private static final Path JAVA = Path.of(System.getProperty("user.dir")).resolve("..").normalize(); + + private static final Path ALLOWLIST = Path.of(System.getProperty("user.dir"), "src/test/resources/layout-ratchet/allowlist.json"); + + /** The allowlist: {@code unconverted} and {@code exempt}, each a map from file to its written reason. */ + record Allowlist(Map unconverted, Map exempt) { + Map entries() { + Map all = new TreeMap<>(unconverted); + all.putAll(exempt); + return all; + } + } + + private static Allowlist readAllowlist(String json) { + Map raw = new Gson().fromJson(json, new TypeToken>() {}.getType()); + return new Allowlist(strings(raw.get("unconverted")), strings(raw.get("exempt"))); + } + + @SuppressWarnings("unchecked") + private static Map strings(Object o) { + return o == null ? new TreeMap<>() : new TreeMap<>((Map) o); + } + + private static final Allowlist allowlist; + private static final Map> findings = new TreeMap<>(); + + static { + try { + allowlist = readAllowlist(Files.readString(ALLOWLIST, StandardCharsets.UTF_8)); + for (String module : LayoutAnalyzer.SCANNED_MODULES) { + Path src = JAVA.resolve(module).resolve("src/main/java"); + try (Stream files = Files.walk(src)) { + for (Path f : files.filter(Files::isRegularFile).toList()) { + String rel = JAVA.relativize(f).toString().replace('\\', '/'); + if (LayoutAnalyzer.isGeneratorSource(rel)) { + findings.put(rel, LayoutAnalyzer.analyze(rel, Files.readString(f, StandardCharsets.UTF_8))); + } + } + } + } + // `-Dlayout.dump=` lists every file that types layout, to write or prune allowlist entries. + String dump = System.getProperty("layout.dump"); + if (dump != null) { + List rows = new ArrayList<>(); + findings.forEach((f, found) -> { if (!found.isEmpty()) rows.add(f + "\t" + found.size() + "\t" + found.stream().map(x -> x.kind().toString()).distinct().sorted().collect(Collectors.joining(","))); }); + Files.write(Path.of(dump), rows); + } + } catch (IOException e) { + throw new IllegalStateException(e); + } + } + + @Test + public void it_reads_every_scanned_module() { + for (String m : LayoutAnalyzer.SCANNED_MODULES) { + assertTrue(m, findings.keySet().stream().anyMatch(f -> f.startsWith(m + "/"))); + } + } + + @Test + public void no_generator_source_types_layout_unless_its_file_is_allowlisted() { + Map entries = allowlist.entries(); + List offenders = new ArrayList<>(); + findings.forEach( + (file, found) -> { + if (!found.isEmpty() && !entries.containsKey(file)) { + offenders.add(file + "\n" + found.stream().map(f -> " " + f).collect(Collectors.joining("\n"))); + } + }); + assertEquals( + "Write these lines through JavaWriter (generator/writer/) instead of typing line breaks or" + + " indentation. A file is never added to the allowlist: it only shrinks.", + List.of(), + offenders); + } + + @Test + public void every_allowlisted_file_still_needs_its_entry() { + List stale = new ArrayList<>(); + for (String file : allowlist.entries().keySet()) { + if (findings.getOrDefault(file, List.of()).isEmpty()) stale.add(file); + } + assertEquals("these files no longer type layout (or no longer exist): remove their allowlist entries", List.of(), stale); + } + + @Test + public void every_allowlisted_path_is_generator_source_that_exists() { + for (String file : allowlist.entries().keySet()) { + assertTrue(file + " is not in the ratchet's scope", LayoutAnalyzer.isGeneratorSource(file)); + assertTrue(file + " does not exist", Files.exists(JAVA.resolve(file))); + } + } + + @Test + public void every_entry_carries_a_written_reason() { + allowlist.entries().forEach((file, reason) -> assertTrue(file + " needs a reason", reason.length() > 40)); + } + + @Test + public void a_file_is_either_unconverted_or_exempt_never_both_and_each_list_is_sorted() { + for (String f : allowlist.unconverted().keySet()) assertFalse(f, allowlist.exempt().containsKey(f)); + for (Map list : List.of(allowlist.unconverted(), allowlist.exempt())) { + assertEquals(new ArrayList<>(new TreeMap<>(list).keySet()), new ArrayList<>(list.keySet())); + } + } + + /** The allowlist may only shrink. Compared with the copy at the merge base of every integration branch this checkout knows. */ + @Test + public void the_allowlist_only_shrinks() throws Exception { + List bases = mergeBaseAllowlists(); + assumeTrue("git or the integration refs are unavailable (an export or a shallow clone)", bases != null); + for (Allowlist base : bases) { + assertEquals( + "the allowlist grew since the merge base; convert the file to the writer instead", + List.of(), + growth(base, allowlist)); + } + } + + @Test + public void growth_is_an_added_entry_or_an_unconverted_file_relabelled_exempt_and_removal_is_not() { + Allowlist before = + new Allowlist(new TreeMap<>(Map.of("A.java", "r", "B.java", "r")), new TreeMap<>(Map.of("C.java", "r"))); + assertEquals(List.of(), growth(before, new Allowlist(new TreeMap<>(Map.of("A.java", "r")), new TreeMap<>()))); + assertEquals( + List.of("added D.java"), + growth(before, new Allowlist(new TreeMap<>(Map.of("A.java", "r", "D.java", "r")), new TreeMap<>(Map.of("C.java", "r"))))); + assertEquals( + List.of("relabelled B.java as exempt"), + growth(before, new Allowlist(new TreeMap<>(Map.of("A.java", "r")), new TreeMap<>(Map.of("B.java", "r", "C.java", "r"))))); + } + + /** How {@code now} grew relative to {@code before}: entries that are new, and unconverted files relabelled exempt. */ + private static List growth(Allowlist before, Allowlist now) { + List out = new ArrayList<>(); + Map had = before.entries(); + for (String f : now.entries().keySet()) if (!had.containsKey(f)) out.add("added " + f); + for (String f : now.exempt().keySet()) if (before.unconverted().containsKey(f)) out.add("relabelled " + f + " as exempt"); + return out; + } + + private static String git(String... args) { + try { + List cmd = new ArrayList<>(List.of("git", "-C", JAVA.toString())); + cmd.addAll(List.of(args)); + Process p = new ProcessBuilder(cmd).redirectError(ProcessBuilder.Redirect.DISCARD).start(); + String out = new String(p.getInputStream().readAllBytes(), StandardCharsets.UTF_8).trim(); + return p.waitFor() == 0 ? out : null; + } catch (IOException | InterruptedException e) { + return null; + } + } + + /** The allowlist as it stood at the merge base of HEAD with each integration branch; null when git or those refs are unavailable. */ + private static List mergeBaseAllowlists() { + String refs = git("for-each-ref", "--format=%(refname:short)", "refs/remotes/origin/main", "refs/remotes/origin/release/"); + if (refs == null || refs.isEmpty()) return null; + String top = git("rev-parse", "--show-toplevel"); + if (top == null) return null; + String rel = Path.of(top).relativize(ALLOWLIST).toString().replace('\\', '/'); + List out = new ArrayList<>(); + boolean reachable = false; + for (String ref : refs.split("\\s+")) { + String base = git("merge-base", "HEAD", ref); + if (base == null) continue; + reachable = true; + String text = git("show", base + ":" + rel); + if (text != null) out.add(readAllowlist(text)); + } + return reachable ? out : null; + } +} 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 new file mode 100644 index 0000000000..1ad86f3d8c --- /dev/null +++ b/server/java/codegen-base/src/test/resources/layout-ratchet/allowlist.json @@ -0,0 +1,35 @@ +{ + "$comment": "The layout ratchet's allowlist for the Java generators (ADR-0063). `unconverted`: generator source that still types its own layout; each entry names what it emits and the writer PR that converts it, and is removed when that PR lands (the test fails while a converted file keeps its entry). `exempt`: source that writes text which is not generated code; each says why. Neither list may grow: LayoutRatchetTest compares it with the copy at the branch's merge base.", + "unconverted": { + "codegen-base/src/main/java/com/metaobjects/generator/direct/FileDirectWriter.java": "Builds the FileIndentor with a hand-typed two-space indentation unit, the older indentor pipeline under the object code generators. Converts with the Java small generators and polish writer PR (W-JV-5).", + "codegen-base/src/main/java/com/metaobjects/generator/direct/object/javacode/ExtractorCodeGenerator.java": "Emits the generated entity Extractor 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-base/src/main/java/com/metaobjects/generator/direct/object/javacode/JavaCodeGenerator.java": "Configures the older object code writer with a hand-typed four-space indentation unit. Converts with the Java small generators and polish writer PR (W-JV-5).", + "codegen-base/src/main/java/com/metaobjects/generator/direct/object/javacode/JavaObjectCodeGenerator.java": "Emits the plain Java object 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/apidocs/JavaApiModelBuilder.java": "Emits the Java code samples shown in the generated API docs 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/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).", + "codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringOutputPromptGenerator.java": "Emits the output prompt 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/SpringRecordBuilder.java": "Emits the record builder source for a DTO 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/SpringRenderHelperGenerator.java": "Emits the render 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/SpringReportExportGenerator.java": "Emits the report export 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/SpringRepositoryGenerator.java": "Emits the repository interface 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/SpringTypeMapper.java": "Emits the enum class for a string-valued enum field 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/SpringValueObjectGenerator.java": "Emits the value object record by string concatenation with hand-typed line breaks and indentation. Converts with the Java small generators and polish writer PR (W-JV-5)." + }, + "exempt": { + "codegen-base/src/main/java/com/metaobjects/generator/GeneratorIOException.java": "Builds the text of an exception message with typed line breaks. It is a diagnostic for the person running the build, not code an adopter edits.", + "codegen-base/src/main/java/com/metaobjects/generator/direct/metadata/ai/MetaDataAIDocumentationGenerator.java": "Builds the one-paragraph configuration summary used in log output with typed line breaks. It is a diagnostic, not generated code.", + "codegen-base/src/main/java/com/metaobjects/generator/direct/metadata/html/MetaDataHtmlDocumentationGenerator.java": "Builds the one-paragraph configuration summary used in log output with typed line breaks. It is a diagnostic, not generated code.", + "codegen-base/src/main/java/com/metaobjects/generator/direct/metadata/html/MetaDataHtmlDocumentationWriter.java": "Emits the HTML metadata documentation page with its stylesheet. Documentation output is exempt from the writer conversion (ADR-0063; the docs and markdown emitters), because it is not code an adopter edits.", + "codegen-base/src/main/java/com/metaobjects/generator/util/HashManifest.java": "Reads and writes the hash manifest, a line-based data file the tool owns and no adopter edits. It is not generated code.", + "codegen-plantuml/src/main/java/com/metaobjects/generator/direct/plantuml/PlantUMLWriter.java": "Emits PlantUML diagram text. A diagram is documentation output, exempt from the writer conversion (ADR-0063), and not code an adopter edits." + } +} diff --git a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringRestSurfaceGoldenTest.java b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringRestSurfaceGoldenTest.java new file mode 100644 index 0000000000..0aa10abd07 --- /dev/null +++ b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringRestSurfaceGoldenTest.java @@ -0,0 +1,99 @@ +package com.metaobjects.generator.spring; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; + +import com.metaobjects.loader.MetaDataLoader; +import com.metaobjects.registry.SharedRegistryTestBase; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import java.util.stream.Stream; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +/** + * The REST surface of the Spring generators, pinned byte for byte (W-JV-2). + * + *

{@code SpringControllerGenerator}, {@code SpringRepositoryGenerator}, + * {@code SpringNamesGenerator} and {@code SpringReportExportGenerator} run over + * {@code golden/spring-rest-surface/input/meta.json}: entities with an enum, a decimal, a date, a + * to-one reference and a many-to-many through entity, a read-only projection and a served report. + * Every emitted file must equal its counterpart under {@code golden/spring-rest-surface/expected/}. + * + *

Why it exists: moving these generators onto the code writer (ADR-0063) changes how they lay + * text out, and until now the Spring module had byte-exact files for DTOs only. The expected files + * are the generators' output as they stood before any conversion. A conversion PR changes them on + * purpose, and its description lists what moved and why; a change nobody meant shows up here as a + * diff against a named file. + * + *

To rewrite the expected files after an intended change, run this test with + * {@code -Dgolden.update=true} and review the diff. + */ +public class SpringRestSurfaceGoldenTest extends SharedRegistryTestBase { + + private static final Path GOLDEN = Path.of("src/test/resources/golden/spring-rest-surface"); + private static final String UPDATE = "golden.update"; + + @Rule public TemporaryFolder tmp = new TemporaryFolder(); + + private static Map filesUnder(Path root) throws IOException { + Map files = new TreeMap<>(); + if (!Files.isDirectory(root)) return files; + try (Stream walk = Files.walk(root)) { + for (Path p : walk.filter(Files::isRegularFile).toList()) { + files.put(root.relativize(p).toString().replace('\\', '/'), Files.readString(p, StandardCharsets.UTF_8)); + } + } + return files; + } + + @Test + public void theRestSurfaceRegeneratesByteIdentical() throws Exception { + MetaDataLoader loader = + SpringTestFixtures.loadFixture( + tmp.newFolder().toPath(), + "restSurface", + Files.readString(GOLDEN.resolve("input/meta.json"), StandardCharsets.UTF_8)); + Path out = tmp.newFolder().toPath(); + Map args = new HashMap<>(); + args.put("outputDir", out.toString()); + for (var generator : + List.of( + new SpringControllerGenerator(), + new SpringRepositoryGenerator(), + new SpringNamesGenerator(), + new SpringReportExportGenerator())) { + generator.setArgs(args); + generator.execute(loader); + } + + Map actual = filesUnder(out); + if (Boolean.getBoolean(UPDATE)) { + Path expectedDir = GOLDEN.resolve("expected"); + if (Files.isDirectory(expectedDir)) { + try (Stream walk = Files.walk(expectedDir)) { + for (Path p : walk.sorted(java.util.Comparator.reverseOrder()).filter(Files::isRegularFile).toList()) Files.delete(p); + } + } + for (Map.Entry e : actual.entrySet()) { + Path target = expectedDir.resolve(e.getKey()); + Files.createDirectories(target.getParent()); + Files.writeString(target, e.getValue(), StandardCharsets.UTF_8); + } + } + + Map expected = filesUnder(GOLDEN.resolve("expected")); + assertFalse("the golden tree must not be empty", expected.isEmpty()); + assertEquals("the generated file set must match the golden tree", expected.keySet(), actual.keySet()); + for (Map.Entry e : expected.entrySet()) { + assertEquals(e.getKey() + " must be byte-identical to the golden file", e.getValue(), actual.get(e.getKey())); + } + } +} diff --git a/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/CustomerController.java b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/CustomerController.java new file mode 100644 index 0000000000..3500ca4ff0 --- /dev/null +++ b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/CustomerController.java @@ -0,0 +1,201 @@ +package acme.shop; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.metaobjects.generator.spring.runtime.ConstraintErrors; +import com.metaobjects.generator.spring.runtime.PatchValidationException; +import com.metaobjects.generator.spring.runtime.UnreadableBody; +import com.metaobjects.generator.spring.runtime.UnknownBodyKeys; +import com.metaobjects.generator.spring.runtime.ValidationIssues; +import com.metaobjects.generator.spring.runtime.RecordComponentNames; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import com.metaobjects.generator.spring.runtime.FilterParseResult; +import com.metaobjects.generator.spring.runtime.FilterParser; +import com.metaobjects.generator.spring.runtime.FilterPredicate; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.validation.Validator; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * GENERATED — REST controller for Customer entity. Implements the cross-port API contract. + * + *

Auth: these endpoints are unauthenticated. Require authentication for this path in + * your Spring Security config, e.g. {@code http.authorizeHttpRequests(a -> + * a.requestMatchers("/api/customers/**").authenticated())}. + * A row-ownership rule ("only the owner may read this row") can't be expressed in path + * config — eject this generator with {@code mvn metaobjects:eject} and hand-write those + * endpoints. + */ +@RestController +@RequestMapping("/api/customers") +public class CustomerController { + + private static final Set SORT_ALLOWLIST = Set.of("id", "name", "status", "balance", "createdAt"); + + private static final Map SORT_DEFAULT_ORDER = Map.ofEntries(); + + /** 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. */ + private static final Set SERVER_OWNED_ON_CREATE = Set.of("id"); + + /** Every field the entity declares, as named on the wire: a body key outside it is refused. */ + private static final Set KNOWN_FIELDS = Set.of("id", "name", "status", "balance", "createdAt"); + + private final CustomerRepository repository; + private final ObjectMapper objectMapper; + private final Validator validator; + + public CustomerController(CustomerRepository repository, ObjectMapper objectMapper, Validator validator) { + this.repository = repository; + this.objectMapper = objectMapper; + this.validator = validator; + } + + @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)); + } + + @GetMapping + public ResponseEntity list( + @RequestParam(required = false) Integer limit, + @RequestParam(required = false) Integer offset, + @RequestParam(required = false) String sort, + @RequestParam(required = false, name = "withCount") Integer withCount, + HttpServletRequest request) { + int actualLimit = limit != null ? limit : 50; + int actualOffset = offset != null ? offset : 0; + CustomerRepository.SortClause sortClause = null; + if (sort != null) { + sortClause = parseSort(sort); + if (sortClause == null) { + return ResponseEntity.badRequest().body(Map.of("error", "invalid_sort", "field", sort.split(":", 2)[0])); + } + } + FilterParseResult filter = FilterParser.parse( + request.getQueryString(), CustomerFilterAllowlist.FIELDS, CustomerFilterAllowlist.OPS_BY_FIELD, CustomerFilterAllowlist.DECIMAL_FIELDS, CustomerFilterAllowlist.DURATION_FIELDS); + if (filter.error() != null) { + return ResponseEntity.badRequest().body(Map.of("error", filter.error(), "field", filter.field())); + } + List filters = filter.predicates(); + List rows = repository.list(actualLimit, actualOffset, sortClause, filters); + if (withCount != null && withCount == 1) { + long total = repository.count(filters); + return ResponseEntity.ok(Map.of("rows", rows, "total", total)); + } + return ResponseEntity.ok(rows); + } + + @GetMapping("/{id}") + public ResponseEntity get(@PathVariable Long id) { + return repository.findById(id) + .>map(ResponseEntity::ok) + .orElseGet(() -> ResponseEntity.status(HttpStatus.NOT_FOUND).body(Map.of("error", "not_found"))); + } + + @PostMapping + public ResponseEntity create(@RequestBody JsonNode body) { + 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()); + } + Map __unknown = UnknownBodyKeys.refusal(body, KNOWN_FIELDS); + if (__unknown != null) { + return ResponseEntity.badRequest().body(__unknown); + } + com.fasterxml.jackson.databind.node.ObjectNode filled = given.deepCopy(); + CustomerDto dto; + try { + dto = objectMapper.treeToValue(filled, CustomerDto.class); + } catch (com.fasterxml.jackson.core.JsonProcessingException | IllegalArgumentException e) { + return ResponseEntity.badRequest().body(UnreadableBody.envelope(e)); + } + dto = new CustomerDto(null, dto.name(), dto.status(), dto.balance(), dto.createdAt()); + ValidationIssues __issues = new ValidationIssues() + .addViolationsExcept(validator.validate(dto), SERVER_OWNED_ON_CREATE); + if (!__issues.isEmpty()) { + return ResponseEntity.badRequest().body(__issues.body()); + } + try { + CustomerDto saved = repository.create(dto); + return ResponseEntity.status(HttpStatus.CREATED).body(saved); + } catch (RuntimeException e) { + 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())); + } + } + + @RequestMapping(value = "/{id}", method = { RequestMethod.PATCH, RequestMethod.PUT }) + public ResponseEntity update(@PathVariable Long id, @RequestBody JsonNode body) { + Map __unknown = UnknownBodyKeys.refusal(body, KNOWN_FIELDS); + if (__unknown != null) { + return ResponseEntity.badRequest().body(__unknown); + } + ValidationIssues __issues = new ValidationIssues(); + CustomerPatch __patch = null; + Map __assigned; + try { + __patch = CustomerPatch.fromJson(body, objectMapper); + __assigned = __patch.assignedValues(); + } catch (PatchValidationException e) { + __issues.addPatchFailure(e); + __assigned = e.assignedValues(); + } + for (Map.Entry __e : __assigned.entrySet()) { + __issues.addAt(validator.validateValue(CustomerDto.class, RecordComponentNames.escape(__e.getKey()), __e.getValue()), __e.getKey()); + } + if (!__issues.isEmpty()) { + return ResponseEntity.badRequest().body(__issues.body()); + } + final var patch = __patch; + try { + return repository.patch(id, patch) + .>map(ResponseEntity::ok) + .orElseGet(() -> ResponseEntity.status(HttpStatus.NOT_FOUND).body(Map.of("error", "not_found"))); + } catch (RuntimeException e) { + 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())); + } + } + + @DeleteMapping("/{id}") + public ResponseEntity delete(@PathVariable Long id) { + try { + if (repository.delete(id)) { + return ResponseEntity.noContent().build(); + } + return ResponseEntity.status(HttpStatus.NOT_FOUND).body(Map.of("error", "not_found")); + } catch (RuntimeException e) { + 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())); + } + } + + private static CustomerRepository.SortClause parseSort(String raw) { + 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; + return new CustomerRepository.SortClause(parts[0], dir); + } +} diff --git a/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/CustomerNames.java b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/CustomerNames.java new file mode 100644 index 0000000000..fc608750c4 --- /dev/null +++ b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/CustomerNames.java @@ -0,0 +1,43 @@ +package acme.shop; + +import java.util.Map; + +/** + * GENERATED — per-object physical database names for Customer. + */ +public abstract class CustomerNames { + + public static final String TYPE = "object"; + public static final String SUB_TYPE = "entity"; + public static final String NAME = "Customer"; + + public static final String SOURCE_PRIMARY_TYPE = "source"; + public static final String SOURCE_PRIMARY_SUB_TYPE = "rdb"; + public static final String SOURCE_PRIMARY_KIND = "table"; + public static final String SOURCE_PRIMARY_TABLE = "customers"; + + public static final String BALANCE_FIELD = "balance"; + public static final String BALANCE_COLUMN = "balance"; + public static final String CREATED_AT_FIELD = "createdAt"; + public static final String CREATED_AT_COLUMN = "created_at"; + public static final String ID_FIELD = "id"; + public static final String ID_COLUMN = "id"; + public static final String NAME_FIELD = "name"; + public static final String NAME_COLUMN = "name"; + public static final String STATUS_FIELD = "status"; + public static final String STATUS_COLUMN = "status"; + + public static final String IDENTITY_PK_TYPE = "identity"; + public static final String IDENTITY_PK_SUB_TYPE = "primary"; + public static final String IDENTITY_PK_NAME = "pk"; + + public static final Map COLUMNS_BY_FIELD = Map.ofEntries( + Map.entry("balance", BALANCE_COLUMN), + Map.entry("createdAt", CREATED_AT_COLUMN), + Map.entry("id", ID_COLUMN), + Map.entry("name", NAME_COLUMN), + Map.entry("status", STATUS_COLUMN) + ); + + protected CustomerNames() {} +} diff --git a/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/CustomerRepository.java b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/CustomerRepository.java new file mode 100644 index 0000000000..2025e52e9f --- /dev/null +++ b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/CustomerRepository.java @@ -0,0 +1,23 @@ +package acme.shop; + +import com.metaobjects.generator.spring.runtime.FilterPredicate; +import java.util.List; +import java.util.Optional; + +/** + * GENERATED interface — consumer implements with their preferred persistence layer + * (Spring Data JPA / jOOQ / plain JDBC). The matching CustomerController delegates to this interface. + */ +public interface CustomerRepository { + + /** Sort directive parsed from the cross-port ?sort=:asc|desc grammar. */ + record SortClause(String field, String direction) {} + + List list(int limit, int offset, SortClause sort, List filters); + long count(List filters); + Optional findById(Long id); + CustomerDto create(CustomerDto dto); + Optional update(Long id, CustomerDto dto); + Optional patch(Long id, CustomerPatch patch); + boolean delete(Long id); +} diff --git a/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/CustomerStatusTotalsController.java b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/CustomerStatusTotalsController.java new file mode 100644 index 0000000000..c26d55624d --- /dev/null +++ b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/CustomerStatusTotalsController.java @@ -0,0 +1,125 @@ +package acme.shop; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import com.metaobjects.generator.spring.runtime.FilterParseResult; +import com.metaobjects.generator.spring.runtime.FilterParser; +import com.metaobjects.generator.spring.runtime.FilterPredicate; +import jakarta.servlet.http.HttpServletRequest; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * GENERATED — READ-ONLY REST controller for the CustomerStatusTotals report. + * Implements the cross-port API contract: GET list; POST answers + * 405 {"error": "method_not_allowed"}. A report has no identity, so no item + * route is mounted. + * + *

Auth: these read endpoints are unauthenticated. Require authentication for this path + * in your Spring Security config, e.g. {@code http.authorizeHttpRequests(a -> + * a.requestMatchers("/api/customer_status_totals/**").authenticated())}. + * A row-ownership rule ("only the owner may read this row") can't be expressed in path + * config — eject this generator with {@code mvn metaobjects:eject} and hand-write those + * endpoints. + */ +@RestController +@RequestMapping("/api/customer_status_totals") +public class CustomerStatusTotalsController { + + private static final Set SORT_ALLOWLIST = Set.of("status", "customers", "activeCustomers"); + + private static final Map SORT_DEFAULT_ORDER = Map.ofEntries(); + + private final CustomerStatusTotalsRepository repository; + + public CustomerStatusTotalsController(CustomerStatusTotalsRepository repository) { + this.repository = repository; + } + + @GetMapping + public ResponseEntity list( + @RequestParam(required = false) String limit, + @RequestParam(required = false) String offset, + @RequestParam(required = false) String sort, + @RequestParam(required = false, name = "withCount") Integer withCount, + HttpServletRequest request) { + final int maxRows = 10000; + Integer requestedLimit = null; + if (limit != null) { + Long parsed = parseBound(limit, 1); + if (parsed == null) { + return ResponseEntity.badRequest().body(Map.of("error", "pagination.invalid_value", "param", "limit", "value", limit, "expected", "an integer from 1 to " + maxRows)); + } + if (parsed > maxRows) { + return ResponseEntity.badRequest().body(Map.of("error", "report_too_large", "maxRows", maxRows)); + } + requestedLimit = parsed.intValue(); + } + int actualOffset = 0; + if (offset != null) { + Long parsed = parseBound(offset, 0); + if (parsed == null) { + return ResponseEntity.badRequest().body(Map.of("error", "pagination.invalid_value", "param", "offset", "value", offset, "expected", "a non-negative integer (0 or more)")); + } + actualOffset = (int) Math.min(parsed, Integer.MAX_VALUE); + } + CustomerStatusTotalsRepository.SortClause sortClause = null; + if (sort != null) { + sortClause = parseSort(sort); + if (sortClause == null) { + return ResponseEntity.badRequest().body(Map.of("error", "invalid_sort", "field", sort.split(":", 2)[0])); + } + } + FilterParseResult filter = FilterParser.parse( + request.getQueryString(), CustomerStatusTotalsFilterAllowlist.FIELDS, CustomerStatusTotalsFilterAllowlist.OPS_BY_FIELD, CustomerStatusTotalsFilterAllowlist.DECIMAL_FIELDS, CustomerStatusTotalsFilterAllowlist.DURATION_FIELDS); + if (filter.error() != null) { + return ResponseEntity.badRequest().body(Map.of("error", filter.error(), "field", filter.field())); + } + List filters = filter.predicates(); + List rows = repository.list(requestedLimit != null ? requestedLimit : maxRows + 1, actualOffset, sortClause, filters); + if (requestedLimit == null && rows.size() > maxRows) { + return ResponseEntity.badRequest().body(Map.of("error", "report_too_large", "maxRows", maxRows)); + } + if (withCount != null && withCount == 1) { + long total = repository.count(filters); + return ResponseEntity.ok(Map.of("rows", rows, "total", total)); + } + return ResponseEntity.ok(rows); + } + + /** A page bound as an integer of at least {@code min}, or null when it is not one. */ + private static Long parseBound(String raw, long min) { + try { + long n = Long.parseLong(raw); + return n >= min ? n : null; + } catch (NumberFormatException e) { + return null; + } + } + + @PostMapping + public ResponseEntity create() { + return methodNotAllowed("POST"); + } + + private static ResponseEntity methodNotAllowed(String verb) { + return ResponseEntity.status(HttpStatus.METHOD_NOT_ALLOWED) + .body(Map.of("error", "method_not_allowed", + "message", verb + " is not supported on a report (read-only).")); + } + + private static CustomerStatusTotalsRepository.SortClause parseSort(String raw) { + 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; + return new CustomerStatusTotalsRepository.SortClause(parts[0], dir); + } +} diff --git a/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/CustomerStatusTotalsExport.java b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/CustomerStatusTotalsExport.java new file mode 100644 index 0000000000..544cb0a84b --- /dev/null +++ b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/CustomerStatusTotalsExport.java @@ -0,0 +1,41 @@ +package acme.shop; + +import java.util.List; + +/** + * GENERATED — the export of the CustomerStatusTotals report: its columns in + * derived-field order, each cell's wire form, and the CSV and XML bodies. The + * route reads {@link #MAX_ROWS}; the shared {@link ReportExportWriter} writes the bytes. + */ +public final class CustomerStatusTotalsExport { + + private CustomerStatusTotalsExport() {} + + /** The most rows one export answers; one more is 400 export_too_large. */ + public static final int MAX_ROWS = 100000; + + /** The XML root element and the report's name. */ + public static final String ROOT = "CustomerStatusTotals"; + + /** The derived fields, in order: the CSV header row and the XML element names. */ + public static final List FIELDS = List.of("status", "customers", "activeCustomers"); + + /** One row's cells in wire form: currency as integer minor units, a date as YYYY-MM-DD, + * a decimal as the wire setting writes it, a boolean as true/false, null as null. */ + public static List cells(CustomerStatusTotalsDto row) { + return List.of( + ReportExportWriter.text(row.status()), + ReportExportWriter.raw(row.customers()), + ReportExportWriter.raw(row.activeCustomers())); + } + + /** The rows as RFC 4180 CSV bytes (UTF-8). */ + public static byte[] csv(List rows) { + return ReportExportWriter.csv(FIELDS, rows.stream().map(CustomerStatusTotalsExport::cells).toList()); + } + + /** The rows as XML bytes (UTF-8, no declaration). */ + public static byte[] xml(List rows) { + return ReportExportWriter.xml(ROOT, FIELDS, rows.stream().map(CustomerStatusTotalsExport::cells).toList()); + } +} diff --git a/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/CustomerStatusTotalsRepository.java b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/CustomerStatusTotalsRepository.java new file mode 100644 index 0000000000..beaaf623ef --- /dev/null +++ b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/CustomerStatusTotalsRepository.java @@ -0,0 +1,20 @@ +package acme.shop; + +import com.metaobjects.generator.spring.runtime.FilterPredicate; +import java.util.List; + +/** + * GENERATED interface — consumer implements with their preferred persistence layer + * (Spring Data JPA / jOOQ / plain JDBC). The matching CustomerStatusTotalsController delegates to this interface. + * + *

READ-ONLY: CustomerStatusTotals is a report over a database view, so there is no write method to + * implement. Its controller answers every write verb with 405.

+ */ +public interface CustomerStatusTotalsRepository { + + /** Sort directive parsed from the cross-port ?sort=:asc|desc grammar. */ + record SortClause(String field, String direction) {} + + List list(int limit, int offset, SortClause sort, List filters); + long count(List filters); +} diff --git a/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/OrderController.java b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/OrderController.java new file mode 100644 index 0000000000..106052f947 --- /dev/null +++ b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/OrderController.java @@ -0,0 +1,206 @@ +package acme.shop; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.metaobjects.generator.spring.runtime.ConstraintErrors; +import com.metaobjects.generator.spring.runtime.PatchValidationException; +import com.metaobjects.generator.spring.runtime.UnreadableBody; +import com.metaobjects.generator.spring.runtime.UnknownBodyKeys; +import com.metaobjects.generator.spring.runtime.ValidationIssues; +import com.metaobjects.generator.spring.runtime.RecordComponentNames; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import com.metaobjects.generator.spring.runtime.FilterParseResult; +import com.metaobjects.generator.spring.runtime.FilterParser; +import com.metaobjects.generator.spring.runtime.FilterPredicate; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.validation.Validator; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * GENERATED — REST controller for Order entity. Implements the cross-port API contract. + * + *

Auth: these endpoints are unauthenticated. Require authentication for this path in + * your Spring Security config, e.g. {@code http.authorizeHttpRequests(a -> + * a.requestMatchers("/api/orders/**").authenticated())}. + * A row-ownership rule ("only the owner may read this row") can't be expressed in path + * config — eject this generator with {@code mvn metaobjects:eject} and hand-write those + * endpoints. + */ +@RestController +@RequestMapping("/api/orders") +public class OrderController { + + private static final Set SORT_ALLOWLIST = Set.of("id", "customerId", "total", "placedOn", "rush"); + + private static final Map SORT_DEFAULT_ORDER = Map.ofEntries(); + + /** 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. */ + private static final Set SERVER_OWNED_ON_CREATE = Set.of("id"); + + /** Every field the entity declares, as named on the wire: a body key outside it is refused. */ + private static final Set KNOWN_FIELDS = Set.of("id", "customerId", "total", "placedOn", "rush"); + + private final OrderRepository repository; + private final ObjectMapper objectMapper; + private final Validator validator; + + public OrderController(OrderRepository repository, ObjectMapper objectMapper, Validator validator) { + this.repository = repository; + this.objectMapper = objectMapper; + this.validator = validator; + } + + @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)); + } + + @GetMapping + public ResponseEntity list( + @RequestParam(required = false) Integer limit, + @RequestParam(required = false) Integer offset, + @RequestParam(required = false) String sort, + @RequestParam(required = false, name = "withCount") Integer withCount, + HttpServletRequest request) { + int actualLimit = limit != null ? limit : 50; + int actualOffset = offset != null ? offset : 0; + OrderRepository.SortClause sortClause = null; + if (sort != null) { + sortClause = parseSort(sort); + if (sortClause == null) { + return ResponseEntity.badRequest().body(Map.of("error", "invalid_sort", "field", sort.split(":", 2)[0])); + } + } + FilterParseResult filter = FilterParser.parse( + request.getQueryString(), OrderFilterAllowlist.FIELDS, OrderFilterAllowlist.OPS_BY_FIELD, OrderFilterAllowlist.DECIMAL_FIELDS, OrderFilterAllowlist.DURATION_FIELDS); + if (filter.error() != null) { + return ResponseEntity.badRequest().body(Map.of("error", filter.error(), "field", filter.field())); + } + List filters = filter.predicates(); + List rows = repository.list(actualLimit, actualOffset, sortClause, filters); + if (withCount != null && withCount == 1) { + long total = repository.count(filters); + return ResponseEntity.ok(Map.of("rows", rows, "total", total)); + } + return ResponseEntity.ok(rows); + } + + @GetMapping("/{id}") + public ResponseEntity get(@PathVariable Long id) { + return repository.findById(id) + .>map(ResponseEntity::ok) + .orElseGet(() -> ResponseEntity.status(HttpStatus.NOT_FOUND).body(Map.of("error", "not_found"))); + } + + @PostMapping + public ResponseEntity create(@RequestBody JsonNode body) { + 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()); + } + Map __unknown = UnknownBodyKeys.refusal(body, KNOWN_FIELDS); + if (__unknown != null) { + return ResponseEntity.badRequest().body(__unknown); + } + com.fasterxml.jackson.databind.node.ObjectNode filled = given.deepCopy(); + OrderDto dto; + try { + dto = objectMapper.treeToValue(filled, OrderDto.class); + } catch (com.fasterxml.jackson.core.JsonProcessingException | IllegalArgumentException e) { + return ResponseEntity.badRequest().body(UnreadableBody.envelope(e)); + } + dto = new OrderDto(null, dto.customerId(), dto.total(), dto.placedOn(), dto.rush()); + ValidationIssues __issues = new ValidationIssues() + .addViolationsExcept(validator.validate(dto), SERVER_OWNED_ON_CREATE); + if (!__issues.isEmpty()) { + return ResponseEntity.badRequest().body(__issues.body()); + } + try { + OrderDto saved = repository.create(dto); + return ResponseEntity.status(HttpStatus.CREATED).body(saved); + } catch (RuntimeException e) { + 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())); + } + } + + @RequestMapping(value = "/{id}", method = { RequestMethod.PATCH, RequestMethod.PUT }) + public ResponseEntity update(@PathVariable Long id, @RequestBody JsonNode body) { + Map __unknown = UnknownBodyKeys.refusal(body, KNOWN_FIELDS); + if (__unknown != null) { + return ResponseEntity.badRequest().body(__unknown); + } + ValidationIssues __issues = new ValidationIssues(); + OrderPatch __patch = null; + Map __assigned; + try { + __patch = OrderPatch.fromJson(body, objectMapper); + __assigned = __patch.assignedValues(); + } catch (PatchValidationException e) { + __issues.addPatchFailure(e); + __assigned = e.assignedValues(); + } + for (Map.Entry __e : __assigned.entrySet()) { + __issues.addAt(validator.validateValue(OrderDto.class, RecordComponentNames.escape(__e.getKey()), __e.getValue()), __e.getKey()); + } + if (!__issues.isEmpty()) { + return ResponseEntity.badRequest().body(__issues.body()); + } + final var patch = __patch; + try { + return repository.patch(id, patch) + .>map(ResponseEntity::ok) + .orElseGet(() -> ResponseEntity.status(HttpStatus.NOT_FOUND).body(Map.of("error", "not_found"))); + } catch (RuntimeException e) { + 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())); + } + } + + @DeleteMapping("/{id}") + public ResponseEntity delete(@PathVariable Long id) { + try { + if (repository.delete(id)) { + return ResponseEntity.noContent().build(); + } + return ResponseEntity.status(HttpStatus.NOT_FOUND).body(Map.of("error", "not_found")); + } catch (RuntimeException e) { + 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())); + } + } + + @GetMapping("/{id}/tags") + public ResponseEntity> findTags(@PathVariable Long id) { + return ResponseEntity.ok(repository.findTags(id)); + } + + private static OrderRepository.SortClause parseSort(String raw) { + 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; + return new OrderRepository.SortClause(parts[0], dir); + } +} diff --git a/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/OrderNames.java b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/OrderNames.java new file mode 100644 index 0000000000..31f2280b21 --- /dev/null +++ b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/OrderNames.java @@ -0,0 +1,46 @@ +package acme.shop; + +import java.util.Map; + +/** + * GENERATED — per-object physical database names for Order. + */ +public abstract class OrderNames { + + public static final String TYPE = "object"; + public static final String SUB_TYPE = "entity"; + public static final String NAME = "Order"; + + public static final String SOURCE_PRIMARY_TYPE = "source"; + public static final String SOURCE_PRIMARY_SUB_TYPE = "rdb"; + public static final String SOURCE_PRIMARY_KIND = "table"; + public static final String SOURCE_PRIMARY_TABLE = "orders"; + + public static final String CUSTOMER_ID_FIELD = "customerId"; + public static final String CUSTOMER_ID_COLUMN = "customer_id"; + public static final String ID_FIELD = "id"; + public static final String ID_COLUMN = "id"; + public static final String PLACED_ON_FIELD = "placedOn"; + public static final String PLACED_ON_COLUMN = "placed_on"; + public static final String RUSH_FIELD = "rush"; + public static final String RUSH_COLUMN = "rush"; + public static final String TOTAL_FIELD = "total"; + public static final String TOTAL_COLUMN = "total"; + + public static final String IDENTITY_FK_CUSTOMER_TYPE = "identity"; + public static final String IDENTITY_FK_CUSTOMER_SUB_TYPE = "reference"; + public static final String IDENTITY_FK_CUSTOMER_NAME = "fkCustomer"; + public static final String IDENTITY_PK_TYPE = "identity"; + public static final String IDENTITY_PK_SUB_TYPE = "primary"; + public static final String IDENTITY_PK_NAME = "pk"; + + public static final Map COLUMNS_BY_FIELD = Map.ofEntries( + Map.entry("customerId", CUSTOMER_ID_COLUMN), + Map.entry("id", ID_COLUMN), + Map.entry("placedOn", PLACED_ON_COLUMN), + Map.entry("rush", RUSH_COLUMN), + Map.entry("total", TOTAL_COLUMN) + ); + + protected OrderNames() {} +} diff --git a/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/OrderRepository.java b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/OrderRepository.java new file mode 100644 index 0000000000..11d577eb94 --- /dev/null +++ b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/OrderRepository.java @@ -0,0 +1,31 @@ +package acme.shop; + +import com.metaobjects.generator.spring.runtime.FilterPredicate; +import java.util.List; +import java.util.Optional; + +/** + * GENERATED interface — consumer implements with their preferred persistence layer + * (Spring Data JPA / jOOQ / plain JDBC). The matching OrderController delegates to this interface. + */ +public interface OrderRepository { + + /** Sort directive parsed from the cross-port ?sort=:asc|desc grammar. */ + record SortClause(String field, String direction) {} + + List list(int limit, int offset, SortClause sort, List filters); + long count(List filters); + Optional findById(Long id); + OrderDto create(OrderDto dto); + Optional update(Long id, OrderDto dto); + Optional patch(Long id, OrderPatch patch); + boolean delete(Long id); + + /** M:N traversal: the Tag rows related to this Order through OrderTag. */ + List findTags(Long sourceId); + + /** Reverse nav: the Order rows whose customerId FK points at the given Customer id (single indexed query). */ + List findByCustomer(Long customerId); + /** Reverse nav (batched, anti-N+1): the Order rows whose customerId FK is IN the given Customer ids. */ + List findByCustomerIn(List customerIds); +} diff --git a/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/OrderSummaryController.java b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/OrderSummaryController.java new file mode 100644 index 0000000000..90befd6bd0 --- /dev/null +++ b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/OrderSummaryController.java @@ -0,0 +1,107 @@ +package acme.shop; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import com.metaobjects.generator.spring.runtime.FilterParseResult; +import com.metaobjects.generator.spring.runtime.FilterParser; +import com.metaobjects.generator.spring.runtime.FilterPredicate; +import jakarta.servlet.http.HttpServletRequest; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * GENERATED — READ-ONLY REST controller for the OrderSummary projection. + * Implements the cross-port API contract: GET list + GET by id; every write + * verb answers 405 {"error": "method_not_allowed"}. + * + *

Auth: these read endpoints are unauthenticated. Require authentication for this path + * in your Spring Security config, e.g. {@code http.authorizeHttpRequests(a -> + * a.requestMatchers("/api/order_summaries/**").authenticated())}. + * A row-ownership rule ("only the owner may read this row") can't be expressed in path + * config — eject this generator with {@code mvn metaobjects:eject} and hand-write those + * endpoints. + */ +@RestController +@RequestMapping("/api/order_summaries") +public class OrderSummaryController { + + private static final Set SORT_ALLOWLIST = Set.of("id", "total", "placedOn"); + + private static final Map SORT_DEFAULT_ORDER = Map.ofEntries(); + + private final OrderSummaryRepository repository; + + public OrderSummaryController(OrderSummaryRepository repository) { + this.repository = repository; + } + + @GetMapping + public ResponseEntity list( + @RequestParam(required = false) Integer limit, + @RequestParam(required = false) Integer offset, + @RequestParam(required = false) String sort, + @RequestParam(required = false, name = "withCount") Integer withCount, + HttpServletRequest request) { + int actualLimit = limit != null ? limit : 50; + int actualOffset = offset != null ? offset : 0; + OrderSummaryRepository.SortClause sortClause = null; + if (sort != null) { + sortClause = parseSort(sort); + if (sortClause == null) { + return ResponseEntity.badRequest().body(Map.of("error", "invalid_sort", "field", sort.split(":", 2)[0])); + } + } + FilterParseResult filter = FilterParser.parse( + request.getQueryString(), OrderSummaryFilterAllowlist.FIELDS, OrderSummaryFilterAllowlist.OPS_BY_FIELD, OrderSummaryFilterAllowlist.DECIMAL_FIELDS, OrderSummaryFilterAllowlist.DURATION_FIELDS); + if (filter.error() != null) { + return ResponseEntity.badRequest().body(Map.of("error", filter.error(), "field", filter.field())); + } + List filters = filter.predicates(); + List rows = repository.list(actualLimit, actualOffset, sortClause, filters); + if (withCount != null && withCount == 1) { + long total = repository.count(filters); + return ResponseEntity.ok(Map.of("rows", rows, "total", total)); + } + return ResponseEntity.ok(rows); + } + + @GetMapping("/{id}") + public ResponseEntity get(@PathVariable Long id) { + return repository.findById(id) + .>map(ResponseEntity::ok) + .orElseGet(() -> ResponseEntity.status(HttpStatus.NOT_FOUND).body(Map.of("error", "not_found"))); + } + + @PostMapping + public ResponseEntity create() { + return methodNotAllowed("POST"); + } + + @RequestMapping(value = "/{id}", method = { RequestMethod.PATCH, RequestMethod.PUT, RequestMethod.DELETE }) + public ResponseEntity rejectItemWrite(@PathVariable Long id, HttpServletRequest request) { + return methodNotAllowed(request.getMethod()); + } + + private static ResponseEntity methodNotAllowed(String verb) { + return ResponseEntity.status(HttpStatus.METHOD_NOT_ALLOWED) + .body(Map.of("error", "method_not_allowed", + "message", verb + " is not supported on a projection (read-only).")); + } + + private static OrderSummaryRepository.SortClause parseSort(String raw) { + 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; + return new OrderSummaryRepository.SortClause(parts[0], dir); + } +} diff --git a/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/OrderSummaryNames.java b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/OrderSummaryNames.java new file mode 100644 index 0000000000..55f20993c1 --- /dev/null +++ b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/OrderSummaryNames.java @@ -0,0 +1,37 @@ +package acme.shop; + +import java.util.Map; + +/** + * GENERATED — per-object physical database names for OrderSummary. + */ +public abstract class OrderSummaryNames { + + public static final String TYPE = "object"; + public static final String SUB_TYPE = "projection"; + public static final String NAME = "OrderSummary"; + + public static final String SOURCE_PRIMARY_TYPE = "source"; + public static final String SOURCE_PRIMARY_SUB_TYPE = "rdb"; + public static final String SOURCE_PRIMARY_KIND = "view"; + public static final String SOURCE_PRIMARY_VIEW = "v_order_summary"; + + public static final String ID_FIELD = "id"; + public static final String ID_COLUMN = "id"; + public static final String PLACED_ON_FIELD = "placedOn"; + public static final String PLACED_ON_COLUMN = "placed_on"; + public static final String TOTAL_FIELD = "total"; + public static final String TOTAL_COLUMN = "total"; + + public static final String IDENTITY_PK_TYPE = "identity"; + public static final String IDENTITY_PK_SUB_TYPE = "primary"; + public static final String IDENTITY_PK_NAME = "pk"; + + public static final Map COLUMNS_BY_FIELD = Map.ofEntries( + Map.entry("id", ID_COLUMN), + Map.entry("placedOn", PLACED_ON_COLUMN), + Map.entry("total", TOTAL_COLUMN) + ); + + protected OrderSummaryNames() {} +} diff --git a/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/OrderSummaryRepository.java b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/OrderSummaryRepository.java new file mode 100644 index 0000000000..9412e6f4f9 --- /dev/null +++ b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/OrderSummaryRepository.java @@ -0,0 +1,22 @@ +package acme.shop; + +import com.metaobjects.generator.spring.runtime.FilterPredicate; +import java.util.List; +import java.util.Optional; + +/** + * GENERATED interface — consumer implements with their preferred persistence layer + * (Spring Data JPA / jOOQ / plain JDBC). The matching OrderSummaryController delegates to this interface. + * + *

READ-ONLY: OrderSummary is a projection over a database view, so there is no write method to + * implement. Its controller answers every write verb with 405.

+ */ +public interface OrderSummaryRepository { + + /** Sort directive parsed from the cross-port ?sort=:asc|desc grammar. */ + record SortClause(String field, String direction) {} + + List list(int limit, int offset, SortClause sort, List filters); + long count(List filters); + Optional findById(Long id); +} diff --git a/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/OrderTagController.java b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/OrderTagController.java new file mode 100644 index 0000000000..0e1524b837 --- /dev/null +++ b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/OrderTagController.java @@ -0,0 +1,200 @@ +package acme.shop; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.metaobjects.generator.spring.runtime.ConstraintErrors; +import com.metaobjects.generator.spring.runtime.PatchValidationException; +import com.metaobjects.generator.spring.runtime.UnreadableBody; +import com.metaobjects.generator.spring.runtime.UnknownBodyKeys; +import com.metaobjects.generator.spring.runtime.ValidationIssues; +import com.metaobjects.generator.spring.runtime.RecordComponentNames; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import com.metaobjects.generator.spring.runtime.FilterParseResult; +import com.metaobjects.generator.spring.runtime.FilterParser; +import com.metaobjects.generator.spring.runtime.FilterPredicate; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.validation.Validator; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * GENERATED — REST controller for OrderTag entity. Implements the cross-port API contract. + * + *

Auth: these endpoints are unauthenticated. Require authentication for this path in + * your Spring Security config, e.g. {@code http.authorizeHttpRequests(a -> + * a.requestMatchers("/api/order_tags/**").authenticated())}. + * A row-ownership rule ("only the owner may read this row") can't be expressed in path + * config — eject this generator with {@code mvn metaobjects:eject} and hand-write those + * endpoints. + */ +@RestController +@RequestMapping("/api/order_tags") +public class OrderTagController { + + private static final Set SORT_ALLOWLIST = Set.of("orderId", "tagId"); + + private static final Map SORT_DEFAULT_ORDER = Map.ofEntries(); + + /** 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. */ + private static final Set SERVER_OWNED_ON_CREATE = Set.of("orderId", "tagId"); + + /** Every field the entity declares, as named on the wire: a body key outside it is refused. */ + private static final Set KNOWN_FIELDS = Set.of("orderId", "tagId"); + + private final OrderTagRepository repository; + private final ObjectMapper objectMapper; + private final Validator validator; + + public OrderTagController(OrderTagRepository repository, ObjectMapper objectMapper, Validator validator) { + this.repository = repository; + this.objectMapper = objectMapper; + this.validator = validator; + } + + @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)); + } + + @GetMapping + public ResponseEntity list( + @RequestParam(required = false) Integer limit, + @RequestParam(required = false) Integer offset, + @RequestParam(required = false) String sort, + @RequestParam(required = false, name = "withCount") Integer withCount, + HttpServletRequest request) { + int actualLimit = limit != null ? limit : 50; + int actualOffset = offset != null ? offset : 0; + OrderTagRepository.SortClause sortClause = null; + if (sort != null) { + sortClause = parseSort(sort); + if (sortClause == null) { + return ResponseEntity.badRequest().body(Map.of("error", "invalid_sort", "field", sort.split(":", 2)[0])); + } + } + FilterParseResult filter = FilterParser.parse( + request.getQueryString(), OrderTagFilterAllowlist.FIELDS, OrderTagFilterAllowlist.OPS_BY_FIELD, OrderTagFilterAllowlist.DECIMAL_FIELDS, OrderTagFilterAllowlist.DURATION_FIELDS); + if (filter.error() != null) { + return ResponseEntity.badRequest().body(Map.of("error", filter.error(), "field", filter.field())); + } + List filters = filter.predicates(); + List rows = repository.list(actualLimit, actualOffset, sortClause, filters); + if (withCount != null && withCount == 1) { + long total = repository.count(filters); + return ResponseEntity.ok(Map.of("rows", rows, "total", total)); + } + return ResponseEntity.ok(rows); + } + + @GetMapping("/{id}") + public ResponseEntity get(@PathVariable Long id) { + return repository.findById(id) + .>map(ResponseEntity::ok) + .orElseGet(() -> ResponseEntity.status(HttpStatus.NOT_FOUND).body(Map.of("error", "not_found"))); + } + + @PostMapping + public ResponseEntity create(@RequestBody JsonNode body) { + 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()); + } + Map __unknown = UnknownBodyKeys.refusal(body, KNOWN_FIELDS); + if (__unknown != null) { + return ResponseEntity.badRequest().body(__unknown); + } + com.fasterxml.jackson.databind.node.ObjectNode filled = given.deepCopy(); + OrderTagDto dto; + try { + dto = objectMapper.treeToValue(filled, OrderTagDto.class); + } catch (com.fasterxml.jackson.core.JsonProcessingException | IllegalArgumentException e) { + return ResponseEntity.badRequest().body(UnreadableBody.envelope(e)); + } + ValidationIssues __issues = new ValidationIssues() + .addViolationsExcept(validator.validate(dto), SERVER_OWNED_ON_CREATE); + if (!__issues.isEmpty()) { + return ResponseEntity.badRequest().body(__issues.body()); + } + try { + OrderTagDto saved = repository.create(dto); + return ResponseEntity.status(HttpStatus.CREATED).body(saved); + } catch (RuntimeException e) { + 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())); + } + } + + @RequestMapping(value = "/{id}", method = { RequestMethod.PATCH, RequestMethod.PUT }) + public ResponseEntity update(@PathVariable Long id, @RequestBody JsonNode body) { + Map __unknown = UnknownBodyKeys.refusal(body, KNOWN_FIELDS); + if (__unknown != null) { + return ResponseEntity.badRequest().body(__unknown); + } + ValidationIssues __issues = new ValidationIssues(); + OrderTagPatch __patch = null; + Map __assigned; + try { + __patch = OrderTagPatch.fromJson(body, objectMapper); + __assigned = __patch.assignedValues(); + } catch (PatchValidationException e) { + __issues.addPatchFailure(e); + __assigned = e.assignedValues(); + } + for (Map.Entry __e : __assigned.entrySet()) { + __issues.addAt(validator.validateValue(OrderTagDto.class, RecordComponentNames.escape(__e.getKey()), __e.getValue()), __e.getKey()); + } + if (!__issues.isEmpty()) { + return ResponseEntity.badRequest().body(__issues.body()); + } + final var patch = __patch; + try { + return repository.patch(id, patch) + .>map(ResponseEntity::ok) + .orElseGet(() -> ResponseEntity.status(HttpStatus.NOT_FOUND).body(Map.of("error", "not_found"))); + } catch (RuntimeException e) { + 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())); + } + } + + @DeleteMapping("/{id}") + public ResponseEntity delete(@PathVariable Long id) { + try { + if (repository.delete(id)) { + return ResponseEntity.noContent().build(); + } + return ResponseEntity.status(HttpStatus.NOT_FOUND).body(Map.of("error", "not_found")); + } catch (RuntimeException e) { + 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())); + } + } + + private static OrderTagRepository.SortClause parseSort(String raw) { + 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; + return new OrderTagRepository.SortClause(parts[0], dir); + } +} diff --git a/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/OrderTagNames.java b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/OrderTagNames.java new file mode 100644 index 0000000000..b9c03857dc --- /dev/null +++ b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/OrderTagNames.java @@ -0,0 +1,40 @@ +package acme.shop; + +import java.util.Map; + +/** + * GENERATED — per-object physical database names for OrderTag. + */ +public abstract class OrderTagNames { + + public static final String TYPE = "object"; + public static final String SUB_TYPE = "entity"; + public static final String NAME = "OrderTag"; + + public static final String SOURCE_PRIMARY_TYPE = "source"; + public static final String SOURCE_PRIMARY_SUB_TYPE = "rdb"; + public static final String SOURCE_PRIMARY_KIND = "table"; + public static final String SOURCE_PRIMARY_TABLE = "order_tags"; + + public static final String ORDER_ID_FIELD = "orderId"; + public static final String ORDER_ID_COLUMN = "order_id"; + public static final String TAG_ID_FIELD = "tagId"; + public static final String TAG_ID_COLUMN = "tag_id"; + + public static final String IDENTITY_FK_ORDER_TYPE = "identity"; + public static final String IDENTITY_FK_ORDER_SUB_TYPE = "reference"; + public static final String IDENTITY_FK_ORDER_NAME = "fkOrder"; + public static final String IDENTITY_FK_TAG_TYPE = "identity"; + public static final String IDENTITY_FK_TAG_SUB_TYPE = "reference"; + public static final String IDENTITY_FK_TAG_NAME = "fkTag"; + public static final String IDENTITY_PK_TYPE = "identity"; + public static final String IDENTITY_PK_SUB_TYPE = "primary"; + public static final String IDENTITY_PK_NAME = "pk"; + + public static final Map COLUMNS_BY_FIELD = Map.ofEntries( + Map.entry("orderId", ORDER_ID_COLUMN), + Map.entry("tagId", TAG_ID_COLUMN) + ); + + protected OrderTagNames() {} +} diff --git a/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/OrderTagRepository.java b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/OrderTagRepository.java new file mode 100644 index 0000000000..931670c68b --- /dev/null +++ b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/OrderTagRepository.java @@ -0,0 +1,33 @@ +package acme.shop; + +import com.metaobjects.generator.spring.runtime.FilterPredicate; +import java.util.List; +import java.util.Optional; + +/** + * GENERATED interface — consumer implements with their preferred persistence layer + * (Spring Data JPA / jOOQ / plain JDBC). The matching OrderTagController delegates to this interface. + */ +public interface OrderTagRepository { + + /** Sort directive parsed from the cross-port ?sort=:asc|desc grammar. */ + record SortClause(String field, String direction) {} + + List list(int limit, int offset, SortClause sort, List filters); + long count(List filters); + Optional findById(Long id); + OrderTagDto create(OrderTagDto dto); + Optional update(Long id, OrderTagDto dto); + Optional patch(Long id, OrderTagPatch patch); + boolean delete(Long id); + + /** Reverse nav: the OrderTag rows whose orderId FK points at the given Order id (single indexed query). */ + List findByOrder(Long orderId); + /** Reverse nav (batched, anti-N+1): the OrderTag rows whose orderId FK is IN the given Order ids. */ + List findByOrderIn(List orderIds); + + /** Reverse nav: the OrderTag rows whose tagId FK points at the given Tag id (single indexed query). */ + List findByTag(Long tagId); + /** Reverse nav (batched, anti-N+1): the OrderTag rows whose tagId FK is IN the given Tag ids. */ + List findByTagIn(List tagIds); +} diff --git a/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/ReportExportWriter.java b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/ReportExportWriter.java new file mode 100644 index 0000000000..40be71de5b --- /dev/null +++ b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/ReportExportWriter.java @@ -0,0 +1,199 @@ +package acme.shop; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import java.io.ByteArrayOutputStream; +import java.math.BigDecimal; +import java.nio.charset.StandardCharsets; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.format.DateTimeFormatter; +import java.util.List; +import javax.xml.stream.XMLOutputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamWriter; + +/** + * GENERATED — the one writer every report export shares: CSV quoting, CRLF, the byte order + * mark constant, the formula-injection guard, and XML over the JDK's StAX writer. + * + *

The guard applies to string-valued cells only (a string, an enum symbol, a uri): a value + * starting with {@code =}, {@code +}, {@code -}, {@code @}, TAB or CR gets a leading + * {@code '}, then the cell is quoted if it holds a quote, comma, CR or LF. A number, a + * decimal, a date or a boolean is never guarded, so a negative number stays a number. + */ +public final class ReportExportWriter { + + private ReportExportWriter() {} + + /** Write a UTF-8 byte order mark before the CSV (Excel on Windows wants one). */ + public static final boolean EXPORT_CSV_BOM = false; + + /** Write a null field as an empty element with xsi:nil="true" (true) or as an empty element (false). */ + public static final boolean EXPORT_XML_NIL = false; + + /** The project's wire.decimals: the canonical string (true, "string") or as Jackson writes a + * BigDecimal number (false, "native"), so a decimal cell matches the list route. */ + public static final boolean DECIMALS_AS_STRING = false; + + private static final String XSI_NS = "http://www.w3.org/2001/XMLSchema-instance"; + + private static final ObjectMapper JSON = new ObjectMapper() + .findAndRegisterModules() + .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + + /** One cell in wire form: its text, or null for a null; {@code guarded} marks a string-valued cell. */ + public static final class Cell { + private final String text; + private final boolean guarded; + + private Cell(String text, boolean guarded) { + this.text = text; + this.guarded = guarded; + } + + public String text() { + return text; + } + + public boolean guarded() { + return guarded; + } + } + + private static final Cell NULL = new Cell(null, false); + + /** A string-valued cell (string, enum symbol, uri): subject to the formula-injection guard. */ + public static Cell text(Object value) { + return value == null ? NULL : new Cell(String.valueOf(value), true); + } + + /** A cell that is never guarded (number, date, time, timestamp, uuid, boolean, currency). + * A time and a zone-less timestamp keep their seconds, as Jackson's JSR-310 serializers write them. */ + public static Cell raw(Object value) { + if (value == null) return NULL; + if (value instanceof LocalTime) { + return new Cell(((LocalTime) value).format(DateTimeFormatter.ISO_LOCAL_TIME), false); + } + if (value instanceof LocalDateTime) { + return new Cell(((LocalDateTime) value).format(DateTimeFormatter.ISO_LOCAL_DATE_TIME), false); + } + return new Cell(String.valueOf(value), false); + } + + /** A decimal as the wire setting writes it: under "string" canonical plain notation (no + * exponent, no trailing fraction zeros, zero as 0), under "native" as Jackson writes it. */ + public static Cell decimal(BigDecimal value) { + if (value == null) return NULL; + if (!DECIMALS_AS_STRING) return new Cell(value.toString(), false); + return new Cell(value.signum() == 0 ? "0" : value.stripTrailingZeros().toPlainString(), false); + } + + /** An array or a map, as compact JSON text. */ + public static Cell json(Object value) { + if (value == null) return NULL; + try { + return new Cell(JSON.writeValueAsString(value), false); + } catch (com.fasterxml.jackson.core.JsonProcessingException e) { + throw new IllegalStateException("cannot write a report cell as JSON: " + e.getMessage(), e); + } + } + + // ----------------------------------------------------------------------- + // CSV + // ----------------------------------------------------------------------- + + /** RFC 4180 CSV: a header row, then one record per row, CRLF after every record. */ + public static byte[] csv(List names, List> rows) { + StringBuilder out = new StringBuilder(); + if (EXPORT_CSV_BOM) out.append('\uFEFF'); + for (int i = 0; i < names.size(); i++) { + if (i > 0) out.append(','); + out.append(quote(names.get(i))); + } + out.append("\r\n"); + for (List row : rows) { + for (int i = 0; i < row.size(); i++) { + if (i > 0) out.append(','); + out.append(csvCell(row.get(i))); + } + out.append("\r\n"); + } + return out.toString().getBytes(StandardCharsets.UTF_8); + } + + /** One cell: null is empty, a guarded string is prefixed with an apostrophe when it starts + * like a formula, then the text is quoted when it needs to be. */ + static String csvCell(Cell cell) { + String value = cell.text(); + if (value == null) return ""; + if (cell.guarded() && !value.isEmpty()) { + char first = value.charAt(0); + if (first == '=' || first == '+' || first == '-' || first == '@' || first == '\t' || first == '\r') { + value = "'" + value; + } + } + return quote(value); + } + + private static String quote(String value) { + boolean needs = false; + for (int i = 0; i < value.length(); i++) { + char c = value.charAt(i); + if (c == '"' || c == ',' || c == '\r' || c == '\n') { + needs = true; + break; + } + } + return needs ? "\"" + value.replace("\"", "\"\"") + "\"" : value; + } + + // ----------------------------------------------------------------------- + // XML + // ----------------------------------------------------------------------- + + /** {@code value......}: UTF-8, no declaration, no indentation. */ + public static byte[] xml(String root, List names, List> rows) { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + try { + XMLStreamWriter w = XMLOutputFactory.newFactory().createXMLStreamWriter(bytes, "UTF-8"); + w.writeStartElement(root); + if (EXPORT_XML_NIL) w.writeNamespace("xsi", XSI_NS); + for (List row : rows) { + w.writeStartElement("row"); + for (int i = 0; i < names.size(); i++) { + String value = row.get(i).text(); + if (value == null) { + w.writeEmptyElement(names.get(i)); + if (EXPORT_XML_NIL) w.writeAttribute("xsi", XSI_NS, "nil", "true"); + } else { + w.writeStartElement(names.get(i)); + w.writeCharacters(xmlText(value)); + w.writeEndElement(); + } + } + w.writeEndElement(); + } + w.writeEndElement(); + w.close(); + } catch (XMLStreamException e) { + throw new IllegalStateException("cannot write the report as XML: " + e.getMessage(), e); + } + return bytes.toByteArray(); + } + + /** A character XML 1.0 cannot hold becomes U+FFFD; the writer escapes {@code & < >}. */ + private static String xmlText(String value) { + StringBuilder out = null; + for (int i = 0; i < value.length(); i++) { + char c = value.charAt(i); + boolean ok = c == '\t' || c == '\n' || c == '\r' || (c >= 0x20 && c <= 0xD7FF) + || (c >= 0xE000 && c <= 0xFFFD) || Character.isSurrogate(c); + if (!ok && out == null) { + out = new StringBuilder(value.length()).append(value, 0, i); + } + if (out != null) out.append(ok ? c : '\uFFFD'); + } + return out == null ? value : out.toString(); + } +} diff --git a/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/TagController.java b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/TagController.java new file mode 100644 index 0000000000..104e4aa139 --- /dev/null +++ b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/TagController.java @@ -0,0 +1,201 @@ +package acme.shop; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.metaobjects.generator.spring.runtime.ConstraintErrors; +import com.metaobjects.generator.spring.runtime.PatchValidationException; +import com.metaobjects.generator.spring.runtime.UnreadableBody; +import com.metaobjects.generator.spring.runtime.UnknownBodyKeys; +import com.metaobjects.generator.spring.runtime.ValidationIssues; +import com.metaobjects.generator.spring.runtime.RecordComponentNames; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import com.metaobjects.generator.spring.runtime.FilterParseResult; +import com.metaobjects.generator.spring.runtime.FilterParser; +import com.metaobjects.generator.spring.runtime.FilterPredicate; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.validation.Validator; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * GENERATED — REST controller for Tag entity. Implements the cross-port API contract. + * + *

Auth: these endpoints are unauthenticated. Require authentication for this path in + * your Spring Security config, e.g. {@code http.authorizeHttpRequests(a -> + * a.requestMatchers("/api/tags/**").authenticated())}. + * A row-ownership rule ("only the owner may read this row") can't be expressed in path + * config — eject this generator with {@code mvn metaobjects:eject} and hand-write those + * endpoints. + */ +@RestController +@RequestMapping("/api/tags") +public class TagController { + + private static final Set SORT_ALLOWLIST = Set.of("id", "label"); + + private static final Map SORT_DEFAULT_ORDER = Map.ofEntries(); + + /** 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. */ + private static final Set SERVER_OWNED_ON_CREATE = Set.of("id"); + + /** Every field the entity declares, as named on the wire: a body key outside it is refused. */ + private static final Set KNOWN_FIELDS = Set.of("id", "label"); + + private final TagRepository repository; + private final ObjectMapper objectMapper; + private final Validator validator; + + public TagController(TagRepository repository, ObjectMapper objectMapper, Validator validator) { + this.repository = repository; + this.objectMapper = objectMapper; + this.validator = validator; + } + + @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)); + } + + @GetMapping + public ResponseEntity list( + @RequestParam(required = false) Integer limit, + @RequestParam(required = false) Integer offset, + @RequestParam(required = false) String sort, + @RequestParam(required = false, name = "withCount") Integer withCount, + HttpServletRequest request) { + int actualLimit = limit != null ? limit : 50; + int actualOffset = offset != null ? offset : 0; + TagRepository.SortClause sortClause = null; + if (sort != null) { + sortClause = parseSort(sort); + if (sortClause == null) { + return ResponseEntity.badRequest().body(Map.of("error", "invalid_sort", "field", sort.split(":", 2)[0])); + } + } + FilterParseResult filter = FilterParser.parse( + request.getQueryString(), TagFilterAllowlist.FIELDS, TagFilterAllowlist.OPS_BY_FIELD, TagFilterAllowlist.DECIMAL_FIELDS, TagFilterAllowlist.DURATION_FIELDS); + if (filter.error() != null) { + return ResponseEntity.badRequest().body(Map.of("error", filter.error(), "field", filter.field())); + } + List filters = filter.predicates(); + List rows = repository.list(actualLimit, actualOffset, sortClause, filters); + if (withCount != null && withCount == 1) { + long total = repository.count(filters); + return ResponseEntity.ok(Map.of("rows", rows, "total", total)); + } + return ResponseEntity.ok(rows); + } + + @GetMapping("/{id}") + public ResponseEntity get(@PathVariable Long id) { + return repository.findById(id) + .>map(ResponseEntity::ok) + .orElseGet(() -> ResponseEntity.status(HttpStatus.NOT_FOUND).body(Map.of("error", "not_found"))); + } + + @PostMapping + public ResponseEntity create(@RequestBody JsonNode body) { + 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()); + } + Map __unknown = UnknownBodyKeys.refusal(body, KNOWN_FIELDS); + if (__unknown != null) { + return ResponseEntity.badRequest().body(__unknown); + } + com.fasterxml.jackson.databind.node.ObjectNode filled = given.deepCopy(); + TagDto dto; + try { + dto = objectMapper.treeToValue(filled, TagDto.class); + } catch (com.fasterxml.jackson.core.JsonProcessingException | IllegalArgumentException e) { + return ResponseEntity.badRequest().body(UnreadableBody.envelope(e)); + } + dto = new TagDto(null, dto.label()); + ValidationIssues __issues = new ValidationIssues() + .addViolationsExcept(validator.validate(dto), SERVER_OWNED_ON_CREATE); + if (!__issues.isEmpty()) { + return ResponseEntity.badRequest().body(__issues.body()); + } + try { + TagDto saved = repository.create(dto); + return ResponseEntity.status(HttpStatus.CREATED).body(saved); + } catch (RuntimeException e) { + 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())); + } + } + + @RequestMapping(value = "/{id}", method = { RequestMethod.PATCH, RequestMethod.PUT }) + public ResponseEntity update(@PathVariable Long id, @RequestBody JsonNode body) { + Map __unknown = UnknownBodyKeys.refusal(body, KNOWN_FIELDS); + if (__unknown != null) { + return ResponseEntity.badRequest().body(__unknown); + } + ValidationIssues __issues = new ValidationIssues(); + TagPatch __patch = null; + Map __assigned; + try { + __patch = TagPatch.fromJson(body, objectMapper); + __assigned = __patch.assignedValues(); + } catch (PatchValidationException e) { + __issues.addPatchFailure(e); + __assigned = e.assignedValues(); + } + for (Map.Entry __e : __assigned.entrySet()) { + __issues.addAt(validator.validateValue(TagDto.class, RecordComponentNames.escape(__e.getKey()), __e.getValue()), __e.getKey()); + } + if (!__issues.isEmpty()) { + return ResponseEntity.badRequest().body(__issues.body()); + } + final var patch = __patch; + try { + return repository.patch(id, patch) + .>map(ResponseEntity::ok) + .orElseGet(() -> ResponseEntity.status(HttpStatus.NOT_FOUND).body(Map.of("error", "not_found"))); + } catch (RuntimeException e) { + 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())); + } + } + + @DeleteMapping("/{id}") + public ResponseEntity delete(@PathVariable Long id) { + try { + if (repository.delete(id)) { + return ResponseEntity.noContent().build(); + } + return ResponseEntity.status(HttpStatus.NOT_FOUND).body(Map.of("error", "not_found")); + } catch (RuntimeException e) { + 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())); + } + } + + private static TagRepository.SortClause parseSort(String raw) { + 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; + return new TagRepository.SortClause(parts[0], dir); + } +} diff --git a/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/TagNames.java b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/TagNames.java new file mode 100644 index 0000000000..69ca37159e --- /dev/null +++ b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/TagNames.java @@ -0,0 +1,34 @@ +package acme.shop; + +import java.util.Map; + +/** + * GENERATED — per-object physical database names for Tag. + */ +public abstract class TagNames { + + public static final String TYPE = "object"; + public static final String SUB_TYPE = "entity"; + public static final String NAME = "Tag"; + + public static final String SOURCE_PRIMARY_TYPE = "source"; + public static final String SOURCE_PRIMARY_SUB_TYPE = "rdb"; + public static final String SOURCE_PRIMARY_KIND = "table"; + public static final String SOURCE_PRIMARY_TABLE = "tags"; + + public static final String ID_FIELD = "id"; + public static final String ID_COLUMN = "id"; + public static final String LABEL_FIELD = "label"; + public static final String LABEL_COLUMN = "label"; + + public static final String IDENTITY_PK_TYPE = "identity"; + public static final String IDENTITY_PK_SUB_TYPE = "primary"; + public static final String IDENTITY_PK_NAME = "pk"; + + public static final Map COLUMNS_BY_FIELD = Map.ofEntries( + Map.entry("id", ID_COLUMN), + Map.entry("label", LABEL_COLUMN) + ); + + protected TagNames() {} +} diff --git a/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/TagRepository.java b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/TagRepository.java new file mode 100644 index 0000000000..698b8a2dd1 --- /dev/null +++ b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/expected/acme/shop/TagRepository.java @@ -0,0 +1,23 @@ +package acme.shop; + +import com.metaobjects.generator.spring.runtime.FilterPredicate; +import java.util.List; +import java.util.Optional; + +/** + * GENERATED interface — consumer implements with their preferred persistence layer + * (Spring Data JPA / jOOQ / plain JDBC). The matching TagController delegates to this interface. + */ +public interface TagRepository { + + /** Sort directive parsed from the cross-port ?sort=:asc|desc grammar. */ + record SortClause(String field, String direction) {} + + List list(int limit, int offset, SortClause sort, List filters); + long count(List filters); + Optional findById(Long id); + TagDto create(TagDto dto); + Optional update(Long id, TagDto dto); + Optional patch(Long id, TagPatch patch); + boolean delete(Long id); +} diff --git a/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/input/meta.json b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/input/meta.json new file mode 100644 index 0000000000..3e3c1f6c3d --- /dev/null +++ b/server/java/codegen-spring/src/test/resources/golden/spring-rest-surface/input/meta.json @@ -0,0 +1,74 @@ +{ + "metadata.root": { + "package": "acme::shop", + "children": [ + { "object.entity": { + "name": "Customer", + "children": [ + { "source.rdb": { "@table": "customers" } }, + { "field.long": { "name": "id" } }, + { "field.string": { "name": "name", "@required": true, "@maxLength": 80 } }, + { "field.enum": { "name": "status", "@required": true, "@values": ["ACTIVE", "SUSPENDED"] } }, + { "field.decimal": { "name": "balance", "@precision": 12, "@scale": 2 } }, + { "field.timestamp": { "name": "createdAt" } }, + { "identity.primary": { "name": "pk", "@fields": "id", "@generation": "increment" } }, + { "segment.filter": { "name": "active", "@filter": { "status": "ACTIVE" } } }, + { "dimension.attribute": { "name": "status", "@of": "Customer.status" } }, + { "measure.aggregate": { "name": "customers", "@agg": "count", "@of": "Customer.id" } }, + { "measure.aggregate": { "name": "activeCustomers", "@agg": "count", "@of": "Customer.id", "@segment": "active" } } + ] + }}, + { "object.entity": { + "name": "Order", + "children": [ + { "source.rdb": { "@table": "orders" } }, + { "field.long": { "name": "id" } }, + { "field.long": { "name": "customerId", "@required": true } }, + { "field.decimal": { "name": "total", "@required": true, "@precision": 12, "@scale": 2 } }, + { "field.date": { "name": "placedOn", "@required": true } }, + { "field.boolean": { "name": "rush" } }, + { "relationship.association": { "name": "tags", "@cardinality": "many", "@objectRef": "Tag", "@through": "OrderTag" } }, + { "identity.primary": { "name": "pk", "@fields": "id", "@generation": "increment" } }, + { "identity.reference": { "name": "fkCustomer", "@fields": "customerId", "@references": "Customer" } } + ] + }}, + { "object.entity": { + "name": "Tag", + "children": [ + { "source.rdb": { "@table": "tags" } }, + { "field.long": { "name": "id" } }, + { "field.string": { "name": "label", "@required": true, "@maxLength": 40 } }, + { "identity.primary": { "name": "pk", "@fields": "id", "@generation": "increment" } } + ] + }}, + { "object.entity": { + "name": "OrderTag", + "children": [ + { "source.rdb": { "@table": "order_tags" } }, + { "field.long": { "name": "orderId", "@required": true } }, + { "field.long": { "name": "tagId", "@required": true } }, + { "identity.primary": { "name": "pk", "@fields": ["orderId", "tagId"] } }, + { "identity.reference": { "name": "fkOrder", "@fields": "orderId", "@references": "Order" } }, + { "identity.reference": { "name": "fkTag", "@fields": "tagId", "@references": "Tag" } } + ] + }}, + { "object.projection": { + "name": "OrderSummary", + "children": [ + { "source.rdb": { "@kind": "view", "@view": "v_order_summary" } }, + { "field.long": { "name": "id", "extends": "Order.id", "@filterable": true, "@sortable": true } }, + { "field.decimal": { "name": "total", "extends": "Order.total", "@filterable": true, "@sortable": true } }, + { "field.date": { "name": "placedOn", "extends": "Order.placedOn", "@filterable": true, "@sortable": true } }, + { "identity.primary": { "name": "pk", "extends": "Order.pk" } } + ] + }}, + { "object.report": { + "name": "CustomerStatusTotals", + "@from": "Customer", + "@dimensions": ["status"], + "@measures": ["customers", "activeCustomers"], + "children": [ { "source.rdb": { "@kind": "view", "@view": "v_customer_status_totals" } } ] + }} + ] + } +} diff --git a/server/typescript/packages/codegen-ts/test/writer-conformance.test.ts b/server/typescript/packages/codegen-ts/test/writer-conformance.test.ts index c0345fc187..d2bd1731f8 100644 --- a/server/typescript/packages/codegen-ts/test/writer-conformance.test.ts +++ b/server/typescript/packages/codegen-ts/test/writer-conformance.test.ts @@ -15,7 +15,7 @@ type Op = [string, ...unknown[]]; interface WriterCase { description: string; - dialect: "core" | "typescript"; + dialect: string; options?: CodeWriterOptions; ops: Op[]; expected?: string[]; @@ -67,6 +67,8 @@ describe("writer conformance", () => { for (const file of files) { const c = JSON.parse(readFileSync(join(CASES, file), "utf8")) as WriterCase; + // A case of another port's dialect (`java`, ...) belongs to that port's writer. + if (c.dialect !== "core" && c.dialect !== "typescript") continue; test(`${file.replace(/\.json$/, "")}: ${c.description}`, () => { if (c.dialect === "core") expect(c.options, "a core case states its options").toBeDefined(); if (c.error !== undefined) { diff --git a/spec/code-writer.md b/spec/code-writer.md index 35a94973e2..45ef909bdc 100644 --- a/spec/code-writer.md +++ b/spec/code-writer.md @@ -21,11 +21,11 @@ smarter. ### Options -| Option | Meaning | TypeScript default | -|---|---|---| -| `indent` | One level of indentation | two spaces | -| `width` | The last column a line may reach before its last list breaks | 120 | -| `trailingComma` | Whether a broken list puts a comma after its last item too | true | +| Option | Meaning | TypeScript default | Java default | +|---|---|---|---| +| `indent` | One level of indentation | two spaces | four spaces | +| `width` | The last column a line may reach before its last list breaks | 120 | 120 | +| `trailingComma` | Whether a broken list puts a comma after its last item too | true | false | A dialect sets the defaults for its language. A `core` case always states all three, so it means the same thing in every port. @@ -122,6 +122,32 @@ units. The comparison includes the indent, and a line exactly `width` long fits. with `.set(name, value)` and `.add(member)`) and `key` (an object key, quoted only when it is not an identifier). +## Java dialect (`JavaWriter`) + +`JavaWriter` is in `codegen-base` (`com.metaobjects.generator.writer`), beside the core +`CodeWriter`. Its `block(head)` is the scoped form: `try (var b = w.block("class A {")) { ... }` +writes the head, indents, and on leaving the `try` dedents and writes `}`. + +- **The package line** is set with `packageName(name)` and prints after the `header(...)` lines + and before the imports, with one blank line between each section. +- **Imports are collected while the body is written.** `use("pkg.Type")` records an import and + returns the name to write, which is the type's last segment (a nested type, + `java.util.Map.Entry`, is imported as written and written `Entry`). `useStatic("pkg.Type.member")` + records a static import and returns the member name. A type in `java.lang`, or in the file's own + package, imports nothing, whichever order the package and the types were named in. +- **Order.** Static imports first, then one blank line, then the other imports. Each group is in + code-unit order, with no blank line between packages. A name used twice is imported once. +- One local name imported from two types, or one static member name from two types, is + **`ERR_WRITER_IMPORT_CONFLICT`**. A generator that needs both writes one of them fully qualified. +- **`doc(lines...)`** writes `/** text */` when there is one entry and it fits. Otherwise it + writes a block of ` * ` lines, with a bare ` *` line for an empty entry. A `*/` inside the text + is written as `*/`. +- Helpers: `str` (a quoted string literal) and `call` (`fn(a, b)`, a list that breaks one item per + line with no trailing comma). +- A part is a `String`, a list (`Group`, built with `CodeWriter.list` or `CodeWriter.padded`) or a + `List` or array of parts, which are concatenated. Anything else (a number, `null`, another + object) is **`ERR_WRITER_UNKNOWN_PIECE`**: the writer never guesses how to print it. + ## Extension by subclassing A writer and the generators built on it are meant to be extended in place @@ -130,7 +156,8 @@ A writer and the generators built on it are meant to be extended in place - A writer class is not final. Every method is public or protected, never private, so a subclass can override one step and keep the rest. In TypeScript the core's steps include `piece` (what a part becomes), `breakAt` (where a line that does not fit breaks) and `fits`. - `TsWriter` adds `writeHeader`, `writeImports`, `writeImport` and `orderModules`. + `TsWriter` adds `writeHeader`, `writeImports`, `writeImport` and `orderModules`. `JavaWriter` + adds `writeHeader`, `writePackage`, `writeImports` and `needsImport`. - A reference generator is a class whose output comes from one overridable method per meaningful piece: the file header, the imports, and each section or member. An adopter overrides the method for the piece it wants changed, and passes its subclass where the